最新版ffmpeg源码分析

 最新版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

  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 ");  
  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" ",  
  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 ",  
  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. }  

ffmpeg源码分析三

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 ", 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. av_reduce(&codec->time_base.num, &codec->time_base.den,  
  126. codec->time_base.num, codec->time_base.den, INT_MAX);  
  127. //单独复制各不同媒体自己的编码参数  
  128. switch (codec->codec_type)  
  129. {  
  130. case AVMEDIA_TYPE_AUDIO:  
  131. //音频的  
  132. if (audio_volume != 256){  
  133. av_log( NULL,AV_LOG_FATAL,  
  134. "-acodec copy and -vol are incompatible (frames are not decoded) ");  
  135. exit_program(1);  
  136. }  
  137. codec->channel_layout = icodec->channel_layout;  
  138. codec->sample_rate = icodec->sample_rate;  
  139. codec->channels = icodec->channels;  
  140. codec->frame_size = icodec->frame_size;  
  141. codec->audio_service_type = icodec->audio_service_type;  
  142. codec->block_align = icodec->block_align;  
  143. break;  
  144. case AVMEDIA_TYPE_VIDEO:  
  145. //视频的  
  146. codec->pix_fmt = icodec->pix_fmt;  
  147. codec->width = icodec->width;  
  148. codec->height = icodec->height;  
  149. codec->has_b_frames = icodec->has_b_frames;  
  150. if (!codec->sample_aspect_ratio.num){  
  151. codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =  
  152. ist->st->sample_aspect_ratio.num ?ist->st->sample_aspect_ratio :  
  153. ist->st->codec->sample_aspect_ratio.num ?ist->st->codec->sample_aspect_ratio :(AVRational){0, 1};  
  154. }  
  155. ost->st->avg_frame_rate = ist->st->avg_frame_rate;  
  156. break;  
  157. case AVMEDIA_TYPE_SUBTITLE:  
  158. //字幕的  
  159. codec->width  = icodec->width;  
  160. codec->height = icodec->height;  
  161. break;  
  162. case AVMEDIA_TYPE_DATA:  
  163. case AVMEDIA_TYPE_ATTACHMENT:  
  164. //??的  
  165. break;  
  166. default:  
  167. abort();  
  168. }  
  169. }  
  170. else  
  171. {  
  172. //如果不是复制,就麻烦多了  
  173. //获取编码器  
  174. if (!ost->enc)  
  175. ost->enc = avcodec_find_encoder(ost->st->codec->codec_id);  
  176. //因为需要转换,所以既需解码又需编码  
  177. ist->decoding_needed = 1;  
  178. ost->encoding_needed = 1;  
  179. switch(codec->codec_type)  
  180. {  
  181. case AVMEDIA_TYPE_AUDIO:  
  182. //鼓捣音频编码器的参数,基本上是把一些不合适的参数替换掉  
  183. ost->fifo = av_fifo_alloc(1024);//音频数据所在的缓冲  
  184. if (!ost->fifo)  {  
  185. return AVERROR(ENOMEM);  
  186. }  
  187. //采样率  
  188. if (!codec->sample_rate)  
  189. codec->sample_rate = icodec->sample_rate;  
  190. choose_sample_rate(ost->st, ost->enc);  
  191. codec->time_base = (AVRational){1, codec->sample_rate};  
  192. //样点格式  
  193. if (codec->sample_fmt == AV_SAMPLE_FMT_NONE)  
  194. codec->sample_fmt = icodec->sample_fmt;  
  195. choose_sample_fmt(ost->st, ost->enc);  
  196. //声道  
  197. if (ost->audio_channels_mapped)  {  
  198. /* the requested output channel is set to the number of 
  199. * -map_channel only if no -ac are specified */  
  200. if (!codec->channels)    {  
  201. codec->channels = ost->audio_channels_mapped;  
  202. codec->channel_layout = av_get_default_channel_layout(codec->channels);  
  203. if (!codec->channel_layout)  {  
  204. av_log(NULL, AV_LOG_FATAL, "Unable to find an appropriate channel layout for requested number of channel );  
  205. exit_program(1);  
  206. }  
  207. }  
  208. /* fill unused channel mapping with -1 (which means a muted 
  209. * channel in case the number of output channels is bigger 
  210. * than the number of mapped channel) */  
  211. for (j = ost->audio_channels_mapped; j < FF_ARRAY_ELEMS(ost->audio_channels_map); j++)  
  212. <span>  </span>ost->audio_channels_map[j] = -1;  
  213. }else if (!codec->channels){  
  214. codec->channels = icodec->channels;  
  215. codec->channel_layout = icodec->channel_layout;  
  216. }  
  217. if (av_get_channel_layout_nb_channels(codec->channel_layout) != codec->channels)  
  218. codec->channel_layout = 0;  
  219. //是否需要重采样  
  220. ost->audio_resample = codec->sample_rate != icodec->sample_rate || audio_sync_method > 1;  
  221. ost->audio_resample |= codec->sample_fmt != icodec->sample_fmt ||  
  222. codec->channel_layout != icodec->channel_layout;  
  223. icodec->request_channels = codec->channels;  
  224. ost->resample_sample_fmt = icodec->sample_fmt;  
  225. ost->resample_sample_rate = icodec->sample_rate;  
  226. ost->resample_channels = icodec->channels;  
  227. break;  
  228. case AVMEDIA_TYPE_VIDEO:  
  229. //鼓捣视频编码器的参数,基本上是把一些不合适的参数替换掉  
  230. if (codec->pix_fmt == PIX_FMT_NONE)  
  231. codec->pix_fmt = icodec->pix_fmt;  
  232. choose_pixel_fmt(ost->st, ost->enc);  
  233. if (ost->st->codec->pix_fmt == PIX_FMT_NONE){  
  234. av_log(NULL, AV_LOG_FATAL, "Video pixel format is unknown, stream cannot be encoded ");  
  235. exit_program(1);  
  236. }  
  237. //宽高  
  238. if (!codec->width || !codec->height){  
  239. codec->width = icodec->width;  
  240. codec->height = icodec->height;  
  241. }  
  242. //视频是否需要重采样  
  243. ost->video_resample = codec->width != icodec->width ||  
  244. codec->height != icodec->height ||  
  245. codec->pix_fmt != icodec->pix_fmt;  
  246. if (ost->video_resample){  
  247. codec->bits_per_raw_sample= frame_bits_per_raw_sample;  
  248. }  
  249. ost->resample_height = icodec->height;  
  250. ost->resample_width = icodec->width;  
  251. ost->resample_pix_fmt = icodec->pix_fmt;  
  252. //计算帧率  
  253. if (!ost->frame_rate.num)  
  254. ost->frame_rate = ist->st->r_frame_rate.num ?  
  255. ist->st->r_frame_rate : (AVRational){25,1};  
  256. if (ost->enc && ost->enc->supported_framerates && !ost->force_fps)  {  
  257. int idx = av_find_nearest_q_idx(ost->frame_rate,ost->enc->supported_framerates);  
  258. ost->frame_rate = ost->enc->supported_framerates[idx];  
  259. }  
  260. codec->time_base = (AVRational)  {ost->frame_rate.den, ost->frame_rate.num};  
  261. if( av_q2d(codec->time_base) < 0.001 &&  
  262. video_sync_method &&  
  263. (video_sync_method==1 ||  
  264. (video_sync_method<0 &&  !  
  265. (oc->oformat->flags & AVFMT_VARIABLE_FPS))))  
  266. {  
  267. av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not effciciently supporting it. "  
  268. "Please consider specifiying a lower framerate, a different muxer or -vsync 2 ");  
  269. }  
  270. <span>  </span>for (j = 0; j < ost->forced_kf_count; j++)  
  271. ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],  
  272. AV_TIME_BASE_Q, codec->time_base);  
  273. break;  
  274. case AVMEDIA_TYPE_SUBTITLE:  
  275. break;  
  276. default:  
  277. abort();  
  278. break;  
  279. }  
  280. /* two pass mode */  
  281. if (codec->codec_id != CODEC_ID_H264 &&  
  282. (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)))  
  283. {  
  284. char logfilename[1024];  
  285. FILE *f;  
  286. snprintf(logfilename, sizeof(logfilename), "%s-%d.log",  
  287. pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,  
  288. i);  
  289. if (codec->flags & CODEC_FLAG_PASS2){  
  290. char *logbuffer;  
  291. size_t logbuffer_size;  
  292. if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0){  
  293. av_log(NULL, AV_LOG_FATAL,  
  294. "Error reading log file '%s' for pass-2 encoding ",  
  295. logfilename);  
  296. exit_program(1);  
  297. }  
  298. codec->stats_in = logbuffer;  
  299. }  
  300. if (codec->flags & CODEC_FLAG_PASS1){  
  301. f = fopen(logfilename, "wb");  
  302. if (!f) {  
  303. av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s ",  
  304. logfilename, strerror(errno));  
  305. exit_program(1);  
  306. }  
  307. ost->logfile = f;  
  308. }  
  309. }  
  310. }  
  311. if (codec->codec_type == AVMEDIA_TYPE_VIDEO){  
  312. /* maximum video buffer size is 6-bytes per pixel, plus DPX header size (1664)*/  
  313. //计算编码输出缓冲的大小,计算一个最大值  
  314. int size = codec->width * codec->height;  
  315. bit_buffer_size = FFMAX(bit_buffer_size, 7 * size + 10000);  
  316. }  
  317. }  
  318. //分配编码后数据所在的缓冲  
  319. if (!bit_buffer)  
  320. bit_buffer = av_malloc(bit_buffer_size);  
  321. if (!bit_buffer){  
  322. av_log(NULL, AV_LOG_ERROR,  
  323. "Cannot allocate %d bytes output buffer ",  
  324. bit_buffer_size);  
  325. return AVERROR(ENOMEM);  
  326. }  
  327. //轮循所有输出流,打开每个输出流的编码器  
  328. for (i = 0; i < nb_output_streams; i++)  
  329. {  
  330. ost = &output_streams[i];  
  331. if (ost->encoding_needed){  
  332. //当然,只有在需要编码时才打开编码器  
  333. AVCodec *codec = ost->enc;  
  334. AVCodecContext *dec = input_streams[ost->source_index].st->codec;  
  335. if (!codec) {  
  336. snprintf(error, sizeof(error),  
  337. "Encoder (codec %s) not found for output stream #%d:%d",  
  338. avcodec_get_name(ost->st->codec->codec_id),  
  339. ost->file_index, ost->index);  
  340. ret = AVERROR(EINVAL);  
  341. goto dump_format;  
  342. }  
  343. if (dec->subtitle_header){  
  344. ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);  
  345. if (!ost->st->codec->subtitle_header){  
  346. ret = AVERROR(ENOMEM);  
  347. goto dump_format;  
  348. }  
  349. memcpy(ost->st->codec->subtitle_header,  
  350. dec->subtitle_header,dec->subtitle_header_size);  
  351. ost->st->codec->subtitle_header_size = dec->subtitle_header_size;  
  352. }  
  353. //打开啦  
  354. if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0)   {  
  355. snprintf(error, sizeof(error),  
  356. "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",  
  357. ost->file_index, ost->index);  
  358. ret = AVERROR(EINVAL);  
  359. goto dump_format;  
  360. }  
  361. assert_codec_experimental(ost->st->codec, 1);  
  362. assert_avoptions(ost->opts);  
  363. if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)  
  364. av_log(NULL, AV_LOG_WARNING,  
  365. "The bitrate parameter is set too low."  
  366. " It takes bits/s as argument, not kbits/s ");  
  367. extra_size += ost->st->codec->extradata_size;  
  368. if (ost->st->codec->me_threshold)  
  369. input_streams[ost->source_index].st->codec->debug |= FF_DEBUG_MV;  
  370. }  
  371. }  
  372. //初始化所有的输入流(主要做的就是在需要时打开解码器)  
  373. for (i = 0; i < nb_input_streams; i++)  
  374. if ((ret = init_input_stream(i, output_streams, nb_output_streams,  
  375. error, sizeof(error))) < 0)  
  376. goto dump_format;  
  377. /* discard unused programs */  
  378. for (i = 0; i < nb_input_files; i++){  
  379. InputFile *ifile = &input_files[i];  
  380. for (j = 0; j < ifile->ctx->nb_programs; j++){  
  381. AVProgram *p = ifile->ctx->programs[j];  
  382. int discard = AVDISCARD_ALL;  
  383. for (k = 0; k < p->nb_stream_indexes; k++){  
  384. if (!input_streams[ifile->ist_index + p->stream_index[k]].discard){  
  385. discard = AVDISCARD_DEFAULT;  
  386. break;  
  387. }  
  388. }  
  389. p->discard = discard;  
  390. }  
  391. }  
  392. //打开所有输出文件,写入媒体文件头  
  393. for (i = 0; i < nb_output_files; i++){  
  394. oc = output_files[i].ctx;  
  395. oc->interrupt_callback = int_cb;  
  396. if (avformat_write_header(oc, &output_files[i].opts) < 0){  
  397. snprintf(error, sizeof(error),  
  398. "Could not write header for output file #%d (incorrect codec parameters ?)",  
  399. i);  
  400. ret = AVERROR(EINVAL);  
  401. goto dump_format;  
  402. }  

424.//        assert_avoptions(output_files[i].opts);  

  1. if (strcmp(oc->oformat->name, "rtp")){  
  2. want_sdp = 0;  
  3. }  
  4. }  
  5. return 0;  

431.}

版权声明:本文为博主原创文章,未经博主允许不得转载

原文地址:https://www.cnblogs.com/skyofbitbit/p/4964019.html