encoder.c
上传用户:hjq518
上传日期:2021-12-09
资源大小:5084k
文件大小:73k
源码类别:

Audio

开发平台:

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.  *
  9.  * This program is free software; you can redistribute it and/or modify
  10.  * it under the terms of the GNU General Public License as published by
  11.  * the Free Software Foundation; either version 2 of the License, or
  12.  * (at your option) any later version.
  13.  *
  14.  * This program is distributed in the hope that it will be useful,
  15.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  17.  * GNU General Public License for more details.
  18.  *
  19.  * You should have received a copy of the GNU General Public License
  20.  * along with this program; if not, write to the Free Software
  21.  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02111, USA.
  22.  *****************************************************************************/
  23. #include <math.h>
  24. #include "common/common.h"
  25. #include "common/cpu.h"
  26. #include "set.h"
  27. #include "analyse.h"
  28. #include "ratecontrol.h"
  29. #include "macroblock.h"
  30. #if VISUALIZE
  31. #include "common/visualize.h"
  32. #endif
  33. //#define DEBUG_MB_TYPE
  34. #define NALU_OVERHEAD 5 // startcode + NAL type costs 5 bytes per frame
  35. #define bs_write_ue bs_write_ue_big
  36. static void x264_encoder_frame_end( x264_t *h, x264_t *thread_current,
  37.                                     x264_nal_t **pp_nal, int *pi_nal,
  38.                                     x264_picture_t *pic_out );
  39. /****************************************************************************
  40.  *
  41.  ******************************* x264 libs **********************************
  42.  *
  43.  ****************************************************************************/
  44. static float x264_psnr( int64_t i_sqe, int64_t i_size )
  45. {
  46.     double f_mse = (double)i_sqe / ((double)65025.0 * (double)i_size);
  47.     if( f_mse <= 0.0000000001 ) /* Max 100dB */
  48.         return 100;
  49.     return (float)(-10.0 * log( f_mse ) / log( 10.0 ));
  50. }
  51. static void x264_frame_dump( x264_t *h )
  52. {
  53.     FILE *f = fopen( h->param.psz_dump_yuv, "r+b" );
  54.     int i, y;
  55.     if( !f )
  56.         return;
  57.     /* Write the frame in display order */
  58.     fseek( f, h->fdec->i_frame * h->param.i_height * h->param.i_width * 3/2, SEEK_SET );
  59.     for( i = 0; i < h->fdec->i_plane; i++ )
  60.         for( y = 0; y < h->param.i_height >> !!i; y++ )
  61.             fwrite( &h->fdec->plane[i][y*h->fdec->i_stride[i]], 1, h->param.i_width >> !!i, f );
  62.     fclose( f );
  63. }
  64. /* Fill "default" values */
  65. static void x264_slice_header_init( x264_t *h, x264_slice_header_t *sh,
  66.                                     x264_sps_t *sps, x264_pps_t *pps,
  67.                                     int i_idr_pic_id, int i_frame, int i_qp )
  68. {
  69.     x264_param_t *param = &h->param;
  70.     int i;
  71.     /* First we fill all field */
  72.     sh->sps = sps;
  73.     sh->pps = pps;
  74.     sh->i_first_mb  = 0;
  75.     sh->i_last_mb   = h->sps->i_mb_width * h->sps->i_mb_height;
  76.     sh->i_pps_id    = pps->i_id;
  77.     sh->i_frame_num = i_frame;
  78.     sh->b_mbaff = h->param.b_interlaced;
  79.     sh->b_field_pic = 0;    /* no field support for now */
  80.     sh->b_bottom_field = 0; /* not yet used */
  81.     sh->i_idr_pic_id = i_idr_pic_id;
  82.     /* poc stuff, fixed later */
  83.     sh->i_poc_lsb = 0;
  84.     sh->i_delta_poc_bottom = 0;
  85.     sh->i_delta_poc[0] = 0;
  86.     sh->i_delta_poc[1] = 0;
  87.     sh->i_redundant_pic_cnt = 0;
  88.     if( !h->mb.b_direct_auto_read )
  89.     {
  90.         if( h->mb.b_direct_auto_write )
  91.             sh->b_direct_spatial_mv_pred = ( h->stat.i_direct_score[1] > h->stat.i_direct_score[0] );
  92.         else
  93.             sh->b_direct_spatial_mv_pred = ( param->analyse.i_direct_mv_pred == X264_DIRECT_PRED_SPATIAL );
  94.     }
  95.     /* else b_direct_spatial_mv_pred was read from the 2pass statsfile */
  96.     sh->b_num_ref_idx_override = 0;
  97.     sh->i_num_ref_idx_l0_active = 1;
  98.     sh->i_num_ref_idx_l1_active = 1;
  99.     sh->b_ref_pic_list_reordering_l0 = h->b_ref_reorder[0];
  100.     sh->b_ref_pic_list_reordering_l1 = h->b_ref_reorder[1];
  101.     /* If the ref list isn't in the default order, construct reordering header */
  102.     /* List1 reordering isn't needed yet */
  103.     if( sh->b_ref_pic_list_reordering_l0 )
  104.     {
  105.         int pred_frame_num = i_frame;
  106.         for( i = 0; i < h->i_ref0; i++ )
  107.         {
  108.             int diff = h->fref0[i]->i_frame_num - pred_frame_num;
  109.             if( diff == 0 )
  110.                 x264_log( h, X264_LOG_ERROR, "diff frame num == 0n" );
  111.             sh->ref_pic_list_order[0][i].idc = ( diff > 0 );
  112.             sh->ref_pic_list_order[0][i].arg = abs( diff ) - 1;
  113.             pred_frame_num = h->fref0[i]->i_frame_num;
  114.         }
  115.     }
  116.     sh->i_cabac_init_idc = param->i_cabac_init_idc;
  117.     sh->i_qp = i_qp;
  118.     sh->i_qp_delta = i_qp - pps->i_pic_init_qp;
  119.     sh->b_sp_for_swidth = 0;
  120.     sh->i_qs_delta = 0;
  121.     /* If effective qp <= 15, deblocking would have no effect anyway */
  122.     if( param->b_deblocking_filter
  123.         && ( h->mb.b_variable_qp
  124.         || 15 < i_qp + 2 * X264_MIN(param->i_deblocking_filter_alphac0, param->i_deblocking_filter_beta) ) )
  125.     {
  126.         sh->i_disable_deblocking_filter_idc = 0;
  127.     }
  128.     else
  129.     {
  130.         sh->i_disable_deblocking_filter_idc = 1;
  131.     }
  132.     sh->i_alpha_c0_offset = param->i_deblocking_filter_alphac0 << 1;
  133.     sh->i_beta_offset = param->i_deblocking_filter_beta << 1;
  134. }
  135. static void x264_slice_header_write( bs_t *s, x264_slice_header_t *sh, int i_nal_ref_idc )
  136. {
  137.     int i;
  138.     if( sh->b_mbaff )
  139.     {
  140.         assert( sh->i_first_mb % (2*sh->sps->i_mb_width) == 0 );
  141.         bs_write_ue( s, sh->i_first_mb >> 1 );
  142.     }
  143.     else
  144.         bs_write_ue( s, sh->i_first_mb );
  145.     bs_write_ue( s, sh->i_type + 5 );   /* same type things */
  146.     bs_write_ue( s, sh->i_pps_id );
  147.     bs_write( s, sh->sps->i_log2_max_frame_num, sh->i_frame_num );
  148.     if( !sh->sps->b_frame_mbs_only )
  149.     {
  150.         bs_write1( s, sh->b_field_pic );
  151.         if ( sh->b_field_pic )
  152.             bs_write1( s, sh->b_bottom_field );
  153.     }
  154.     if( sh->i_idr_pic_id >= 0 ) /* NAL IDR */
  155.     {
  156.         bs_write_ue( s, sh->i_idr_pic_id );
  157.     }
  158.     if( sh->sps->i_poc_type == 0 )
  159.     {
  160.         bs_write( s, sh->sps->i_log2_max_poc_lsb, sh->i_poc_lsb );
  161.         if( sh->pps->b_pic_order && !sh->b_field_pic )
  162.         {
  163.             bs_write_se( s, sh->i_delta_poc_bottom );
  164.         }
  165.     }
  166.     else if( sh->sps->i_poc_type == 1 && !sh->sps->b_delta_pic_order_always_zero )
  167.     {
  168.         bs_write_se( s, sh->i_delta_poc[0] );
  169.         if( sh->pps->b_pic_order && !sh->b_field_pic )
  170.         {
  171.             bs_write_se( s, sh->i_delta_poc[1] );
  172.         }
  173.     }
  174.     if( sh->pps->b_redundant_pic_cnt )
  175.     {
  176.         bs_write_ue( s, sh->i_redundant_pic_cnt );
  177.     }
  178.     if( sh->i_type == SLICE_TYPE_B )
  179.     {
  180.         bs_write1( s, sh->b_direct_spatial_mv_pred );
  181.     }
  182.     if( sh->i_type == SLICE_TYPE_P || sh->i_type == SLICE_TYPE_SP || sh->i_type == SLICE_TYPE_B )
  183.     {
  184.         bs_write1( s, sh->b_num_ref_idx_override );
  185.         if( sh->b_num_ref_idx_override )
  186.         {
  187.             bs_write_ue( s, sh->i_num_ref_idx_l0_active - 1 );
  188.             if( sh->i_type == SLICE_TYPE_B )
  189.             {
  190.                 bs_write_ue( s, sh->i_num_ref_idx_l1_active - 1 );
  191.             }
  192.         }
  193.     }
  194.     /* ref pic list reordering */
  195.     if( sh->i_type != SLICE_TYPE_I )
  196.     {
  197.         bs_write1( s, sh->b_ref_pic_list_reordering_l0 );
  198.         if( sh->b_ref_pic_list_reordering_l0 )
  199.         {
  200.             for( i = 0; i < sh->i_num_ref_idx_l0_active; i++ )
  201.             {
  202.                 bs_write_ue( s, sh->ref_pic_list_order[0][i].idc );
  203.                 bs_write_ue( s, sh->ref_pic_list_order[0][i].arg );
  204.             }
  205.             bs_write_ue( s, 3 );
  206.         }
  207.     }
  208.     if( sh->i_type == SLICE_TYPE_B )
  209.     {
  210.         bs_write1( s, sh->b_ref_pic_list_reordering_l1 );
  211.         if( sh->b_ref_pic_list_reordering_l1 )
  212.         {
  213.             for( i = 0; i < sh->i_num_ref_idx_l1_active; i++ )
  214.             {
  215.                 bs_write_ue( s, sh->ref_pic_list_order[1][i].idc );
  216.                 bs_write_ue( s, sh->ref_pic_list_order[1][i].arg );
  217.             }
  218.             bs_write_ue( s, 3 );
  219.         }
  220.     }
  221.     if( ( sh->pps->b_weighted_pred && ( sh->i_type == SLICE_TYPE_P || sh->i_type == SLICE_TYPE_SP ) ) ||
  222.         ( sh->pps->b_weighted_bipred == 1 && sh->i_type == SLICE_TYPE_B ) )
  223.     {
  224.         /* FIXME */
  225.     }
  226.     if( i_nal_ref_idc != 0 )
  227.     {
  228.         if( sh->i_idr_pic_id >= 0 )
  229.         {
  230.             bs_write1( s, 0 );  /* no output of prior pics flag */
  231.             bs_write1( s, 0 );  /* long term reference flag */
  232.         }
  233.         else
  234.         {
  235.             bs_write1( s, 0 );  /* adaptive_ref_pic_marking_mode_flag */
  236.         }
  237.     }
  238.     if( sh->pps->b_cabac && sh->i_type != SLICE_TYPE_I )
  239.     {
  240.         bs_write_ue( s, sh->i_cabac_init_idc );
  241.     }
  242.     bs_write_se( s, sh->i_qp_delta );      /* slice qp delta */
  243.     if( sh->pps->b_deblocking_filter_control )
  244.     {
  245.         bs_write_ue( s, sh->i_disable_deblocking_filter_idc );
  246.         if( sh->i_disable_deblocking_filter_idc != 1 )
  247.         {
  248.             bs_write_se( s, sh->i_alpha_c0_offset >> 1 );
  249.             bs_write_se( s, sh->i_beta_offset >> 1 );
  250.         }
  251.     }
  252. }
  253. /* If we are within a reasonable distance of the end of the memory allocated for the bitstream, */
  254. /* reallocate, adding an arbitrary amount of space (100 kilobytes). */
  255. static void x264_bitstream_check_buffer( x264_t *h )
  256. {
  257.     if( ( h->param.b_cabac && (h->cabac.p_end - h->cabac.p < 2500) )
  258.      || ( h->out.bs.p_end - h->out.bs.p < 2500 ) )
  259.     {
  260.         uint8_t *bs_bak = h->out.p_bitstream;
  261.         intptr_t delta;
  262.         int i;
  263.         h->out.i_bitstream += 100000;
  264.         h->out.p_bitstream = x264_realloc( h->out.p_bitstream, h->out.i_bitstream );
  265.         delta = h->out.p_bitstream - bs_bak;
  266.         h->out.bs.p_start += delta;
  267.         h->out.bs.p += delta;
  268.         h->out.bs.p_end = h->out.p_bitstream + h->out.i_bitstream;
  269.         h->cabac.p_start += delta;
  270.         h->cabac.p += delta;
  271.         h->cabac.p_end = h->out.p_bitstream + h->out.i_bitstream;
  272.         for( i = 0; i <= h->out.i_nal; i++ )
  273.             h->out.nal[i].p_payload += delta;
  274.     }
  275. }
  276. /****************************************************************************
  277.  *
  278.  ****************************************************************************
  279.  ****************************** External API*********************************
  280.  ****************************************************************************
  281.  *
  282.  ****************************************************************************/
  283. static int x264_validate_parameters( x264_t *h )
  284. {
  285. #ifdef HAVE_MMX
  286.     if( !(x264_cpu_detect() & X264_CPU_MMXEXT) )
  287.     {
  288.         x264_log( h, X264_LOG_ERROR, "your cpu does not support MMXEXT, but x264 was compiled with asm supportn");
  289.         x264_log( h, X264_LOG_ERROR, "to run x264, recompile without asm support (configure --disable-asm)n");
  290.         return -1;
  291.     }
  292. #endif
  293.     if( h->param.i_width <= 0 || h->param.i_height <= 0 )
  294.     {
  295.         x264_log( h, X264_LOG_ERROR, "invalid width x height (%dx%d)n",
  296.                   h->param.i_width, h->param.i_height );
  297.         return -1;
  298.     }
  299.     if( h->param.i_width % 2 || h->param.i_height % 2 )
  300.     {
  301.         x264_log( h, X264_LOG_ERROR, "width or height not divisible by 2 (%dx%d)n",
  302.                   h->param.i_width, h->param.i_height );
  303.         return -1;
  304.     }
  305.     if( h->param.i_csp != X264_CSP_I420 )
  306.     {
  307.         x264_log( h, X264_LOG_ERROR, "invalid CSP (only I420 supported)n" );
  308.         return -1;
  309.     }
  310.     if( h->param.i_threads == 0 )
  311.         h->param.i_threads = x264_cpu_num_processors() * 3/2;
  312.     h->param.i_threads = x264_clip3( h->param.i_threads, 1, X264_THREAD_MAX );
  313.     if( h->param.i_threads > 1 )
  314.     {
  315. #ifndef HAVE_PTHREAD
  316.         x264_log( h, X264_LOG_WARNING, "not compiled with pthread support!n");
  317.         h->param.i_threads = 1;
  318. #else
  319.         if( h->param.i_scenecut_threshold >= 0 )
  320.             h->param.b_pre_scenecut = 1;
  321. #endif
  322.     }
  323.     if( h->param.b_interlaced )
  324.     {
  325.         if( h->param.analyse.i_me_method >= X264_ME_ESA )
  326.         {
  327.             x264_log( h, X264_LOG_WARNING, "interlace + me=esa is not implementedn" );
  328.             h->param.analyse.i_me_method = X264_ME_UMH;
  329.         }
  330.         if( h->param.analyse.i_direct_mv_pred > X264_DIRECT_PRED_SPATIAL )
  331.         {
  332.             x264_log( h, X264_LOG_WARNING, "interlace + direct=temporal is not implementedn" );
  333.             h->param.analyse.i_direct_mv_pred = X264_DIRECT_PRED_SPATIAL;
  334.         }
  335.     }
  336.     if( h->param.rc.i_rc_method < 0 || h->param.rc.i_rc_method > 2 )
  337.     {
  338.         x264_log( h, X264_LOG_ERROR, "no ratecontrol method specifiedn" );
  339.         return -1;
  340.     }
  341.     h->param.rc.f_rf_constant = x264_clip3f( h->param.rc.f_rf_constant, 0, 51 );
  342.     h->param.rc.i_qp_constant = x264_clip3( h->param.rc.i_qp_constant, 0, 51 );
  343.     if( h->param.rc.i_rc_method == X264_RC_CRF )
  344.         h->param.rc.i_qp_constant = h->param.rc.f_rf_constant;
  345.     if( (h->param.rc.i_rc_method == X264_RC_CQP || h->param.rc.i_rc_method == X264_RC_CRF)
  346.         && h->param.rc.i_qp_constant == 0 )
  347.     {
  348.         h->mb.b_lossless = 1;
  349.         h->param.i_cqm_preset = X264_CQM_FLAT;
  350.         h->param.psz_cqm_file = NULL;
  351.         h->param.rc.i_rc_method = X264_RC_CQP;
  352.         h->param.rc.f_ip_factor = 1;
  353.         h->param.rc.f_pb_factor = 1;
  354.         h->param.analyse.b_transform_8x8 = 0;
  355.         h->param.analyse.b_psnr = 0;
  356.         h->param.analyse.b_ssim = 0;
  357.         h->param.analyse.i_chroma_qp_offset = 0;
  358.         h->param.analyse.i_trellis = 0;
  359.         h->param.analyse.b_fast_pskip = 0;
  360.         h->param.analyse.i_noise_reduction = 0;
  361.     }
  362.     if( h->param.rc.i_rc_method == X264_RC_CQP )
  363.     {
  364.         float qp_p = h->param.rc.i_qp_constant;
  365.         float qp_i = qp_p - 6*log(h->param.rc.f_ip_factor)/log(2);
  366.         float qp_b = qp_p + 6*log(h->param.rc.f_pb_factor)/log(2);
  367.         h->param.rc.i_qp_min = x264_clip3( (int)(X264_MIN3( qp_p, qp_i, qp_b )), 0, 51 );
  368.         h->param.rc.i_qp_max = x264_clip3( (int)(X264_MAX3( qp_p, qp_i, qp_b ) + .999), 0, 51 );
  369.         h->param.rc.i_aq_mode = 0;
  370.     }
  371.     h->param.rc.i_qp_max = x264_clip3( h->param.rc.i_qp_max, 0, 51 );
  372.     h->param.rc.i_qp_min = x264_clip3( h->param.rc.i_qp_min, 0, h->param.rc.i_qp_max );
  373.     if( ( h->param.i_width % 16 || h->param.i_height % 16 )
  374.         && h->param.i_height != 1080 && !h->mb.b_lossless )
  375.     {
  376.         // There's nothing special about 1080 in that the warning still applies to it,
  377.         // but chances are the user can't help it if his content is already 1080p,
  378.         // so there's no point in warning in that case.
  379.         x264_log( h, X264_LOG_WARNING,
  380.                   "width or height not divisible by 16 (%dx%d), compression will suffer.n",
  381.                   h->param.i_width, h->param.i_height );
  382.     }
  383.     h->param.i_frame_reference = x264_clip3( h->param.i_frame_reference, 1, 16 );
  384.     if( h->param.i_keyint_max <= 0 )
  385.         h->param.i_keyint_max = 1;
  386.     h->param.i_keyint_min = x264_clip3( h->param.i_keyint_min, 1, h->param.i_keyint_max/2+1 );
  387.     h->param.i_bframe = x264_clip3( h->param.i_bframe, 0, X264_BFRAME_MAX );
  388.     h->param.i_bframe_bias = x264_clip3( h->param.i_bframe_bias, -90, 100 );
  389.     h->param.b_bframe_pyramid = h->param.b_bframe_pyramid && h->param.i_bframe > 1;
  390.     h->param.b_bframe_adaptive = h->param.b_bframe_adaptive && h->param.i_bframe > 0;
  391.     h->param.analyse.b_weighted_bipred = h->param.analyse.b_weighted_bipred && h->param.i_bframe > 0;
  392.     h->mb.b_direct_auto_write = h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_AUTO
  393.                                 && h->param.i_bframe
  394.                                 && ( h->param.rc.b_stat_write || !h->param.rc.b_stat_read );
  395.     if( h->param.i_scenecut_threshold < 0 )
  396.         h->param.b_pre_scenecut = 0;
  397.     h->param.i_deblocking_filter_alphac0 = x264_clip3( h->param.i_deblocking_filter_alphac0, -6, 6 );
  398.     h->param.i_deblocking_filter_beta    = x264_clip3( h->param.i_deblocking_filter_beta, -6, 6 );
  399.     h->param.analyse.i_luma_deadzone[0] = x264_clip3( h->param.analyse.i_luma_deadzone[0], 0, 32 );
  400.     h->param.analyse.i_luma_deadzone[1] = x264_clip3( h->param.analyse.i_luma_deadzone[1], 0, 32 );
  401.     h->param.i_cabac_init_idc = x264_clip3( h->param.i_cabac_init_idc, 0, 2 );
  402.     if( h->param.i_cqm_preset < X264_CQM_FLAT || h->param.i_cqm_preset > X264_CQM_CUSTOM )
  403.         h->param.i_cqm_preset = X264_CQM_FLAT;
  404.     if( h->param.analyse.i_me_method < X264_ME_DIA ||
  405.         h->param.analyse.i_me_method > X264_ME_TESA )
  406.         h->param.analyse.i_me_method = X264_ME_HEX;
  407.     if( h->param.analyse.i_me_range < 4 )
  408.         h->param.analyse.i_me_range = 4;
  409.     if( h->param.analyse.i_me_range > 16 && h->param.analyse.i_me_method <= X264_ME_HEX )
  410.         h->param.analyse.i_me_range = 16;
  411.     if( h->param.analyse.i_me_method == X264_ME_TESA &&
  412.         (h->mb.b_lossless || h->param.analyse.i_subpel_refine <= 1) )
  413.         h->param.analyse.i_me_method = X264_ME_ESA;
  414.     h->param.analyse.i_subpel_refine = x264_clip3( h->param.analyse.i_subpel_refine, 1, 7 );
  415.     h->param.analyse.b_bframe_rdo = h->param.analyse.b_bframe_rdo && h->param.analyse.i_subpel_refine >= 6;
  416.     h->param.analyse.b_mixed_references = h->param.analyse.b_mixed_references && h->param.i_frame_reference > 1;
  417.     h->param.analyse.inter &= X264_ANALYSE_PSUB16x16|X264_ANALYSE_PSUB8x8|X264_ANALYSE_BSUB16x16|
  418.                               X264_ANALYSE_I4x4|X264_ANALYSE_I8x8;
  419.     h->param.analyse.intra &= X264_ANALYSE_I4x4|X264_ANALYSE_I8x8;
  420.     if( !(h->param.analyse.inter & X264_ANALYSE_PSUB16x16) )
  421.         h->param.analyse.inter &= ~X264_ANALYSE_PSUB8x8;
  422.     if( !h->param.analyse.b_transform_8x8 )
  423.     {
  424.         h->param.analyse.inter &= ~X264_ANALYSE_I8x8;
  425.         h->param.analyse.intra &= ~X264_ANALYSE_I8x8;
  426.     }
  427.     h->param.analyse.i_chroma_qp_offset = x264_clip3(h->param.analyse.i_chroma_qp_offset, -12, 12);
  428.     if( !h->param.b_cabac )
  429.         h->param.analyse.i_trellis = 0;
  430.     h->param.analyse.i_trellis = x264_clip3( h->param.analyse.i_trellis, 0, 2 );
  431.     h->param.rc.i_aq_mode = x264_clip3( h->param.rc.i_aq_mode, 0, 2 );
  432.     if( h->param.rc.f_aq_strength <= 0 )
  433.         h->param.rc.i_aq_mode = 0;
  434.     /* VAQ effectively replaces qcomp, so qcomp is raised towards 1 to compensate. */
  435.     if( h->param.rc.i_aq_mode == X264_AQ_GLOBAL )
  436.         h->param.rc.f_qcompress = x264_clip3f(h->param.rc.f_qcompress + h->param.rc.f_aq_strength / 0.7, 0, 1);
  437.     h->param.analyse.i_noise_reduction = x264_clip3( h->param.analyse.i_noise_reduction, 0, 1<<16 );
  438.     {
  439.         const x264_level_t *l = x264_levels;
  440.         if( h->param.i_level_idc < 0 )
  441.         {
  442.             if( h->param.rc.i_rc_method == X264_RC_ABR && h->param.rc.i_vbv_buffer_size <= 0 )
  443.                 h->param.rc.i_vbv_max_bitrate = h->param.rc.i_bitrate * 2;
  444.             h->sps = h->sps_array;
  445.             x264_sps_init( h->sps, h->param.i_sps_id, &h->param );
  446.             do h->param.i_level_idc = l->level_idc;
  447.                 while( l[1].level_idc && x264_validate_levels( h, 0 ) && l++ );
  448.             if( h->param.rc.i_vbv_buffer_size <= 0 )
  449.                 h->param.rc.i_vbv_max_bitrate = 0;
  450.             x264_log( h, X264_LOG_DEBUG, "level_idc: %dn", h->param.i_level_idc );
  451.         }
  452.         else
  453.         {
  454.             while( l->level_idc && l->level_idc != h->param.i_level_idc )
  455.                 l++;
  456.             if( l->level_idc == 0 )
  457.             {
  458.                 x264_log( h, X264_LOG_ERROR, "invalid level_idc: %dn", h->param.i_level_idc );
  459.                 return -1;
  460.             }
  461.         }
  462.         if( h->param.analyse.i_mv_range <= 0 )
  463.             h->param.analyse.i_mv_range = l->mv_range >> h->param.b_interlaced;
  464.         else
  465.             h->param.analyse.i_mv_range = x264_clip3(h->param.analyse.i_mv_range, 32, 512 >> h->param.b_interlaced);
  466.         if( h->param.analyse.i_direct_8x8_inference < 0 )
  467.             h->param.analyse.i_direct_8x8_inference = l->direct8x8;
  468.     }
  469.     if( h->param.i_threads > 1 )
  470.     {
  471.         int r = h->param.analyse.i_mv_range_thread;
  472.         int r2;
  473.         if( r <= 0 )
  474.         {
  475.             // half of the available space is reserved and divided evenly among the threads,
  476.             // the rest is allocated to whichever thread is far enough ahead to use it.
  477.             // reserving more space increases quality for some videos, but costs more time
  478.             // in thread synchronization.
  479.             int max_range = (h->param.i_height + X264_THREAD_HEIGHT) / h->param.i_threads - X264_THREAD_HEIGHT;
  480.             r = max_range / 2;
  481.         }
  482.         r = X264_MAX( r, h->param.analyse.i_me_range );
  483.         r = X264_MIN( r, h->param.analyse.i_mv_range );
  484.         // round up to use the whole mb row
  485.         r2 = (r & ~15) + ((-X264_THREAD_HEIGHT) & 15);
  486.         if( r2 < r )
  487.             r2 += 16;
  488.         x264_log( h, X264_LOG_DEBUG, "using mv_range_thread = %dn", r2 );
  489.         h->param.analyse.i_mv_range_thread = r2;
  490.     }
  491.     if( h->param.rc.f_qblur < 0 )
  492.         h->param.rc.f_qblur = 0;
  493.     if( h->param.rc.f_complexity_blur < 0 )
  494.         h->param.rc.f_complexity_blur = 0;
  495.     h->param.i_sps_id &= 31;
  496.     if( h->param.i_log_level < X264_LOG_INFO )
  497.     {
  498.         h->param.analyse.b_psnr = 0;
  499.         h->param.analyse.b_ssim = 0;
  500.     }
  501.     /* ensure the booleans are 0 or 1 so they can be used in math */
  502. #define BOOLIFY(x) h->param.x = !!h->param.x
  503.     BOOLIFY( b_cabac );
  504.     BOOLIFY( b_deblocking_filter );
  505.     BOOLIFY( b_interlaced );
  506.     BOOLIFY( analyse.b_transform_8x8 );
  507.     BOOLIFY( analyse.i_direct_8x8_inference );
  508.     BOOLIFY( analyse.b_bidir_me );
  509.     BOOLIFY( analyse.b_chroma_me );
  510.     BOOLIFY( analyse.b_fast_pskip );
  511.     BOOLIFY( rc.b_stat_write );
  512.     BOOLIFY( rc.b_stat_read );
  513. #undef BOOLIFY
  514.     return 0;
  515. }
  516. static void mbcmp_init( x264_t *h )
  517. {
  518.     int satd = !h->mb.b_lossless && h->param.analyse.i_subpel_refine > 1;
  519.     memcpy( h->pixf.mbcmp, satd ? h->pixf.satd : h->pixf.sad_aligned, sizeof(h->pixf.mbcmp) );
  520.     memcpy( h->pixf.mbcmp_unaligned, satd ? h->pixf.satd : h->pixf.sad, sizeof(h->pixf.mbcmp_unaligned) );
  521.     h->pixf.intra_mbcmp_x3_16x16 = satd ? h->pixf.intra_satd_x3_16x16 : h->pixf.intra_sad_x3_16x16;
  522.     satd &= h->param.analyse.i_me_method == X264_ME_TESA;
  523.     memcpy( h->pixf.fpelcmp, satd ? h->pixf.satd : h->pixf.sad, sizeof(h->pixf.fpelcmp) );
  524.     memcpy( h->pixf.fpelcmp_x3, satd ? h->pixf.satd_x3 : h->pixf.sad_x3, sizeof(h->pixf.fpelcmp_x3) );
  525.     memcpy( h->pixf.fpelcmp_x4, satd ? h->pixf.satd_x4 : h->pixf.sad_x4, sizeof(h->pixf.fpelcmp_x4) );
  526. }
  527. /****************************************************************************
  528.  * x264_encoder_open:
  529.  ****************************************************************************/
  530. x264_t *x264_encoder_open   ( x264_param_t *param )
  531. {
  532.     x264_t *h = x264_malloc( sizeof( x264_t ) );
  533.     char buf[1000], *p;
  534.     int i;
  535.     memset( h, 0, sizeof( x264_t ) );
  536.     /* Create a copy of param */
  537.     memcpy( &h->param, param, sizeof( x264_param_t ) );
  538.     if( x264_validate_parameters( h ) < 0 )
  539.     {
  540.         x264_free( h );
  541.         return NULL;
  542.     }
  543.     if( h->param.psz_cqm_file )
  544.         if( x264_cqm_parse_file( h, h->param.psz_cqm_file ) < 0 )
  545.         {
  546.             x264_free( h );
  547.             return NULL;
  548.         }
  549.     if( h->param.rc.psz_stat_out )
  550.         h->param.rc.psz_stat_out = strdup( h->param.rc.psz_stat_out );
  551.     if( h->param.rc.psz_stat_in )
  552.         h->param.rc.psz_stat_in = strdup( h->param.rc.psz_stat_in );
  553.     /* VUI */
  554.     if( h->param.vui.i_sar_width > 0 && h->param.vui.i_sar_height > 0 )
  555.     {
  556.         int i_w = param->vui.i_sar_width;
  557.         int i_h = param->vui.i_sar_height;
  558.         x264_reduce_fraction( &i_w, &i_h );
  559.         while( i_w > 65535 || i_h > 65535 )
  560.         {
  561.             i_w /= 2;
  562.             i_h /= 2;
  563.         }
  564.         h->param.vui.i_sar_width = 0;
  565.         h->param.vui.i_sar_height = 0;
  566.         if( i_w == 0 || i_h == 0 )
  567.         {
  568.             x264_log( h, X264_LOG_WARNING, "cannot create valid sample aspect ration" );
  569.         }
  570.         else
  571.         {
  572.             x264_log( h, X264_LOG_INFO, "using SAR=%d/%dn", i_w, i_h );
  573.             h->param.vui.i_sar_width = i_w;
  574.             h->param.vui.i_sar_height = i_h;
  575.         }
  576.     }
  577.     x264_reduce_fraction( &h->param.i_fps_num, &h->param.i_fps_den );
  578.     /* Init x264_t */
  579.     h->i_frame = 0;
  580.     h->i_frame_num = 0;
  581.     h->i_idr_pic_id = 0;
  582.     h->sps = &h->sps_array[0];
  583.     x264_sps_init( h->sps, h->param.i_sps_id, &h->param );
  584.     h->pps = &h->pps_array[0];
  585.     x264_pps_init( h->pps, h->param.i_sps_id, &h->param, h->sps);
  586.     x264_validate_levels( h, 1 );
  587.     if( x264_cqm_init( h ) < 0 )
  588.     {
  589.         x264_free( h );
  590.         return NULL;
  591.     }
  592.     h->mb.i_mb_count = h->sps->i_mb_width * h->sps->i_mb_height;
  593.     /* Init frames. */
  594.     h->frames.i_delay = h->param.i_bframe + h->param.i_threads - 1;
  595.     h->frames.i_max_ref0 = h->param.i_frame_reference;
  596.     h->frames.i_max_ref1 = h->sps->vui.i_num_reorder_frames;
  597.     h->frames.i_max_dpb  = h->sps->vui.i_max_dec_frame_buffering;
  598.     h->frames.b_have_lowres = !h->param.rc.b_stat_read
  599.         && ( h->param.rc.i_rc_method == X264_RC_ABR
  600.           || h->param.rc.i_rc_method == X264_RC_CRF
  601.           || h->param.b_bframe_adaptive
  602.           || h->param.b_pre_scenecut );
  603.     h->frames.b_have_lowres |= (h->param.rc.b_stat_read && h->param.rc.i_vbv_buffer_size > 0);
  604.     h->frames.i_last_idr = - h->param.i_keyint_max;
  605.     h->frames.i_input    = 0;
  606.     h->frames.last_nonb  = NULL;
  607.     h->i_ref0 = 0;
  608.     h->i_ref1 = 0;
  609.     h->chroma_qp_table = i_chroma_qp_table + 12 + h->pps->i_chroma_qp_index_offset;
  610.     x264_rdo_init( );
  611.     /* init CPU functions */
  612.     x264_predict_16x16_init( h->param.cpu, h->predict_16x16 );
  613.     x264_predict_8x8c_init( h->param.cpu, h->predict_8x8c );
  614.     x264_predict_8x8_init( h->param.cpu, h->predict_8x8 );
  615.     x264_predict_4x4_init( h->param.cpu, h->predict_4x4 );
  616.     x264_pixel_init( h->param.cpu, &h->pixf );
  617.     x264_dct_init( h->param.cpu, &h->dctf );
  618.     x264_zigzag_init( h->param.cpu, &h->zigzagf, h->param.b_interlaced );
  619.     x264_mc_init( h->param.cpu, &h->mc );
  620.     x264_quant_init( h, h->param.cpu, &h->quantf );
  621.     x264_deblock_init( h->param.cpu, &h->loopf );
  622.     x264_dct_init_weights();
  623.     mbcmp_init( h );
  624.     p = buf + sprintf( buf, "using cpu capabilities:" );
  625.     for( i=0; x264_cpu_names[i].flags; i++ )
  626.     {
  627.         if( !strcmp(x264_cpu_names[i].name, "SSE2")
  628.             && param->cpu & (X264_CPU_SSE2_IS_FAST|X264_CPU_SSE2_IS_SLOW) )
  629.             continue;
  630.         if( !strcmp(x264_cpu_names[i].name, "SSE3")
  631.             && (param->cpu & X264_CPU_SSSE3 || !(param->cpu & X264_CPU_CACHELINE_64)) )
  632.             continue;
  633.         if( (param->cpu & x264_cpu_names[i].flags) == x264_cpu_names[i].flags
  634.             && (!i || x264_cpu_names[i].flags != x264_cpu_names[i-1].flags) )
  635.             p += sprintf( p, " %s", x264_cpu_names[i].name );
  636.     }
  637.     if( !param->cpu )
  638.         p += sprintf( p, " none!" );
  639.     x264_log( h, X264_LOG_INFO, "%sn", buf );
  640.     h->out.i_nal = 0;
  641.     h->out.i_bitstream = X264_MAX( 1000000, h->param.i_width * h->param.i_height * 4
  642.         * ( h->param.rc.i_rc_method == X264_RC_ABR ? pow( 0.95, h->param.rc.i_qp_min )
  643.           : pow( 0.95, h->param.rc.i_qp_constant ) * X264_MAX( 1, h->param.rc.f_ip_factor )));
  644.     h->thread[0] = h;
  645.     h->i_thread_num = 0;
  646.     for( i = 1; i < h->param.i_threads; i++ )
  647.         h->thread[i] = x264_malloc( sizeof(x264_t) );
  648.     for( i = 0; i < h->param.i_threads; i++ )
  649.     {
  650.         if( i > 0 )
  651.             *h->thread[i] = *h;
  652.         h->thread[i]->fdec = x264_frame_pop_unused( h );
  653.         h->thread[i]->out.p_bitstream = x264_malloc( h->out.i_bitstream );
  654.         if( x264_macroblock_cache_init( h->thread[i] ) < 0 )
  655.             return NULL;
  656.     }
  657.     if( x264_ratecontrol_new( h ) < 0 )
  658.         return NULL;
  659.     if( h->param.psz_dump_yuv )
  660.     {
  661.         /* create or truncate the reconstructed video file */
  662.         FILE *f = fopen( h->param.psz_dump_yuv, "w" );
  663.         if( f )
  664.             fclose( f );
  665.         else
  666.         {
  667.             x264_log( h, X264_LOG_ERROR, "can't write to fdec.yuvn" );
  668.             x264_free( h );
  669.             return NULL;
  670.         }
  671.     }
  672.     return h;
  673. }
  674. /****************************************************************************
  675.  * x264_encoder_reconfig:
  676.  ****************************************************************************/
  677. int x264_encoder_reconfig( x264_t *h, x264_param_t *param )
  678. {
  679. #define COPY(var) h->param.var = param->var
  680.     COPY( i_frame_reference ); // but never uses more refs than initially specified
  681.     COPY( i_bframe_bias );
  682.     if( h->param.i_scenecut_threshold >= 0 && param->i_scenecut_threshold >= 0 )
  683.         COPY( i_scenecut_threshold ); // can't turn it on or off, only vary the threshold
  684.     COPY( b_deblocking_filter );
  685.     COPY( i_deblocking_filter_alphac0 );
  686.     COPY( i_deblocking_filter_beta );
  687.     COPY( analyse.intra );
  688.     COPY( analyse.inter );
  689.     COPY( analyse.i_direct_mv_pred );
  690.     COPY( analyse.i_me_method );
  691.     COPY( analyse.i_me_range );
  692.     COPY( analyse.i_noise_reduction );
  693.     COPY( analyse.i_subpel_refine );
  694.     COPY( analyse.i_trellis );
  695.     COPY( analyse.b_bidir_me );
  696.     COPY( analyse.b_bframe_rdo );
  697.     COPY( analyse.b_chroma_me );
  698.     COPY( analyse.b_dct_decimate );
  699.     COPY( analyse.b_fast_pskip );
  700.     COPY( analyse.b_mixed_references );
  701.     // can only twiddle these if they were enabled to begin with:
  702.     if( h->pps->b_transform_8x8_mode )
  703.         COPY( analyse.b_transform_8x8 );
  704.     if( h->frames.i_max_ref1 > 1 )
  705.         COPY( b_bframe_pyramid );
  706. #undef COPY
  707.     mbcmp_init( h );
  708.     return x264_validate_parameters( h );
  709. }
  710. /* internal usage */
  711. static void x264_nal_start( x264_t *h, int i_type, int i_ref_idc )
  712. {
  713.     x264_nal_t *nal = &h->out.nal[h->out.i_nal];
  714.     nal->i_ref_idc = i_ref_idc;
  715.     nal->i_type    = i_type;
  716.     nal->i_payload= 0;
  717.     nal->p_payload= &h->out.p_bitstream[bs_pos( &h->out.bs ) / 8];
  718. }
  719. static void x264_nal_end( x264_t *h )
  720. {
  721.     x264_nal_t *nal = &h->out.nal[h->out.i_nal];
  722.     nal->i_payload = &h->out.p_bitstream[bs_pos( &h->out.bs ) / 8] - nal->p_payload;
  723.     h->out.i_nal++;
  724. }
  725. /****************************************************************************
  726.  * x264_encoder_headers:
  727.  ****************************************************************************/
  728. int x264_encoder_headers( x264_t *h, x264_nal_t **pp_nal, int *pi_nal )
  729. {
  730.     /* init bitstream context */
  731.     h->out.i_nal = 0;
  732.     bs_init( &h->out.bs, h->out.p_bitstream, h->out.i_bitstream );
  733.     /* Put SPS and PPS */
  734.     if( h->i_frame == 0 )
  735.     {
  736.         /* identify ourself */
  737.         x264_nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
  738.         x264_sei_version_write( h, &h->out.bs );
  739.         x264_nal_end( h );
  740.         /* generate sequence parameters */
  741.         x264_nal_start( h, NAL_SPS, NAL_PRIORITY_HIGHEST );
  742.         x264_sps_write( &h->out.bs, h->sps );
  743.         x264_nal_end( h );
  744.         /* generate picture parameters */
  745.         x264_nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
  746.         x264_pps_write( &h->out.bs, h->pps );
  747.         x264_nal_end( h );
  748.     }
  749.     /* now set output*/
  750.     *pi_nal = h->out.i_nal;
  751.     *pp_nal = &h->out.nal[0];
  752.     h->out.i_nal = 0;
  753.     return 0;
  754. }
  755. static inline void x264_reference_build_list( x264_t *h, int i_poc )
  756. {
  757.     int i;
  758.     int b_ok;
  759.     /* build ref list 0/1 */
  760.     h->i_ref0 = 0;
  761.     h->i_ref1 = 0;
  762.     for( i = 0; h->frames.reference[i]; i++ )
  763.     {
  764.         if( h->frames.reference[i]->i_poc < i_poc )
  765.         {
  766.             h->fref0[h->i_ref0++] = h->frames.reference[i];
  767.         }
  768.         else if( h->frames.reference[i]->i_poc > i_poc )
  769.         {
  770.             h->fref1[h->i_ref1++] = h->frames.reference[i];
  771.         }
  772.     }
  773.     /* Order ref0 from higher to lower poc */
  774.     do
  775.     {
  776.         b_ok = 1;
  777.         for( i = 0; i < h->i_ref0 - 1; i++ )
  778.         {
  779.             if( h->fref0[i]->i_poc < h->fref0[i+1]->i_poc )
  780.             {
  781.                 XCHG( x264_frame_t*, h->fref0[i], h->fref0[i+1] );
  782.                 b_ok = 0;
  783.                 break;
  784.             }
  785.         }
  786.     } while( !b_ok );
  787.     /* Order ref1 from lower to higher poc (bubble sort) for B-frame */
  788.     do
  789.     {
  790.         b_ok = 1;
  791.         for( i = 0; i < h->i_ref1 - 1; i++ )
  792.         {
  793.             if( h->fref1[i]->i_poc > h->fref1[i+1]->i_poc )
  794.             {
  795.                 XCHG( x264_frame_t*, h->fref1[i], h->fref1[i+1] );
  796.                 b_ok = 0;
  797.                 break;
  798.             }
  799.         }
  800.     } while( !b_ok );
  801.     /* In the standard, a P-frame's ref list is sorted by frame_num.
  802.      * We use POC, but check whether explicit reordering is needed */
  803.     h->b_ref_reorder[0] =
  804.     h->b_ref_reorder[1] = 0;
  805.     if( h->sh.i_type == SLICE_TYPE_P )
  806.     {
  807.         for( i = 0; i < h->i_ref0 - 1; i++ )
  808.             if( h->fref0[i]->i_frame_num < h->fref0[i+1]->i_frame_num )
  809.             {
  810.                 h->b_ref_reorder[0] = 1;
  811.                 break;
  812.             }
  813.     }
  814.     h->i_ref1 = X264_MIN( h->i_ref1, h->frames.i_max_ref1 );
  815.     h->i_ref0 = X264_MIN( h->i_ref0, h->frames.i_max_ref0 );
  816.     h->i_ref0 = X264_MIN( h->i_ref0, h->param.i_frame_reference ); // if reconfig() has lowered the limit
  817.     assert( h->i_ref0 + h->i_ref1 <= 16 );
  818.     h->mb.pic.i_fref[0] = h->i_ref0;
  819.     h->mb.pic.i_fref[1] = h->i_ref1;
  820. }
  821. static void x264_fdec_filter_row( x264_t *h, int mb_y )
  822. {
  823.     /* mb_y is the mb to be encoded next, not the mb to be filtered here */
  824.     int b_hpel = h->fdec->b_kept_as_ref;
  825.     int b_deblock = !h->sh.i_disable_deblocking_filter_idc;
  826.     int b_end = mb_y == h->sps->i_mb_height;
  827.     int min_y = mb_y - (1 << h->sh.b_mbaff);
  828.     int max_y = b_end ? h->sps->i_mb_height : mb_y;
  829.     b_deblock &= b_hpel || h->param.psz_dump_yuv;
  830.     if( mb_y & h->sh.b_mbaff )
  831.         return;
  832.     if( min_y < 0 )
  833.         return;
  834.     if( !b_end )
  835.     {
  836.         int i, j;
  837.         for( j=0; j<=h->sh.b_mbaff; j++ )
  838.             for( i=0; i<3; i++ )
  839.             {
  840.                 memcpy( h->mb.intra_border_backup[j][i],
  841.                         h->fdec->plane[i] + ((mb_y*16 >> !!i) + j - 1 - h->sh.b_mbaff) * h->fdec->i_stride[i],
  842.                         h->sps->i_mb_width*16 >> !!i );
  843.             }
  844.     }
  845.     if( b_deblock )
  846.     {
  847.         int y;
  848.         for( y = min_y; y < max_y; y += (1 << h->sh.b_mbaff) )
  849.             x264_frame_deblock_row( h, y );
  850.     }
  851.     if( b_hpel )
  852.     {
  853.         x264_frame_expand_border( h, h->fdec, min_y, b_end );
  854.         x264_frame_filter( h, h->fdec, min_y, b_end );
  855.         x264_frame_expand_border_filtered( h, h->fdec, min_y, b_end );
  856.     }
  857.     if( h->param.i_threads > 1 && h->fdec->b_kept_as_ref )
  858.     {
  859.         x264_frame_cond_broadcast( h->fdec, mb_y*16 + (b_end ? 10000 : -(X264_THREAD_HEIGHT << h->sh.b_mbaff)) );
  860.     }
  861.     min_y = X264_MAX( min_y*16-8, 0 );
  862.     max_y = b_end ? h->param.i_height : mb_y*16-8;
  863.     if( h->param.analyse.b_psnr )
  864.     {
  865.         int i;
  866.         for( i=0; i<3; i++ )
  867.             h->stat.frame.i_ssd[i] +=
  868.                 x264_pixel_ssd_wxh( &h->pixf,
  869.                     h->fdec->plane[i] + (min_y>>!!i) * h->fdec->i_stride[i], h->fdec->i_stride[i],
  870.                     h->fenc->plane[i] + (min_y>>!!i) * h->fenc->i_stride[i], h->fenc->i_stride[i],
  871.                     h->param.i_width >> !!i, (max_y-min_y) >> !!i );
  872.     }
  873.     if( h->param.analyse.b_ssim )
  874.     {
  875.         x264_emms();
  876.         /* offset by 2 pixels to avoid alignment of ssim blocks with dct blocks,
  877.          * and overlap by 4 */
  878.         min_y += min_y == 0 ? 2 : -6;
  879.         h->stat.frame.f_ssim +=
  880.             x264_pixel_ssim_wxh( &h->pixf,
  881.                 h->fdec->plane[0] + 2+min_y*h->fdec->i_stride[0], h->fdec->i_stride[0],
  882.                 h->fenc->plane[0] + 2+min_y*h->fenc->i_stride[0], h->fenc->i_stride[0],
  883.                 h->param.i_width-2, max_y-min_y );
  884.     }
  885. }
  886. static inline void x264_reference_update( x264_t *h )
  887. {
  888.     int i;
  889.     if( h->fdec->i_frame >= 0 )
  890.         h->i_frame++;
  891.     if( !h->fdec->b_kept_as_ref )
  892.     {
  893.         if( h->param.i_threads > 1 )
  894.         {
  895.             x264_frame_push_unused( h, h->fdec );
  896.             h->fdec = x264_frame_pop_unused( h );
  897.         }
  898.         return;
  899.     }
  900.     /* move lowres copy of the image to the ref frame */
  901.     for( i = 0; i < 4; i++)
  902.     {
  903.         XCHG( uint8_t*, h->fdec->lowres[i], h->fenc->lowres[i] );
  904.         XCHG( uint8_t*, h->fdec->buffer_lowres[i], h->fenc->buffer_lowres[i] );
  905.     }
  906.     /* adaptive B decision needs a pointer, since it can't use the ref lists */
  907.     if( h->sh.i_type != SLICE_TYPE_B )
  908.         h->frames.last_nonb = h->fdec;
  909.     /* move frame in the buffer */
  910.     x264_frame_push( h->frames.reference, h->fdec );
  911.     if( h->frames.reference[h->frames.i_max_dpb] )
  912.         x264_frame_push_unused( h, x264_frame_shift( h->frames.reference ) );
  913.     h->fdec = x264_frame_pop_unused( h );
  914. }
  915. static inline void x264_reference_reset( x264_t *h )
  916. {
  917.     while( h->frames.reference[0] )
  918.         x264_frame_push_unused( h, x264_frame_pop( h->frames.reference ) );
  919.     h->fdec->i_poc =
  920.     h->fenc->i_poc = 0;
  921. }
  922. static inline void x264_slice_init( x264_t *h, int i_nal_type, int i_global_qp )
  923. {
  924.     /* ------------------------ Create slice header  ----------------------- */
  925.     if( i_nal_type == NAL_SLICE_IDR )
  926.     {
  927.         x264_slice_header_init( h, &h->sh, h->sps, h->pps, h->i_idr_pic_id, h->i_frame_num, i_global_qp );
  928.         /* increment id */
  929.         h->i_idr_pic_id = ( h->i_idr_pic_id + 1 ) % 65536;
  930.     }
  931.     else
  932.     {
  933.         x264_slice_header_init( h, &h->sh, h->sps, h->pps, -1, h->i_frame_num, i_global_qp );
  934.         /* always set the real higher num of ref frame used */
  935.         h->sh.b_num_ref_idx_override = 1;
  936.         h->sh.i_num_ref_idx_l0_active = h->i_ref0 <= 0 ? 1 : h->i_ref0;
  937.         h->sh.i_num_ref_idx_l1_active = h->i_ref1 <= 0 ? 1 : h->i_ref1;
  938.     }
  939.     h->fdec->i_frame_num = h->sh.i_frame_num;
  940.     if( h->sps->i_poc_type == 0 )
  941.     {
  942.         h->sh.i_poc_lsb = h->fdec->i_poc & ( (1 << h->sps->i_log2_max_poc_lsb) - 1 );
  943.         h->sh.i_delta_poc_bottom = 0;   /* XXX won't work for field */
  944.     }
  945.     else if( h->sps->i_poc_type == 1 )
  946.     {
  947.         /* FIXME TODO FIXME */
  948.     }
  949.     else
  950.     {
  951.         /* Nothing to do ? */
  952.     }
  953.     x264_macroblock_slice_init( h );
  954. }
  955. static void x264_slice_write( x264_t *h )
  956. {
  957.     int i_skip;
  958.     int mb_xy, i_mb_x, i_mb_y;
  959.     int i, i_list, i_ref;
  960.     /* init stats */
  961.     memset( &h->stat.frame, 0, sizeof(h->stat.frame) );
  962.     /* Slice */
  963.     x264_nal_start( h, h->i_nal_type, h->i_nal_ref_idc );
  964.     /* Slice header */
  965.     x264_slice_header_write( &h->out.bs, &h->sh, h->i_nal_ref_idc );
  966.     if( h->param.b_cabac )
  967.     {
  968.         /* alignment needed */
  969.         bs_align_1( &h->out.bs );
  970.         /* init cabac */
  971.         x264_cabac_context_init( &h->cabac, h->sh.i_type, h->sh.i_qp, h->sh.i_cabac_init_idc );
  972.         x264_cabac_encode_init ( &h->cabac, h->out.bs.p, h->out.bs.p_end );
  973.     }
  974.     h->mb.i_last_qp = h->sh.i_qp;
  975.     h->mb.i_last_dqp = 0;
  976.     i_mb_y = h->sh.i_first_mb / h->sps->i_mb_width;
  977.     i_mb_x = h->sh.i_first_mb % h->sps->i_mb_width;
  978.     i_skip = 0;
  979.     while( (mb_xy = i_mb_x + i_mb_y * h->sps->i_mb_width) < h->sh.i_last_mb )
  980.     {
  981.         int mb_spos = bs_pos(&h->out.bs) + x264_cabac_pos(&h->cabac);
  982.         if( i_mb_x == 0 )
  983.             x264_fdec_filter_row( h, i_mb_y );
  984.         /* load cache */
  985.         x264_macroblock_cache_load( h, i_mb_x, i_mb_y );
  986.         /* analyse parameters
  987.          * Slice I: choose I_4x4 or I_16x16 mode
  988.          * Slice P: choose between using P mode or intra (4x4 or 16x16)
  989.          * */
  990.         x264_macroblock_analyse( h );
  991.         /* encode this macroblock -> be careful it can change the mb type to P_SKIP if needed */
  992.         x264_macroblock_encode( h );
  993.         x264_bitstream_check_buffer( h );
  994.         if( h->param.b_cabac )
  995.         {
  996.             if( mb_xy > h->sh.i_first_mb && !(h->sh.b_mbaff && (i_mb_y&1)) )
  997.                 x264_cabac_encode_terminal( &h->cabac );
  998.             if( IS_SKIP( h->mb.i_type ) )
  999.                 x264_cabac_mb_skip( h, 1 );
  1000.             else
  1001.             {
  1002.                 if( h->sh.i_type != SLICE_TYPE_I )
  1003.                     x264_cabac_mb_skip( h, 0 );
  1004.                 x264_macroblock_write_cabac( h, &h->cabac );
  1005.             }
  1006.         }
  1007.         else
  1008.         {
  1009.             if( IS_SKIP( h->mb.i_type ) )
  1010.                 i_skip++;
  1011.             else
  1012.             {
  1013.                 if( h->sh.i_type != SLICE_TYPE_I )
  1014.                 {
  1015.                     bs_write_ue( &h->out.bs, i_skip );  /* skip run */
  1016.                     i_skip = 0;
  1017.                 }
  1018.                 x264_macroblock_write_cavlc( h, &h->out.bs );
  1019.             }
  1020.         }
  1021. #if VISUALIZE
  1022.         if( h->param.b_visualize )
  1023.             x264_visualize_mb( h );
  1024. #endif
  1025.         /* save cache */
  1026.         x264_macroblock_cache_save( h );
  1027.         /* accumulate mb stats */
  1028.         h->stat.frame.i_mb_count[h->mb.i_type]++;
  1029.         if( !IS_SKIP(h->mb.i_type) && !IS_INTRA(h->mb.i_type) && !IS_DIRECT(h->mb.i_type) )
  1030.         {
  1031.             if( h->mb.i_partition != D_8x8 )
  1032.                 h->stat.frame.i_mb_partition[h->mb.i_partition] += 4;
  1033.             else
  1034.                 for( i = 0; i < 4; i++ )
  1035.                     h->stat.frame.i_mb_partition[h->mb.i_sub_partition[i]] ++;
  1036.             if( h->param.i_frame_reference > 1 )
  1037.                 for( i_list = 0; i_list <= (h->sh.i_type == SLICE_TYPE_B); i_list++ )
  1038.                     for( i = 0; i < 4; i++ )
  1039.                     {
  1040.                         i_ref = h->mb.cache.ref[i_list][ x264_scan8[4*i] ];
  1041.                         if( i_ref >= 0 )
  1042.                             h->stat.frame.i_mb_count_ref[i_list][i_ref] ++;
  1043.                     }
  1044.         }
  1045.         if( h->mb.i_cbp_luma && !IS_INTRA(h->mb.i_type) )
  1046.         {
  1047.             h->stat.frame.i_mb_count_8x8dct[0] ++;
  1048.             h->stat.frame.i_mb_count_8x8dct[1] += h->mb.b_transform_8x8;
  1049.         }
  1050.         x264_ratecontrol_mb( h, bs_pos(&h->out.bs) + x264_cabac_pos(&h->cabac) - mb_spos );
  1051.         if( h->sh.b_mbaff )
  1052.         {
  1053.             i_mb_x += i_mb_y & 1;
  1054.             i_mb_y ^= i_mb_x < h->sps->i_mb_width;
  1055.         }
  1056.         else
  1057.             i_mb_x++;
  1058.         if(i_mb_x == h->sps->i_mb_width)
  1059.         {
  1060.             i_mb_y++;
  1061.             i_mb_x = 0;
  1062.         }
  1063.     }
  1064.     if( h->param.b_cabac )
  1065.     {
  1066.         x264_cabac_encode_flush( h, &h->cabac );
  1067.         h->out.bs.p = h->cabac.p;
  1068.     }
  1069.     else
  1070.     {
  1071.         if( i_skip > 0 )
  1072.             bs_write_ue( &h->out.bs, i_skip );  /* last skip run */
  1073.         /* rbsp_slice_trailing_bits */
  1074.         bs_rbsp_trailing( &h->out.bs );
  1075.     }
  1076.     x264_nal_end( h );
  1077.     x264_fdec_filter_row( h, h->sps->i_mb_height );
  1078.     /* Compute misc bits */
  1079.     h->stat.frame.i_misc_bits = bs_pos( &h->out.bs )
  1080.                               + NALU_OVERHEAD * 8
  1081.                               - h->stat.frame.i_tex_bits
  1082.                               - h->stat.frame.i_mv_bits;
  1083. }
  1084. static void x264_thread_sync_context( x264_t *dst, x264_t *src )
  1085. {
  1086.     x264_frame_t **f;
  1087.     if( dst == src )
  1088.         return;
  1089.     // reference counting
  1090.     for( f = src->frames.reference; *f; f++ )
  1091.         (*f)->i_reference_count++;
  1092.     for( f = dst->frames.reference; *f; f++ )
  1093.         x264_frame_push_unused( src, *f );
  1094.     src->fdec->i_reference_count++;
  1095.     x264_frame_push_unused( src, dst->fdec );
  1096.     // copy everything except the per-thread pointers and the constants.
  1097.     memcpy( &dst->i_frame, &src->i_frame, offsetof(x264_t, mb.type) - offsetof(x264_t, i_frame) );
  1098.     dst->stat = src->stat;
  1099. }
  1100. static void x264_thread_sync_stat( x264_t *dst, x264_t *src )
  1101. {
  1102.     if( dst == src )
  1103.         return;
  1104.     memcpy( &dst->stat.i_slice_count, &src->stat.i_slice_count, sizeof(dst->stat) - sizeof(dst->stat.frame) );
  1105. }
  1106. static int x264_slices_write( x264_t *h )
  1107. {
  1108.     int i_frame_size;
  1109. #if VISUALIZE
  1110.     if( h->param.b_visualize )
  1111.         x264_visualize_init( h );
  1112. #endif
  1113.     x264_stack_align( x264_slice_write, h );
  1114.     i_frame_size = h->out.nal[h->out.i_nal-1].i_payload;
  1115. #if VISUALIZE
  1116.     if( h->param.b_visualize )
  1117.     {
  1118.         x264_visualize_show( h );
  1119.         x264_visualize_close( h );
  1120.     }
  1121. #endif
  1122.     h->out.i_frame_size = i_frame_size;
  1123.     return 0;
  1124. }
  1125. /****************************************************************************
  1126.  * x264_encoder_encode:
  1127.  *  XXX: i_poc   : is the poc of the current given picture
  1128.  *       i_frame : is the number of the frame being coded
  1129.  *  ex:  type frame poc
  1130.  *       I      0   2*0
  1131.  *       P      1   2*3
  1132.  *       B      2   2*1
  1133.  *       B      3   2*2
  1134.  *       P      4   2*6
  1135.  *       B      5   2*4
  1136.  *       B      6   2*5
  1137.  ****************************************************************************/
  1138. int     x264_encoder_encode( x264_t *h,
  1139.                              x264_nal_t **pp_nal, int *pi_nal,
  1140.                              x264_picture_t *pic_in,
  1141.                              x264_picture_t *pic_out )
  1142. {
  1143.     x264_t *thread_current, *thread_prev, *thread_oldest;
  1144.     int     i_nal_type;
  1145.     int     i_nal_ref_idc;
  1146.     int   i_global_qp;
  1147.     if( h->param.i_threads > 1)
  1148.     {
  1149.         int i = ++h->i_thread_phase;
  1150.         int t = h->param.i_threads;
  1151.         thread_current = h->thread[ i%t ];
  1152.         thread_prev    = h->thread[ (i-1)%t ];
  1153.         thread_oldest  = h->thread[ (i+1)%t ];
  1154.         x264_thread_sync_context( thread_current, thread_prev );
  1155.         x264_thread_sync_ratecontrol( thread_current, thread_prev, thread_oldest );
  1156.         h = thread_current;
  1157. //      fprintf(stderr, "current: %p  prev: %p  oldest: %p n", thread_current, thread_prev, thread_oldest);
  1158.     }
  1159.     else
  1160.     {
  1161.         thread_current =
  1162.         thread_prev    =
  1163.         thread_oldest  = h;
  1164.     }
  1165.     // ok to call this before encoding any frames, since the initial values of fdec have b_kept_as_ref=0
  1166.     x264_reference_update( h );
  1167.     h->fdec->i_lines_completed = -1;
  1168.     /* no data out */
  1169.     *pi_nal = 0;
  1170.     *pp_nal = NULL;
  1171.     /* ------------------- Setup new frame from picture -------------------- */
  1172.     if( pic_in != NULL )
  1173.     {
  1174.         /* 1: Copy the picture to a frame and move it to a buffer */
  1175.         x264_frame_t *fenc = x264_frame_pop_unused( h );
  1176.         if( x264_frame_copy_picture( h, fenc, pic_in ) < 0 )
  1177.             return -1;
  1178.         if( h->param.i_width != 16 * h->sps->i_mb_width ||
  1179.             h->param.i_height != 16 * h->sps->i_mb_height )
  1180.             x264_frame_expand_border_mod16( h, fenc );
  1181.         fenc->i_frame = h->frames.i_input++;
  1182.         x264_frame_push( h->frames.next, fenc );
  1183.         if( h->frames.b_have_lowres )
  1184.             x264_frame_init_lowres( h, fenc );
  1185.         if( h->frames.i_input <= h->frames.i_delay + 1 - h->param.i_threads )
  1186.         {
  1187.             /* Nothing yet to encode */
  1188.             /* waiting for filling bframe buffer */
  1189.             pic_out->i_type = X264_TYPE_AUTO;
  1190.             return 0;
  1191.         }
  1192.     }
  1193.     if( h->frames.current[0] == NULL )
  1194.     {
  1195.         int bframes = 0;
  1196.         /* 2: Select frame types */
  1197.         if( h->frames.next[0] == NULL )
  1198.         {
  1199.             x264_encoder_frame_end( thread_oldest, thread_current, pp_nal, pi_nal, pic_out );
  1200.             return 0;
  1201.         }
  1202.         x264_slicetype_decide( h );
  1203.         /* 3: move some B-frames and 1 non-B to encode queue */
  1204.         while( IS_X264_TYPE_B( h->frames.next[bframes]->i_type ) )
  1205.             bframes++;
  1206.         x264_frame_push( h->frames.current, x264_frame_shift( &h->frames.next[bframes] ) );
  1207.         /* FIXME: when max B-frames > 3, BREF may no longer be centered after GOP closing */
  1208.         if( h->param.b_bframe_pyramid && bframes > 1 )
  1209.         {
  1210.             x264_frame_t *mid = x264_frame_shift( &h->frames.next[bframes/2] );
  1211.             mid->i_type = X264_TYPE_BREF;
  1212.             x264_frame_push( h->frames.current, mid );
  1213.             bframes--;
  1214.         }
  1215.         while( bframes-- )
  1216.             x264_frame_push( h->frames.current, x264_frame_shift( h->frames.next ) );
  1217.     }
  1218.     /* ------------------- Get frame to be encoded ------------------------- */
  1219.     /* 4: get picture to encode */
  1220.     h->fenc = x264_frame_shift( h->frames.current );
  1221.     if( h->fenc == NULL )
  1222.     {
  1223.         /* Nothing yet to encode (ex: waiting for I/P with B frames) */
  1224.         /* waiting for filling bframe buffer */
  1225.         pic_out->i_type = X264_TYPE_AUTO;
  1226.         return 0;
  1227.     }
  1228. do_encode:
  1229.     if( h->fenc->i_type == X264_TYPE_IDR )
  1230.     {
  1231.         h->frames.i_last_idr = h->fenc->i_frame;
  1232.     }
  1233.     /* ------------------- Setup frame context ----------------------------- */
  1234.     /* 5: Init data dependent of frame type */
  1235.     if( h->fenc->i_type == X264_TYPE_IDR )
  1236.     {
  1237.         /* reset ref pictures */
  1238.         x264_reference_reset( h );
  1239.         i_nal_type    = NAL_SLICE_IDR;
  1240.         i_nal_ref_idc = NAL_PRIORITY_HIGHEST;
  1241.         h->sh.i_type = SLICE_TYPE_I;
  1242.     }
  1243.     else if( h->fenc->i_type == X264_TYPE_I )
  1244.     {
  1245.         i_nal_type    = NAL_SLICE;
  1246.         i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
  1247.         h->sh.i_type = SLICE_TYPE_I;
  1248.     }
  1249.     else if( h->fenc->i_type == X264_TYPE_P )
  1250.     {
  1251.         i_nal_type    = NAL_SLICE;
  1252.         i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
  1253.         h->sh.i_type = SLICE_TYPE_P;
  1254.     }
  1255.     else if( h->fenc->i_type == X264_TYPE_BREF )
  1256.     {
  1257.         i_nal_type    = NAL_SLICE;
  1258.         i_nal_ref_idc = NAL_PRIORITY_HIGH; /* maybe add MMCO to forget it? -> low */
  1259.         h->sh.i_type = SLICE_TYPE_B;
  1260.     }
  1261.     else    /* B frame */
  1262.     {
  1263.         i_nal_type    = NAL_SLICE;
  1264.         i_nal_ref_idc = NAL_PRIORITY_DISPOSABLE;
  1265.         h->sh.i_type = SLICE_TYPE_B;
  1266.     }
  1267.     h->fdec->i_poc =
  1268.     h->fenc->i_poc = 2 * (h->fenc->i_frame - h->frames.i_last_idr);
  1269.     h->fdec->i_type = h->fenc->i_type;
  1270.     h->fdec->i_frame = h->fenc->i_frame;
  1271.     h->fenc->b_kept_as_ref =
  1272.     h->fdec->b_kept_as_ref = i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE && h->param.i_keyint_max > 1;
  1273.     /* ------------------- Init                ----------------------------- */
  1274.     /* build ref list 0/1 */
  1275.     x264_reference_build_list( h, h->fdec->i_poc );
  1276.     /* Init the rate control */
  1277.     x264_ratecontrol_start( h, h->fenc->i_qpplus1 );
  1278.     i_global_qp = x264_ratecontrol_qp( h );
  1279.     pic_out->i_qpplus1 =
  1280.     h->fdec->i_qpplus1 = i_global_qp + 1;
  1281.     if( h->sh.i_type == SLICE_TYPE_B )
  1282.         x264_macroblock_bipred_init( h );
  1283.     /* ------------------------ Create slice header  ----------------------- */
  1284.     x264_slice_init( h, i_nal_type, i_global_qp );
  1285.     if( i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE )
  1286.         h->i_frame_num++;
  1287.     /* ---------------------- Write the bitstream -------------------------- */
  1288.     /* Init bitstream context */
  1289.     h->out.i_nal = 0;
  1290.     bs_init( &h->out.bs, h->out.p_bitstream, h->out.i_bitstream );
  1291.     if(h->param.b_aud){
  1292.         int pic_type;
  1293.         if(h->sh.i_type == SLICE_TYPE_I)
  1294.             pic_type = 0;
  1295.         else if(h->sh.i_type == SLICE_TYPE_P)
  1296.             pic_type = 1;
  1297.         else if(h->sh.i_type == SLICE_TYPE_B)
  1298.             pic_type = 2;
  1299.         else
  1300.             pic_type = 7;
  1301.         x264_nal_start(h, NAL_AUD, NAL_PRIORITY_DISPOSABLE);
  1302.         bs_write(&h->out.bs, 3, pic_type);
  1303.         bs_rbsp_trailing(&h->out.bs);
  1304.         x264_nal_end(h);
  1305.     }
  1306.     h->i_nal_type = i_nal_type;
  1307.     h->i_nal_ref_idc = i_nal_ref_idc;
  1308.     /* Write SPS and PPS */
  1309.     if( i_nal_type == NAL_SLICE_IDR && h->param.b_repeat_headers )
  1310.     {
  1311.         if( h->fenc->i_frame == 0 )
  1312.         {
  1313.             /* identify ourself */
  1314.             x264_nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
  1315.             x264_sei_version_write( h, &h->out.bs );
  1316.             x264_nal_end( h );
  1317.         }
  1318.         /* generate sequence parameters */
  1319.         x264_nal_start( h, NAL_SPS, NAL_PRIORITY_HIGHEST );
  1320.         x264_sps_write( &h->out.bs, h->sps );
  1321.         x264_nal_end( h );
  1322.         /* generate picture parameters */
  1323.         x264_nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
  1324.         x264_pps_write( &h->out.bs, h->pps );
  1325.         x264_nal_end( h );
  1326.     }
  1327.     /* Write frame */
  1328.     if( h->param.i_threads > 1 )
  1329.     {
  1330.         x264_pthread_create( &h->thread_handle, NULL, (void*)x264_slices_write, h );
  1331.         h->b_thread_active = 1;
  1332.     }
  1333.     else
  1334.         x264_slices_write( h );
  1335.     /* restore CPU state (before using float again) */
  1336.     x264_emms();
  1337.     if( h->sh.i_type == SLICE_TYPE_P && !h->param.rc.b_stat_read
  1338.         && h->param.i_scenecut_threshold >= 0
  1339.         && !h->param.b_pre_scenecut )
  1340.     {
  1341.         const int *mbs = h->stat.frame.i_mb_count;
  1342.         int i_mb_i = mbs[I_16x16] + mbs[I_8x8] + mbs[I_4x4];
  1343.         int i_mb_p = mbs[P_L0] + mbs[P_8x8];
  1344.         int i_mb_s = mbs[P_SKIP];
  1345.         int i_mb   = h->sps->i_mb_width * h->sps->i_mb_height;
  1346.         int64_t i_inter_cost = h->stat.frame.i_inter_cost;
  1347.         int64_t i_intra_cost = h->stat.frame.i_intra_cost;
  1348.         float f_bias;
  1349.         int i_gop_size = h->fenc->i_frame - h->frames.i_last_idr;
  1350.         float f_thresh_max = h->param.i_scenecut_threshold / 100.0;
  1351.         /* magic numbers pulled out of thin air */
  1352.         float f_thresh_min = f_thresh_max * h->param.i_keyint_min
  1353.                              / ( h->param.i_keyint_max * 4 );
  1354.         if( h->param.i_keyint_min == h->param.i_keyint_max )
  1355.              f_thresh_min= f_thresh_max;
  1356.         /* macroblock_analyse() doesn't further analyse skipped mbs,
  1357.          * so we have to guess their cost */
  1358.         if( h->stat.frame.i_mbs_analysed > 0 )
  1359.             i_intra_cost = i_intra_cost * i_mb / h->stat.frame.i_mbs_analysed;
  1360.         if( i_gop_size < h->param.i_keyint_min / 4 )
  1361.             f_bias = f_thresh_min / 4;
  1362.         else if( i_gop_size <= h->param.i_keyint_min )
  1363.             f_bias = f_thresh_min * i_gop_size / h->param.i_keyint_min;
  1364.         else
  1365.         {
  1366.             f_bias = f_thresh_min
  1367.                      + ( f_thresh_max - f_thresh_min )
  1368.                        * ( i_gop_size - h->param.i_keyint_min )
  1369.                        / ( h->param.i_keyint_max - h->param.i_keyint_min );
  1370.         }
  1371.         f_bias = X264_MIN( f_bias, 1.0 );
  1372.         /* Bad P will be reencoded as I */
  1373.         if( h->stat.frame.i_mbs_analysed > 0 &&
  1374.             i_inter_cost >= (1.0 - f_bias) * i_intra_cost )
  1375.         {
  1376.             int b;
  1377.             x264_log( h, X264_LOG_DEBUG, "scene cut at %d Icost:%.0f Pcost:%.0f ratio:%.4f bias:%.4f gop:%d (imb:%d pmb:%d smb:%d)n",
  1378.                       h->fenc->i_frame,
  1379.                       (double)i_intra_cost, (double)i_inter_cost,
  1380.                       1. - (double)i_inter_cost / i_intra_cost,
  1381.                       f_bias, i_gop_size,
  1382.                       i_mb_i, i_mb_p, i_mb_s );
  1383.             /* Restore frame num */
  1384.             h->i_frame_num--;
  1385.             for( b = 0; h->frames.current[b] && IS_X264_TYPE_B( h->frames.current[b]->i_type ); b++ );
  1386.             if( b > 0 )
  1387.             {
  1388.                 /* If using B-frames, force GOP to be closed.
  1389.                  * Even if this frame is going to be I and not IDR, forcing a
  1390.                  * P-frame before the scenecut will probably help compression.
  1391.                  *
  1392.                  * We don't yet know exactly which frame is the scene cut, so
  1393.                  * we can't assign an I-frame. Instead, change the previous
  1394.                  * B-frame to P, and rearrange coding order. */
  1395.                 if( h->param.b_bframe_adaptive || b > 1 )
  1396.                     h->fenc->i_type = X264_TYPE_AUTO;
  1397.                 x264_frame_sort_pts( h->frames.current );
  1398.                 x264_frame_unshift( h->frames.next, h->fenc );
  1399.                 h->fenc = h->frames.current[b-1];
  1400.                 h->frames.current[b-1] = NULL;
  1401.                 h->fenc->i_type = X264_TYPE_P;
  1402.                 x264_frame_sort_dts( h->frames.current );
  1403.             }
  1404.             /* Do IDR if needed */
  1405.             else if( i_gop_size >= h->param.i_keyint_min )
  1406.             {
  1407.                 /* Reset */
  1408.                 h->i_frame_num = 0;
  1409.                 /* Reinit field of fenc */
  1410.                 h->fenc->i_type = X264_TYPE_IDR;
  1411.                 h->fenc->i_poc = 0;
  1412.                 /* Put enqueued frames back in the pool */
  1413.                 while( h->frames.current[0] )
  1414.                     x264_frame_push( h->frames.next, x264_frame_shift( h->frames.current ) );
  1415.                 x264_frame_sort_pts( h->frames.next );
  1416.             }
  1417.             else
  1418.             {
  1419.                 h->fenc->i_type = X264_TYPE_I;
  1420.             }
  1421.             goto do_encode;
  1422.         }
  1423.     }
  1424.     x264_encoder_frame_end( thread_oldest, thread_current, pp_nal, pi_nal, pic_out );
  1425.     return 0;
  1426. }
  1427. static void x264_encoder_frame_end( x264_t *h, x264_t *thread_current,
  1428.                                     x264_nal_t **pp_nal, int *pi_nal,
  1429.                                     x264_picture_t *pic_out )
  1430. {
  1431.     int i, i_list;
  1432.     char psz_message[80];
  1433.     if( h->b_thread_active )
  1434.     {
  1435.         x264_pthread_join( h->thread_handle, NULL );
  1436.         h->b_thread_active = 0;
  1437.     }
  1438.     if( !h->out.i_nal )
  1439.     {
  1440.         pic_out->i_type = X264_TYPE_AUTO;
  1441.         return;
  1442.     }
  1443.     x264_frame_push_unused( thread_current, h->fenc );
  1444.     /* End bitstream, set output  */
  1445.     *pi_nal = h->out.i_nal;
  1446.     *pp_nal = h->out.nal;
  1447.     h->out.i_nal = 0;
  1448.     /* Set output picture properties */
  1449.     if( h->sh.i_type == SLICE_TYPE_I )
  1450.         pic_out->i_type = h->i_nal_type == NAL_SLICE_IDR ? X264_TYPE_IDR : X264_TYPE_I;
  1451.     else if( h->sh.i_type == SLICE_TYPE_P )
  1452.         pic_out->i_type = X264_TYPE_P;
  1453.     else
  1454.         pic_out->i_type = X264_TYPE_B;
  1455.     pic_out->i_pts = h->fenc->i_pts;
  1456.     pic_out->img.i_plane = h->fdec->i_plane;
  1457.     for(i = 0; i < 4; i++){
  1458.         pic_out->img.i_stride[i] = h->fdec->i_stride[i];
  1459.         pic_out->img.plane[i] = h->fdec->plane[i];
  1460.     }
  1461.     /* ---------------------- Update encoder state ------------------------- */
  1462.     /* update rc */
  1463.     x264_emms();
  1464.     x264_ratecontrol_end( h, h->out.i_frame_size * 8 );
  1465.     /* restore CPU state (before using float again) */
  1466.     x264_emms();
  1467.     x264_noise_reduction_update( thread_current );
  1468.     /* ---------------------- Compute/Print statistics --------------------- */
  1469.     x264_thread_sync_stat( h, h->thread[0] );
  1470.     /* Slice stat */
  1471.     h->stat.i_slice_count[h->sh.i_type]++;
  1472.     h->stat.i_slice_size[h->sh.i_type] += h->out.i_frame_size + NALU_OVERHEAD;
  1473.     h->stat.f_slice_qp[h->sh.i_type] += h->fdec->f_qp_avg_aq;
  1474.     for( i = 0; i < X264_MBTYPE_MAX; i++ )
  1475.         h->stat.i_mb_count[h->sh.i_type][i] += h->stat.frame.i_mb_count[i];
  1476.     for( i = 0; i < X264_PARTTYPE_MAX; i++ )
  1477.         h->stat.i_mb_partition[h->sh.i_type][i] += h->stat.frame.i_mb_partition[i];
  1478.     for( i = 0; i < 2; i++ )
  1479.         h->stat.i_mb_count_8x8dct[i] += h->stat.frame.i_mb_count_8x8dct[i];
  1480.     if( h->sh.i_type != SLICE_TYPE_I )
  1481.         for( i_list = 0; i_list < 2; i_list++ )
  1482.             for( i = 0; i < 32; i++ )
  1483.                 h->stat.i_mb_count_ref[h->sh.i_type][i_list][i] += h->stat.frame.i_mb_count_ref[i_list][i];
  1484.     if( h->sh.i_type == SLICE_TYPE_P )
  1485.         h->stat.i_consecutive_bframes[h->fdec->i_frame - h->fref0[0]->i_frame - 1]++;
  1486.     if( h->sh.i_type == SLICE_TYPE_B )
  1487.     {
  1488.         h->stat.i_direct_frames[ h->sh.b_direct_spatial_mv_pred ] ++;
  1489.         if( h->mb.b_direct_auto_write )
  1490.         {
  1491.             //FIXME somewhat arbitrary time constants
  1492.             if( h->stat.i_direct_score[0] + h->stat.i_direct_score[1] > h->mb.i_mb_count )
  1493.             {
  1494.                 for( i = 0; i < 2; i++ )
  1495.                     h->stat.i_direct_score[i] = h->stat.i_direct_score[i] * 9/10;
  1496.             }
  1497.             for( i = 0; i < 2; i++ )
  1498.                 h->stat.i_direct_score[i] += h->stat.frame.i_direct_score[i];
  1499.         }
  1500.     }
  1501.     psz_message[0] = '';
  1502.     if( h->param.analyse.b_psnr )
  1503.     {
  1504.         int64_t ssd[3] = {
  1505.             h->stat.frame.i_ssd[0],
  1506.             h->stat.frame.i_ssd[1],
  1507.             h->stat.frame.i_ssd[2],
  1508.         };
  1509.         h->stat.i_ssd_global[h->sh.i_type] += ssd[0] + ssd[1] + ssd[2];
  1510.         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 );
  1511.         h->stat.f_psnr_mean_y[h->sh.i_type] += x264_psnr( ssd[0], h->param.i_width * h->param.i_height );
  1512.         h->stat.f_psnr_mean_u[h->sh.i_type] += x264_psnr( ssd[1], h->param.i_width * h->param.i_height / 4 );
  1513.         h->stat.f_psnr_mean_v[h->sh.i_type] += x264_psnr( ssd[2], h->param.i_width * h->param.i_height / 4 );
  1514.         snprintf( psz_message, 80, " PSNR Y:%5.2f U:%5.2f V:%5.2f",
  1515.                   x264_psnr( ssd[0], h->param.i_width * h->param.i_height ),
  1516.                   x264_psnr( ssd[1], h->param.i_width * h->param.i_height / 4),
  1517.                   x264_psnr( ssd[2], h->param.i_width * h->param.i_height / 4) );
  1518.     }
  1519.     if( h->param.analyse.b_ssim )
  1520.     {
  1521.         double ssim_y = h->stat.frame.f_ssim
  1522.                       / (((h->param.i_width-6)>>2) * ((h->param.i_height-6)>>2));
  1523.         h->stat.f_ssim_mean_y[h->sh.i_type] += ssim_y;
  1524.         snprintf( psz_message + strlen(psz_message), 80 - strlen(psz_message),
  1525.                   " SSIM Y:%.5f", ssim_y );
  1526.     }
  1527.     psz_message[79] = '';
  1528.     x264_log( h, X264_LOG_DEBUG,
  1529.                   "frame=%4d QP=%.2f NAL=%d Slice:%c Poc:%-3d I:%-4d P:%-4d SKIP:%-4d size=%d bytes%sn",
  1530.               h->i_frame,
  1531.               h->fdec->f_qp_avg_aq,
  1532.               h->i_nal_ref_idc,
  1533.               h->sh.i_type == SLICE_TYPE_I ? 'I' : (h->sh.i_type == SLICE_TYPE_P ? 'P' : 'B' ),
  1534.               h->fdec->i_poc,
  1535.               h->stat.frame.i_mb_count_i,
  1536.               h->stat.frame.i_mb_count_p,
  1537.               h->stat.frame.i_mb_count_skip,
  1538.               h->out.i_frame_size,
  1539.               psz_message );
  1540.     // keep stats all in one place
  1541.     x264_thread_sync_stat( h->thread[0], h );
  1542.     // for the use of the next frame
  1543.     x264_thread_sync_stat( thread_current, h );
  1544. #ifdef DEBUG_MB_TYPE
  1545. {
  1546.     static const char mb_chars[] = { 'i', 'i', 'I', 'C', 'P', '8', 'S',
  1547.         'D', '<', 'X', 'B', 'X', '>', 'B', 'B', 'B', 'B', '8', 'S' };
  1548.     int mb_xy;
  1549.     for( mb_xy = 0; mb_xy < h->sps->i_mb_width * h->sps->i_mb_height; mb_xy++ )
  1550.     {
  1551.         if( h->mb.type[mb_xy] < X264_MBTYPE_MAX && h->mb.type[mb_xy] >= 0 )
  1552.             fprintf( stderr, "%c ", mb_chars[ h->mb.type[mb_xy] ] );
  1553.         else
  1554.             fprintf( stderr, "? " );
  1555.         if( (mb_xy+1) % h->sps->i_mb_width == 0 )
  1556.             fprintf( stderr, "n" );
  1557.     }
  1558. }
  1559. #endif
  1560.     if( h->param.psz_dump_yuv )
  1561.         x264_frame_dump( h );
  1562. }
  1563. static void x264_print_intra( int64_t *i_mb_count, double i_count, int b_print_pcm, char *intra )
  1564. {
  1565.     intra += sprintf( intra, "I16..4%s: %4.1f%% %4.1f%% %4.1f%%",
  1566.         b_print_pcm ? "..PCM" : "",
  1567.         i_mb_count[I_16x16]/ i_count,
  1568.         i_mb_count[I_8x8]  / i_count,
  1569.         i_mb_count[I_4x4]  / i_count );
  1570.     if( b_print_pcm )
  1571.         sprintf( intra, " %4.1f%%", i_mb_count[I_PCM]  / i_count );
  1572. }
  1573. /****************************************************************************
  1574.  * x264_encoder_close:
  1575.  ****************************************************************************/
  1576. void    x264_encoder_close  ( x264_t *h )
  1577. {
  1578.     int64_t i_yuv_size = 3 * h->param.i_width * h->param.i_height / 2;
  1579.     int64_t i_mb_count_size[2][7] = {{0}};
  1580.     char buf[200];
  1581.     int i, j, i_list, i_type;
  1582.     int b_print_pcm = h->stat.i_mb_count[SLICE_TYPE_I][I_PCM]
  1583.                    || h->stat.i_mb_count[SLICE_TYPE_P][I_PCM]
  1584.                    || h->stat.i_mb_count[SLICE_TYPE_B][I_PCM];
  1585.     for( i=0; i<h->param.i_threads; i++ )
  1586.     {
  1587.         // don't strictly have to wait for the other threads, but it's simpler than canceling them
  1588.         if( h->thread[i]->b_thread_active )
  1589.         {
  1590.             x264_pthread_join( h->thread[i]->thread_handle, NULL );
  1591.             assert( h->thread[i]->fenc->i_reference_count == 1 );
  1592.             x264_frame_delete( h->thread[i]->fenc );
  1593.         }
  1594.     }
  1595.     /* Slices used and PSNR */
  1596.     for( i=0; i<5; i++ )
  1597.     {
  1598.         static const int slice_order[] = { SLICE_TYPE_I, SLICE_TYPE_SI, SLICE_TYPE_P, SLICE_TYPE_SP, SLICE_TYPE_B };
  1599.         static const char *slice_name[] = { "P", "B", "I", "SP", "SI" };
  1600.         int i_slice = slice_order[i];
  1601.         if( h->stat.i_slice_count[i_slice] > 0 )
  1602.         {
  1603.             const int i_count = h->stat.i_slice_count[i_slice];
  1604.             if( h->param.analyse.b_psnr )
  1605.             {
  1606.                 x264_log( h, X264_LOG_INFO,
  1607.                           "slice %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",
  1608.                           slice_name[i_slice],
  1609.                           i_count,
  1610.                           h->stat.f_slice_qp[i_slice] / i_count,
  1611.                           (double)h->stat.i_slice_size[i_slice] / i_count,
  1612.                           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,
  1613.                           h->stat.f_psnr_average[i_slice] / i_count,
  1614.                           x264_psnr( h->stat.i_ssd_global[i_slice], i_count * i_yuv_size ) );
  1615.             }
  1616.             else
  1617.             {
  1618.                 x264_log( h, X264_LOG_INFO,
  1619.                           "slice %s:%-5d Avg QP:%5.2f  size:%6.0fn",
  1620.                           slice_name[i_slice],
  1621.                           i_count,
  1622.                           h->stat.f_slice_qp[i_slice] / i_count,
  1623.                           (double)h->stat.i_slice_size[i_slice] / i_count );
  1624.             }
  1625.         }
  1626.     }
  1627.     if( h->param.i_bframe && h->stat.i_slice_count[SLICE_TYPE_P] )
  1628.     {
  1629.         char *p = buf;
  1630.         int den = 0;
  1631.         // weight by number of frames (including the P-frame) that are in a sequence of N B-frames
  1632.         for( i=0; i<=h->param.i_bframe; i++ )
  1633.             den += (i+1) * h->stat.i_consecutive_bframes[i];
  1634.         for( i=0; i<=h->param.i_bframe; i++ )
  1635.             p += sprintf( p, " %4.1f%%", 100. * (i+1) * h->stat.i_consecutive_bframes[i] / den );
  1636.         x264_log( h, X264_LOG_INFO, "consecutive B-frames:%sn", buf );
  1637.     }
  1638.     for( i_type = 0; i_type < 2; i_type++ )
  1639.         for( i = 0; i < X264_PARTTYPE_MAX; i++ )
  1640.         {
  1641.             if( i == D_DIRECT_8x8 ) continue; /* direct is counted as its own type */
  1642.             i_mb_count_size[i_type][x264_mb_partition_pixel_table[i]] += h->stat.i_mb_partition[i_type][i];
  1643.         }
  1644.     /* MB types used */
  1645.     if( h->stat.i_slice_count[SLICE_TYPE_I] > 0 )
  1646.     {
  1647.         int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_I];
  1648.         double i_count = h->stat.i_slice_count[SLICE_TYPE_I] * h->mb.i_mb_count / 100.0;
  1649.         x264_print_intra( i_mb_count, i_count, b_print_pcm, buf );
  1650.         x264_log( h, X264_LOG_INFO, "mb I  %sn", buf );
  1651.     }
  1652.     if( h->stat.i_slice_count[SLICE_TYPE_P] > 0 )
  1653.     {
  1654.         int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_P];
  1655.         double i_count = h->stat.i_slice_count[SLICE_TYPE_P] * h->mb.i_mb_count / 100.0;
  1656.         int64_t *i_mb_size = i_mb_count_size[SLICE_TYPE_P];
  1657.         x264_print_intra( i_mb_count, i_count, b_print_pcm, buf );
  1658.         x264_log( h, X264_LOG_INFO,
  1659.                   "mb P  %s  P16..4: %4.1f%% %4.1f%% %4.1f%% %4.1f%% %4.1f%%    skip:%4.1f%%n",
  1660.                   buf,
  1661.                   i_mb_size[PIXEL_16x16] / (i_count*4),
  1662.                   (i_mb_size[PIXEL_16x8] + i_mb_size[PIXEL_8x16]) / (i_count*4),
  1663.                   i_mb_size[PIXEL_8x8] / (i_count*4),
  1664.                   (i_mb_size[PIXEL_8x4] + i_mb_size[PIXEL_4x8]) / (i_count*4),
  1665.                   i_mb_size[PIXEL_4x4] / (i_count*4),
  1666.                   i_mb_count[P_SKIP] / i_count );
  1667.     }
  1668.     if( h->stat.i_slice_count[SLICE_TYPE_B] > 0 )
  1669.     {
  1670.         int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_B];
  1671.         double i_count = h->stat.i_slice_count[SLICE_TYPE_B] * h->mb.i_mb_count / 100.0;
  1672.         double i_mb_list_count;
  1673.         int64_t *i_mb_size = i_mb_count_size[SLICE_TYPE_B];
  1674.         int64_t list_count[3] = {0}; /* 0 == L0, 1 == L1, 2 == BI */
  1675.         x264_print_intra( i_mb_count, i_count, b_print_pcm, buf );
  1676.         for( i = 0; i < X264_PARTTYPE_MAX; i++ )
  1677.             for( j = 0; j < 2; j++ )
  1678.             {
  1679.                 int l0 = x264_mb_type_list0_table[i][j];
  1680.                 int l1 = x264_mb_type_list1_table[i][j];
  1681.                 if( l0 || l1 )
  1682.                     list_count[l1+l0*l1] += h->stat.i_mb_count[SLICE_TYPE_B][i] * 2;
  1683.             }
  1684.         list_count[0] += h->stat.i_mb_partition[SLICE_TYPE_B][D_L0_8x8];
  1685.         list_count[1] += h->stat.i_mb_partition[SLICE_TYPE_B][D_L1_8x8];
  1686.         list_count[2] += h->stat.i_mb_partition[SLICE_TYPE_B][D_BI_8x8];
  1687.         i_mb_count[B_DIRECT] += (h->stat.i_mb_partition[SLICE_TYPE_B][D_DIRECT_8x8]+2)/4;
  1688.         i_mb_list_count = (list_count[0] + list_count[1] + list_count[2]) / 100.0;
  1689.         x264_log( h, X264_LOG_INFO,
  1690.                   "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",
  1691.                   buf,
  1692.                   i_mb_size[PIXEL_16x16] / (i_count*4),
  1693.                   (i_mb_size[PIXEL_16x8] + i_mb_size[PIXEL_8x16]) / (i_count*4),
  1694.                   i_mb_size[PIXEL_8x8] / (i_count*4),
  1695.                   i_mb_count[B_DIRECT] / i_count,
  1696.                   i_mb_count[B_SKIP]   / i_count,
  1697.                   list_count[0] / i_mb_list_count,
  1698.                   list_count[1] / i_mb_list_count,
  1699.                   list_count[2] / i_mb_list_count );
  1700.     }
  1701.     x264_ratecontrol_summary( h );
  1702.     if( h->stat.i_slice_count[SLICE_TYPE_I] + h->stat.i_slice_count[SLICE_TYPE_P] + h->stat.i_slice_count[SLICE_TYPE_B] > 0 )
  1703.     {
  1704.         const int i_count = h->stat.i_slice_count[SLICE_TYPE_I] +
  1705.                             h->stat.i_slice_count[SLICE_TYPE_P] +
  1706.                             h->stat.i_slice_count[SLICE_TYPE_B];
  1707.         float fps = (float) h->param.i_fps_num / h->param.i_fps_den;
  1708. #define SUM3(p) (p[SLICE_TYPE_I] + p[SLICE_TYPE_P] + p[SLICE_TYPE_B])
  1709. #define SUM3b(p,o) (p[SLICE_TYPE_I][o] + p[SLICE_TYPE_P][o] + p[SLICE_TYPE_B][o])
  1710.         float f_bitrate = fps * SUM3(h->stat.i_slice_size) / i_count / 125;
  1711.         if( h->pps->b_transform_8x8_mode )
  1712.         {
  1713.             int64_t i_i8x8 = SUM3b( h->stat.i_mb_count, I_8x8 );
  1714.             int64_t i_intra = i_i8x8 + SUM3b( h->stat.i_mb_count, I_4x4 )
  1715.                                      + SUM3b( h->stat.i_mb_count, I_16x16 );
  1716.             x264_log( h, X264_LOG_INFO, "8x8 transform  intra:%.1f%%  inter:%.1f%%n",
  1717.                       100. * i_i8x8 / i_intra,
  1718.                       100. * h->stat.i_mb_count_8x8dct[1] / h->stat.i_mb_count_8x8dct[0] );
  1719.         }
  1720.         if( h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_AUTO
  1721.             && h->stat.i_slice_count[SLICE_TYPE_B] )
  1722.         {
  1723.             x264_log( h, X264_LOG_INFO, "direct mvs  spatial:%.1f%%  temporal:%.1f%%n",
  1724.                       h->stat.i_direct_frames[1] * 100. / h->stat.i_slice_count[SLICE_TYPE_B],
  1725.                       h->stat.i_direct_frames[0] * 100. / h->stat.i_slice_count[SLICE_TYPE_B] );
  1726.         }
  1727.         for( i_list = 0; i_list < 2; i_list++ )
  1728.         {
  1729.             int i_slice;
  1730.             for( i_slice = 0; i_slice < 2; i_slice++ )
  1731.             {
  1732.                 char *p = buf;
  1733.                 int64_t i_den = 0;
  1734.                 int i_max = 0;
  1735.                 for( i = 0; i < 32; i++ )
  1736.                     if( h->stat.i_mb_count_ref[i_slice][i_list][i] )
  1737.                     {
  1738.                         i_den += h->stat.i_mb_count_ref[i_slice][i_list][i];
  1739.                         i_max = i;
  1740.                     }
  1741.                 if( i_max == 0 )
  1742.                     continue;
  1743.                 for( i = 0; i <= i_max; i++ )
  1744.                     p += sprintf( p, " %4.1f%%", 100. * h->stat.i_mb_count_ref[i_slice][i_list][i] / i_den );
  1745.                 x264_log( h, X264_LOG_INFO, "ref %c L%d %sn", "PB"[i_slice], i_list, buf );
  1746.             }
  1747.         }
  1748.         if( h->param.analyse.b_ssim )
  1749.         {
  1750.             x264_log( h, X264_LOG_INFO,
  1751.                       "SSIM Mean Y:%.7fn",
  1752.                       SUM3( h->stat.f_ssim_mean_y ) / i_count );
  1753.         }
  1754.         if( h->param.analyse.b_psnr )
  1755.         {
  1756.             x264_log( h, X264_LOG_INFO,
  1757.                       "PSNR Mean Y:%6.3f U:%6.3f V:%6.3f Avg:%6.3f Global:%6.3f kb/s:%.2fn",
  1758.                       SUM3( h->stat.f_psnr_mean_y ) / i_count,
  1759.                       SUM3( h->stat.f_psnr_mean_u ) / i_count,
  1760.                       SUM3( h->stat.f_psnr_mean_v ) / i_count,
  1761.                       SUM3( h->stat.f_psnr_average ) / i_count,
  1762.                       x264_psnr( SUM3( h->stat.i_ssd_global ), i_count * i_yuv_size ),
  1763.                       f_bitrate );
  1764.         }
  1765.         else
  1766.             x264_log( h, X264_LOG_INFO, "kb/s:%.1fn", f_bitrate );
  1767.     }
  1768.     /* rc */
  1769.     x264_ratecontrol_delete( h );
  1770.     /* param */
  1771.     if( h->param.rc.psz_stat_out )
  1772.         free( h->param.rc.psz_stat_out );
  1773.     if( h->param.rc.psz_stat_in )
  1774.         free( h->param.rc.psz_stat_in );
  1775.     x264_cqm_delete( h );
  1776.     if( h->param.i_threads > 1)
  1777.         h = h->thread[ h->i_thread_phase % h->param.i_threads ];
  1778.     /* frames */
  1779.     for( i = 0; h->frames.current[i]; i++ )
  1780.     {
  1781.         assert( h->frames.current[i]->i_reference_count == 1 );
  1782.         x264_frame_delete( h->frames.current[i] );
  1783.     }
  1784.     for( i = 0; h->frames.next[i]; i++ )
  1785.     {
  1786.         assert( h->frames.next[i]->i_reference_count == 1 );
  1787.         x264_frame_delete( h->frames.next[i] );
  1788.     }
  1789.     for( i = 0; h->frames.unused[i]; i++ )
  1790.     {
  1791.         assert( h->frames.unused[i]->i_reference_count == 0 );
  1792.         x264_frame_delete( h->frames.unused[i] );
  1793.     }
  1794.     h = h->thread[0];
  1795.     for( i = h->param.i_threads - 1; i >= 0; i-- )
  1796.     {
  1797.         x264_frame_t **frame;
  1798.         for( frame = h->thread[i]->frames.reference; *frame; frame++ )
  1799.         {
  1800.             assert( (*frame)->i_reference_count > 0 );
  1801.             (*frame)->i_reference_count--;
  1802.             if( (*frame)->i_reference_count == 0 )
  1803.                 x264_frame_delete( *frame );
  1804.         }
  1805.         frame = &h->thread[i]->fdec;
  1806.         assert( (*frame)->i_reference_count > 0 );
  1807.         (*frame)->i_reference_count--;
  1808.         if( (*frame)->i_reference_count == 0 )
  1809.             x264_frame_delete( *frame );
  1810.         x264_macroblock_cache_end( h->thread[i] );
  1811.         x264_free( h->thread[i]->out.p_bitstream );
  1812.         x264_free( h->thread[i] );
  1813.     }
  1814. }