最新版ffmpeg源码分析

来源:互联网 发布:淘宝男士手表50以下 编辑:程序博客网 时间:2024/05/17 14:20

(ffmpeg v0.9)

框架

最新版的ffmpeg中发现了一个新的东西:avconv,而且ffmpeg.c与avconv.c一个模样,一研究才发现是libav下把ffmpeg改名为avconv了.

到底libav与ffmpeg现在是什么个关系?我也搞得希里糊涂的,先不管它了.

ffmpeg的主要功能是音视频的转换和处理.其功能之强大已经到了匪夷所思的地步(有点替它吹了).它的主要特点是能做到把多个输入文件中的任意几个流重新组合到输出文件中,当然输出文件也可以有多个.

所以我们就会发现,在ffmpeg.c中,有类似于如下的一些变量:
[cpp] view plaincopy
  1. <span style="font-size:18px;">static InputStream *input_streams = NULL;  
  2. static int         nb_input_streams = 0;  
  3. static InputFile   *input_files   = NULL;  
  4. static int         nb_input_files   = 0;  
  5.   
  6.   
  7. static OutputStream *output_streams = NULL;  
  8. static int        nb_output_streams = 0;  
  9. static OutputFile   *output_files   = NULL;  
  10. static int        nb_output_files   = 0;</span>  

其中:
input_streams 是输入流的数组,nb_input_streams是输入流的个数.
InputFile 是输入文件(也可能是设备)的数组,input_files是输入文件的个数.
下面的输出相关的变量们就不用解释了.

可以看出,文件和流是分别保存的.于是,可以想象,结构InputStream中应有其所属的文件在input_files中的序号,结构OutputStream中也应有其所属文件在output_files中的序号.输入流数组应是这样填充的:每当在输入文件中找到一个流时,就把它添加到input_streams中,所以一个输入文件对应的流们在input_streams中是紧靠着的,于是InputFile结构中应有其第一个流在input_streams中的开始序号和被放在input_streams中的流的个数,因为并不是一个输入文件中所有的流都会被转到输出文件中.我们看一下InputFile:
[cpp] view plaincopy
  1. <span style="font-size:18px;">typedef struct InputFile {  
  2.     AVFormatContext *ctx;  
  3.     int eof_reached;      /* true if eof reached */  
  4.     int ist_index;        /* index of first stream in input_streams */  
  5.     int buffer_size;      /* current total buffer size */  
  6.     int64_t ts_offset;  
  7.     int nb_streams;       /* number of stream that ffmpeg is aware of; may be different 
  8.                              from ctx.nb_streams if new streams appear during av_read_frame() */  
  9.     int rate_emu;  
  10. } InputFile;</span>  

注意其中的ist_index和nb_streams。

在输出流中,除了要保存其所在的输出文件在output_files中的序号,还应保存其对应的输入流在input_streams中的序号,也应保存其在所属输出文件中的流序号.而输出文件中呢,只需保存它的第一个流在output_streams中的序号,但是为啥不保存输出文件中流的个数呢?我也不知道,但我知道肯定不用保存也不影响实现功能(嘿嘿,相当于没说).
各位看官看到这里应该明白ffmpeg是怎样做到可以把多个文件中的任意个流重新组和到输出文件中了吧?

流和文件都准备好了,下面就是转换,那么转换过程是怎样的呢?还是我来猜一猜吧:

首先打开输入文件们,然后跟据输入流们准备并打开解码器们,然后跟据输出流们准备并打开编码器们,然后创建输出文件们,然后为所有输出文件们写好头部,然后就在循环中把输入流转换到输出流并写入输出文件中,转换完后跳出循环,然后写入文件尾,最后关闭所有的输出文件.


transcode()函数分析

还是先看一下主函数吧:(省略了很多无关大雅的代码)

[cpp] view plaincopy
  1. int main(int argc, char **argv)  
  2. {  
  3.     OptionsContext o = { 0 };  
  4.     int64_t ti;  
  5.   
  6.     //与命令行分析有关的结构的初始化,下面不再罗嗦  
  7.     reset_options(&o, 0);  
  8.   
  9.     //设置日志级别  
  10.     av_log_set_flags(AV_LOG_SKIP_REPEATED);  
  11.     parse_loglevel(argc, argv, options);  
  12.   
  13.     if (argc > 1 && !strcmp(argv[1], "-d"))  {  
  14.         run_as_daemon = 1;  
  15.         av_log_set_callback(log_callback_null);  
  16.         argc--;  
  17.         argv++;  
  18.     }  
  19.   
  20.     //注册组件们  
  21.     avcodec_register_all();  
  22. #if CONFIG_AVDEVICE  
  23.     avdevice_register_all();  
  24. #endif  
  25. #if CONFIG_AVFILTER  
  26.     avfilter_register_all();  
  27. #endif  
  28.     av_register_all();  
  29.     //初始化网络,windows下需要  
  30.     avformat_network_init();  
  31.   
  32.     show_banner();  
  33.   
  34.     term_init();  
  35.   
  36.     //分析命令行输入的参数们  
  37.     parse_options(&o, argc, argv, options, opt_output_file);  
  38.   
  39.     //文件的转换就在此函数中发生  
  40.     if (transcode(output_files, nb_output_files, input_files, nb_input_files)< 0)  
  41.         exit_program(1);  
  42.   
  43.     exit_program(0);  
  44.     return 0;  
  45. }  

下面是transcode()函数,转换就发生在它里面.不废话,看注释吧,应很详细了

[cpp] view plaincopy
  1. static int transcode(  
  2.         OutputFile *output_files,//输出文件数组  
  3.         int nb_output_files,//输出文件的数量  
  4.         InputFile *input_files,//输入文件数组  
  5.         int nb_input_files)//输入文件的数量  
  6. {  
  7.     int ret, i;  
  8.     AVFormatContext *is, *os;  
  9.     OutputStream *ost;  
  10.     InputStream *ist;  
  11.     uint8_t *no_packet;  
  12.     int no_packet_count = 0;  
  13.     int64_t timer_start;  
  14.     int key;  
  15.   
  16.     if (!(no_packet = av_mallocz(nb_input_files)))  
  17.         exit_program(1);  
  18.   
  19.     //设置编码参数,打开所有输出流的编码器,打开所有输入流的解码器,写入所有输出文件的文件头,于是准备好了  
  20.     ret = transcode_init(output_files, nb_output_files, input_files,nb_input_files);  
  21.     if (ret < 0)  
  22.         goto fail;  
  23.   
  24.     if (!using_stdin){  
  25.         av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");  
  26.     }  
  27.   
  28.     timer_start = av_gettime();  
  29.   
  30.     //循环,直到收到系统信号才退出  
  31.     for (; received_sigterm == 0;)  
  32.     {  
  33.         int file_index, ist_index;  
  34.         AVPacket pkt;  
  35.         int64_t ipts_min;  
  36.         double opts_min;  
  37.         int64_t cur_time = av_gettime();  
  38.   
  39.         ipts_min = INT64_MAX;  
  40.         opts_min = 1e100;  
  41.         /* if 'q' pressed, exits */  
  42.         if (!using_stdin)  
  43.         {  
  44.             //先查看用户按下了什么键,跟据键做出相应的反应  
  45.             static int64_t last_time;  
  46.             if (received_nb_signals)  
  47.                 break;  
  48.             /* read_key() returns 0 on EOF */  
  49.             if (cur_time - last_time >= 100000 && !run_as_daemon){  
  50.                 key = read_key();  
  51.                 last_time = cur_time;  
  52.             }else{  
  53. <span>          </span>.................................  
  54.         }  
  55.   
  56.         /* select the stream that we must read now by looking at the 
  57.          smallest output pts */  
  58.         //下面这个循环的目的是找一个最小的输出pts(也就是离当前最近的)的输出流  
  59.         file_index = -1;  
  60.         for (i = 0; i < nb_output_streams; i++){  
  61.             OutputFile *of;  
  62.             int64_t ipts;  
  63.             double opts;  
  64.             ost = &output_streams[i];//循环每一个输出流  
  65.             of = &output_files[ost->file_index];//输出流对应的输出文件  
  66.             os = output_files[ost->file_index].ctx;//输出流对应的FormatContext  
  67.             ist = &input_streams[ost->source_index];//输出流对应的输入流  
  68.   
  69.             if (ost->is_past_recording_time || //是否过了录制时间?(可能用户指定了一个录制时间段)  
  70.                     no_packet[ist->file_index]|| //对应的输入流这个时间内没有数据?  
  71.                     (os->pb && avio_tell(os->pb) >= of->limit_filesize))//是否超出了录制范围(也是用户指定的)  
  72.                 continue;//是的,符合上面某一条,那么再看下一个输出流吧  
  73.   
  74.             //判断当前输入流所在的文件是否可以使用(我也不很明白)  
  75.             opts = ost->st->pts.val * av_q2d(ost->st->time_base);  
  76.             ipts = ist->pts;  
  77.             if (!input_files[ist->file_index].eof_reached)   {  
  78.                 if (ipts < ipts_min){  
  79.                     //每找到一个pts更小的输入流就记录下来,这样循环完所有的输出流时就找到了  
  80.                     //pts最小的输入流,及输入文件的序号  
  81.                     ipts_min = ipts;  
  82.                     if (input_sync)  
  83.                         file_index = ist->file_index;  
  84.                 }  
  85.                 if (opts < opts_min){  
  86.                     opts_min = opts;  
  87.                     if (!input_sync)  
  88.                         file_index = ist->file_index;  
  89.                 }  
  90.             }  
  91.   
  92.             //难道下面这句话的意思是:如果当前的输出流已接收的帧数,超出用户指定的输出最大帧数时,  
  93.             //则当前输出流所属的输出文件对应的所有输出流,都算超过了录像时间?  
  94.             if (ost->frame_number >= ost->max_frames){  
  95.                 int j;  
  96.                 for (j = 0; j < of->ctx->nb_streams; j++)  
  97.                     output_streams[of->ost_index + j].is_past_recording_time =   1;  
  98.                 continue;  
  99.             }  
  100.         }  
  101.         /* if none, if is finished */  
  102.         if (file_index < 0)  {  
  103.             //如果没有找到合适的输入文件  
  104.             if (no_packet_count){  
  105.                 //如果是因为有的输入文件暂时得不到数据,则还不算是结束  
  106.                 no_packet_count = 0;  
  107.                 memset(no_packet, 0, nb_input_files);  
  108.                 usleep(10000);  
  109.                 continue;  
  110.             }  
  111.             //全部转换完成了,跳出大循环  
  112.             break;  
  113.         }  
  114.   
  115.         //从找到的输入文件中读出一帧(可能是音频也可能是视频),并放到fifo队列中  
  116.         is = input_files[file_index].ctx;  
  117.         ret = av_read_frame(is, &pkt);  
  118.         if (ret == AVERROR(EAGAIN)) {  
  119.             //此时发生了暂时没数据的情况  
  120.             no_packet[file_index] = 1;  
  121.             no_packet_count++;  
  122.             continue;  
  123.         }  
  124.   
  125.         //下文判断是否有输入文件到最后了  
  126.         if (ret < 0){  
  127.             input_files[file_index].eof_reached = 1;  
  128.             if (opt_shortest)  
  129.                 break;  
  130.             else  
  131.                 continue;  
  132.         }  
  133.   
  134.         no_packet_count = 0;  
  135.         memset(no_packet, 0, nb_input_files);  
  136.   
  137.         if (do_pkt_dump){  
  138.             av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,  
  139.                     is->streams[pkt.stream_index]);  
  140.         }  
  141.         /* the following test is needed in case new streams appear 
  142.          dynamically in stream : we ignore them */  
  143.         //如果在输入文件中遇到一个忽然冒出的流,那么我们不鸟它  
  144.         if (pkt.stream_index >= input_files[file_index].nb_streams)  
  145.             goto discard_packet;  
  146.   
  147.         //取得当前获得的帧对应的输入流  
  148.         ist_index = input_files[file_index].ist_index + pkt.stream_index;  
  149.         ist = &input_streams[ist_index];  
  150.         if (ist->discard)  
  151.             goto discard_packet;  
  152.   
  153.         //重新鼓捣一下帧的时间戳  
  154.         if (pkt.dts != AV_NOPTS_VALUE)  
  155.             pkt.dts += av_rescale_q(input_files[ist->file_index].ts_offset,  
  156.                     AV_TIME_BASE_Q, ist->st->time_base);  
  157.         if (pkt.pts != AV_NOPTS_VALUE)  
  158.             pkt.pts += av_rescale_q(input_files[ist->file_index].ts_offset,  
  159.                     AV_TIME_BASE_Q, ist->st->time_base);  
  160.   
  161.         if (pkt.pts != AV_NOPTS_VALUE)  
  162.             pkt.pts *= ist->ts_scale;  
  163.         if (pkt.dts != AV_NOPTS_VALUE)  
  164.             pkt.dts *= ist->ts_scale;  
  165.   
  166.         if (pkt.dts != AV_NOPTS_VALUE && ist->next_pts != AV_NOPTS_VALUE  
  167.                 && (is->iformat->flags & AVFMT_TS_DISCONT))  
  168.         {  
  169.             int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base,  
  170.                     AV_TIME_BASE_Q);  
  171.             int64_t delta = pkt_dts - ist->next_pts;  
  172.             if ((delta < -1LL * dts_delta_threshold * AV_TIME_BASE  
  173.                     || (delta > 1LL * dts_delta_threshold * AV_TIME_BASE  
  174.                             && ist->st->codec->codec_type  
  175.                                     != AVMEDIA_TYPE_SUBTITLE)  
  176.                     || pkt_dts + 1 < ist->pts) && !copy_ts)  
  177.             {  
  178.                 input_files[ist->file_index].ts_offset -= delta;  
  179.                 av_log( NULL,   AV_LOG_DEBUG,  
  180.                         "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",  
  181.                         delta, input_files[ist->file_index].ts_offset);  
  182.                 pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q,  ist->st->time_base);  
  183.                 if (pkt.pts != AV_NOPTS_VALUE)  
  184.                     pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q,  ist->st->time_base);  
  185.             }  
  186.         }  
  187.   
  188.         //把这一帧转换并写入到输出文件中  
  189.         if (output_packet(ist, output_streams, nb_output_streams, &pkt) < 0){  
  190.             av_log(NULL, AV_LOG_ERROR,  
  191.                     "Error while decoding stream #%d:%d\n",  
  192.                     ist->file_index, ist->st->index);  
  193.             if (exit_on_error)  
  194.                 exit_program(1);  
  195.             av_free_packet(&pkt);  
  196.             continue;  
  197.         }  
  198.   
  199. discard_packet:  
  200.         av_free_packet(&pkt);  
  201.   
  202.         /* dump report by using the output first video and audio streams */  
  203.         print_report(output_files, output_streams, nb_output_streams, 0,  
  204.                 timer_start, cur_time);  
  205.     }  
  206.   
  207.     //文件处理完了,把缓冲中剩余的数据写到输出文件中  
  208.     for (i = 0; i < nb_input_streams; i++){  
  209.         ist = &input_streams[i];  
  210.         if (ist->decoding_needed){  
  211.             output_packet(ist, output_streams, nb_output_streams, NULL);  
  212.         }  
  213.     }  
  214.     flush_encoders(output_streams, nb_output_streams);  
  215.   
  216.     term_exit();  
  217.   
  218.     //为输出文件写文件尾(有的不需要).  
  219.     for (i = 0; i < nb_output_files; i++){  
  220.         os = output_files[i].ctx;  
  221.         av_write_trailer(os);  
  222.     }  
  223.   
  224.     /* dump report by using the first video and audio streams */  
  225.     print_report(output_files, output_streams, nb_output_streams, 1,  
  226.             timer_start, av_gettime());  
  227.   
  228.     //关闭所有的编码器  
  229.     for (i = 0; i < nb_output_streams; i++){  
  230.         ost = &output_streams[i];  
  231.         if (ost->encoding_needed){  
  232.             av_freep(&ost->st->codec->stats_in);  
  233.             avcodec_close(ost->st->codec);  
  234.         }  
  235. #if CONFIG_AVFILTER  
  236.         avfilter_graph_free(&ost->graph);  
  237. #endif  
  238.     }  
  239.   
  240.     //关闭所有的解码器  
  241.     for (i = 0; i < nb_input_streams; i++){  
  242.         ist = &input_streams[i];  
  243.         if (ist->decoding_needed){  
  244.             avcodec_close(ist->st->codec);  
  245.         }  
  246.     }  
  247.   
  248.     /* finished ! */  
  249.     ret = 0;  
  250.   
  251.     fail: av_freep(&bit_buffer);  
  252.     av_freep(&no_packet);  
  253.   
  254.     if (output_streams) {  
  255.         for (i = 0; i < nb_output_streams; i++)  {  
  256.             ost = &output_streams[i];  
  257.             if (ost)    {  
  258.                 if (ost->stream_copy)  
  259.                     av_freep(&ost->st->codec->extradata);  
  260.                 if (ost->logfile){  
  261.                     fclose(ost->logfile);  
  262.                     ost->logfile = NULL;  
  263.                 }  
  264.                 av_fifo_free(ost->fifo); /* works even if fifo is not 
  265.                  initialized but set to zero */  
  266.                 av_freep(&ost->st->codec->subtitle_header);  
  267.                 av_free(ost->resample_frame.data[0]);  
  268.                 av_free(ost->forced_kf_pts);  
  269.                 if (ost->video_resample)  
  270.                     sws_freeContext(ost->img_resample_ctx);  
  271.                 swr_free(&ost->swr);  
  272.                 av_dict_free(&ost->opts);  
  273.             }  
  274.         }  
  275.     }  
  276.     return ret;  
  277. }  

transcode_init()函数

transcode_init()函数是在转换前做准备工作的.其大体要完成的任务在第一篇中已做了猜测.此处看一下它的真面目,不废话,看注释吧:

[cpp] view plaincopy
  1. //为转换过程做准备  
  2. static int transcode_init(OutputFile *output_files,  
  3.         int nb_output_files,  
  4.         InputFile *input_files,  
  5.         int nb_input_files)  
  6. {  
  7.     int ret = 0, i, j, k;  
  8.     AVFormatContext *oc;  
  9.     AVCodecContext *codec, *icodec;  
  10.     OutputStream *ost;  
  11.     InputStream *ist;  
  12.     char error[1024];  
  13.     int want_sdp = 1;  
  14.   
  15.     /* init framerate emulation */  
  16.     //初始化帧率仿真(转换时是不按帧率来的,但如果要求帧率仿真,就可以做到)  
  17.     for (i = 0; i < nb_input_files; i++)  
  18.     {  
  19.         InputFile *ifile = &input_files[i];  
  20.         //如果一个输入文件被要求帧率仿真(指的是即使是转换也像播放那样按照帧率来进行),  
  21.         //则为这个文件中所有流记录下开始时间  
  22.         if (ifile->rate_emu)  
  23.             for (j = 0; j < ifile->nb_streams; j++)  
  24.                 input_streams[j + ifile->ist_index].start = av_gettime();  
  25.     }  
  26.   
  27.     /* output stream init */  
  28.     for (i = 0; i < nb_output_files; i++)  
  29.     {  
  30.         //什么也没做,只是做了个判断而已  
  31.         oc = output_files[i].ctx;  
  32.         if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS))  
  33.         {  
  34.             av_dump_format(oc, i, oc->filename, 1);  
  35.             av_log(NULL, AV_LOG_ERROR,  
  36.                     "Output file #%d does not contain any stream\n", i);  
  37.             return AVERROR(EINVAL);  
  38.         }  
  39.     }  
  40.   
  41.     //轮循所有的输出流,跟据对应的输入流,设置其编解码器的参数  
  42.     for (i = 0; i < nb_output_streams; i++)  
  43.     {  
  44.         //轮循所有的输出流  
  45.         ost = &output_streams[i];  
  46.         //输出流对应的FormatContext  
  47.         oc = output_files[ost->file_index].ctx;  
  48.         //取得输出流对应的输入流  
  49.         ist = &input_streams[ost->source_index];  
  50.   
  51.         //attachment_filename是不是这样的东西:一个文件,它单独容纳一个输出流?此处不懂  
  52.         if (ost->attachment_filename)  
  53.             continue;  
  54.   
  55.         codec = ost->st->codec;//输出流的编解码器结构  
  56.         icodec = ist->st->codec;//输入流的编解码器结构  
  57.   
  58.         //先把能复制的复制一下  
  59.         ost->st->disposition = ist->st->disposition;  
  60.         codec->bits_per_raw_sample = icodec->bits_per_raw_sample;  
  61.         codec->chroma_sample_location = icodec->chroma_sample_location;  
  62.   
  63.         //如果只是复制一个流(不用解码后再编码),则把输入流的编码参数直接复制给输出流  
  64.         //此时是不需要解码也不需要编码的,所以不需打开解码器和编码器  
  65.         if (ost->stream_copy)  
  66.         {  
  67.             //计算输出流的编解码器的extradata的大小,然后分配容纳extradata的缓冲  
  68.             //然后把输入流的编解码器的extradata复制到输出流的编解码器中  
  69.             uint64_t extra_size = (uint64_t) icodec->extradata_size  
  70.                     + FF_INPUT_BUFFER_PADDING_SIZE;  
  71.   
  72.             if (extra_size > INT_MAX)    {  
  73.                 return AVERROR(EINVAL);  
  74.             }  
  75.   
  76.             /* if stream_copy is selected, no need to decode or encode */  
  77.             codec->codec_id = icodec->codec_id;  
  78.             codec->codec_type = icodec->codec_type;  
  79.   
  80.             if (!codec->codec_tag){  
  81.                 if (!oc->oformat->codec_tag  
  82.                     ||av_codec_get_id(oc->oformat->codec_tag,icodec->codec_tag) == codec->codec_id  
  83.                     ||av_codec_get_tag(oc->oformat->codec_tag,icodec->codec_id) <= 0)  
  84.                     codec->codec_tag = icodec->codec_tag;  
  85.             }  
  86.   
  87.             codec->bit_rate = icodec->bit_rate;  
  88.             codec->rc_max_rate = icodec->rc_max_rate;  
  89.             codec->rc_buffer_size = icodec->rc_buffer_size;  
  90.             codec->extradata = av_mallocz(extra_size);  
  91.             if (!codec->extradata){  
  92.                 return AVERROR(ENOMEM);  
  93.             }  
  94.             memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);  
  95.             codec->extradata_size = icodec->extradata_size;  
  96.   
  97.             //重新鼓捣一下time base(这家伙就是帧率)  
  98.             codec->time_base = ist->st->time_base;  
  99.             //如果输出文件是avi,做一点特殊处理  
  100.             if (!strcmp(oc->oformat->name, "avi"))    {  
  101.                 if (copy_tb < 0  
  102.                         && av_q2d(icodec->time_base) * icodec->ticks_per_frame    >  
  103.                             2 * av_q2d(ist->st->time_base)  
  104.                         && av_q2d(ist->st->time_base) < 1.0 / 500  
  105.                         || copy_tb == 0)  
  106.                 {  
  107.                     codec->time_base = icodec->time_base;  
  108.                     codec->time_base.num *= icodec->ticks_per_frame;  
  109.                     codec->time_base.den *= 2;  
  110.                 }  
  111.             }  
  112.             else if (!(oc->oformat->flags & AVFMT_VARIABLE_FPS))  
  113.             {  
  114.                 if (copy_tb < 0  
  115.                         && av_q2d(icodec->time_base) * icodec->ticks_per_frame  
  116.                                 > av_q2d(ist->st->time_base)  
  117.                         && av_q2d(ist->st->time_base) < 1.0 / 500  
  118.                         || copy_tb == 0)  
  119.                 {  
  120.                     codec->time_base = icodec->time_base;  
  121.                     codec->time_base.num *= icodec->ticks_per_frame;  
  122.                 }  
  123.             }  
  124.   
  125.             //再修正一下帧率  
  126.             av_reduce(&codec->time_base.num, &codec->time_base.den,  
  127.                     codec->time_base.num, codec->time_base.den, INT_MAX);  
  128.   
  129.             //单独复制各不同媒体自己的编码参数  
  130.             switch (codec->codec_type)  
  131.             {  
  132.             case AVMEDIA_TYPE_AUDIO:  
  133.                 //音频的  
  134.                 if (audio_volume != 256){  
  135.                     av_log( NULL,AV_LOG_FATAL,  
  136.                             "-acodec copy and -vol are incompatible (frames are not decoded)\n");  
  137.                     exit_program(1);  
  138.                 }  
  139.                 codec->channel_layout = icodec->channel_layout;  
  140.                 codec->sample_rate = icodec->sample_rate;  
  141.                 codec->channels = icodec->channels;  
  142.                 codec->frame_size = icodec->frame_size;  
  143.                 codec->audio_service_type = icodec->audio_service_type;  
  144.                 codec->block_align = icodec->block_align;  
  145.                 break;  
  146.             case AVMEDIA_TYPE_VIDEO:  
  147.                 //视频的  
  148.                 codec->pix_fmt = icodec->pix_fmt;  
  149.                 codec->width = icodec->width;  
  150.                 codec->height = icodec->height;  
  151.                 codec->has_b_frames = icodec->has_b_frames;  
  152.                 if (!codec->sample_aspect_ratio.num){  
  153.                     codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =  
  154.                             ist->st->sample_aspect_ratio.num ?ist->st->sample_aspect_ratio :  
  155.                                     ist->st->codec->sample_aspect_ratio.num ?ist->st->codec->sample_aspect_ratio :(AVRational){0, 1};  
  156.                 }  
  157.                 ost->st->avg_frame_rate = ist->st->avg_frame_rate;  
  158.                 break;  
  159.             case AVMEDIA_TYPE_SUBTITLE:  
  160.                 //字幕的  
  161.                 codec->width  = icodec->width;  
  162.                 codec->height = icodec->height;  
  163.                 break;  
  164.             case AVMEDIA_TYPE_DATA:  
  165.             case AVMEDIA_TYPE_ATTACHMENT:  
  166.                 //??的  
  167.                 break;  
  168.             default:  
  169.                 abort();  
  170.             }  
  171.     }  
  172.     else  
  173.     {  
  174.         //如果不是复制,就麻烦多了  
  175.   
  176.         //获取编码器  
  177.         if (!ost->enc)  
  178.             ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);  
  179.   
  180.         //因为需要转换,所以既需解码又需编码  
  181.         ist->decoding_needed = 1;  
  182.         ost->encoding_needed = 1;  
  183.   
  184.         switch(codec->codec_type)  
  185.         {  
  186.         case AVMEDIA_TYPE_AUDIO:  
  187.             //鼓捣音频编码器的参数,基本上是把一些不合适的参数替换掉  
  188.             ost->fifo = av_fifo_alloc(1024);//音频数据所在的缓冲  
  189.             if (!ost->fifo)  {  
  190.                 return AVERROR(ENOMEM);  
  191.             }  
  192.   
  193.             //采样率  
  194.             if (!codec->sample_rate)  
  195.                 codec->sample_rate = icodec->sample_rate;  
  196.             choose_sample_rate(ost->st, ost->enc);  
  197.             codec->time_base = (AVRational){1, codec->sample_rate};  
  198.   
  199.             //样点格式  
  200.             if (codec->sample_fmt == AV_SAMPLE_FMT_NONE)  
  201.                 codec->sample_fmt = icodec->sample_fmt;  
  202.             choose_sample_fmt(ost->st, ost->enc);  
  203.   
  204.             //声道  
  205.             if (ost->audio_channels_mapped)  {  
  206.                 /* the requested output channel is set to the number of 
  207.                  * -map_channel only if no -ac are specified */  
  208.                 if (!codec->channels)    {  
  209.                     codec->channels = ost->audio_channels_mapped;  
  210.                     codec->channel_layout = av_get_default_channel_layout(codec->channels);  
  211.                     if (!codec->channel_layout)  {  
  212.                         av_log(NULL, AV_LOG_FATAL, "Unable to find an appropriate channel layout for requested number of channel\n);  
  213.                         exit_program(1);  
  214.                     }  
  215.                 }  
  216.                 /* fill unused channel mapping with -1 (which means a muted 
  217.                  * channel in case the number of output channels is bigger 
  218.                  * than the number of mapped channel) */  
  219.                 for (j = ost->audio_channels_mapped; j < FF_ARRAY_ELEMS(ost->audio_channels_map); j++)  
  220.                 <span>  </span>ost->audio_channels_map[j] = -1;  
  221.             }else if (!codec->channels){  
  222.                 codec->channels = icodec->channels;  
  223.                 codec->channel_layout = icodec->channel_layout;  
  224.             }  
  225.             if (av_get_channel_layout_nb_channels(codec->channel_layout) != codec->channels)  
  226.                 codec->channel_layout = 0;  
  227.   
  228.             //是否需要重采样  
  229.             ost->audio_resample = codec->sample_rate != icodec->sample_rate || audio_sync_method > 1;  
  230.             ost->audio_resample |= codec->sample_fmt != icodec->sample_fmt ||  
  231.                     codec->channel_layout != icodec->channel_layout;  
  232.             icodec->request_channels = codec->channels;  
  233.             ost->resample_sample_fmt = icodec->sample_fmt;  
  234.             ost->resample_sample_rate = icodec->sample_rate;  
  235.             ost->resample_channels = icodec->channels;  
  236.             break;  
  237.         case AVMEDIA_TYPE_VIDEO:  
  238.             //鼓捣视频编码器的参数,基本上是把一些不合适的参数替换掉  
  239.             if (codec->pix_fmt == PIX_FMT_NONE)  
  240.                 codec->pix_fmt = icodec->pix_fmt;  
  241.             choose_pixel_fmt(ost->st, ost->enc);  
  242.             if (ost->st->codec->pix_fmt == PIX_FMT_NONE){  
  243.                 av_log(NULL, AV_LOG_FATAL, "Video pixel format is unknown, stream cannot be encoded\n");  
  244.                 exit_program(1);  
  245.             }  
  246.   
  247.             //宽高  
  248.             if (!codec->width || !codec->height){  
  249.                 codec->width = icodec->width;  
  250.                 codec->height = icodec->height;  
  251.             }  
  252.   
  253.             //视频是否需要重采样  
  254.             ost->video_resample = codec->width != icodec->width ||  
  255.                     codec->height != icodec->height ||  
  256.                     codec->pix_fmt != icodec->pix_fmt;  
  257.             if (ost->video_resample){  
  258.                 codec->bits_per_raw_sample= frame_bits_per_raw_sample;  
  259.             }  
  260.   
  261.             ost->resample_height = icodec->height;  
  262.             ost->resample_width = icodec->width;  
  263.             ost->resample_pix_fmt = icodec->pix_fmt;  
  264.   
  265.             //计算帧率  
  266.             if (!ost->frame_rate.num)  
  267.                 ost->frame_rate = ist->st->r_frame_rate.num ?  
  268.                         ist->st->r_frame_rate : (AVRational){25,1};  
  269.             if (ost->enc && ost->enc->supported_framerates && !ost->force_fps)  {  
  270.                 int idx = av_find_nearest_q_idx(ost->frame_rate,ost->enc->supported_framerates);  
  271.                 ost->frame_rate = ost->enc->supported_framerates[idx];  
  272.             }  
  273.             codec->time_base = (AVRational)  {ost->frame_rate.den, ost->frame_rate.num};  
  274.             if( av_q2d(codec->time_base) < 0.001 &&  
  275.                     video_sync_method &&  
  276.                     (video_sync_method==1 ||  
  277.                         (video_sync_method<0 &&  !  
  278.                             (oc->oformat->flags & AVFMT_VARIABLE_FPS))))  
  279.             {  
  280.                 av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not effciciently supporting it.\n"  
  281.                         "Please consider specifiying a lower framerate, a different muxer or -vsync 2\n");  
  282.             }  
  283.         <span>  </span>for (j = 0; j < ost->forced_kf_count; j++)  
  284.                 ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],  
  285.                         AV_TIME_BASE_Q, codec->time_base);  
  286.                 break;  
  287.             case AVMEDIA_TYPE_SUBTITLE:  
  288.                 break;  
  289.             default:  
  290.                 abort();  
  291.                 break;  
  292.             }  
  293.             /* two pass mode */  
  294.             if (codec->codec_id != CODEC_ID_H264 &&  
  295.                     (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)))  
  296.             {  
  297.                 char logfilename[1024];  
  298.                 FILE *f;  
  299.   
  300.                 snprintf(logfilename, sizeof(logfilename), "%s-%d.log",  
  301.                         pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,  
  302.                         i);  
  303.                 if (codec->flags & CODEC_FLAG_PASS2){  
  304.                     char *logbuffer;  
  305.                     size_t logbuffer_size;  
  306.                     if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0){  
  307.                         av_log(NULL, AV_LOG_FATAL,  
  308.                                 "Error reading log file '%s' for pass-2 encoding\n",  
  309.                                 logfilename);  
  310.                         exit_program(1);  
  311.                     }  
  312.                     codec->stats_in = logbuffer;  
  313.                 }  
  314.                 if (codec->flags & CODEC_FLAG_PASS1){  
  315.                     f = fopen(logfilename, "wb");  
  316.                     if (!f) {  
  317.                         av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",  
  318.                                 logfilename, strerror(errno));  
  319.                         exit_program(1);  
  320.                     }  
  321.                     ost->logfile = f;  
  322.                 }  
  323.             }  
  324.         }  
  325.         if (codec->codec_type == AVMEDIA_TYPE_VIDEO){  
  326.             /* maximum video buffer size is 6-bytes per pixel, plus DPX header size (1664)*/  
  327.             //计算编码输出缓冲的大小,计算一个最大值  
  328.             int size = codec->width * codec->height;  
  329.             bit_buffer_size = FFMAX(bit_buffer_size, 7 * size + 10000);  
  330.         }  
  331.     }  
  332.   
  333.     //分配编码后数据所在的缓冲  
  334.     if (!bit_buffer)  
  335.         bit_buffer = av_malloc(bit_buffer_size);  
  336.     if (!bit_buffer){  
  337.         av_log(NULL, AV_LOG_ERROR,  
  338.                 "Cannot allocate %d bytes output buffer\n",  
  339.                 bit_buffer_size);  
  340.         return AVERROR(ENOMEM);  
  341.     }  
  342.   
  343.     //轮循所有输出流,打开每个输出流的编码器  
  344.     for (i = 0; i < nb_output_streams; i++)  
  345.     {  
  346.         ost = &output_streams[i];  
  347.         if (ost->encoding_needed){  
  348.             //当然,只有在需要编码时才打开编码器  
  349.             AVCodec *codec = ost->enc;  
  350.             AVCodecContext *dec = input_streams[ost->source_index].st->codec;  
  351.             if (!codec) {  
  352.                 snprintf(error, sizeof(error),  
  353.                         "Encoder (codec %s) not found for output stream #%d:%d",  
  354.                         avcodec_get_name(ost->st->codec->codec_id),  
  355.                         ost->file_index, ost->index);  
  356.                 ret = AVERROR(EINVAL);  
  357.                 goto dump_format;  
  358.             }  
  359.             if (dec->subtitle_header){  
  360.                 ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);  
  361.                 if (!ost->st->codec->subtitle_header){  
  362.                     ret = AVERROR(ENOMEM);  
  363.                     goto dump_format;  
  364.                 }  
  365.                 memcpy(ost->st->codec->subtitle_header,  
  366.                         dec->subtitle_header,dec->subtitle_header_size);  
  367.                 ost->st->codec->subtitle_header_size = dec->subtitle_header_size;  
  368.             }  
  369.             //打开啦  
  370.             if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0)   {  
  371.                 snprintf(error, sizeof(error),  
  372.                         "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",  
  373.                         ost->file_index, ost->index);  
  374.                 ret = AVERROR(EINVAL);  
  375.                 goto dump_format;  
  376.             }  
  377.             assert_codec_experimental(ost->st->codec, 1);  
  378.             assert_avoptions(ost->opts);  
  379.             if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)  
  380.                 av_log(NULL, AV_LOG_WARNING,  
  381.                         "The bitrate parameter is set too low."  
  382.                         " It takes bits/s as argument, not kbits/s\n");  
  383.             extra_size += ost->st->codec->extradata_size;  
  384.   
  385.             if (ost->st->codec->me_threshold)  
  386.                 input_streams[ost->source_index].st->codec->debug |= FF_DEBUG_MV;  
  387.         }  
  388.     }  
  389.   
  390.     //初始化所有的输入流(主要做的就是在需要时打开解码器)  
  391.     for (i = 0; i < nb_input_streams; i++)  
  392.         if ((ret = init_input_stream(i, output_streams, nb_output_streams,  
  393.                 error, sizeof(error))) < 0)  
  394.             goto dump_format;  
  395.   
  396.     /* discard unused programs */  
  397.     for (i = 0; i < nb_input_files; i++){  
  398.         InputFile *ifile = &input_files[i];  
  399.         for (j = 0; j < ifile->ctx->nb_programs; j++){  
  400.             AVProgram *p = ifile->ctx->programs[j];  
  401.             int discard = AVDISCARD_ALL;  
  402.   
  403.             for (k = 0; k < p->nb_stream_indexes; k++){  
  404.                 if (!input_streams[ifile->ist_index + p->stream_index[k]].discard){  
  405.                     discard = AVDISCARD_DEFAULT;  
  406.                     break;  
  407.                 }  
  408.             }  
  409.             p->discard = discard;  
  410.         }  
  411.     }  
  412.   
  413.     //打开所有输出文件,写入媒体文件头  
  414.     for (i = 0; i < nb_output_files; i++){  
  415.         oc = output_files[i].ctx;  
  416.         oc->interrupt_callback = int_cb;  
  417.         if (avformat_write_header(oc, &output_files[i].opts) < 0){  
  418.             snprintf(error, sizeof(error),  
  419.                     "Could not write header for output file #%d (incorrect codec parameters ?)",  
  420.                     i);  
  421.             ret = AVERROR(EINVAL);  
  422.             goto dump_format;  
  423.         }  
  424. //        assert_avoptions(output_files[i].opts);  
  425.         if (strcmp(oc->oformat->name, "rtp")){  
  426.             want_sdp = 0;  
  427.         }  
  428.     }  
  429.   
  430.     return 0;  
  431. }  
转自:http://blog.csdn.net/nkmnkm/article/details/7177877