最新版ffmpeg源码分析
(ffmpeg v0.9)
框架
最新版的ffmpeg中发现了一个新的东西:avconv,而且ffmpeg.c与avconv.c一个模样,一研究才发现是libav下把ffmpeg改名为avconv了.
到底libav与ffmpeg现在是什么个关系?我也搞得希里糊涂的,先不管它了.
ffmpeg的主要功能是音视频的转换和处理.其功能之强大已经到了匪夷所思的地步(有点替它吹了).它的主要特点是能做到把多个输入文件中的任意几个流重新组合到输出文件中,当然输出文件也可以有多个.
所以我们就会发现,在ffmpeg.c中,有类似于如下的一些变量:
static InputStream *input_streams = NULL;
static int nb_input_streams =
0;
static InputFile *input_files = NULL;
static int
nb_input_files = 0;
static OutputStream *output_streams = NULL;
static int nb_output_streams =
0;
static OutputFile *output_files = NULL;
static int
nb_output_files = 0;</span>
<span style="font-size:18px;">static InputStream *input_streams
= NULL;
static int nb_input_streams =
0;
static InputFile *input_files = NULL;
static int
nb_input_files = 0;
static OutputStream *output_streams = NULL;
static int nb_output_streams = 0;
static OutputFile *output_files = NULL;
static int
nb_output_files = 0;</span>
其中:
input_streams 是输入流的数组,nb_input_streams是输入流的个数.
InputFile 是输入文件(也可能是设备)的数组,input_files是输入文件的个数.
下面的输出相关的变量们就不用解释了. www.2cto.com
可以看出,文件和流是分别保存的.于是,可以想象,结构InputStream中应有其所属的文件在input_files中的序号,结构OutputStream中也应有其所属文件在output_files中的序号.输入流数组应是这样填充的:每当在输入文件中找到一个流时,就把它添加到input_streams中,所以一个输入文件对应的流们在input_streams中是紧靠着的,于是InputFile结构中应有其第一个流在input_streams中的开始序号和被放在input_streams中的流的个数,因为并不是一个输入文件中所有的流都会被转到输出文件中.我们看一下InputFile:
<span style="font-size:18px;">typedef struct InputFile {
AVFormatContext *ctx;
int eof_reached; /* true if
eof reached */
int ist_index; /*
index of first stream in input_streams */
int buffer_size; /* current
total buffer size */
int64_t ts_offset;
int nb_streams; /*
number of stream that ffmpeg is aware of; may be different
from ctx.nb_streams if new streams appear during av_read_frame() */
int rate_emu;
} InputFile;</span>
<span style="font-size:18px;">typedef struct InputFile {
AVFormatContext *ctx;
int eof_reached; /* true if
eof reached */
int ist_index; /*
index of first stream in input_streams */
int buffer_size; /* current total
buffer size */
int64_t ts_offset;
int nb_streams; /*
number of stream that ffmpeg is aware of; may be different
from ctx.nb_streams if new streams appear during av_read_frame() */
int rate_emu;
} InputFile;</span>
注意其中的ist_index和nb_streams。
在输出流中,除了要保存其所在的输出文件在output_files中的序号,还应保存其对应的输入流在input_streams中的序号,也应保存其在所属输出文件中的流序号.而输出文件中呢,只需保存它的第一个流在output_streams中的序号,但是为啥不保存输出文件中流的个数呢?我也不知道,但我知道肯定不用保存也不影响实现功能(嘿嘿,相当于没说).
各位看官看到这里应该明白ffmpeg是怎样做到可以把多个文件中的任意个流重新组和到输出文件中了吧?
流和文件都准备好了,下面就是转换,那么转换过程是怎样的呢?还是我来猜一猜吧:
首先打开输入文件们,然后跟据输入流们准备并打开解码器们,然后跟据输出流们准备并打开编码器们,然后创建输出文件们,然后为所有输出文件们写好头部,然后就在循环中把输入流转换到输出流并写入输出文件中,转换完后跳出循环,然后写入文件尾,最后关闭所有的输出文件.
概述就先到这里吧,后面会对几个重要函数做详细分析
最新版ffmpeg源码分析二:transcode()函数
还是先看一下主函数吧:(省略了很多无关大雅的代码)
[cpp] view plaincopy
- int main(int argc, char **argv)
- {
- OptionsContext o = { 0 };
- int64_t ti;
- //与命令行分析有关的结构的初始化,下面不再罗嗦
- reset_options(&o, 0);
- //设置日志级别
- av_log_set_flags(AV_LOG_SKIP_REPEATED);
- parse_loglevel(argc, argv, options);
- if (argc > 1 && !strcmp(argv[1], "-d")) {
- run_as_daemon = 1;
- av_log_set_callback(log_callback_null);
- argc--;
- argv++;
- }
- //注册组件们
- avcodec_register_all();
- #if CONFIG_AVDEVICE
- avdevice_register_all();
- #endif
- #if CONFIG_AVFILTER
- avfilter_register_all();
- #endif
- av_register_all();
- //初始化网络,windows下需要
- avformat_network_init();
- show_banner();
- term_init();
- //分析命令行输入的参数们
- parse_options(&o, argc, argv, options, opt_output_file);
- //文件的转换就在此函数中发生
- if (transcode(output_files, nb_output_files, input_files, nb_input_files)< 0)
- exit_program(1);
- exit_program(0);
- return 0;
- }
下面是transcode()函数,转换就发生在它里面.不废话,看注释吧,应很详细了
[cpp] view plaincopy
- static int transcode(
- OutputFile *output_files,//输出文件数组
- int nb_output_files,//输出文件的数量
- InputFile *input_files,//输入文件数组
- int nb_input_files)//输入文件的数量
- {
- int ret, i;
- AVFormatContext *is, *os;
- OutputStream *ost;
- InputStream *ist;
- uint8_t *no_packet;
- int no_packet_count = 0;
- int64_t timer_start;
- int key;
- if (!(no_packet = av_mallocz(nb_input_files)))
- exit_program(1);
- //设置编码参数,打开所有输出流的编码器,打开所有输入流的解码器,写入所有输出文件的文件头,于是准备好了
- ret = transcode_init(output_files, nb_output_files, input_files,nb_input_files);
- if (ret < 0)
- goto fail;
- if (!using_stdin){
- av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
- }
- timer_start = av_gettime();
- //循环,直到收到系统信号才退出
- for (; received_sigterm == 0;)
- {
- int file_index, ist_index;
- AVPacket pkt;
- int64_t ipts_min;
- double opts_min;
- int64_t cur_time = av_gettime();
- ipts_min = INT64_MAX;
- opts_min = 1e100;
- /* if 'q' pressed, exits */
- if (!using_stdin)
- {
- //先查看用户按下了什么键,跟据键做出相应的反应
- static int64_t last_time;
- if (received_nb_signals)
- break;
- /* read_key() returns 0 on EOF */
- if (cur_time - last_time >= 100000 && !run_as_daemon){
- key = read_key();
- last_time = cur_time;
- }else{
- <span> </span>.................................
- }
- /* select the stream that we must read now by looking at the
- smallest output pts */
- //下面这个循环的目的是找一个最小的输出pts(也就是离当前最近的)的输出流
- file_index = -1;
- for (i = 0; i < nb_output_streams; i++){
- OutputFile *of;
- int64_t ipts;
- double opts;
- ost = &output_streams[i];//循环每一个输出流
- of = &output_files[ost->file_index];//输出流对应的输出文件
- os = output_files[ost->file_index].ctx;//输出流对应的FormatContext
- ist = &input_streams[ost->source_index];//输出流对应的输入流
- if (ost->is_past_recording_time || //是否过了录制时间?(可能用户指定了一个录制时间段)
- no_packet[ist->file_index]|| //对应的输入流这个时间内没有数据?
- (os->pb && avio_tell(os->pb) >= of->limit_filesize))//是否超出了录制范围(也是用户指定的)
- continue;//是的,符合上面某一条,那么再看下一个输出流吧
- //判断当前输入流所在的文件是否可以使用(我也不很明白)
- opts = ost->st->pts.val * av_q2d(ost->st->time_base);
- ipts = ist->pts;
- if (!input_files[ist->file_index].eof_reached) {
- if (ipts < ipts_min){
- //每找到一个pts更小的输入流就记录下来,这样循环完所有的输出流时就找到了
- //pts最小的输入流,及输入文件的序号
- ipts_min = ipts;
- if (input_sync)
- file_index = ist->file_index;
- }
- if (opts < opts_min){
- opts_min = opts;
- if (!input_sync)
- file_index = ist->file_index;
- }
- }
- //难道下面这句话的意思是:如果当前的输出流已接收的帧数,超出用户指定的输出最大帧数时,
- //则当前输出流所属的输出文件对应的所有输出流,都算超过了录像时间?
- if (ost->frame_number >= ost->max_frames){
- int j;
- for (j = 0; j < of->ctx->nb_streams; j++)
- output_streams[of->ost_index + j].is_past_recording_time = 1;
- continue;
- }
- }
- /* if none, if is finished */
- if (file_index < 0) {
- //如果没有找到合适的输入文件
- if (no_packet_count){
- //如果是因为有的输入文件暂时得不到数据,则还不算是结束
- no_packet_count = 0;
- memset(no_packet, 0, nb_input_files);
- usleep(10000);
- continue;
- }
- //全部转换完成了,跳出大循环
- break;
- }
- //从找到的输入文件中读出一帧(可能是音频也可能是视频),并放到fifo队列中
- is = input_files[file_index].ctx;
- ret = av_read_frame(is, &pkt);
- if (ret == AVERROR(EAGAIN)) {
- //此时发生了暂时没数据的情况
- no_packet[file_index] = 1;
- no_packet_count++;
- continue;
- }
- //下文判断是否有输入文件到最后了
- if (ret < 0){
- input_files[file_index].eof_reached = 1;
- if (opt_shortest)
- break;
- else
- continue;
- }
- no_packet_count = 0;
- memset(no_packet, 0, nb_input_files);
- if (do_pkt_dump){
- av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
- is->streams[pkt.stream_index]);
- }
- /* the following test is needed in case new streams appear
- dynamically in stream : we ignore them */
- //如果在输入文件中遇到一个忽然冒出的流,那么我们不鸟它
- if (pkt.stream_index >= input_files[file_index].nb_streams)
- goto discard_packet;
- //取得当前获得的帧对应的输入流
- ist_index = input_files[file_index].ist_index + pkt.stream_index;
- ist = &input_streams[ist_index];
- if (ist->discard)
- goto discard_packet;
- //重新鼓捣一下帧的时间戳
- if (pkt.dts != AV_NOPTS_VALUE)
- pkt.dts += av_rescale_q(input_files[ist->file_index].ts_offset,
- AV_TIME_BASE_Q, ist->st->time_base);
- if (pkt.pts != AV_NOPTS_VALUE)
- pkt.pts += av_rescale_q(input_files[ist->file_index].ts_offset,
- AV_TIME_BASE_Q, ist->st->time_base);
- if (pkt.pts != AV_NOPTS_VALUE)
- pkt.pts *= ist->ts_scale;
- if (pkt.dts != AV_NOPTS_VALUE)
- pkt.dts *= ist->ts_scale;
- if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE
- && (is->iformat->flags & AVFMT_TS_DISCONT))
- {
- int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base,
- AV_TIME_BASE_Q);
- int64_t delta = pkt_dts - ist->next_pts;
- if ((delta < -1LL * dts_delta_threshold * AV_TIME_BASE
- || (delta > 1LL * dts_delta_threshold * AV_TIME_BASE
- && ist->st->codec->codec_type
- != AVMEDIA_TYPE_SUBTITLE)
- || pkt_dts + 1 < ist->pts) && !copy_ts)
- {
- input_files[ist->file_index].ts_offset -= delta;
- av_log( NULL, AV_LOG_DEBUG,
- "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
- delta, input_files[ist->file_index].ts_offset);
- pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
- if (pkt.pts != AV_NOPTS_VALUE)
- pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
- }
- }
- //把这一帧转换并写入到输出文件中
- if (output_packet(ist, output_streams, nb_output_streams, &pkt) < 0){
- av_log(NULL, AV_LOG_ERROR,
- "Error while decoding stream #%d:%d\n",
- ist->file_index, ist->st->index);
- if (exit_on_error)
- exit_program(1);
- av_free_packet(&pkt);
- continue;
- }
- discard_packet:
- av_free_packet(&pkt);
- /* dump report by using the output first video and audio streams */
- print_report(output_files, output_streams, nb_output_streams, 0,
- timer_start, cur_time);
- }
- //文件处理完了,把缓冲中剩余的数据写到输出文件中
- for (i = 0; i < nb_input_streams; i++){
- ist = &input_streams[i];
- if (ist->decoding_needed){
- output_packet(ist, output_streams, nb_output_streams, NULL);
- }
- }
- flush_encoders(output_streams, nb_output_streams);
- term_exit();
- //为输出文件写文件尾(有的不需要).
- for (i = 0; i < nb_output_files; i++){
- os = output_files[i].ctx;
- av_write_trailer(os);
- }
- /* dump report by using the first video and audio streams */
- print_report(output_files, output_streams, nb_output_streams, 1,
- timer_start, av_gettime());
- //关闭所有的编码器
- for (i = 0; i < nb_output_streams; i++){
- ost = &output_streams[i];
- if (ost->encoding_needed){
- av_freep(&ost->st->codec->stats_in);
- avcodec_close(ost->st->codec);
- }
- #if CONFIG_AVFILTER
- avfilter_graph_free(&ost->graph);
- #endif
- }
- //关闭所有的解码器
- for (i = 0; i < nb_input_streams; i++){
- ist = &input_streams[i];
- if (ist->decoding_needed){
- avcodec_close(ist->st->codec);
- }
- }
- /* finished ! */
- ret = 0;
- fail: av_freep(&bit_buffer);
- av_freep(&no_packet);
- if (output_streams) {
- for (i = 0; i < nb_output_streams; i++) {
- ost = &output_streams[i];
- if (ost) {
- if (ost->stream_copy)
- av_freep(&ost->st->codec->extradata);
- if (ost->logfile){
- fclose(ost->logfile);
- ost->logfile = NULL;
- }
- av_fifo_free(ost->fifo); /* works even if fifo is not
- initialized but set to zero */
- av_freep(&ost->st->codec->subtitle_header);
- av_free(ost->resample_frame.data[0]);
- av_free(ost->forced_kf_pts);
- if (ost->video_resample)
- sws_freeContext(ost->img_resample_ctx);
- swr_free(&ost->swr);
- av_dict_free(&ost->opts);
- }
- }
- }
- return ret;
- }
transcode_init()函数是在转换前做准备工作的.其大体要完成的任务在第一篇中已做了猜测.此处看一下它的真面目,不废话,看注释吧:
[cpp] view plaincopy
- //为转换过程做准备
- static int transcode_init(OutputFile *output_files,
- int nb_output_files,
- InputFile *input_files,
- int nb_input_files)
- {
- int ret = 0, i, j, k;
- AVFormatContext *oc;
- AVCodecContext *codec, *icodec;
- OutputStream *ost;
- InputStream *ist;
- char error[1024];
- int want_sdp = 1;
- /* init framerate emulation */
- //初始化帧率仿真(转换时是不按帧率来的,但如果要求帧率仿真,就可以做到)
- for (i = 0; i < nb_input_files; i++)
- {
- InputFile *ifile = &input_files[i];
- //如果一个输入文件被要求帧率仿真(指的是即使是转换也像播放那样按照帧率来进行),
- //则为这个文件中所有流记录下开始时间
- if (ifile->rate_emu)
- for (j = 0; j < ifile->nb_streams; j++)
- input_streams[j + ifile->ist_index].start = av_gettime();
- }
- /* output stream init */
- for (i = 0; i < nb_output_files; i++)
- {
- //什么也没做,只是做了个判断而已
- oc = output_files[i].ctx;
- if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS))
- {
- av_dump_format(oc, i, oc->filename, 1);
- av_log(NULL, AV_LOG_ERROR,
- "Output file #%d does not contain any stream\n", i);
- return AVERROR(EINVAL);
- }
- }
- //轮循所有的输出流,跟据对应的输入流,设置其编解码器的参数
- for (i = 0; i < nb_output_streams; i++)
- {
- //轮循所有的输出流
- ost = &output_streams[i];
- //输出流对应的FormatContext
- oc = output_files[ost->file_index].ctx;
- //取得输出流对应的输入流
- ist = &input_streams[ost->source_index];
- //attachment_filename是不是这样的东西:一个文件,它单独容纳一个输出流?此处不懂
- if (ost->attachment_filename)
- continue;
- codec = ost->st->codec;//输出流的编解码器结构
- icodec = ist->st->codec;//输入流的编解码器结构
- //先把能复制的复制一下
- ost->st->disposition = ist->st->disposition;
- codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
- codec->chroma_sample_location = icodec->chroma_sample_location;
- //如果只是复制一个流(不用解码后再编码),则把输入流的编码参数直接复制给输出流
- //此时是不需要解码也不需要编码的,所以不需打开解码器和编码器
- if (ost->stream_copy)
- {
- //计算输出流的编解码器的extradata的大小,然后分配容纳extradata的缓冲
- //然后把输入流的编解码器的extradata复制到输出流的编解码器中
- uint64_t extra_size = (uint64_t) icodec->extradata_size
- + FF_INPUT_BUFFER_PADDING_SIZE;
- if (extra_size > INT_MAX) {
- return AVERROR(EINVAL);
- }
- /* if stream_copy is selected, no need to decode or encode */
- codec->codec_id = icodec->codec_id;
- codec->codec_type = icodec->codec_type;
- if (!codec->codec_tag){
- if (!oc->oformat->codec_tag
- ||av_codec_get_id(oc->oformat->codec_tag,icodec->codec_tag) == codec->codec_id
- ||av_codec_get_tag(oc->oformat->codec_tag,icodec->codec_id) <= 0)
- codec->codec_tag = icodec->codec_tag;
- }
- codec->bit_rate = icodec->bit_rate;
- codec->rc_max_rate = icodec->rc_max_rate;
- codec->rc_buffer_size = icodec->rc_buffer_size;
- codec->extradata = av_mallocz(extra_size);
- if (!codec->extradata){
- return AVERROR(ENOMEM);
- }
- memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
- codec->extradata_size = icodec->extradata_size;
- //重新鼓捣一下time base(这家伙就是帧率)
- codec->time_base = ist->st->time_base;
- //如果输出文件是avi,做一点特殊处理
- if (!strcmp(oc->oformat->name, "avi")) {
- if (copy_tb < 0
- && av_q2d(icodec->time_base) * icodec->ticks_per_frame >
- 2 * av_q2d(ist->st->time_base)
- && av_q2d(ist->st->time_base) < 1.0 / 500
- || copy_tb == 0)
- {
- codec->time_base = icodec->time_base;
- codec->time_base.num *= icodec->ticks_per_frame;
- codec->time_base.den *= 2;
- }
- }
- else if (!(oc->oformat->flags & AVFMT_VARIABLE_FPS))
- {
- if (copy_tb < 0
- && av_q2d(icodec->time_base) * icodec->ticks_per_frame
- > av_q2d(ist->st->time_base)
- && av_q2d(ist->st->time_base) < 1.0 / 500
- || copy_tb == 0)
- {
- codec->time_base = icodec->time_base;
- codec->time_base.num *= icodec->ticks_per_frame;
- }
- }
- //再修正一下帧率
- av_reduce(&codec->time_base.num, &codec->time_base.den,
- codec->time_base.num, codec->time_base.den, INT_MAX);
- //单独复制各不同媒体自己的编码参数
- switch (codec->codec_type)
- {
- case AVMEDIA_TYPE_AUDIO:
- //音频的
- if (audio_volume != 256){
- av_log( NULL,AV_LOG_FATAL,
- "-acodec copy and -vol are incompatible (frames are not decoded)\n");
- exit_program(1);
- }
- codec->channel_layout = icodec->channel_layout;
- codec->sample_rate = icodec->sample_rate;
- codec->channels = icodec->channels;
- codec->frame_size = icodec->frame_size;
- codec->audio_service_type = icodec->audio_service_type;
- codec->block_align = icodec->block_align;
- break;
- case AVMEDIA_TYPE_VIDEO:
- //视频的
- codec->pix_fmt = icodec->pix_fmt;
- codec->width = icodec->width;
- codec->height = icodec->height;
- codec->has_b_frames = icodec->has_b_frames;
- if (!codec->sample_aspect_ratio.num){
- codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
- ist->st->sample_aspect_ratio.num ?ist->st->sample_aspect_ratio :
- ist->st->codec->sample_aspect_ratio.num ?ist->st->codec->sample_aspect_ratio :(AVRational){0, 1};
- }
- ost->st->avg_frame_rate = ist->st->avg_frame_rate;
- break;
- case AVMEDIA_TYPE_SUBTITLE:
- //字幕的
- codec->width = icodec->width;
- codec->height = icodec->height;
- break;
- case AVMEDIA_TYPE_DATA:
- case AVMEDIA_TYPE_ATTACHMENT:
- //??的
- break;
- default:
- abort();
- }
- }
- else
- {
- //如果不是复制,就麻烦多了
- //获取编码器
- if (!ost->enc)
- ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);
- //因为需要转换,所以既需解码又需编码
- ist->decoding_needed = 1;
- ost->encoding_needed = 1;
- switch(codec->codec_type)
- {
- case AVMEDIA_TYPE_AUDIO:
- //鼓捣音频编码器的参数,基本上是把一些不合适的参数替换掉
- ost->fifo = av_fifo_alloc(1024);//音频数据所在的缓冲
- if (!ost->fifo) {
- return AVERROR(ENOMEM);
- }
- //采样率
- if (!codec->sample_rate)
- codec->sample_rate = icodec->sample_rate;
- choose_sample_rate(ost->st, ost->enc);
- codec->time_base = (AVRational){1, codec->sample_rate};
- //样点格式
- if (codec->sample_fmt == AV_SAMPLE_FMT_NONE)
- codec->sample_fmt = icodec->sample_fmt;
- choose_sample_fmt(ost->st, ost->enc);
- //声道
- if (ost->audio_channels_mapped) {
- /* the requested output channel is set to the number of
- * -map_channel only if no -ac are specified */
- if (!codec->channels) {
- codec->channels = ost->audio_channels_mapped;
- codec->channel_layout = av_get_default_channel_layout(codec->channels);
- if (!codec->channel_layout) {
- av_log(NULL, AV_LOG_FATAL, "Unable to find an appropriate channel layout for requested number of channel\n);
- exit_program(1);
- }
- }
- /* fill unused channel mapping with -1 (which means a muted
- * channel in case the number of output channels is bigger
- * than the number of mapped channel) */
- for (j = ost->audio_channels_mapped; j < FF_ARRAY_ELEMS(ost->audio_channels_map); j++)
- <span> </span>ost->audio_channels_map[j] = -1;
- }else if (!codec->channels){
- codec->channels = icodec->channels;
- codec->channel_layout = icodec->channel_layout;
- }
- if (av_get_channel_layout_nb_channels(codec->channel_layout) != codec->channels)
- codec->channel_layout = 0;
- //是否需要重采样
- ost->audio_resample = codec->sample_rate != icodec->sample_rate || audio_sync_method > 1;
- ost->audio_resample |= codec->sample_fmt != icodec->sample_fmt ||
- codec->channel_layout != icodec->channel_layout;
- icodec->request_channels = codec->channels;
- ost->resample_sample_fmt = icodec->sample_fmt;
- ost->resample_sample_rate = icodec->sample_rate;
- ost->resample_channels = icodec->channels;
- break;
- case AVMEDIA_TYPE_VIDEO:
- //鼓捣视频编码器的参数,基本上是把一些不合适的参数替换掉
- if (codec->pix_fmt == PIX_FMT_NONE)
- codec->pix_fmt = icodec->pix_fmt;
- choose_pixel_fmt(ost->st, ost->enc);
- if (ost->st->codec->pix_fmt == PIX_FMT_NONE){
- av_log(NULL, AV_LOG_FATAL, "Video pixel format is unknown, stream cannot be encoded\n");
- exit_program(1);
- }
- //宽高
- if (!codec->width || !codec->height){
- codec->width = icodec->width;
- codec->height = icodec->height;
- }
- //视频是否需要重采样
- ost->video_resample = codec->width != icodec->width ||
- codec->height != icodec->height ||
- codec->pix_fmt != icodec->pix_fmt;
- if (ost->video_resample){
- codec->bits_per_raw_sample= frame_bits_per_raw_sample;
- }
- ost->resample_height = icodec->height;
- ost->resample_width = icodec->width;
- ost->resample_pix_fmt = icodec->pix_fmt;
- //计算帧率
- if (!ost->frame_rate.num)
- ost->frame_rate = ist->st->r_frame_rate.num ?
- ist->st->r_frame_rate : (AVRational){25,1};
- if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
- int idx = av_find_nearest_q_idx(ost->frame_rate,ost->enc->supported_framerates);
- ost->frame_rate = ost->enc->supported_framerates[idx];
- }
- codec->time_base = (AVRational) {ost->frame_rate.den, ost->frame_rate.num};
- if( av_q2d(codec->time_base) < 0.001 &&
- video_sync_method &&
- (video_sync_method==1 ||
- (video_sync_method<0 && !
- (oc->oformat->flags & AVFMT_VARIABLE_FPS))))
- {
- av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not effciciently supporting it.\n"
- "Please consider specifiying a lower framerate, a different muxer or -vsync 2\n");
- }
- <span> </span>for (j = 0; j < ost->forced_kf_count; j++)
- ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
- AV_TIME_BASE_Q, codec->time_base);
- break;
- case AVMEDIA_TYPE_SUBTITLE:
- break;
- default:
- abort();
- break;
- }
- /* two pass mode */
- if (codec->codec_id != CODEC_ID_H264 &&
- (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)))
- {
- char logfilename[1024];
- FILE *f;
- snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
- pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
- i);
- if (codec->flags & CODEC_FLAG_PASS2){
- char *logbuffer;
- size_t logbuffer_size;
- if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0){
- av_log(NULL, AV_LOG_FATAL,
- "Error reading log file '%s' for pass-2 encoding\n",
- logfilename);
- exit_program(1);
- }
- codec->stats_in = logbuffer;
- }
- if (codec->flags & CODEC_FLAG_PASS1){
- f = fopen(logfilename, "wb");
- if (!f) {
- av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
- logfilename, strerror(errno));
- exit_program(1);
- }
- ost->logfile = f;
- }
- }
- }
- if (codec->codec_type == AVMEDIA_TYPE_VIDEO){
- /* maximum video buffer size is 6-bytes per pixel, plus DPX header size (1664)*/
- //计算编码输出缓冲的大小,计算一个最大值
- int size = codec->width * codec->height;
- bit_buffer_size = FFMAX(bit_buffer_size, 7 * size + 10000);
- }
- }
- //分配编码后数据所在的缓冲
- if (!bit_buffer)
- bit_buffer = av_malloc(bit_buffer_size);
- if (!bit_buffer){
- av_log(NULL, AV_LOG_ERROR,
- "Cannot allocate %d bytes output buffer\n",
- bit_buffer_size);
- return AVERROR(ENOMEM);
- }
- //轮循所有输出流,打开每个输出流的编码器
- for (i = 0; i < nb_output_streams; i++)
- {
- ost = &output_streams[i];
- if (ost->encoding_needed){
- //当然,只有在需要编码时才打开编码器
- AVCodec *codec = ost->enc;
- AVCodecContext *dec = input_streams[ost->source_index].st->codec;
- if (!codec) {
- snprintf(error, sizeof(error),
- "Encoder (codec %s) not found for output stream #%d:%d",
- avcodec_get_name(ost->st->codec->codec_id),
- ost->file_index, ost->index);
- ret = AVERROR(EINVAL);
- goto dump_format;
- }
- if (dec->subtitle_header){
- ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
- if (!ost->st->codec->subtitle_header){
- ret = AVERROR(ENOMEM);
- goto dump_format;
- }
- memcpy(ost->st->codec->subtitle_header,
- dec->subtitle_header,dec->subtitle_header_size);
- ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
- }
- //打开啦
- if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
- snprintf(error, sizeof(error),
- "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
- ost->file_index, ost->index);
- ret = AVERROR(EINVAL);
- goto dump_format;
- }
- assert_codec_experimental(ost->st->codec, 1);
- assert_avoptions(ost->opts);
- if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
- av_log(NULL, AV_LOG_WARNING,
- "The bitrate parameter is set too low."
- " It takes bits/s as argument, not kbits/s\n");
- extra_size += ost->st->codec->extradata_size;
- if (ost->st->codec->me_threshold)
- input_streams[ost->source_index].st->codec->debug |= FF_DEBUG_MV;
- }
- }
- //初始化所有的输入流(主要做的就是在需要时打开解码器)
- for (i = 0; i < nb_input_streams; i++)
- if ((ret = init_input_stream(i, output_streams, nb_output_streams,
- error, sizeof(error))) < 0)
- goto dump_format;
- /* discard unused programs */
- for (i = 0; i < nb_input_files; i++){
- InputFile *ifile = &input_files[i];
- for (j = 0; j < ifile->ctx->nb_programs; j++){
- AVProgram *p = ifile->ctx->programs[j];
- int discard = AVDISCARD_ALL;
- for (k = 0; k < p->nb_stream_indexes; k++){
- if (!input_streams[ifile->ist_index + p->stream_index[k]].discard){
- discard = AVDISCARD_DEFAULT;
- break;
- }
- }
- p->discard = discard;
- }
- }
- //打开所有输出文件,写入媒体文件头
- for (i = 0; i < nb_output_files; i++){
- oc = output_files[i].ctx;
- oc->interrupt_callback = int_cb;
- if (avformat_write_header(oc, &output_files[i].opts) < 0){
- snprintf(error, sizeof(error),
- "Could not write header for output file #%d (incorrect codec parameters ?)",
- i);
- ret = AVERROR(EINVAL);
- goto dump_format;
- }
424.// assert_avoptions(output_files[i].opts);
- if (strcmp(oc->oformat->name, "rtp")){
- want_sdp = 0;
- }
- }
- return 0;
431.}
版权声明:本文为博主原创文章,未经博主允许不得转载
最新版ffmpeg源码分析的更多相关文章
- ffmpeg 源码分析
http://blog.csdn.net/liuhongxiangm/article/details/8824761 https://code.google.com/p/ffmpegsource/is ...
- ffmpeg源码分析一:概述 (转1)
原帖地址:http://blog.csdn.net/austinblog/article/details/24800381 首先先看ffmpeg.c文件,有类似于如下的一些变量: InputStrea ...
- ffmpeg源码分析五:ffmpeg调用x264编码器的过程分析 (转5)
原帖地址:http://blog.csdn.net/austinblog/article/details/25127533 该文将以X264编码器为例,解释说明FFMPEG是怎么调用第三方编码器来进行 ...
- ffmpeg源码分析三:transcode_init函数 (转3)
原帖地址:http://blog.csdn.net/austinblog/article/details/25061945 transcode_init()函数是在转换前做准备工作的.下面看看其源代码 ...
- ffmpeg源码分析二:main函数和transcode函数 (转2)
原帖地址:http://blog.csdn.net/austinblog/article/details/24804455 首先从main函数看起,关键解释部分已加注释,该函数在ffmpeg.c文件中 ...
- ffmpeg源码分析之媒体打开过程
int avformat_open_input(AVFormatContext **ps, const char *filename, AVInputForma ...
- ffmpeg源码分析--av_find_best_stream <转>
1. av_find_best_streama. 就是要获取音视频及字幕的stream_indexb.以前没有函数av_find_best_stream时,获取索引可以通过如下 ; i<is-& ...
- ffmpeg源码分析四:transcode_step函数 (转4)
原帖地址:http://blog.csdn.net/austinblog/article/details/25099979 该函数的主要功能是一步完整的转换工作,下面看看源代码: static int ...
- FFmpeg源码简单分析:libswscale的sws_scale()
===================================================== FFmpeg的库函数源码分析文章列表: [架构图] FFmpeg源码结构图 - 解码 FFm ...
随机推荐
- 根据UserAgent 获取操作系统名称
/// <summary> /// 根据 User Agent 获取操作系统名称 /// </summary> private sta ...
- 用JS制作简易的可切换的年历,类似于选项卡
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 30.0px Consolas; color: #2b7ec3 } p.p2 { margin: 0.0px ...
- noip2010-t2
题目大意:小明过生日的时候,爸爸送给他一副乌龟棋当作礼物.乌龟棋的棋盘是一行 N个格子,每个格子上一个分数(非负整数).棋盘第 1 格是唯一 的起点,第 N格是终点,游戏要求玩家控制一个乌龟棋子从起点 ...
- log4j.properties example
google search log4j.properties example Output to Console # Root logger option log4j.rootLogger=INFO, ...
- Linux内核分析之扒开系统调用的三层皮(上)
一.原理总结 本周老师讲的内容主要包括三个方面,用户态.内核态和中断,系统调用概述,以及使用库函数API获取系统当前时间.系统调用是操作系统为用户态进程与硬件设备进行交互提供的一组接口,也是一种特殊的 ...
- 百度ECHARTS 饼图使用心得 处理data属性
做过CRM系统的童鞋应该都或多或少接触过hicharts或者echarts等数据统计插件.用过这两款,个人感觉echarts的画面更好看.至于功能,只有适合自己的才是最好的. 今天来说说我使用echa ...
- 使用ODP.NET一次执行多句SQL语句
在实际开发的时候有的时候希望一次执行多句SQL语句,又不想使用Transcation的话,可以直接将多句SQL语句拼接起来.例如: var sql = "Begin " + &qu ...
- sqlhelper sqlparameter 实现增删改查
这是sqlHelper.cs类,类内里封装了方法 using System; using System.Collections.Generic; using System.Linq; using Sy ...
- C#设计模式(16)——迭代器模式(Iterator Pattern)
一.引言 在上篇博文中分享了我对命令模式的理解,命令模式主要是把行为进行抽象成命令,使得请求者的行为和接受者的行为形成低耦合.在一章中,将介绍一下迭代器模式.下面废话不多说了,直接进入本博文的主题. ...
- 史无前例的Firefox奇怪问题:host中的common名称造成css文件无法加载
今天遭遇了一个非常非常奇怪的问题,一个css文件(common.cnblogs.com/Skins/marvin3/green.css),Firefox怎么也无法打开,一直在转圈. 而换成其它浏览器都 ...