1 /*****************************************************************************
3 *****************************************************************************
4 * Copyright (C) 2003 Laurent Aimar
5 * $Id: encoder.c,v 1.1 2004/06/03 19:27:08 fenrir Exp $
7 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
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.
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.
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 *****************************************************************************/
28 #include "common/common.h"
29 #include "common/cpu.h"
33 #include "ratecontrol.h"
34 #include "macroblock.h"
37 #include "common/visualize.h"
40 //#define DEBUG_MB_TYPE
41 //#define DEBUG_DUMP_FRAME
42 //#define DEBUG_BENCHMARK
44 #ifdef DEBUG_BENCHMARK
45 static int64_t i_mtime_encode_frame = 0;
46 static int64_t i_mtime_analyse = 0;
47 static int64_t i_mtime_encode = 0;
48 static int64_t i_mtime_write = 0;
49 static int64_t i_mtime_filter = 0;
50 #define TIMER_START( d ) \
52 int64_t d##start = x264_mdate();
54 #define TIMER_STOP( d ) \
55 d += x264_mdate() - d##start;\
58 #define TIMER_START( d )
59 #define TIMER_STOP( d )
62 #define NALU_OVERHEAD 5 // startcode + NAL type costs 5 bytes per frame
64 /****************************************************************************
66 ******************************* x264 libs **********************************
68 ****************************************************************************/
69 static float x264_psnr( int64_t i_sqe, int64_t i_size )
71 double f_mse = (double)i_sqe / ((double)65025.0 * (double)i_size);
72 if( f_mse <= 0.0000000001 ) /* Max 100dB */
75 return (float)(-10.0 * log( f_mse ) / log( 10.0 ));
78 #ifdef DEBUG_DUMP_FRAME
79 static void x264_frame_dump( x264_t *h, x264_frame_t *fr, char *name )
81 FILE *f = fopen( name, "r+b" );
86 /* Write the frame in display order */
87 fseek( f, fr->i_frame * h->param.i_height * h->param.i_width * 3 / 2, SEEK_SET );
89 for( i = 0; i < fr->i_plane; i++ )
91 for( y = 0; y < h->param.i_height / ( i == 0 ? 1 : 2 ); y++ )
93 fwrite( &fr->plane[i][y*fr->i_stride[i]], 1, h->param.i_width / ( i == 0 ? 1 : 2 ), f );
101 /* Fill "default" values */
102 static void x264_slice_header_init( x264_t *h, x264_slice_header_t *sh,
103 x264_sps_t *sps, x264_pps_t *pps,
104 int i_type, int i_idr_pic_id, int i_frame, int i_qp )
106 x264_param_t *param = &h->param;
109 /* First we fill all field */
115 sh->i_last_mb = h->sps->i_mb_width * h->sps->i_mb_height;
116 sh->i_pps_id = pps->i_id;
118 sh->i_frame_num = i_frame;
120 sh->b_field_pic = 0; /* Not field support for now */
121 sh->b_bottom_field = 1; /* not yet used */
123 sh->i_idr_pic_id = i_idr_pic_id;
125 /* poc stuff, fixed later */
127 sh->i_delta_poc_bottom = 0;
128 sh->i_delta_poc[0] = 0;
129 sh->i_delta_poc[1] = 0;
131 sh->i_redundant_pic_cnt = 0;
133 if( !h->mb.b_direct_auto_read )
135 if( h->mb.b_direct_auto_write )
136 sh->b_direct_spatial_mv_pred = ( h->stat.i_direct_score[1] > h->stat.i_direct_score[0] );
138 sh->b_direct_spatial_mv_pred = ( param->analyse.i_direct_mv_pred == X264_DIRECT_PRED_SPATIAL );
140 /* else b_direct_spatial_mv_pred was read from the 2pass statsfile */
142 sh->b_num_ref_idx_override = 0;
143 sh->i_num_ref_idx_l0_active = 1;
144 sh->i_num_ref_idx_l1_active = 1;
146 sh->b_ref_pic_list_reordering_l0 = h->b_ref_reorder[0];
147 sh->b_ref_pic_list_reordering_l1 = h->b_ref_reorder[1];
149 /* If the ref list isn't in the default order, construct reordering header */
150 /* List1 reordering isn't needed yet */
151 if( sh->b_ref_pic_list_reordering_l0 )
153 int pred_frame_num = i_frame;
154 for( i = 0; i < h->i_ref0; i++ )
156 int diff = h->fref0[i]->i_frame_num - pred_frame_num;
158 x264_log( h, X264_LOG_ERROR, "diff frame num == 0\n" );
159 sh->ref_pic_list_order[0][i].idc = ( diff > 0 );
160 sh->ref_pic_list_order[0][i].arg = abs( diff ) - 1;
161 pred_frame_num = h->fref0[i]->i_frame_num;
165 sh->i_cabac_init_idc = param->i_cabac_init_idc;
168 sh->i_qp_delta = i_qp - pps->i_pic_init_qp;
169 sh->b_sp_for_swidth = 0;
172 /* If effective qp <= 15, deblocking would have no effect anyway */
173 if( param->b_deblocking_filter
174 && ( h->mb.b_variable_qp
175 || 15 < i_qp + 2 * X264_MAX(param->i_deblocking_filter_alphac0, param->i_deblocking_filter_beta) ) )
177 sh->i_disable_deblocking_filter_idc = 0;
181 sh->i_disable_deblocking_filter_idc = 1;
183 sh->i_alpha_c0_offset = param->i_deblocking_filter_alphac0 << 1;
184 sh->i_beta_offset = param->i_deblocking_filter_beta << 1;
187 static void x264_slice_header_write( bs_t *s, x264_slice_header_t *sh, int i_nal_ref_idc )
191 bs_write_ue( s, sh->i_first_mb );
192 bs_write_ue( s, sh->i_type + 5 ); /* same type things */
193 bs_write_ue( s, sh->i_pps_id );
194 bs_write( s, sh->sps->i_log2_max_frame_num, sh->i_frame_num );
196 if( sh->i_idr_pic_id >= 0 ) /* NAL IDR */
198 bs_write_ue( s, sh->i_idr_pic_id );
201 if( sh->sps->i_poc_type == 0 )
203 bs_write( s, sh->sps->i_log2_max_poc_lsb, sh->i_poc_lsb );
204 if( sh->pps->b_pic_order && !sh->b_field_pic )
206 bs_write_se( s, sh->i_delta_poc_bottom );
209 else if( sh->sps->i_poc_type == 1 && !sh->sps->b_delta_pic_order_always_zero )
211 bs_write_se( s, sh->i_delta_poc[0] );
212 if( sh->pps->b_pic_order && !sh->b_field_pic )
214 bs_write_se( s, sh->i_delta_poc[1] );
218 if( sh->pps->b_redundant_pic_cnt )
220 bs_write_ue( s, sh->i_redundant_pic_cnt );
223 if( sh->i_type == SLICE_TYPE_B )
225 bs_write1( s, sh->b_direct_spatial_mv_pred );
227 if( sh->i_type == SLICE_TYPE_P || sh->i_type == SLICE_TYPE_SP || sh->i_type == SLICE_TYPE_B )
229 bs_write1( s, sh->b_num_ref_idx_override );
230 if( sh->b_num_ref_idx_override )
232 bs_write_ue( s, sh->i_num_ref_idx_l0_active - 1 );
233 if( sh->i_type == SLICE_TYPE_B )
235 bs_write_ue( s, sh->i_num_ref_idx_l1_active - 1 );
240 /* ref pic list reordering */
241 if( sh->i_type != SLICE_TYPE_I )
243 bs_write1( s, sh->b_ref_pic_list_reordering_l0 );
244 if( sh->b_ref_pic_list_reordering_l0 )
246 for( i = 0; i < sh->i_num_ref_idx_l0_active; i++ )
248 bs_write_ue( s, sh->ref_pic_list_order[0][i].idc );
249 bs_write_ue( s, sh->ref_pic_list_order[0][i].arg );
255 if( sh->i_type == SLICE_TYPE_B )
257 bs_write1( s, sh->b_ref_pic_list_reordering_l1 );
258 if( sh->b_ref_pic_list_reordering_l1 )
260 for( i = 0; i < sh->i_num_ref_idx_l1_active; i++ )
262 bs_write_ue( s, sh->ref_pic_list_order[1][i].idc );
263 bs_write_ue( s, sh->ref_pic_list_order[1][i].arg );
269 if( ( sh->pps->b_weighted_pred && ( sh->i_type == SLICE_TYPE_P || sh->i_type == SLICE_TYPE_SP ) ) ||
270 ( sh->pps->b_weighted_bipred == 1 && sh->i_type == SLICE_TYPE_B ) )
275 if( i_nal_ref_idc != 0 )
277 if( sh->i_idr_pic_id >= 0 )
279 bs_write1( s, 0 ); /* no output of prior pics flag */
280 bs_write1( s, 0 ); /* long term reference flag */
284 bs_write1( s, 0 ); /* adaptive_ref_pic_marking_mode_flag */
288 if( sh->pps->b_cabac && sh->i_type != SLICE_TYPE_I )
290 bs_write_ue( s, sh->i_cabac_init_idc );
292 bs_write_se( s, sh->i_qp_delta ); /* slice qp delta */
294 if( sh->pps->b_deblocking_filter_control )
296 bs_write_ue( s, sh->i_disable_deblocking_filter_idc );
297 if( sh->i_disable_deblocking_filter_idc != 1 )
299 bs_write_se( s, sh->i_alpha_c0_offset >> 1 );
300 bs_write_se( s, sh->i_beta_offset >> 1 );
305 /****************************************************************************
307 ****************************************************************************
308 ****************************** External API*********************************
309 ****************************************************************************
311 ****************************************************************************/
313 static int x264_validate_parameters( x264_t *h )
315 if( h->param.i_width <= 0 || h->param.i_height <= 0 )
317 x264_log( h, X264_LOG_ERROR, "invalid width x height (%dx%d)\n",
318 h->param.i_width, h->param.i_height );
322 if( h->param.i_width % 2 || h->param.i_height % 2 )
324 x264_log( h, X264_LOG_ERROR, "width or height not divisible by 2 (%dx%d)\n",
325 h->param.i_width, h->param.i_height );
328 if( h->param.i_csp != X264_CSP_I420 )
330 x264_log( h, X264_LOG_ERROR, "invalid CSP (only I420 supported)\n" );
334 h->param.i_threads = x264_clip3( h->param.i_threads, 1, X264_SLICE_MAX );
335 h->param.i_threads = X264_MIN( h->param.i_threads, (h->param.i_height + 15) / 16 );
337 if( h->param.i_threads > 1 )
339 x264_log( h, X264_LOG_WARNING, "not compiled with pthread support!\n");
340 x264_log( h, X264_LOG_WARNING, "multislicing anyway, but you won't see any speed gain.\n" );
344 if( h->param.rc.i_rc_method < 0 || h->param.rc.i_rc_method > 2 )
346 x264_log( h, X264_LOG_ERROR, "invalid RC method\n" );
349 h->param.rc.i_rf_constant = x264_clip3( h->param.rc.i_rf_constant, 0, 51 );
350 h->param.rc.i_qp_constant = x264_clip3( h->param.rc.i_qp_constant, 0, 51 );
351 if( h->param.rc.i_rc_method == X264_RC_CRF )
352 h->param.rc.i_qp_constant = h->param.rc.i_rf_constant;
353 if( (h->param.rc.i_rc_method == X264_RC_CQP || h->param.rc.i_rc_method == X264_RC_CRF)
354 && h->param.rc.i_qp_constant == 0 )
356 h->mb.b_lossless = 1;
357 h->param.i_cqm_preset = X264_CQM_FLAT;
358 h->param.psz_cqm_file = NULL;
359 h->param.rc.i_rc_method = X264_RC_CQP;
360 h->param.rc.f_ip_factor = 1;
361 h->param.rc.f_pb_factor = 1;
362 h->param.analyse.b_transform_8x8 = 0;
363 h->param.analyse.b_psnr = 0;
364 h->param.analyse.i_chroma_qp_offset = 0;
365 h->param.analyse.i_trellis = 0;
366 h->param.analyse.b_fast_pskip = 0;
367 h->param.analyse.i_noise_reduction = 0;
368 h->param.analyse.i_subpel_refine = x264_clip3( h->param.analyse.i_subpel_refine, 1, 6 );
371 if( ( h->param.i_width % 16 || h->param.i_height % 16 ) && !h->mb.b_lossless )
373 x264_log( h, X264_LOG_WARNING,
374 "width or height not divisible by 16 (%dx%d), compression will suffer.\n",
375 h->param.i_width, h->param.i_height );
378 h->param.i_frame_reference = x264_clip3( h->param.i_frame_reference, 1, 16 );
379 if( h->param.i_keyint_max <= 0 )
380 h->param.i_keyint_max = 1;
381 h->param.i_keyint_min = x264_clip3( h->param.i_keyint_min, 1, h->param.i_keyint_max/2+1 );
383 h->param.i_bframe = x264_clip3( h->param.i_bframe, 0, X264_BFRAME_MAX );
384 h->param.i_bframe_bias = x264_clip3( h->param.i_bframe_bias, -90, 100 );
385 h->param.b_bframe_pyramid = h->param.b_bframe_pyramid && h->param.i_bframe > 1;
386 h->param.b_bframe_adaptive = h->param.b_bframe_adaptive && h->param.i_bframe > 0;
387 h->param.analyse.b_weighted_bipred = h->param.analyse.b_weighted_bipred && h->param.i_bframe > 0;
388 h->mb.b_direct_auto_write = h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_AUTO
390 && ( h->param.rc.b_stat_write || !h->param.rc.b_stat_read );
392 h->param.i_deblocking_filter_alphac0 = x264_clip3( h->param.i_deblocking_filter_alphac0, -6, 6 );
393 h->param.i_deblocking_filter_beta = x264_clip3( h->param.i_deblocking_filter_beta, -6, 6 );
395 h->param.i_cabac_init_idc = x264_clip3( h->param.i_cabac_init_idc, 0, 2 );
397 if( h->param.i_cqm_preset < X264_CQM_FLAT || h->param.i_cqm_preset > X264_CQM_CUSTOM )
398 h->param.i_cqm_preset = X264_CQM_FLAT;
400 if( h->param.analyse.i_me_method < X264_ME_DIA ||
401 h->param.analyse.i_me_method > X264_ME_ESA )
402 h->param.analyse.i_me_method = X264_ME_HEX;
403 if( h->param.analyse.i_me_range < 4 )
404 h->param.analyse.i_me_range = 4;
405 if( h->param.analyse.i_me_range > 16 && h->param.analyse.i_me_method <= X264_ME_HEX )
406 h->param.analyse.i_me_range = 16;
407 h->param.analyse.i_subpel_refine = x264_clip3( h->param.analyse.i_subpel_refine, 1, 7 );
408 h->param.analyse.b_bframe_rdo = h->param.analyse.b_bframe_rdo && h->param.analyse.i_subpel_refine >= 6;
409 h->param.analyse.b_mixed_references = h->param.analyse.b_mixed_references && h->param.i_frame_reference > 1;
410 h->param.analyse.inter &= X264_ANALYSE_PSUB16x16|X264_ANALYSE_PSUB8x8|X264_ANALYSE_BSUB16x16|
411 X264_ANALYSE_I4x4|X264_ANALYSE_I8x8;
412 h->param.analyse.intra &= X264_ANALYSE_I4x4|X264_ANALYSE_I8x8;
413 if( !(h->param.analyse.inter & X264_ANALYSE_PSUB16x16) )
414 h->param.analyse.inter &= ~X264_ANALYSE_PSUB8x8;
415 if( !h->param.analyse.b_transform_8x8 )
417 h->param.analyse.inter &= ~X264_ANALYSE_I8x8;
418 h->param.analyse.intra &= ~X264_ANALYSE_I8x8;
420 h->param.analyse.i_chroma_qp_offset = x264_clip3(h->param.analyse.i_chroma_qp_offset, -12, 12);
421 if( !h->param.b_cabac )
422 h->param.analyse.i_trellis = 0;
423 h->param.analyse.i_trellis = x264_clip3( h->param.analyse.i_trellis, 0, 2 );
424 h->param.analyse.i_noise_reduction = x264_clip3( h->param.analyse.i_noise_reduction, 0, 1<<16 );
427 const x264_level_t *l = x264_levels;
428 while( l->level_idc != 0 && l->level_idc != h->param.i_level_idc )
430 if( l->level_idc == 0 )
432 x264_log( h, X264_LOG_ERROR, "invalid level_idc: %d\n", h->param.i_level_idc );
435 if( h->param.analyse.i_mv_range <= 0 )
436 h->param.analyse.i_mv_range = l->mv_range;
438 h->param.analyse.i_mv_range = x264_clip3(h->param.analyse.i_mv_range, 32, 2048);
441 if( h->param.rc.f_qblur < 0 )
442 h->param.rc.f_qblur = 0;
443 if( h->param.rc.f_complexity_blur < 0 )
444 h->param.rc.f_complexity_blur = 0;
446 h->param.i_sps_id &= 31;
448 /* ensure the booleans are 0 or 1 so they can be used in math */
449 #define BOOLIFY(x) h->param.x = !!h->param.x
451 BOOLIFY( b_deblocking_filter );
452 BOOLIFY( analyse.b_transform_8x8 );
453 BOOLIFY( analyse.b_bidir_me );
454 BOOLIFY( analyse.b_chroma_me );
455 BOOLIFY( analyse.b_fast_pskip );
456 BOOLIFY( rc.b_stat_write );
457 BOOLIFY( rc.b_stat_read );
463 /****************************************************************************
465 ****************************************************************************/
466 x264_t *x264_encoder_open ( x264_param_t *param )
468 x264_t *h = x264_malloc( sizeof( x264_t ) );
471 memset( h, 0, sizeof( x264_t ) );
473 /* Create a copy of param */
474 memcpy( &h->param, param, sizeof( x264_param_t ) );
476 if( x264_validate_parameters( h ) < 0 )
482 if( h->param.psz_cqm_file )
483 if( x264_cqm_parse_file( h, h->param.psz_cqm_file ) < 0 )
489 if( h->param.rc.psz_stat_out )
490 h->param.rc.psz_stat_out = strdup( h->param.rc.psz_stat_out );
491 if( h->param.rc.psz_stat_in )
492 h->param.rc.psz_stat_in = strdup( h->param.rc.psz_stat_in );
493 if( h->param.rc.psz_rc_eq )
494 h->param.rc.psz_rc_eq = strdup( h->param.rc.psz_rc_eq );
497 if( h->param.vui.i_sar_width > 0 && h->param.vui.i_sar_height > 0 )
499 int i_w = param->vui.i_sar_width;
500 int i_h = param->vui.i_sar_height;
502 x264_reduce_fraction( &i_w, &i_h );
504 while( i_w > 65535 || i_h > 65535 )
510 h->param.vui.i_sar_width = 0;
511 h->param.vui.i_sar_height = 0;
512 if( i_w == 0 || i_h == 0 )
514 x264_log( h, X264_LOG_WARNING, "cannot create valid sample aspect ratio\n" );
518 x264_log( h, X264_LOG_INFO, "using SAR=%d/%d\n", i_w, i_h );
519 h->param.vui.i_sar_width = i_w;
520 h->param.vui.i_sar_height = i_h;
524 x264_reduce_fraction( &h->param.i_fps_num, &h->param.i_fps_den );
528 h->out.i_bitstream = X264_MAX( 1000000, h->param.i_width * h->param.i_height * 1.7
529 * ( h->param.rc.i_rc_method == X264_RC_ABR ? pow( 0.5, h->param.rc.i_qp_min )
530 : pow( 0.5, h->param.rc.i_qp_constant ) * X264_MAX( 1, h->param.rc.f_ip_factor )));
531 h->out.p_bitstream = x264_malloc( h->out.i_bitstream );
537 h->sps = &h->sps_array[0];
538 x264_sps_init( h->sps, h->param.i_sps_id, &h->param );
540 h->pps = &h->pps_array[0];
541 x264_pps_init( h->pps, h->param.i_sps_id, &h->param, h->sps);
543 x264_validate_levels( h );
547 h->mb.i_mb_count = h->sps->i_mb_width * h->sps->i_mb_height;
550 h->frames.i_delay = h->param.i_bframe;
551 h->frames.i_max_ref0 = h->param.i_frame_reference;
552 h->frames.i_max_ref1 = h->sps->vui.i_num_reorder_frames;
553 h->frames.i_max_dpb = h->sps->vui.i_max_dec_frame_buffering + 1;
554 h->frames.b_have_lowres = !h->param.rc.b_stat_read
555 && ( h->param.rc.i_rc_method == X264_RC_ABR
556 || h->param.rc.i_rc_method == X264_RC_CRF
557 || h->param.b_bframe_adaptive );
559 for( i = 0; i < X264_BFRAME_MAX + 3; i++ )
561 h->frames.current[i] = NULL;
562 h->frames.next[i] = NULL;
563 h->frames.unused[i] = NULL;
565 for( i = 0; i < 1 + h->frames.i_delay; i++ )
567 h->frames.unused[i] = x264_frame_new( h );
568 if( !h->frames.unused[i] )
571 for( i = 0; i < h->frames.i_max_dpb; i++ )
573 h->frames.reference[i] = x264_frame_new( h );
574 if( !h->frames.reference[i] )
577 h->frames.reference[h->frames.i_max_dpb] = NULL;
578 h->frames.i_last_idr = - h->param.i_keyint_max;
579 h->frames.i_input = 0;
580 h->frames.last_nonb = NULL;
585 h->fdec = h->frames.reference[0];
587 if( x264_macroblock_cache_init( h ) < 0 )
591 /* init CPU functions */
592 x264_predict_16x16_init( h->param.cpu, h->predict_16x16 );
593 x264_predict_8x8c_init( h->param.cpu, h->predict_8x8c );
594 x264_predict_8x8_init( h->param.cpu, h->predict_8x8 );
595 x264_predict_4x4_init( h->param.cpu, h->predict_4x4 );
597 x264_pixel_init( h->param.cpu, &h->pixf );
598 x264_dct_init( h->param.cpu, &h->dctf );
599 x264_mc_init( h->param.cpu, &h->mc );
600 x264_csp_init( h->param.cpu, h->param.i_csp, &h->csp );
601 x264_quant_init( h, h->param.cpu, &h->quantf );
602 x264_deblock_init( h->param.cpu, &h->loopf );
604 memcpy( h->pixf.mbcmp,
605 ( h->mb.b_lossless || h->param.analyse.i_subpel_refine <= 1 ) ? h->pixf.sad : h->pixf.satd,
606 sizeof(h->pixf.mbcmp) );
609 if( x264_ratecontrol_new( h ) < 0 )
612 x264_log( h, X264_LOG_INFO, "using cpu capabilities %s%s%s%s%s%s\n",
613 param->cpu&X264_CPU_MMX ? "MMX " : "",
614 param->cpu&X264_CPU_MMXEXT ? "MMXEXT " : "",
615 param->cpu&X264_CPU_SSE ? "SSE " : "",
616 param->cpu&X264_CPU_SSE2 ? "SSE2 " : "",
617 param->cpu&X264_CPU_3DNOW ? "3DNow! " : "",
618 param->cpu&X264_CPU_ALTIVEC ? "Altivec " : "" );
622 for( i = 1; i < param->i_threads; i++ )
623 h->thread[i] = x264_malloc( sizeof(x264_t) );
625 #ifdef DEBUG_DUMP_FRAME
627 /* create or truncate the reconstructed video file */
628 FILE *f = fopen( "fdec.yuv", "w" );
633 x264_log( h, X264_LOG_ERROR, "can't write to fdec.yuv\n" );
643 /****************************************************************************
644 * x264_encoder_reconfig:
645 ****************************************************************************/
646 int x264_encoder_reconfig( x264_t *h, x264_param_t *param )
648 h->param.i_bframe_bias = param->i_bframe_bias;
649 h->param.i_deblocking_filter_alphac0 = param->i_deblocking_filter_alphac0;
650 h->param.i_deblocking_filter_beta = param->i_deblocking_filter_beta;
651 h->param.analyse.i_me_method = param->analyse.i_me_method;
652 h->param.analyse.i_me_range = param->analyse.i_me_range;
653 h->param.analyse.i_subpel_refine = param->analyse.i_subpel_refine;
654 h->param.analyse.i_trellis = param->analyse.i_trellis;
655 h->param.analyse.intra = param->analyse.intra;
656 h->param.analyse.inter = param->analyse.inter;
658 memcpy( h->pixf.mbcmp,
659 ( h->mb.b_lossless || h->param.analyse.i_subpel_refine <= 1 ) ? h->pixf.sad : h->pixf.satd,
660 sizeof(h->pixf.mbcmp) );
662 return x264_validate_parameters( h );
666 static void x264_nal_start( x264_t *h, int i_type, int i_ref_idc )
668 x264_nal_t *nal = &h->out.nal[h->out.i_nal];
670 nal->i_ref_idc = i_ref_idc;
671 nal->i_type = i_type;
673 bs_align_0( &h->out.bs ); /* not needed */
676 nal->p_payload= &h->out.p_bitstream[bs_pos( &h->out.bs) / 8];
678 static void x264_nal_end( x264_t *h )
680 x264_nal_t *nal = &h->out.nal[h->out.i_nal];
682 bs_align_0( &h->out.bs ); /* not needed */
684 nal->i_payload = &h->out.p_bitstream[bs_pos( &h->out.bs)/8] - nal->p_payload;
689 /****************************************************************************
690 * x264_encoder_headers:
691 ****************************************************************************/
692 int x264_encoder_headers( x264_t *h, x264_nal_t **pp_nal, int *pi_nal )
694 /* init bitstream context */
696 bs_init( &h->out.bs, h->out.p_bitstream, h->out.i_bitstream );
698 /* Put SPS and PPS */
699 if( h->i_frame == 0 )
701 /* identify ourself */
702 x264_nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
703 x264_sei_version_write( h, &h->out.bs );
706 /* generate sequence parameters */
707 x264_nal_start( h, NAL_SPS, NAL_PRIORITY_HIGHEST );
708 x264_sps_write( &h->out.bs, h->sps );
711 /* generate picture parameters */
712 x264_nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
713 x264_pps_write( &h->out.bs, h->pps );
717 *pi_nal = h->out.i_nal;
718 *pp_nal = &h->out.nal[0];
724 static void x264_frame_put( x264_frame_t *list[X264_BFRAME_MAX], x264_frame_t *frame )
727 while( list[i] ) i++;
731 static void x264_frame_push( x264_frame_t *list[X264_BFRAME_MAX], x264_frame_t *frame )
734 while( list[i] ) i++;
740 static x264_frame_t *x264_frame_get( x264_frame_t *list[X264_BFRAME_MAX+1] )
742 x264_frame_t *frame = list[0];
744 for( i = 0; list[i]; i++ )
749 static void x264_frame_sort( x264_frame_t *list[X264_BFRAME_MAX+1], int b_dts )
754 for( i = 0; list[i+1]; i++ )
756 int dtype = list[i]->i_type - list[i+1]->i_type;
757 int dtime = list[i]->i_frame - list[i+1]->i_frame;
758 int swap = b_dts ? dtype > 0 || ( dtype == 0 && dtime > 0 )
762 XCHG( x264_frame_t*, list[i], list[i+1] );
768 #define x264_frame_sort_dts(list) x264_frame_sort(list, 1)
769 #define x264_frame_sort_pts(list) x264_frame_sort(list, 0)
771 static inline void x264_reference_build_list( x264_t *h, int i_poc, int i_slice_type )
776 /* build ref list 0/1 */
779 for( i = 1; i < h->frames.i_max_dpb; i++ )
781 if( h->frames.reference[i]->i_poc >= 0 )
783 if( h->frames.reference[i]->i_poc < i_poc )
785 h->fref0[h->i_ref0++] = h->frames.reference[i];
787 else if( h->frames.reference[i]->i_poc > i_poc )
789 h->fref1[h->i_ref1++] = h->frames.reference[i];
794 /* Order ref0 from higher to lower poc */
798 for( i = 0; i < h->i_ref0 - 1; i++ )
800 if( h->fref0[i]->i_poc < h->fref0[i+1]->i_poc )
802 XCHG( x264_frame_t*, h->fref0[i], h->fref0[i+1] );
808 /* Order ref1 from lower to higher poc (bubble sort) for B-frame */
812 for( i = 0; i < h->i_ref1 - 1; i++ )
814 if( h->fref1[i]->i_poc > h->fref1[i+1]->i_poc )
816 XCHG( x264_frame_t*, h->fref1[i], h->fref1[i+1] );
823 /* In the standard, a P-frame's ref list is sorted by frame_num.
824 * We use POC, but check whether explicit reordering is needed */
825 h->b_ref_reorder[0] =
826 h->b_ref_reorder[1] = 0;
827 if( i_slice_type == SLICE_TYPE_P )
829 for( i = 0; i < h->i_ref0 - 1; i++ )
830 if( h->fref0[i]->i_frame_num < h->fref0[i+1]->i_frame_num )
832 h->b_ref_reorder[0] = 1;
837 h->i_ref1 = X264_MIN( h->i_ref1, h->frames.i_max_ref1 );
838 h->i_ref0 = X264_MIN( h->i_ref0, h->frames.i_max_ref0 );
839 h->i_ref0 = X264_MIN( h->i_ref0, 16 - h->i_ref1 );
842 static inline void x264_fdec_deblock( x264_t *h )
844 /* apply deblocking filter to the current decoded picture */
845 if( !h->sh.i_disable_deblocking_filter_idc )
847 TIMER_START( i_mtime_filter );
848 x264_frame_deblocking_filter( h, h->sh.i_type );
849 TIMER_STOP( i_mtime_filter );
853 static inline void x264_reference_update( x264_t *h )
857 x264_fdec_deblock( h );
860 x264_frame_expand_border( h->fdec );
862 /* create filtered images */
863 x264_frame_filter( h->param.cpu, h->fdec );
865 /* expand border of filtered images */
866 x264_frame_expand_border_filtered( h->fdec );
868 /* move lowres copy of the image to the ref frame */
869 for( i = 0; i < 4; i++)
870 XCHG( uint8_t*, h->fdec->lowres[i], h->fenc->lowres[i] );
872 /* adaptive B decision needs a pointer, since it can't use the ref lists */
873 if( h->sh.i_type != SLICE_TYPE_B )
874 h->frames.last_nonb = h->fdec;
876 /* move frame in the buffer */
877 h->fdec = h->frames.reference[h->frames.i_max_dpb-1];
878 for( i = h->frames.i_max_dpb-1; i > 0; i-- )
880 h->frames.reference[i] = h->frames.reference[i-1];
882 h->frames.reference[0] = h->fdec;
885 static inline void x264_reference_reset( x264_t *h )
889 /* reset ref pictures */
890 for( i = 1; i < h->frames.i_max_dpb; i++ )
892 h->frames.reference[i]->i_poc = -1;
894 h->frames.reference[0]->i_poc = 0;
897 static inline void x264_slice_init( x264_t *h, int i_nal_type, int i_slice_type, int i_global_qp )
899 /* ------------------------ Create slice header ----------------------- */
900 if( i_nal_type == NAL_SLICE_IDR )
902 x264_slice_header_init( h, &h->sh, h->sps, h->pps, i_slice_type, h->i_idr_pic_id, h->i_frame_num, i_global_qp );
905 h->i_idr_pic_id = ( h->i_idr_pic_id + 1 ) % 65536;
909 x264_slice_header_init( h, &h->sh, h->sps, h->pps, i_slice_type, -1, h->i_frame_num, i_global_qp );
911 /* always set the real higher num of ref frame used */
912 h->sh.b_num_ref_idx_override = 1;
913 h->sh.i_num_ref_idx_l0_active = h->i_ref0 <= 0 ? 1 : h->i_ref0;
914 h->sh.i_num_ref_idx_l1_active = h->i_ref1 <= 0 ? 1 : h->i_ref1;
917 h->fdec->i_frame_num = h->sh.i_frame_num;
919 if( h->sps->i_poc_type == 0 )
921 h->sh.i_poc_lsb = h->fdec->i_poc & ( (1 << h->sps->i_log2_max_poc_lsb) - 1 );
922 h->sh.i_delta_poc_bottom = 0; /* XXX won't work for field */
924 else if( h->sps->i_poc_type == 1 )
926 /* FIXME TODO FIXME */
930 /* Nothing to do ? */
933 x264_macroblock_slice_init( h );
936 static int x264_slice_write( x264_t *h )
943 memset( &h->stat.frame, 0, sizeof(h->stat.frame) );
946 x264_nal_start( h, h->i_nal_type, h->i_nal_ref_idc );
949 x264_slice_header_write( &h->out.bs, &h->sh, h->i_nal_ref_idc );
950 if( h->param.b_cabac )
952 /* alignment needed */
953 bs_align_1( &h->out.bs );
956 x264_cabac_context_init( &h->cabac, h->sh.i_type, h->sh.i_qp, h->sh.i_cabac_init_idc );
957 x264_cabac_encode_init ( &h->cabac, &h->out.bs );
959 h->mb.i_last_qp = h->sh.i_qp;
960 h->mb.i_last_dqp = 0;
962 for( mb_xy = h->sh.i_first_mb, i_skip = 0; mb_xy < h->sh.i_last_mb; mb_xy++ )
964 const int i_mb_y = mb_xy / h->sps->i_mb_width;
965 const int i_mb_x = mb_xy % h->sps->i_mb_width;
967 int mb_spos = bs_pos(&h->out.bs);
970 x264_macroblock_cache_load( h, i_mb_x, i_mb_y );
972 /* analyse parameters
973 * Slice I: choose I_4x4 or I_16x16 mode
974 * Slice P: choose between using P mode or intra (4x4 or 16x16)
976 TIMER_START( i_mtime_analyse );
977 x264_macroblock_analyse( h );
978 TIMER_STOP( i_mtime_analyse );
980 /* encode this macrobock -> be carefull it can change the mb type to P_SKIP if needed */
981 TIMER_START( i_mtime_encode );
982 x264_macroblock_encode( h );
983 TIMER_STOP( i_mtime_encode );
985 TIMER_START( i_mtime_write );
986 if( h->param.b_cabac )
988 if( mb_xy > h->sh.i_first_mb )
989 x264_cabac_encode_terminal( &h->cabac, 0 );
991 if( IS_SKIP( h->mb.i_type ) )
992 x264_cabac_mb_skip( h, 1 );
995 if( h->sh.i_type != SLICE_TYPE_I )
996 x264_cabac_mb_skip( h, 0 );
997 x264_macroblock_write_cabac( h, &h->cabac );
1002 if( IS_SKIP( h->mb.i_type ) )
1006 if( h->sh.i_type != SLICE_TYPE_I )
1008 bs_write_ue( &h->out.bs, i_skip ); /* skip run */
1011 x264_macroblock_write_cavlc( h, &h->out.bs );
1014 TIMER_STOP( i_mtime_write );
1017 if( h->param.b_visualize )
1018 x264_visualize_mb( h );
1022 x264_macroblock_cache_save( h );
1024 /* accumulate mb stats */
1025 h->stat.frame.i_mb_count[h->mb.i_type]++;
1026 if( !IS_SKIP(h->mb.i_type) && !IS_INTRA(h->mb.i_type) && !IS_DIRECT(h->mb.i_type) )
1028 if( h->mb.i_partition != D_8x8 )
1029 h->stat.frame.i_mb_count_size[ x264_mb_partition_pixel_table[ h->mb.i_partition ] ] += 4;
1031 for( i = 0; i < 4; i++ )
1032 h->stat.frame.i_mb_count_size[ x264_mb_partition_pixel_table[ h->mb.i_sub_partition[i] ] ] ++;
1033 if( h->param.i_frame_reference > 1 )
1035 for( i = 0; i < 4; i++ )
1037 int i_ref = h->mb.cache.ref[0][ x264_scan8[4*i] ];
1039 h->stat.frame.i_mb_count_ref[i_ref] ++;
1043 if( h->mb.i_cbp_luma && !IS_INTRA(h->mb.i_type) )
1045 h->stat.frame.i_mb_count_8x8dct[0] ++;
1046 h->stat.frame.i_mb_count_8x8dct[1] += h->mb.b_transform_8x8;
1049 if( h->mb.b_variable_qp )
1050 x264_ratecontrol_mb(h, bs_pos(&h->out.bs) - mb_spos);
1053 if( h->param.b_cabac )
1056 x264_cabac_encode_terminal( &h->cabac, 1 );
1058 else if( i_skip > 0 )
1060 bs_write_ue( &h->out.bs, i_skip ); /* last skip run */
1063 if( h->param.b_cabac )
1065 x264_cabac_encode_flush( &h->cabac );
1070 /* rbsp_slice_trailing_bits */
1071 bs_rbsp_trailing( &h->out.bs );
1076 /* Compute misc bits */
1077 h->stat.frame.i_misc_bits = bs_pos( &h->out.bs )
1079 - h->stat.frame.i_itex_bits
1080 - h->stat.frame.i_ptex_bits
1081 - h->stat.frame.i_hdr_bits;
1086 static inline int x264_slices_write( x264_t *h )
1091 if( h->param.b_visualize )
1092 x264_visualize_init( h );
1095 if( h->param.i_threads == 1 )
1097 x264_ratecontrol_threads_start( h );
1098 x264_slice_write( h );
1099 i_frame_size = h->out.nal[h->out.i_nal-1].i_payload;
1103 int i_nal = h->out.i_nal;
1104 int i_bs_size = h->out.i_bitstream / h->param.i_threads;
1106 /* duplicate contexts */
1107 for( i = 0; i < h->param.i_threads; i++ )
1109 x264_t *t = h->thread[i];
1112 memcpy( t, h, sizeof(x264_t) );
1113 t->out.p_bitstream += i*i_bs_size;
1114 bs_init( &t->out.bs, t->out.p_bitstream, i_bs_size );
1115 t->i_thread_num = i;
1117 t->sh.i_first_mb = (i * h->sps->i_mb_height / h->param.i_threads) * h->sps->i_mb_width;
1118 t->sh.i_last_mb = ((i+1) * h->sps->i_mb_height / h->param.i_threads) * h->sps->i_mb_width;
1119 t->out.i_nal = i_nal + i;
1121 x264_ratecontrol_threads_start( h );
1126 pthread_t handles[X264_SLICE_MAX];
1127 for( i = 0; i < h->param.i_threads; i++ )
1128 pthread_create( &handles[i], NULL, (void*)x264_slice_write, (void*)h->thread[i] );
1129 for( i = 0; i < h->param.i_threads; i++ )
1130 pthread_join( handles[i], NULL );
1133 for( i = 0; i < h->param.i_threads; i++ )
1134 x264_slice_write( h->thread[i] );
1137 /* merge contexts */
1138 i_frame_size = h->out.nal[i_nal].i_payload;
1139 for( i = 1; i < h->param.i_threads; i++ )
1142 x264_t *t = h->thread[i];
1143 h->out.nal[i_nal+i] = t->out.nal[i_nal+i];
1144 i_frame_size += t->out.nal[i_nal+i].i_payload;
1145 // all entries in stat.frame are ints
1146 for( j = 0; j < sizeof(h->stat.frame) / sizeof(int); j++ )
1147 ((int*)&h->stat.frame)[j] += ((int*)&t->stat.frame)[j];
1149 h->out.i_nal = i_nal + h->param.i_threads;
1153 if( h->param.b_visualize )
1155 x264_visualize_show( h );
1156 x264_visualize_close( h );
1160 return i_frame_size;
1163 /****************************************************************************
1164 * x264_encoder_encode:
1165 * XXX: i_poc : is the poc of the current given picture
1166 * i_frame : is the number of the frame being coded
1167 * ex: type frame poc
1175 ****************************************************************************/
1176 int x264_encoder_encode( x264_t *h,
1177 x264_nal_t **pp_nal, int *pi_nal,
1178 x264_picture_t *pic_in,
1179 x264_picture_t *pic_out )
1181 x264_frame_t *frame_psnr = h->fdec; /* just to keep the current decoded frame for psnr calculation */
1191 char psz_message[80];
1198 /* ------------------- Setup new frame from picture -------------------- */
1199 TIMER_START( i_mtime_encode_frame );
1200 if( pic_in != NULL )
1202 /* 1: Copy the picture to a frame and move it to a buffer */
1203 x264_frame_t *fenc = x264_frame_get( h->frames.unused );
1205 x264_frame_copy_picture( h, fenc, pic_in );
1207 if( h->param.i_width % 16 || h->param.i_height % 16 )
1208 x264_frame_expand_border_mod16( h, fenc );
1210 fenc->i_frame = h->frames.i_input++;
1212 x264_frame_put( h->frames.next, fenc );
1214 if( h->frames.b_have_lowres )
1215 x264_frame_init_lowres( h->param.cpu, fenc );
1217 if( h->frames.i_input <= h->frames.i_delay )
1219 /* Nothing yet to encode */
1220 /* waiting for filling bframe buffer */
1221 pic_out->i_type = X264_TYPE_AUTO;
1226 if( h->frames.current[0] == NULL )
1229 /* 2: Select frame types */
1230 if( h->frames.next[0] == NULL )
1233 x264_slicetype_decide( h );
1235 /* 3: move some B-frames and 1 non-B to encode queue */
1236 while( IS_X264_TYPE_B( h->frames.next[bframes]->i_type ) )
1238 x264_frame_put( h->frames.current, x264_frame_get( &h->frames.next[bframes] ) );
1239 /* FIXME: when max B-frames > 3, BREF may no longer be centered after GOP closing */
1240 if( h->param.b_bframe_pyramid && bframes > 1 )
1242 x264_frame_t *mid = x264_frame_get( &h->frames.next[bframes/2] );
1243 mid->i_type = X264_TYPE_BREF;
1244 x264_frame_put( h->frames.current, mid );
1248 x264_frame_put( h->frames.current, x264_frame_get( h->frames.next ) );
1250 TIMER_STOP( i_mtime_encode_frame );
1252 /* ------------------- Get frame to be encoded ------------------------- */
1253 /* 4: get picture to encode */
1254 h->fenc = x264_frame_get( h->frames.current );
1255 if( h->fenc == NULL )
1257 /* Nothing yet to encode (ex: waiting for I/P with B frames) */
1258 /* waiting for filling bframe buffer */
1259 pic_out->i_type = X264_TYPE_AUTO;
1265 if( h->fenc->i_type == X264_TYPE_IDR )
1267 h->frames.i_last_idr = h->fenc->i_frame;
1270 /* ------------------- Setup frame context ----------------------------- */
1271 /* 5: Init data dependant of frame type */
1272 TIMER_START( i_mtime_encode_frame );
1273 if( h->fenc->i_type == X264_TYPE_IDR )
1275 /* reset ref pictures */
1276 x264_reference_reset( h );
1278 i_nal_type = NAL_SLICE_IDR;
1279 i_nal_ref_idc = NAL_PRIORITY_HIGHEST;
1280 i_slice_type = SLICE_TYPE_I;
1282 else if( h->fenc->i_type == X264_TYPE_I )
1284 i_nal_type = NAL_SLICE;
1285 i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
1286 i_slice_type = SLICE_TYPE_I;
1288 else if( h->fenc->i_type == X264_TYPE_P )
1290 i_nal_type = NAL_SLICE;
1291 i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
1292 i_slice_type = SLICE_TYPE_P;
1294 else if( h->fenc->i_type == X264_TYPE_BREF )
1296 i_nal_type = NAL_SLICE;
1297 i_nal_ref_idc = NAL_PRIORITY_HIGH; /* maybe add MMCO to forget it? -> low */
1298 i_slice_type = SLICE_TYPE_B;
1302 i_nal_type = NAL_SLICE;
1303 i_nal_ref_idc = NAL_PRIORITY_DISPOSABLE;
1304 i_slice_type = SLICE_TYPE_B;
1308 h->fenc->i_poc = 2 * (h->fenc->i_frame - h->frames.i_last_idr);
1309 h->fdec->i_type = h->fenc->i_type;
1310 h->fdec->i_frame = h->fenc->i_frame;
1311 h->fenc->b_kept_as_ref =
1312 h->fdec->b_kept_as_ref = i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE;
1316 /* ------------------- Init ----------------------------- */
1317 /* build ref list 0/1 */
1318 x264_reference_build_list( h, h->fdec->i_poc, i_slice_type );
1320 /* Init the rate control */
1321 x264_ratecontrol_start( h, i_slice_type, h->fenc->i_qpplus1 );
1322 i_global_qp = x264_ratecontrol_qp( h );
1324 pic_out->i_qpplus1 =
1325 h->fdec->i_qpplus1 = i_global_qp + 1;
1327 if( i_slice_type == SLICE_TYPE_B )
1328 x264_macroblock_bipred_init( h );
1330 /* ------------------------ Create slice header ----------------------- */
1331 x264_slice_init( h, i_nal_type, i_slice_type, i_global_qp );
1333 if( h->fenc->b_kept_as_ref )
1336 /* ---------------------- Write the bitstream -------------------------- */
1337 /* Init bitstream context */
1339 bs_init( &h->out.bs, h->out.p_bitstream, h->out.i_bitstream );
1344 if(i_slice_type == SLICE_TYPE_I)
1346 else if(i_slice_type == SLICE_TYPE_P)
1348 else if(i_slice_type == SLICE_TYPE_B)
1353 x264_nal_start(h, NAL_AUD, NAL_PRIORITY_DISPOSABLE);
1354 bs_write(&h->out.bs, 3, pic_type);
1355 bs_rbsp_trailing(&h->out.bs);
1359 h->i_nal_type = i_nal_type;
1360 h->i_nal_ref_idc = i_nal_ref_idc;
1362 /* Write SPS and PPS */
1363 if( i_nal_type == NAL_SLICE_IDR && h->param.b_repeat_headers )
1365 if( h->fenc->i_frame == 0 )
1367 /* identify ourself */
1368 x264_nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
1369 x264_sei_version_write( h, &h->out.bs );
1373 /* generate sequence parameters */
1374 x264_nal_start( h, NAL_SPS, NAL_PRIORITY_HIGHEST );
1375 x264_sps_write( &h->out.bs, h->sps );
1378 /* generate picture parameters */
1379 x264_nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
1380 x264_pps_write( &h->out.bs, h->pps );
1385 i_frame_size = x264_slices_write( h );
1387 /* restore CPU state (before using float again) */
1388 x264_cpu_restore( h->param.cpu );
1390 if( i_slice_type == SLICE_TYPE_P && !h->param.rc.b_stat_read
1391 && h->param.i_scenecut_threshold >= 0 )
1393 const int *mbs = h->stat.frame.i_mb_count;
1394 int i_mb_i = mbs[I_16x16] + mbs[I_8x8] + mbs[I_4x4];
1395 int i_mb_p = mbs[P_L0] + mbs[P_8x8];
1396 int i_mb_s = mbs[P_SKIP];
1397 int i_mb = h->sps->i_mb_width * h->sps->i_mb_height;
1398 int64_t i_inter_cost = h->stat.frame.i_inter_cost;
1399 int64_t i_intra_cost = h->stat.frame.i_intra_cost;
1402 int i_gop_size = h->fenc->i_frame - h->frames.i_last_idr;
1403 float f_thresh_max = h->param.i_scenecut_threshold / 100.0;
1404 /* magic numbers pulled out of thin air */
1405 float f_thresh_min = f_thresh_max * h->param.i_keyint_min
1406 / ( h->param.i_keyint_max * 4 );
1407 if( h->param.i_keyint_min == h->param.i_keyint_max )
1408 f_thresh_min= f_thresh_max;
1410 /* macroblock_analyse() doesn't further analyse skipped mbs,
1411 * so we have to guess their cost */
1413 i_intra_cost = i_intra_cost * i_mb / (i_mb - i_mb_s);
1415 if( i_gop_size < h->param.i_keyint_min / 4 )
1416 f_bias = f_thresh_min / 4;
1417 else if( i_gop_size <= h->param.i_keyint_min )
1418 f_bias = f_thresh_min * i_gop_size / h->param.i_keyint_min;
1421 f_bias = f_thresh_min
1422 + ( f_thresh_max - f_thresh_min )
1423 * ( i_gop_size - h->param.i_keyint_min )
1424 / ( h->param.i_keyint_max - h->param.i_keyint_min );
1426 f_bias = X264_MIN( f_bias, 1.0 );
1428 /* Bad P will be reencoded as I */
1429 if( i_mb_s < i_mb &&
1430 i_inter_cost >= (1.0 - f_bias) * i_intra_cost )
1434 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",
1436 (double)i_intra_cost, (double)i_inter_cost,
1437 (double)i_inter_cost / i_intra_cost,
1439 i_mb_i, i_mb_p, i_mb_s );
1441 /* Restore frame num */
1444 for( b = 0; h->frames.current[b] && IS_X264_TYPE_B( h->frames.current[b]->i_type ); b++ );
1447 /* If using B-frames, force GOP to be closed.
1448 * Even if this frame is going to be I and not IDR, forcing a
1449 * P-frame before the scenecut will probably help compression.
1451 * We don't yet know exactly which frame is the scene cut, so
1452 * we can't assign an I-frame. Instead, change the previous
1453 * B-frame to P, and rearrange coding order. */
1455 if( h->param.b_bframe_adaptive || b > 1 )
1456 h->fenc->i_type = X264_TYPE_AUTO;
1457 x264_frame_sort_pts( h->frames.current );
1458 x264_frame_push( h->frames.next, h->fenc );
1459 h->fenc = h->frames.current[b-1];
1460 h->frames.current[b-1] = NULL;
1461 h->fenc->i_type = X264_TYPE_P;
1462 x264_frame_sort_dts( h->frames.current );
1464 /* Do IDR if needed */
1465 else if( i_gop_size >= h->param.i_keyint_min )
1472 /* Reinit field of fenc */
1473 h->fenc->i_type = X264_TYPE_IDR;
1476 /* Put enqueued frames back in the pool */
1477 while( (tmp = x264_frame_get( h->frames.current ) ) != NULL )
1478 x264_frame_put( h->frames.next, tmp );
1479 x264_frame_sort_pts( h->frames.next );
1483 h->fenc->i_type = X264_TYPE_I;
1489 /* End bitstream, set output */
1490 *pi_nal = h->out.i_nal;
1491 *pp_nal = h->out.nal;
1493 /* Set output picture properties */
1494 if( i_slice_type == SLICE_TYPE_I )
1495 pic_out->i_type = i_nal_type == NAL_SLICE_IDR ? X264_TYPE_IDR : X264_TYPE_I;
1496 else if( i_slice_type == SLICE_TYPE_P )
1497 pic_out->i_type = X264_TYPE_P;
1499 pic_out->i_type = X264_TYPE_B;
1500 pic_out->i_pts = h->fenc->i_pts;
1502 pic_out->img.i_plane = h->fdec->i_plane;
1503 for(i = 0; i < 4; i++){
1504 pic_out->img.i_stride[i] = h->fdec->i_stride[i];
1505 pic_out->img.plane[i] = h->fdec->plane[i];
1508 /* ---------------------- Update encoder state ------------------------- */
1511 x264_cpu_restore( h->param.cpu );
1512 x264_ratecontrol_end( h, i_frame_size * 8 );
1514 /* handle references */
1515 if( i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE )
1516 x264_reference_update( h );
1517 #ifdef DEBUG_DUMP_FRAME
1519 x264_fdec_deblock( h );
1521 x264_frame_put( h->frames.unused, h->fenc );
1523 /* increase frame count */
1526 /* restore CPU state (before using float again) */
1527 x264_cpu_restore( h->param.cpu );
1529 x264_noise_reduction_update( h );
1531 TIMER_STOP( i_mtime_encode_frame );
1533 /* ---------------------- Compute/Print statistics --------------------- */
1535 h->stat.i_slice_count[i_slice_type]++;
1536 h->stat.i_slice_size[i_slice_type] += i_frame_size + NALU_OVERHEAD;
1537 h->stat.i_slice_qp[i_slice_type] += i_global_qp;
1539 for( i = 0; i < 19; i++ )
1540 h->stat.i_mb_count[h->sh.i_type][i] += h->stat.frame.i_mb_count[i];
1541 for( i = 0; i < 2; i++ )
1542 h->stat.i_mb_count_8x8dct[i] += h->stat.frame.i_mb_count_8x8dct[i];
1543 if( h->sh.i_type != SLICE_TYPE_I )
1545 for( i = 0; i < 7; i++ )
1546 h->stat.i_mb_count_size[h->sh.i_type][i] += h->stat.frame.i_mb_count_size[i];
1547 for( i = 0; i < 16; i++ )
1548 h->stat.i_mb_count_ref[h->sh.i_type][i] += h->stat.frame.i_mb_count_ref[i];
1550 if( i_slice_type == SLICE_TYPE_B )
1552 h->stat.i_direct_frames[ h->sh.b_direct_spatial_mv_pred ] ++;
1553 if( h->mb.b_direct_auto_write )
1555 //FIXME somewhat arbitrary time constants
1556 if( h->stat.i_direct_score[0] + h->stat.i_direct_score[1] > h->mb.i_mb_count )
1558 for( i = 0; i < 2; i++ )
1559 h->stat.i_direct_score[i] = h->stat.i_direct_score[i] * 9/10;
1561 for( i = 0; i < 2; i++ )
1562 h->stat.i_direct_score[i] += h->stat.frame.i_direct_score[i];
1566 if( h->param.analyse.b_psnr )
1568 int64_t i_sqe_y, i_sqe_u, i_sqe_v;
1571 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 );
1572 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);
1573 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);
1574 x264_cpu_restore( h->param.cpu );
1576 h->stat.i_sqe_global[i_slice_type] += i_sqe_y + i_sqe_u + i_sqe_v;
1577 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 );
1578 h->stat.f_psnr_mean_y[i_slice_type] += x264_psnr( i_sqe_y, h->param.i_width * h->param.i_height );
1579 h->stat.f_psnr_mean_u[i_slice_type] += x264_psnr( i_sqe_u, h->param.i_width * h->param.i_height / 4 );
1580 h->stat.f_psnr_mean_v[i_slice_type] += x264_psnr( i_sqe_v, h->param.i_width * h->param.i_height / 4 );
1582 snprintf( psz_message, 80, " PSNR Y:%2.2f U:%2.2f V:%2.2f",
1583 x264_psnr( i_sqe_y, h->param.i_width * h->param.i_height ),
1584 x264_psnr( i_sqe_u, h->param.i_width * h->param.i_height / 4),
1585 x264_psnr( i_sqe_v, h->param.i_width * h->param.i_height / 4) );
1586 psz_message[79] = '\0';
1590 psz_message[0] = '\0';
1593 x264_log( h, X264_LOG_DEBUG,
1594 "frame=%4d QP=%i NAL=%d Slice:%c Poc:%-3d I:%-4d P:%-4d SKIP:%-4d size=%d bytes%s\n",
1598 i_slice_type == SLICE_TYPE_I ? 'I' : (i_slice_type == SLICE_TYPE_P ? 'P' : 'B' ),
1600 h->stat.frame.i_mb_count_i,
1601 h->stat.frame.i_mb_count_p,
1602 h->stat.frame.i_mb_count_skip,
1607 #ifdef DEBUG_MB_TYPE
1609 static const char mb_chars[] = { 'i', 'i', 'I', 'C', 'P', '8', 'S',
1610 'D', '<', 'X', 'B', 'X', '>', 'B', 'B', 'B', 'B', '8', 'S' };
1612 for( mb_xy = 0; mb_xy < h->sps->i_mb_width * h->sps->i_mb_height; mb_xy++ )
1614 if( h->mb.type[mb_xy] < 19 && h->mb.type[mb_xy] >= 0 )
1615 fprintf( stderr, "%c ", mb_chars[ h->mb.type[mb_xy] ] );
1617 fprintf( stderr, "? " );
1619 if( (mb_xy+1) % h->sps->i_mb_width == 0 )
1620 fprintf( stderr, "\n" );
1625 #ifdef DEBUG_DUMP_FRAME
1626 /* Dump reconstructed frame */
1627 x264_frame_dump( h, frame_psnr, "fdec.yuv" );
1632 /****************************************************************************
1633 * x264_encoder_close:
1634 ****************************************************************************/
1635 void x264_encoder_close ( x264_t *h )
1637 #ifdef DEBUG_BENCHMARK
1638 int64_t i_mtime_total = i_mtime_analyse + i_mtime_encode + i_mtime_write + i_mtime_filter + 1;
1640 int64_t i_yuv_size = 3 * h->param.i_width * h->param.i_height / 2;
1643 #ifdef DEBUG_BENCHMARK
1644 x264_log( h, X264_LOG_INFO,
1645 "analyse=%d(%lldms) encode=%d(%lldms) write=%d(%lldms) filter=%d(%lldms)\n",
1646 (int)(100*i_mtime_analyse/i_mtime_total), i_mtime_analyse/1000,
1647 (int)(100*i_mtime_encode/i_mtime_total), i_mtime_encode/1000,
1648 (int)(100*i_mtime_write/i_mtime_total), i_mtime_write/1000,
1649 (int)(100*i_mtime_filter/i_mtime_total), i_mtime_filter/1000 );
1652 /* Slices used and PSNR */
1653 for( i=0; i<5; i++ )
1655 static const int slice_order[] = { SLICE_TYPE_I, SLICE_TYPE_SI, SLICE_TYPE_P, SLICE_TYPE_SP, SLICE_TYPE_B };
1656 static const char *slice_name[] = { "P", "B", "I", "SP", "SI" };
1657 int i_slice = slice_order[i];
1659 if( h->stat.i_slice_count[i_slice] > 0 )
1661 const int i_count = h->stat.i_slice_count[i_slice];
1662 if( h->param.analyse.b_psnr )
1664 x264_log( h, X264_LOG_INFO,
1665 "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.2f\n",
1666 slice_name[i_slice],
1668 (double)h->stat.i_slice_qp[i_slice] / i_count,
1669 (double)h->stat.i_slice_size[i_slice] / i_count,
1670 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,
1671 h->stat.f_psnr_average[i_slice] / i_count,
1672 x264_psnr( h->stat.i_sqe_global[i_slice], i_count * i_yuv_size ) );
1676 x264_log( h, X264_LOG_INFO,
1677 "slice %s:%-5d Avg QP:%5.2f size:%6.0f\n",
1678 slice_name[i_slice],
1680 (double)h->stat.i_slice_qp[i_slice] / i_count,
1681 (double)h->stat.i_slice_size[i_slice] / i_count );
1687 if( h->stat.i_slice_count[SLICE_TYPE_I] > 0 )
1689 const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_I];
1690 const double i_count = h->stat.i_slice_count[SLICE_TYPE_I] * h->mb.i_mb_count / 100.0;
1691 x264_log( h, X264_LOG_INFO,
1692 "mb I I16..4: %4.1f%% %4.1f%% %4.1f%%\n",
1693 i_mb_count[I_16x16]/ i_count,
1694 i_mb_count[I_8x8] / i_count,
1695 i_mb_count[I_4x4] / i_count );
1697 if( h->stat.i_slice_count[SLICE_TYPE_P] > 0 )
1699 const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_P];
1700 const int64_t *i_mb_size = h->stat.i_mb_count_size[SLICE_TYPE_P];
1701 const double i_count = h->stat.i_slice_count[SLICE_TYPE_P] * h->mb.i_mb_count / 100.0;
1702 x264_log( h, X264_LOG_INFO,
1703 "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",
1704 i_mb_count[I_16x16]/ i_count,
1705 i_mb_count[I_8x8] / i_count,
1706 i_mb_count[I_4x4] / i_count,
1707 i_mb_size[PIXEL_16x16] / (i_count*4),
1708 (i_mb_size[PIXEL_16x8] + i_mb_size[PIXEL_8x16]) / (i_count*4),
1709 i_mb_size[PIXEL_8x8] / (i_count*4),
1710 (i_mb_size[PIXEL_8x4] + i_mb_size[PIXEL_4x8]) / (i_count*4),
1711 i_mb_size[PIXEL_4x4] / (i_count*4),
1712 i_mb_count[P_SKIP] / i_count );
1714 if( h->stat.i_slice_count[SLICE_TYPE_B] > 0 )
1716 const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_B];
1717 const int64_t *i_mb_size = h->stat.i_mb_count_size[SLICE_TYPE_B];
1718 const double i_count = h->stat.i_slice_count[SLICE_TYPE_B] * h->mb.i_mb_count / 100.0;
1719 x264_log( h, X264_LOG_INFO,
1720 "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",
1721 i_mb_count[I_16x16] / i_count,
1722 i_mb_count[I_8x8] / i_count,
1723 i_mb_count[I_4x4] / i_count,
1724 i_mb_size[PIXEL_16x16] / (i_count*4),
1725 (i_mb_size[PIXEL_16x8] + i_mb_size[PIXEL_8x16]) / (i_count*4),
1726 i_mb_size[PIXEL_8x8] / (i_count*4),
1727 i_mb_count[B_DIRECT] / i_count,
1728 i_mb_count[B_SKIP] / i_count );
1731 x264_ratecontrol_summary( h );
1733 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 )
1735 const int i_count = h->stat.i_slice_count[SLICE_TYPE_I] +
1736 h->stat.i_slice_count[SLICE_TYPE_P] +
1737 h->stat.i_slice_count[SLICE_TYPE_B];
1738 float fps = (float) h->param.i_fps_num / h->param.i_fps_den;
1739 #define SUM3(p) (p[SLICE_TYPE_I] + p[SLICE_TYPE_P] + p[SLICE_TYPE_B])
1740 #define SUM3b(p,o) (p[SLICE_TYPE_I][o] + p[SLICE_TYPE_P][o] + p[SLICE_TYPE_B][o])
1741 float f_bitrate = fps * SUM3(h->stat.i_slice_size) / i_count / 125;
1743 if( h->param.analyse.b_transform_8x8 )
1745 int64_t i_i8x8 = SUM3b( h->stat.i_mb_count, I_8x8 );
1746 int64_t i_intra = i_i8x8 + SUM3b( h->stat.i_mb_count, I_4x4 )
1747 + SUM3b( h->stat.i_mb_count, I_16x16 );
1748 x264_log( h, X264_LOG_INFO, "8x8 transform intra:%.1f%% inter:%.1f%%\n",
1749 100. * i_i8x8 / i_intra,
1750 100. * h->stat.i_mb_count_8x8dct[1] / h->stat.i_mb_count_8x8dct[0] );
1753 if( h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_AUTO
1754 && h->stat.i_slice_count[SLICE_TYPE_B] )
1756 x264_log( h, X264_LOG_INFO, "direct mvs spatial:%.1f%% temporal:%.1f%%\n",
1757 h->stat.i_direct_frames[1] * 100. / h->stat.i_slice_count[SLICE_TYPE_B],
1758 h->stat.i_direct_frames[0] * 100. / h->stat.i_slice_count[SLICE_TYPE_B] );
1761 if( h->param.i_frame_reference > 1 )
1764 for( i_slice = 0; i_slice < 2; i_slice++ )
1770 for( i = 0; i < h->param.i_frame_reference; i++ )
1771 if( h->stat.i_mb_count_ref[i_slice][i] )
1773 i_den += h->stat.i_mb_count_ref[i_slice][i];
1778 for( i = 0; i <= i_max; i++ )
1779 p += sprintf( p, " %4.1f%%", 100. * h->stat.i_mb_count_ref[i_slice][i] / i_den );
1780 x264_log( h, X264_LOG_INFO, "ref %c %s\n", i_slice==SLICE_TYPE_P ? 'P' : 'B', buf );
1784 if( h->param.analyse.b_psnr )
1785 x264_log( h, X264_LOG_INFO,
1786 "PSNR Mean Y:%6.3f U:%6.3f V:%6.3f Avg:%6.3f Global:%6.3f kb/s:%.2f\n",
1787 SUM3( h->stat.f_psnr_mean_y ) / i_count,
1788 SUM3( h->stat.f_psnr_mean_u ) / i_count,
1789 SUM3( h->stat.f_psnr_mean_v ) / i_count,
1790 SUM3( h->stat.f_psnr_average ) / i_count,
1791 x264_psnr( SUM3( h->stat.i_sqe_global ), i_count * i_yuv_size ),
1794 x264_log( h, X264_LOG_INFO, "kb/s:%.1f\n", f_bitrate );
1798 for( i = 0; i < X264_BFRAME_MAX + 3; i++ )
1800 if( h->frames.current[i] ) x264_frame_delete( h->frames.current[i] );
1801 if( h->frames.next[i] ) x264_frame_delete( h->frames.next[i] );
1802 if( h->frames.unused[i] ) x264_frame_delete( h->frames.unused[i] );
1805 for( i = 0; i < h->frames.i_max_dpb; i++ )
1807 x264_frame_delete( h->frames.reference[i] );
1811 x264_ratecontrol_delete( h );
1814 if( h->param.rc.psz_stat_out )
1815 free( h->param.rc.psz_stat_out );
1816 if( h->param.rc.psz_stat_in )
1817 free( h->param.rc.psz_stat_in );
1818 if( h->param.rc.psz_rc_eq )
1819 free( h->param.rc.psz_rc_eq );
1821 x264_cqm_delete( h );
1822 x264_macroblock_cache_end( h );
1823 x264_free( h->out.p_bitstream );
1824 for( i = 1; i < h->param.i_threads; i++ )
1825 x264_free( h->thread[i] );