encoder.c
上传用户:lctgjx
上传日期:2022-06-04
资源大小:8887k
文件大小:88k
源码类别:

流媒体/Mpeg4/MP4

开发平台:

Visual C++

  1. /*****************************************************************************
  2.  * x264: h264 encoder
  3.  *****************************************************************************
  4.  * Copyright (C) 2003-2008 x264 project
  5.  *
  6.  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
  7.  *          Loren Merritt <lorenm@u.washington.edu>
  8.  *          Jason Garrett-Glaser <darkshikari@gmail.com>
  9.  *
  10.  * This program is free software; you can redistribute it and/or modify
  11.  * it under the terms of the GNU General Public License as published by
  12.  * the Free Software Foundation; either version 2 of the License, or
  13.  * (at your option) any later version.
  14.  *
  15.  * This program is distributed in the hope that it will be useful,
  16.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  18.  * GNU General Public License for more details.
  19.  *
  20.  * You should have received a copy of the GNU General Public License
  21.  * along with this program; if not, write to the Free Software
  22.  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111, USA.
  23.  *****************************************************************************/
  24. #include <math.h>
  25. #include "common/common.h"
  26. #include "common/cpu.h"
  27. #include "set.h"
  28. #include "analyse.h"
  29. #include "ratecontrol.h"
  30. #include "macroblock.h"
  31. #if VISUALIZE
  32. #include "common/visualize.h"
  33. #endif
  34. //#define DEBUG_MB_TYPE
  35. #define NALU_OVERHEAD 5 // startcode + NAL type costs 5 bytes per frame
  36. #define bs_write_ue bs_write_ue_big
  37. static int x264_encoder_frame_end( x264_t *h, x264_t *thread_current,
  38.                                    x264_nal_t **pp_nal, int *pi_nal,
  39.                                    x264_picture_t *pic_out );
  40. /****************************************************************************
  41.  *
  42.  ******************************* x264 libs **********************************
  43.  *
  44.  ****************************************************************************/
  45. static float x264_psnr( int64_t i_sqe, int64_t i_size )
  46. {
  47.     double f_mse = (double)i_sqe / ((double)65025.0 * (double)i_size);
  48.     if( f_mse <= 0.0000000001 ) /* Max 100dB */
  49.         return 100;
  50.     return (float)(-10.0 * log( f_mse ) / log( 10.0 ));
  51. }
  52. static void x264_frame_dump( x264_t *h )
  53. {
  54.     FILE *f = fopen( h->param.psz_dump_yuv, "r+b" );
  55.     int i, y;
  56.     if( !f )
  57.         return;
  58.     /* Write the frame in display order */
  59.     fseek( f, h->fdec->i_frame * h->param.i_height * h->param.i_width * 3/2, SEEK_SET );
  60.     for( i = 0; i < h->fdec->i_plane; i++ )
  61.         for( y = 0; y < h->param.i_height >> !!i; y++ )
  62.             fwrite( &h->fdec->plane[i][y*h->fdec->i_stride[i]], 1, h->param.i_width >> !!i, f );
  63.     fclose( f );
  64. }
  65. /* Fill "default" values */
  66. static void x264_slice_header_init( x264_t *h, x264_slice_header_t *sh,
  67.                                     x264_sps_t *sps, x264_pps_t *pps,
  68.                                     int i_idr_pic_id, int i_frame, int i_qp )
  69. {
  70.     x264_param_t *param = &h->param;
  71.     int i;
  72.     /* First we fill all field */
  73.     sh->sps = sps;
  74.     sh->pps = pps;
  75.     sh->i_first_mb  = 0;
  76.     sh->i_last_mb   = h->mb.i_mb_count - 1;
  77.     sh->i_pps_id    = pps->i_id;
  78.     sh->i_frame_num = i_frame;
  79.     sh->b_mbaff = h->param.b_interlaced;
  80.     sh->b_field_pic = 0;    /* no field support for now */
  81.     sh->b_bottom_field = 0; /* not yet used */
  82.     sh->i_idr_pic_id = i_idr_pic_id;
  83.     /* poc stuff, fixed later */
  84.     sh->i_poc_lsb = 0;
  85.     sh->i_delta_poc_bottom = 0;
  86.     sh->i_delta_poc[0] = 0;
  87.     sh->i_delta_poc[1] = 0;
  88.     sh->i_redundant_pic_cnt = 0;
  89.     if( !h->mb.b_direct_auto_read )
  90.     {
  91.         if( h->mb.b_direct_auto_write )
  92.             sh->b_direct_spatial_mv_pred = ( h->stat.i_direct_score[1] > h->stat.i_direct_score[0] );
  93.         else
  94.             sh->b_direct_spatial_mv_pred = ( param->analyse.i_direct_mv_pred == X264_DIRECT_PRED_SPATIAL );
  95.     }
  96.     /* else b_direct_spatial_mv_pred was read from the 2pass statsfile */
  97.     sh->b_num_ref_idx_override = 0;
  98.     sh->i_num_ref_idx_l0_active = 1;
  99.     sh->i_num_ref_idx_l1_active = 1;
  100.     sh->b_ref_pic_list_reordering_l0 = h->b_ref_reorder[0];
  101.     sh->b_ref_pic_list_reordering_l1 = h->b_ref_reorder[1];
  102.     /* If the ref list isn't in the default order, construct reordering header */
  103.     /* List1 reordering isn't needed yet */
  104.     if( sh->b_ref_pic_list_reordering_l0 )
  105.     {
  106.         int pred_frame_num = i_frame;
  107.         for( i = 0; i < h->i_ref0; i++ )
  108.         {
  109.             int diff = h->fref0[i]->i_frame_num - pred_frame_num;
  110.             if( diff == 0 )
  111.                 x264_log( h, X264_LOG_ERROR, "diff frame num == 0n" );
  112.             sh->ref_pic_list_order[0][i].idc = ( diff > 0 );
  113.             sh->ref_pic_list_order[0][i].arg = abs( diff ) - 1;
  114.             pred_frame_num = h->fref0[i]->i_frame_num;
  115.         }
  116.     }
  117.     sh->i_cabac_init_idc = param->i_cabac_init_idc;
  118.     sh->i_qp = i_qp;
  119.     sh->i_qp_delta = i_qp - pps->i_pic_init_qp;
  120.     sh->b_sp_for_swidth = 0;
  121.     sh->i_qs_delta = 0;
  122.     /* If effective qp <= 15, deblocking would have no effect anyway */
  123.     if( param->b_deblocking_filter
  124.         && ( h->mb.b_variable_qp
  125.         || 15 < i_qp + 2 * X264_MIN(param->i_deblocking_filter_alphac0, param->i_deblocking_filter_beta) ) )
  126.     {
  127.         sh->i_disable_deblocking_filter_idc = 0;
  128.     }
  129.     else
  130.     {
  131.         sh->i_disable_deblocking_filter_idc = 1;
  132.     }
  133.     sh->i_alpha_c0_offset = param->i_deblocking_filter_alphac0 << 1;
  134.     sh->i_beta_offset = param->i_deblocking_filter_beta << 1;
  135. }
  136. static void x264_slice_header_write( bs_t *s, x264_slice_header_t *sh, int i_nal_ref_idc )
  137. {
  138.     int i;
  139.     if( sh->b_mbaff )
  140.     {
  141.         assert( sh->i_first_mb % (2*sh->sps->i_mb_width) == 0 );
  142.         bs_write_ue( s, sh->i_first_mb >> 1 );
  143.     }
  144.     else
  145.         bs_write_ue( s, sh->i_first_mb );
  146.     bs_write_ue( s, sh->i_type + 5 );   /* same type things */
  147.     bs_write_ue( s, sh->i_pps_id );
  148.     bs_write( s, sh->sps->i_log2_max_frame_num, sh->i_frame_num & ((1<<sh->sps->i_log2_max_frame_num)-1) );
  149.     if( !sh->sps->b_frame_mbs_only )
  150.     {
  151.         bs_write1( s, sh->b_field_pic );
  152.         if( sh->b_field_pic )
  153.             bs_write1( s, sh->b_bottom_field );
  154.     }
  155.     if( sh->i_idr_pic_id >= 0 ) /* NAL IDR */
  156.     {
  157.         bs_write_ue( s, sh->i_idr_pic_id );
  158.     }
  159.     if( sh->sps->i_poc_type == 0 )
  160.     {
  161.         bs_write( s, sh->sps->i_log2_max_poc_lsb, sh->i_poc_lsb & ((1<<sh->sps->i_log2_max_poc_lsb)-1) );
  162.         if( sh->pps->b_pic_order && !sh->b_field_pic )
  163.         {
  164.             bs_write_se( s, sh->i_delta_poc_bottom );
  165.         }
  166.     }
  167.     else if( sh->sps->i_poc_type == 1 && !sh->sps->b_delta_pic_order_always_zero )
  168.     {
  169.         bs_write_se( s, sh->i_delta_poc[0] );
  170.         if( sh->pps->b_pic_order && !sh->b_field_pic )
  171.         {
  172.             bs_write_se( s, sh->i_delta_poc[1] );
  173.         }
  174.     }
  175.     if( sh->pps->b_redundant_pic_cnt )
  176.     {
  177.         bs_write_ue( s, sh->i_redundant_pic_cnt );
  178.     }
  179.     if( sh->i_type == SLICE_TYPE_B )
  180.     {
  181.         bs_write1( s, sh->b_direct_spatial_mv_pred );
  182.     }
  183.     if( sh->i_type == SLICE_TYPE_P || sh->i_type == SLICE_TYPE_SP || sh->i_type == SLICE_TYPE_B )
  184.     {
  185.         bs_write1( s, sh->b_num_ref_idx_override );
  186.         if( sh->b_num_ref_idx_override )
  187.         {
  188.             bs_write_ue( s, sh->i_num_ref_idx_l0_active - 1 );
  189.             if( sh->i_type == SLICE_TYPE_B )
  190.             {
  191.                 bs_write_ue( s, sh->i_num_ref_idx_l1_active - 1 );
  192.             }
  193.         }
  194.     }
  195.     /* ref pic list reordering */
  196.     if( sh->i_type != SLICE_TYPE_I )
  197.     {
  198.         bs_write1( s, sh->b_ref_pic_list_reordering_l0 );
  199.         if( sh->b_ref_pic_list_reordering_l0 )
  200.         {
  201.             for( i = 0; i < sh->i_num_ref_idx_l0_active; i++ )
  202.             {
  203.                 bs_write_ue( s, sh->ref_pic_list_order[0][i].idc );
  204.                 bs_write_ue( s, sh->ref_pic_list_order[0][i].arg );
  205.             }
  206.             bs_write_ue( s, 3 );
  207.         }
  208.     }
  209.     if( sh->i_type == SLICE_TYPE_B )
  210.     {
  211.         bs_write1( s, sh->b_ref_pic_list_reordering_l1 );
  212.         if( sh->b_ref_pic_list_reordering_l1 )
  213.         {
  214.             for( i = 0; i < sh->i_num_ref_idx_l1_active; i++ )
  215.             {
  216.                 bs_write_ue( s, sh->ref_pic_list_order[1][i].idc );
  217.                 bs_write_ue( s, sh->ref_pic_list_order[1][i].arg );
  218.             }
  219.             bs_write_ue( s, 3 );
  220.         }
  221.     }
  222.     if( ( sh->pps->b_weighted_pred && ( sh->i_type == SLICE_TYPE_P || sh->i_type == SLICE_TYPE_SP ) ) ||
  223.         ( sh->pps->b_weighted_bipred == 1 && sh->i_type == SLICE_TYPE_B ) )
  224.     {
  225.         /* FIXME */
  226.     }
  227.     if( i_nal_ref_idc != 0 )
  228.     {
  229.         if( sh->i_idr_pic_id >= 0 )
  230.         {
  231.             bs_write1( s, 0 );  /* no output of prior pics flag */
  232.             bs_write1( s, 0 );  /* long term reference flag */
  233.         }
  234.         else
  235.         {
  236.             bs_write1( s, 0 );  /* adaptive_ref_pic_marking_mode_flag */
  237.         }
  238.     }
  239.     if( sh->pps->b_cabac && sh->i_type != SLICE_TYPE_I )
  240.     {
  241.         bs_write_ue( s, sh->i_cabac_init_idc );
  242.     }
  243.     bs_write_se( s, sh->i_qp_delta );      /* slice qp delta */
  244.     if( sh->pps->b_deblocking_filter_control )
  245.     {
  246.         bs_write_ue( s, sh->i_disable_deblocking_filter_idc );
  247.         if( sh->i_disable_deblocking_filter_idc != 1 )
  248.         {
  249.             bs_write_se( s, sh->i_alpha_c0_offset >> 1 );
  250.             bs_write_se( s, sh->i_beta_offset >> 1 );
  251.         }
  252.     }
  253. }
  254. /* If we are within a reasonable distance of the end of the memory allocated for the bitstream, */
  255. /* reallocate, adding an arbitrary amount of space (100 kilobytes). */
  256. static int x264_bitstream_check_buffer( x264_t *h )
  257. {
  258.     uint8_t *bs_bak = h->out.p_bitstream;
  259.     if( ( h->param.b_cabac && (h->cabac.p_end - h->cabac.p < 2500) )
  260.      || ( h->out.bs.p_end - h->out.bs.p < 2500 ) )
  261.     {
  262.         intptr_t delta;
  263.         int i;
  264.         h->out.i_bitstream += 100000;
  265.         CHECKED_MALLOC( h->out.p_bitstream, h->out.i_bitstream );
  266.         h->mc.memcpy_aligned( h->out.p_bitstream, bs_bak, (h->out.i_bitstream - 100000) & ~15 );
  267.         delta = h->out.p_bitstream - bs_bak;
  268.         h->out.bs.p_start += delta;
  269.         h->out.bs.p += delta;
  270.         h->out.bs.p_end = h->out.p_bitstream + h->out.i_bitstream;
  271.         h->cabac.p_start += delta;
  272.         h->cabac.p += delta;
  273.         h->cabac.p_end = h->out.p_bitstream + h->out.i_bitstream;
  274.         for( i = 0; i <= h->out.i_nal; i++ )
  275.             h->out.nal[i].p_payload += delta;
  276.         x264_free( bs_bak );
  277.     }
  278.     return 0;
  279. fail:
  280.     x264_free( bs_bak );
  281.     return -1;
  282. }
  283. /****************************************************************************
  284.  *
  285.  ****************************************************************************
  286.  ****************************** External API*********************************
  287.  ****************************************************************************
  288.  *
  289.  ****************************************************************************/
  290. static int x264_validate_parameters( x264_t *h )
  291. {
  292. //C程序不能中间定义变量 --@lia
  293. int max_slices;
  294. #ifdef HAVE_MMX
  295.     if( !(x264_cpu_detect() & X264_CPU_SSE) )
  296.     {
  297.         x264_log( h, X264_LOG_ERROR, "your cpu does not support SSE1, but x264 was compiled with asm supportn");
  298.         x264_log( h, X264_LOG_ERROR, "to run x264, recompile without asm support (configure --disable-asm)n");
  299.         return -1;
  300.     }
  301. #endif
  302.     if( h->param.i_width <= 0 || h->param.i_height <= 0 )
  303.     {
  304.         x264_log( h, X264_LOG_ERROR, "invalid width x height (%dx%d)n",
  305.                   h->param.i_width, h->param.i_height );
  306.         return -1;
  307.     }
  308.     if( h->param.i_width % 2 || h->param.i_height % 2 )
  309.     {
  310.         x264_log( h, X264_LOG_ERROR, "width or height not divisible by 2 (%dx%d)n",
  311.                   h->param.i_width, h->param.i_height );
  312.         return -1;
  313.     }
  314.     if( h->param.i_csp != X264_CSP_I420 )
  315.     {
  316.         x264_log( h, X264_LOG_ERROR, "invalid CSP (only I420 supported)n" );
  317.         return -1;
  318.     }
  319.     if( h->param.i_threads == X264_THREADS_AUTO )
  320.         h->param.i_threads = x264_cpu_num_processors() * 3/2;
  321.     h->param.i_threads = x264_clip3( h->param.i_threads, 1, X264_THREAD_MAX );
  322.     if( h->param.i_threads > 1 )
  323.     {
  324. #ifndef HAVE_PTHREAD
  325.         x264_log( h, X264_LOG_WARNING, "not compiled with pthread support!n");
  326.         h->param.i_threads = 1;
  327. #endif
  328.     }
  329.     if( h->param.b_interlaced )
  330.     {
  331.         if( h->param.analyse.i_me_method >= X264_ME_ESA )
  332.         {
  333.             x264_log( h, X264_LOG_WARNING, "interlace + me=esa is not implementedn" );
  334.             h->param.analyse.i_me_method = X264_ME_UMH;
  335.         }
  336.         if( h->param.analyse.i_direct_mv_pred > X264_DIRECT_PRED_SPATIAL )
  337.         {
  338.             x264_log( h, X264_LOG_WARNING, "interlace + direct=temporal is not implementedn" );
  339.             h->param.analyse.i_direct_mv_pred = X264_DIRECT_PRED_SPATIAL;
  340.         }
  341.     }
  342.     /* Detect default ffmpeg settings and terminate with an error. */
  343.     {
  344.         int score = 0;
  345.         score += h->param.analyse.i_me_range == 0;
  346.         score += h->param.rc.i_qp_step == 3;
  347.         score += h->param.i_keyint_max == 12;
  348.         score += h->param.rc.i_qp_min == 2;
  349.         score += h->param.rc.i_qp_max == 31;
  350.         score += h->param.rc.f_qcompress == 0.5;
  351.         score += fabs(h->param.rc.f_ip_factor - 1.25) < 0.01;
  352.         score += fabs(h->param.rc.f_pb_factor - 1.25) < 0.01;
  353.         score += h->param.analyse.inter == 0 && h->param.analyse.i_subpel_refine == 8;
  354.         if( score >= 5 )
  355.         {
  356.             x264_log( h, X264_LOG_ERROR, "broken ffmpeg default settings detectedn" );
  357.             x264_log( h, X264_LOG_ERROR, "use an encoding preset (vpre)n" );
  358.             return -1;
  359.         }
  360.     }
  361.     if( h->param.rc.i_rc_method < 0 || h->param.rc.i_rc_method > 2 )
  362.     {
  363.         x264_log( h, X264_LOG_ERROR, "no ratecontrol method specifiedn" );
  364.         return -1;
  365.     }
  366.     h->param.rc.f_rf_constant = x264_clip3f( h->param.rc.f_rf_constant, 0, 51 );
  367.     h->param.rc.i_qp_constant = x264_clip3( h->param.rc.i_qp_constant, 0, 51 );
  368.     if( h->param.rc.i_rc_method == X264_RC_CRF )
  369.     {
  370.         h->param.rc.i_qp_constant = h->param.rc.f_rf_constant;
  371.         h->param.rc.i_bitrate = 0;
  372.     }
  373.     if( (h->param.rc.i_rc_method == X264_RC_CQP || h->param.rc.i_rc_method == X264_RC_CRF)
  374.         && h->param.rc.i_qp_constant == 0 )
  375.     {
  376.         h->mb.b_lossless = 1;
  377.         h->param.i_cqm_preset = X264_CQM_FLAT;
  378.         h->param.psz_cqm_file = NULL;
  379.         h->param.rc.i_rc_method = X264_RC_CQP;
  380.         h->param.rc.f_ip_factor = 1;
  381.         h->param.rc.f_pb_factor = 1;
  382.         h->param.analyse.b_psnr = 0;
  383.         h->param.analyse.b_ssim = 0;
  384.         h->param.analyse.i_chroma_qp_offset = 0;
  385.         h->param.analyse.i_trellis = 0;
  386.         h->param.analyse.b_fast_pskip = 0;
  387.         h->param.analyse.i_noise_reduction = 0;
  388.         h->param.analyse.f_psy_rd = 0;
  389.         h->param.i_bframe = 0;
  390.         /* 8x8dct is not useful at all in CAVLC lossless */
  391.         if( !h->param.b_cabac )
  392.             h->param.analyse.b_transform_8x8 = 0;
  393.     }
  394.     if( h->param.rc.i_rc_method == X264_RC_CQP )
  395.     {
  396.         float qp_p = h->param.rc.i_qp_constant;
  397.         float qp_i = qp_p - 6*log(h->param.rc.f_ip_factor)/log(2);
  398.         float qp_b = qp_p + 6*log(h->param.rc.f_pb_factor)/log(2);
  399.         h->param.rc.i_qp_min = x264_clip3( (int)(X264_MIN3( qp_p, qp_i, qp_b )), 0, 51 );
  400.         h->param.rc.i_qp_max = x264_clip3( (int)(X264_MAX3( qp_p, qp_i, qp_b ) + .999), 0, 51 );
  401.         h->param.rc.i_aq_mode = 0;
  402.         h->param.rc.b_mb_tree = 0;
  403.     }
  404.     h->param.rc.i_qp_max = x264_clip3( h->param.rc.i_qp_max, 0, 51 );
  405.     h->param.rc.i_qp_min = x264_clip3( h->param.rc.i_qp_min, 0, h->param.rc.i_qp_max );
  406.     if( ( h->param.i_width % 16 || h->param.i_height % 16 )
  407.         && h->param.i_height != 1080 && !h->mb.b_lossless )
  408.     {
  409.         // There's nothing special about 1080 in that the warning still applies to it,
  410.         // but chances are the user can't help it if his content is already 1080p,
  411.         // so there's no point in warning in that case.
  412.         x264_log( h, X264_LOG_WARNING,
  413.                   "width or height not divisible by 16 (%dx%d), compression will suffer.n",
  414.                   h->param.i_width, h->param.i_height );
  415.     }
  416.     
  417. //C程序不能中间定义变量 --@lia
  418. //int 
  419. max_slices = (h->param.i_height+((16<<h->param.b_interlaced)-1))/(16<<h->param.b_interlaced);
  420.     h->param.i_slice_count = x264_clip3( h->param.i_slice_count, 0, max_slices );
  421.     h->param.i_slice_max_size = X264_MAX( h->param.i_slice_max_size, 0 );
  422.     h->param.i_slice_max_mbs = X264_MAX( h->param.i_slice_max_mbs, 0 );
  423.     if( h->param.b_interlaced && h->param.i_slice_max_size )
  424.     {
  425.         x264_log( h, X264_LOG_WARNING, "interlaced + slice-max-size is not implementedn" );
  426.         h->param.i_slice_max_size = 0;
  427.     }
  428.     if( h->param.b_interlaced && h->param.i_slice_max_mbs )
  429.     {
  430.         x264_log( h, X264_LOG_WARNING, "interlaced + slice-max-mbs is not implementedn" );
  431.         h->param.i_slice_max_mbs = 0;
  432.     }
  433.     if( h->param.i_slice_max_mbs || h->param.i_slice_max_size )
  434.         h->param.i_slice_count = 0;
  435.     h->param.i_frame_reference = x264_clip3( h->param.i_frame_reference, 1, 16 );
  436.     if( h->param.i_keyint_max <= 0 )
  437.         h->param.i_keyint_max = 1;
  438.     if( h->param.i_scenecut_threshold < 0 )
  439.         h->param.i_scenecut_threshold = 0;
  440.     h->param.i_keyint_min = x264_clip3( h->param.i_keyint_min, 1, h->param.i_keyint_max/2+1 );
  441.     if( !h->param.analyse.i_subpel_refine && h->param.analyse.i_direct_mv_pred > X264_DIRECT_PRED_SPATIAL )
  442.     {
  443.         x264_log( h, X264_LOG_WARNING, "subme=0 + direct=temporal is not supportedn" );
  444.         h->param.analyse.i_direct_mv_pred = X264_DIRECT_PRED_SPATIAL;
  445.     }
  446.     h->param.i_bframe = x264_clip3( h->param.i_bframe, 0, X264_BFRAME_MAX );
  447.     if( h->param.i_keyint_max == 1 )
  448.         h->param.i_bframe = 0;
  449.     h->param.i_bframe_bias = x264_clip3( h->param.i_bframe_bias, -90, 100 );
  450.     h->param.b_bframe_pyramid = h->param.b_bframe_pyramid && h->param.i_bframe > 1;
  451.     if( !h->param.i_bframe )
  452.     {
  453.         h->param.i_bframe_adaptive = X264_B_ADAPT_NONE;
  454.         h->param.analyse.i_direct_mv_pred = 0;
  455.         h->param.analyse.b_weighted_bipred = 0;
  456.     }
  457.     h->param.rc.i_lookahead = x264_clip3( h->param.rc.i_lookahead, 0, X264_LOOKAHEAD_MAX );
  458.     {
  459.         int maxrate = X264_MAX( h->param.rc.i_vbv_max_bitrate, h->param.rc.i_bitrate );
  460.         float bufsize = maxrate ? (float)h->param.rc.i_vbv_buffer_size / maxrate : 0;
  461.         float fps = h->param.i_fps_num > 0 && h->param.i_fps_den > 0 ? (float) h->param.i_fps_num / h->param.i_fps_den : 25.0;
  462.         h->param.rc.i_lookahead = X264_MIN( h->param.rc.i_lookahead, X264_MAX( h->param.i_keyint_max, bufsize*fps ) );
  463.     }
  464.     h->param.rc.f_qcompress = x264_clip3f( h->param.rc.f_qcompress, 0.0, 1.0 );
  465.     if( !h->param.rc.i_lookahead || h->param.i_keyint_max == 1 || h->param.rc.f_qcompress == 1 )
  466.         h->param.rc.b_mb_tree = 0;
  467.     if( h->param.rc.b_stat_read )
  468.         h->param.rc.i_lookahead = 0;
  469. #ifdef HAVE_PTHREAD
  470.     if( h->param.i_sync_lookahead )
  471.         h->param.i_sync_lookahead = x264_clip3( h->param.i_sync_lookahead, h->param.i_threads + h->param.i_bframe, X264_LOOKAHEAD_MAX );
  472.     if( h->param.rc.b_stat_read || h->param.i_threads == 1 )
  473.         h->param.i_sync_lookahead = 0;
  474. #else
  475.     h->param.i_sync_lookahead = 0;
  476. #endif
  477.     h->mb.b_direct_auto_write = h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_AUTO
  478.                                 && h->param.i_bframe
  479.                                 && ( h->param.rc.b_stat_write || !h->param.rc.b_stat_read );
  480.     h->param.i_deblocking_filter_alphac0 = x264_clip3( h->param.i_deblocking_filter_alphac0, -6, 6 );
  481.     h->param.i_deblocking_filter_beta    = x264_clip3( h->param.i_deblocking_filter_beta, -6, 6 );
  482.     h->param.analyse.i_luma_deadzone[0] = x264_clip3( h->param.analyse.i_luma_deadzone[0], 0, 32 );
  483.     h->param.analyse.i_luma_deadzone[1] = x264_clip3( h->param.analyse.i_luma_deadzone[1], 0, 32 );
  484.     h->param.i_cabac_init_idc = x264_clip3( h->param.i_cabac_init_idc, 0, 2 );
  485.     if( h->param.i_cqm_preset < X264_CQM_FLAT || h->param.i_cqm_preset > X264_CQM_CUSTOM )
  486.         h->param.i_cqm_preset = X264_CQM_FLAT;
  487.     if( h->param.analyse.i_me_method < X264_ME_DIA ||
  488.         h->param.analyse.i_me_method > X264_ME_TESA )
  489.         h->param.analyse.i_me_method = X264_ME_HEX;
  490.     if( h->param.analyse.i_me_range < 4 )
  491.         h->param.analyse.i_me_range = 4;
  492.     if( h->param.analyse.i_me_range > 16 && h->param.analyse.i_me_method <= X264_ME_HEX )
  493.         h->param.analyse.i_me_range = 16;
  494.     if( h->param.analyse.i_me_method == X264_ME_TESA &&
  495.         (h->mb.b_lossless || h->param.analyse.i_subpel_refine <= 1) )
  496.         h->param.analyse.i_me_method = X264_ME_ESA;
  497.     h->param.analyse.i_subpel_refine = x264_clip3( h->param.analyse.i_subpel_refine, 0, 10 );
  498.     h->param.analyse.b_mixed_references = h->param.analyse.b_mixed_references && h->param.i_frame_reference > 1;
  499.     h->param.analyse.inter &= X264_ANALYSE_PSUB16x16|X264_ANALYSE_PSUB8x8|X264_ANALYSE_BSUB16x16|
  500.                               X264_ANALYSE_I4x4|X264_ANALYSE_I8x8;
  501.     h->param.analyse.intra &= X264_ANALYSE_I4x4|X264_ANALYSE_I8x8;
  502.     if( !(h->param.analyse.inter & X264_ANALYSE_PSUB16x16) )
  503.         h->param.analyse.inter &= ~X264_ANALYSE_PSUB8x8;
  504.     if( !h->param.analyse.b_transform_8x8 )
  505.     {
  506.         h->param.analyse.inter &= ~X264_ANALYSE_I8x8;
  507.         h->param.analyse.intra &= ~X264_ANALYSE_I8x8;
  508.     }
  509.     h->param.analyse.i_chroma_qp_offset = x264_clip3(h->param.analyse.i_chroma_qp_offset, -12, 12);
  510.     if( !h->param.b_cabac )
  511.         h->param.analyse.i_trellis = 0;
  512.     h->param.analyse.i_trellis = x264_clip3( h->param.analyse.i_trellis, 0, 2 );
  513.     if( !h->param.analyse.b_psy )
  514.     {
  515.         h->param.analyse.f_psy_rd = 0;
  516.         h->param.analyse.f_psy_trellis = 0;
  517.     }
  518.     if( !h->param.analyse.i_trellis )
  519.         h->param.analyse.f_psy_trellis = 0;
  520.     h->param.analyse.f_psy_rd = x264_clip3f( h->param.analyse.f_psy_rd, 0, 10 );
  521.     h->param.analyse.f_psy_trellis = x264_clip3f( h->param.analyse.f_psy_trellis, 0, 10 );
  522.     if( h->param.analyse.i_subpel_refine < 6 )
  523.         h->param.analyse.f_psy_rd = 0;
  524.     h->mb.i_psy_rd = FIX8( h->param.analyse.f_psy_rd );
  525.     /* Psy RDO increases overall quantizers to improve the quality of luma--this indirectly hurts chroma quality */
  526.     /* so we lower the chroma QP offset to compensate */
  527.     /* This can be triggered repeatedly on multiple calls to parameter_validate, but since encoding
  528.      * uses the pps chroma qp offset not the param chroma qp offset, this is not a problem. */
  529.     if( h->mb.i_psy_rd )
  530.         h->param.analyse.i_chroma_qp_offset -= h->param.analyse.f_psy_rd < 0.25 ? 1 : 2;
  531.     h->mb.i_psy_trellis = FIX8( h->param.analyse.f_psy_trellis / 4 );
  532.     /* Psy trellis has a similar effect. */
  533.     if( h->mb.i_psy_trellis )
  534.         h->param.analyse.i_chroma_qp_offset -= h->param.analyse.f_psy_trellis < 0.25 ? 1 : 2;
  535.     else
  536.         h->mb.i_psy_trellis = 0;
  537.     h->param.analyse.i_chroma_qp_offset = x264_clip3(h->param.analyse.i_chroma_qp_offset, -12, 12);
  538.     h->param.rc.i_aq_mode = x264_clip3( h->param.rc.i_aq_mode, 0, 2 );
  539.     h->param.rc.f_aq_strength = x264_clip3f( h->param.rc.f_aq_strength, 0, 3 );
  540.     if( h->param.rc.f_aq_strength == 0 )
  541.         h->param.rc.i_aq_mode = 0;
  542.     /* MB-tree requires AQ to be on, even if the strength is zero. */
  543.     if( !h->param.rc.i_aq_mode && h->param.rc.b_mb_tree )
  544.     {
  545.         h->param.rc.i_aq_mode = 1;
  546.         h->param.rc.f_aq_strength = 0;
  547.     }
  548.     if( h->param.rc.b_mb_tree && h->param.b_bframe_pyramid )
  549.     {
  550.         x264_log( h, X264_LOG_WARNING, "b-pyramid + mb-tree is not supportedn" );
  551.         h->param.b_bframe_pyramid = 0;
  552.     }
  553.     h->param.analyse.i_noise_reduction = x264_clip3( h->param.analyse.i_noise_reduction, 0, 1<<16 );
  554.     if( h->param.analyse.i_subpel_refine == 10 && (h->param.analyse.i_trellis != 2 || !h->param.rc.i_aq_mode) )
  555.         h->param.analyse.i_subpel_refine = 9;
  556.     {
  557.         const x264_level_t *l = x264_levels;
  558.         if( h->param.i_level_idc < 0 )
  559.         {
  560.             int maxrate_bak = h->param.rc.i_vbv_max_bitrate;
  561.             if( h->param.rc.i_rc_method == X264_RC_ABR && h->param.rc.i_vbv_buffer_size <= 0 )
  562.                 h->param.rc.i_vbv_max_bitrate = h->param.rc.i_bitrate * 2;
  563.             h->sps = h->sps_array;
  564.             x264_sps_init( h->sps, h->param.i_sps_id, &h->param );
  565.             do h->param.i_level_idc = l->level_idc;
  566.                 while( l[1].level_idc && x264_validate_levels( h, 0 ) && l++ );
  567.             h->param.rc.i_vbv_max_bitrate = maxrate_bak;
  568.         }
  569.         else
  570.         {
  571.             while( l->level_idc && l->level_idc != h->param.i_level_idc )
  572.                 l++;
  573.             if( l->level_idc == 0 )
  574.             {
  575.                 x264_log( h, X264_LOG_ERROR, "invalid level_idc: %dn", h->param.i_level_idc );
  576.                 return -1;
  577.             }
  578.         }
  579.         if( h->param.analyse.i_mv_range <= 0 )
  580.             h->param.analyse.i_mv_range = l->mv_range >> h->param.b_interlaced;
  581.         else
  582.             h->param.analyse.i_mv_range = x264_clip3(h->param.analyse.i_mv_range, 32, 512 >> h->param.b_interlaced);
  583.     }
  584.     if( h->param.i_threads > 1 )
  585.     {
  586.         int r = h->param.analyse.i_mv_range_thread;
  587.         int r2;
  588.         if( r <= 0 )
  589.         {
  590.             // half of the available space is reserved and divided evenly among the threads,
  591.             // the rest is allocated to whichever thread is far enough ahead to use it.
  592.             // reserving more space increases quality for some videos, but costs more time
  593.             // in thread synchronization.
  594.             int max_range = (h->param.i_height + X264_THREAD_HEIGHT) / h->param.i_threads - X264_THREAD_HEIGHT;
  595.             r = max_range / 2;
  596.         }
  597.         r = X264_MAX( r, h->param.analyse.i_me_range );
  598.         r = X264_MIN( r, h->param.analyse.i_mv_range );
  599.         // round up to use the whole mb row
  600.         r2 = (r & ~15) + ((-X264_THREAD_HEIGHT) & 15);
  601.         if( r2 < r )
  602.             r2 += 16;
  603.         x264_log( h, X264_LOG_DEBUG, "using mv_range_thread = %dn", r2 );
  604.         h->param.analyse.i_mv_range_thread = r2;
  605.     }
  606.     if( h->param.rc.f_qblur < 0 )
  607.         h->param.rc.f_qblur = 0;
  608.     if( h->param.rc.f_complexity_blur < 0 )
  609.         h->param.rc.f_complexity_blur = 0;
  610.     h->param.i_sps_id &= 31;
  611.     if( h->param.i_log_level < X264_LOG_INFO )
  612.     {
  613.         h->param.analyse.b_psnr = 0;
  614.         h->param.analyse.b_ssim = 0;
  615.     }
  616.     /* ensure the booleans are 0 or 1 so they can be used in math */
  617. #define BOOLIFY(x) h->param.x = !!h->param.x
  618.     BOOLIFY( b_cabac );
  619.     BOOLIFY( b_deblocking_filter );
  620.     BOOLIFY( b_interlaced );
  621.     BOOLIFY( analyse.b_transform_8x8 );
  622.     BOOLIFY( analyse.b_chroma_me );
  623.     BOOLIFY( analyse.b_fast_pskip );
  624.     BOOLIFY( rc.b_stat_write );
  625.     BOOLIFY( rc.b_stat_read );
  626.     BOOLIFY( rc.b_mb_tree );
  627. #undef BOOLIFY
  628.     return 0;
  629. }
  630. static void mbcmp_init( x264_t *h )
  631. {
  632.     int satd = !h->mb.b_lossless && h->param.analyse.i_subpel_refine > 1;
  633.     memcpy( h->pixf.mbcmp, satd ? h->pixf.satd : h->pixf.sad_aligned, sizeof(h->pixf.mbcmp) );
  634.     memcpy( h->pixf.mbcmp_unaligned, satd ? h->pixf.satd : h->pixf.sad, sizeof(h->pixf.mbcmp_unaligned) );
  635.     h->pixf.intra_mbcmp_x3_16x16 = satd ? h->pixf.intra_satd_x3_16x16 : h->pixf.intra_sad_x3_16x16;
  636.     h->pixf.intra_mbcmp_x3_8x8c = satd ? h->pixf.intra_satd_x3_8x8c : h->pixf.intra_sad_x3_8x8c;
  637.     h->pixf.intra_mbcmp_x3_4x4 = satd ? h->pixf.intra_satd_x3_4x4 : h->pixf.intra_sad_x3_4x4;
  638.     satd &= h->param.analyse.i_me_method == X264_ME_TESA;
  639.     memcpy( h->pixf.fpelcmp, satd ? h->pixf.satd : h->pixf.sad, sizeof(h->pixf.fpelcmp) );
  640.     memcpy( h->pixf.fpelcmp_x3, satd ? h->pixf.satd_x3 : h->pixf.sad_x3, sizeof(h->pixf.fpelcmp_x3) );
  641.     memcpy( h->pixf.fpelcmp_x4, satd ? h->pixf.satd_x4 : h->pixf.sad_x4, sizeof(h->pixf.fpelcmp_x4) );
  642. }
  643. static void x264_set_aspect_ratio( x264_t *h, x264_param_t *param, int initial )
  644. {
  645.     /* VUI */
  646.     if( param->vui.i_sar_width > 0 && param->vui.i_sar_height > 0 )
  647.     {
  648.         int i_w = param->vui.i_sar_width;
  649.         int i_h = param->vui.i_sar_height;
  650.         int old_w = h->param.vui.i_sar_width;
  651.         int old_h = h->param.vui.i_sar_height;
  652.         x264_reduce_fraction( &i_w, &i_h );
  653.         while( i_w > 65535 || i_h > 65535 )
  654.         {
  655.             i_w /= 2;
  656.             i_h /= 2;
  657.         }
  658.         if( i_w != old_w || i_h != old_h || initial )
  659.         {
  660.             h->param.vui.i_sar_width = 0;
  661.             h->param.vui.i_sar_height = 0;
  662.             if( i_w == 0 || i_h == 0 )
  663.                 x264_log( h, X264_LOG_WARNING, "cannot create valid sample aspect ration" );
  664.             else
  665.             {
  666.                 x264_log( h, initial?X264_LOG_INFO:X264_LOG_DEBUG, "using SAR=%d/%dn", i_w, i_h );
  667.                 h->param.vui.i_sar_width = i_w;
  668.                 h->param.vui.i_sar_height = i_h;
  669.             }
  670.         }
  671.     }
  672. }
  673. /****************************************************************************
  674.  * x264_encoder_open:
  675.  ****************************************************************************/
  676. x264_t *x264_encoder_open( x264_param_t *param )
  677. {
  678.     x264_t *h;
  679.     char buf[1000], *p;
  680.     int i, qp, i_slicetype_length;
  681.     CHECKED_MALLOCZERO( h, sizeof(x264_t) );
  682.     /* Create a copy of param */
  683.     memcpy( &h->param, param, sizeof(x264_param_t) );
  684.     if( param->param_free )
  685.         param->param_free( param );
  686.     if( x264_validate_parameters( h ) < 0 )
  687.         goto fail;
  688.     if( h->param.psz_cqm_file )
  689.         if( x264_cqm_parse_file( h, h->param.psz_cqm_file ) < 0 )
  690.             goto fail;
  691.     if( h->param.rc.psz_stat_out )
  692.         h->param.rc.psz_stat_out = strdup( h->param.rc.psz_stat_out );
  693.     if( h->param.rc.psz_stat_in )
  694.         h->param.rc.psz_stat_in = strdup( h->param.rc.psz_stat_in );
  695.     x264_set_aspect_ratio( h, param, 1 );
  696.     x264_reduce_fraction( &h->param.i_fps_num, &h->param.i_fps_den );
  697.     /* Init x264_t */
  698.     h->i_frame = -1;
  699.     h->i_frame_num = 0;
  700.     h->i_idr_pic_id = 0;
  701.     h->sps = &h->sps_array[0];
  702.     x264_sps_init( h->sps, h->param.i_sps_id, &h->param );
  703.     h->pps = &h->pps_array[0];
  704.     x264_pps_init( h->pps, h->param.i_sps_id, &h->param, h->sps );
  705.     x264_validate_levels( h, 1 );
  706.     h->chroma_qp_table = i_chroma_qp_table + 12 + h->pps->i_chroma_qp_index_offset;
  707.     if( x264_cqm_init( h ) < 0 )
  708.         goto fail;
  709.     h->mb.i_mb_count = h->sps->i_mb_width * h->sps->i_mb_height;
  710.     /* Init frames. */
  711.     if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS )
  712.         h->frames.i_delay = X264_MAX(h->param.i_bframe,3)*4;
  713.     else
  714.         h->frames.i_delay = h->param.i_bframe;
  715.     if( h->param.rc.b_mb_tree || h->param.rc.i_vbv_buffer_size )
  716.         h->frames.i_delay = X264_MAX( h->frames.i_delay, h->param.rc.i_lookahead );
  717.     i_slicetype_length = h->frames.i_delay;
  718.     h->frames.i_delay += h->param.i_threads - 1;
  719.     h->frames.i_delay = X264_MIN( h->frames.i_delay, X264_LOOKAHEAD_MAX );
  720.     h->frames.i_delay += h->param.i_sync_lookahead;
  721.     h->frames.i_max_ref0 = h->param.i_frame_reference;
  722.     h->frames.i_max_ref1 = h->sps->vui.i_num_reorder_frames;
  723.     h->frames.i_max_dpb  = h->sps->vui.i_max_dec_frame_buffering;
  724.     h->frames.b_have_lowres = !h->param.rc.b_stat_read
  725.         && ( h->param.rc.i_rc_method == X264_RC_ABR
  726.           || h->param.rc.i_rc_method == X264_RC_CRF
  727.           || h->param.i_bframe_adaptive
  728.           || h->param.i_scenecut_threshold
  729.           || h->param.rc.b_mb_tree );
  730.     h->frames.b_have_lowres |= h->param.rc.b_stat_read && h->param.rc.i_vbv_buffer_size > 0;
  731.     h->frames.b_have_sub8x8_esa = !!(h->param.analyse.inter & X264_ANALYSE_PSUB8x8);
  732.     h->frames.i_last_idr = - h->param.i_keyint_max;
  733.     h->frames.i_input    = 0;
  734.     CHECKED_MALLOCZERO( h->frames.unused[0], (h->frames.i_delay + 3) * sizeof(x264_frame_t *) );
  735.     /* Allocate room for max refs plus a few extra just in case. */
  736.     CHECKED_MALLOCZERO( h->frames.unused[1], (h->param.i_threads + 20) * sizeof(x264_frame_t *) );
  737.     CHECKED_MALLOCZERO( h->frames.current, (h->param.i_sync_lookahead + h->param.i_bframe
  738.                         + h->param.i_threads + 3) * sizeof(x264_frame_t *) );
  739.     h->i_ref0 = 0;
  740.     h->i_ref1 = 0;
  741.     x264_rdo_init();
  742.     /* init CPU functions */
  743.     x264_predict_16x16_init( h->param.cpu, h->predict_16x16 );
  744.     x264_predict_8x8c_init( h->param.cpu, h->predict_8x8c );
  745.     x264_predict_8x8_init( h->param.cpu, h->predict_8x8, &h->predict_8x8_filter );
  746.     x264_predict_4x4_init( h->param.cpu, h->predict_4x4 );
  747.     if( !h->param.b_cabac )
  748.         x264_init_vlc_tables();
  749.     x264_pixel_init( h->param.cpu, &h->pixf );
  750.     x264_dct_init( h->param.cpu, &h->dctf );
  751.     x264_zigzag_init( h->param.cpu, &h->zigzagf, h->param.b_interlaced );
  752.     x264_mc_init( h->param.cpu, &h->mc );
  753.     x264_quant_init( h, h->param.cpu, &h->quantf );
  754.     x264_deblock_init( h->param.cpu, &h->loopf );
  755.     x264_dct_init_weights();
  756.     mbcmp_init( h );
  757.     p = buf + sprintf( buf, "using cpu capabilities:" );
  758.     for( i=0; x264_cpu_names[i].flags; i++ )
  759.     {
  760.         if( !strcmp(x264_cpu_names[i].name, "SSE2")
  761.             && param->cpu & (X264_CPU_SSE2_IS_FAST|X264_CPU_SSE2_IS_SLOW) )
  762.             continue;
  763.         if( !strcmp(x264_cpu_names[i].name, "SSE3")
  764.             && (param->cpu & X264_CPU_SSSE3 || !(param->cpu & X264_CPU_CACHELINE_64)) )
  765.             continue;
  766.         if( !strcmp(x264_cpu_names[i].name, "SSE4.1")
  767.             && (param->cpu & X264_CPU_SSE42) )
  768.             continue;
  769.         if( (param->cpu & x264_cpu_names[i].flags) == x264_cpu_names[i].flags
  770.             && (!i || x264_cpu_names[i].flags != x264_cpu_names[i-1].flags) )
  771.             p += sprintf( p, " %s", x264_cpu_names[i].name );
  772.     }
  773.     if( !param->cpu )
  774.         p += sprintf( p, " none!" );
  775.     x264_log( h, X264_LOG_INFO, "%sn", buf );
  776.     for( qp = h->param.rc.i_qp_min; qp <= h->param.rc.i_qp_max; qp++ )
  777.         if( x264_analyse_init_costs( h, qp ) )
  778.             goto fail;
  779.     if( x264_analyse_init_costs( h, X264_LOOKAHEAD_QP ) )
  780.         goto fail;
  781.     if( h->cost_mv[1][2013] != 24 )
  782.     {
  783.         x264_log( h, X264_LOG_ERROR, "MV cost test failed: x264 has been miscompiled!n" );
  784.         goto fail;
  785.     }
  786.     h->out.i_nal = 0;
  787.     h->out.i_bitstream = X264_MAX( 1000000, h->param.i_width * h->param.i_height * 4
  788.         * ( h->param.rc.i_rc_method == X264_RC_ABR ? pow( 0.95, h->param.rc.i_qp_min )
  789.           : pow( 0.95, h->param.rc.i_qp_constant ) * X264_MAX( 1, h->param.rc.f_ip_factor )));
  790.     CHECKED_MALLOC( h->nal_buffer, h->out.i_bitstream * 3/2 + 4 );
  791.     h->nal_buffer_size = h->out.i_bitstream * 3/2 + 4;
  792.     h->thread[0] = h;
  793.     h->i_thread_num = 0;
  794.     for( i = 1; i < h->param.i_threads + !!h->param.i_sync_lookahead; i++ )
  795.         CHECKED_MALLOC( h->thread[i], sizeof(x264_t) );
  796.     for( i = 0; i < h->param.i_threads; i++ )
  797.     {
  798.         if( i > 0 )
  799.             *h->thread[i] = *h;
  800.         h->thread[i]->fdec = x264_frame_pop_unused( h, 1 );
  801.         if( !h->thread[i]->fdec )
  802.             goto fail;
  803.         CHECKED_MALLOC( h->thread[i]->out.p_bitstream, h->out.i_bitstream );
  804.         /* Start each thread with room for 8 NAL units; it'll realloc later if needed. */
  805.         CHECKED_MALLOC( h->thread[i]->out.nal, 8*sizeof(x264_nal_t) );
  806.         h->thread[i]->out.i_nals_allocated = 8;
  807.         if( x264_macroblock_cache_init( h->thread[i] ) < 0 )
  808.             goto fail;
  809.     }
  810.     if( x264_lookahead_init( h, i_slicetype_length ) )
  811.         goto fail;
  812.     if( x264_ratecontrol_new( h ) < 0 )
  813.         goto fail;
  814.     if( h->param.psz_dump_yuv )
  815.     {
  816.         /* create or truncate the reconstructed video file */
  817.         FILE *f = fopen( h->param.psz_dump_yuv, "w" );
  818.         if( f )
  819.             fclose( f );
  820.         else
  821.         {
  822.             x264_log( h, X264_LOG_ERROR, "can't write to fdec.yuvn" );
  823.             goto fail;
  824.         }
  825.     }
  826.     x264_log( h, X264_LOG_INFO, "profile %s, level %d.%dn",
  827.         h->sps->i_profile_idc == PROFILE_BASELINE ? "Baseline" :
  828.         h->sps->i_profile_idc == PROFILE_MAIN ? "Main" :
  829.         h->sps->i_profile_idc == PROFILE_HIGH ? "High" :
  830.         "High 4:4:4 Predictive", h->sps->i_level_idc/10, h->sps->i_level_idc%10 );
  831.     return h;
  832. fail:
  833.     x264_free( h );
  834.     return NULL;
  835. }
  836. /****************************************************************************
  837.  * x264_encoder_reconfig:
  838.  ****************************************************************************/
  839. int x264_encoder_reconfig( x264_t *h, x264_param_t *param )
  840. {
  841.     h = h->thread[h->i_thread_phase%h->param.i_threads];
  842.     x264_set_aspect_ratio( h, param, 0 );
  843. #define COPY(var) h->param.var = param->var
  844.     COPY( i_frame_reference ); // but never uses more refs than initially specified
  845.     COPY( i_bframe_bias );
  846.     if( h->param.i_scenecut_threshold )
  847.         COPY( i_scenecut_threshold ); // can't turn it on or off, only vary the threshold
  848.     COPY( b_deblocking_filter );
  849.     COPY( i_deblocking_filter_alphac0 );
  850.     COPY( i_deblocking_filter_beta );
  851.     COPY( analyse.intra );
  852.     COPY( analyse.inter );
  853.     COPY( analyse.i_direct_mv_pred );
  854.     /* Scratch buffer prevents me_range from being increased for esa/tesa */
  855.     if( h->param.analyse.i_me_method < X264_ME_ESA || param->analyse.i_me_range < h->param.analyse.i_me_range )
  856.         COPY( analyse.i_me_range );
  857.     COPY( analyse.i_noise_reduction );
  858.     /* We can't switch out of subme=0 during encoding. */
  859.     if( h->param.analyse.i_subpel_refine )
  860.         COPY( analyse.i_subpel_refine );
  861.     COPY( analyse.i_trellis );
  862.     COPY( analyse.b_chroma_me );
  863.     COPY( analyse.b_dct_decimate );
  864.     COPY( analyse.b_fast_pskip );
  865.     COPY( analyse.b_mixed_references );
  866.     COPY( analyse.f_psy_rd );
  867.     COPY( analyse.f_psy_trellis );
  868.     // can only twiddle these if they were enabled to begin with:
  869.     if( h->param.analyse.i_me_method >= X264_ME_ESA || param->analyse.i_me_method < X264_ME_ESA )
  870.         COPY( analyse.i_me_method );
  871.     if( h->param.analyse.i_me_method >= X264_ME_ESA && !h->frames.b_have_sub8x8_esa )
  872.         h->param.analyse.inter &= ~X264_ANALYSE_PSUB8x8;
  873.     if( h->pps->b_transform_8x8_mode )
  874.         COPY( analyse.b_transform_8x8 );
  875.     if( h->frames.i_max_ref1 > 1 )
  876.         COPY( b_bframe_pyramid );
  877.     COPY( i_slice_max_size );
  878.     COPY( i_slice_max_mbs );
  879.     COPY( i_slice_count );
  880. #undef COPY
  881.     mbcmp_init( h );
  882.     return x264_validate_parameters( h );
  883. }
  884. /* internal usage */
  885. static void x264_nal_start( x264_t *h, int i_type, int i_ref_idc )
  886. {
  887.     x264_nal_t *nal = &h->out.nal[h->out.i_nal];
  888.     nal->i_ref_idc = i_ref_idc;
  889.     nal->i_type    = i_type;
  890.     nal->i_payload= 0;
  891.     nal->p_payload= &h->out.p_bitstream[bs_pos( &h->out.bs ) / 8];
  892. }
  893. static int x264_nal_end( x264_t *h )
  894. {
  895.     x264_nal_t *nal = &h->out.nal[h->out.i_nal];
  896.     nal->i_payload = &h->out.p_bitstream[bs_pos( &h->out.bs ) / 8] - nal->p_payload;
  897.     h->out.i_nal++;
  898.     /* if number of allocated nals is not enough, re-allocate a larger one. */
  899.     if( h->out.i_nal >= h->out.i_nals_allocated )
  900.     {
  901.         x264_nal_t *new_out = x264_malloc( sizeof(x264_nal_t) * (h->out.i_nals_allocated*2) );
  902.         if( !new_out )
  903.             return -1;
  904.         memcpy( new_out, h->out.nal, sizeof(x264_nal_t) * (h->out.i_nals_allocated) );
  905.         x264_free( h->out.nal );
  906.         h->out.nal = new_out;
  907.         h->out.i_nals_allocated *= 2;
  908.     }
  909.     return 0;
  910. }
  911. static int x264_encoder_encapsulate_nals( x264_t *h )
  912. {
  913.     int nal_size = 0, i;
  914. //C程序不能中间定义变量 --@lia
  915. uint8_t *nal_buffer;
  916.     for( i = 0; i < h->out.i_nal; i++ )
  917.         nal_size += h->out.nal[i].i_payload;
  918.     /* Worst-case NAL unit escaping: reallocate the buffer if it's too small. */
  919.     if( h->nal_buffer_size < nal_size * 3/2 + h->out.i_nal * 4 )
  920.     {
  921.         uint8_t *buf = x264_malloc( nal_size * 2 + h->out.i_nal * 4 );
  922.         if( !buf )
  923.             return -1;
  924.         x264_free( h->nal_buffer );
  925.         h->nal_buffer = buf;
  926.     }
  927.     //C程序不能中间定义变量 --@lia
  928. //uint8_t *
  929. nal_buffer = h->nal_buffer;
  930.     for( i = 0; i < h->out.i_nal; i++ )
  931.     {
  932.         int size = x264_nal_encode( nal_buffer, h->param.b_annexb, &h->out.nal[i] );
  933.         h->out.nal[i].i_payload = size;
  934.         h->out.nal[i].p_payload = nal_buffer;
  935.         nal_buffer += size;
  936.     }
  937.     return nal_buffer - h->nal_buffer;
  938. }
  939. /****************************************************************************
  940.  * x264_encoder_headers:
  941.  ****************************************************************************/
  942. int x264_encoder_headers( x264_t *h, x264_nal_t **pp_nal, int *pi_nal )
  943. {
  944.     int frame_size = 0;
  945.     /* init bitstream context */
  946.     h->out.i_nal = 0;
  947.     bs_init( &h->out.bs, h->out.p_bitstream, h->out.i_bitstream );
  948.     /* Write SEI, SPS and PPS. */
  949.     x264_nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
  950.     if( x264_sei_version_write( h, &h->out.bs ) )
  951.         return -1;
  952.     if( x264_nal_end( h ) )
  953.         return -1;
  954.     /* generate sequence parameters */
  955.     x264_nal_start( h, NAL_SPS, NAL_PRIORITY_HIGHEST );
  956.     x264_sps_write( &h->out.bs, h->sps );
  957.     if( x264_nal_end( h ) )
  958.         return -1;
  959.     /* generate picture parameters */
  960.     x264_nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
  961.     x264_pps_write( &h->out.bs, h->pps );
  962.     if( x264_nal_end( h ) )
  963.         return -1;
  964.     bs_flush( &h->out.bs );
  965.     frame_size = x264_encoder_encapsulate_nals( h );
  966.     /* now set output*/
  967.     *pi_nal = h->out.i_nal;
  968.     *pp_nal = &h->out.nal[0];
  969.     h->out.i_nal = 0;
  970.     return frame_size;
  971. }
  972. static inline void x264_reference_build_list( x264_t *h, int i_poc )
  973. {
  974.     int i;
  975.     int b_ok;
  976.     /* build ref list 0/1 */
  977.     h->i_ref0 = 0;
  978.     h->i_ref1 = 0;
  979.     for( i = 0; h->frames.reference[i]; i++ )
  980.     {
  981.         if( h->frames.reference[i]->i_poc < i_poc )
  982.         {
  983.             h->fref0[h->i_ref0++] = h->frames.reference[i];
  984.         }
  985.         else if( h->frames.reference[i]->i_poc > i_poc )
  986.         {
  987.             h->fref1[h->i_ref1++] = h->frames.reference[i];
  988.         }
  989.     }
  990.     /* Order ref0 from higher to lower poc */
  991.     do
  992.     {
  993.         b_ok = 1;
  994.         for( i = 0; i < h->i_ref0 - 1; i++ )
  995.         {
  996.             if( h->fref0[i]->i_poc < h->fref0[i+1]->i_poc )
  997.             {
  998.                 XCHG( x264_frame_t*, h->fref0[i], h->fref0[i+1] );
  999.                 b_ok = 0;
  1000.                 break;
  1001.             }
  1002.         }
  1003.     } while( !b_ok );
  1004.     /* Order ref1 from lower to higher poc (bubble sort) for B-frame */
  1005.     do
  1006.     {
  1007.         b_ok = 1;
  1008.         for( i = 0; i < h->i_ref1 - 1; i++ )
  1009.         {
  1010.             if( h->fref1[i]->i_poc > h->fref1[i+1]->i_poc )
  1011.             {
  1012.                 XCHG( x264_frame_t*, h->fref1[i], h->fref1[i+1] );
  1013.                 b_ok = 0;
  1014.                 break;
  1015.             }
  1016.         }
  1017.     } while( !b_ok );
  1018.     h->i_ref1 = X264_MIN( h->i_ref1, h->frames.i_max_ref1 );
  1019.     h->i_ref0 = X264_MIN( h->i_ref0, h->frames.i_max_ref0 );
  1020.     h->i_ref0 = X264_MIN( h->i_ref0, h->param.i_frame_reference ); // if reconfig() has lowered the limit
  1021.     assert( h->i_ref0 + h->i_ref1 <= 16 );
  1022.     h->mb.pic.i_fref[0] = h->i_ref0;
  1023.     h->mb.pic.i_fref[1] = h->i_ref1;
  1024. }
  1025. static void x264_fdec_filter_row( x264_t *h, int mb_y )
  1026. {
  1027.     /* mb_y is the mb to be encoded next, not the mb to be filtered here */
  1028.     int b_hpel = h->fdec->b_kept_as_ref;
  1029.     int b_deblock = !h->sh.i_disable_deblocking_filter_idc;
  1030.     int b_end = mb_y == h->sps->i_mb_height;
  1031.     int min_y = mb_y - (1 << h->sh.b_mbaff);
  1032.     int max_y = b_end ? h->sps->i_mb_height : mb_y;
  1033.     b_deblock &= b_hpel || h->param.psz_dump_yuv;
  1034.     if( mb_y & h->sh.b_mbaff )
  1035.         return;
  1036.     if( min_y < 0 )
  1037.         return;
  1038.     if( !b_end )
  1039.     {
  1040.         int i, j;
  1041.         for( j=0; j<=h->sh.b_mbaff; j++ )
  1042.             for( i=0; i<3; i++ )
  1043.             {
  1044.                 memcpy( h->mb.intra_border_backup[j][i],
  1045.                         h->fdec->plane[i] + ((mb_y*16 >> !!i) + j - 1 - h->sh.b_mbaff) * h->fdec->i_stride[i],
  1046.                         h->sps->i_mb_width*16 >> !!i );
  1047.             }
  1048.     }
  1049.     if( b_deblock )
  1050.     {
  1051.         int y;
  1052.         for( y = min_y; y < max_y; y += (1 << h->sh.b_mbaff) )
  1053.             x264_frame_deblock_row( h, y );
  1054.     }
  1055.     if( b_hpel )
  1056.     {
  1057.         x264_frame_expand_border( h, h->fdec, min_y, b_end );
  1058.         if( h->param.analyse.i_subpel_refine )
  1059.         {
  1060.             x264_frame_filter( h, h->fdec, min_y, b_end );
  1061.             x264_frame_expand_border_filtered( h, h->fdec, min_y, b_end );
  1062.         }
  1063.     }
  1064.     if( h->param.i_threads > 1 && h->fdec->b_kept_as_ref )
  1065.     {
  1066.         x264_frame_cond_broadcast( h->fdec, mb_y*16 + (b_end ? 10000 : -(X264_THREAD_HEIGHT << h->sh.b_mbaff)) );
  1067.     }
  1068.     min_y = X264_MAX( min_y*16-8, 0 );
  1069.     max_y = b_end ? h->param.i_height : mb_y*16-8;
  1070.     if( h->param.analyse.b_psnr )
  1071.     {
  1072.         int i;
  1073.         for( i=0; i<3; i++ )
  1074.             h->stat.frame.i_ssd[i] +=
  1075.                 x264_pixel_ssd_wxh( &h->pixf,
  1076.                     h->fdec->plane[i] + (min_y>>!!i) * h->fdec->i_stride[i], h->fdec->i_stride[i],
  1077.                     h->fenc->plane[i] + (min_y>>!!i) * h->fenc->i_stride[i], h->fenc->i_stride[i],
  1078.                     h->param.i_width >> !!i, (max_y-min_y) >> !!i );
  1079.     }
  1080.     if( h->param.analyse.b_ssim )
  1081.     {
  1082.         x264_emms();
  1083.         /* offset by 2 pixels to avoid alignment of ssim blocks with dct blocks,
  1084.          * and overlap by 4 */
  1085.         min_y += min_y == 0 ? 2 : -6;
  1086.         h->stat.frame.f_ssim +=
  1087.             x264_pixel_ssim_wxh( &h->pixf,
  1088.                 h->fdec->plane[0] + 2+min_y*h->fdec->i_stride[0], h->fdec->i_stride[0],
  1089.                 h->fenc->plane[0] + 2+min_y*h->fenc->i_stride[0], h->fenc->i_stride[0],
  1090.                 h->param.i_width-2, max_y-min_y, h->scratch_buffer );
  1091.     }
  1092. }
  1093. static inline int x264_reference_update( x264_t *h )
  1094. {
  1095.     if( !h->fdec->b_kept_as_ref )
  1096.     {
  1097.         if( h->param.i_threads > 1 )
  1098.         {
  1099.             x264_frame_push_unused( h, h->fdec );
  1100.             h->fdec = x264_frame_pop_unused( h, 1 );
  1101.             if( !h->fdec )
  1102.                 return -1;
  1103.         }
  1104.         return 0;
  1105.     }
  1106.     /* move frame in the buffer */
  1107.     x264_frame_push( h->frames.reference, h->fdec );
  1108.     if( h->frames.reference[h->frames.i_max_dpb] )
  1109.         x264_frame_push_unused( h, x264_frame_shift( h->frames.reference ) );
  1110.     h->fdec = x264_frame_pop_unused( h, 1 );
  1111.     if( !h->fdec )
  1112.         return -1;
  1113.     return 0;
  1114. }
  1115. static inline void x264_reference_reset( x264_t *h )
  1116. {
  1117.     while( h->frames.reference[0] )
  1118.         x264_frame_push_unused( h, x264_frame_pop( h->frames.reference ) );
  1119.     h->fdec->i_poc =
  1120.     h->fenc->i_poc = 0;
  1121. }
  1122. static inline void x264_slice_init( x264_t *h, int i_nal_type, int i_global_qp )
  1123. {
  1124.     /* ------------------------ Create slice header  ----------------------- */
  1125.     if( i_nal_type == NAL_SLICE_IDR )
  1126.     {
  1127.         x264_slice_header_init( h, &h->sh, h->sps, h->pps, h->i_idr_pic_id, h->i_frame_num, i_global_qp );
  1128.         /* increment id */
  1129.         h->i_idr_pic_id = ( h->i_idr_pic_id + 1 ) % 65536;
  1130.     }
  1131.     else
  1132.     {
  1133.         x264_slice_header_init( h, &h->sh, h->sps, h->pps, -1, h->i_frame_num, i_global_qp );
  1134.         /* always set the real higher num of ref frame used */
  1135.         h->sh.b_num_ref_idx_override = 1;
  1136.         h->sh.i_num_ref_idx_l0_active = h->i_ref0 <= 0 ? 1 : h->i_ref0;
  1137.         h->sh.i_num_ref_idx_l1_active = h->i_ref1 <= 0 ? 1 : h->i_ref1;
  1138.     }
  1139.     h->fdec->i_frame_num = h->sh.i_frame_num;
  1140.     if( h->sps->i_poc_type == 0 )
  1141.     {
  1142.         h->sh.i_poc_lsb = h->fdec->i_poc & ( (1 << h->sps->i_log2_max_poc_lsb) - 1 );
  1143.         h->sh.i_delta_poc_bottom = 0;   /* XXX won't work for field */
  1144.     }
  1145.     else if( h->sps->i_poc_type == 1 )
  1146.     {
  1147.         /* FIXME TODO FIXME */
  1148.     }
  1149.     else
  1150.     {
  1151.         /* Nothing to do ? */
  1152.     }
  1153.     x264_macroblock_slice_init( h );
  1154. }
  1155. static int x264_slice_write( x264_t *h )
  1156. {
  1157.     int i_skip;
  1158.     int mb_xy, i_mb_x, i_mb_y;
  1159.     int i, i_list, i_ref, i_skip_bak = 0; /* Shut up GCC. */
  1160.     bs_t bs_bak;
  1161.     x264_cabac_t cabac_bak;
  1162.     uint8_t cabac_prevbyte_bak = 0; /* Shut up GCC. */
  1163.     /* Assume no more than 3 bytes of NALU escaping. */
  1164.     int slice_max_size = h->param.i_slice_max_size > 0 ? (h->param.i_slice_max_size-3-NALU_OVERHEAD)*8 : INT_MAX;
  1165.     int starting_bits = bs_pos(&h->out.bs);
  1166.     /* Slice */
  1167.     x264_nal_start( h, h->i_nal_type, h->i_nal_ref_idc );
  1168.     /* Slice header */
  1169.     x264_slice_header_write( &h->out.bs, &h->sh, h->i_nal_ref_idc );
  1170.     if( h->param.b_cabac )
  1171.     {
  1172.         /* alignment needed */
  1173.         bs_align_1( &h->out.bs );
  1174.         /* init cabac */
  1175.         x264_cabac_context_init( &h->cabac, h->sh.i_type, h->sh.i_qp, h->sh.i_cabac_init_idc );
  1176.         x264_cabac_encode_init ( &h->cabac, h->out.bs.p, h->out.bs.p_end );
  1177.     }
  1178.     h->mb.i_last_qp = h->sh.i_qp;
  1179.     h->mb.i_last_dqp = 0;
  1180.     i_mb_y = h->sh.i_first_mb / h->sps->i_mb_width;
  1181.     i_mb_x = h->sh.i_first_mb % h->sps->i_mb_width;
  1182.     i_skip = 0;
  1183.     while( (mb_xy = i_mb_x + i_mb_y * h->sps->i_mb_width) <= h->sh.i_last_mb )
  1184.     {
  1185.         int mb_spos = bs_pos(&h->out.bs) + x264_cabac_pos(&h->cabac);
  1186. //C程序不能中间定义变量 --@lia
  1187. int total_bits,mb_size;
  1188.         if( h->param.i_slice_max_size > 0 )
  1189.         {
  1190.             /* We don't need the contexts because flushing the CABAC encoder has no context
  1191.              * dependency and macroblocks are only re-encoded in the case where a slice is
  1192.              * ended (and thus the content of all contexts are thrown away). */
  1193.             if( h->param.b_cabac )
  1194.             {
  1195.                 memcpy( &cabac_bak, &h->cabac, offsetof(x264_cabac_t, f8_bits_encoded) );
  1196.                 /* x264's CABAC writer modifies the previous byte during carry, so it has to be
  1197.                  * backed up. */
  1198.                 cabac_prevbyte_bak = h->cabac.p[-1];
  1199.             }
  1200.             else
  1201.             {
  1202.                 bs_bak = h->out.bs;
  1203.                 i_skip_bak = i_skip;
  1204.             }
  1205.         }
  1206.         if( i_mb_x == 0 && !h->mb.b_reencode_mb )
  1207.             x264_fdec_filter_row( h, i_mb_y );
  1208.         /* load cache */
  1209.         x264_macroblock_cache_load( h, i_mb_x, i_mb_y );
  1210.         x264_macroblock_analyse( h );
  1211.         /* encode this macroblock -> be careful it can change the mb type to P_SKIP if needed */
  1212.         x264_macroblock_encode( h );
  1213.         if( x264_bitstream_check_buffer( h ) )
  1214.             return -1;
  1215.         if( h->param.b_cabac )
  1216.         {
  1217.             if( mb_xy > h->sh.i_first_mb && !(h->sh.b_mbaff && (i_mb_y&1)) )
  1218.                 x264_cabac_encode_terminal( &h->cabac );
  1219.             if( IS_SKIP( h->mb.i_type ) )
  1220.                 x264_cabac_mb_skip( h, 1 );
  1221.             else
  1222.             {
  1223.                 if( h->sh.i_type != SLICE_TYPE_I )
  1224.                     x264_cabac_mb_skip( h, 0 );
  1225.                 x264_macroblock_write_cabac( h, &h->cabac );
  1226.             }
  1227.         }
  1228.         else
  1229.         {
  1230.             if( IS_SKIP( h->mb.i_type ) )
  1231.                 i_skip++;
  1232.             else
  1233.             {
  1234.                 if( h->sh.i_type != SLICE_TYPE_I )
  1235.                 {
  1236.                     bs_write_ue( &h->out.bs, i_skip );  /* skip run */
  1237.                     i_skip = 0;
  1238.                 }
  1239.                 x264_macroblock_write_cavlc( h, &h->out.bs );
  1240.             }
  1241.         }
  1242.         //C程序不能中间定义变量 --@lia
  1243. //int 
  1244. total_bits = bs_pos(&h->out.bs) + x264_cabac_pos(&h->cabac);
  1245.         //int 
  1246. mb_size = total_bits - mb_spos;
  1247.         /* We'll just re-encode this last macroblock if we go over the max slice size. */
  1248.         if( total_bits - starting_bits > slice_max_size && !h->mb.b_reencode_mb )
  1249.         {
  1250.             if( mb_xy != h->sh.i_first_mb )
  1251.             {
  1252.                 if( h->param.b_cabac )
  1253.                 {
  1254.                     memcpy( &h->cabac, &cabac_bak, offsetof(x264_cabac_t, f8_bits_encoded) );
  1255.                     h->cabac.p[-1] = cabac_prevbyte_bak;
  1256.                 }
  1257.                 else
  1258.                 {
  1259.                     h->out.bs = bs_bak;
  1260.                     i_skip = i_skip_bak;
  1261.                 }
  1262.                 h->mb.b_reencode_mb = 1;
  1263.                 h->sh.i_last_mb = mb_xy-1;
  1264.                 break;
  1265.             }
  1266.             else
  1267.             {
  1268.                 h->sh.i_last_mb = mb_xy;
  1269.                 h->mb.b_reencode_mb = 0;
  1270.             }
  1271.         }
  1272.         else
  1273.             h->mb.b_reencode_mb = 0;
  1274. #if VISUALIZE
  1275.         if( h->param.b_visualize )
  1276.             x264_visualize_mb( h );
  1277. #endif
  1278.         /* save cache */
  1279.         x264_macroblock_cache_save( h );
  1280.         /* accumulate mb stats */
  1281.         h->stat.frame.i_mb_count[h->mb.i_type]++;
  1282.         if( !IS_INTRA(h->mb.i_type) && !IS_SKIP(h->mb.i_type) && !IS_DIRECT(h->mb.i_type) )
  1283.         {
  1284.             if( h->mb.i_partition != D_8x8 )
  1285.                     h->stat.frame.i_mb_partition[h->mb.i_partition] += 4;
  1286.                 else
  1287.                     for( i = 0; i < 4; i++ )
  1288.                         h->stat.frame.i_mb_partition[h->mb.i_sub_partition[i]] ++;
  1289.             if( h->param.i_frame_reference > 1 )
  1290.                 for( i_list = 0; i_list <= (h->sh.i_type == SLICE_TYPE_B); i_list++ )
  1291.                     for( i = 0; i < 4; i++ )
  1292.                     {
  1293.                         i_ref = h->mb.cache.ref[i_list][ x264_scan8[4*i] ];
  1294.                         if( i_ref >= 0 )
  1295.                             h->stat.frame.i_mb_count_ref[i_list][i_ref] ++;
  1296.                     }
  1297.         }
  1298.         if( h->param.i_log_level >= X264_LOG_INFO )
  1299.         {
  1300.             if( h->mb.i_cbp_luma || h->mb.i_cbp_chroma )
  1301.             {
  1302.                 int cbpsum = (h->mb.i_cbp_luma&1) + ((h->mb.i_cbp_luma>>1)&1)
  1303.                            + ((h->mb.i_cbp_luma>>2)&1) + (h->mb.i_cbp_luma>>3);
  1304.                 int b_intra = IS_INTRA(h->mb.i_type);
  1305.                 h->stat.frame.i_mb_cbp[!b_intra + 0] += cbpsum;
  1306.                 h->stat.frame.i_mb_cbp[!b_intra + 2] += h->mb.i_cbp_chroma >= 1;
  1307.                 h->stat.frame.i_mb_cbp[!b_intra + 4] += h->mb.i_cbp_chroma == 2;
  1308.             }
  1309.             if( h->mb.i_cbp_luma && !IS_INTRA(h->mb.i_type) )
  1310.             {
  1311.                 h->stat.frame.i_mb_count_8x8dct[0] ++;
  1312.                 h->stat.frame.i_mb_count_8x8dct[1] += h->mb.b_transform_8x8;
  1313.             }
  1314.             if( IS_INTRA(h->mb.i_type) && h->mb.i_type != I_PCM )
  1315.             {
  1316.                 if( h->mb.i_type == I_16x16 )
  1317.                     h->stat.frame.i_mb_pred_mode[0][h->mb.i_intra16x16_pred_mode]++;
  1318.                 else if( h->mb.i_type == I_8x8 )
  1319.                     for( i = 0; i < 16; i += 4 )
  1320.                         h->stat.frame.i_mb_pred_mode[1][h->mb.cache.intra4x4_pred_mode[x264_scan8[i]]]++;
  1321.                 else //if( h->mb.i_type == I_4x4 )
  1322.                     for( i = 0; i < 16; i++ )
  1323.                         h->stat.frame.i_mb_pred_mode[2][h->mb.cache.intra4x4_pred_mode[x264_scan8[i]]]++;
  1324.             }
  1325.         }
  1326.         x264_ratecontrol_mb( h, mb_size );
  1327.         if( h->sh.b_mbaff )
  1328.         {
  1329.             i_mb_x += i_mb_y & 1;
  1330.             i_mb_y ^= i_mb_x < h->sps->i_mb_width;
  1331.         }
  1332.         else
  1333.             i_mb_x++;
  1334.         if( i_mb_x == h->sps->i_mb_width )
  1335.         {
  1336.             i_mb_y++;
  1337.             i_mb_x = 0;
  1338.         }
  1339.     }
  1340.     if( h->param.b_cabac )
  1341.     {
  1342.         x264_cabac_encode_flush( h, &h->cabac );
  1343.         h->out.bs.p = h->cabac.p;
  1344.     }
  1345.     else
  1346.     {
  1347.         if( i_skip > 0 )
  1348.             bs_write_ue( &h->out.bs, i_skip );  /* last skip run */
  1349.         /* rbsp_slice_trailing_bits */
  1350.         bs_rbsp_trailing( &h->out.bs );
  1351.         bs_flush( &h->out.bs );
  1352.     }
  1353.     if( x264_nal_end( h ) )
  1354.         return -1;
  1355.     if( h->sh.i_last_mb == h->mb.i_mb_count-1 )
  1356.     {
  1357.         h->stat.frame.i_misc_bits = bs_pos( &h->out.bs )
  1358.                                   + (h->out.i_nal*NALU_OVERHEAD * 8)
  1359.                                   - h->stat.frame.i_tex_bits
  1360.                                   - h->stat.frame.i_mv_bits;
  1361.         x264_fdec_filter_row( h, h->sps->i_mb_height );
  1362.     }
  1363.     return 0;
  1364. }
  1365. static void x264_thread_sync_context( x264_t *dst, x264_t *src )
  1366. {
  1367.     x264_frame_t **f;
  1368.     if( dst == src )
  1369.         return;
  1370.     // reference counting
  1371.     for( f = src->frames.reference; *f; f++ )
  1372.         (*f)->i_reference_count++;
  1373.     for( f = dst->frames.reference; *f; f++ )
  1374.         x264_frame_push_unused( src, *f );
  1375.     src->fdec->i_reference_count++;
  1376.     x264_frame_push_unused( src, dst->fdec );
  1377.     // copy everything except the per-thread pointers and the constants.
  1378.     memcpy( &dst->i_frame, &src->i_frame, offsetof(x264_t, mb.type) - offsetof(x264_t, i_frame) );
  1379.     dst->param = src->param;
  1380.     dst->stat = src->stat;
  1381. }
  1382. static void x264_thread_sync_stat( x264_t *dst, x264_t *src )
  1383. {
  1384.     if( dst == src )
  1385.         return;
  1386.     memcpy( &dst->stat.i_frame_count, &src->stat.i_frame_count, sizeof(dst->stat) - sizeof(dst->stat.frame) );
  1387. }
  1388. static void *x264_slices_write( x264_t *h )
  1389. {
  1390.     int i_slice_num = 0;
  1391.     if( h->param.i_sync_lookahead )
  1392.         x264_lower_thread_priority( 10 );
  1393. #ifdef HAVE_MMX
  1394.     /* Misalign mask has to be set separately for each thread. */
  1395.     if( h->param.cpu&X264_CPU_SSE_MISALIGN )
  1396.         x264_cpu_mask_misalign_sse();
  1397. #endif
  1398. #if VISUALIZE
  1399.     if( h->param.b_visualize )
  1400.         if( x264_visualize_init( h ) )
  1401.             return (void *)-1;
  1402. #endif
  1403.     /* init stats */
  1404.     memset( &h->stat.frame, 0, sizeof(h->stat.frame) );
  1405.     h->mb.b_reencode_mb = 0;
  1406.     while( h->sh.i_first_mb < h->mb.i_mb_count )
  1407.     {
  1408.         h->sh.i_last_mb = h->mb.i_mb_count - 1;
  1409.         if( h->param.i_slice_max_mbs )
  1410.             h->sh.i_last_mb = h->sh.i_first_mb + h->param.i_slice_max_mbs - 1;
  1411.         else if( h->param.i_slice_count )
  1412.         {
  1413.             //C程序不能中间定义变量 --@lia
  1414. double height;
  1415. int width;
  1416. x264_emms();
  1417.             i_slice_num++;
  1418.             //C程序不能中间定义变量 --@lia
  1419. //double 
  1420. height = h->sps->i_mb_height >> h->param.b_interlaced;
  1421.             //int 
  1422. width = h->sps->i_mb_width << h->param.b_interlaced;
  1423.             h->sh.i_last_mb = (int)(height * i_slice_num / h->param.i_slice_count + 0.5) * width - 1;
  1424.         }
  1425.         h->sh.i_last_mb = X264_MIN( h->sh.i_last_mb, h->mb.i_mb_count - 1 );
  1426.         if( x264_stack_align( x264_slice_write, h ) )
  1427.             return (void *)-1;
  1428.         h->sh.i_first_mb = h->sh.i_last_mb + 1;
  1429.     }
  1430. #if VISUALIZE
  1431.     if( h->param.b_visualize )
  1432.     {
  1433.         x264_visualize_show( h );
  1434.         x264_visualize_close( h );
  1435.     }
  1436. #endif
  1437.     return (void *)0;
  1438. }
  1439. /****************************************************************************
  1440.  * x264_encoder_encode:
  1441.  *  XXX: i_poc   : is the poc of the current given picture
  1442.  *       i_frame : is the number of the frame being coded
  1443.  *  ex:  type frame poc
  1444.  *       I      0   2*0
  1445.  *       P      1   2*3
  1446.  *       B      2   2*1
  1447.  *       B      3   2*2
  1448.  *       P      4   2*6
  1449.  *       B      5   2*4
  1450.  *       B      6   2*5
  1451.  ****************************************************************************/
  1452. int     x264_encoder_encode( x264_t *h,
  1453.                              x264_nal_t **pp_nal, int *pi_nal,
  1454.                              x264_picture_t *pic_in,
  1455.                              x264_picture_t *pic_out )
  1456. {
  1457.     x264_t *thread_current, *thread_prev, *thread_oldest;
  1458.     int     i_nal_type, i;
  1459.     int     i_nal_ref_idc;
  1460.     int   i_global_qp;
  1461. //C程序不能中间定义变量 --@lia
  1462. int overhead;
  1463.     if( h->param.i_threads > 1)
  1464.     {
  1465.         int i = ++h->i_thread_phase;
  1466.         int t = h->param.i_threads;
  1467.         thread_current = h->thread[ i%t ];
  1468.         thread_prev    = h->thread[ (i-1)%t ];
  1469.         thread_oldest  = h->thread[ (i+1)%t ];
  1470.         x264_thread_sync_context( thread_current, thread_prev );
  1471.         x264_thread_sync_ratecontrol( thread_current, thread_prev, thread_oldest );
  1472.         h = thread_current;
  1473. //      fprintf(stderr, "current: %p  prev: %p  oldest: %p n", thread_current, thread_prev, thread_oldest);
  1474.     }
  1475.     else
  1476.     {
  1477.         thread_current =
  1478.         thread_oldest  = h;
  1479.     }
  1480.     // ok to call this before encoding any frames, since the initial values of fdec have b_kept_as_ref=0
  1481.     if( x264_reference_update( h ) )
  1482.         return -1;
  1483.     h->fdec->i_lines_completed = -1;
  1484.     /* no data out */
  1485.     *pi_nal = 0;
  1486.     *pp_nal = NULL;
  1487.     /* ------------------- Setup new frame from picture -------------------- */
  1488.     if( pic_in != NULL )
  1489.     {
  1490.         /* 1: Copy the picture to a frame and move it to a buffer */
  1491.         x264_frame_t *fenc = x264_frame_pop_unused( h, 0 );
  1492.         if( !fenc )
  1493.             return -1;
  1494.         if( x264_frame_copy_picture( h, fenc, pic_in ) < 0 )
  1495.             return -1;
  1496.         if( h->param.i_width != 16 * h->sps->i_mb_width ||
  1497.             h->param.i_height != 16 * h->sps->i_mb_height )
  1498.             x264_frame_expand_border_mod16( h, fenc );
  1499.         fenc->i_frame = h->frames.i_input++;
  1500.         if( h->frames.b_have_lowres )
  1501.             x264_frame_init_lowres( h, fenc );
  1502.         if( h->param.rc.b_mb_tree && h->param.rc.b_stat_read )
  1503.         {
  1504.             if( x264_macroblock_tree_read( h, fenc ) )
  1505.                 return -1;
  1506.         }
  1507.         else if( h->param.rc.i_aq_mode )
  1508.             x264_adaptive_quant_frame( h, fenc );
  1509.         /* 2: Place the frame into the queue for its slice type decision */
  1510.         x264_lookahead_put_frame( h, fenc );
  1511.         if( h->frames.i_input <= h->frames.i_delay + 1 - h->param.i_threads )
  1512.         {
  1513.             /* Nothing yet to encode, waiting for filling of buffers */
  1514.             pic_out->i_type = X264_TYPE_AUTO;
  1515.             return 0;
  1516.         }
  1517.     }
  1518.     else
  1519.     {
  1520.         /* signal kills for lookahead thread */
  1521.         h->lookahead->b_exit_thread = 1;
  1522.         x264_pthread_cond_broadcast( &h->lookahead->ifbuf.cv_fill );
  1523.     }
  1524.     h->i_frame++;
  1525.     /* 3: The picture is analyzed in the lookahead */
  1526.     if( !h->frames.current[0] )
  1527.         x264_lookahead_get_frames( h );
  1528.     if( !h->frames.current[0] && x264_lookahead_is_empty( h ) )
  1529.         return x264_encoder_frame_end( thread_oldest, thread_current, pp_nal, pi_nal, pic_out );
  1530.     /* ------------------- Get frame to be encoded ------------------------- */
  1531.     /* 4: get picture to encode */
  1532.     h->fenc = x264_frame_shift( h->frames.current );
  1533.     if( h->fenc->param )
  1534.     {
  1535.         x264_encoder_reconfig( h, h->fenc->param );
  1536.         if( h->fenc->param->param_free )
  1537.             h->fenc->param->param_free( h->fenc->param );
  1538.     }
  1539.     if( h->fenc->i_type == X264_TYPE_IDR )
  1540.     {
  1541.         h->frames.i_last_idr = h->fenc->i_frame;
  1542.         h->i_frame_num = 0;
  1543.     }
  1544.     /* ------------------- Setup frame context ----------------------------- */
  1545.     /* 5: Init data dependent of frame type */
  1546.     if( h->fenc->i_type == X264_TYPE_IDR )
  1547.     {
  1548.         /* reset ref pictures */
  1549.         x264_reference_reset( h );
  1550.         i_nal_type    = NAL_SLICE_IDR;
  1551.         i_nal_ref_idc = NAL_PRIORITY_HIGHEST;
  1552.         h->sh.i_type = SLICE_TYPE_I;
  1553.     }
  1554.     else if( h->fenc->i_type == X264_TYPE_I )
  1555.     {
  1556.         i_nal_type    = NAL_SLICE;
  1557.         i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
  1558.         h->sh.i_type = SLICE_TYPE_I;
  1559.     }
  1560.     else if( h->fenc->i_type == X264_TYPE_P )
  1561.     {
  1562.         i_nal_type    = NAL_SLICE;
  1563.         i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
  1564.         h->sh.i_type = SLICE_TYPE_P;
  1565.     }
  1566.     else if( h->fenc->i_type == X264_TYPE_BREF )
  1567.     {
  1568.         i_nal_type    = NAL_SLICE;
  1569.         i_nal_ref_idc = NAL_PRIORITY_HIGH; /* maybe add MMCO to forget it? -> low */
  1570.         h->sh.i_type = SLICE_TYPE_B;
  1571.     }
  1572.     else    /* B frame */
  1573.     {
  1574.         i_nal_type    = NAL_SLICE;
  1575.         i_nal_ref_idc = NAL_PRIORITY_DISPOSABLE;
  1576.         h->sh.i_type = SLICE_TYPE_B;
  1577.     }
  1578.     h->fdec->i_poc =
  1579.     h->fenc->i_poc = 2 * (h->fenc->i_frame - h->frames.i_last_idr);
  1580.     h->fdec->i_type = h->fenc->i_type;
  1581.     h->fdec->i_frame = h->fenc->i_frame;
  1582.     h->fenc->b_kept_as_ref =
  1583.     h->fdec->b_kept_as_ref = i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE && h->param.i_keyint_max > 1;
  1584.     /* ------------------- Init                ----------------------------- */
  1585.     /* build ref list 0/1 */
  1586.     x264_reference_build_list( h, h->fdec->i_poc );
  1587.     if( h->sh.i_type == SLICE_TYPE_B )
  1588.         x264_macroblock_bipred_init( h );
  1589.     /* ---------------------- Write the bitstream -------------------------- */
  1590.     /* Init bitstream context */
  1591.     h->out.i_nal = 0;
  1592.     bs_init( &h->out.bs, h->out.p_bitstream, h->out.i_bitstream );
  1593.     if( h->param.b_aud )
  1594.     {
  1595.         int pic_type;
  1596.         if( h->sh.i_type == SLICE_TYPE_I )
  1597.             pic_type = 0;
  1598.         else if( h->sh.i_type == SLICE_TYPE_P )
  1599.             pic_type = 1;
  1600.         else if( h->sh.i_type == SLICE_TYPE_B )
  1601.             pic_type = 2;
  1602.         else
  1603.             pic_type = 7;
  1604.         x264_nal_start( h, NAL_AUD, NAL_PRIORITY_DISPOSABLE );
  1605.         bs_write( &h->out.bs, 3, pic_type );
  1606.         bs_rbsp_trailing( &h->out.bs );
  1607.         if( x264_nal_end( h ) )
  1608.             return -1;
  1609.     }
  1610.     h->i_nal_type = i_nal_type;
  1611.     h->i_nal_ref_idc = i_nal_ref_idc;
  1612.     //C程序不能中间定义变量 --@lia
  1613. //int 
  1614. overhead = NALU_OVERHEAD;
  1615.     /* Write SPS and PPS */
  1616.     if( i_nal_type == NAL_SLICE_IDR && h->param.b_repeat_headers )
  1617.     {
  1618.         if( h->fenc->i_frame == 0 )
  1619.         {
  1620.             /* identify ourself */
  1621.             x264_nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
  1622.             if( x264_sei_version_write( h, &h->out.bs ) )
  1623.                 return -1;
  1624.             if( x264_nal_end( h ) )
  1625.                 return -1;
  1626.             overhead += h->out.nal[h->out.i_nal-1].i_payload + NALU_OVERHEAD;
  1627.         }
  1628.         /* generate sequence parameters */
  1629.         x264_nal_start( h, NAL_SPS, NAL_PRIORITY_HIGHEST );
  1630.         x264_sps_write( &h->out.bs, h->sps );
  1631.         if( x264_nal_end( h ) )
  1632.             return -1;
  1633.         overhead += h->out.nal[h->out.i_nal-1].i_payload + NALU_OVERHEAD;
  1634.         /* generate picture parameters */
  1635.         x264_nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
  1636.         x264_pps_write( &h->out.bs, h->pps );
  1637.         if( x264_nal_end( h ) )
  1638.             return -1;
  1639.         overhead += h->out.nal[h->out.i_nal-1].i_payload + NALU_OVERHEAD;
  1640.     }
  1641.     /* Init the rate control */
  1642.     /* FIXME: Include slice header bit cost. */
  1643.     x264_ratecontrol_start( h, h->fenc->i_qpplus1, overhead*8 );
  1644.     i_global_qp = x264_ratecontrol_qp( h );
  1645.     pic_out->i_qpplus1 =
  1646.     h->fdec->i_qpplus1 = i_global_qp + 1;
  1647.     if( h->param.rc.b_stat_read && h->sh.i_type != SLICE_TYPE_I )
  1648.         x264_reference_build_list_optimal( h );
  1649.     /* Check to see whether we have chosen a reference list ordering different
  1650.      * from the standard's default. */
  1651.     h->b_ref_reorder[0] =
  1652.     h->b_ref_reorder[1] = 0;
  1653.     for( i = 0; i < h->i_ref0 - 1; i++ )
  1654.         /* P and B-frames use different default orders. */
  1655.         if( h->sh.i_type == SLICE_TYPE_P ? h->fref0[i]->i_frame_num < h->fref0[i+1]->i_frame_num
  1656.                                          : h->fref0[i]->i_poc < h->fref0[i+1]->i_poc )
  1657.         {
  1658.             h->b_ref_reorder[0] = 1;
  1659.             break;
  1660.         }
  1661.     /* ------------------------ Create slice header  ----------------------- */
  1662.     x264_slice_init( h, i_nal_type, i_global_qp );
  1663.     if( i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE )
  1664.         h->i_frame_num++;
  1665.     /* Write frame */
  1666.     if( h->param.i_threads > 1 )
  1667.     {
  1668.         if( x264_pthread_create( &h->thread_handle, NULL, (void*)x264_slices_write, h ) )
  1669.             return -1;
  1670.         h->b_thread_active = 1;
  1671.     }
  1672.     else
  1673.         if( (intptr_t)x264_slices_write( h ) )
  1674.             return -1;
  1675.     return x264_encoder_frame_end( thread_oldest, thread_current, pp_nal, pi_nal, pic_out );
  1676. }
  1677. static int x264_encoder_frame_end( x264_t *h, x264_t *thread_current,
  1678.                                    x264_nal_t **pp_nal, int *pi_nal,
  1679.                                    x264_picture_t *pic_out )
  1680. {
  1681.     int i, j, i_list, frame_size;
  1682.     char psz_message[80];
  1683.     if( h->b_thread_active )
  1684.     {
  1685.         void *ret = NULL;
  1686.         x264_pthread_join( h->thread_handle, &ret );
  1687.         if( (intptr_t)ret )
  1688.             return (intptr_t)ret;
  1689.         h->b_thread_active = 0;
  1690.     }
  1691.     if( !h->out.i_nal )
  1692.     {
  1693.         pic_out->i_type = X264_TYPE_AUTO;
  1694.         return 0;
  1695.     }
  1696.     x264_frame_push_unused( thread_current, h->fenc );
  1697.     /* End bitstream, set output  */
  1698.     *pi_nal = h->out.i_nal;
  1699.     *pp_nal = h->out.nal;
  1700.     frame_size = x264_encoder_encapsulate_nals( h );
  1701.     h->out.i_nal = 0;
  1702.     /* Set output picture properties */
  1703.     if( h->sh.i_type == SLICE_TYPE_I )
  1704.         pic_out->i_type = h->i_nal_type == NAL_SLICE_IDR ? X264_TYPE_IDR : X264_TYPE_I;
  1705.     else if( h->sh.i_type == SLICE_TYPE_P )
  1706.         pic_out->i_type = X264_TYPE_P;
  1707.     else
  1708.         pic_out->i_type = X264_TYPE_B;
  1709.     pic_out->i_pts = h->fenc->i_pts;
  1710.     pic_out->img.i_plane = h->fdec->i_plane;
  1711.     for(i = 0; i < 3; i++)
  1712.     {
  1713.         pic_out->img.i_stride[i] = h->fdec->i_stride[i];
  1714.         pic_out->img.plane[i] = h->fdec->plane[i];
  1715.     }
  1716.     /* ---------------------- Update encoder state ------------------------- */
  1717.     /* update rc */
  1718.     x264_emms();
  1719.     if( x264_ratecontrol_end( h, frame_size * 8 ) < 0 )
  1720.         return -1;
  1721.     x264_noise_reduction_update( thread_current );
  1722.     /* ---------------------- Compute/Print statistics --------------------- */
  1723.     x264_thread_sync_stat( h, h->thread[0] );
  1724.     /* Slice stat */
  1725.     h->stat.i_frame_count[h->sh.i_type]++;
  1726.     h->stat.i_frame_size[h->sh.i_type] += frame_size;
  1727.     h->stat.f_frame_qp[h->sh.i_type] += h->fdec->f_qp_avg_aq;
  1728.     for( i = 0; i < X264_MBTYPE_MAX; i++ )
  1729.         h->stat.i_mb_count[h->sh.i_type][i] += h->stat.frame.i_mb_count[i];
  1730.     for( i = 0; i < X264_PARTTYPE_MAX; i++ )
  1731.         h->stat.i_mb_partition[h->sh.i_type][i] += h->stat.frame.i_mb_partition[i];
  1732.     for( i = 0; i < 2; i++ )
  1733.         h->stat.i_mb_count_8x8dct[i] += h->stat.frame.i_mb_count_8x8dct[i];
  1734.     for( i = 0; i < 6; i++ )
  1735.         h->stat.i_mb_cbp[i] += h->stat.frame.i_mb_cbp[i];
  1736.     for( i = 0; i < 3; i++ )
  1737.         for( j = 0; j < 13; j++ )
  1738.             h->stat.i_mb_pred_mode[i][j] += h->stat.frame.i_mb_pred_mode[i][j];
  1739.     if( h->sh.i_type != SLICE_TYPE_I )
  1740.         for( i_list = 0; i_list < 2; i_list++ )
  1741.             for( i = 0; i < 32; i++ )
  1742.                 h->stat.i_mb_count_ref[h->sh.i_type][i_list][i] += h->stat.frame.i_mb_count_ref[i_list][i];
  1743.     if( h->sh.i_type == SLICE_TYPE_P )
  1744.         h->stat.i_consecutive_bframes[h->fdec->i_frame - h->fref0[0]->i_frame - 1]++;
  1745.     if( h->sh.i_type == SLICE_TYPE_B )
  1746.     {
  1747.         h->stat.i_direct_frames[ h->sh.b_direct_spatial_mv_pred ] ++;
  1748.         if( h->mb.b_direct_auto_write )
  1749.         {
  1750.             //FIXME somewhat arbitrary time constants
  1751.             if( h->stat.i_direct_score[0] + h->stat.i_direct_score[1] > h->mb.i_mb_count )
  1752.             {
  1753.                 for( i = 0; i < 2; i++ )
  1754.                     h->stat.i_direct_score[i] = h->stat.i_direct_score[i] * 9/10;
  1755.             }
  1756.             for( i = 0; i < 2; i++ )
  1757.                 h->stat.i_direct_score[i] += h->stat.frame.i_direct_score[i];
  1758.         }
  1759.     }
  1760.     psz_message[0] = '';
  1761.     if( h->param.analyse.b_psnr )
  1762.     {
  1763.         int64_t ssd[3] = {
  1764.             h->stat.frame.i_ssd[0],
  1765.             h->stat.frame.i_ssd[1],
  1766.             h->stat.frame.i_ssd[2],
  1767.         };
  1768.         h->stat.i_ssd_global[h->sh.i_type] += ssd[0] + ssd[1] + ssd[2];
  1769.         h->stat.f_psnr_average[h->sh.i_type] += x264_psnr( ssd[0] + ssd[1] + ssd[2], 3 * h->param.i_width * h->param.i_height / 2 );
  1770.         h->stat.f_psnr_mean_y[h->sh.i_type] += x264_psnr( ssd[0], h->param.i_width * h->param.i_height );
  1771.         h->stat.f_psnr_mean_u[h->sh.i_type] += x264_psnr( ssd[1], h->param.i_width * h->param.i_height / 4 );
  1772.         h->stat.f_psnr_mean_v[h->sh.i_type] += x264_psnr( ssd[2], h->param.i_width * h->param.i_height / 4 );
  1773.         snprintf( psz_message, 80, " PSNR Y:%5.2f U:%5.2f V:%5.2f",
  1774.                   x264_psnr( ssd[0], h->param.i_width * h->param.i_height ),
  1775.                   x264_psnr( ssd[1], h->param.i_width * h->param.i_height / 4),
  1776.                   x264_psnr( ssd[2], h->param.i_width * h->param.i_height / 4) );
  1777.     }
  1778.     if( h->param.analyse.b_ssim )
  1779.     {
  1780.         double ssim_y = h->stat.frame.f_ssim
  1781.                       / (((h->param.i_width-6)>>2) * ((h->param.i_height-6)>>2));
  1782.         h->stat.f_ssim_mean_y[h->sh.i_type] += ssim_y;
  1783.         snprintf( psz_message + strlen(psz_message), 80 - strlen(psz_message),
  1784.                   " SSIM Y:%.5f", ssim_y );
  1785.     }
  1786.     psz_message[79] = '';
  1787.     x264_log( h, X264_LOG_DEBUG,
  1788.                   "frame=%4d QP=%.2f NAL=%d Slice:%c Poc:%-3d I:%-4d P:%-4d SKIP:%-4d size=%d bytes%sn",
  1789.               h->i_frame,
  1790.               h->fdec->f_qp_avg_aq,
  1791.               h->i_nal_ref_idc,
  1792.               h->sh.i_type == SLICE_TYPE_I ? 'I' : (h->sh.i_type == SLICE_TYPE_P ? 'P' : 'B' ),
  1793.               h->fdec->i_poc,
  1794.               h->stat.frame.i_mb_count_i,
  1795.               h->stat.frame.i_mb_count_p,
  1796.               h->stat.frame.i_mb_count_skip,
  1797.               frame_size,
  1798.               psz_message );
  1799.     // keep stats all in one place
  1800.     x264_thread_sync_stat( h->thread[0], h );
  1801.     // for the use of the next frame
  1802.     x264_thread_sync_stat( thread_current, h );
  1803. #ifdef DEBUG_MB_TYPE
  1804. {
  1805.     static const char mb_chars[] = { 'i', 'i', 'I', 'C', 'P', '8', 'S',
  1806.         'D', '<', 'X', 'B', 'X', '>', 'B', 'B', 'B', 'B', '8', 'S' };
  1807.     int mb_xy;
  1808.     for( mb_xy = 0; mb_xy < h->sps->i_mb_width * h->sps->i_mb_height; mb_xy++ )
  1809.     {
  1810.         if( h->mb.type[mb_xy] < X264_MBTYPE_MAX && h->mb.type[mb_xy] >= 0 )
  1811.             fprintf( stderr, "%c ", mb_chars[ h->mb.type[mb_xy] ] );
  1812.         else
  1813.             fprintf( stderr, "? " );
  1814.         if( (mb_xy+1) % h->sps->i_mb_width == 0 )
  1815.             fprintf( stderr, "n" );
  1816.     }
  1817. }
  1818. #endif
  1819.     if( h->param.psz_dump_yuv )
  1820.         x264_frame_dump( h );
  1821.     return frame_size;
  1822. }
  1823. static void x264_print_intra( int64_t *i_mb_count, double i_count, int b_print_pcm, char *intra )
  1824. {
  1825.     intra += sprintf( intra, "I16..4%s: %4.1f%% %4.1f%% %4.1f%%",
  1826.         b_print_pcm ? "..PCM" : "",
  1827.         i_mb_count[I_16x16]/ i_count,
  1828.         i_mb_count[I_8x8]  / i_count,
  1829.         i_mb_count[I_4x4]  / i_count );
  1830.     if( b_print_pcm )
  1831.         sprintf( intra, " %4.1f%%", i_mb_count[I_PCM]  / i_count );
  1832. }
  1833. /****************************************************************************
  1834.  * x264_encoder_close:
  1835.  ****************************************************************************/
  1836. void    x264_encoder_close  ( x264_t *h )
  1837. {
  1838.     int64_t i_yuv_size = 3 * h->param.i_width * h->param.i_height / 2;
  1839.     int64_t i_mb_count_size[2][7] = {{0}};
  1840.     char buf[200];
  1841.     int i, j, i_list, i_type;
  1842.     int b_print_pcm = h->stat.i_mb_count[SLICE_TYPE_I][I_PCM]
  1843.                    || h->stat.i_mb_count[SLICE_TYPE_P][I_PCM]
  1844.                    || h->stat.i_mb_count[SLICE_TYPE_B][I_PCM];
  1845.     x264_lookahead_delete( h );
  1846.     for( i=0; i<h->param.i_threads; i++ )
  1847.     {
  1848.         // don't strictly have to wait for the other threads, but it's simpler than canceling them
  1849.         if( h->thread[i]->b_thread_active )
  1850.         {
  1851.             x264_pthread_join( h->thread[i]->thread_handle, NULL );
  1852.             assert( h->thread[i]->fenc->i_reference_count == 1 );
  1853.             x264_frame_delete( h->thread[i]->fenc );
  1854.         }
  1855.     }
  1856.     if( h->param.i_threads > 1 )
  1857.     {
  1858.         x264_t *thread_prev;
  1859.         thread_prev = h->thread[ h->i_thread_phase % h->param.i_threads ];
  1860.         x264_thread_sync_ratecontrol( h, thread_prev, h );
  1861.         x264_thread_sync_ratecontrol( thread_prev, thread_prev, h );
  1862.         h->i_frame = thread_prev->i_frame + 1 - h->param.i_threads;
  1863.     }
  1864.     h->i_frame++;
  1865.     /* Slices used and PSNR */
  1866.     for( i=0; i<5; i++ )
  1867.     {
  1868.         static const int slice_order[] = { SLICE_TYPE_I, SLICE_TYPE_SI, SLICE_TYPE_P, SLICE_TYPE_SP, SLICE_TYPE_B };
  1869.         static const char *slice_name[] = { "P", "B", "I", "SP", "SI" };
  1870.         int i_slice = slice_order[i];
  1871.         if( h->stat.i_frame_count[i_slice] > 0 )
  1872.         {
  1873.             const int i_count = h->stat.i_frame_count[i_slice];
  1874.             if( h->param.analyse.b_psnr )
  1875.             {
  1876.                 x264_log( h, X264_LOG_INFO,
  1877.                           "frame %s:%-5d Avg QP:%5.2f  size:%6.0f  PSNR Mean Y:%5.2f U:%5.2f V:%5.2f Avg:%5.2f Global:%5.2fn",
  1878.                           slice_name[i_slice],
  1879.                           i_count,
  1880.                           h->stat.f_frame_qp[i_slice] / i_count,
  1881.                           (double)h->stat.i_frame_size[i_slice] / i_count,
  1882.                           h->stat.f_psnr_mean_y[i_slice] / i_count, h->stat.f_psnr_mean_u[i_slice] / i_count, h->stat.f_psnr_mean_v[i_slice] / i_count,
  1883.                           h->stat.f_psnr_average[i_slice] / i_count,
  1884.                           x264_psnr( h->stat.i_ssd_global[i_slice], i_count * i_yuv_size ) );
  1885.             }
  1886.             else
  1887.             {
  1888.                 x264_log( h, X264_LOG_INFO,
  1889.                           "frame %s:%-5d Avg QP:%5.2f  size:%6.0fn",
  1890.                           slice_name[i_slice],
  1891.                           i_count,
  1892.                           h->stat.f_frame_qp[i_slice] / i_count,
  1893.                           (double)h->stat.i_frame_size[i_slice] / i_count );
  1894.             }
  1895.         }
  1896.     }
  1897.     if( h->param.i_bframe && h->stat.i_frame_count[SLICE_TYPE_P] )
  1898.     {
  1899.         char *p = buf;
  1900.         int den = 0;
  1901.         // weight by number of frames (including the P-frame) that are in a sequence of N B-frames
  1902.         for( i=0; i<=h->param.i_bframe; i++ )
  1903.             den += (i+1) * h->stat.i_consecutive_bframes[i];
  1904.         for( i=0; i<=h->param.i_bframe; i++ )
  1905.             p += sprintf( p, " %4.1f%%", 100. * (i+1) * h->stat.i_consecutive_bframes[i] / den );
  1906.         x264_log( h, X264_LOG_INFO, "consecutive B-frames:%sn", buf );
  1907.     }
  1908.     for( i_type = 0; i_type < 2; i_type++ )
  1909.         for( i = 0; i < X264_PARTTYPE_MAX; i++ )
  1910.         {
  1911.             if( i == D_DIRECT_8x8 ) continue; /* direct is counted as its own type */
  1912.             i_mb_count_size[i_type][x264_mb_partition_pixel_table[i]] += h->stat.i_mb_partition[i_type][i];
  1913.         }
  1914.     /* MB types used */
  1915.     if( h->stat.i_frame_count[SLICE_TYPE_I] > 0 )
  1916.     {
  1917.         int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_I];
  1918.         double i_count = h->stat.i_frame_count[SLICE_TYPE_I] * h->mb.i_mb_count / 100.0;
  1919.         x264_print_intra( i_mb_count, i_count, b_print_pcm, buf );
  1920.         x264_log( h, X264_LOG_INFO, "mb I  %sn", buf );
  1921.     }
  1922.     if( h->stat.i_frame_count[SLICE_TYPE_P] > 0 )
  1923.     {
  1924.         int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_P];
  1925.         double i_count = h->stat.i_frame_count[SLICE_TYPE_P] * h->mb.i_mb_count / 100.0;
  1926.         int64_t *i_mb_size = i_mb_count_size[SLICE_TYPE_P];
  1927.         x264_print_intra( i_mb_count, i_count, b_print_pcm, buf );
  1928.         x264_log( h, X264_LOG_INFO,
  1929.                   "mb P  %s  P16..4: %4.1f%% %4.1f%% %4.1f%% %4.1f%% %4.1f%%    skip:%4.1f%%n",
  1930.                   buf,
  1931.                   i_mb_size[PIXEL_16x16] / (i_count*4),
  1932.                   (i_mb_size[PIXEL_16x8] + i_mb_size[PIXEL_8x16]) / (i_count*4),
  1933.                   i_mb_size[PIXEL_8x8] / (i_count*4),
  1934.                   (i_mb_size[PIXEL_8x4] + i_mb_size[PIXEL_4x8]) / (i_count*4),
  1935.                   i_mb_size[PIXEL_4x4] / (i_count*4),
  1936.                   i_mb_count[P_SKIP] / i_count );
  1937.     }
  1938.     if( h->stat.i_frame_count[SLICE_TYPE_B] > 0 )
  1939.     {
  1940.         int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_B];
  1941.         double i_count = h->stat.i_frame_count[SLICE_TYPE_B] * h->mb.i_mb_count / 100.0;
  1942.         double i_mb_list_count;
  1943.         int64_t *i_mb_size = i_mb_count_size[SLICE_TYPE_B];
  1944.         int64_t list_count[3] = {0}; /* 0 == L0, 1 == L1, 2 == BI */
  1945.         x264_print_intra( i_mb_count, i_count, b_print_pcm, buf );
  1946.         for( i = 0; i < X264_PARTTYPE_MAX; i++ )
  1947.             for( j = 0; j < 2; j++ )
  1948.             {
  1949.                 int l0 = x264_mb_type_list_table[i][0][j];
  1950.                 int l1 = x264_mb_type_list_table[i][1][j];
  1951.                 if( l0 || l1 )
  1952.                     list_count[l1+l0*l1] += h->stat.i_mb_count[SLICE_TYPE_B][i] * 2;
  1953.             }
  1954.         list_count[0] += h->stat.i_mb_partition[SLICE_TYPE_B][D_L0_8x8];
  1955.         list_count[1] += h->stat.i_mb_partition[SLICE_TYPE_B][D_L1_8x8];
  1956.         list_count[2] += h->stat.i_mb_partition[SLICE_TYPE_B][D_BI_8x8];
  1957.         i_mb_count[B_DIRECT] += (h->stat.i_mb_partition[SLICE_TYPE_B][D_DIRECT_8x8]+2)/4;
  1958.         i_mb_list_count = (list_count[0] + list_count[1] + list_count[2]) / 100.0;
  1959.         x264_log( h, X264_LOG_INFO,
  1960.                   "mb B  %s  B16..8: %4.1f%% %4.1f%% %4.1f%%  direct:%4.1f%%  skip:%4.1f%%  L0:%4.1f%% L1:%4.1f%% BI:%4.1f%%n",
  1961.                   buf,
  1962.                   i_mb_size[PIXEL_16x16] / (i_count*4),
  1963.                   (i_mb_size[PIXEL_16x8] + i_mb_size[PIXEL_8x16]) / (i_count*4),
  1964.                   i_mb_size[PIXEL_8x8] / (i_count*4),
  1965.                   i_mb_count[B_DIRECT] / i_count,
  1966.                   i_mb_count[B_SKIP]   / i_count,
  1967.                   list_count[0] / i_mb_list_count,
  1968.                   list_count[1] / i_mb_list_count,
  1969.                   list_count[2] / i_mb_list_count );
  1970.     }
  1971.     x264_ratecontrol_summary( h );
  1972.     if( h->stat.i_frame_count[SLICE_TYPE_I] + h->stat.i_frame_count[SLICE_TYPE_P] + h->stat.i_frame_count[SLICE_TYPE_B] > 0 )
  1973.     {
  1974. #define SUM3(p) (p[SLICE_TYPE_I] + p[SLICE_TYPE_P] + p[SLICE_TYPE_B])
  1975. #define SUM3b(p,o) (p[SLICE_TYPE_I][o] + p[SLICE_TYPE_P][o] + p[SLICE_TYPE_B][o])
  1976.         int64_t i_i8x8 = SUM3b( h->stat.i_mb_count, I_8x8 );
  1977.         int64_t i_intra = i_i8x8 + SUM3b( h->stat.i_mb_count, I_4x4 )
  1978.                                  + SUM3b( h->stat.i_mb_count, I_16x16 );
  1979.         int64_t i_all_intra = i_intra + SUM3b( h->stat.i_mb_count, I_PCM);
  1980.         const int i_count = h->stat.i_frame_count[SLICE_TYPE_I] +
  1981.                             h->stat.i_frame_count[SLICE_TYPE_P] +
  1982.                             h->stat.i_frame_count[SLICE_TYPE_B];
  1983.         int64_t i_mb_count = i_count * h->mb.i_mb_count;
  1984.         float fps = (float) h->param.i_fps_num / h->param.i_fps_den;
  1985.         float f_bitrate = fps * SUM3(h->stat.i_frame_size) / i_count / 125;
  1986. //C程序不能中间定义变量 --@lia
  1987. int64_t fixed_pred_modes[3][9] = {{0}};
  1988.         int64_t sum_pred_modes[3] = {0};
  1989.         if( h->pps->b_transform_8x8_mode )
  1990.         {
  1991.             buf[0] = 0;
  1992.             if( h->stat.i_mb_count_8x8dct[0] )
  1993.                 sprintf( buf, " inter:%.1f%%", 100. * h->stat.i_mb_count_8x8dct[1] / h->stat.i_mb_count_8x8dct[0] );
  1994.             x264_log( h, X264_LOG_INFO, "8x8 transform intra:%.1f%%%sn", 100. * i_i8x8 / i_intra, buf );
  1995.         }
  1996.         if( h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_AUTO
  1997.             && h->stat.i_frame_count[SLICE_TYPE_B] )
  1998.         {
  1999.             x264_log( h, X264_LOG_INFO, "direct mvs  spatial:%.1f%% temporal:%.1f%%n",
  2000.                       h->stat.i_direct_frames[1] * 100. / h->stat.i_frame_count[SLICE_TYPE_B],
  2001.                       h->stat.i_direct_frames[0] * 100. / h->stat.i_frame_count[SLICE_TYPE_B] );
  2002.         }
  2003.         buf[0] = 0;
  2004.         if( i_mb_count != i_all_intra )
  2005.             sprintf( buf, " inter: %.1f%% %.1f%% %.1f%%",
  2006.                      h->stat.i_mb_cbp[1] * 100.0 / ((i_mb_count - i_all_intra)*4),
  2007.                      h->stat.i_mb_cbp[3] * 100.0 / ((i_mb_count - i_all_intra)  ),
  2008.                      h->stat.i_mb_cbp[5] * 100.0 / ((i_mb_count - i_all_intra)) );
  2009.         x264_log( h, X264_LOG_INFO, "coded y,uvDC,uvAC intra: %.1f%% %.1f%% %.1f%%%sn",
  2010.                   h->stat.i_mb_cbp[0] * 100.0 / (i_all_intra*4),
  2011.                   h->stat.i_mb_cbp[2] * 100.0 / (i_all_intra  ),
  2012.                   h->stat.i_mb_cbp[4] * 100.0 / (i_all_intra  ), buf );
  2013.         //C程序不能中间定义变量 --@lia
  2014. //int64_t fixed_pred_modes[3][9] = {{0}};
  2015.         //int64_t sum_pred_modes[3] = {0};
  2016.         for( i = 0; i <= I_PRED_16x16_DC_128; i++ )
  2017.         {
  2018.             fixed_pred_modes[0][x264_mb_pred_mode16x16_fix[i]] += h->stat.i_mb_pred_mode[0][i];
  2019.             sum_pred_modes[0] += h->stat.i_mb_pred_mode[0][i];
  2020.         }
  2021.         if( sum_pred_modes[0] )
  2022.             x264_log( h, X264_LOG_INFO, "i16 v,h,dc,p: %2.0f%% %2.0f%% %2.0f%% %2.0f%%n",
  2023.                       fixed_pred_modes[0][0] * 100.0 / sum_pred_modes[0],
  2024.                       fixed_pred_modes[0][1] * 100.0 / sum_pred_modes[0],
  2025.                       fixed_pred_modes[0][2] * 100.0 / sum_pred_modes[0],
  2026.                       fixed_pred_modes[0][3] * 100.0 / sum_pred_modes[0] );
  2027.         for( i = 1; i <= 2; i++ )
  2028.         {
  2029.             for( j = 0; j <= I_PRED_8x8_DC_128; j++ )
  2030.             {
  2031.                 fixed_pred_modes[i][x264_mb_pred_mode4x4_fix(j)] += h->stat.i_mb_pred_mode[i][j];
  2032.                 sum_pred_modes[i] += h->stat.i_mb_pred_mode[i][j];
  2033.             }
  2034.             if( sum_pred_modes[i] )
  2035.                 x264_log( h, X264_LOG_INFO, "i%d v,h,dc,ddl,ddr,vr,hd,vl,hu: %2.0f%% %2.0f%% %2.0f%% %2.0f%% %2.0f%% %2.0f%% %2.0f%% %2.0f%% %2.0f%%n", (3-i)*4,
  2036.                           fixed_pred_modes[i][0] * 100.0 / sum_pred_modes[i],
  2037.                           fixed_pred_modes[i][1] * 100.0 / sum_pred_modes[i],
  2038.                           fixed_pred_modes[i][2] * 100.0 / sum_pred_modes[i],
  2039.                           fixed_pred_modes[i][3] * 100.0 / sum_pred_modes[i],
  2040.                           fixed_pred_modes[i][4] * 100.0 / sum_pred_modes[i],
  2041.                           fixed_pred_modes[i][5] * 100.0 / sum_pred_modes[i],
  2042.                           fixed_pred_modes[i][6] * 100.0 / sum_pred_modes[i],
  2043.                           fixed_pred_modes[i][7] * 100.0 / sum_pred_modes[i],
  2044.                           fixed_pred_modes[i][8] * 100.0 / sum_pred_modes[i] );
  2045.         }
  2046.         for( i_list = 0; i_list < 2; i_list++ )
  2047.         {
  2048.             int i_slice;
  2049.             for( i_slice = 0; i_slice < 2; i_slice++ )
  2050.             {
  2051.                 char *p = buf;
  2052.                 int64_t i_den = 0;
  2053.                 int i_max = 0;
  2054.                 for( i = 0; i < 32; i++ )
  2055.                     if( h->stat.i_mb_count_ref[i_slice][i_list][i] )
  2056.                     {
  2057.                         i_den += h->stat.i_mb_count_ref[i_slice][i_list][i];
  2058.                         i_max = i;
  2059.                     }
  2060.                 if( i_max == 0 )
  2061.                     continue;
  2062.                 for( i = 0; i <= i_max; i++ )
  2063.                     p += sprintf( p, " %4.1f%%", 100. * h->stat.i_mb_count_ref[i_slice][i_list][i] / i_den );
  2064.                 x264_log( h, X264_LOG_INFO, "ref %c L%d:%sn", "PB"[i_slice], i_list, buf );
  2065.             }
  2066.         }
  2067.         if( h->param.analyse.b_ssim )
  2068.         {
  2069.             x264_log( h, X264_LOG_INFO,
  2070.                       "SSIM Mean Y:%.7fn",
  2071.                       SUM3( h->stat.f_ssim_mean_y ) / i_count );
  2072.         }
  2073.         if( h->param.analyse.b_psnr )
  2074.         {
  2075.             x264_log( h, X264_LOG_INFO,
  2076.                       "PSNR Mean Y:%6.3f U:%6.3f V:%6.3f Avg:%6.3f Global:%6.3f kb/s:%.2fn",
  2077.                       SUM3( h->stat.f_psnr_mean_y ) / i_count,
  2078.                       SUM3( h->stat.f_psnr_mean_u ) / i_count,
  2079.                       SUM3( h->stat.f_psnr_mean_v ) / i_count,
  2080.                       SUM3( h->stat.f_psnr_average ) / i_count,
  2081.                       x264_psnr( SUM3( h->stat.i_ssd_global ), i_count * i_yuv_size ),
  2082.                       f_bitrate );
  2083.         }
  2084.         else
  2085.             x264_log( h, X264_LOG_INFO, "kb/s:%.2fn", f_bitrate );
  2086.     }
  2087.     /* rc */
  2088.     x264_ratecontrol_delete( h );
  2089.     /* param */
  2090.     if( h->param.rc.psz_stat_out )
  2091.         free( h->param.rc.psz_stat_out );
  2092.     if( h->param.rc.psz_stat_in )
  2093.         free( h->param.rc.psz_stat_in );
  2094.     x264_cqm_delete( h );
  2095.     x264_analyse_free_costs( h );
  2096.     if( h->param.i_threads > 1)
  2097.         h = h->thread[ h->i_thread_phase % h->param.i_threads ];
  2098.     /* frames */
  2099.     x264_frame_delete_list( h->frames.unused[0] );
  2100.     x264_frame_delete_list( h->frames.unused[1] );
  2101.     x264_frame_delete_list( h->frames.current );
  2102.     h = h->thread[0];
  2103.     for( i = h->param.i_threads - 1; i >= 0; i-- )
  2104.     {
  2105.         x264_frame_t **frame;
  2106.         for( frame = h->thread[i]->frames.reference; *frame; frame++ )
  2107.         {
  2108.             assert( (*frame)->i_reference_count > 0 );
  2109.             (*frame)->i_reference_count--;
  2110.             if( (*frame)->i_reference_count == 0 )
  2111.                 x264_frame_delete( *frame );
  2112.         }
  2113.         frame = &h->thread[i]->fdec;
  2114.         assert( (*frame)->i_reference_count > 0 );
  2115.         (*frame)->i_reference_count--;
  2116.         if( (*frame)->i_reference_count == 0 )
  2117.             x264_frame_delete( *frame );
  2118.         x264_macroblock_cache_end( h->thread[i] );
  2119.         x264_free( h->thread[i]->out.p_bitstream );
  2120.         x264_free( h->thread[i]->out.nal);
  2121.         x264_free( h->thread[i] );
  2122.     }
  2123. }
  2124. /****************************************************************************
  2125.  * x264_encoder_delayed_frames:
  2126.  ****************************************************************************/
  2127. int x264_encoder_delayed_frames( x264_t *h )
  2128. {
  2129.     int delayed_frames = 0;
  2130.     int i;
  2131.     for( i=0; i<h->param.i_threads; i++ )
  2132.         delayed_frames += h->thread[i]->b_thread_active;
  2133.     h = h->thread[ h->i_thread_phase % h->param.i_threads ];
  2134.     for( i=0; h->frames.current[i]; i++ )
  2135.         delayed_frames++;
  2136.     x264_pthread_mutex_lock( &h->lookahead->ofbuf.mutex );
  2137.     x264_pthread_mutex_lock( &h->lookahead->ifbuf.mutex );
  2138.     x264_pthread_mutex_lock( &h->lookahead->next.mutex );
  2139.     delayed_frames += h->lookahead->ifbuf.i_size + h->lookahead->next.i_size + h->lookahead->ofbuf.i_size;
  2140.     x264_pthread_mutex_unlock( &h->lookahead->next.mutex );
  2141.     x264_pthread_mutex_unlock( &h->lookahead->ifbuf.mutex );
  2142.     x264_pthread_mutex_unlock( &h->lookahead->ofbuf.mutex );
  2143.     return delayed_frames;
  2144. }