最新版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. reset_options(&o, 0);
  7. //设置日志级别
  8. av_log_set_flags(AV_LOG_SKIP_REPEATED);
  9. parse_loglevel(argc, argv, options);
  10. if (argc > 1 && !strcmp(argv[1], "-d"))  {
  11. run_as_daemon = 1;
  12. av_log_set_callback(log_callback_null);
  13. argc--;
  14. argv++;
  15. }
  16. //注册组件们
  17. avcodec_register_all();
  18. #if CONFIG_AVDEVICE
  19. avdevice_register_all();
  20. #endif
  21. #if CONFIG_AVFILTER
  22. avfilter_register_all();
  23. #endif
  24. av_register_all();
  25. //初始化网络,windows下需要
  26. avformat_network_init();
  27. show_banner();
  28. term_init();
  29. //分析命令行输入的参数们
  30. parse_options(&o, argc, argv, options, opt_output_file);
  31. //文件的转换就在此函数中发生
  32. if (transcode(output_files, nb_output_files, input_files, nb_input_files)< 0)
  33. exit_program(1);
  34. exit_program(0);
  35. return 0;
  36. }

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

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

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

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

431.}

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

最新文章

  1. 377. Combination Sum IV
  2. 根据屏幕的宽度使用不同的css-文件
  3. ArcEngine10.1二次开发错误: 无法嵌入互操作类型,请改用适用的接口
  4. Java提高篇---Map总结
  5. 使用FindFirstFile,FindNextFile遍历一个文件夹
  6. ZOJ3717 Balloon(2-SAT)
  7. Android之开发杂记(一)
  8. ubuntu下hadoop2.6在eclipse上的配置
  9. ios swift学习日记1-Swift 初见
  10. (五)Hololens Unity 开发之 手势识别
  11. githup教程
  12. flask_login 整合 pyjwt + json 简易flask框架
  13. Java中的几种常用循环
  14. TensorFlow Jupyter Notebook 和matplotlib安装配置
  15. HashMap 实现总结
  16. JQuery设置和去除disabled属性 与 display显示隐藏
  17. ES6对抽象工厂模式与策略模式结合的实践
  18. MySQL Replication 线程(理解详细过程)
  19. java判断字符串中是否含有中文
  20. javascript飞机大战-----008积分

热门文章

  1. ios initialize和init等方法
  2. C# 基础(5)--字符串
  3. 线状DP(石子归并)
  4. nodejs:csv模块解析
  5. oracle decode(nvl(estimate_qty,0),0,1,estimate_qty) 函數
  6. Objective C笔记(第一天)
  7. 安装SQLSERVER2012遇到的一些问题
  8. C#设计模式(16)——迭代器模式(Iterator Pattern)
  9. ASP.NET Core 1.0 中使用 Swagger 生成文档
  10. ArcMap 连接SDE 出错&ldquo;Failed to connect to the specified server. Entry for SDE instance no found in services file.&rdquo;