x264源码分析与应用示例(二)——码率控制

1、x264的码率控制原理与对应源码解析

基本概念

对于此前了解过H.264的码率控制原理的读者(如果不了解,也可以去看我的文章H.264码率控制算法研究及JM相应代码分析),首先需要说明的是x264采用的码率控制算法并没有采用拉格朗日代价函数来控制编码,而是使用一种更简单的方法,即利用半精度帧的SATD作为量化等级参数选择的依据。SATD即将残差经哈德曼变换的4×4块的预测残差绝对值总和,可以将其看作简单的时频变换,其值在一定程度上可以反映生成码流的大小。

X264显式支持的一趟码率控制方法有:ABR, CQP, CRF. 缺省方法是CRF。这三种方式的优先级是ABR > CQP > CRF. 

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1.  if ( bitrate )                rc_method = ABR;    
  2. else if ( qp || qp_constant ) rc_method = CQP;    
  3. else                          rc_method = CRF;     

bitrate和QP都没有缺省值,一旦设置他们就表示要按照相应的码率控制方法进行编码,CRF有缺省值23,没有任何关于编码控制的设置时就按照CRF缺省值23来编码。

关于这三种方法的更详细的介绍,可以参见这里。而一些码率控制相关的命令行参数的介绍则可以看这篇文章

源码分析

x264中和码率控制相关的内容都在ratecontrol.h ratecontrol.c这两个文件中,基本的调用流程如下,图中最左边的几个函数代表码率控制的内容是在哪里被调用的,对这几个函数不清楚的读者可以参见我的上一篇文章


首先需要知道,在整个码率控制流程中的关键结构体就是x264_ratecontrol_t了,其定义如下

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. struct x264_ratecontrol_t  
  2. {  
  3.     /* constants */  
  4.     int b_abr;  
  5.     /* 2pass 是变码率(VBR)压缩的一项关键技术,意思是通过两次分析来压缩一个文件。 
  6.        * 第一次分析影片各部分的动作快慢及分配相应的码率并作以相应记录, 
  7.        * 第二次再根据第一次的记录进行压缩,这样就能让码率得到最佳分配, 
  8.        * 从而在指定文件大小或规定码流内最大限度的提高视频质量。*/  
  9.     int b_2pass;  
  10.     int b_vbv;  //视频缓冲检验器  
  11.     int b_vbv_min_rate;  
  12.     double fps;  
  13.     double bitrate;  
  14.     double rate_tolerance;  
  15.     double qcompress;  
  16.     int nmb;                    /* number of macroblocks in a frame */  
  17.     int qp_constant[3];  
  18.   
  19.     /* current frame */  
  20.     ratecontrol_entry_t *rce;   //当前帧码率控制的相关内容  
  21.     int qp;                     /* qp for current frame */  
  22.     float qpm;                  /* qp for current macroblock: precise float for AQ */  
  23.     float qpa_rc;               /* average of macroblocks' qp before aq */  
  24.     float qpa_rc_prev;  
  25.     int   qpa_aq;               /* average of macroblocks' qp after aq */  
  26.     int   qpa_aq_prev;  
  27.     float qp_novbv;             /* QP for the current frame if 1-pass VBV was disabled. */  
  28.   
  29.     /* VBV stuff */  
  30.     double buffer_size;  
  31.     int64_t buffer_fill_final;   /* 上一个完成的帧实际使用的缓冲区大小 */  
  32.     int64_t buffer_fill_final_min;  
  33.     double buffer_fill;         /* planned buffer, if all in-progress frames hit their bit budget */  
  34.                                 /* 计划的缓冲区大小, 就是处理的所有帧都算上可能出现的最大缓冲区使用量 */  
  35.     double buffer_rate;         /* # of bits added to buffer_fill after each frame */  
  36.                                 /* 每帧过后要加在buffer_fill上的比特数 */  
  37.     double vbv_max_rate;        /* # of bits added to buffer_fill per second */  
  38.     predictor_t *pred;          /* predict frame size from satd */  
  39.     int single_frame_vbv;  
  40.     float rate_factor_max_increment; /* Don't allow RF above (CRF + this value). */  
  41.   
  42.     /* ABR stuff */  
  43.     int    last_satd;  
  44.     double last_rceq;//last rc estimated qscale  
  45.     double cplxr_sum;           /* sum of bits*qscale/rceq */  
  46.     double expected_bits_sum;   /* sum of qscale2bits after rceq, ratefactor, and overflow, only includes finished frames */  
  47.     int64_t filler_bits_sum;    /* sum in bits of finished frames' filler data */  
  48.     double wanted_bits_window;  /* target bitrate * window */  
  49.     double cbr_decay;//还不清楚是做什么的  
  50.     double short_term_cplxsum;  
  51.     double short_term_cplxcount;  
  52.     double rate_factor_constant;  
  53.     double ip_offset;  
  54.     double pb_offset;  
  55.   
  56.     /* 2pass stuff */  
  57.     FILE *p_stat_file_out;  
  58.     char *psz_stat_file_tmpname;  
  59.     FILE *p_mbtree_stat_file_out;  
  60.     char *psz_mbtree_stat_file_tmpname;  
  61.     char *psz_mbtree_stat_file_name;  
  62.     FILE *p_mbtree_stat_file_in;  
  63.   
  64.     int num_entries;            /* number of ratecontrol_entry_ts */  
  65.     ratecontrol_entry_t *entry; /* FIXME: copy needed data and free this once init is done */  
  66.     double last_qscale;  
  67.     double last_qscale_for[3];  /* last qscale for a specific pict type, used for max_diff & ipb factor stuff */  
  68.     int last_non_b_pict_type;  
  69.     double accum_p_qp;          /* for determining I-frame quant;accumulation of p frame qp*/  
  70.                                 /* 用于决定I帧的量化系数 */  
  71.     double accum_p_norm;  
  72.     double last_accum_p_norm;  
  73.     double lmin[3];             /* min qscale by frame type */  
  74.     double lmax[3];  
  75.     double lstep;               /* max change (multiply) in qscale per frame */  
  76.     struct  
  77.     {  
  78.         uint16_t *qp_buffer[2]; /* Global buffers for converting MB-tree quantizer data. */  
  79.         int qpbuf_pos;          /* In order to handle pyramid reordering, QP buffer acts as a stack. 
  80.                                  * This value is the current position (0 or 1). */  
  81.         int src_mb_count;  
  82.   
  83.         /* For rescaling */  
  84.         int rescale_enabled;  
  85.         float *scale_buffer[2]; /* Intermediate buffers */  
  86.         int filtersize[2];      /* filter size (H/V) */  
  87.         float *coeffs[2];  
  88.         int *pos[2];  
  89.         int srcdim[2];          /* Source dimensions (W/H) */  
  90.     } mbtree;  
  91.   
  92.     /* MBRC stuff */  
  93.     float frame_size_estimated; /* Access to this variable must be atomic: double is 
  94.                                  * not atomic on all arches we care about */  
  95.     double frame_size_maximum;  /* Maximum frame size due to MinCR */  
  96.     double frame_size_planned;  
  97.     double slice_size_planned;  
  98.     predictor_t *row_pred;//用satd和qscale预测framesize的一组系数  
  99.     predictor_t row_preds[3][2];//3代表IPB帧,但是2代表什么还不清楚  
  100.     predictor_t *pred_b_from_p; /* predict B-frame size from P-frame satd */  
  101.     int bframes;                /* # consecutive B-frames before this P-frame */  
  102.     int bframe_bits;            /* total cost of those frames */  
  103.   
  104.     int i_zones;  
  105.     x264_zone_t *zones;  
  106.     x264_zone_t *prev_zone;  
  107.   
  108.     /* hrd stuff */  
  109.     int initial_cpb_removal_delay;  
  110.     int initial_cpb_removal_delay_offset;  
  111.     double nrt_first_access_unit; /* nominal removal time */  
  112.     double previous_cpb_final_arrival_time;  
  113.     uint64_t hrd_multiply_denom;  
  114. };  

根据我的学习经验,看完这个结构体之后肯定会好奇里面一些奇怪的变量是干什么的,这时候就有必要先大致了解一下x264码率控制的理论方法了。这方面建议大家搜索一些论文来学习,给出一个我认为讲的比较好的。



步骤中有很多经验公式,这方面应该也有一些论述文章,以后有时间再做补充。

下面就依照前面的流程图和理论步骤来分析代码。依照顺序分析各个关键函数,各个函数的作用,代码详细分析的内容都写在注释中。希望三者结合能有助于大家理解x264的码率控制。如果有任何问题或者错误,欢迎大家指出,代码分析中还有一些我自己不理解的地方,也希望了解的朋友多多指点。

x264_ratecontrol_new

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. //call by x264_encoder_open  
  2. //用于各种赋值和初始化,管理与2pass码率控制相关的输入输出文件  
  3. int x264_ratecontrol_new( x264_t *h )  
  4. {  
  5.     x264_ratecontrol_t *rc;  
  6.   
  7.     x264_emms();  
  8.   
  9.     CHECKED_MALLOCZERO( h->rc, h->param.i_threads * sizeof(x264_ratecontrol_t) );  
  10.     rc = h->rc;  
  11.     //判断码率控制方法  
  12.     rc->b_abr = h->param.rc.i_rc_method != X264_RC_CQP && !h->param.rc.b_stat_read;  
  13.     rc->b_2pass = h->param.rc.i_rc_method == X264_RC_ABR && h->param.rc.b_stat_read;  
  14.   
  15.     /* FIXME: use integers */  
  16.     if( h->param.i_fps_num > 0 && h->param.i_fps_den > 0 )  
  17.         rc->fps = (float) h->param.i_fps_num / h->param.i_fps_den;  
  18.     else  
  19.         rc->fps = 25.0;  //default fps  
  20.   
  21.     // macroblock tree:决定该MB使用何种大小的qp值进行量化。对每个MB处理,  
  22.     // 向前预测一定数量的帧,记录该MB被参考的情况,qp的大小与被参考次数成反比。  
  23.     // 与mb_tree相关的参数:rc-lookahead 决定mb_tree向前预测的帧数  
  24.     if( h->param.rc.b_mb_tree )  
  25.     {  
  26.         h->param.rc.f_pb_factor = 1;  
  27.         // Qcomp (Quantizer Curve Compression) : 控制整个视频的码率波动大小,  
  28.         // 它会影响mb_tree的强度 (Higher qcomp = weaker mbtree)  
  29.         // 0% 时相当于CBR模式,100%时相当于CQP模式  
  30.         rc->qcompress = 1;  
  31.     }  
  32.     else  
  33.         rc->qcompress = h->param.rc.f_qcompress;  // 0.0 => cbr, 1.0 => constant qp  
  34.     //码率单位一般是1000  
  35.     rc->bitrate = h->param.rc.i_bitrate * (h->param.i_avcintra_class ? 1024. : 1000.);  
  36.     rc->rate_tolerance = h->param.rc.f_rate_tolerance;  
  37.     rc->nmb = h->mb.i_mb_count;   //number of mbs in a frame  
  38.     rc->last_non_b_pict_type = -1;  
  39.     rc->cbr_decay = 1.0;  
  40.   
  41.     if( h->param.rc.i_rc_method == X264_RC_CRF && h->param.rc.b_stat_read )  
  42.     {  
  43.         x264_log( h, X264_LOG_ERROR, "constant rate-factor is incompatible with 2pass.\n" );  
  44.         return -1;  
  45.     }  
  46.   
  47.     x264_ratecontrol_init_reconfigurable( h, 1 );  
  48.   
  49.     if( h->param.i_nal_hrd )  
  50.     {  
  51.         uint64_t denom = (uint64_t)h->sps->vui.hrd.i_bit_rate_unscaled * h->sps->vui.i_time_scale;  
  52.         uint64_t num = 90000;  
  53.         x264_reduce_fraction64( &num, &denom );  
  54.         rc->hrd_multiply_denom = 90000 / num;  
  55.   
  56.         //计算需要的比特数  
  57.         double bits_required = log2( 90000 / rc->hrd_multiply_denom )  
  58.                              + log2( h->sps->vui.i_time_scale )  
  59.                              + log2( h->sps->vui.hrd.i_cpb_size_unscaled );  
  60.         if( bits_required >= 63 )  
  61.         {  
  62.             x264_log( h, X264_LOG_ERROR, "HRD with very large timescale and bufsize not supported\n" );  
  63.             return -1;  
  64.         }  
  65.     }  
  66.   
  67.     if( rc->rate_tolerance < 0.01 )  
  68.     {  
  69.         x264_log( h, X264_LOG_WARNING, "bitrate tolerance too small, using .01\n" );  
  70.         rc->rate_tolerance = 0.01;  
  71.     }  
  72.   
  73.     /* whether qp is allowed to vary per macroblock */  
  74.     h->mb.b_variable_qp = rc->b_vbv || h->param.rc.i_aq_mode;  
  75.   
  76.     if( rc->b_abr )  
  77.     {  
  78.         /* FIXME ABR_INIT_QP is actually used only in CRF */  
  79. #define ABR_INIT_QP (( h->param.rc.i_rc_method == X264_RC_CRF ? h->param.rc.f_rf_constant : 24 ) + QP_BD_OFFSET)  
  80.         rc->accum_p_norm = .01;  
  81.         rc->accum_p_qp = ABR_INIT_QP * rc->accum_p_norm;  
  82.         /* estimated ratio that produces a reasonable QP for the first I-frame */  
  83.         // 估计初始复杂度 = 0.01 * (700000 ^ qcomp) * (宏块总数目^ 0.5)  
  84.         rc->cplxr_sum = .01 * pow( 7.0e5, rc->qcompress ) * pow( h->mb.i_mb_count, 0.5 );  
  85.         //每个帧的比特数  
  86.         rc->wanted_bits_window = 1.0 * rc->bitrate / rc->fps;  
  87.         rc->last_non_b_pict_type = SLICE_TYPE_I;  
  88.     }  
  89.   
  90.     rc->ip_offset = 6.0 * log2f( h->param.rc.f_ip_factor );  
  91.     rc->pb_offset = 6.0 * log2f( h->param.rc.f_pb_factor );  
  92.     //get qp for p frame at first, then use offset to calculate values for i framne and b frame  
  93.     rc->qp_constant[SLICE_TYPE_P] = h->param.rc.i_qp_constant;  
  94.     rc->qp_constant[SLICE_TYPE_I] = x264_clip3( h->param.rc.i_qp_constant - rc->ip_offset + 0.5, 0, QP_MAX );  
  95.     rc->qp_constant[SLICE_TYPE_B] = x264_clip3( h->param.rc.i_qp_constant + rc->pb_offset + 0.5, 0, QP_MAX );  
  96.     h->mb.ip_offset = rc->ip_offset + 0.5;  
  97.   
  98.     //每帧qscale的最大改变倍数=qp_step/6  
  99.     rc->lstep = pow( 2, h->param.rc.i_qp_step / 6.0 );  
  100.     rc->last_qscale = qp2qscale( 26 );  
  101.     int num_preds = h->param.b_sliced_threads * h->param.i_threads + 1;  
  102.     //预测误差都用satd来计算  
  103.     CHECKED_MALLOC( rc->pred, 5 * sizeof(predictor_t) * num_preds );  
  104.     CHECKED_MALLOC( rc->pred_b_from_p, sizeof(predictor_t) );  
  105.     forint i = 0; i < 3; i++ )  
  106.     {//对应P B I帧  
  107.         rc->last_qscale_for[i] = qp2qscale( ABR_INIT_QP );  
  108.         rc->lmin[i] = qp2qscale( h->param.rc.i_qp_min );  
  109.         rc->lmax[i] = qp2qscale( h->param.rc.i_qp_max );  
  110.         forint j = 0; j < num_preds; j++ )  
  111.         {  
  112.             rc->pred[i+j*5].coeff_min = 2.0 / 4;  
  113.             rc->pred[i+j*5].coeff = 2.0;  
  114.             rc->pred[i+j*5].count = 1.0;  
  115.             rc->pred[i+j*5].decay = 0.5;  
  116.             rc->pred[i+j*5].offset = 0.0;  
  117.         }  
  118.         forint j = 0; j < 2; j++ )  
  119.         {  
  120.             rc->row_preds[i][j].coeff_min = .25 / 4;  
  121.             rc->row_preds[i][j].coeff = .25;  
  122.             rc->row_preds[i][j].count = 1.0;  
  123.             rc->row_preds[i][j].decay = 0.5;  
  124.             rc->row_preds[i][j].offset = 0.0;  
  125.         }  
  126.     }  
  127.     *rc->pred_b_from_p = rc->pred[0];  
  128.     // 用于手动分配低或高码率给视频的某个特定部分  
  129.     if( parse_zones( h ) < 0 )  
  130.     {  
  131.         x264_log( h, X264_LOG_ERROR, "failed to parse zones\n" );  
  132.         return -1;  
  133.     }……2pass相关的内容省略不看  
其中调用的x264_ratecontrol_init_reconfigurable主要是对vbv做一些初始化的设置。有不了解vbv的可以参见 这篇文章 ,非常生动形象。

x264_ratecontrol_start

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /* Before encoding a frame, choose a QP for it */  
  2. //called by x264_encode_encode  
  3. //计算一帧的QP值,帧层码率控制,到这一步,一帧中所有宏块还是统一qp的  
  4. void x264_ratecontrol_start( x264_t *h, int i_force_qp, int overhead )  
  5. {  
  6.     x264_ratecontrol_t *rc = h->rc;  
  7.     ratecontrol_entry_t *rce = NULL;    //used for 2pass  
  8.     x264_zone_t *zone = get_zone( h, h->fenc->i_frame );  
  9.     float q;  
  10.   
  11.     x264_emms();  
  12.   
  13.     if( zone && (!rc->prev_zone || zone->param != rc->prev_zone->param) )  
  14.         x264_encoder_reconfig_apply( h, zone->param );  
  15.     rc->prev_zone = zone;  
  16.   
  17.     if( h->param.rc.b_stat_read )  
  18.     {  
  19.         int frame = h->fenc->i_frame;  
  20.         assert( frame >= 0 && frame < rc->num_entries );  
  21.         rce = h->rc->rce = &h->rc->entry[frame];  
  22.   
  23.         if( h->sh.i_type == SLICE_TYPE_B  
  24.             && h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_AUTO )  
  25.         {  
  26.             h->sh.b_direct_spatial_mv_pred = ( rce->direct_mode == 's' );  
  27.             h->mb.b_direct_auto_read = ( rce->direct_mode == 's' || rce->direct_mode == 't' );  
  28.         }  
  29.     }  
  30.   
  31.     if( rc->b_vbv )  
  32.     {  
  33.         // 初始化重构帧的的几个参数,主要用于自适应B帧的确定  
  34.         memset( h->fdec->i_row_bits, 0, h->mb.i_mb_height * sizeof(int) );  
  35.         memset( h->fdec->f_row_qp, 0, h->mb.i_mb_height * sizeof(float) );  
  36.         memset( h->fdec->f_row_qscale, 0, h->mb.i_mb_height * sizeof(float) );  
  37.         rc->row_pred = rc->row_preds[h->sh.i_type];  
  38.         rc->buffer_rate = h->fenc->i_cpb_duration * rc->vbv_max_rate * h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;  
  39.         // 根据当前所有帧预计的大小临时更新VBV,也即更新h->rc->buffer_fill,就是更新缓冲区  
  40.         update_vbv_plan( h, overhead );  
  41.   
  42.         //h264级别  
  43.         const x264_level_t *l = x264_levels;  
  44.         while( l->level_idc != 0 && l->level_idc != h->param.i_level_idc )  
  45.             l++;  
  46.   
  47.         // 获取该h264级别的最小压缩比,例如:级别3.1,mincr值为4  
  48.         int mincr = l->mincr;  
  49.         // 蓝光碟压缩,最小压缩比为4  
  50.         if( h->param.b_bluray_compat )  
  51.             mincr = 4;  
  52.   
  53.         /* Profiles above High don't require minCR, so just set the maximum to a large value. */  
  54.         // profile高于high的档次不需要mincr,因此将帧的最大值设为一个非常大的值  
  55.         // profile的各种取值定义在文件common/set.h中  
  56.         if( h->sps->i_profile_idc > PROFILE_HIGH )  
  57.             rc->frame_size_maximum = 1e9;  
  58.         else  
  59.         {  
  60.             /* The spec has a bizarre special case for the first frame. */  
  61.             if( h->i_frame == 0 )  
  62.             {  
  63.                 //384 * ( Max( PicSizeInMbs, fR * MaxMBPS ) + MaxMBPS * ( tr( 0 ) - tr,n( 0 ) ) ) / MinCR  
  64.                 double fr = 1. / 172;  
  65.                 int pic_size_in_mbs = h->mb.i_mb_width * h->mb.i_mb_height;  
  66.                 // Maximum frame size due to MinCR,计算每帧最大尺寸  
  67.                 rc->frame_size_maximum = 384 * BIT_DEPTH * X264_MAX( pic_size_in_mbs, fr*l->mbps ) / mincr;  
  68.             }  
  69.             else  
  70.             {  
  71.                 //384 * MaxMBPS * ( tr( n ) - tr( n - 1 ) ) / MinCR  
  72.                 rc->frame_size_maximum = 384 * BIT_DEPTH * ((double)h->fenc->i_cpb_duration * h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale) * l->mbps / mincr;  
  73.             }  
  74.         }  
  75.     }//if(rc->vbv)  
  76.   
  77.     if( h->sh.i_type != SLICE_TYPE_B )  
  78.         rc->bframes = h->fenc->i_bframes;  
  79.   
  80.     // 根据不同码率控制方式计算qp值  
  81.     if( rc->b_abr )  
  82.     {  
  83.         // update qscale for 1 frame based on actual bits used so far  
  84.         q = qscale2qp( rate_estimate_qscale( h ) );  
  85.     }  
  86.     else if( rc->b_2pass )  
  87.     {  
  88.         rce->new_qscale = rate_estimate_qscale( h );  
  89.         q = qscale2qp( rce->new_qscale );  
  90.     }  
  91.     else /* CQP */  
  92.     {  
  93.         if( h->sh.i_type == SLICE_TYPE_B && h->fdec->b_kept_as_ref )  
  94.             q = ( rc->qp_constant[ SLICE_TYPE_B ] + rc->qp_constant[ SLICE_TYPE_P ] ) / 2;  
  95.         else  
  96.             q = rc->qp_constant[ h->sh.i_type ];  
  97.   
  98.         if( zone )  
  99.         {  
  100.             if( zone->b_force_qp )  
  101.                 q += zone->i_qp - rc->qp_constant[SLICE_TYPE_P];  
  102.             else  
  103.                 q -= 6*log2f( zone->f_bitrate_factor );  
  104.         }  
  105.     }  
  106.     if( i_force_qp != X264_QP_AUTO )  
  107.         q = i_force_qp - 1;  
  108.   
  109.     q = x264_clip3f( q, h->param.rc.i_qp_min, h->param.rc.i_qp_max );  
  110.   
  111.     // 设置当前帧的qp,以及aq之前和之后的宏块平均qp  
  112.     rc->qpa_rc = rc->qpa_rc_prev =  
  113.     rc->qpa_aq = rc->qpa_aq_prev = 0;  
  114.     rc->qp = x264_clip3( q + 0.5f, 0, QP_MAX );  
  115.     h->fdec->f_qp_avg_rc =  
  116.     h->fdec->f_qp_avg_aq =  
  117.     rc->qpm = q;// 当前宏块的qp值  
  118.     if( rce )  
  119.         rce->new_qp = rc->qp;  
  120.   
  121.     //更新h->rc->accum_p_qp的值  
  122.     accum_p_qp_update( h, rc->qpm );  
  123.   
  124.     // 记录最后一个非B帧的类型  
  125.     if( h->sh.i_type != SLICE_TYPE_B )  
  126.         rc->last_non_b_pict_type = h->sh.i_type;  
  127. }  

rate_estimate_qscale

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. // update qscale for 1 frame based on actual bits used so far  
  2. //得到一帧的QP和satd值  
  3. /*码率控制部分的核心之一,另一个是get_scale 
  4.  * 0、计算SATD和图像的模糊复杂度 
  5.  * 1、在get_scale中,按复杂度采用指数模型得到qscale 
  6.  * rcc->last_qscale = pow( rce->blurred_complexity, 1 - rcc->qcompress )/rate_factor 
  7.  * 2、在get_scale中根据复杂度和目标比特数调整qp 
  8.  * q /= rate_factor;    //rcc->wanted_bits_window / rcc->cplxr_sum 
  9.  * 3、根据已编码帧的实际比特数和目标比特数的偏差再次调整qp 
  10.  * overflow = x264_clip3f( 1.0 + (total_bits - wanted_bits) / abr_buffer, .5, 2 ); 
  11.    q *= overflow; 
  12.  */  
  13. static float rate_estimate_qscale( x264_t *h )  
  14. {  
  15.     float q;  
  16.     x264_ratecontrol_t *rcc = h->rc;  
  17.     ratecontrol_entry_t rce = {0};  
  18.     int pict_type = h->sh.i_type;  
  19.     //zhanghui:will there be total_bits if not 2pass,no  
  20.     int64_t total_bits = 8*(h->stat.i_frame_size[SLICE_TYPE_I]  
  21.                           + h->stat.i_frame_size[SLICE_TYPE_P]  
  22.                           + h->stat.i_frame_size[SLICE_TYPE_B])  
  23.                        - rcc->filler_bits_sum;  
  24.   
  25.     if( rcc->b_2pass )  
  26.     {  
  27.         rce = *rcc->rce;  
  28.         if( pict_type != rce.pict_type )  
  29.         {  
  30.             x264_log( h, X264_LOG_ERROR, "slice=%c but 2pass stats say %c\n",  
  31.                       slice_type_to_char[pict_type], slice_type_to_char[rce.pict_type] );  
  32.         }  
  33.     }  
  34.   
  35.     if( pict_type == SLICE_TYPE_B )  
  36.     {  
  37.         /* B-frames don't have independent ratecontrol, but rather get the 
  38.          * average QP of the two adjacent P-frames + an offset */  
  39.         //B帧的QP由两个相邻的参考帧的QP值计算而来,求平均  
  40.         int i0 = IS_X264_TYPE_I(h->fref_nearest[0]->i_type);  
  41.         int i1 = IS_X264_TYPE_I(h->fref_nearest[1]->i_type);  
  42.         int dt0 = abs(h->fenc->i_poc - h->fref_nearest[0]->i_poc);  
  43.         int dt1 = abs(h->fenc->i_poc - h->fref_nearest[1]->i_poc);  
  44.         float q0 = h->fref_nearest[0]->f_qp_avg_rc;  
  45.         float q1 = h->fref_nearest[1]->f_qp_avg_rc;  
  46.   
  47.         if( h->fref_nearest[0]->i_type == X264_TYPE_BREF )  
  48.             q0 -= rcc->pb_offset/2;  
  49.         if( h->fref_nearest[1]->i_type == X264_TYPE_BREF )  
  50.             q1 -= rcc->pb_offset/2;  
  51.   
  52.         if( i0 && i1 )  
  53.             q = (q0 + q1) / 2 + rcc->ip_offset;  
  54.         else if( i0 )   //取不是I帧的那个  
  55.             q = q1;  
  56.         else if( i1 )  
  57.             q = q0;  
  58.         else    //如果都不是I帧  
  59.             q = (q0*dt1 + q1*dt0) / (dt0 + dt1);  
  60.   
  61.         if( h->fenc->b_kept_as_ref )  
  62.             q += rcc->pb_offset/2;  
  63.         else  
  64.             q += rcc->pb_offset;  
  65.   
  66.         //估算frame_size  
  67.         if( rcc->b_2pass && rcc->b_vbv )  
  68.             rcc->frame_size_planned = qscale2bits( &rce, qp2qscale( q ) );  
  69.         else  
  70.             rcc->frame_size_planned = predict_size( rcc->pred_b_from_p, qp2qscale( q ), h->fref[1][h->i_ref[1]-1]->i_satd );  
  71.         /* Limit planned size by MinCR */  
  72.         if( rcc->b_vbv )  
  73.             rcc->frame_size_planned = X264_MIN( rcc->frame_size_planned, rcc->frame_size_maximum );  
  74.         h->rc->frame_size_estimated = rcc->frame_size_planned;  
  75.   
  76.         /* For row SATDs */  
  77.         if( rcc->b_vbv )  
  78.             //从slice decide那里得到计算好的satd值  
  79.             rcc->last_satd = x264_rc_analyse_slice( h );  
  80.         rcc->qp_novbv = q;  
  81.         return qp2qscale( q );  
  82.     }//if( pict_type == SLICE_TYPE_B )  
  83.     else  
  84.     {  
  85.         //缓冲区初始值  
  86.         double abr_buffer = 2 * rcc->rate_tolerance * rcc->bitrate;  
  87.   
  88.         if( rcc->b_2pass )  
  89.         {  
  90.             double lmin = rcc->lmin[pict_type];  
  91.             double lmax = rcc->lmax[pict_type];  
  92.             int64_t diff;  
  93.             int64_t predicted_bits = total_bits;  
  94.   
  95.             if( rcc->b_vbv )  
  96.             {  
  97.                 if( h->i_thread_frames > 1 )  
  98.                 {  
  99.                     int j = h->rc - h->thread[0]->rc;  
  100.                     forint i = 1; i < h->i_thread_frames; i++ )  
  101.                     {  
  102.                         x264_t *t = h->thread[ (j+i)%h->i_thread_frames ];  
  103.                         double bits = t->rc->frame_size_planned;  
  104.                         if( !t->b_thread_active )  
  105.                             continue;  
  106.                         bits = X264_MAX(bits, t->rc->frame_size_estimated);  
  107.                         predicted_bits += (int64_t)bits;  
  108.                     }  
  109.                 }  
  110.             }  
  111.             else  
  112.             {  
  113.                 if( h->i_frame < h->i_thread_frames )  
  114.                     predicted_bits += (int64_t)h->i_frame * rcc->bitrate / rcc->fps;  
  115.                 else  
  116.                     predicted_bits += (int64_t)(h->i_thread_frames - 1) * rcc->bitrate / rcc->fps;  
  117.             }  
  118.   
  119.             /* Adjust ABR buffer based on distance to the end of the video. */  
  120.             if( rcc->num_entries > h->i_frame )  
  121.             {  
  122.                 double final_bits = rcc->entry[rcc->num_entries-1].expected_bits;  
  123.                 double video_pos = rce.expected_bits / final_bits;  
  124.                 double scale_factor = sqrt( (1 - video_pos) * rcc->num_entries );  
  125.                 abr_buffer *= 0.5 * X264_MAX( scale_factor, 0.5 );  
  126.             }  
  127.   
  128.             diff = predicted_bits - (int64_t)rce.expected_bits;  
  129.             q = rce.new_qscale;  
  130.             q /= x264_clip3f((double)(abr_buffer - diff) / abr_buffer, .5, 2);  
  131.             if( ((h->i_frame + 1 - h->i_thread_frames) >= rcc->fps) &&  
  132.                 (rcc->expected_bits_sum > 0))  
  133.             {  
  134.                 /* Adjust quant based on the difference between 
  135.                  * achieved and expected bitrate so far */  
  136.                 double cur_time = (double)h->i_frame / rcc->num_entries;  
  137.                 double w = x264_clip3f( cur_time*100, 0.0, 1.0 );  
  138.                 q *= pow( (double)total_bits / rcc->expected_bits_sum, w );  
  139.             }  
  140.             rcc->qp_novbv = qscale2qp( q );  
  141.             if( rcc->b_vbv )  
  142.             {  
  143.                 /* Do not overflow vbv */  
  144.                 double expected_size = qscale2bits( &rce, q );  
  145.                 double expected_vbv = rcc->buffer_fill + rcc->buffer_rate - expected_size;  
  146.                 double expected_fullness = rce.expected_vbv / rcc->buffer_size;  
  147.                 double qmax = q*(2 - expected_fullness);  
  148.                 double size_constraint = 1 + expected_fullness;  
  149.                 qmax = X264_MAX( qmax, rce.new_qscale );  
  150.                 if( expected_fullness < .05 )  
  151.                     qmax = lmax;  
  152.                 qmax = X264_MIN(qmax, lmax);  
  153.                 while( ((expected_vbv < rce.expected_vbv/size_constraint) && (q < qmax)) ||  
  154.                         ((expected_vbv < 0) && (q < lmax)))  
  155.                 {  
  156.                     q *= 1.05;  
  157.                     expected_size = qscale2bits(&rce, q);  
  158.                     expected_vbv = rcc->buffer_fill + rcc->buffer_rate - expected_size;  
  159.                 }  
  160.                 rcc->last_satd = x264_rc_analyse_slice( h );  
  161.             }  
  162.             q = x264_clip3f( q, lmin, lmax );  
  163.         }//if( rcc->b_2pass )  
  164.         else /* 1pass ABR */  
  165.         {  
  166.             /* Calculate the quantizer which would have produced the desired 
  167.              * average bitrate if it had been applied to all frames so far. 
  168.              * Then modulate that quant based on the current frame's complexity 
  169.              * relative to the average complexity so far (using the 2pass RCEQ). 
  170.              * Then bias the quant up or down if total size so far was far from 
  171.              * the target. 
  172.              * 1、计算出一个Qp值,如果将该值应用到当前所有的帧,则可以获得目标平均吗率 
  173.              * 2、根据当前帧的复杂度和平均复杂度的差距,调整QP 
  174.              * 3、如果total size和目标相差太多,再调整QP 
  175.              * Result: Depending on the value of rate_tolerance, there is a 
  176.              * tradeoff between quality and bitrate precision. But at large 
  177.              * tolerances, the bit distribution approaches that of 2pass. */  
  178.   
  179.             double wanted_bits, overflow = 1;  
  180.             //首先计算当前帧的SATD  
  181.             rcc->last_satd = x264_rc_analyse_slice( h );  
  182.             //计算cplxsum (累计复杂度) 和 cplxcount(加权累计帧数)  
  183.             rcc->short_term_cplxsum *= 0.5;  
  184.             rcc->short_term_cplxcount *= 0.5;  
  185.             rcc->short_term_cplxsum += rcc->last_satd / (CLIP_DURATION(h->fenc->f_duration) / BASE_FRAME_DURATION);  
  186.             rcc->short_term_cplxcount ++;  
  187.   
  188.             rce.tex_bits = rcc->last_satd;  
  189.             //计算图像的模糊复杂度  
  190.             rce.blurred_complexity = rcc->short_term_cplxsum / rcc->short_term_cplxcount;  
  191.             rce.mv_bits = 0;  
  192.             rce.p_count = rcc->nmb;  
  193.             rce.i_count = 0;  
  194.             rce.s_count = 0;  
  195.             rce.qscale = 1;  
  196.             rce.pict_type = pict_type;  
  197.             rce.i_duration = h->fenc->i_duration;  
  198.   
  199.             if( h->param.rc.i_rc_method == X264_RC_CRF )  
  200.             {  
  201.                 q = get_qscale( h, &rce, rcc->rate_factor_constant, h->fenc->i_frame );  
  202.             }  
  203.             else  
  204.             {  
  205.                 q = get_qscale( h, &rce, rcc->wanted_bits_window / rcc->cplxr_sum, h->fenc->i_frame );  
  206.   
  207.                 /* ABR code can potentially be counterproductive in CBR, so just don't bother. 
  208.                  * Don't run it if the frame complexity is zero either. */  
  209.                 if( !rcc->b_vbv_min_rate && rcc->last_satd )  
  210.                 {  
  211.                     // FIXME is it simpler to keep track of wanted_bits in ratecontrol_end?  
  212.                     int i_frame_done = h->i_frame + 1 - h->i_thread_frames;  
  213.                     double time_done = i_frame_done / rcc->fps;  
  214.                     if( h->param.b_vfr_input && i_frame_done > 0 )  
  215.                         time_done = ((double)(h->fenc->i_reordered_pts - h->i_reordered_pts_delay)) * h->param.i_timebase_num / h->param.i_timebase_den;  
  216.                     wanted_bits = time_done * rcc->bitrate;  
  217.                     if( wanted_bits > 0 )  
  218.                     {  
  219.                         //缓存区增长函数  
  220.                         abr_buffer *= X264_MAX( 1, sqrt( time_done ) );  
  221.                         overflow = x264_clip3f( 1.0 + (total_bits - wanted_bits) / abr_buffer, .5, 2 );  
  222.                         q *= overflow;  
  223.                     }  
  224.                 }  
  225.             }  
  226.   
  227.             //如果不是第一个I帧  
  228.             if( pict_type == SLICE_TYPE_I && h->param.i_keyint_max > 1  
  229.                 /* should test _next_ pict type, but that isn't decided yet */  
  230.                 && rcc->last_non_b_pict_type != SLICE_TYPE_I )  
  231.             {  
  232.                 q = qp2qscale( rcc->accum_p_qp / rcc->accum_p_norm );  
  233.                 q /= fabs( h->param.rc.f_ip_factor );  
  234.             }  
  235.             //否则如果不是第一帧  
  236.             else if( h->i_frame > 0 )  
  237.             {  
  238.                 if( h->param.rc.i_rc_method != X264_RC_CRF )  
  239.                 {  
  240.                     /* Asymmetric clipping, because symmetric would prevent 
  241.                      * overflow control in areas of rapidly oscillating complexity */  
  242.                     double lmin = rcc->last_qscale_for[pict_type] / rcc->lstep;  
  243.                     double lmax = rcc->last_qscale_for[pict_type] * rcc->lstep;  
  244.                     if( overflow > 1.1 && h->i_frame > 3 )  
  245.                         lmax *= rcc->lstep;  
  246.                     else if( overflow < 0.9 )  
  247.                         lmin /= rcc->lstep;  
  248.   
  249.                     q = x264_clip3f(q, lmin, lmax);  
  250.                 }  
  251.             }  
  252.             else if( h->param.rc.i_rc_method == X264_RC_CRF && rcc->qcompress != 1 )  
  253.             {  
  254.                 q = qp2qscale( ABR_INIT_QP ) / fabs( h->param.rc.f_ip_factor );  
  255.             }  
  256.             rcc->qp_novbv = qscale2qp( q );  
  257.   
  258.             //FIXME use get_diff_limited_q() ?  
  259.             q = clip_qscale( h, pict_type, q );  
  260.         }  
  261.   
  262.         rcc->last_qscale_for[pict_type] =  
  263.         rcc->last_qscale = q;  
  264.         //根据最后的qscale预测frame size  
  265.         if( !(rcc->b_2pass && !rcc->b_vbv) && h->fenc->i_frame == 0 )  
  266.             rcc->last_qscale_for[SLICE_TYPE_P] = q * fabs( h->param.rc.f_ip_factor );  
  267.   
  268.         if( rcc->b_2pass && rcc->b_vbv )  
  269.             rcc->frame_size_planned = qscale2bits(&rce, q);  
  270.         else  
  271.             rcc->frame_size_planned = predict_size( &rcc->pred[h->sh.i_type], q, rcc->last_satd );  
  272.   
  273.         /* Always use up the whole VBV in this case. */  
  274.         if( rcc->single_frame_vbv )  
  275.             rcc->frame_size_planned = rcc->buffer_rate;  
  276.         /* Limit planned size by MinCR */  
  277.         if( rcc->b_vbv )  
  278.             rcc->frame_size_planned = X264_MIN( rcc->frame_size_planned, rcc->frame_size_maximum );  
  279.         h->rc->frame_size_estimated = rcc->frame_size_planned;  
  280.         return q;  
  281.     }  
  282. }  

get_qscale
[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * modify the bitrate curve from pass1 for one frame 
  3.  * 码率控制部分的核心之一,另一个是rate_estimate_qscale 
  4.  * 1、按复杂度采用指数模型得到qscale 
  5.  * rcc->last_qscale = pow( rce->blurred_complexity, 1 - rcc->qcompress )/rate_factor 
  6.  * 2、根据复杂度和目标比特数调整qp 
  7.  * q /= rate_factor;    //rcc->wanted_bits_window / rcc->cplxr_sum 
  8.  * 3、在rate_estimate_qscale中,根据已编码帧的实际比特数和目标比特数的偏差再次调整qp 
  9.  */  
  10. static double get_qscale(x264_t *h, ratecontrol_entry_t *rce, double rate_factor, int frame_num)  
  11. {  
  12.     x264_ratecontrol_t *rcc= h->rc;  
  13.     x264_zone_t *zone = get_zone( h, frame_num );  
  14.     double q;  
  15.     if( h->param.rc.b_mb_tree )  
  16.     {  
  17.         double timescale = (double)h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;  
  18.         q = pow( BASE_FRAME_DURATION / CLIP_DURATION(rce->i_duration * timescale), 1 - h->param.rc.f_qcompress );  
  19.     }  
  20.     else  
  21.         q = pow( rce->blurred_complexity, 1 - rcc->qcompress );  
  22.   
  23.     // avoid NaN's in the rc_eq  
  24.     if( !isfinite(q) || rce->tex_bits + rce->mv_bits == 0 )  
  25.         q = rcc->last_qscale_for[rce->pict_type];  
  26.     else  
  27.     {  
  28.         rcc->last_rceq = q;  
  29.         q /= rate_factor;   //rcc->wanted_bits_window / rcc->cplxr_sum  
  30.         rcc->last_qscale = q;  
  31.     }  
  32.   
  33.     if( zone )  
  34.     {  
  35.         if( zone->b_force_qp )  
  36.             q = qp2qscale( zone->i_qp );  
  37.         else  
  38.             q /= zone->f_bitrate_factor;  
  39.     }  
  40.   
  41.     return q;  
  42. }  
clip_qscale
[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. // apply VBV constraints and clip qscale to between lmin and lmax  
  2. //按一阶模型根据satd估计分配的bits,结合vbv限制,修正qscale  
  3. static double clip_qscale( x264_t *h, int pict_type, double q )  
  4. {  
  5.     x264_ratecontrol_t *rcc = h->rc;  
  6.     double lmin = rcc->lmin[pict_type];  
  7.     double lmax = rcc->lmax[pict_type];  
  8.     if( rcc->rate_factor_max_increment )  
  9.         lmax = X264_MIN( lmax, qp2qscale( rcc->qp_novbv + rcc->rate_factor_max_increment ) );  
  10.     double q0 = q;  
  11.   
  12.     /* B-frames are not directly subject to VBV, 
  13.      * since they are controlled by the P-frames' QPs. */  
  14.   
  15.     if( rcc->b_vbv && rcc->last_satd > 0 )  
  16.     {  
  17.         double fenc_cpb_duration = (double)h->fenc->i_cpb_duration *  
  18.                                    h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;  
  19.         /* Lookahead VBV: raise the quantizer as necessary such that no frames in 
  20.          * the lookahead overflow and such that the buffer is in a reasonable state 
  21.          * by the end of the lookahead. */  
  22.         if( h->param.rc.i_lookahead )  
  23.         {  
  24.             int terminate = 0;  
  25.   
  26.             /* Avoid an infinite loop. */  
  27.             forint iterations = 0; iterations < 1000 && terminate != 3; iterations++ )  
  28.             {  
  29.                 double frame_q[3];  
  30.                 double cur_bits = predict_size( &rcc->pred[h->sh.i_type], q, rcc->last_satd );  
  31.                 double buffer_fill_cur = rcc->buffer_fill - cur_bits;  
  32.                 double target_fill;  
  33.                 double total_duration = 0;  
  34.                 double last_duration = fenc_cpb_duration;  
  35.                 frame_q[0] = h->sh.i_type == SLICE_TYPE_I ? q * h->param.rc.f_ip_factor : q;  
  36.                 frame_q[1] = frame_q[0] * h->param.rc.f_pb_factor;  
  37.                 frame_q[2] = frame_q[0] / h->param.rc.f_ip_factor;  
  38.   
  39.                 /* Loop over the planned future frames. */  
  40.                 forint j = 0; buffer_fill_cur >= 0 && buffer_fill_cur <= rcc->buffer_size; j++ )  
  41.                 {//如果未来几帧都按照这个qscale设置来编码的话,全都编码完会用掉多少buffer  
  42.                     total_duration += last_duration;  
  43.                     buffer_fill_cur += rcc->vbv_max_rate * last_duration;  
  44.                     int i_type = h->fenc->i_planned_type[j];  
  45.                     int i_satd = h->fenc->i_planned_satd[j];  
  46.                     if( i_type == X264_TYPE_AUTO )  
  47.                         break;  
  48.                     i_type = IS_X264_TYPE_I( i_type ) ? SLICE_TYPE_I : IS_X264_TYPE_B( i_type ) ? SLICE_TYPE_B : SLICE_TYPE_P;  
  49.                     cur_bits = predict_size( &rcc->pred[i_type], frame_q[i_type], i_satd );  
  50.                     buffer_fill_cur -= cur_bits;  
  51.                     last_duration = h->fenc->f_planned_cpb_duration[j];  
  52.                 }  
  53.                 /* Try to get to get the buffer at least 50% filled, but don't set an impossible goal. */  
  54.                 target_fill = X264_MIN( rcc->buffer_fill + total_duration * rcc->vbv_max_rate * 0.5, rcc->buffer_size * 0.5 );  
  55.                 if( buffer_fill_cur < target_fill )  
  56.                 {//zhanghui:如果达不到预期,就加大qscale??为什么,这样难道不会更小吗?  
  57.                     q *= 1.01;  
  58.                     terminate |= 1;  
  59.                     continue;  
  60.                 }  
  61.                 /* Try to get the buffer no more than 80% filled, but don't set an impossible goal. */  
  62.                 target_fill = x264_clip3f( rcc->buffer_fill - total_duration * rcc->vbv_max_rate * 0.5, rcc->buffer_size * 0.8, rcc->buffer_size );  
  63.                 if( rcc->b_vbv_min_rate && buffer_fill_cur > target_fill )  
  64.                 {//zhanghui:如果超过预期,就减小qscale??为什么?这样难道不会更大吗?  
  65.                     q /= 1.01;  
  66.                     terminate |= 2;  
  67.                     continue;  
  68.                 }  
  69.                 break;  
  70.             }  
  71.         }  
  72.         /* Fallback to old purely-reactive algorithm: no lookahead. */  
  73.         //if( h->param.rc.i_lookahead )  
  74.         else  
  75.         {  
  76.             if( ( pict_type == SLICE_TYPE_P ||  
  77.                 ( pict_type == SLICE_TYPE_I && rcc->last_non_b_pict_type == SLICE_TYPE_I ) ) &&  
  78.                 rcc->buffer_fill/rcc->buffer_size < 0.5 )  
  79.             {  
  80.                 q /= x264_clip3f( 2.0*rcc->buffer_fill/rcc->buffer_size, 0.5, 1.0 );  
  81.             }  
  82.   
  83.             /* Now a hard threshold to make sure the frame fits in VBV. 
  84.              * This one is mostly for I-frames. */  
  85.             double bits = predict_size( &rcc->pred[h->sh.i_type], q, rcc->last_satd );  
  86.             /* For small VBVs, allow the frame to use up the entire VBV. */  
  87.             double max_fill_factor = h->param.rc.i_vbv_buffer_size >= 5*h->param.rc.i_vbv_max_bitrate / rcc->fps ? 2 : 1;  
  88.             /* For single-frame VBVs, request that the frame use up the entire VBV. */  
  89.             double min_fill_factor = rcc->single_frame_vbv ? 1 : 2;  
  90.   
  91.             if( bits > rcc->buffer_fill/max_fill_factor )  
  92.             {  
  93.                 double qf = x264_clip3f( rcc->buffer_fill/(max_fill_factor*bits), 0.2, 1.0 );  
  94.                 q /= qf;  
  95.                 bits *= qf;  
  96.             }  
  97.             if( bits < rcc->buffer_rate/min_fill_factor )  
  98.             {  
  99.                 double qf = x264_clip3f( bits*min_fill_factor/rcc->buffer_rate, 0.001, 1.0 );  
  100.                 q *= qf;  
  101.             }  
  102.             q = X264_MAX( q0, q );  
  103.         }  
  104.   
  105.         /* Check B-frame complexity, and use up any bits that would 
  106.          * overflow before the next P-frame. */  
  107.         if( h->sh.i_type == SLICE_TYPE_P && !rcc->single_frame_vbv )  
  108.         {  
  109.             int nb = rcc->bframes;  
  110.             double bits = predict_size( &rcc->pred[h->sh.i_type], q, rcc->last_satd );  
  111.             double pbbits = bits;  
  112.             double bbits = predict_size( rcc->pred_b_from_p, q * h->param.rc.f_pb_factor, rcc->last_satd );  
  113.             double space;  
  114.             double bframe_cpb_duration = 0;  
  115.             double minigop_cpb_duration;  
  116.             forint i = 0; i < nb; i++ )  
  117.                 bframe_cpb_duration += h->fenc->f_planned_cpb_duration[i];  
  118.   
  119.             if( bbits * nb > bframe_cpb_duration * rcc->vbv_max_rate )  
  120.                 nb = 0;  
  121.             pbbits += nb * bbits;  
  122.   
  123.             minigop_cpb_duration = bframe_cpb_duration + fenc_cpb_duration;  
  124.             space = rcc->buffer_fill + minigop_cpb_duration*rcc->vbv_max_rate - rcc->buffer_size;  
  125.             if( pbbits < space )  
  126.             {  
  127.                 q *= X264_MAX( pbbits / space, bits / (0.5 * rcc->buffer_size) );  
  128.             }  
  129.             q = X264_MAX( q0/2, q );  
  130.         }  
  131.   
  132.         /* Apply MinCR and buffer fill restrictions */  
  133.         double bits = predict_size( &rcc->pred[h->sh.i_type], q, rcc->last_satd );  
  134.         double frame_size_maximum = X264_MIN( rcc->frame_size_maximum, X264_MAX( rcc->buffer_fill, 0.001 ) );  
  135.         if( bits > frame_size_maximum )  
  136.             q *= bits / frame_size_maximum;  
  137.   
  138.         if( !rcc->b_vbv_min_rate )  
  139.             q = X264_MAX( q0, q );  
  140.     }  
  141.   
  142.     if( lmin==lmax )  
  143.         return lmin;  
  144.     else if( rcc->b_2pass )  
  145.     {  
  146.         double min2 = log( lmin );  
  147.         double max2 = log( lmax );  
  148.         q = (log(q) - min2)/(max2-min2) - 0.5;  
  149.         q = 1.0/(1.0 + exp( -4*q ));  
  150.         q = q*(max2-min2) + min2;  
  151.         return exp( q );  
  152.     }  
  153.     else  
  154.         return x264_clip3f( q, lmin, lmax );  
  155. }  

accum_p_qp_update
[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. //更新h->rc->accum_p_qp的值  
  2. static void accum_p_qp_update( x264_t *h, float qp )  
  3. {  
  4.     x264_ratecontrol_t *rc = h->rc;  
  5.     rc->accum_p_qp   *= .95;  
  6.     rc->accum_p_norm *= .95;  
  7.     rc->accum_p_norm += 1;  
  8.     if( h->sh.i_type == SLICE_TYPE_I )  
  9.         rc->accum_p_qp += qp + rc->ip_offset;  
  10.     else  
  11.         rc->accum_p_qp += qp;  
  12. }  
x264_ratecontrol_qp
[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. //确定QP在规定范围内  
  2. int x264_ratecontrol_qp( x264_t *h )  
  3. {  
  4.     x264_emms();  
  5.     return x264_clip3( h->rc->qpm + 0.5f, h->param.rc.i_qp_min, h->param.rc.i_qp_max );  
  6. }  
x264_ratecontrol_mb_qp
[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. //自适应量化的作用在此体现  
  2. int x264_ratecontrol_mb_qp( x264_t *h )  
  3. {  
  4.     x264_emms();  
  5.     float qp = h->rc->qpm;  
  6.     if( h->param.rc.i_aq_mode )  
  7.     {  
  8.          /* MB-tree currently doesn't adjust quantizers in unreferenced frames. */  
  9.         float qp_offset = h->fdec->b_kept_as_ref ? h->fenc->f_qp_offset[h->mb.i_mb_xy] : h->fenc->f_qp_offset_aq[h->mb.i_mb_xy];  
  10.         /* Scale AQ's effect towards zero in emergency mode. */  
  11.         if( qp > QP_MAX_SPEC )  
  12.             qp_offset *= (QP_MAX - qp) / (QP_MAX - QP_MAX_SPEC);  
  13.         qp += qp_offset;  
  14.     }  
  15.     return x264_clip3( qp + 0.5f, h->param.rc.i_qp_min, h->param.rc.i_qp_max );  
  16. }  

x264_ratecontrol_mb
[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /* TODO: 
  2.  *  eliminate all use of qp in row ratecontrol: make it entirely qscale-based. 
  3.  *  make this function stop being needlessly O(N^2) 
  4.  *  update more often than once per row? */  
  5. //宏块级的码率控制?感觉更多的是根据缓冲区和framesize做一些增减,是以一行宏块为单位的  
  6. //为什么要在熵编码的最后部分,应该因为是要给下一行编码做指导,相当于模型的更新  
  7. int x264_ratecontrol_mb( x264_t *h, int bits )  
  8. {  
  9.     x264_ratecontrol_t *rc = h->rc;  
  10.     const int y = h->mb.i_mb_y;  
  11.     //这一行的qp  
  12.     h->fdec->i_row_bits[y] += bits;  
  13.     //加上这个qp,计算平均qp用,这个qp是被aq过的  
  14.     rc->qpa_aq += h->mb.i_qp;  
  15.     //没到这一行的结尾,返回  
  16.     if( h->mb.i_mb_x != h->mb.i_mb_width - 1 )  
  17.         return 0;  
  18.   
  19.     x264_emms();  
  20.     //aq之前,所有qp都一样,所以这样计算,用于算平均qp  
  21.     rc->qpa_rc += rc->qpm * h->mb.i_mb_width;  
  22.     //没有vbv,返回  
  23.     if( !rc->b_vbv )  
  24.         return 0;  
  25.   
  26.     float qscale = qp2qscale( rc->qpm );  
  27.     //重建帧,这一行的qp都一样,qscale也一样  
  28.     h->fdec->f_row_qp[y] = rc->qpm;  
  29.     h->fdec->f_row_qscale[y] = qscale;  
  30.     //根据这一行的satd,比特数,qscale更新predictor  
  31.     update_predictor( &rc->row_pred[0], qscale, h->fdec->i_row_satd[y], h->fdec->i_row_bits[y] );  
  32.     if( h->sh.i_type == SLICE_TYPE_P && rc->qpm < h->fref[0][0]->f_row_qp[y] )  
  33.         update_predictor( &rc->row_pred[1], qscale, h->fdec->i_row_satds[0][0][y], h->fdec->i_row_bits[y] );  
  34.   
  35.     /* update ratecontrol per-mbpair in MBAFF */  
  36.     if( SLICE_MBAFF && !(y&1) )  
  37.         return 0;  
  38.   
  39.     /* FIXME: We don't currently support the case where there's a slice 
  40.      * boundary in between. 
  41.      * slice一定是整行,其实一般也就是整个帧*/  
  42.     int can_reencode_row = h->sh.i_first_mb <= ((h->mb.i_mb_y - SLICE_MBAFF) * h->mb.i_mb_stride);  
  43.   
  44.     /* tweak quality based on difference from predicted size */  
  45.     //根据与预测大小的差距调整quality  
  46.     float prev_row_qp = h->fdec->f_row_qp[y];  
  47.     float qp_absolute_max = h->param.rc.i_qp_max;  
  48.     if( rc->rate_factor_max_increment )  
  49.         qp_absolute_max = X264_MIN( qp_absolute_max, rc->qp_novbv + rc->rate_factor_max_increment );  
  50.     float qp_max = X264_MIN( prev_row_qp + h->param.rc.i_qp_step, qp_absolute_max );  
  51.     float qp_min = X264_MAX( prev_row_qp - h->param.rc.i_qp_step, h->param.rc.i_qp_min );  
  52.     float step_size = 0.5f;  
  53.     float buffer_left_planned = rc->buffer_fill - rc->frame_size_planned;  
  54.     float slice_size_planned = h->param.b_sliced_threads ? rc->slice_size_planned : rc->frame_size_planned;  
  55.     float max_frame_error = X264_MAX( 0.05f, 1.0f / h->mb.i_mb_height );  
  56.     float size_of_other_slices = 0;  
  57.     if( h->param.b_sliced_threads )  
  58.     {  
  59.         float size_of_other_slices_planned = 0;  
  60.         forint i = 0; i < h->param.i_threads; i++ )  
  61.             if( h != h->thread[i] )  
  62.             {  
  63.                 size_of_other_slices += h->thread[i]->rc->frame_size_estimated;  
  64.                 size_of_other_slices_planned += h->thread[i]->rc->slice_size_planned;  
  65.             }  
  66.         float weight = rc->slice_size_planned / rc->frame_size_planned;  
  67.         size_of_other_slices = (size_of_other_slices - size_of_other_slices_planned) * weight + size_of_other_slices_planned;  
  68.     }  
  69.     if( y < h->i_threadslice_end-1 )  
  70.     {//没到最后一行  
  71.         /* B-frames shouldn't use lower QP than their reference frames. */  
  72.         if( h->sh.i_type == SLICE_TYPE_B )  
  73.         {  
  74.             qp_min = X264_MAX( qp_min, X264_MAX( h->fref[0][0]->f_row_qp[y+1], h->fref[1][0]->f_row_qp[y+1] ) );  
  75.             rc->qpm = X264_MAX( rc->qpm, qp_min );  
  76.         }  
  77.   
  78.         /* More threads means we have to be more cautious in letting ratecontrol use up extra bits. */  
  79.         float rc_tol = buffer_left_planned / h->param.i_threads * rc->rate_tolerance;  
  80.         float b1 = predict_row_size_sum( h, y, rc->qpm ) + size_of_other_slices;//预测以当前qp编码下去的framesize  
  81.   
  82.         /* Don't increase the row QPs until a sufficent amount of the bits of the frame have been processed, in case a flat */  
  83.         /* area at the top of the frame was measured inaccurately. */  
  84.         if( row_bits_so_far( h, y ) < 0.05f * slice_size_planned )  
  85.             qp_max = qp_absolute_max = prev_row_qp;  
  86.         //不是I slice  
  87.         if( h->sh.i_type != SLICE_TYPE_I )  
  88.             rc_tol *= 0.5f;  
  89.   
  90.         if( !rc->b_vbv_min_rate )  
  91.             qp_min = X264_MAX( qp_min, rc->qp_novbv );  
  92.   
  93.         while( rc->qpm < qp_max   //不超过最大qp  
  94.                && ((b1 > rc->frame_size_planned + rc_tol) ||  //预计framesize超标  
  95.                    (rc->buffer_fill - b1 < buffer_left_planned * 0.5f) || //预计缓冲区不足  
  96.                    (b1 > rc->frame_size_planned && rc->qpm < rc->qp_novbv)) ) //预计framesize超标&&qp不超过qp_novbv  
  97.         {  
  98.             rc->qpm += step_size;  
  99.             b1 = predict_row_size_sum( h, y, rc->qpm ) + size_of_other_slices;  
  100.         }  
  101.   
  102.         while( rc->qpm > qp_min   //不低于最小qp  
  103.                && (rc->qpm > h->fdec->f_row_qp[0] || rc->single_frame_vbv)     
  104.                && ((b1 < rc->frame_size_planned * 0.8f && rc->qpm <= prev_row_qp)   //framesize比预期小太多,且当前行qp比前一行的qp小  
  105.                || b1 < (rc->buffer_fill - rc->buffer_size + rc->buffer_rate) * 1.1f) )    
  106.         {  
  107.             rc->qpm -= step_size;  
  108.             b1 = predict_row_size_sum( h, y, rc->qpm ) + size_of_other_slices;  
  109.         }  
  110.   
  111.         /* avoid VBV underflow or MinCR violation */  
  112.         while( (rc->qpm < qp_absolute_max)  
  113.                && ((rc->buffer_fill - b1 < rc->buffer_rate * max_frame_error) ||  
  114.                    (rc->frame_size_maximum - b1 < rc->frame_size_maximum * max_frame_error)))  
  115.         {  
  116.             rc->qpm += step_size;  
  117.             b1 = predict_row_size_sum( h, y, rc->qpm ) + size_of_other_slices;  
  118.         }  
  119.         //经过反复调整后的预期framesize  
  120.         h->rc->frame_size_estimated = b1 - size_of_other_slices;  
  121.   
  122.         /* If the current row was large enough to cause a large QP jump, try re-encoding it. */  
  123.         //经过各种调整的qp值过大,尝试重新编码  
  124.         if( rc->qpm > qp_max && prev_row_qp < qp_max && can_reencode_row )  
  125.         {  
  126.             /* Bump QP to halfway in between... close enough. */  
  127.             rc->qpm = x264_clip3f( (prev_row_qp + rc->qpm)*0.5f, prev_row_qp + 1.0f, qp_max );  
  128.             rc->qpa_rc = rc->qpa_rc_prev;  
  129.             rc->qpa_aq = rc->qpa_aq_prev;  
  130.             h->fdec->i_row_bits[y] = 0;  
  131.             h->fdec->i_row_bits[y-SLICE_MBAFF] = 0;  
  132.             return -1;  
  133.         }  
  134.     }  
  135.     else  
  136.     {//到了最后一行  
  137.         h->rc->frame_size_estimated = predict_row_size_sum( h, y, rc->qpm );  
  138.   
  139.         /* Last-ditch attempt: if the last row of the frame underflowed the VBV, 
  140.          * try again. 
  141.          * 如果最后一行导致VBV 下溢,尝试重新编码*/  
  142.         if( (h->rc->frame_size_estimated + size_of_other_slices) > (rc->buffer_fill - rc->buffer_rate * max_frame_error) &&  
  143.              rc->qpm < qp_max && can_reencode_row )  
  144.         {  
  145.             rc->qpm = qp_max;  
  146.             rc->qpa_rc = rc->qpa_rc_prev;  
  147.             rc->qpa_aq = rc->qpa_aq_prev;  
  148.             h->fdec->i_row_bits[y] = 0;  
  149.             h->fdec->i_row_bits[y-SLICE_MBAFF] = 0;  
  150.             return -1;  
  151.         }  
  152.     }  
  153.   
  154.     rc->qpa_rc_prev = rc->qpa_rc;  
  155.     rc->qpa_aq_prev = rc->qpa_aq;  
  156.   
  157.     return 0;  
  158. }  

update_predictor
[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. //更新frame size预测模型的系数  
  2. static void update_predictor( predictor_t *p, float q, float var, float bits )  
  3. {  
  4.     float range = 1.5;  
  5.     if( var < 10 )  
  6.         return;  
  7.     float old_coeff = p->coeff / p->count;  
  8.     float new_coeff = X264_MAX( bits*q / var, p->coeff_min );  
  9.     float new_coeff_clipped = x264_clip3f( new_coeff, old_coeff/range, old_coeff*range );  
  10.     float new_offset = bits*q - new_coeff_clipped * var;  
  11.     if( new_offset >= 0 )  
  12.         new_coeff = new_coeff_clipped;  
  13.     else  
  14.         new_offset = 0;  
  15.     p->count  *= p->decay;  
  16.     p->coeff  *= p->decay;  
  17.     p->offset *= p->decay;  
  18.     p->count  ++;  
  19.     p->coeff  += new_coeff;  
  20.     p->offset += new_offset;  
  21. }  
x264_ratecontrol_end
[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /* After encoding one frame, save stats and update ratecontrol state */  
  2. //编码一帧之后,保存数据,更新rc状态  
  3. int x264_ratecontrol_end( x264_t *h, int bits, int *filler )  
  4. {  
  5.     x264_ratecontrol_t *rc = h->rc;  
  6.     const int *mbs = h->stat.frame.i_mb_count;  
  7.   
  8.     x264_emms();  
  9.     //各个类型的帧计数  
  10.     h->stat.frame.i_mb_count_skip = mbs[P_SKIP] + mbs[B_SKIP];  
  11.     h->stat.frame.i_mb_count_i = mbs[I_16x16] + mbs[I_8x8] + mbs[I_4x4];  
  12.     h->stat.frame.i_mb_count_p = mbs[P_L0] + mbs[P_8x8];  
  13.     forint i = B_DIRECT; i < B_8x8; i++ )  
  14.         h->stat.frame.i_mb_count_p += mbs[i];  
  15.     //qp均值,crf均值  
  16.     h->fdec->f_qp_avg_rc = rc->qpa_rc /= h->mb.i_mb_count;  
  17.     h->fdec->f_qp_avg_aq = (float)rc->qpa_aq / h->mb.i_mb_count;  
  18.     h->fdec->f_crf_avg = h->param.rc.f_rf_constant + h->fdec->f_qp_avg_rc - rc->qp_novbv;  
  19.   
  20.     //输出stat  
  21.     if( h->param.rc.b_stat_write )  
  22.     {  
  23.         char c_type = h->sh.i_type==SLICE_TYPE_I ? (h->fenc->i_poc==0 ? 'I' : 'i')  
  24.                     : h->sh.i_type==SLICE_TYPE_P ? 'P'  
  25.                     : h->fenc->b_kept_as_ref ? 'B' : 'b';  
  26.         int dir_frame = h->stat.frame.i_direct_score[1] - h->stat.frame.i_direct_score[0];  
  27.         int dir_avg = h->stat.i_direct_score[1] - h->stat.i_direct_score[0];  
  28.         char c_direct = h->mb.b_direct_auto_write ?  
  29.                         ( dir_frame>0 ? 's' : dir_frame<0 ? 't' :  
  30.                           dir_avg>0 ? 's' : dir_avg<0 ? 't' : '-' )  
  31.                         : '-';  
  32.         if( fprintf( rc->p_stat_file_out,  
  33.                  "in:%d out:%d type:%c dur:%"PRId64" cpbdur:%"PRId64" q:%.2f aq:%.2f tex:%d mv:%d misc:%d imb:%d pmb:%d smb:%d d:%c ref:",  
  34.                  h->fenc->i_frame, h->i_frame,  
  35.                  c_type, h->fenc->i_duration,  
  36.                  h->fenc->i_cpb_duration,  
  37.                  rc->qpa_rc, h->fdec->f_qp_avg_aq,  
  38.                  h->stat.frame.i_tex_bits,  
  39.                  h->stat.frame.i_mv_bits,  
  40.                  h->stat.frame.i_misc_bits,  
  41.                  h->stat.frame.i_mb_count_i,  
  42.                  h->stat.frame.i_mb_count_p,  
  43.                  h->stat.frame.i_mb_count_skip,  
  44.                  c_direct) < 0 )  
  45.             goto fail;  
  46.   
  47.         /* Only write information for reference reordering once. */  
  48.         int use_old_stats = h->param.rc.b_stat_read && rc->rce->refs > 1;  
  49.         forint i = 0; i < (use_old_stats ? rc->rce->refs : h->i_ref[0]); i++ )  
  50.         {  
  51.             int refcount = use_old_stats         ? rc->rce->refcount[i]  
  52.                          : PARAM_INTERLACED      ? h->stat.frame.i_mb_count_ref[0][i*2]  
  53.                                                  + h->stat.frame.i_mb_count_ref[0][i*2+1]  
  54.                          :                         h->stat.frame.i_mb_count_ref[0][i];  
  55.             if( fprintf( rc->p_stat_file_out, "%d ", refcount ) < 0 )  
  56.                 goto fail;  
  57.         }  
  58.   
  59.         if( h->param.analyse.i_weighted_pred >= X264_WEIGHTP_SIMPLE && h->sh.weight[0][0].weightfn )  
  60.         {  
  61.             if( fprintf( rc->p_stat_file_out, "w:%d,%d,%d",  
  62.                          h->sh.weight[0][0].i_denom, h->sh.weight[0][0].i_scale, h->sh.weight[0][0].i_offset ) < 0 )  
  63.                 goto fail;  
  64.             if( h->sh.weight[0][1].weightfn || h->sh.weight[0][2].weightfn )  
  65.             {  
  66.                 if( fprintf( rc->p_stat_file_out, ",%d,%d,%d,%d,%d ",  
  67.                              h->sh.weight[0][1].i_denom, h->sh.weight[0][1].i_scale, h->sh.weight[0][1].i_offset,  
  68.                              h->sh.weight[0][2].i_scale, h->sh.weight[0][2].i_offset ) < 0 )  
  69.                     goto fail;  
  70.             }  
  71.             else if( fprintf( rc->p_stat_file_out, " " ) < 0 )  
  72.                 goto fail;  
  73.         }  
  74.   
  75.         if( fprintf( rc->p_stat_file_out, ";\n") < 0 )  
  76.             goto fail;  
  77.   
  78.         /* Don't re-write the data in multi-pass mode. */  
  79.         if( h->param.rc.b_mb_tree && h->fenc->b_kept_as_ref && !h->param.rc.b_stat_read )  
  80.         {  
  81.             uint8_t i_type = h->sh.i_type;  
  82.             /* Values are stored as big-endian FIX8.8 */  
  83.             forint i = 0; i < h->mb.i_mb_count; i++ )  
  84.                 rc->mbtree.qp_buffer[0][i] = endian_fix16( h->fenc->f_qp_offset[i]*256.0 );  
  85.             if( fwrite( &i_type, 1, 1, rc->p_mbtree_stat_file_out ) < 1 )  
  86.                 goto fail;  
  87.             if( fwrite( rc->mbtree.qp_buffer[0], sizeof(uint16_t), h->mb.i_mb_count, rc->p_mbtree_stat_file_out ) < h->mb.i_mb_count )  
  88.                 goto fail;  
  89.         }  
  90.     }  
  91.   
  92.     if( rc->b_abr )  
  93.     {  
  94.         //更新cplxr_sum和wanted_bits_window  
  95.         if( h->sh.i_type != SLICE_TYPE_B )  
  96.             rc->cplxr_sum += bits * qp2qscale( rc->qpa_rc ) / rc->last_rceq;  
  97.         else  
  98.         {  
  99.             /* Depends on the fact that B-frame's QP is an offset from the following P-frame's. 
  100.              * Not perfectly accurate with B-refs, but good enough. */  
  101.             rc->cplxr_sum += bits * qp2qscale( rc->qpa_rc ) / (rc->last_rceq * fabs( h->param.rc.f_pb_factor ));  
  102.         }  
  103.         rc->cplxr_sum *= rc->cbr_decay;  
  104.         rc->wanted_bits_window += h->fenc->f_duration * rc->bitrate;  
  105.         rc->wanted_bits_window *= rc->cbr_decay;  
  106.     }  
  107.   
  108.     if( rc->b_2pass )  
  109.         rc->expected_bits_sum += qscale2bits( rc->rce, qp2qscale( rc->rce->new_qp ) );  
  110.   
  111.     if( h->mb.b_variable_qp )  
  112.     {  
  113.         if( h->sh.i_type == SLICE_TYPE_B )  
  114.         {  
  115.             rc->bframe_bits += bits;  
  116.             if( h->fenc->b_last_minigop_bframe )  
  117.             {  
  118.                 update_predictor( rc->pred_b_from_p, qp2qscale( rc->qpa_rc ),  
  119.                                   h->fref[1][h->i_ref[1]-1]->i_satd, rc->bframe_bits / rc->bframes );  
  120.                 rc->bframe_bits = 0;  
  121.             }  
  122.         }  
  123.     }  
  124.   
  125.     //更新vbv  
  126.     *filler = update_vbv( h, bits );  
  127.     rc->filler_bits_sum += *filler * 8;  
  128.   
  129.     if( h->sps->vui.b_nal_hrd_parameters_present )  
  130.     {  
  131.         if( h->fenc->i_frame == 0 )  
  132.         {  
  133.             // access unit initialises the HRD  
  134.             h->fenc->hrd_timing.cpb_initial_arrival_time = 0;  
  135.             rc->initial_cpb_removal_delay = h->initial_cpb_removal_delay;  
  136.             rc->initial_cpb_removal_delay_offset = h->initial_cpb_removal_delay_offset;  
  137.             h->fenc->hrd_timing.cpb_removal_time = rc->nrt_first_access_unit = (double)rc->initial_cpb_removal_delay / 90000;  
  138.         }  
  139.         else  
  140.         {  
  141.             h->fenc->hrd_timing.cpb_removal_time = rc->nrt_first_access_unit + (double)(h->fenc->i_cpb_delay - h->i_cpb_delay_pir_offset) *  
  142.                                                    h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale;  
  143.   
  144.             if( h->fenc->b_keyframe )  
  145.             {  
  146.                 rc->nrt_first_access_unit = h->fenc->hrd_timing.cpb_removal_time;  
  147.                 rc->initial_cpb_removal_delay = h->initial_cpb_removal_delay;  
  148.                 rc->initial_cpb_removal_delay_offset = h->initial_cpb_removal_delay_offset;  
  149.             }  
  150.   
  151.             double cpb_earliest_arrival_time = h->fenc->hrd_timing.cpb_removal_time - (double)rc->initial_cpb_removal_delay / 90000;  
  152.             if( !h->fenc->b_keyframe )  
  153.                 cpb_earliest_arrival_time -= (double)rc->initial_cpb_removal_delay_offset / 90000;  
  154.   
  155.             if( h->sps->vui.hrd.b_cbr_hrd )  
  156.                 h->fenc->hrd_timing.cpb_initial_arrival_time = rc->previous_cpb_final_arrival_time;  
  157.             else  
  158.                 h->fenc->hrd_timing.cpb_initial_arrival_time = X264_MAX( rc->previous_cpb_final_arrival_time, cpb_earliest_arrival_time );  
  159.         }  
  160.         int filler_bits = *filler ? X264_MAX( (FILLER_OVERHEAD - h->param.b_annexb), *filler )*8 : 0;  
  161.         // Equation C-6  
  162.         h->fenc->hrd_timing.cpb_final_arrival_time = rc->previous_cpb_final_arrival_time = h->fenc->hrd_timing.cpb_initial_arrival_time +  
  163.                                                      (double)(bits + filler_bits) / h->sps->vui.hrd.i_bit_rate_unscaled;  
  164.   
  165.         h->fenc->hrd_timing.dpb_output_time = (double)h->fenc->i_dpb_output_delay * h->sps->vui.i_num_units_in_tick / h->sps->vui.i_time_scale +  
  166.                                               h->fenc->hrd_timing.cpb_removal_time;  
  167.     }  
  168.   
  169.     return 0;  
  170. fail:  
  171.     x264_log( h, X264_LOG_ERROR, "ratecontrol_end: stats file could not be written to\n" );  
  172.     return -1;  
  173. }  
update_vbv
[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. // update VBV after encoding a frame  
  2. static int update_vbv( x264_t *h, int bits )  
  3. {  
  4.     int filler = 0;  
  5.     int bitrate = h->sps->vui.hrd.i_bit_rate_unscaled;  
  6.     x264_ratecontrol_t *rcc = h->rc;  
  7.     x264_ratecontrol_t *rct = h->thread[0]->rc;  
  8.     int64_t buffer_size = (int64_t)h->sps->vui.hrd.i_cpb_size_unscaled * h->sps->vui.i_time_scale;  
  9.   
  10.     if( rcc->last_satd >= h->mb.i_mb_count )   //为什么要把这两个比较  
  11.         update_predictor( &rct->pred[h->sh.i_type], qp2qscale( rcc->qpa_rc ), rcc->last_satd, bits );  
  12.   
  13.     if( !rcc->b_vbv )  
  14.         return filler;  
  15.   
  16.     uint64_t buffer_diff = (uint64_t)bits * h->sps->vui.i_time_scale;  
  17.     rct->buffer_fill_final -= buffer_diff;  
  18.     rct->buffer_fill_final_min -= buffer_diff;  
  19.   
  20.     if( rct->buffer_fill_final_min < 0 )  
  21.     {//underflow happens  
  22.         double underflow = (double)rct->buffer_fill_final_min / h->sps->vui.i_time_scale;  
  23.         if( rcc->rate_factor_max_increment && rcc->qpm >= rcc->qp_novbv + rcc->rate_factor_max_increment )  
  24.             x264_log( h, X264_LOG_DEBUG, "VBV underflow due to CRF-max (frame %d, %.0f bits)\n", h->i_frame, underflow );  
  25.         else  
  26.             x264_log( h, X264_LOG_WARNING, "VBV underflow (frame %d, %.0f bits)\n", h->i_frame, underflow );  
  27.         rct->buffer_fill_final =  
  28.         rct->buffer_fill_final_min = 0;  
  29.     }  
  30.   
  31.     if( h->param.i_avcintra_class )  
  32.         buffer_diff = buffer_size;  
  33.     else  
  34.         buffer_diff = (uint64_t)bitrate * h->sps->vui.i_num_units_in_tick * h->fenc->i_cpb_duration;  
  35.     rct->buffer_fill_final += buffer_diff;  
  36.     rct->buffer_fill_final_min += buffer_diff;  
  37.   
  38.     if( rct->buffer_fill_final > buffer_size )  
  39.     {  
  40.         if( h->param.rc.b_filler )  
  41.         {  
  42.             int64_t scale = (int64_t)h->sps->vui.i_time_scale * 8;  
  43.             filler = (rct->buffer_fill_final - buffer_size + scale - 1) / scale;  
  44.             bits = h->param.i_avcintra_class ? filler * 8 : X264_MAX( (FILLER_OVERHEAD - h->param.b_annexb), filler ) * 8;  
  45.             buffer_diff = (uint64_t)bits * h->sps->vui.i_time_scale;  
  46.             rct->buffer_fill_final -= buffer_diff;  
  47.             rct->buffer_fill_final_min -= buffer_diff;  
  48.         }  
  49.         else  
  50.         {  
  51.             rct->buffer_fill_final = X264_MIN( rct->buffer_fill_final, buffer_size );  
  52.             rct->buffer_fill_final_min = X264_MIN( rct->buffer_fill_final_min, buffer_size );  
  53.         }  
  54.     }  
  55.   
  56.     return filler;  
  57. }  

最后的x264_ratecontrol_summary和x264_ratecontrol_delete略。

一些补充内容
1、什么是Macroblock Tree
Macroblock Tree是一个基于macroblock的qp控制方法。MB Tree的工作原理类似于古典的qp compression,只不过qcomp处理的对象是整张frame而MB Tree针对的是每个MB进行处理。工作过程简单来说,是对于每个MB,向前预测一定数量的帧(该数量由rc-lookahead和keyint的较小值决定)中该MB被参考的情况,根据引用次数的多寡,决定对该MB使用何种大小的qp进行quantization。而qp的大小与被参考次数成反比,也就是说,对于被参考次数多的MB,264的解码器认为此对应于缓慢变化的场景,因此给与比较高的质量(比较低的qp数值)。至于视频的变化率与人眼感知能力的关系,这是一个基于主观测试的经验结果:视频变化率越大 人眼的敏感度越低,也就是说,人眼可以容忍快速变化场景的某些缺陷,但相对而言某些平滑场景的缺陷,人眼则相当敏感。注意此处说的平滑,指的是沿时间维度上场景的变化频率,而非普通意义上的像素域中的场景。

2、MBTree File
这是一个临时文件,记录了每个P帧中每个MB被参考的情况。

3、MB Tree的处理对象
据说目前mbtree只处理p frames的mb,同时也不支持bpyramid。还没有细看。

4、与Mbtree相关的参数
--qcomp qcomp有削弱mbtree强度的倾向,具体来说,qcomp的值越趋近于1(Constant Quantizer),mbtree的效力越差。
--rc-lookahead 决定mbtree向前预测的帧数。

5、x264中可以调整每个mb的qp的方式有2种
(1) 启动aq---这种方式会略微扰乱码率控制;
(2) 启用vbv---vbv和abr都是接近cbr的模式,vbv会逐行调整qp,码率控制会更准确一些;

6、rate_tolerance的单位是啥?没有单位,就是一个简单的相乘系数,double abr_buffer = 2 * rcc->rate_tolerance * rcc->bitrate;

7、rate_estimate_qscale中的total_bits事一直都有吗?不是,只有在2pass的时候才能通过stat文件读取到
  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
提供的源码资源涵盖了Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 适合毕业设计、课程设计作业。这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。 所有源码均经过严格测试,可以直接运行,可以放心下载使用。有任何使用问题欢迎随时与博主沟通,第一时间进行解答!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值