从ffmpeg源代码分析如何解决ffmpeg编码的延迟问题

192 篇文章 3 订阅 ¥19.90 ¥99.00

近日在做一个分布式转码服务器,解码器是采用开源的ffmpeg,在开发的过程中遇到一个问题:编码延迟多大5、6秒钟,也就是最初编码的几十帧并不能马上取出,而我们的要求是实时编码!虽然我对视频编码方面不是很熟悉,但根据开发的经验,我想必定可以通过设置一些参数来改变这些情况。但我本人接触ffmpeg项目时间并不长,对很多与编解码方面参数的设置并不熟悉,于是google了很久,网上也有相关方面的讨论,说什么的都有,但我试了不行,更有甚者说修改源代码的,这个可能能够解决问题,但修改源代码毕竟不是解决问题的最佳途径。于是决定分析一下源代码,跟踪源码来找出问题的根源。

    首先我使用的ffmpeg源代码版本是1.0.3,同时给出我的测试代码,项目中的代码就不给出来了,我给个简单的玩具代码:

[cpp]  view plain  copy
  1. <span style="font-family:Courier New;">/** 
  2.  * @file 
  3.  * libavcodec API use example. 
  4.  * 
  5.  * Note that libavcodec only handles codecs (mpeg, mpeg4, etc...), 
  6.  * not file formats (avi, vob, mp4, mov, mkv, mxf, flv, mpegts, mpegps, etc...). See library 'libavformat' for the 
  7.  * format handling 
  8.  */  
  9.   
  10. #if _MSC_VER  
  11. #define snprintf _snprintf  
  12. #endif  
  13.   
  14. #include <stdio.h>  
  15. #include <math.h>  
  16.   
  17. extern "C" {  
  18. #include <libavutil/opt.h>        // for av_opt_set  
  19. #include <libavcodec/avcodec.h>  
  20. #include <libavutil/imgutils.h>  
  21. };  
  22.   
  23. /* 
  24.  * Video encoding example 
  25.  */  
  26. static void video_encode_example(const char *filename, int codec_id)  
  27. {  
  28.     AVCodec *codec;  
  29.     AVCodecContext *c= NULL;  
  30.     int i, ret, x, y, got_output;  
  31.     FILE *f;  
  32.     AVFrame *picture;  
  33.     AVPacket pkt;  
  34.     uint8_t endcode[] = { 0, 0, 1, 0xb7 };  
  35.   
  36.     printf("Encode video file %s\n", filename);  
  37.   
  38.     /* find the mpeg1 video encoder */  
  39.     codec = avcodec_find_encoder((AVCodecID)codec_id);  
  40.     if (!codec) {  
  41.         fprintf(stderr, "codec not found\n");  
  42.         exit(1);  
  43.     }  
  44.   
  45.     c = avcodec_alloc_context3(codec);  
  46.   
  47.     /* put sample parameters */  
  48.     c->bit_rate = 400000;  
  49.     /* resolution must be a multiple of two */  
  50.     c->width = 800/*352*/;  
  51.     c->height = 500/*288*/;  
  52.     /* frames per second */  
  53.     c->time_base.den = 1;  
  54.     c->time_base.num = 25;  
  55.     c->gop_size = 10; /* emit one intra frame every ten frames */  
  56.     c->max_b_frames=1;  
  57.     c->pix_fmt = PIX_FMT_YUV420P;  
  58.   
  59.     /* open it */  
  60.     if (avcodec_open2(c, codec, NULL) < 0) {  
  61.         fprintf(stderr, "could not open codec\n");  
  62.         exit(1);  
  63.     }  
  64.   
  65.     f = fopen(filename, "wb");  
  66.     if (!f) {  
  67.         fprintf(stderr, "could not open %s\n", filename);  
  68.         exit(1);  
  69.     }  
  70.   
  71.     picture = avcodec_alloc_frame();  
  72.     if (!picture) {  
  73.         fprintf(stderr, "Could not allocate video frame\n");  
  74.         exit(1);  
  75.     }  
  76.     picture->format = c->pix_fmt;  
  77.     picture->width  = c->width;  
  78.     picture->height = c->height;  
  79.   
  80.     /* the image can be allocated by any means and av_image_alloc() is 
  81.      * just the most convenient way if av_malloc() is to be used */  
  82.     ret = av_image_alloc(picture->data, picture->linesize, c->width, c->height,  
  83.                          c->pix_fmt, 32);  
  84.     if (ret < 0) {  
  85.         fprintf(stderr, "could not alloc raw picture buffer\n");  
  86.         exit(1);  
  87.     }  
  88.   
  89.     static int delayedFrame = 0;  
  90.     /* encode 1 second of video */  
  91.     for(i=0;i<25;i++) {  
  92.         av_init_packet(&pkt);  
  93.         pkt.data = NULL;    // packet data will be allocated by the encoder  
  94.         pkt.size = 0;  
  95.   
  96.         fflush(stdout);  
  97.         /* prepare a dummy image */  
  98.         /* Y */  
  99.         for(y=0;y<c->height;y++) {  
  100.             for(x=0;x<c->width;x++) {  
  101.                 picture->data[0][y * picture->linesize[0] + x] = x + y + i * 3;  
  102.             }  
  103.         }  
  104.   
  105.         /* Cb and Cr */  
  106.         for(y=0;y<c->height/2;y++) {  
  107.             for(x=0;x<c->width/2;x++) {  
  108.                 picture->data[1][y * picture->linesize[1] + x] = 128 + y + i * 2;  
  109.                 picture->data[2][y * picture->linesize[2] + x] = 64 + x + i * 5;  
  110.             }  
  111.         }  
  112.   
  113.         picture->pts = i;  
  114.   
  115.         printf("encoding frame %3d----", i);  
  116.         /* encode the image */  
  117.         ret = avcodec_encode_video2(c, &pkt, picture, &got_output);  
  118.         if (ret < 0) {  
  119.             fprintf(stderr, "error encoding frame\n");  
  120.             exit(1);  
  121.         }  
  122.   
  123.         if (got_output) {  
  124.             printf("output frame %3d (size=%5d)\n", i-delayedFrame, pkt.size);  
  125.             fwrite(pkt.data, 1, pkt.size, f);  
  126.             av_free_packet(&pkt);  
  127.         }  
  128.         else {  
  129.             delayedFrame++;  
  130.             printf("no output frame\n");  
  131.         }  
  132.     }  
  133.   
  134.     /* get the delayed frames */  
  135.     for (got_output = 1; got_output; i++) {  
  136.         fflush(stdout);  
  137.   
  138.         ret = avcodec_encode_video2(c, &pkt, NULL, &got_output);  
  139.         if (ret < 0) {  
  140.             fprintf(stderr, "error encoding frame\n");  
  141.             exit(1);  
  142.         }  
  143.   
  144.         if (got_output) {  
  145.             printf("output delayed frame %3d (size=%5d)\n", i-delayedFrame, pkt.size);  
  146.             fwrite(pkt.data, 1, pkt.size, f);  
  147.             av_free_packet(&pkt);  
  148.         }  
  149.     }  
  150.   
  151.     /* add sequence end code to have a real mpeg file */  
  152.     fwrite(endcode, 1, sizeof(endcode), f);  
  153.     fclose(f);  
  154.   
  155.     avcodec_close(c);  
  156.     av_free(c);  
  157.     av_freep(&picture->data[0]);  
  158.     av_free(picture);  
  159.     printf("\n");  
  160. }  
  161.   
  162. int main(int argc, char **argv)  
  163. {  
  164.     /* register all the codecs */  
  165.     avcodec_register_all();  
  166.   
  167.     video_encode_example("test.h264", AV_CODEC_ID_H264);  
  168.   
  169.     system("pause");  
  170.   
  171.     return 0;  
  172. }</span>  
     运行上面的代码,我们编码25帧,发现延迟了多达18帧,如下图所示:

    现在我们开始分析ffmpeg的源代码(因为ffmpeg的编码器是基于X264项目的,所以我们的代码还要追踪带X264中去):

avcodec_register_all()做了些什么

    因为我们关心的是H.264的编码所以我们只关心该函数中对X264编码器做了些什么,该函数主要是注册ffmpeg提供的所有编解码器,由于该函数较长,但都是相同的动作(注册编解码器),所以我们只列出部分的代码:

[cpp]  view plain  copy
  1. <span style="font-family:Courier New;">void avcodec_register_all(void)  
  2. {  
  3.     static int initialized;  
  4.   
  5.     if (initialized)  
  6.         return;  
  7.     initialized = 1;  
  8.   
  9.     /* hardware accelerators */  
  10.     REGISTER_HWACCEL (H263_VAAPI, h263_vaapi);  
  11.     REGISTER_HWACCEL (H264_DXVA2, h264_dxva2);  
  12.     ......  
  13.   
  14.     /* video codecs */  
  15.     REGISTER_ENCODER (A64MULTI, a64multi);  
  16.     REGISTER_ENCODER (A64MULTI5, a64multi5);  
  17.     ......  
  18.   
  19.     /* audio codecs */  
  20.     REGISTER_ENCDEC  (AAC, aac);  
  21.     REGISTER_DECODER (AAC_LATM, aac_latm);  
  22.     ......  
  23.   
  24.     /* PCM codecs */  
  25.     REGISTER_ENCDEC  (PCM_ALAW, pcm_alaw);  
  26.     REGISTER_DECODER (PCM_BLURAY, pcm_bluray);  
  27.     ......  
  28.   
  29.     /* DPCM codecs */  
  30.     REGISTER_DECODER (INTERPLAY_DPCM, interplay_dpcm);  
  31.     REGISTER_ENCDEC  (ROQ_DPCM, roq_dpcm);  
  32.     ......  
  33.   
  34.     /* ADPCM codecs */  
  35.     REGISTER_DECODER (ADPCM_4XM, adpcm_4xm);  
  36.     REGISTER_ENCDEC  (ADPCM_ADX, adpcm_adx);  
  37.     ......  
  38.   
  39.     /* subtitles */  
  40.     REGISTER_ENCDEC  (ASS, ass);  
  41.     REGISTER_ENCDEC  (DVBSUB, dvbsub);  
  42.     ......  
  43.   
  44.     /* external libraries */  
  45.     REGISTER_DECODER (LIBCELT, libcelt);  
  46.     ......  
  47.   
  48. <span style="color:#ff6666;">    //  
  49.     // 这是我们关注的libx264编码器  
  50.     REGISTER_ENCODER (LIBX264, libx264);</span>  
  51.     ......  
  52.   
  53.     /* text */  
  54.     REGISTER_DECODER (BINTEXT, bintext);  
  55.     ......  
  56.   
  57.     /* parsers */  
  58.     REGISTER_PARSER  (AAC, aac);  
  59.     REGISTER_PARSER  (AAC_LATM, aac_latm);  
  60.     ......  
  61.   
  62.     /* bitstream filters */  
  63.     REGISTER_BSF     (AAC_ADTSTOASC, aac_adtstoasc);  
  64.     REGISTER_BSF     (CHOMP, chomp);  
  65.     ......  
  66. }</span>  
    很显然,我们关心的是REGISTER_ENCODER (LIBX264, libx264),这里是注册libx264编码器:

[cpp]  view plain  copy
  1. <span style="font-family:Courier New;">#define REGISTER_ENCODER(X,x) { \  
  2.           extern AVCodec ff_##x##_encoder; \  
  3.           if(CONFIG_##X##_ENCODER)  avcodec_register(&ff_##x##_encoder); }</span>  

将宏以参数LIBX264和libx264展开得到:

[cpp]  view plain  copy
  1. <span style="font-family:Courier New;">{  
  2.     extern AVCodec ff_libx264_encoder;  
  3.     if (CONFIG_LIBX264_ENCODER)  
  4.         avcodec_register(&ff_libx264_encoder);  
  5. }</span>  
在ffmpeg中查找ff_libx264_encoder变量:

[cpp]  view plain  copy
  1. <span style="font-family:Courier New;">AVCodec ff_libx264_encoder = {  
  2.     .name             = "libx264",  
  3.     .type             = AVMEDIA_TYPE_VIDEO,  
  4.     .id               = AV_CODEC_ID_H264,  
  5.     .priv_data_size   = sizeof(X264Context),  
  6.     <span style="color:#ff6666;">.init             = X264_init,</span>  
  7.     .encode2          = X264_frame,  
  8.     .close            = X264_close,  
  9.     .capabilities     = CODEC_CAP_DELAY | CODEC_CAP_AUTO_THREADS,  
  10.     .long_name        = NULL_IF_CONFIG_SMALL("libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10"),  
  11.     .priv_class       = &class,  
  12.     .defaults         = x264_defaults,  
  13.     .init_static_data = X264_init_static,  
  14. };</span>  
看到这个结构体中的init成员,我们可以推测这个成员注册的X264_init函数一定是对X264编码器的各项参数做初始化工作,这给我们提供了继续查找下去的线索,稍后我们来分析,这里有个条件判断CONFIG_LIBX264_ENCODER,我们在ffmpeg工程中查找,发现在它Config.mak中,这个文件是在咱们编译ffmpeg工程时由./configure根据你的选项自动生成的,还记得我们编译时用了--enable-libx264选项吗(我们要使用X264编码器,当然要指定该选项)?所以有CONFIG_LIBX264_ENCODER=yes,因此这里可以成功注册x264编码器,如果当初没有指定该选项,编码器是不会注册进去的。

    而avcodec_register则是将具体的codec注册到编解码器链表中去:

[cpp]  view plain  copy
  1. <span style="font-family:Courier New;">void avcodec_register(AVCodec *codec)  
  2. {  
  3.     AVCodec **p;  
  4.     avcodec_init();  
  5.     p = &first_avcodec;  
  6.     while (*p != NULL) p = &(*p)->next;  
  7.     *p = codec;  
  8.     codec->next = NULL;  
  9.   
  10.     if (codec->init_static_data)  
  11.         codec->init_static_data(codec);  
  12. }</span>  
这里first_avcodec是一个全局变量,作为编解码器链表的起始位置,之后注册的编解码器都加入到这个链表中去。

avcodec_find_encoder

该函数就是在编解码器链表中找出你需要的codec,如果你之前没有注册该device,将会查找失败,从代码中可以看出,它就是中first_avcodec开始查找每个节点,比较每个device的id是否与你参数给的一直,如果是,则找到了,并返回之:

[cpp]  view plain  copy
  1. <span style="font-family:Courier New;">AVCodec *avcodec_find_encoder(enum AVCodecID id)  
  2. {  
  3.     AVCodec *p, *experimental=NULL;  
  4.     p = first_avcodec;  
  5.     id= remap_deprecated_codec_id(id);  
  6.     while (p) {  
  7.         if (av_codec_is_encoder(p) && p->id == id) {  
  8.             if (p->capabilities & CODEC_CAP_EXPERIMENTAL && !experimental) {  
  9.                 experimental = p;  
  10.             } else  
  11.                 return p;  
  12.         }  
  13.         p = p->next;  
  14.     }  
  15.     return experimental;  
  16. }</span>  
至此你应该理解了为什么每次使用编码器前,我们都会先调用avcodec_register_all或者avcodec_register,你也了解到了为什么你调用了avcodec_register_all,但查找AV_CODEC_ID_H264编码器时会还是会失败(因为你编译ffmpeg时未指定--enable-libx264)。

打开编码器,avcodec_open2

这个函数主要是打开你找到的编码器,所谓打开其实是设置编码器的各项参数,要设置的参数数据则是从我么设置的AVCodecContext来获得的

[cpp]  view plain  copy
  1. <span style="font-family:Courier New;">int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)  
  2. {  
  3.     int ret = 0;  
  4.     AVDictionary *tmp = NULL;  
  5.   
  6.     if (avcodec_is_open(avctx))  
  7.         return 0;  
  8.   
  9.     if ((!codec && !avctx->codec)) {  
  10.         av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2().\n");  
  11.         return AVERROR(EINVAL);  
  12.     }  
  13.     if ((codec && avctx->codec && codec != avctx->codec)) {  
  14.         av_log(avctx, AV_LOG_ERROR, "This AVCodecContext was allocated for %s, "  
  15.                "but %s passed to avcodec_open2().\n", avctx->codec->name, codec->name);  
  16.         return AVERROR(EINVAL);  
  17.     }  
  18.     if (!codec)  
  19.         codec = avctx->codec;  
  20.   
  21.     if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE)  
  22.         return AVERROR(EINVAL);  
  23.   
  24.     if (options)  
  25.         av_dict_copy(&tmp, *options, 0);  
  26.   
  27.     /* If there is a user-supplied mutex locking routine, call it. */  
  28.     if (ff_lockmgr_cb) {  
  29.         if ((*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))  
  30.             return -1;  
  31.     }  
  32.   
  33.     entangled_thread_counter++;  
  34.     if(entangled_thread_counter != 1){  
  35.         av_log(avctx, AV_LOG_ERROR, "insufficient thread locking around avcodec_open/close()\n");  
  36.         ret = -1;  
  37.         goto end;  
  38.     }  
  39.   
  40.     avctx->internal = av_mallocz(sizeof(AVCodecInternal));  
  41.     if (!avctx->internal) {  
  42.         ret = AVERROR(ENOMEM);  
  43.         goto end;  
  44.     }  
  45.   
  46.     if (codec->priv_data_size > 0) {  
  47.       if(!avctx->priv_data){  
  48.         avctx->priv_data = av_mallocz(codec->priv_data_size);  
  49.         if (!avctx->priv_data) {  
  50.             ret = AVERROR(ENOMEM);  
  51.             goto end;  
  52.         }  
  53.         if (codec->priv_class) {  
  54.             *(const AVClass**)avctx->priv_data= codec->priv_class;  
  55.             av_opt_set_defaults(avctx->priv_data);  
  56.         }  
  57.       }  
  58.       if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0)  
  59.           goto free_and_end;  
  60.     } else {  
  61.         avctx->priv_data = NULL;  
  62.     }  
  63.     if ((ret = av_opt_set_dict(avctx, &tmp)) < 0)  
  64.         goto free_and_end;  
  65.   
  66.     if (codec->capabilities & CODEC_CAP_EXPERIMENTAL)  
  67.         if (avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {  
  68.             av_log(avctx, AV_LOG_ERROR, "Codec is experimental but experimental codecs are not enabled, try -strict -2\n");  
  69.             ret = -1;  
  70.             goto free_and_end;  
  71.         }  
  72.   
  73.     //We only call avcodec_set_dimensions() for non h264 codecs so as not to overwrite previously setup dimensions  
  74.     if(!( avctx->coded_width && avctx->coded_height && avctx->width && avctx->height && avctx->codec_id == AV_CODEC_ID_H264)){  
  75.     if(avctx->coded_width && avctx->coded_height)  
  76.         avcodec_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);  
  77.     else if(avctx->width && avctx->height)  
  78.         avcodec_set_dimensions(avctx, avctx->width, avctx->height);  
  79.     }  
  80.   
  81.     if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)  
  82.         && (  av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx) < 0  
  83.            || av_image_check_size(avctx->width,       avctx->height,       0, avctx) < 0)) {  
  84.         av_log(avctx, AV_LOG_WARNING, "ignoring invalid width/height values\n");  
  85.         avcodec_set_dimensions(avctx, 0, 0);  
  86.     }  
  87.   
  88.     /* if the decoder init function was already called previously, 
  89.        free the already allocated subtitle_header before overwriting it */  
  90.     if (av_codec_is_decoder(codec))  
  91.         av_freep(&avctx->subtitle_header);  
  92.   
  93. #define SANE_NB_CHANNELS 128U  
  94.     if (avctx->channels > SANE_NB_CHANNELS) {  
  95.         ret = AVERROR(EINVAL);  
  96.         goto free_and_end;  
  97.     }  
  98.   
  99.     avctx->codec = codec;  
  100.     if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&  
  101.         avctx->codec_id == AV_CODEC_ID_NONE) {  
  102.         avctx->codec_type = codec->type;  
  103.         avctx->codec_id   = codec->id;  
  104.     }  
  105.     if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type  
  106.                            && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {  
  107.         av_log(avctx, AV_LOG_ERROR, "codec type or id mismatches\n");  
  108.         ret = AVERROR(EINVAL);  
  109.         goto free_and_end;  
  110.     }  
  111.     avctx->frame_number = 0;  
  112.     avctx->codec_descriptor = avcodec_descriptor_get(avctx->codec_id);  
  113.   
  114.     if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&  
  115.         (!avctx->time_base.num || !avctx->time_base.den)) {  
  116.         avctx->time_base.num = 1;  
  117.         avctx->time_base.den = avctx->sample_rate;  
  118.     }  
  119.   
  120.     if (!HAVE_THREADS)  
  121.         av_log(avctx, AV_LOG_WARNING, "Warning: not compiled with thread support, using thread emulation\n");  
  122.   
  123.     if (HAVE_THREADS) {  
  124.         entangled_thread_counter--; //we will instanciate a few encoders thus kick the counter to prevent false detection of a problem  
  125.         ret = ff_frame_thread_encoder_init(avctx, options ? *options : NULL);  
  126.         entangled_thread_counter++;  
  127.         if (ret < 0)  
  128.             goto free_and_end;  
  129.     }  
  130.   
  131.     if (HAVE_THREADS && !avctx->thread_opaque  
  132.         && !(avctx->internal->frame_thread_encoder && (avctx->active_thread_type&FF_THREAD_FRAME))) {  
  133.         ret = ff_thread_init(avctx);  
  134.         if (ret < 0) {  
  135.             goto free_and_end;  
  136.         }  
  137.     }  
  138.     if (!HAVE_THREADS && !(codec->capabilities & CODEC_CAP_AUTO_THREADS))  
  139.         avctx->thread_count = 1;  
  140.   
  141.     if (avctx->codec->max_lowres < avctx->lowres || avctx->lowres < 0) {  
  142.         av_log(avctx, AV_LOG_ERROR, "The maximum value for lowres supported by the decoder is %d\n",  
  143.                avctx->codec->max_lowres);  
  144.         ret = AVERROR(EINVAL);  
  145.         goto free_and_end;  
  146.     }  
  147.   
  148.     if (av_codec_is_encoder(avctx->codec)) {  
  149.         int i;  
  150.         if (avctx->codec->sample_fmts) {  
  151.             for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++)  
  152.                 if (avctx->sample_fmt == avctx->codec->sample_fmts[i])  
  153.                     break;  
  154.             if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {  
  155.                 av_log(avctx, AV_LOG_ERROR, "Specified sample_fmt is not supported.\n");  
  156.                 ret = AVERROR(EINVAL);  
  157.                 goto free_and_end;  
  158.             }  
  159.         }  
  160.         if (avctx->codec->pix_fmts) {  
  161.             for (i = 0; avctx->codec->pix_fmts[i] != PIX_FMT_NONE; i++)  
  162.                 if (avctx->pix_fmt == avctx->codec->pix_fmts[i])  
  163.                     break;  
  164.             if (avctx->codec->pix_fmts[i] == PIX_FMT_NONE  
  165.                 && !((avctx->codec_id == AV_CODEC_ID_MJPEG || avctx->codec_id == AV_CODEC_ID_LJPEG)  
  166.                      && avctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL)) {  
  167.                 av_log(avctx, AV_LOG_ERROR, "Specified pix_fmt is not supported\n");  
  168.                 ret = AVERROR(EINVAL);  
  169.                 goto free_and_end;  
  170.             }  
  171.         }  
  172.         if (avctx->codec->supported_samplerates) {  
  173.             for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++)  
  174.                 if (avctx->sample_rate == avctx->codec->supported_samplerates[i])  
  175.                     break;  
  176.             if (avctx->codec->supported_samplerates[i] == 0) {  
  177.                 av_log(avctx, AV_LOG_ERROR, "Specified sample_rate is not supported\n");  
  178.                 ret = AVERROR(EINVAL);  
  179.                 goto free_and_end;  
  180.             }  
  181.         }  
  182.         if (avctx->codec->channel_layouts) {  
  183.             if (!avctx->channel_layout) {  
  184.                 av_log(avctx, AV_LOG_WARNING, "channel_layout not specified\n");  
  185.             } else {  
  186.                 for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)  
  187.                     if (avctx->channel_layout == avctx->codec->channel_layouts[i])  
  188.                         break;  
  189.                 if (avctx->codec->channel_layouts[i] == 0) {  
  190.                     av_log(avctx, AV_LOG_ERROR, "Specified channel_layout is not supported\n");  
  191.                     ret = AVERROR(EINVAL);  
  192.                     goto free_and_end;  
  193.                 }  
  194.             }  
  195.         }  
  196.         if (avctx->channel_layout && avctx->channels) {  
  197.             if (av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels) {  
  198.                 av_log(avctx, AV_LOG_ERROR, "channel layout does not match number of channels\n");  
  199.                 ret = AVERROR(EINVAL);  
  200.                 goto free_and_end;  
  201.             }  
  202.         } else if (avctx->channel_layout) {  
  203.             avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout);  
  204.         }  
  205.     }  
  206.   
  207.     avctx->pts_correction_num_faulty_pts =  
  208.     avctx->pts_correction_num_faulty_dts = 0;  
  209.     avctx->pts_correction_last_pts =  
  210.     avctx->pts_correction_last_dts = INT64_MIN;  
  211.   
  212. <span style="color:#ff6666;">      
  213.     // 这里会调用编码器的中指定的初始化函数init, 对于x264编码器,也就是调用ff_libx264_encoder中指定的X264_init  
  214.     if(avctx->codec->init && (!(avctx->active_thread_type&FF_THREAD_FRAME) || avctx->internal->frame_thread_encoder)){  
  215.         ret = avctx->codec->init(avctx);  
  216.         if (ret < 0) {  
  217.             goto free_and_end;  
  218.         }  
  219.     }  
  220.     </span>  
  221.   
  222.     ret=0;  
  223.   
  224.     if (av_codec_is_decoder(avctx->codec)) {  
  225.         if (!avctx->bit_rate)  
  226.             avctx->bit_rate = get_bit_rate(avctx);  
  227.         /* validate channel layout from the decoder */  
  228.         if (avctx->channel_layout &&  
  229.             av_get_channel_layout_nb_channels(avctx->channel_layout) != avctx->channels) {  
  230.             av_log(avctx, AV_LOG_WARNING, "channel layout does not match number of channels\n");  
  231.             avctx->channel_layout = 0;  
  232.         }  
  233.     }  
  234. end:  
  235.     entangled_thread_counter--;  
  236.   
  237.     /* Release any user-supplied mutex. */  
  238.     if (ff_lockmgr_cb) {  
  239.         (*ff_lockmgr_cb)(&codec_mutex, AV_LOCK_RELEASE);  
  240.     }  
  241.     if (options) {  
  242.         av_dict_free(options);  
  243.         *options = tmp;  
  244.     }  
  245.   
  246.     return ret;  
  247. free_and_end:  
  248.     av_dict_free(&tmp);  
  249.     av_freep(&avctx->priv_data);  
  250.     av_freep(&avctx->internal);  
  251.     avctx->codec= NULL;  
  252.     goto end;  
  253. }</span>  
看看我们在代码中标注的那几行代码:

[cpp]  view plain  copy
  1. <span style="font-family:Courier New;">if(avctx->codec->init && (!(avctx->active_thread_type&FF_THREAD_FRAME) || avctx->internal->frame_thread_encoder)){  
  2.         ret = avctx->codec->init(avctx);  
  3.         if (ret < 0) {  
  4.             goto free_and_end;  
  5.         }  
  6.     }</span>  
这里如果codec的init成员指定了对codec的初始化函数时,它会调用该初始化函数,通过前面的分析我们知道,X264编码器的初始化函数指定为X264_init,该函数的参数即是我们给定的AVCodecContext,下面我们来看看X264_init做了些什么。

X264编码器的初始化,X264_init

首先列出源代码:

[cpp]  view plain  copy
  1. <span style="font-family:Courier New;">static av_cold int X264_init(AVCodecContext *avctx)  
  2. {  
  3.     X264Context *x4 = avctx->priv_data;  
  4.     int sw,sh;  
  5.   
  6.     x264_param_default(&x4->params);  
  7.   
  8.     x4->params.b_deblocking_filter         = avctx->flags & CODEC_FLAG_LOOP_FILTER;  
  9.   
  10.     x4->params.rc.f_ip_factor             = 1 / fabs(avctx->i_quant_factor);  
  11.     x4->params.rc.f_pb_factor             = avctx->b_quant_factor;  
  12.     x4->params.analyse.i_chroma_qp_offset = avctx->chromaoffset;  
  13.     if (x4->preset || x4->tune)  
  14.   
  15. <span style="color:#ff6666;">          
  16.         // 在这里面会设置很多关键的参数,这个函数式X264提供的,接下来我们要到X264中查看其源代码  
  17.         if (x264_param_default_preset(&x4->params, x4->preset, x4->tune) < 0) {  
  18.             int i;  
  19.             av_log(avctx, AV_LOG_ERROR, "Error setting preset/tune %s/%s.\n", x4->preset, x4->tune);  
  20.             av_log(avctx, AV_LOG_INFO, "Possible presets:");  
  21.             for (i = 0; x264_preset_names[i]; i++)  
  22.                 av_log(avctx, AV_LOG_INFO, " %s", x264_preset_names[i]);  
  23.             av_log(avctx, AV_LOG_INFO, "\n");  
  24.             av_log(avctx, AV_LOG_INFO, "Possible tunes:");  
  25.             for (i = 0; x264_tune_names[i]; i++)  
  26.                 av_log(avctx, AV_LOG_INFO, " %s", x264_tune_names[i]);  
  27.             av_log(avctx, AV_LOG_INFO, "\n");  
  28.             return AVERROR(EINVAL);  
  29.         }  
  30.         /</span>  
  31.   
  32.     if (avctx->level > 0)  
  33.         x4->params.i_level_idc = avctx->level;  
  34.   
  35.     x4->params.pf_log               = X264_log;  
  36.     x4->params.p_log_private        = avctx;  
  37.     x4->params.i_log_level          = X264_LOG_DEBUG;  
  38.     x4->params.i_csp                = convert_pix_fmt(avctx->pix_fmt);  
  39.   
  40.     OPT_STR("weightp", x4->wpredp);  
  41.   
  42.     if (avctx->bit_rate) {  
  43.         x4->params.rc.i_bitrate   = avctx->bit_rate / 1000;  
  44.         x4->params.rc.i_rc_method = X264_RC_ABR;  
  45.     }  
  46.     x4->params.rc.i_vbv_buffer_size = avctx->rc_buffer_size / 1000;  
  47.     x4->params.rc.i_vbv_max_bitrate = avctx->rc_max_rate    / 1000;  
  48.     x4->params.rc.b_stat_write      = avctx->flags & CODEC_FLAG_PASS1;  
  49.     if (avctx->flags & CODEC_FLAG_PASS2) {  
  50.         x4->params.rc.b_stat_read = 1;  
  51.     } else {  
  52.         if (x4->crf >= 0) {  
  53.             x4->params.rc.i_rc_method   = X264_RC_CRF;  
  54.             x4->params.rc.f_rf_constant = x4->crf;  
  55.         } else if (x4->cqp >= 0) {  
  56.             x4->params.rc.i_rc_method   = X264_RC_CQP;  
  57.             x4->params.rc.i_qp_constant = x4->cqp;  
  58.         }  
  59.   
  60.         if (x4->crf_max >= 0)  
  61.             x4->params.rc.f_rf_constant_max = x4->crf_max;  
  62.     }  
  63.   
  64.     if (avctx->rc_buffer_size && avctx->rc_initial_buffer_occupancy &&  
  65.         (avctx->rc_initial_buffer_occupancy <= avctx->rc_buffer_size)) {  
  66.         x4->params.rc.f_vbv_buffer_init =  
  67.             (float)avctx->rc_initial_buffer_occupancy / avctx->rc_buffer_size;  
  68.     }  
  69.   
  70.     OPT_STR("level", x4->level);  
  71.   
  72.     if(x4->x264opts){  
  73.         const char *p= x4->x264opts;  
  74.         while(p){  
  75.             char param[256]={0}, val[256]={0};  
  76.             if(sscanf(p, "%255[^:=]=%255[^:]", param, val) == 1){  
  77.                 OPT_STR(param, "1");  
  78.             }else  
  79.                 OPT_STR(param, val);  
  80.             p= strchr(p, ':');  
  81.             p+=!!p;  
  82.         }  
  83.     }  
  84.   
  85.     if (avctx->me_method == ME_EPZS)  
  86.         x4->params.analyse.i_me_method = X264_ME_DIA;  
  87.     else if (avctx->me_method == ME_HEX)  
  88.         x4->params.analyse.i_me_method = X264_ME_HEX;  
  89.     else if (avctx->me_method == ME_UMH)  
  90.         x4->params.analyse.i_me_method = X264_ME_UMH;  
  91.     else if (avctx->me_method == ME_FULL)  
  92.         x4->params.analyse.i_me_method = X264_ME_ESA;  
  93.     else if (avctx->me_method == ME_TESA)  
  94.         x4->params.analyse.i_me_method = X264_ME_TESA;  
  95.   
  96.     if (avctx->gop_size >= 0)  
  97.         x4->params.i_keyint_max         = avctx->gop_size;  
  98.     if (avctx->max_b_frames >= 0)  
  99.         x4->params.i_bframe             = avctx->max_b_frames;  
  100.     if (avctx->scenechange_threshold >= 0)  
  101.         x4->params.i_scenecut_threshold = avctx->scenechange_threshold;  
  102.     if (avctx->qmin >= 0)  
  103.         x4->params.rc.i_qp_min          = avctx->qmin;  
  104.     if (avctx->qmax >= 0)  
  105.         x4->params.rc.i_qp_max          = avctx->qmax;  
  106.     if (avctx->max_qdiff >= 0)  
  107.         x4->params.rc.i_qp_step         = avctx->max_qdiff;  
  108.     if (avctx->qblur >= 0)  
  109.         x4->params.rc.f_qblur           = avctx->qblur;     /* temporally blur quants */  
  110.     if (avctx->qcompress >= 0)  
  111.         x4->params.rc.f_qcompress       = avctx->qcompress; /* 0.0 => cbr, 1.0 => constant qp */  
  112.     if (avctx->refs >= 0)  
  113.         x4->params.i_frame_reference    = avctx->refs;  
  114.     if (avctx->trellis >= 0)  
  115.         x4->params.analyse.i_trellis    = avctx->trellis;  
  116.     if (avctx->me_range >= 0)  
  117.         x4->params.analyse.i_me_range   = avctx->me_range;  
  118.     if (avctx->noise_reduction >= 0)  
  119.         x4->params.analyse.i_noise_reduction = avctx->noise_reduction;  
  120.     if (avctx->me_subpel_quality >= 0)  
  121.         x4->params.analyse.i_subpel_refine   = avctx->me_subpel_quality;  
  122.     if (avctx->b_frame_strategy >= 0)  
  123.         x4->params.i_bframe_adaptive = avctx->b_frame_strategy;  
  124.     if (avctx->keyint_min >= 0)  
  125.         x4->params.i_keyint_min = avctx->keyint_min;  
  126.     if (avctx->coder_type >= 0)  
  127.         x4->params.b_cabac = avctx->coder_type == FF_CODER_TYPE_AC;  
  128.     if (avctx->me_cmp >= 0)  
  129.         x4->params.analyse.b_chroma_me = avctx->me_cmp & FF_CMP_CHROMA;  
  130.   
  131.     if (x4->aq_mode >= 0)  
  132.         x4->params.rc.i_aq_mode = x4->aq_mode;  
  133.     if (x4->aq_strength >= 0)  
  134.         x4->params.rc.f_aq_strength = x4->aq_strength;  
  135.     PARSE_X264_OPT("psy-rd", psy_rd);  
  136.     PARSE_X264_OPT("deblock", deblock);  
  137.     PARSE_X264_OPT("partitions", partitions);  
  138.     PARSE_X264_OPT("stats", stats);  
  139.     if (x4->psy >= 0)  
  140.         x4->params.analyse.b_psy  = x4->psy;  
  141.     if (x4->rc_lookahead >= 0)  
  142.         x4->params.rc.i_lookahead = x4->rc_lookahead;  
  143.     if (x4->weightp >= 0)  
  144.         x4->params.analyse.i_weighted_pred = x4->weightp;  
  145.     if (x4->weightb >= 0)  
  146.         x4->params.analyse.b_weighted_bipred = x4->weightb;  
  147.     if (x4->cplxblur >= 0)  
  148.         x4->params.rc.f_complexity_blur = x4->cplxblur;  
  149.   
  150.     if (x4->ssim >= 0)  
  151.         x4->params.analyse.b_ssim = x4->ssim;  
  152.     if (x4->intra_refresh >= 0)  
  153.         x4->params.b_intra_refresh = x4->intra_refresh;  
  154.     if (x4->b_bias != INT_MIN)  
  155.         x4->params.i_bframe_bias              = x4->b_bias;  
  156.     if (x4->b_pyramid >= 0)  
  157.         x4->params.i_bframe_pyramid = x4->b_pyramid;  
  158.     if (x4->mixed_refs >= 0)  
  159.         x4->params.analyse.b_mixed_references = x4->mixed_refs;  
  160.     if (x4->dct8x8 >= 0)  
  161.         x4->params.analyse.b_transform_8x8    = x4->dct8x8;  
  162.     if (x4->fast_pskip >= 0)  
  163.         x4->params.analyse.b_fast_pskip       = x4->fast_pskip;  
  164.     if (x4->aud >= 0)  
  165.         x4->params.b_aud                      = x4->aud;  
  166.     if (x4->mbtree >= 0)  
  167.         x4->params.rc.b_mb_tree               = x4->mbtree;  
  168.     if (x4->direct_pred >= 0)  
  169.         x4->params.analyse.i_direct_mv_pred   = x4->direct_pred;  
  170.   
  171.     if (x4->slice_max_size >= 0)  
  172.         x4->params.i_slice_max_size =  x4->slice_max_size;  
  173.   
  174.     if (x4->fastfirstpass)  
  175.         x264_param_apply_fastfirstpass(&x4->params);  
  176.   
  177.     if (x4->profile)  
  178.         if (x264_param_apply_profile(&x4->params, x4->profile) < 0) {  
  179.             int i;  
  180.             av_log(avctx, AV_LOG_ERROR, "Error setting profile %s.\n", x4->profile);  
  181.             av_log(avctx, AV_LOG_INFO, "Possible profiles:");  
  182.             for (i = 0; x264_profile_names[i]; i++)  
  183.                 av_log(avctx, AV_LOG_INFO, " %s", x264_profile_names[i]);  
  184.             av_log(avctx, AV_LOG_INFO, "\n");  
  185.             return AVERROR(EINVAL);  
  186.         }  
  187.   
  188.     x4->params.i_width          = avctx->width;  
  189.     x4->params.i_height         = avctx->height;  
  190.     av_reduce(&sw, &sh, avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den, 4096);  
  191.     x4->params.vui.i_sar_width  = sw;  
  192.     x4->params.vui.i_sar_height = sh;  
  193.     x4->params.i_fps_num = x4->params.i_timebase_den = avctx->time_base.den;  
  194.     x4->params.i_fps_den = x4->params.i_timebase_num = avctx->time_base.num;  
  195.   
  196.     x4->params.analyse.b_psnr = avctx->flags & CODEC_FLAG_PSNR;  
  197.   
  198.     x4->params.i_threads      = avctx->thread_count;  
  199.     if (avctx->thread_type)  
  200.         x4->params.b_sliced_threads = avctx->thread_type == FF_THREAD_SLICE;  
  201.   
  202.     x4->params.b_interlaced   = avctx->flags & CODEC_FLAG_INTERLACED_DCT;  
  203.   
  204. //    x4->params.b_open_gop     = !(avctx->flags & CODEC_FLAG_CLOSED_GOP);  
  205.   
  206.     x4->params.i_slice_count  = avctx->slices;  
  207.   
  208.     x4->params.vui.b_fullrange = avctx->pix_fmt == PIX_FMT_YUVJ420P;  
  209.   
  210.     if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER)  
  211.         x4->params.b_repeat_headers = 0;  
  212.   
  213.     // update AVCodecContext with x264 parameters  
  214.     avctx->has_b_frames = x4->params.i_bframe ?  
  215.         x4->params.i_bframe_pyramid ? 2 : 1 : 0;  
  216.     if (avctx->max_b_frames < 0)  
  217.         avctx->max_b_frames = 0;  
  218.   
  219.     avctx->bit_rate = x4->params.rc.i_bitrate*1000;  
  220.     x4->enc = x264_encoder_open(&x4->params);  
  221.     if (!x4->enc)  
  222.         return -1;  
  223.   
  224.     avctx->coded_frame = &x4->out_pic;  
  225.   
  226.     if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) {  
  227.         x264_nal_t *nal;  
  228.         uint8_t *p;  
  229.         int nnal, s, i;  
  230.   
  231.         s = x264_encoder_headers(x4->enc, &nal, &nnal);  
  232.         avctx->extradata = p = av_malloc(s);  
  233.   
  234.         for (i = 0; i < nnal; i++) {  
  235.             /* Don't put the SEI in extradata. */  
  236.             if (nal[i].i_type == NAL_SEI) {  
  237.                 av_log(avctx, AV_LOG_INFO, "%s\n", nal[i].p_payload+25);  
  238.                 x4->sei_size = nal[i].i_payload;  
  239.                 x4->sei      = av_malloc(x4->sei_size);  
  240.                 memcpy(x4->sei, nal[i].p_payload, nal[i].i_payload);  
  241.                 continue;  
  242.             }  
  243.             memcpy(p, nal[i].p_payload, nal[i].i_payload);  
  244.             p += nal[i].i_payload;  
  245.         }  
  246.         avctx->extradata_size = p - avctx->extradata;  
  247.     }  
  248.   
  249.     return 0;  
  250. }  
  251. </span>  
看看我们做出标记的那几行代码,这里它调用了x264_param_default_preset(&x4->params, x4->preset, x4->tune),所以我们接下来当然是看看这个函数了。

对编码器参数的设置,x264_param_default_preset

    这个函数的定义并不在ffmpeg中,因为这是X264提供给外界对编码器做设置API函数,于是我们在X264项目中查找该函数,它定义在Common.c中,代码如下:

[cpp]  view plain  copy
  1. <span style="font-family:Courier New;">int x264_param_default_preset( x264_param_t *param, const char *preset, const char *tune )  
  2. {  
  3.     x264_param_default( param );  
  4.   
  5.     if( preset && <span style="color:#ff6666;">x264_param_apply_preset( param, preset )</span> < 0 )  
  6.         return -1;  
  7.     if( tune && <span style="color:#ff6666;">x264_param_apply_tune( param, tune )</span> < 0 )  
  8.         return -1;  
  9.     return 0;  
  10. }</span>  
它首先调用下x264_param_default设置默认参数,这在用户没有指定额外设置时,设置就是使用该函数默认参数,但如果用户指定了preset和(或者)tune参数时,它就会进行额外参数的设置。

    首先看一下应用模式的设置:

[cpp]  view plain  copy
  1. <span style="font-family:Courier New;">static int x264_param_apply_preset( x264_param_t *param, const char *preset )  
  2. {  
  3.     char *end;  
  4.     int i = strtol( preset, &end, 10 );  
  5.     if( *end == 0 && i >= 0 && i < sizeof(x264_preset_names)/sizeof(*x264_preset_names)-1 )  
  6.         preset = x264_preset_names[i];  
  7.   
  8.     if( !strcasecmp( preset, "ultrafast" ) )  
  9.     {  
  10.         param->i_frame_reference = 1;  
  11.         param->i_scenecut_threshold = 0;  
  12.         param->b_deblocking_filter = 0;  
  13.         param->b_cabac = 0;  
  14.         param->i_bframe = 0;  
  15.         param->analyse.intra = 0;  
  16.         param->analyse.inter = 0;  
  17.         param->analyse.b_transform_8x8 = 0;  
  18.         param->analyse.i_me_method = X264_ME_DIA;  
  19.         param->analyse.i_subpel_refine = 0;  
  20.         param->rc.i_aq_mode = 0;  
  21.         param->analyse.b_mixed_references = 0;  
  22.         param->analyse.i_trellis = 0;  
  23.         param->i_bframe_adaptive = X264_B_ADAPT_NONE;  
  24.         param->rc.b_mb_tree = 0;  
  25.         param->analyse.i_weighted_pred = X264_WEIGHTP_NONE;  
  26.         param->analyse.b_weighted_bipred = 0;  
  27.         param->rc.i_lookahead = 0;  
  28.     }  
  29.     else if( !strcasecmp( preset, "superfast" ) )  
  30.     {  
  31.         param->analyse.inter = X264_ANALYSE_I8x8|X264_ANALYSE_I4x4;  
  32.         param->analyse.i_me_method = X264_ME_DIA;  
  33.         param->analyse.i_subpel_refine = 1;  
  34.         param->i_frame_reference = 1;  
  35.         param->analyse.b_mixed_references = 0;  
  36.         param->analyse.i_trellis = 0;  
  37.         param->rc.b_mb_tree = 0;  
  38.         param->analyse.i_weighted_pred = X264_WEIGHTP_SIMPLE;  
  39.         param->rc.i_lookahead = 0;  
  40.     }  
  41.     else if( !strcasecmp( preset, "veryfast" ) )  
  42.     {  
  43.         param->analyse.i_me_method = X264_ME_HEX;  
  44.         param->analyse.i_subpel_refine = 2;  
  45.         param->i_frame_reference = 1;  
  46.         param->analyse.b_mixed_references = 0;  
  47.         param->analyse.i_trellis = 0;  
  48.         param->analyse.i_weighted_pred = X264_WEIGHTP_SIMPLE;  
  49.         param->rc.i_lookahead = 10;  
  50.     }  
  51.     else if( !strcasecmp( preset, "faster" ) )  
  52.     {  
  53.         param->analyse.b_mixed_references = 0;  
  54.         param->i_frame_reference = 2;  
  55.         param->analyse.i_subpel_refine = 4;  
  56.         param->analyse.i_weighted_pred = X264_WEIGHTP_SIMPLE;  
  57.         param->rc.i_lookahead = 20;  
  58.     }  
  59.     else if( !strcasecmp( preset, "fast" ) )  
  60.     {  
  61.         param->i_frame_reference = 2;  
  62.         param->analyse.i_subpel_refine = 6;  
  63.         param->analyse.i_weighted_pred = X264_WEIGHTP_SIMPLE;  
  64.         param->rc.i_lookahead = 30;  
  65.     }  
  66.     else if( !strcasecmp( preset, "medium" ) )  
  67.     {  
  68.         /* Default is medium */  
  69.     }  
  70.     else if( !strcasecmp( preset, "slow" ) )  
  71.     {  
  72.         param->analyse.i_me_method = X264_ME_UMH;  
  73.         param->analyse.i_subpel_refine = 8;  
  74.         param->i_frame_reference = 5;  
  75.         param->i_bframe_adaptive = X264_B_ADAPT_TRELLIS;  
  76.         param->analyse.i_direct_mv_pred = X264_DIRECT_PRED_AUTO;  
  77.         param->rc.i_lookahead = 50;  
  78.     }  
  79.     else if( !strcasecmp( preset, "slower" ) )  
  80.     {  
  81.         param->analyse.i_me_method = X264_ME_UMH;  
  82.         param->analyse.i_subpel_refine = 9;  
  83.         param->i_frame_reference = 8;  
  84.         param->i_bframe_adaptive = X264_B_ADAPT_TRELLIS;  
  85.         param->analyse.i_direct_mv_pred = X264_DIRECT_PRED_AUTO;  
  86.         param->analyse.inter |= X264_ANALYSE_PSUB8x8;  
  87.         param->analyse.i_trellis = 2;  
  88.         param->rc.i_lookahead = 60;  
  89.     }  
  90.     else if( !strcasecmp( preset, "veryslow" ) )  
  91.     {  
  92.         param->analyse.i_me_method = X264_ME_UMH;  
  93.         param->analyse.i_subpel_refine = 10;  
  94.         param->analyse.i_me_range = 24;  
  95.         param->i_frame_reference = 16;  
  96.         param->i_bframe_adaptive = X264_B_ADAPT_TRELLIS;  
  97.         param->analyse.i_direct_mv_pred = X264_DIRECT_PRED_AUTO;  
  98.         param->analyse.inter |= X264_ANALYSE_PSUB8x8;  
  99.         param->analyse.i_trellis = 2;  
  100.         param->i_bframe = 8;  
  101.         param->rc.i_lookahead = 60;  
  102.     }  
  103.     else if( !strcasecmp( preset, "placebo" ) )  
  104.     {  
  105.         param->analyse.i_me_method = X264_ME_TESA;  
  106.         param->analyse.i_subpel_refine = 11;  
  107.         param->analyse.i_me_range = 24;  
  108.         param->i_frame_reference = 16;  
  109.         param->i_bframe_adaptive = X264_B_ADAPT_TRELLIS;  
  110.         param->analyse.i_direct_mv_pred = X264_DIRECT_PRED_AUTO;  
  111.         param->analyse.inter |= X264_ANALYSE_PSUB8x8;  
  112.         param->analyse.b_fast_pskip = 0;  
  113.         param->analyse.i_trellis = 2;  
  114.         param->i_bframe = 16;  
  115.         param->rc.i_lookahead = 60;  
  116.     }  
  117.     else  
  118.     {  
  119.         x264_log( NULL, X264_LOG_ERROR, "invalid preset '%s'\n", preset );  
  120.         return -1;  
  121.     }  
  122.     return 0;  
  123. }</span>  
这里定义了几种模式供用户选择,经过测试,这些模式是会影响到编码的延迟时间的,越快的模式,其延迟越小,对于"ultralfast"模式,我们发现延迟帧减少了许多,同时发现越快的模式相对于其他模式会有些花屏,但此时我发现所有模式都没有使得延迟为0的情况(此时我是直接修改源代码来固定设置为特定模式的,后面我们会讲到如何通过ffmpeg中的API来设置),于是我将希望寄托于下面的x264_param_apply_tune,我感觉这可能是我最后的救命稻草了!下面我们来看一下这个函数的源代码:

[cpp]  view plain  copy
  1. <span style="font-family:Courier New;">static int x264_param_apply_tune( x264_param_t *param, const char *tune )  
  2. {  
  3.     char *tmp = x264_malloc( strlen( tune ) + 1 );  
  4.     if( !tmp )  
  5.         return -1;  
  6.     tmp = strcpy( tmp, tune );  
  7.     char *s = strtok( tmp, ",./-+" );  
  8.     int psy_tuning_used = 0;  
  9.     while( s )  
  10.     {  
  11.         if( !strncasecmp( s, "film", 4 ) )  
  12.         {  
  13.             if( psy_tuning_used++ ) goto psy_failure;  
  14.             param->i_deblocking_filter_alphac0 = -1;  
  15.             param->i_deblocking_filter_beta = -1;  
  16.             param->analyse.f_psy_trellis = 0.15;  
  17.         }  
  18.         else if( !strncasecmp( s, "animation", 9 ) )  
  19.         {  
  20.             if( psy_tuning_used++ ) goto psy_failure;  
  21.             param->i_frame_reference = param->i_frame_reference > 1 ? param->i_frame_reference*2 : 1;  
  22.             param->i_deblocking_filter_alphac0 = 1;  
  23.             param->i_deblocking_filter_beta = 1;  
  24.             param->analyse.f_psy_rd = 0.4;  
  25.             param->rc.f_aq_strength = 0.6;  
  26.             param->i_bframe += 2;  
  27.         }  
  28.         else if( !strncasecmp( s, "grain", 5 ) )  
  29.         {  
  30.             if( psy_tuning_used++ ) goto psy_failure;  
  31.             param->i_deblocking_filter_alphac0 = -2;  
  32.             param->i_deblocking_filter_beta = -2;  
  33.             param->analyse.f_psy_trellis = 0.25;  
  34.             param->analyse.b_dct_decimate = 0;  
  35.             param->rc.f_pb_factor = 1.1;  
  36.             param->rc.f_ip_factor = 1.1;  
  37.             param->rc.f_aq_strength = 0.5;  
  38.             param->analyse.i_luma_deadzone[0] = 6;  
  39.             param->analyse.i_luma_deadzone[1] = 6;  
  40.             param->rc.f_qcompress = 0.8;  
  41.         }  
  42.         else if( !strncasecmp( s, "stillimage", 5 ) )  
  43.         {  
  44.             if( psy_tuning_used++ ) goto psy_failure;  
  45.             param->i_deblocking_filter_alphac0 = -3;  
  46.             param->i_deblocking_filter_beta = -3;  
  47.             param->analyse.f_psy_rd = 2.0;  
  48.             param->analyse.f_psy_trellis = 0.7;  
  49.             param->rc.f_aq_strength = 1.2;  
  50.         }  
  51.         else if( !strncasecmp( s, "psnr", 4 ) )  
  52.         {  
  53.             if( psy_tuning_used++ ) goto psy_failure;  
  54.             param->rc.i_aq_mode = X264_AQ_NONE;  
  55.             param->analyse.b_psy = 0;  
  56.         }  
  57.         else if( !strncasecmp( s, "ssim", 4 ) )  
  58.         {  
  59.             if( psy_tuning_used++ ) goto psy_failure;  
  60.             param->rc.i_aq_mode = X264_AQ_AUTOVARIANCE;  
  61.             param->analyse.b_psy = 0;  
  62.         }  
  63.         else if( !strncasecmp( s, "fastdecode", 10 ) )  
  64.         {  
  65.             param->b_deblocking_filter = 0;  
  66.             param->b_cabac = 0;  
  67.             param->analyse.b_weighted_bipred = 0;  
  68.             param->analyse.i_weighted_pred = X264_WEIGHTP_NONE;  
  69.         }  
  70.         <span style="color:#ff6666;">else if( !strncasecmp( s, "zerolatency", 11 ) )  
  71.         {  
  72.             param->rc.i_lookahead = 0;  
  73.             param->i_sync_lookahead = 0;  
  74.             param->i_bframe = 0;  
  75.             param->b_sliced_threads = 1;  
  76.             param->b_vfr_input = 0;  
  77.             param->rc.b_mb_tree = 0;  
  78.         }</span>  
  79.         else if( !strncasecmp( s, "touhou", 6 ) )  
  80.         {  
  81.             if( psy_tuning_used++ ) goto psy_failure;  
  82.             param->i_frame_reference = param->i_frame_reference > 1 ? param->i_frame_reference*2 : 1;  
  83.             param->i_deblocking_filter_alphac0 = -1;  
  84.             param->i_deblocking_filter_beta = -1;  
  85.             param->analyse.f_psy_trellis = 0.2;  
  86.             param->rc.f_aq_strength = 1.3;  
  87.             if( param->analyse.inter & X264_ANALYSE_PSUB16x16 )  
  88.                 param->analyse.inter |= X264_ANALYSE_PSUB8x8;  
  89.         }  
  90.         else  
  91.         {  
  92.             x264_log( NULL, X264_LOG_ERROR, "invalid tune '%s'\n", s );  
  93.             x264_free( tmp );  
  94.             return -1;  
  95.         }  
  96.         if( 0 )  
  97.         {  
  98.     psy_failure:  
  99.             x264_log( NULL, X264_LOG_WARNING, "only 1 psy tuning can be used: ignoring tune %s\n", s );  
  100.         }  
  101.         s = strtok( NULL, ",./-+" );  
  102.     }  
  103.     x264_free( tmp );  
  104.     return 0;  
  105. }</span>  
我们在代码中也看到了有几种模式供选择,每种模式都是对一些参数的具体设置,当然这些参数的意义我也不是很清楚,有待后面继续的研究,但我却惊喜地发现了一个“zerolatency”模式,这不就是我要找的实时编码模式吗,至少从字面上来讲是!于是修改源代码写死为“zerolatency”模式,编译、运行,我的天哪,终于找到了!

    另外,我了解到,其实在工程编译出的可执行文件运行时也是可以指定这些运行参数的,这更加证实了我的想法。于是我得出了一个结论:

x264_param_apply_preset和x264_param_apply_tune的参数决定了编码器的全部运作方式(当然包括是否编码延迟,以及延迟多长)!

如何不修改ffmpeg或者x264工程源代码来达到实时编码

    知道了影响编码延迟的原因后,我们又要上溯到ffmpeg中的X264_init代码中去了,看看该函数是如何指定x264_param_default_preset函数的参数的,为了便于讲解,我们再次列出部分代码:

[cpp]  view plain  copy
  1. <span style="font-family:Courier New;">static av_cold int X264_init(AVCodecContext *avctx)  
  2. {  
  3.     X264Context *x4 = avctx->priv_data;  
  4.     int sw,sh;  
  5.   
  6.     x264_param_default(&x4->params);  
  7.   
  8.     x4->params.b_deblocking_filter         = avctx->flags & CODEC_FLAG_LOOP_FILTER;  
  9.   
  10.     x4->params.rc.f_ip_factor             = 1 / fabs(avctx->i_quant_factor);  
  11.     x4->params.rc.f_pb_factor             = avctx->b_quant_factor;  
  12.     x4->params.analyse.i_chroma_qp_offset = avctx->chromaoffset;  
  13.     if (x4->preset || x4->tune)  
  14.         <span style="color:#ff6666;">/  
  15.         // 主要看看这个函数,在这里面会设置很多关键的参数,这个函数式X264提供的,接下来我们要到X264中查看其源代码  
  16.         if (x264_param_default_preset(&x4->params, x4->preset, x4->tune) < 0) {  
  17.             int i;  
  18.             av_log(avctx, AV_LOG_ERROR, "Error setting preset/tune %s/%s.\n", x4->preset, x4->tune);  
  19.             av_log(avctx, AV_LOG_INFO, "Possible presets:");  
  20.             for (i = 0; x264_preset_names[i]; i++)  
  21.                 av_log(avctx, AV_LOG_INFO, " %s", x264_preset_names[i]);  
  22.             av_log(avctx, AV_LOG_INFO, "\n");  
  23.             av_log(avctx, AV_LOG_INFO, "Possible tunes:");  
  24.             for (i = 0; x264_tune_names[i]; i++)  
  25.                 av_log(avctx, AV_LOG_INFO, " %s", x264_tune_names[i]);  
  26.             av_log(avctx, AV_LOG_INFO, "\n");  
  27.             return AVERROR(EINVAL);  
  28.         }  
  29.         </span>  
  30.     ......  
  31.     ......  
  32. }</span>  
    这里调用x264_param_default_preset(&x4->params, x4->preset, x4->tune) ,而x4变量的类型是X264Context ,这个结构体中的参数是最终要传给X264来设置编码器参数的,我们还可以从X264Context *x4 = avctx->priv_data;中看到,x4变量其实是有AVCodecContext中的priv_data成员指定的,在AVCodecContext中priv_data是void*类型,而AVCodecContext正是我们传进来的,也就是说,我们现在终于可以想办法控制这些参数了----这要把这些参数指定给priv_data成员即可了。

    现在我们还是先看看X264Context 中那些成员指定了控制得到实时编码的的参数:

[cpp]  view plain  copy
  1. <span style="font-family:Courier New;">typedef struct X264Context {  
  2.     AVClass        *class;  
  3.     x264_param_t    params;  
  4.     x264_t         *enc;  
  5.     x264_picture_t  pic;  
  6.     uint8_t        *sei;  
  7.     int             sei_size;  
  8.     AVFrame         out_pic;  
  9.     char *preset;  
  10.     char *tune;  
  11.     char *profile;  
  12.     char *level;  
  13.     int fastfirstpass;  
  14.     char *wpredp;  
  15.     char *x264opts;  
  16.     float crf;  
  17.     float crf_max;  
  18.     int cqp;  
  19.     int aq_mode;  
  20.     float aq_strength;  
  21.     char *psy_rd;  
  22.     int psy;  
  23.     int rc_lookahead;  
  24.     int weightp;  
  25.     int weightb;  
  26.     int ssim;  
  27.     int intra_refresh;  
  28.     int b_bias;  
  29.     int b_pyramid;  
  30.     int mixed_refs;  
  31.     int dct8x8;  
  32.     int fast_pskip;  
  33.     int aud;  
  34.     int mbtree;  
  35.     char *deblock;  
  36.     float cplxblur;  
  37.     char *partitions;  
  38.     int direct_pred;  
  39.     int slice_max_size;  
  40.     char *stats;  
  41. } X264Context;</span>  
    出于本能,我第一时间发现了两个我最关心的两个参数:preset和tune,这正是(x264_param_default_preset要用到的两个参数。

    至此,我认为已经想到了解决编码延迟的解决方案了(离完美还差那么一步),于是我立马在将测试代码中做出如下的修改:

[cpp]  view plain  copy
  1. <span style="font-family:Courier New;">   ......    
  2.    c = avcodec_alloc_context3(codec);  
  3.   
  4.     /* put sample parameters */  
  5.     c->bit_rate = 400000;  
  6.     /* resolution must be a multiple of two */  
  7.     c->width = 800/*352*/;  
  8.     c->height = 500/*288*/;  
  9.     /* frames per second */  
  10.     c->time_base.den = 1;  
  11.     c->time_base.num = 25;  
  12.     c->gop_size = 10; /* emit one intra frame every ten frames */  
  13.     c->max_b_frames=1;  
  14.     c->pix_fmt = PIX_FMT_YUV420P;  
  15.   
  16.     <span style="color:#ff6666;">// 新增语句,设置为编码延迟  
  17.     if (c->priv_data) {  
  18.         ((X264Context*)(c->priv_data))->preset = "superfast";  
  19.         ((X264Context*)(c->priv_data))->tune = "zerolatency";  
  20.     }</span>  
  21.     ......  
  22.     ......</span>  
   编译......error!原来编译器不认识X264Context,一定是忘了包含头文件,查看源代码,发现这是一个对外不公开的结构体,我无法通过包含头文件来包含该结构体,于是抱怨ffmpeg怎么搞的!也许是给予解决问题,同时验证之前的的理解正确与否,我采用了最粗暴的方法,直接将该结构体复制到我的文件中,当然这个结构体中有一个名为class的成员需要更改一下名字,因为我的项目是C++开发的,这个而class是C++的关键字,同时也要将x264.h和x264_config.h头文件复制到你的工程中,因为X264Context中的几个成员类型如x264_param_t、x264_t等是在x264.h中定义的,而x264.h又包含x264_config.h,好在x264_config.h没有在继续包含别的文件了(这也再次证明了我们在开发的一条规范的好处:尽量在头文件中不再包含其他头文件,而是尽量使用向前声明,这样方便代码的移植)。折腾一番之后,编译代码,终于顺利通过了,此时,正如我的想象一样,编码果然没有任何延迟了!(在我的工程代码中却是没有哪怕一帧的延迟,但在这个测试代码中却存在一帧的延迟,当然一帧的延迟几乎没有任何影响),见下图运行效果:


我的目的终于达到了,同时验证我的理解也是正确的,一时间海阔天空!

但欢呼胜利之后,我却看着自己定义的那个X264Context非常别扭,于是我想,ffmpeg不会肯定提供了其他的途径来设置我们想要的这些参数,而不至于用户自己手工去配置priv_data,要知道这是一个void*指针!而且ffmpeg并没有将X264Context开放给外部使用者,这让我更加怀疑我的设置方式是否合理?是否存在接口让我方便地设置priv_data?

让我欢喜的av_opt_set

    带着对自己的怀疑,我继续查找资料,看源代码......终于我在一个官方的例子代码中发现了新大陆,在decoding_encdoing.cpp的视频编码例子(我的测试例子正是从该例子文件中提取出来的,见该文件中的video_encode_example函数)中,我发现了下面一条语句(其实以前看例子就看到过这条语句,但当时由于没有细细研究,也没有管它的用意何在):

[cpp]  view plain  copy
  1. if(codec_id == AV_CODEC_ID_H264)   
  2.         av_opt_set(c->priv_data, "preset""slow", 0);  
于是赶紧查查看源代码:

[cpp]  view plain  copy
  1. int av_opt_set(void *obj, const char *name, const char *val, int search_flags)  
  2. {  
  3.     int ret;  
  4.     void *dst, *target_obj;  
  5.     const AVOption *o = av_opt_find2(obj, name, NULL, 0, search_flags, &target_obj);  
  6.     if (!o || !target_obj)  
  7.         return AVERROR_OPTION_NOT_FOUND;  
  8.     if (!val && (o->type != AV_OPT_TYPE_STRING && o->type != AV_OPT_TYPE_PIXEL_FMT && o->type != AV_OPT_TYPE_IMAGE_SIZE))  
  9.         return AVERROR(EINVAL);  
  10.   
  11.     dst = ((uint8_t*)target_obj) + o->offset;  
  12.     switch (o->type) {  
  13.     case AV_OPT_TYPE_STRING:   return set_string(obj, o, val, dst);  
  14.     case AV_OPT_TYPE_BINARY:   return set_string_binary(obj, o, val, dst);  
  15.     case AV_OPT_TYPE_FLAGS:  
  16.     case AV_OPT_TYPE_INT:  
  17.     case AV_OPT_TYPE_INT64:  
  18.     case AV_OPT_TYPE_FLOAT:  
  19.     case AV_OPT_TYPE_DOUBLE:  
  20.     case AV_OPT_TYPE_RATIONAL: return set_string_number(obj, o, val, dst);  
  21.     case AV_OPT_TYPE_IMAGE_SIZE:  
  22.         if (!val || !strcmp(val, "none")) {  
  23.             *(int *)dst = *((int *)dst + 1) = 0;  
  24.             return 0;  
  25.         }  
  26.         ret = av_parse_video_size(dst, ((int *)dst) + 1, val);  
  27.         if (ret < 0)  
  28.             av_log(obj, AV_LOG_ERROR, "Unable to parse option value \"%s\" as image size\n", val);  
  29.         return ret;  
  30.     case AV_OPT_TYPE_PIXEL_FMT:  
  31.         if (!val || !strcmp(val, "none"))  
  32.             ret = PIX_FMT_NONE;  
  33.         else {  
  34.             ret = av_get_pix_fmt(val);  
  35.             if (ret == PIX_FMT_NONE) {  
  36.                 char *tail;  
  37.                 ret = strtol(val, &tail, 0);  
  38.                 if (*tail || (unsigned)ret >= PIX_FMT_NB) {  
  39.                     av_log(obj, AV_LOG_ERROR, "Unable to parse option value \"%s\" as pixel format\n", val);  
  40.                     return AVERROR(EINVAL);  
  41.                 }  
  42.             }  
  43.         }  
  44.         *(enum PixelFormat *)dst = ret;  
  45.         return 0;  
  46.     }  
  47.   
  48.     av_log(obj, AV_LOG_ERROR, "Invalid option type.\n");  
  49.     return AVERROR(EINVAL);  
  50. }  
果然不出我所料,就是它了!

于是迫不及待地重新修改我的测试代码,将原先的修改全删掉,修改为如下:

[cpp]  view plain  copy
  1. <span style="font-family:Courier New;">    ......    
  2.    c = avcodec_alloc_context3(codec);  
  3.   
  4.     /* put sample parameters */  
  5.     c->bit_rate = 400000;  
  6.     /* resolution must be a multiple of two */  
  7.     c->width = 800/*352*/;  
  8.     c->height = 500/*288*/;  
  9.     /* frames per second */  
  10.     c->time_base.den = 1;  
  11.     c->time_base.num = 25;  
  12.     c->gop_size = 10; /* emit one intra frame every ten frames */  
  13.     c->max_b_frames=1;  
  14.     c->pix_fmt = PIX_FMT_YUV420P;  
  15.   
  16. <span style="color:#ff6666;">    // 新增语句,设置为编码延迟  
  17.     av_opt_set(c->priv_data, "preset""superfast", 0);  
  18.   
  19.     // 实时编码关键看这句,上面那条无所谓  
  20.     av_opt_set(c->priv_data, "tune""zerolatency", 0);</span>  
  21.     ......  
  22.     ......</span>  
编译运行.......果然OK,见下图测试结果(在我的项目中没有延迟哪怕一帧,但这个例子代码中有一帧延迟,但一帧无伤大雅):


困扰我两天的问题终于圆满解决了!万岁!

总结

    我在想,如果我之前在网上或者别的什么地方看到了用av_op_set这样一条简单的语句就解决了我的问题,那么我节省了两天时间,但仅此而已,我也仅仅是知其然而不知其所以然。但在我在网上没有寻找到满意的答案之后,我决定自己阅读源代码,刨根问底,我花费了两天时间,但是换回的不仅仅是知道要这么做,也知道了为什么这样做可以有效果!

    所以,开源项目对已我们每个IT从业人员都是一笔宝贵的财富,开源项目源代码的阅读是提高我们软件开发能力的一条最佳途径之一。

    这篇文章记录了我阅读ffmpeg源代码解决问题的各个环节,以备后用,也希望我的这些文字可以给遇到同样问题的人提供一点点帮助。

    最后列出一些我在解决这个问题中参看的一些网页:

    http://bbs.csdn.net/topics/370233998

    http://x264-settings.wikispaces.com/x264_Encoding_Suggestions





http://blog.csdn.net/ymsdu2004/article/details/8565822

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值