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

Audio

开发平台:

Visual C++

  1. /*****************************************************************************
  2.  * x264: h264 encoder
  3.  *****************************************************************************
  4.  * Copyright (C) 2003 Laurent Aimar
  5.  * $Id: encoder.c,v 1.1 2004/06/03 19:27:08 fenrir Exp $
  6.  *
  7.  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
  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., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
  22.  *****************************************************************************/
  23. #include <stdio.h>
  24. #include <string.h>
  25. #include <math.h>
  26. #ifdef __WIN32__
  27. #include <windows.h>
  28. #define pthread_t               HANDLE
  29. #define pthread_create(t,u,f,d) *(t)=CreateThread(NULL,0,f,d,0,NULL)
  30. #define pthread_join(t,s)       { WaitForSingleObject(t,INFINITE); 
  31.                                   CloseHandle(t); } 
  32. #define HAVE_PTHREAD 1
  33. #elif defined(SYS_BEOS)
  34. #include <kernel/OS.h>
  35. #define pthread_t               thread_id
  36. #define pthread_create(t,u,f,d) { *(t)=spawn_thread(f,"",10,d); 
  37.                                   resume_thread(*(t)); }
  38. #define pthread_join(t,s)       wait_for_thread(t,(long*)s)
  39. #define HAVE_PTHREAD 1
  40. #elif HAVE_PTHREAD
  41. #include <pthread.h>
  42. #endif
  43. #include "common/common.h"
  44. #include "common/cpu.h"
  45. #include "set.h"
  46. #include "analyse.h"
  47. #include "ratecontrol.h"
  48. #include "macroblock.h"
  49. #if VISUALIZE
  50. #include "common/visualize.h"
  51. #endif
  52. //#define DEBUG_MB_TYPE
  53. //#define DEBUG_DUMP_FRAME
  54. //#define DEBUG_BENCHMARK
  55. #ifdef DEBUG_BENCHMARK
  56. static int64_t i_mtime_encode_frame = 0;
  57. static int64_t i_mtime_analyse = 0;
  58. static int64_t i_mtime_encode = 0;
  59. static int64_t i_mtime_write = 0;
  60. static int64_t i_mtime_filter = 0;
  61. #define TIMER_START( d ) 
  62.     { 
  63.         int64_t d##start = x264_mdate();
  64. #define TIMER_STOP( d ) 
  65.         d += x264_mdate() - d##start;
  66.     }
  67. #else
  68. #define TIMER_START( d )
  69. #define TIMER_STOP( d )
  70. #endif
  71. #define NALU_OVERHEAD 5 // startcode + NAL type costs 5 bytes per frame
  72. /****************************************************************************
  73.  *
  74.  ******************************* x264 libs **********************************
  75.  *
  76.  ****************************************************************************/
  77. static float x264_psnr( int64_t i_sqe, int64_t i_size )
  78. {
  79.     double f_mse = (double)i_sqe / ((double)65025.0 * (double)i_size);
  80.     if( f_mse <= 0.0000000001 ) /* Max 100dB */
  81.         return 100;
  82.     return (float)(-10.0 * log( f_mse ) / log( 10.0 ));
  83. }
  84. #ifdef DEBUG_DUMP_FRAME
  85. static void x264_frame_dump( x264_t *h, x264_frame_t *fr, char *name )
  86. {
  87.     FILE * f = fopen( name, "a" );
  88.     int i, y;
  89.     fseek( f, 0, SEEK_END );
  90.     for( i = 0; i < fr->i_plane; i++ )
  91.     {
  92.         for( y = 0; y < h->param.i_height / ( i == 0 ? 1 : 2 ); y++ )
  93.         {
  94.             fwrite( &fr->plane[i][y*fr->i_stride[i]], 1, h->param.i_width / ( i == 0 ? 1 : 2 ), f );
  95.         }
  96.     }
  97.     fclose( f );
  98. }
  99. #endif
  100. /* Fill "default" values */
  101. static void x264_slice_header_init( x264_t *h, x264_slice_header_t *sh,
  102.                                     x264_sps_t *sps, x264_pps_t *pps,
  103.                                     int i_type, int i_idr_pic_id, int i_frame, int i_qp )
  104. {
  105.     x264_param_t *param = &h->param;
  106.     int i;
  107.     /* First we fill all field */
  108.     sh->sps = sps;
  109.     sh->pps = pps;
  110.     sh->i_type      = i_type;
  111.     sh->i_first_mb  = 0;
  112.     sh->i_last_mb   = h->sps->i_mb_width * h->sps->i_mb_height;
  113.     sh->i_pps_id    = pps->i_id;
  114.     sh->i_frame_num = i_frame;
  115.     sh->b_field_pic = 0;    /* Not field support for now */
  116.     sh->b_bottom_field = 1; /* not yet used */
  117.     sh->i_idr_pic_id = i_idr_pic_id;
  118.     /* poc stuff, fixed later */
  119.     sh->i_poc_lsb = 0;
  120.     sh->i_delta_poc_bottom = 0;
  121.     sh->i_delta_poc[0] = 0;
  122.     sh->i_delta_poc[1] = 0;
  123.     sh->i_redundant_pic_cnt = 0;
  124.     if( !h->mb.b_direct_auto_read )
  125.     {
  126.         if( h->mb.b_direct_auto_write )
  127.             sh->b_direct_spatial_mv_pred = ( h->stat.i_direct_score[1] > h->stat.i_direct_score[0] );
  128.         else
  129.             sh->b_direct_spatial_mv_pred = ( param->analyse.i_direct_mv_pred == X264_DIRECT_PRED_SPATIAL );
  130.     }
  131.     /* else b_direct_spatial_mv_pred was read from the 2pass statsfile */
  132.     sh->b_num_ref_idx_override = 0;
  133.     sh->i_num_ref_idx_l0_active = 1;
  134.     sh->i_num_ref_idx_l1_active = 1;
  135.     sh->b_ref_pic_list_reordering_l0 = h->b_ref_reorder[0];
  136.     sh->b_ref_pic_list_reordering_l1 = h->b_ref_reorder[1];
  137.     /* If the ref list isn't in the default order, construct reordering header */
  138.     /* List1 reordering isn't needed yet */
  139.     if( sh->b_ref_pic_list_reordering_l0 )
  140.     {
  141.         int pred_frame_num = i_frame;
  142.         for( i = 0; i < h->i_ref0; i++ )
  143.         {
  144.             int diff = h->fref0[i]->i_frame_num - pred_frame_num;
  145.             if( diff == 0 )
  146.                 x264_log( h, X264_LOG_ERROR, "diff frame num == 0n" );
  147.             sh->ref_pic_list_order[0][i].idc = ( diff > 0 );
  148.             sh->ref_pic_list_order[0][i].arg = abs( diff ) - 1;
  149.             pred_frame_num = h->fref0[i]->i_frame_num;
  150.         }
  151.     }
  152.     sh->i_cabac_init_idc = param->i_cabac_init_idc;
  153.     sh->i_qp = i_qp;
  154.     sh->i_qp_delta = i_qp - pps->i_pic_init_qp;
  155.     sh->b_sp_for_swidth = 0;
  156.     sh->i_qs_delta = 0;
  157.     /* If effective qp <= 15, deblocking would have no effect anyway */
  158.     if( param->b_deblocking_filter
  159.         && ( h->mb.b_variable_qp
  160.         || 15 < i_qp + X264_MAX(param->i_deblocking_filter_alphac0, param->i_deblocking_filter_beta) ) )
  161.     {
  162.         sh->i_disable_deblocking_filter_idc = 0;
  163.     }
  164.     else
  165.     {
  166.         sh->i_disable_deblocking_filter_idc = 1;
  167.     }
  168.     sh->i_alpha_c0_offset = param->i_deblocking_filter_alphac0 << 1;
  169.     sh->i_beta_offset = param->i_deblocking_filter_beta << 1;
  170. }
  171. static void x264_slice_header_write( bs_t *s, x264_slice_header_t *sh, int i_nal_ref_idc )
  172. {
  173.     int i;
  174.     bs_write_ue( s, sh->i_first_mb );
  175.     bs_write_ue( s, sh->i_type + 5 );   /* same type things */
  176.     bs_write_ue( s, sh->i_pps_id );
  177.     bs_write( s, sh->sps->i_log2_max_frame_num, sh->i_frame_num );
  178.     if( sh->i_idr_pic_id >= 0 ) /* NAL IDR */
  179.     {
  180.         bs_write_ue( s, sh->i_idr_pic_id );
  181.     }
  182.     if( sh->sps->i_poc_type == 0 )
  183.     {
  184.         bs_write( s, sh->sps->i_log2_max_poc_lsb, sh->i_poc_lsb );
  185.         if( sh->pps->b_pic_order && !sh->b_field_pic )
  186.         {
  187.             bs_write_se( s, sh->i_delta_poc_bottom );
  188.         }
  189.     }
  190.     else if( sh->sps->i_poc_type == 1 && !sh->sps->b_delta_pic_order_always_zero )
  191.     {
  192.         bs_write_se( s, sh->i_delta_poc[0] );
  193.         if( sh->pps->b_pic_order && !sh->b_field_pic )
  194.         {
  195.             bs_write_se( s, sh->i_delta_poc[1] );
  196.         }
  197.     }
  198.     if( sh->pps->b_redundant_pic_cnt )
  199.     {
  200.         bs_write_ue( s, sh->i_redundant_pic_cnt );
  201.     }
  202.     if( sh->i_type == SLICE_TYPE_B )
  203.     {
  204.         bs_write1( s, sh->b_direct_spatial_mv_pred );
  205.     }
  206.     if( sh->i_type == SLICE_TYPE_P || sh->i_type == SLICE_TYPE_SP || sh->i_type == SLICE_TYPE_B )
  207.     {
  208.         bs_write1( s, sh->b_num_ref_idx_override );
  209.         if( sh->b_num_ref_idx_override )
  210.         {
  211.             bs_write_ue( s, sh->i_num_ref_idx_l0_active - 1 );
  212.             if( sh->i_type == SLICE_TYPE_B )
  213.             {
  214.                 bs_write_ue( s, sh->i_num_ref_idx_l1_active - 1 );
  215.             }
  216.         }
  217.     }
  218.     /* ref pic list reordering */
  219.     if( sh->i_type != SLICE_TYPE_I )
  220.     {
  221.         bs_write1( s, sh->b_ref_pic_list_reordering_l0 );
  222.         if( sh->b_ref_pic_list_reordering_l0 )
  223.         {
  224.             for( i = 0; i < sh->i_num_ref_idx_l0_active; i++ )
  225.             {
  226.                 bs_write_ue( s, sh->ref_pic_list_order[0][i].idc );
  227.                 bs_write_ue( s, sh->ref_pic_list_order[0][i].arg );
  228.                         
  229.             }
  230.             bs_write_ue( s, 3 );
  231.         }
  232.     }
  233.     if( sh->i_type == SLICE_TYPE_B )
  234.     {
  235.         bs_write1( s, sh->b_ref_pic_list_reordering_l1 );
  236.         if( sh->b_ref_pic_list_reordering_l1 )
  237.         {
  238.             for( i = 0; i < sh->i_num_ref_idx_l1_active; i++ )
  239.             {
  240.                 bs_write_ue( s, sh->ref_pic_list_order[1][i].idc );
  241.                 bs_write_ue( s, sh->ref_pic_list_order[1][i].arg );
  242.             }
  243.             bs_write_ue( s, 3 );
  244.         }
  245.     }
  246.     if( ( sh->pps->b_weighted_pred && ( sh->i_type == SLICE_TYPE_P || sh->i_type == SLICE_TYPE_SP ) ) ||
  247.         ( sh->pps->b_weighted_bipred == 1 && sh->i_type == SLICE_TYPE_B ) )
  248.     {
  249.         /* FIXME */
  250.     }
  251.     if( i_nal_ref_idc != 0 )
  252.     {
  253.         if( sh->i_idr_pic_id >= 0 )
  254.         {
  255.             bs_write1( s, 0 );  /* no output of prior pics flag */
  256.             bs_write1( s, 0 );  /* long term reference flag */
  257.         }
  258.         else
  259.         {
  260.             bs_write1( s, 0 );  /* adaptive_ref_pic_marking_mode_flag */
  261.         }
  262.     }
  263.     if( sh->pps->b_cabac && sh->i_type != SLICE_TYPE_I )
  264.     {
  265.         bs_write_ue( s, sh->i_cabac_init_idc );
  266.     }
  267.     bs_write_se( s, sh->i_qp_delta );      /* slice qp delta */
  268.     if( sh->pps->b_deblocking_filter_control )
  269.     {
  270.         bs_write_ue( s, sh->i_disable_deblocking_filter_idc );
  271.         if( sh->i_disable_deblocking_filter_idc != 1 )
  272.         {
  273.             bs_write_se( s, sh->i_alpha_c0_offset >> 1 );
  274.             bs_write_se( s, sh->i_beta_offset >> 1 );
  275.         }
  276.     }
  277. }
  278. /****************************************************************************
  279.  *
  280.  ****************************************************************************
  281.  ****************************** External API*********************************
  282.  ****************************************************************************
  283.  *
  284.  ****************************************************************************/
  285. static int x264_validate_parameters( x264_t *h )
  286. {
  287.     if( h->param.i_width <= 0 || h->param.i_height <= 0 )
  288.     {
  289.         x264_log( h, X264_LOG_ERROR, "invalid width x height (%dx%d)n",
  290.                   h->param.i_width, h->param.i_height );
  291.         return -1;
  292.     }
  293.     if( h->param.i_width % 2 || h->param.i_height % 2 )
  294.     {
  295.         x264_log( h, X264_LOG_ERROR, "width or height not divisible by 2 (%dx%d)n",
  296.                   h->param.i_width, h->param.i_height );
  297.         return -1;
  298.     }
  299.     if( h->param.i_csp != X264_CSP_I420 )
  300.     {
  301.         x264_log( h, X264_LOG_ERROR, "invalid CSP (only I420 supported)n" );
  302.         return -1;
  303.     }
  304.     h->param.i_threads = x264_clip3( h->param.i_threads, 1, X264_SLICE_MAX );
  305.     h->param.i_threads = X264_MIN( h->param.i_threads, (h->param.i_height + 15) / 16 );
  306. #if !(HAVE_PTHREAD)
  307.     if( h->param.i_threads > 1 )
  308.     {
  309.         x264_log( h, X264_LOG_WARNING, "not compiled with pthread support!n");
  310.         x264_log( h, X264_LOG_WARNING, "multislicing anyway, but you won't see any speed gain.n" );
  311.     }
  312. #endif
  313.     if( h->param.rc.b_cbr )
  314.         h->param.rc.i_rf_constant = 0;
  315.     if( h->param.rc.i_rf_constant > 0 )
  316.         h->param.rc.i_qp_constant = h->param.rc.i_rf_constant;
  317.     h->param.rc.i_rf_constant = x264_clip3( h->param.rc.i_rf_constant, 0, 51 );
  318.     h->param.rc.i_qp_constant = x264_clip3( h->param.rc.i_qp_constant, 0, 51 );
  319.     if( !h->param.rc.b_cbr && h->param.rc.i_qp_constant == 0 )
  320.     {
  321.         h->mb.b_lossless = 1;
  322.         h->param.analyse.b_transform_8x8 = 0;
  323.         h->param.i_cqm_preset = X264_CQM_FLAT;
  324.         h->param.psz_cqm_file = NULL;
  325.         h->param.rc.f_ip_factor = 1;
  326.         h->param.rc.f_pb_factor = 1;
  327.         h->param.analyse.b_psnr = 0;
  328.         h->param.analyse.i_chroma_qp_offset = 0;
  329.         h->param.analyse.i_trellis = 0;
  330.         h->param.analyse.b_fast_pskip = 0;
  331.         h->param.analyse.i_noise_reduction = 0;
  332.     }
  333.     if( ( h->param.i_width % 16 || h->param.i_height % 16 ) && !h->mb.b_lossless )
  334.     {
  335.         x264_log( h, X264_LOG_WARNING, 
  336.                   "width or height not divisible by 16 (%dx%d), compression will suffer.n",
  337.                   h->param.i_width, h->param.i_height );
  338.     }
  339.     h->param.i_frame_reference = x264_clip3( h->param.i_frame_reference, 1, 16 );
  340.     if( h->param.i_keyint_max <= 0 )
  341.         h->param.i_keyint_max = 1;
  342.     h->param.i_keyint_min = x264_clip3( h->param.i_keyint_min, 1, h->param.i_keyint_max/2+1 );
  343.     h->param.i_bframe = x264_clip3( h->param.i_bframe, 0, X264_BFRAME_MAX );
  344.     h->param.i_bframe_bias = x264_clip3( h->param.i_bframe_bias, -90, 100 );
  345.     h->param.b_bframe_pyramid = h->param.b_bframe_pyramid && h->param.i_bframe > 1;
  346.     h->param.b_bframe_adaptive = h->param.b_bframe_adaptive && h->param.i_bframe > 0;
  347.     h->mb.b_direct_auto_write = h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_AUTO
  348.                                 && h->param.i_bframe
  349.                                 && ( h->param.rc.b_stat_write || !h->param.rc.b_stat_read );
  350.     h->param.i_deblocking_filter_alphac0 = x264_clip3( h->param.i_deblocking_filter_alphac0, -6, 6 );
  351.     h->param.i_deblocking_filter_beta    = x264_clip3( h->param.i_deblocking_filter_beta, -6, 6 );
  352.     h->param.i_cabac_init_idc = x264_clip3( h->param.i_cabac_init_idc, 0, 2 );
  353.     if( h->param.i_cqm_preset < X264_CQM_FLAT || h->param.i_cqm_preset > X264_CQM_CUSTOM )
  354.         h->param.i_cqm_preset = X264_CQM_FLAT;
  355.     if( h->param.analyse.i_me_method < X264_ME_DIA ||
  356.         h->param.analyse.i_me_method > X264_ME_ESA )
  357.         h->param.analyse.i_me_method = X264_ME_HEX;
  358.     if( h->param.analyse.i_me_range < 4 )
  359.         h->param.analyse.i_me_range = 4;
  360.     if( h->param.analyse.i_me_range > 16 && h->param.analyse.i_me_method <= X264_ME_HEX )
  361.         h->param.analyse.i_me_range = 16;
  362.     h->param.analyse.i_subpel_refine = x264_clip3( h->param.analyse.i_subpel_refine, 1, 6 );
  363.     h->param.analyse.b_bframe_rdo = h->param.analyse.b_bframe_rdo && h->param.analyse.i_subpel_refine >= 6;
  364.     h->param.analyse.b_mixed_references = h->param.analyse.b_mixed_references && h->param.i_frame_reference > 1;
  365.     h->param.analyse.inter &= X264_ANALYSE_PSUB16x16|X264_ANALYSE_PSUB8x8|X264_ANALYSE_BSUB16x16|
  366.                               X264_ANALYSE_I4x4|X264_ANALYSE_I8x8;
  367.     h->param.analyse.intra &= X264_ANALYSE_I4x4|X264_ANALYSE_I8x8;
  368.     if( !(h->param.analyse.inter & X264_ANALYSE_PSUB16x16) )
  369.         h->param.analyse.inter &= ~X264_ANALYSE_PSUB8x8;
  370.     if( !h->param.analyse.b_transform_8x8 )
  371.     {
  372.         h->param.analyse.inter &= ~X264_ANALYSE_I8x8;
  373.         h->param.analyse.intra &= ~X264_ANALYSE_I8x8;
  374.     }
  375.     h->param.analyse.i_chroma_qp_offset = x264_clip3(h->param.analyse.i_chroma_qp_offset, -12, 12);
  376.     if( !h->param.b_cabac )
  377.         h->param.analyse.i_trellis = 0;
  378.     h->param.analyse.i_trellis = x264_clip3( h->param.analyse.i_trellis, 0, 2 );
  379.     h->param.analyse.i_noise_reduction = x264_clip3( h->param.analyse.i_noise_reduction, 0, 1<<16 );
  380.     {
  381.         const x264_level_t *l = x264_levels;
  382.         while( l->level_idc != 0 && l->level_idc != h->param.i_level_idc )
  383.             l++;
  384.         if( l->level_idc == 0 )
  385.         {
  386.             x264_log( h, X264_LOG_ERROR, "invalid level_idc: %dn", h->param.i_level_idc );
  387.             return -1;
  388.         }
  389.         if( h->param.analyse.i_mv_range <= 0 )
  390.             h->param.analyse.i_mv_range = l->mv_range;
  391.         else
  392.             h->param.analyse.i_mv_range = x264_clip3(h->param.analyse.i_mv_range, 32, 2048);
  393.     }
  394.     if( h->param.rc.f_qblur < 0 )
  395.         h->param.rc.f_qblur = 0;
  396.     if( h->param.rc.f_complexity_blur < 0 )
  397.         h->param.rc.f_complexity_blur = 0;
  398.     /* ensure the booleans are 0 or 1 so they can be used in math */
  399. #define BOOLIFY(x) h->param.x = !!h->param.x
  400.     BOOLIFY( b_cabac );
  401.     BOOLIFY( b_deblocking_filter );
  402.     BOOLIFY( analyse.b_transform_8x8 );
  403.     BOOLIFY( analyse.b_weighted_bipred );
  404.     BOOLIFY( analyse.b_bidir_me );
  405.     BOOLIFY( analyse.b_chroma_me );
  406.     BOOLIFY( analyse.b_fast_pskip );
  407.     BOOLIFY( rc.b_cbr );
  408.     BOOLIFY( rc.b_stat_write );
  409.     BOOLIFY( rc.b_stat_read );
  410. #undef BOOLIFY
  411.     return 0;
  412. }
  413. /****************************************************************************
  414.  * x264_encoder_open:
  415.  ****************************************************************************/
  416. x264_t *x264_encoder_open   ( x264_param_t *param )
  417. {
  418.     x264_t *h = x264_malloc( sizeof( x264_t ) );
  419.     int i;
  420.     memset( h, 0, sizeof( x264_t ) );
  421.     /* Create a copy of param */
  422.     memcpy( &h->param, param, sizeof( x264_param_t ) );
  423.     if( x264_validate_parameters( h ) < 0 )
  424.     {
  425.         x264_free( h );
  426.         return NULL;
  427.     }
  428.     if( h->param.psz_cqm_file )
  429.         if( x264_cqm_parse_file( h, h->param.psz_cqm_file ) < 0 )
  430.         {
  431.             x264_free( h );
  432.             return NULL;
  433.         }
  434.     if( h->param.rc.psz_stat_out )
  435.         h->param.rc.psz_stat_out = strdup( h->param.rc.psz_stat_out );
  436.     if( h->param.rc.psz_stat_in )
  437.         h->param.rc.psz_stat_in = strdup( h->param.rc.psz_stat_in );
  438.     if( h->param.rc.psz_rc_eq )
  439.         h->param.rc.psz_rc_eq = strdup( h->param.rc.psz_rc_eq );
  440.     /* VUI */
  441.     if( h->param.vui.i_sar_width > 0 && h->param.vui.i_sar_height > 0 )
  442.     {
  443.         int i_w = param->vui.i_sar_width;
  444.         int i_h = param->vui.i_sar_height;
  445.         int a = i_w, b = i_h;
  446.         while( b != 0 )
  447.         {
  448.             int t = a;
  449.             a = b;
  450.             b = t % b;
  451.         }
  452.         i_w /= a;
  453.         i_h /= a;
  454.         while( i_w > 65535 || i_h > 65535 )
  455.         {
  456.             i_w /= 2;
  457.             i_h /= 2;
  458.         }
  459.         h->param.vui.i_sar_width = 0;
  460.         h->param.vui.i_sar_height = 0;
  461.         if( i_w == 0 || i_h == 0 )
  462.         {
  463.             x264_log( h, X264_LOG_ERROR, "cannot create valid sample aspect ration" );
  464.         }
  465.         else if( i_w == i_h )
  466.         {
  467.             x264_log( h, X264_LOG_INFO, "no need for a SARn" );
  468.         }
  469.         else
  470.         {
  471.             x264_log( h, X264_LOG_INFO, "using SAR=%d/%dn", i_w, i_h );
  472.             h->param.vui.i_sar_width = i_w;
  473.             h->param.vui.i_sar_height = i_h;
  474.         }
  475.     }
  476.     /* Init x264_t */
  477.     h->out.i_nal = 0;
  478.     h->out.i_bitstream = X264_MAX( 1000000, h->param.i_width * h->param.i_height * 1.7
  479.         * ( h->param.rc.b_cbr ? pow( 0.5, h->param.rc.i_qp_min )
  480.           : pow( 0.5, h->param.rc.i_qp_constant ) * X264_MAX( 1, h->param.rc.f_ip_factor )));
  481.     h->out.p_bitstream = x264_malloc( h->out.i_bitstream );
  482.     h->i_frame = 0;
  483.     h->i_frame_num = 0;
  484.     h->i_idr_pic_id = 0;
  485.     h->sps = &h->sps_array[0];
  486.     x264_sps_init( h->sps, 0, &h->param );
  487.     h->pps = &h->pps_array[0];
  488.     x264_pps_init( h->pps, 0, &h->param, h->sps);
  489.     x264_validate_levels( h );
  490.     x264_cqm_init( h );
  491.     
  492.     h->mb.i_mb_count = h->sps->i_mb_width * h->sps->i_mb_height;
  493.     /* Init frames. */
  494.     h->frames.i_delay = h->param.i_bframe;
  495.     h->frames.i_max_ref0 = h->param.i_frame_reference;
  496.     h->frames.i_max_ref1 = h->sps->vui.i_num_reorder_frames;
  497.     h->frames.i_max_dpb  = h->sps->vui.i_max_dec_frame_buffering + 1;
  498.     h->frames.b_have_lowres = !h->param.rc.b_stat_read
  499.         && ( h->param.rc.b_cbr || h->param.rc.i_rf_constant || h->param.b_bframe_adaptive );
  500.     for( i = 0; i < X264_BFRAME_MAX + 3; i++ )
  501.     {
  502.         h->frames.current[i] = NULL;
  503.         h->frames.next[i]    = NULL;
  504.         h->frames.unused[i]  = NULL;
  505.     }
  506.     for( i = 0; i < 1 + h->frames.i_delay; i++ )
  507.     {
  508.         h->frames.unused[i] =  x264_frame_new( h );
  509.     }
  510.     for( i = 0; i < h->frames.i_max_dpb; i++ )
  511.     {
  512.         h->frames.reference[i] = x264_frame_new( h );
  513.     }
  514.     h->frames.reference[h->frames.i_max_dpb] = NULL;
  515.     h->frames.i_last_idr = - h->param.i_keyint_max;
  516.     h->frames.i_input    = 0;
  517.     h->frames.last_nonb  = NULL;
  518.     h->i_ref0 = 0;
  519.     h->i_ref1 = 0;
  520.     h->fdec = h->frames.reference[0];
  521.     x264_macroblock_cache_init( h );
  522.     x264_rdo_init( );
  523.     /* init CPU functions */
  524.     x264_predict_16x16_init( h->param.cpu, h->predict_16x16 );
  525.     x264_predict_8x8c_init( h->param.cpu, h->predict_8x8c );
  526.     x264_predict_8x8_init( h->param.cpu, h->predict_8x8 );
  527.     x264_predict_4x4_init( h->param.cpu, h->predict_4x4 );
  528.     x264_pixel_init( h->param.cpu, &h->pixf );
  529.     x264_dct_init( h->param.cpu, &h->dctf );
  530.     x264_mc_init( h->param.cpu, &h->mc );
  531.     x264_csp_init( h->param.cpu, h->param.i_csp, &h->csp );
  532.     x264_quant_init( h, h->param.cpu, &h->quantf );
  533.     x264_deblock_init( h->param.cpu, &h->loopf );
  534.     memcpy( h->pixf.mbcmp,
  535.             ( h->mb.b_lossless || h->param.analyse.i_subpel_refine <= 1 ) ? h->pixf.sad : h->pixf.satd,
  536.             sizeof(h->pixf.mbcmp) );
  537.     /* rate control */
  538.     if( x264_ratecontrol_new( h ) < 0 )
  539.         return NULL;
  540.     x264_log( h, X264_LOG_INFO, "using cpu capabilities %s%s%s%s%s%sn",
  541.              param->cpu&X264_CPU_MMX ? "MMX " : "",
  542.              param->cpu&X264_CPU_MMXEXT ? "MMXEXT " : "",
  543.              param->cpu&X264_CPU_SSE ? "SSE " : "",
  544.              param->cpu&X264_CPU_SSE2 ? "SSE2 " : "",
  545.              param->cpu&X264_CPU_3DNOW ? "3DNow! " : "",
  546.              param->cpu&X264_CPU_ALTIVEC ? "Altivec " : "" );
  547.     h->thread[0] = h;
  548.     for( i = 1; i < param->i_threads; i++ )
  549.         h->thread[i] = x264_malloc( sizeof(x264_t) );
  550.     return h;
  551. }
  552. /****************************************************************************
  553.  * x264_encoder_reconfig:
  554.  ****************************************************************************/
  555. int x264_encoder_reconfig( x264_t *h, x264_param_t *param )
  556. {
  557.     h->param.i_bframe_bias = param->i_bframe_bias;
  558.     h->param.i_deblocking_filter_alphac0 = param->i_deblocking_filter_alphac0;
  559.     h->param.i_deblocking_filter_beta    = param->i_deblocking_filter_beta;
  560.     h->param.analyse.i_me_method = param->analyse.i_me_method;
  561.     h->param.analyse.i_me_range = param->analyse.i_me_range;
  562.     h->param.analyse.i_subpel_refine = param->analyse.i_subpel_refine;
  563.     h->param.analyse.i_trellis = param->analyse.i_trellis;
  564.     h->param.analyse.intra = param->analyse.intra;
  565.     h->param.analyse.inter = param->analyse.inter;
  566.     memcpy( h->pixf.mbcmp,
  567.             ( h->mb.b_lossless || h->param.analyse.i_subpel_refine <= 1 ) ? h->pixf.sad : h->pixf.satd,
  568.             sizeof(h->pixf.mbcmp) );
  569.     return x264_validate_parameters( h );
  570. }
  571. /* internal usage */
  572. static void x264_nal_start( x264_t *h, int i_type, int i_ref_idc )
  573. {
  574.     x264_nal_t *nal = &h->out.nal[h->out.i_nal];
  575.     nal->i_ref_idc = i_ref_idc;
  576.     nal->i_type    = i_type;
  577.     bs_align_0( &h->out.bs );   /* not needed */
  578.     nal->i_payload= 0;
  579.     nal->p_payload= &h->out.p_bitstream[bs_pos( &h->out.bs) / 8];
  580. }
  581. static void x264_nal_end( x264_t *h )
  582. {
  583.     x264_nal_t *nal = &h->out.nal[h->out.i_nal];
  584.     bs_align_0( &h->out.bs );   /* not needed */
  585.     nal->i_payload = &h->out.p_bitstream[bs_pos( &h->out.bs)/8] - nal->p_payload;
  586.     h->out.i_nal++;
  587. }
  588. /****************************************************************************
  589.  * x264_encoder_headers:
  590.  ****************************************************************************/
  591. int x264_encoder_headers( x264_t *h, x264_nal_t **pp_nal, int *pi_nal )
  592. {
  593.     /* init bitstream context */
  594.     h->out.i_nal = 0;
  595.     bs_init( &h->out.bs, h->out.p_bitstream, h->out.i_bitstream );
  596.     /* Put SPS and PPS */
  597.     if( h->i_frame == 0 )
  598.     {
  599.         /* identify ourself */
  600.         x264_nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
  601.         x264_sei_version_write( h, &h->out.bs );
  602.         x264_nal_end( h );
  603.         /* generate sequence parameters */
  604.         x264_nal_start( h, NAL_SPS, NAL_PRIORITY_HIGHEST );
  605.         x264_sps_write( &h->out.bs, h->sps );
  606.         x264_nal_end( h );
  607.         /* generate picture parameters */
  608.         x264_nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
  609.         x264_pps_write( &h->out.bs, h->pps );
  610.         x264_nal_end( h );
  611.     }
  612.     /* now set output*/
  613.     *pi_nal = h->out.i_nal;
  614.     *pp_nal = &h->out.nal[0];
  615.     return 0;
  616. }
  617. static void x264_frame_put( x264_frame_t *list[X264_BFRAME_MAX], x264_frame_t *frame )
  618. {
  619.     int i = 0;
  620.     while( list[i] ) i++;
  621.     list[i] = frame;
  622. }
  623. static void x264_frame_push( x264_frame_t *list[X264_BFRAME_MAX], x264_frame_t *frame )
  624. {
  625.     int i = 0;
  626.     while( list[i] ) i++;
  627.     while( i-- )
  628.         list[i+1] = list[i];
  629.     list[0] = frame;
  630. }
  631. static x264_frame_t *x264_frame_get( x264_frame_t *list[X264_BFRAME_MAX+1] )
  632. {
  633.     x264_frame_t *frame = list[0];
  634.     int i;
  635.     for( i = 0; list[i]; i++ )
  636.         list[i] = list[i+1];
  637.     return frame;
  638. }
  639. static void x264_frame_sort( x264_frame_t *list[X264_BFRAME_MAX+1], int b_dts )
  640. {
  641.     int i, b_ok;
  642.     do {
  643.         b_ok = 1;
  644.         for( i = 0; list[i+1]; i++ )
  645.         {
  646.             int dtype = list[i]->i_type - list[i+1]->i_type;
  647.             int dtime = list[i]->i_frame - list[i+1]->i_frame;
  648.             int swap = b_dts ? dtype > 0 || ( dtype == 0 && dtime > 0 )
  649.                              : dtime > 0;
  650.             if( swap )
  651.             {
  652.                 XCHG( x264_frame_t*, list[i], list[i+1] );
  653.                 b_ok = 0;
  654.             }
  655.         }
  656.     } while( !b_ok );
  657. }
  658. #define x264_frame_sort_dts(list) x264_frame_sort(list, 1)
  659. #define x264_frame_sort_pts(list) x264_frame_sort(list, 0)
  660. static inline void x264_reference_build_list( x264_t *h, int i_poc, int i_slice_type )
  661. {
  662.     int i;
  663.     int b_ok;
  664.     /* build ref list 0/1 */
  665.     h->i_ref0 = 0;
  666.     h->i_ref1 = 0;
  667.     for( i = 1; i < h->frames.i_max_dpb; i++ )
  668.     {
  669.         if( h->frames.reference[i]->i_poc >= 0 )
  670.         {
  671.             if( h->frames.reference[i]->i_poc < i_poc )
  672.             {
  673.                 h->fref0[h->i_ref0++] = h->frames.reference[i];
  674.             }
  675.             else if( h->frames.reference[i]->i_poc > i_poc )
  676.             {
  677.                 h->fref1[h->i_ref1++] = h->frames.reference[i];
  678.             }
  679.         }
  680.     }
  681.     /* Order ref0 from higher to lower poc */
  682.     do
  683.     {
  684.         b_ok = 1;
  685.         for( i = 0; i < h->i_ref0 - 1; i++ )
  686.         {
  687.             if( h->fref0[i]->i_poc < h->fref0[i+1]->i_poc )
  688.             {
  689.                 XCHG( x264_frame_t*, h->fref0[i], h->fref0[i+1] );
  690.                 b_ok = 0;
  691.                 break;
  692.             }
  693.         }
  694.     } while( !b_ok );
  695.     /* Order ref1 from lower to higher poc (bubble sort) for B-frame */
  696.     do
  697.     {
  698.         b_ok = 1;
  699.         for( i = 0; i < h->i_ref1 - 1; i++ )
  700.         {
  701.             if( h->fref1[i]->i_poc > h->fref1[i+1]->i_poc )
  702.             {
  703.                 XCHG( x264_frame_t*, h->fref1[i], h->fref1[i+1] );
  704.                 b_ok = 0;
  705.                 break;
  706.             }
  707.         }
  708.     } while( !b_ok );
  709.     /* In the standard, a P-frame's ref list is sorted by frame_num.
  710.      * We use POC, but check whether explicit reordering is needed */
  711.     h->b_ref_reorder[0] =
  712.     h->b_ref_reorder[1] = 0;
  713.     if( i_slice_type == SLICE_TYPE_P )
  714.     {
  715.         for( i = 0; i < h->i_ref0 - 1; i++ )
  716.             if( h->fref0[i]->i_frame_num < h->fref0[i+1]->i_frame_num )
  717.             {
  718.                 h->b_ref_reorder[0] = 1;
  719.                 break;
  720.             }
  721.     }
  722.     h->i_ref1 = X264_MIN( h->i_ref1, h->frames.i_max_ref1 );
  723.     h->i_ref0 = X264_MIN( h->i_ref0, h->frames.i_max_ref0 );
  724.     h->i_ref0 = X264_MIN( h->i_ref0, 16 - h->i_ref1 );
  725. }
  726. static inline void x264_reference_update( x264_t *h )
  727. {
  728.     int i;
  729.     /* apply deblocking filter to the current decoded picture */
  730.     if( !h->sh.i_disable_deblocking_filter_idc )
  731.     {
  732.         TIMER_START( i_mtime_filter );
  733.         x264_frame_deblocking_filter( h, h->sh.i_type );
  734.         TIMER_STOP( i_mtime_filter );
  735.     }
  736.     /* expand border */
  737.     x264_frame_expand_border( h->fdec );
  738.     /* create filtered images */
  739.     x264_frame_filter( h->param.cpu, h->fdec );
  740.     /* expand border of filtered images */
  741.     x264_frame_expand_border_filtered( h->fdec );
  742.     /* move lowres copy of the image to the ref frame */
  743.     for( i = 0; i < 4; i++)
  744.         XCHG( uint8_t*, h->fdec->lowres[i], h->fenc->lowres[i] );
  745.     /* adaptive B decision needs a pointer, since it can't use the ref lists */
  746.     if( h->sh.i_type != SLICE_TYPE_B )
  747.         h->frames.last_nonb = h->fdec;
  748.     /* move frame in the buffer */
  749.     h->fdec = h->frames.reference[h->frames.i_max_dpb-1];
  750.     for( i = h->frames.i_max_dpb-1; i > 0; i-- )
  751.     {
  752.         h->frames.reference[i] = h->frames.reference[i-1];
  753.     }
  754.     h->frames.reference[0] = h->fdec;
  755. }
  756. static inline void x264_reference_reset( x264_t *h )
  757. {
  758.     int i;
  759.     /* reset ref pictures */
  760.     for( i = 1; i < h->frames.i_max_dpb; i++ )
  761.     {
  762.         h->frames.reference[i]->i_poc = -1;
  763.     }
  764.     h->frames.reference[0]->i_poc = 0;
  765. }
  766. static inline void x264_slice_init( x264_t *h, int i_nal_type, int i_slice_type, int i_global_qp )
  767. {
  768.     /* ------------------------ Create slice header  ----------------------- */
  769.     if( i_nal_type == NAL_SLICE_IDR )
  770.     {
  771.         x264_slice_header_init( h, &h->sh, h->sps, h->pps, i_slice_type, h->i_idr_pic_id, h->i_frame_num - 1, i_global_qp );
  772.         /* increment id */
  773.         h->i_idr_pic_id = ( h->i_idr_pic_id + 1 ) % 65536;
  774.     }
  775.     else
  776.     {
  777.         x264_slice_header_init( h, &h->sh, h->sps, h->pps, i_slice_type, -1, h->i_frame_num - 1, i_global_qp );
  778.         /* always set the real higher num of ref frame used */
  779.         h->sh.b_num_ref_idx_override = 1;
  780.         h->sh.i_num_ref_idx_l0_active = h->i_ref0 <= 0 ? 1 : h->i_ref0;
  781.         h->sh.i_num_ref_idx_l1_active = h->i_ref1 <= 0 ? 1 : h->i_ref1;
  782.     }
  783.     h->fdec->i_frame_num = h->sh.i_frame_num;
  784.     if( h->sps->i_poc_type == 0 )
  785.     {
  786.         h->sh.i_poc_lsb = h->fdec->i_poc & ( (1 << h->sps->i_log2_max_poc_lsb) - 1 );
  787.         h->sh.i_delta_poc_bottom = 0;   /* XXX won't work for field */
  788.     }
  789.     else if( h->sps->i_poc_type == 1 )
  790.     {
  791.         /* FIXME TODO FIXME */
  792.     }
  793.     else
  794.     {
  795.         /* Nothing to do ? */
  796.     }
  797.     x264_macroblock_slice_init( h );
  798. }
  799. static int x264_slice_write( x264_t *h )
  800. {
  801.     int i_skip;
  802.     int mb_xy;
  803.     int i;
  804.     /* init stats */
  805.     memset( &h->stat.frame, 0, sizeof(h->stat.frame) );
  806.     /* Slice */
  807.     x264_nal_start( h, h->i_nal_type, h->i_nal_ref_idc );
  808.     /* Slice header */
  809.     x264_slice_header_write( &h->out.bs, &h->sh, h->i_nal_ref_idc );
  810.     if( h->param.b_cabac )
  811.     {
  812.         /* alignment needed */
  813.         bs_align_1( &h->out.bs );
  814.         /* init cabac */
  815.         x264_cabac_context_init( &h->cabac, h->sh.i_type, h->sh.i_qp, h->sh.i_cabac_init_idc );
  816.         x264_cabac_encode_init ( &h->cabac, &h->out.bs );
  817.     }
  818.     h->mb.i_last_qp = h->sh.i_qp;
  819.     h->mb.i_last_dqp = 0;
  820.     for( mb_xy = h->sh.i_first_mb, i_skip = 0; mb_xy < h->sh.i_last_mb; mb_xy++ )
  821.     {
  822.         const int i_mb_y = mb_xy / h->sps->i_mb_width;
  823.         const int i_mb_x = mb_xy % h->sps->i_mb_width;
  824.         int mb_spos = bs_pos(&h->out.bs);
  825.         /* load cache */
  826.         x264_macroblock_cache_load( h, i_mb_x, i_mb_y );
  827.         /* analyse parameters
  828.          * Slice I: choose I_4x4 or I_16x16 mode
  829.          * Slice P: choose between using P mode or intra (4x4 or 16x16)
  830.          * */
  831.         TIMER_START( i_mtime_analyse );
  832.         x264_macroblock_analyse( h );
  833.         TIMER_STOP( i_mtime_analyse );
  834.         /* encode this macrobock -> be carefull it can change the mb type to P_SKIP if needed */
  835.         TIMER_START( i_mtime_encode );
  836.         x264_macroblock_encode( h );
  837.         TIMER_STOP( i_mtime_encode );
  838.         TIMER_START( i_mtime_write );
  839.         if( h->param.b_cabac )
  840.         {
  841.             if( mb_xy > h->sh.i_first_mb )
  842.                 x264_cabac_encode_terminal( &h->cabac, 0 );
  843.             if( IS_SKIP( h->mb.i_type ) )
  844.                 x264_cabac_mb_skip( h, 1 );
  845.             else
  846.             {
  847.                 if( h->sh.i_type != SLICE_TYPE_I )
  848.                     x264_cabac_mb_skip( h, 0 );
  849.                 x264_macroblock_write_cabac( h, &h->cabac );
  850.             }
  851.         }
  852.         else
  853.         {
  854.             if( IS_SKIP( h->mb.i_type ) )
  855.                 i_skip++;
  856.             else
  857.             {
  858.                 if( h->sh.i_type != SLICE_TYPE_I )
  859.                 {
  860.                     bs_write_ue( &h->out.bs, i_skip );  /* skip run */
  861.                     i_skip = 0;
  862.                 }
  863.                 x264_macroblock_write_cavlc( h, &h->out.bs );
  864.             }
  865.         }
  866.         TIMER_STOP( i_mtime_write );
  867. #if VISUALIZE
  868.         if( h->param.b_visualize )
  869.             x264_visualize_mb( h );
  870. #endif
  871.         /* save cache */
  872.         x264_macroblock_cache_save( h );
  873.         /* accumulate mb stats */
  874.         h->stat.frame.i_mb_count[h->mb.i_type]++;
  875.         if( !IS_SKIP(h->mb.i_type) && !IS_INTRA(h->mb.i_type) && !IS_DIRECT(h->mb.i_type) )
  876.         {
  877.             if( h->mb.i_partition != D_8x8 )
  878.                 h->stat.frame.i_mb_count_size[ x264_mb_partition_pixel_table[ h->mb.i_partition ] ] += 4;
  879.             else
  880.                 for( i = 0; i < 4; i++ )
  881.                     h->stat.frame.i_mb_count_size[ x264_mb_partition_pixel_table[ h->mb.i_sub_partition[i] ] ] ++;
  882.             if( h->param.i_frame_reference > 1 )
  883.             {
  884.                 for( i = 0; i < 4; i++ )
  885.                 {
  886.                     int i_ref = h->mb.cache.ref[0][ x264_scan8[4*i] ];
  887.                     if( i_ref >= 0 )
  888.                         h->stat.frame.i_mb_count_ref[i_ref] ++;
  889.                 }
  890.             }
  891.         }
  892.         if( h->mb.i_cbp_luma && !IS_INTRA(h->mb.i_type) )
  893.         {
  894.             h->stat.frame.i_mb_count_8x8dct[0] ++;
  895.             h->stat.frame.i_mb_count_8x8dct[1] += h->mb.b_transform_8x8;
  896.         }
  897.         if( h->mb.b_variable_qp )
  898.             x264_ratecontrol_mb(h, bs_pos(&h->out.bs) - mb_spos);
  899.     }
  900.     if( h->param.b_cabac )
  901.     {
  902.         /* end of slice */
  903.         x264_cabac_encode_terminal( &h->cabac, 1 );
  904.     }
  905.     else if( i_skip > 0 )
  906.     {
  907.         bs_write_ue( &h->out.bs, i_skip );  /* last skip run */
  908.     }
  909.     if( h->param.b_cabac )
  910.     {
  911.         x264_cabac_encode_flush( &h->cabac );
  912.     }
  913.     else
  914.     {
  915.         /* rbsp_slice_trailing_bits */
  916.         bs_rbsp_trailing( &h->out.bs );
  917.     }
  918.     x264_nal_end( h );
  919.     /* Compute misc bits */
  920.     h->stat.frame.i_misc_bits = bs_pos( &h->out.bs )
  921.                               + NALU_OVERHEAD * 8
  922.                               - h->stat.frame.i_itex_bits
  923.                               - h->stat.frame.i_ptex_bits
  924.                               - h->stat.frame.i_hdr_bits;
  925.     return 0;
  926. }
  927. static inline int x264_slices_write( x264_t *h )
  928. {
  929.     int i_frame_size;
  930. #if VISUALIZE
  931.     if( h->param.b_visualize )
  932.         x264_visualize_init( h );
  933. #endif
  934.     if( h->param.i_threads == 1 )
  935.     {
  936.         x264_slice_write( h );
  937.         i_frame_size = h->out.nal[h->out.i_nal-1].i_payload;
  938.     }
  939.     else
  940.     {
  941.         int i_nal = h->out.i_nal;
  942.         int i_bs_size = h->out.i_bitstream / h->param.i_threads;
  943.         int i;
  944.         /* duplicate contexts */
  945.         for( i = 0; i < h->param.i_threads; i++ )
  946.         {
  947.             x264_t *t = h->thread[i];
  948.             if( i > 0 )
  949.             {
  950.                 memcpy( t, h, sizeof(x264_t) );
  951.                 t->out.p_bitstream += i*i_bs_size;
  952.                 bs_init( &t->out.bs, t->out.p_bitstream, i_bs_size );
  953.             }
  954.             t->sh.i_first_mb = (i    * h->sps->i_mb_height / h->param.i_threads) * h->sps->i_mb_width;
  955.             t->sh.i_last_mb = ((i+1) * h->sps->i_mb_height / h->param.i_threads) * h->sps->i_mb_width;
  956.             t->out.i_nal = i_nal + i;
  957.         }
  958.         /* dispatch */
  959. #if HAVE_PTHREAD
  960.         {
  961.             pthread_t handles[X264_SLICE_MAX];
  962.             void *status;
  963.             for( i = 0; i < h->param.i_threads; i++ )
  964.                 pthread_create( &handles[i], NULL, (void*)x264_slice_write, (void*)h->thread[i] );
  965.             for( i = 0; i < h->param.i_threads; i++ )
  966.                 pthread_join( handles[i], &status );
  967.         }
  968. #else
  969.         for( i = 0; i < h->param.i_threads; i++ )
  970.             x264_slice_write( h->thread[i] );
  971. #endif
  972.         /* merge contexts */
  973.         i_frame_size = h->out.nal[i_nal].i_payload;
  974.         for( i = 1; i < h->param.i_threads; i++ )
  975.         {
  976.             int j;
  977.             x264_t *t = h->thread[i];
  978.             h->out.nal[i_nal+i] = t->out.nal[i_nal+i];
  979.             i_frame_size += t->out.nal[i_nal+i].i_payload;
  980.             // all entries in stat.frame are ints
  981.             for( j = 0; j < sizeof(h->stat.frame) / sizeof(int); j++ )
  982.                 ((int*)&h->stat.frame)[j] += ((int*)&t->stat.frame)[j];
  983.         }
  984.         h->out.i_nal = i_nal + h->param.i_threads;
  985.     }
  986. #if VISUALIZE
  987.     if( h->param.b_visualize )
  988.     {
  989.         x264_visualize_show( h );
  990.         x264_visualize_close( h );
  991.     }
  992. #endif
  993.     return i_frame_size;
  994. }
  995. /****************************************************************************
  996.  * x264_encoder_encode:
  997.  *  XXX: i_poc   : is the poc of the current given picture
  998.  *       i_frame : is the number of the frame being coded
  999.  *  ex:  type frame poc
  1000.  *       I      0   2*0
  1001.  *       P      1   2*3
  1002.  *       B      2   2*1
  1003.  *       B      3   2*2
  1004.  *       P      4   2*6
  1005.  *       B      5   2*4
  1006.  *       B      6   2*5
  1007.  ****************************************************************************/
  1008. int     x264_encoder_encode( x264_t *h,
  1009.                              x264_nal_t **pp_nal, int *pi_nal,
  1010.                              x264_picture_t *pic_in,
  1011.                              x264_picture_t *pic_out )
  1012. {
  1013.     x264_frame_t   *frame_psnr = h->fdec; /* just to keep the current decoded frame for psnr calculation */
  1014.     int     i_nal_type;
  1015.     int     i_nal_ref_idc;
  1016.     int     i_slice_type;
  1017.     int     i_frame_size;
  1018.     int i;
  1019.     int   i_global_qp;
  1020.     char psz_message[80];
  1021.     /* no data out */
  1022.     *pi_nal = 0;
  1023.     *pp_nal = NULL;
  1024.     /* ------------------- Setup new frame from picture -------------------- */
  1025.     TIMER_START( i_mtime_encode_frame );
  1026.     if( pic_in != NULL )
  1027.     {
  1028.         /* 1: Copy the picture to a frame and move it to a buffer */
  1029.         x264_frame_t *fenc = x264_frame_get( h->frames.unused );
  1030.         x264_frame_copy_picture( h, fenc, pic_in );
  1031.         if( h->param.i_width % 16 || h->param.i_height % 16 )
  1032.             x264_frame_expand_border_mod16( h, fenc );
  1033.         fenc->i_frame = h->frames.i_input++;
  1034.         x264_frame_put( h->frames.next, fenc );
  1035.         if( h->frames.b_have_lowres )
  1036.             x264_frame_init_lowres( h->param.cpu, fenc );
  1037.         if( h->frames.i_input <= h->frames.i_delay )
  1038.         {
  1039.             /* Nothing yet to encode */
  1040.             /* waiting for filling bframe buffer */
  1041.             pic_out->i_type = X264_TYPE_AUTO;
  1042.             return 0;
  1043.         }
  1044.     }
  1045.     if( h->frames.current[0] == NULL )
  1046.     {
  1047.         int bframes = 0;
  1048.         /* 2: Select frame types */
  1049.         if( h->frames.next[0] == NULL )
  1050.             return 0;
  1051.         x264_slicetype_decide( h );
  1052.         /* 3: move some B-frames and 1 non-B to encode queue */
  1053.         while( IS_X264_TYPE_B( h->frames.next[bframes]->i_type ) )
  1054.             bframes++;
  1055.         x264_frame_put( h->frames.current, x264_frame_get( &h->frames.next[bframes] ) );
  1056.         /* FIXME: when max B-frames > 3, BREF may no longer be centered after GOP closing */
  1057.         if( h->param.b_bframe_pyramid && bframes > 1 )
  1058.         {
  1059.             x264_frame_t *mid = x264_frame_get( &h->frames.next[bframes/2] );
  1060.             mid->i_type = X264_TYPE_BREF;
  1061.             x264_frame_put( h->frames.current, mid );
  1062.             bframes--;
  1063.         }
  1064.         while( bframes-- )
  1065.             x264_frame_put( h->frames.current, x264_frame_get( h->frames.next ) );
  1066.     }
  1067.     TIMER_STOP( i_mtime_encode_frame );
  1068.     /* ------------------- Get frame to be encoded ------------------------- */
  1069.     /* 4: get picture to encode */
  1070.     h->fenc = x264_frame_get( h->frames.current );
  1071.     if( h->fenc == NULL )
  1072.     {
  1073.         /* Nothing yet to encode (ex: waiting for I/P with B frames) */
  1074.         /* waiting for filling bframe buffer */
  1075.         pic_out->i_type = X264_TYPE_AUTO;
  1076.         return 0;
  1077.     }
  1078. do_encode:
  1079.     if( h->fenc->i_type == X264_TYPE_IDR )
  1080.     {
  1081.         h->frames.i_last_idr = h->fenc->i_frame;
  1082.     }
  1083.     /* ------------------- Setup frame context ----------------------------- */
  1084.     /* 5: Init data dependant of frame type */
  1085.     TIMER_START( i_mtime_encode_frame );
  1086.     if( h->fenc->i_type == X264_TYPE_IDR )
  1087.     {
  1088.         /* reset ref pictures */
  1089.         x264_reference_reset( h );
  1090.         i_nal_type    = NAL_SLICE_IDR;
  1091.         i_nal_ref_idc = NAL_PRIORITY_HIGHEST;
  1092.         i_slice_type = SLICE_TYPE_I;
  1093.     }
  1094.     else if( h->fenc->i_type == X264_TYPE_I )
  1095.     {
  1096.         i_nal_type    = NAL_SLICE;
  1097.         i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
  1098.         i_slice_type = SLICE_TYPE_I;
  1099.     }
  1100.     else if( h->fenc->i_type == X264_TYPE_P )
  1101.     {
  1102.         i_nal_type    = NAL_SLICE;
  1103.         i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
  1104.         i_slice_type = SLICE_TYPE_P;
  1105.     }
  1106.     else if( h->fenc->i_type == X264_TYPE_BREF )
  1107.     {
  1108.         i_nal_type    = NAL_SLICE;
  1109.         i_nal_ref_idc = NAL_PRIORITY_HIGH; /* maybe add MMCO to forget it? -> low */
  1110.         i_slice_type = SLICE_TYPE_B;
  1111.     }
  1112.     else    /* B frame */
  1113.     {
  1114.         i_nal_type    = NAL_SLICE;
  1115.         i_nal_ref_idc = NAL_PRIORITY_DISPOSABLE;
  1116.         i_slice_type = SLICE_TYPE_B;
  1117.     }
  1118.     h->fdec->i_poc =
  1119.     h->fenc->i_poc = 2 * (h->fenc->i_frame - h->frames.i_last_idr);
  1120.     h->fdec->i_type = h->fenc->i_type;
  1121.     h->fdec->i_frame = h->fenc->i_frame;
  1122.     h->fenc->b_kept_as_ref =
  1123.     h->fdec->b_kept_as_ref = i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE;
  1124.     /* ------------------- Init                ----------------------------- */
  1125.     /* build ref list 0/1 */
  1126.     x264_reference_build_list( h, h->fdec->i_poc, i_slice_type );
  1127.     /* Init the rate control */
  1128.     x264_ratecontrol_start( h, i_slice_type, h->fenc->i_qpplus1 );
  1129.     i_global_qp = x264_ratecontrol_qp( h );
  1130.     pic_out->i_qpplus1 =
  1131.     h->fdec->i_qpplus1 = i_global_qp + 1;
  1132.     if( i_slice_type == SLICE_TYPE_B )
  1133.         x264_macroblock_bipred_init( h );
  1134.     if( h->fenc->b_kept_as_ref )
  1135.         h->i_frame_num++;
  1136.     /* ------------------------ Create slice header  ----------------------- */
  1137.     x264_slice_init( h, i_nal_type, i_slice_type, i_global_qp );
  1138.     /* ---------------------- Write the bitstream -------------------------- */
  1139.     /* Init bitstream context */
  1140.     h->out.i_nal = 0;
  1141.     bs_init( &h->out.bs, h->out.p_bitstream, h->out.i_bitstream );
  1142.     if(h->param.b_aud){
  1143.         int pic_type;
  1144.         if(i_slice_type == SLICE_TYPE_I)
  1145.             pic_type = 0;
  1146.         else if(i_slice_type == SLICE_TYPE_P)
  1147.             pic_type = 1;
  1148.         else if(i_slice_type == SLICE_TYPE_B)
  1149.             pic_type = 2;
  1150.         else
  1151.             pic_type = 7;
  1152.         x264_nal_start(h, NAL_AUD, NAL_PRIORITY_DISPOSABLE);
  1153.         bs_write(&h->out.bs, 3, pic_type);
  1154.         bs_rbsp_trailing(&h->out.bs);
  1155.         x264_nal_end(h);
  1156.     }
  1157.     h->i_nal_type = i_nal_type;
  1158.     h->i_nal_ref_idc = i_nal_ref_idc;
  1159.     /* Write SPS and PPS */
  1160.     if( i_nal_type == NAL_SLICE_IDR && h->param.b_repeat_headers )
  1161.     {
  1162.         if( h->fenc->i_frame == 0 )
  1163.         {
  1164.             /* identify ourself */
  1165.             x264_nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
  1166.             x264_sei_version_write( h, &h->out.bs );
  1167.             x264_nal_end( h );
  1168.         }
  1169.         /* generate sequence parameters */
  1170.         x264_nal_start( h, NAL_SPS, NAL_PRIORITY_HIGHEST );
  1171.         x264_sps_write( &h->out.bs, h->sps );
  1172.         x264_nal_end( h );
  1173.         /* generate picture parameters */
  1174.         x264_nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
  1175.         x264_pps_write( &h->out.bs, h->pps );
  1176.         x264_nal_end( h );
  1177.     }
  1178.     /* Write frame */
  1179.     i_frame_size = x264_slices_write( h );
  1180.     /* restore CPU state (before using float again) */
  1181.     x264_cpu_restore( h->param.cpu );
  1182.     if( i_slice_type == SLICE_TYPE_P && !h->param.rc.b_stat_read 
  1183.         && h->param.i_scenecut_threshold >= 0 )
  1184.     {
  1185.         const int *mbs = h->stat.frame.i_mb_count;
  1186.         int i_mb_i = mbs[I_16x16] + mbs[I_8x8] + mbs[I_4x4];
  1187.         int i_mb_p = mbs[P_L0] + mbs[P_8x8];
  1188.         int i_mb_s = mbs[P_SKIP];
  1189.         int i_mb   = h->sps->i_mb_width * h->sps->i_mb_height;
  1190.         int64_t i_inter_cost = h->stat.frame.i_inter_cost;
  1191.         int64_t i_intra_cost = h->stat.frame.i_intra_cost;
  1192.         float f_bias;
  1193.         int i_gop_size = h->fenc->i_frame - h->frames.i_last_idr;
  1194.         float f_thresh_max = h->param.i_scenecut_threshold / 100.0;
  1195.         /* magic numbers pulled out of thin air */
  1196.         float f_thresh_min = f_thresh_max * h->param.i_keyint_min
  1197.                              / ( h->param.i_keyint_max * 4 );
  1198.         if( h->param.i_keyint_min == h->param.i_keyint_max )
  1199.              f_thresh_min= f_thresh_max;
  1200.         /* macroblock_analyse() doesn't further analyse skipped mbs,
  1201.          * so we have to guess their cost */
  1202.         if( i_mb_s < i_mb )
  1203.             i_intra_cost = i_intra_cost * i_mb / (i_mb - i_mb_s);
  1204.         if( i_gop_size < h->param.i_keyint_min / 4 )
  1205.             f_bias = f_thresh_min / 4;
  1206.         else if( i_gop_size <= h->param.i_keyint_min )
  1207.             f_bias = f_thresh_min * i_gop_size / h->param.i_keyint_min;
  1208.         else
  1209.         {
  1210.             f_bias = f_thresh_min
  1211.                      + ( f_thresh_max - f_thresh_min )
  1212.                        * ( i_gop_size - h->param.i_keyint_min )
  1213.                        / ( h->param.i_keyint_max - h->param.i_keyint_min );
  1214.         }
  1215.         f_bias = X264_MIN( f_bias, 1.0 );
  1216.         /* Bad P will be reencoded as I */
  1217.         if( i_mb_s < i_mb &&
  1218.             i_inter_cost >= (1.0 - f_bias) * i_intra_cost )
  1219.         {
  1220.             int b;
  1221.             x264_log( h, X264_LOG_DEBUG, "scene cut at %d Icost:%.0f Pcost:%.0f ratio:%.3f bias=%.3f lastIDR:%d (I:%d P:%d S:%d)n",
  1222.                       h->fenc->i_frame,
  1223.                       (double)i_intra_cost, (double)i_inter_cost,
  1224.                       (double)i_inter_cost / i_intra_cost,
  1225.                       f_bias, i_gop_size,
  1226.                       i_mb_i, i_mb_p, i_mb_s );
  1227.             /* Restore frame num */
  1228.             h->i_frame_num--;
  1229.             for( b = 0; h->frames.current[b] && IS_X264_TYPE_B( h->frames.current[b]->i_type ); b++ );
  1230.             if( b > 0 )
  1231.             {
  1232.                 /* If using B-frames, force GOP to be closed.
  1233.                  * Even if this frame is going to be I and not IDR, forcing a
  1234.                  * P-frame before the scenecut will probably help compression.
  1235.                  * 
  1236.                  * We don't yet know exactly which frame is the scene cut, so
  1237.                  * we can't assign an I-frame. Instead, change the previous
  1238.                  * B-frame to P, and rearrange coding order. */
  1239.                 if( h->param.b_bframe_adaptive || b > 1 )
  1240.                     h->fenc->i_type = X264_TYPE_AUTO;
  1241.                 x264_frame_sort_pts( h->frames.current );
  1242.                 x264_frame_push( h->frames.next, h->fenc );
  1243.                 h->fenc = h->frames.current[b-1];
  1244.                 h->frames.current[b-1] = NULL;
  1245.                 h->fenc->i_type = X264_TYPE_P;
  1246.                 x264_frame_sort_dts( h->frames.current );
  1247.             }
  1248.             /* Do IDR if needed */
  1249.             else if( i_gop_size >= h->param.i_keyint_min )
  1250.             {
  1251.                 x264_frame_t *tmp;
  1252.                 /* Reset */
  1253.                 h->i_frame_num = 0;
  1254.                 /* Reinit field of fenc */
  1255.                 h->fenc->i_type = X264_TYPE_IDR;
  1256.                 h->fenc->i_poc = 0;
  1257.                 /* Put enqueued frames back in the pool */
  1258.                 while( (tmp = x264_frame_get( h->frames.current ) ) != NULL )
  1259.                     x264_frame_put( h->frames.next, tmp );
  1260.                 x264_frame_sort_pts( h->frames.next );
  1261.             }
  1262.             else
  1263.             {
  1264.                 h->fenc->i_type = X264_TYPE_I;
  1265.             }
  1266.             goto do_encode;
  1267.         }
  1268.     }
  1269.     /* End bitstream, set output  */
  1270.     *pi_nal = h->out.i_nal;
  1271.     *pp_nal = h->out.nal;
  1272.     /* Set output picture properties */
  1273.     if( i_slice_type == SLICE_TYPE_I )
  1274.         pic_out->i_type = i_nal_type == NAL_SLICE_IDR ? X264_TYPE_IDR : X264_TYPE_I;
  1275.     else if( i_slice_type == SLICE_TYPE_P )
  1276.         pic_out->i_type = X264_TYPE_P;
  1277.     else
  1278.         pic_out->i_type = X264_TYPE_B;
  1279.     pic_out->i_pts = h->fenc->i_pts;
  1280.     pic_out->img.i_plane = h->fdec->i_plane;
  1281.     for(i = 0; i < 4; i++){
  1282.         pic_out->img.i_stride[i] = h->fdec->i_stride[i];
  1283.         pic_out->img.plane[i] = h->fdec->plane[i];
  1284.     }
  1285.     /* ---------------------- Update encoder state ------------------------- */
  1286.     /* handle references */
  1287.     if( i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE )
  1288.     {
  1289.         x264_reference_update( h );
  1290.     }
  1291.     /* increase frame count */
  1292.     h->i_frame++;
  1293.     /* restore CPU state (before using float again) */
  1294.     /* XXX: not needed? (done above) */
  1295.     x264_cpu_restore( h->param.cpu );
  1296.     /* update rc */
  1297.     x264_ratecontrol_end( h, i_frame_size * 8 );
  1298.     x264_frame_put( h->frames.unused, h->fenc );
  1299.     x264_noise_reduction_update( h );
  1300.     TIMER_STOP( i_mtime_encode_frame );
  1301.     /* ---------------------- Compute/Print statistics --------------------- */
  1302.     /* Slice stat */
  1303.     h->stat.i_slice_count[i_slice_type]++;
  1304.     h->stat.i_slice_size[i_slice_type] += i_frame_size + NALU_OVERHEAD;
  1305.     h->stat.i_slice_qp[i_slice_type] += i_global_qp;
  1306.     for( i = 0; i < 19; i++ )
  1307.         h->stat.i_mb_count[h->sh.i_type][i] += h->stat.frame.i_mb_count[i];
  1308.     for( i = 0; i < 2; i++ )
  1309.         h->stat.i_mb_count_8x8dct[i] += h->stat.frame.i_mb_count_8x8dct[i];
  1310.     if( h->sh.i_type != SLICE_TYPE_I )
  1311.     {
  1312.         for( i = 0; i < 7; i++ )
  1313.             h->stat.i_mb_count_size[h->sh.i_type][i] += h->stat.frame.i_mb_count_size[i];
  1314.         for( i = 0; i < 16; i++ )
  1315.             h->stat.i_mb_count_ref[h->sh.i_type][i] += h->stat.frame.i_mb_count_ref[i];
  1316.     }
  1317.     if( i_slice_type == SLICE_TYPE_B )
  1318.     {
  1319.         h->stat.i_direct_frames[ h->sh.b_direct_spatial_mv_pred ] ++;
  1320.         if( h->mb.b_direct_auto_write )
  1321.         {
  1322.             //FIXME somewhat arbitrary time constants
  1323.             if( h->stat.i_direct_score[0] + h->stat.i_direct_score[1] > h->mb.i_mb_count )
  1324.             {
  1325.                 for( i = 0; i < 2; i++ )
  1326.                     h->stat.i_direct_score[i] = h->stat.i_direct_score[i] * 9/10;
  1327.             }
  1328.             for( i = 0; i < 2; i++ )
  1329.                 h->stat.i_direct_score[i] += h->stat.frame.i_direct_score[i];
  1330.         }
  1331.     }
  1332.     if( h->param.analyse.b_psnr )
  1333.     {
  1334.         int64_t i_sqe_y, i_sqe_u, i_sqe_v;
  1335.         /* PSNR */
  1336.         i_sqe_y = x264_pixel_ssd_wxh( &h->pixf, frame_psnr->plane[0], frame_psnr->i_stride[0], h->fenc->plane[0], h->fenc->i_stride[0], h->param.i_width, h->param.i_height );
  1337.         i_sqe_u = x264_pixel_ssd_wxh( &h->pixf, frame_psnr->plane[1], frame_psnr->i_stride[1], h->fenc->plane[1], h->fenc->i_stride[1], h->param.i_width/2, h->param.i_height/2);
  1338.         i_sqe_v = x264_pixel_ssd_wxh( &h->pixf, frame_psnr->plane[2], frame_psnr->i_stride[2], h->fenc->plane[2], h->fenc->i_stride[2], h->param.i_width/2, h->param.i_height/2);
  1339.         x264_cpu_restore( h->param.cpu );
  1340.         h->stat.i_sqe_global[i_slice_type] += i_sqe_y + i_sqe_u + i_sqe_v;
  1341.         h->stat.f_psnr_average[i_slice_type] += x264_psnr( i_sqe_y + i_sqe_u + i_sqe_v, 3 * h->param.i_width * h->param.i_height / 2 );
  1342.         h->stat.f_psnr_mean_y[i_slice_type] += x264_psnr( i_sqe_y, h->param.i_width * h->param.i_height );
  1343.         h->stat.f_psnr_mean_u[i_slice_type] += x264_psnr( i_sqe_u, h->param.i_width * h->param.i_height / 4 );
  1344.         h->stat.f_psnr_mean_v[i_slice_type] += x264_psnr( i_sqe_v, h->param.i_width * h->param.i_height / 4 );
  1345.         snprintf( psz_message, 80, " PSNR Y:%2.2f U:%2.2f V:%2.2f",
  1346.                   x264_psnr( i_sqe_y, h->param.i_width * h->param.i_height ),
  1347.                   x264_psnr( i_sqe_u, h->param.i_width * h->param.i_height / 4),
  1348.                   x264_psnr( i_sqe_v, h->param.i_width * h->param.i_height / 4) );
  1349.         psz_message[79] = '';
  1350.     }
  1351.     else
  1352.     {
  1353.         psz_message[0] = '';
  1354.     }
  1355.     
  1356.     x264_log( h, X264_LOG_DEBUG,
  1357.                   "frame=%4d QP=%i NAL=%d Slice:%c Poc:%-3d I:%-4d P:%-4d SKIP:%-4d size=%d bytes%sn",
  1358.               h->i_frame - 1,
  1359.               i_global_qp,
  1360.               i_nal_ref_idc,
  1361.               i_slice_type == SLICE_TYPE_I ? 'I' : (i_slice_type == SLICE_TYPE_P ? 'P' : 'B' ),
  1362.               frame_psnr->i_poc,
  1363.               h->stat.frame.i_mb_count_i,
  1364.               h->stat.frame.i_mb_count_p,
  1365.               h->stat.frame.i_mb_count_skip,
  1366.               i_frame_size,
  1367.               psz_message );
  1368. #ifdef DEBUG_MB_TYPE
  1369. {
  1370.     static const char mb_chars[] = { 'i', 'i', 'I', 'C', 'P', '8', 'S',
  1371.         'D', '<', 'X', 'B', 'X', '>', 'B', 'B', 'B', 'B', '8', 'S' };
  1372.     int mb_xy;
  1373.     for( mb_xy = 0; mb_xy < h->sps->i_mb_width * h->sps->i_mb_height; mb_xy++ )
  1374.     {
  1375.         if( h->mb.type[mb_xy] < 19 && h->mb.type[mb_xy] >= 0 )
  1376.             fprintf( stderr, "%c ", mb_chars[ h->mb.type[mb_xy] ] );
  1377.         else
  1378.             fprintf( stderr, "? " );
  1379.         if( (mb_xy+1) % h->sps->i_mb_width == 0 )
  1380.             fprintf( stderr, "n" );
  1381.     }
  1382. }
  1383. #endif
  1384. #ifdef DEBUG_DUMP_FRAME
  1385.     /* Dump reconstructed frame */
  1386.     x264_frame_dump( h, frame_psnr, "fdec.yuv" );
  1387. #endif
  1388.     return 0;
  1389. }
  1390. /****************************************************************************
  1391.  * x264_encoder_close:
  1392.  ****************************************************************************/
  1393. void    x264_encoder_close  ( x264_t *h )
  1394. {
  1395. #ifdef DEBUG_BENCHMARK
  1396.     int64_t i_mtime_total = i_mtime_analyse + i_mtime_encode + i_mtime_write + i_mtime_filter + 1;
  1397. #endif
  1398.     int64_t i_yuv_size = 3 * h->param.i_width * h->param.i_height / 2;
  1399.     int i;
  1400. #ifdef DEBUG_BENCHMARK
  1401.     x264_log( h, X264_LOG_INFO,
  1402.               "analyse=%d(%lldms) encode=%d(%lldms) write=%d(%lldms) filter=%d(%lldms)n",
  1403.               (int)(100*i_mtime_analyse/i_mtime_total), i_mtime_analyse/1000,
  1404.               (int)(100*i_mtime_encode/i_mtime_total), i_mtime_encode/1000,
  1405.               (int)(100*i_mtime_write/i_mtime_total), i_mtime_write/1000,
  1406.               (int)(100*i_mtime_filter/i_mtime_total), i_mtime_filter/1000 );
  1407. #endif
  1408.     /* Slices used and PSNR */
  1409.     for( i=0; i<5; i++ )
  1410.     {
  1411.         static const int slice_order[] = { SLICE_TYPE_I, SLICE_TYPE_SI, SLICE_TYPE_P, SLICE_TYPE_SP, SLICE_TYPE_B };
  1412.         static const char *slice_name[] = { "P", "B", "I", "SP", "SI" };
  1413.         int i_slice = slice_order[i];
  1414.         if( h->stat.i_slice_count[i_slice] > 0 )
  1415.         {
  1416.             const int i_count = h->stat.i_slice_count[i_slice];
  1417.             if( h->param.analyse.b_psnr )
  1418.             {
  1419.                 x264_log( h, X264_LOG_INFO,
  1420.                           "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",
  1421.                           slice_name[i_slice],
  1422.                           i_count,
  1423.                           (double)h->stat.i_slice_qp[i_slice] / i_count,
  1424.                           (double)h->stat.i_slice_size[i_slice] / i_count,
  1425.                           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,
  1426.                           h->stat.f_psnr_average[i_slice] / i_count,
  1427.                           x264_psnr( h->stat.i_sqe_global[i_slice], i_count * i_yuv_size ) );
  1428.             }
  1429.             else
  1430.             {
  1431.                 x264_log( h, X264_LOG_INFO,
  1432.                           "slice %s:%-5d Avg QP:%5.2f  size:%6.0fn",
  1433.                           slice_name[i_slice],
  1434.                           i_count,
  1435.                           (double)h->stat.i_slice_qp[i_slice] / i_count,
  1436.                           (double)h->stat.i_slice_size[i_slice] / i_count );
  1437.             }
  1438.         }
  1439.     }
  1440.     /* MB types used */
  1441.     if( h->stat.i_slice_count[SLICE_TYPE_I] > 0 )
  1442.     {
  1443.         const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_I];
  1444.         const double i_count = h->stat.i_slice_count[SLICE_TYPE_I] * h->mb.i_mb_count / 100.0;
  1445.         x264_log( h, X264_LOG_INFO,
  1446.                   "mb I  I16..4: %4.1f%% %4.1f%% %4.1f%%n",
  1447.                   i_mb_count[I_16x16]/ i_count,
  1448.                   i_mb_count[I_8x8]  / i_count,
  1449.                   i_mb_count[I_4x4]  / i_count );
  1450.     }
  1451.     if( h->stat.i_slice_count[SLICE_TYPE_P] > 0 )
  1452.     {
  1453.         const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_P];
  1454.         const int64_t *i_mb_size = h->stat.i_mb_count_size[SLICE_TYPE_P];
  1455.         const double i_count = h->stat.i_slice_count[SLICE_TYPE_P] * h->mb.i_mb_count / 100.0;
  1456.         x264_log( h, X264_LOG_INFO,
  1457.                   "mb P  I16..4: %4.1f%% %4.1f%% %4.1f%%  P16..4: %4.1f%% %4.1f%% %4.1f%% %4.1f%% %4.1f%%    skip:%4.1f%%n",
  1458.                   i_mb_count[I_16x16]/ i_count,
  1459.                   i_mb_count[I_8x8]  / i_count,
  1460.                   i_mb_count[I_4x4]  / i_count,
  1461.                   i_mb_size[PIXEL_16x16] / (i_count*4),
  1462.                   (i_mb_size[PIXEL_16x8] + i_mb_size[PIXEL_8x16]) / (i_count*4),
  1463.                   i_mb_size[PIXEL_8x8] / (i_count*4),
  1464.                   (i_mb_size[PIXEL_8x4] + i_mb_size[PIXEL_4x8]) / (i_count*4),
  1465.                   i_mb_size[PIXEL_4x4] / (i_count*4),
  1466.                   i_mb_count[P_SKIP] / i_count );
  1467.     }
  1468.     if( h->stat.i_slice_count[SLICE_TYPE_B] > 0 )
  1469.     {
  1470.         const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_B];
  1471.         const int64_t *i_mb_size = h->stat.i_mb_count_size[SLICE_TYPE_B];
  1472.         const double i_count = h->stat.i_slice_count[SLICE_TYPE_B] * h->mb.i_mb_count / 100.0;
  1473.         x264_log( h, X264_LOG_INFO,
  1474.                   "mb B  I16..4: %4.1f%% %4.1f%% %4.1f%%  B16..8: %4.1f%% %4.1f%% %4.1f%%  direct:%4.1f%%  skip:%4.1f%%n",
  1475.                   i_mb_count[I_16x16]  / i_count,
  1476.                   i_mb_count[I_8x8]    / i_count,
  1477.                   i_mb_count[I_4x4]    / i_count,
  1478.                   i_mb_size[PIXEL_16x16] / (i_count*4),
  1479.                   (i_mb_size[PIXEL_16x8] + i_mb_size[PIXEL_8x16]) / (i_count*4),
  1480.                   i_mb_size[PIXEL_8x8] / (i_count*4),
  1481.                   i_mb_count[B_DIRECT] / i_count,
  1482.                   i_mb_count[B_SKIP]   / i_count );
  1483.     }
  1484.     x264_ratecontrol_summary( h );
  1485.     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 )
  1486.     {
  1487.         const int i_count = h->stat.i_slice_count[SLICE_TYPE_I] +
  1488.                             h->stat.i_slice_count[SLICE_TYPE_P] +
  1489.                             h->stat.i_slice_count[SLICE_TYPE_B];
  1490.         float fps = (float) h->param.i_fps_num / h->param.i_fps_den;
  1491. #define SUM3(p) (p[SLICE_TYPE_I] + p[SLICE_TYPE_P] + p[SLICE_TYPE_B])
  1492. #define SUM3b(p,o) (p[SLICE_TYPE_I][o] + p[SLICE_TYPE_P][o] + p[SLICE_TYPE_B][o])
  1493.         float f_bitrate = fps * SUM3(h->stat.i_slice_size) / i_count / 125;
  1494.         if( h->param.analyse.b_transform_8x8 )
  1495.         {
  1496.             int64_t i_i8x8 = SUM3b( h->stat.i_mb_count, I_8x8 );
  1497.             int64_t i_intra = i_i8x8 + SUM3b( h->stat.i_mb_count, I_4x4 )
  1498.                                      + SUM3b( h->stat.i_mb_count, I_16x16 );
  1499.             x264_log( h, X264_LOG_INFO, "8x8 transform  intra:%.1f%%  inter:%.1f%%n",
  1500.                       100. * i_i8x8 / i_intra,
  1501.                       100. * h->stat.i_mb_count_8x8dct[1] / h->stat.i_mb_count_8x8dct[0] );
  1502.         }
  1503.         if( h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_AUTO
  1504.             && h->stat.i_slice_count[SLICE_TYPE_B] )
  1505.         {
  1506.             x264_log( h, X264_LOG_INFO, "direct mvs  spatial:%.1f%%  temporal:%.1f%%n",
  1507.                       h->stat.i_direct_frames[1] * 100. / h->stat.i_slice_count[SLICE_TYPE_B],
  1508.                       h->stat.i_direct_frames[0] * 100. / h->stat.i_slice_count[SLICE_TYPE_B] );
  1509.         }
  1510.         if( h->param.i_frame_reference > 1 )
  1511.         {
  1512.             int i_slice;
  1513.             for( i_slice = 0; i_slice < 2; i_slice++ )
  1514.             {
  1515.                 char buf[200];
  1516.                 char *p = buf;
  1517.                 int64_t i_den = 0;
  1518.                 int i_max = 0;
  1519.                 for( i = 0; i < h->param.i_frame_reference; i++ )
  1520.                     if( h->stat.i_mb_count_ref[i_slice][i] )
  1521.                     {
  1522.                         i_den += h->stat.i_mb_count_ref[i_slice][i];
  1523.                         i_max = i;
  1524.                     }
  1525.                 if( i_max == 0 )
  1526.                     continue;
  1527.                 for( i = 0; i <= i_max; i++ )
  1528.                     p += sprintf( p, " %4.1f%%", 100. * h->stat.i_mb_count_ref[i_slice][i] / i_den );
  1529.                 x264_log( h, X264_LOG_INFO, "ref %c %sn", i_slice==SLICE_TYPE_P ? 'P' : 'B', buf );
  1530.             }
  1531.         }
  1532.         if( h->param.analyse.b_psnr )
  1533.             x264_log( h, X264_LOG_INFO,
  1534.                       "PSNR Mean Y:%6.3f U:%6.3f V:%6.3f Avg:%6.3f Global:%6.3f kb/s:%.2fn",
  1535.                       SUM3( h->stat.f_psnr_mean_y ) / i_count,
  1536.                       SUM3( h->stat.f_psnr_mean_u ) / i_count,
  1537.                       SUM3( h->stat.f_psnr_mean_v ) / i_count,
  1538.                       SUM3( h->stat.f_psnr_average ) / i_count,
  1539.                       x264_psnr( SUM3( h->stat.i_sqe_global ), i_count * i_yuv_size ),
  1540.                       f_bitrate );
  1541.         else
  1542.             x264_log( h, X264_LOG_INFO, "kb/s:%.1fn", f_bitrate );
  1543.     }
  1544.     /* frames */
  1545.     for( i = 0; i < X264_BFRAME_MAX + 3; i++ )
  1546.     {
  1547.         if( h->frames.current[i] ) x264_frame_delete( h->frames.current[i] );
  1548.         if( h->frames.next[i] )    x264_frame_delete( h->frames.next[i] );
  1549.         if( h->frames.unused[i] )  x264_frame_delete( h->frames.unused[i] );
  1550.     }
  1551.     /* ref frames */
  1552.     for( i = 0; i < h->frames.i_max_dpb; i++ )
  1553.     {
  1554.         x264_frame_delete( h->frames.reference[i] );
  1555.     }
  1556.     /* rc */
  1557.     x264_ratecontrol_delete( h );
  1558.     /* param */
  1559.     if( h->param.rc.psz_stat_out )
  1560.         free( h->param.rc.psz_stat_out );
  1561.     if( h->param.rc.psz_stat_in )
  1562.         free( h->param.rc.psz_stat_in );
  1563.     if( h->param.rc.psz_rc_eq )
  1564.         free( h->param.rc.psz_rc_eq );
  1565.     x264_macroblock_cache_end( h );
  1566.     x264_free( h->out.p_bitstream );
  1567.     for( i = 1; i < h->param.i_threads; i++ )
  1568.         x264_free( h->thread[i] );
  1569.     x264_free( h );
  1570. }