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 *****************************************************************************/
30 #define pthread_t HANDLE
31 #define pthread_create(t,u,f,d) *(t)=CreateThread(NULL,0,f,d,0,NULL)
32 #define pthread_join(t,s) { WaitForSingleObject(t,INFINITE); \
34 #define HAVE_PTHREAD 1
36 #elif defined(SYS_BEOS)
37 #include <kernel/OS.h>
38 #define pthread_t thread_id
39 #define pthread_create(t,u,f,d) { *(t)=spawn_thread(f,"",10,d); \
40 resume_thread(*(t)); }
41 #define pthread_join(t,s) wait_for_thread(t,(long*)s)
42 #define HAVE_PTHREAD 1
48 #include "common/common.h"
49 #include "common/cpu.h"
53 #include "ratecontrol.h"
54 #include "macroblock.h"
57 #include "common/visualize.h"
60 //#define DEBUG_MB_TYPE
61 //#define DEBUG_DUMP_FRAME
62 //#define DEBUG_BENCHMARK
64 #ifdef DEBUG_BENCHMARK
65 static int64_t i_mtime_encode_frame = 0;
66 static int64_t i_mtime_analyse = 0;
67 static int64_t i_mtime_encode = 0;
68 static int64_t i_mtime_write = 0;
69 static int64_t i_mtime_filter = 0;
70 #define TIMER_START( d ) \
72 int64_t d##start = x264_mdate();
74 #define TIMER_STOP( d ) \
75 d += x264_mdate() - d##start;\
78 #define TIMER_START( d )
79 #define TIMER_STOP( d )
82 #define NALU_OVERHEAD 5 // startcode + NAL type costs 5 bytes per frame
84 /****************************************************************************
86 ******************************* x264 libs **********************************
88 ****************************************************************************/
89 static float x264_psnr( int64_t i_sqe, int64_t i_size )
91 double f_mse = (double)i_sqe / ((double)65025.0 * (double)i_size);
92 if( f_mse <= 0.0000000001 ) /* Max 100dB */
95 return (float)(-10.0 * log( f_mse ) / log( 10.0 ));
98 #ifdef DEBUG_DUMP_FRAME
99 static void x264_frame_dump( x264_t *h, x264_frame_t *fr, char *name )
101 FILE * f = fopen( name, "a" );
104 fseek( f, 0, SEEK_END );
106 for( i = 0; i < fr->i_plane; i++ )
108 for( y = 0; y < h->param.i_height / ( i == 0 ? 1 : 2 ); y++ )
110 fwrite( &fr->plane[i][y*fr->i_stride[i]], 1, h->param.i_width / ( i == 0 ? 1 : 2 ), f );
118 /* Fill "default" values */
119 static void x264_slice_header_init( x264_t *h, x264_slice_header_t *sh,
120 x264_sps_t *sps, x264_pps_t *pps,
121 int i_type, int i_idr_pic_id, int i_frame, int i_qp )
123 x264_param_t *param = &h->param;
126 /* First we fill all field */
132 sh->i_last_mb = h->sps->i_mb_width * h->sps->i_mb_height;
133 sh->i_pps_id = pps->i_id;
135 sh->i_frame_num = i_frame;
137 sh->b_field_pic = 0; /* Not field support for now */
138 sh->b_bottom_field = 1; /* not yet used */
140 sh->i_idr_pic_id = i_idr_pic_id;
142 /* poc stuff, fixed later */
144 sh->i_delta_poc_bottom = 0;
145 sh->i_delta_poc[0] = 0;
146 sh->i_delta_poc[1] = 0;
148 sh->i_redundant_pic_cnt = 0;
150 if( !h->mb.b_direct_auto_read )
152 if( h->mb.b_direct_auto_write )
153 sh->b_direct_spatial_mv_pred = ( h->stat.i_direct_score[1] > h->stat.i_direct_score[0] );
155 sh->b_direct_spatial_mv_pred = ( param->analyse.i_direct_mv_pred == X264_DIRECT_PRED_SPATIAL );
157 /* else b_direct_spatial_mv_pred was read from the 2pass statsfile */
159 sh->b_num_ref_idx_override = 0;
160 sh->i_num_ref_idx_l0_active = 1;
161 sh->i_num_ref_idx_l1_active = 1;
163 sh->b_ref_pic_list_reordering_l0 = h->b_ref_reorder[0];
164 sh->b_ref_pic_list_reordering_l1 = h->b_ref_reorder[1];
166 /* If the ref list isn't in the default order, construct reordering header */
167 /* List1 reordering isn't needed yet */
168 if( sh->b_ref_pic_list_reordering_l0 )
170 int pred_frame_num = i_frame;
171 for( i = 0; i < h->i_ref0; i++ )
173 int diff = h->fref0[i]->i_frame_num - pred_frame_num;
175 x264_log( h, X264_LOG_ERROR, "diff frame num == 0\n" );
176 sh->ref_pic_list_order[0][i].idc = ( diff > 0 );
177 sh->ref_pic_list_order[0][i].arg = abs( diff ) - 1;
178 pred_frame_num = h->fref0[i]->i_frame_num;
182 sh->i_cabac_init_idc = param->i_cabac_init_idc;
185 sh->i_qp_delta = i_qp - pps->i_pic_init_qp;
186 sh->b_sp_for_swidth = 0;
189 /* If effective qp <= 15, deblocking would have no effect anyway */
190 if( param->b_deblocking_filter
191 && ( h->mb.b_variable_qp
192 || 15 < i_qp + 2 * X264_MAX(param->i_deblocking_filter_alphac0, param->i_deblocking_filter_beta) ) )
194 sh->i_disable_deblocking_filter_idc = 0;
198 sh->i_disable_deblocking_filter_idc = 1;
200 sh->i_alpha_c0_offset = param->i_deblocking_filter_alphac0 << 1;
201 sh->i_beta_offset = param->i_deblocking_filter_beta << 1;
204 static void x264_slice_header_write( bs_t *s, x264_slice_header_t *sh, int i_nal_ref_idc )
208 bs_write_ue( s, sh->i_first_mb );
209 bs_write_ue( s, sh->i_type + 5 ); /* same type things */
210 bs_write_ue( s, sh->i_pps_id );
211 bs_write( s, sh->sps->i_log2_max_frame_num, sh->i_frame_num );
213 if( sh->i_idr_pic_id >= 0 ) /* NAL IDR */
215 bs_write_ue( s, sh->i_idr_pic_id );
218 if( sh->sps->i_poc_type == 0 )
220 bs_write( s, sh->sps->i_log2_max_poc_lsb, sh->i_poc_lsb );
221 if( sh->pps->b_pic_order && !sh->b_field_pic )
223 bs_write_se( s, sh->i_delta_poc_bottom );
226 else if( sh->sps->i_poc_type == 1 && !sh->sps->b_delta_pic_order_always_zero )
228 bs_write_se( s, sh->i_delta_poc[0] );
229 if( sh->pps->b_pic_order && !sh->b_field_pic )
231 bs_write_se( s, sh->i_delta_poc[1] );
235 if( sh->pps->b_redundant_pic_cnt )
237 bs_write_ue( s, sh->i_redundant_pic_cnt );
240 if( sh->i_type == SLICE_TYPE_B )
242 bs_write1( s, sh->b_direct_spatial_mv_pred );
244 if( sh->i_type == SLICE_TYPE_P || sh->i_type == SLICE_TYPE_SP || sh->i_type == SLICE_TYPE_B )
246 bs_write1( s, sh->b_num_ref_idx_override );
247 if( sh->b_num_ref_idx_override )
249 bs_write_ue( s, sh->i_num_ref_idx_l0_active - 1 );
250 if( sh->i_type == SLICE_TYPE_B )
252 bs_write_ue( s, sh->i_num_ref_idx_l1_active - 1 );
257 /* ref pic list reordering */
258 if( sh->i_type != SLICE_TYPE_I )
260 bs_write1( s, sh->b_ref_pic_list_reordering_l0 );
261 if( sh->b_ref_pic_list_reordering_l0 )
263 for( i = 0; i < sh->i_num_ref_idx_l0_active; i++ )
265 bs_write_ue( s, sh->ref_pic_list_order[0][i].idc );
266 bs_write_ue( s, sh->ref_pic_list_order[0][i].arg );
272 if( sh->i_type == SLICE_TYPE_B )
274 bs_write1( s, sh->b_ref_pic_list_reordering_l1 );
275 if( sh->b_ref_pic_list_reordering_l1 )
277 for( i = 0; i < sh->i_num_ref_idx_l1_active; i++ )
279 bs_write_ue( s, sh->ref_pic_list_order[1][i].idc );
280 bs_write_ue( s, sh->ref_pic_list_order[1][i].arg );
286 if( ( sh->pps->b_weighted_pred && ( sh->i_type == SLICE_TYPE_P || sh->i_type == SLICE_TYPE_SP ) ) ||
287 ( sh->pps->b_weighted_bipred == 1 && sh->i_type == SLICE_TYPE_B ) )
292 if( i_nal_ref_idc != 0 )
294 if( sh->i_idr_pic_id >= 0 )
296 bs_write1( s, 0 ); /* no output of prior pics flag */
297 bs_write1( s, 0 ); /* long term reference flag */
301 bs_write1( s, 0 ); /* adaptive_ref_pic_marking_mode_flag */
305 if( sh->pps->b_cabac && sh->i_type != SLICE_TYPE_I )
307 bs_write_ue( s, sh->i_cabac_init_idc );
309 bs_write_se( s, sh->i_qp_delta ); /* slice qp delta */
311 if( sh->pps->b_deblocking_filter_control )
313 bs_write_ue( s, sh->i_disable_deblocking_filter_idc );
314 if( sh->i_disable_deblocking_filter_idc != 1 )
316 bs_write_se( s, sh->i_alpha_c0_offset >> 1 );
317 bs_write_se( s, sh->i_beta_offset >> 1 );
322 /****************************************************************************
324 ****************************************************************************
325 ****************************** External API*********************************
326 ****************************************************************************
328 ****************************************************************************/
330 static int x264_validate_parameters( x264_t *h )
332 if( h->param.i_width <= 0 || h->param.i_height <= 0 )
334 x264_log( h, X264_LOG_ERROR, "invalid width x height (%dx%d)\n",
335 h->param.i_width, h->param.i_height );
339 if( h->param.i_width % 2 || h->param.i_height % 2 )
341 x264_log( h, X264_LOG_ERROR, "width or height not divisible by 2 (%dx%d)\n",
342 h->param.i_width, h->param.i_height );
345 if( h->param.i_csp != X264_CSP_I420 )
347 x264_log( h, X264_LOG_ERROR, "invalid CSP (only I420 supported)\n" );
351 h->param.i_threads = x264_clip3( h->param.i_threads, 1, X264_SLICE_MAX );
352 h->param.i_threads = X264_MIN( h->param.i_threads, (h->param.i_height + 15) / 16 );
354 if( h->param.i_threads > 1 )
356 x264_log( h, X264_LOG_WARNING, "not compiled with pthread support!\n");
357 x264_log( h, X264_LOG_WARNING, "multislicing anyway, but you won't see any speed gain.\n" );
361 if( h->param.rc.b_cbr )
362 h->param.rc.i_rf_constant = 0;
363 if( h->param.rc.i_rf_constant > 0 )
364 h->param.rc.i_qp_constant = h->param.rc.i_rf_constant;
365 h->param.rc.i_rf_constant = x264_clip3( h->param.rc.i_rf_constant, 0, 51 );
366 h->param.rc.i_qp_constant = x264_clip3( h->param.rc.i_qp_constant, 0, 51 );
367 if( !h->param.rc.b_cbr && h->param.rc.i_qp_constant == 0 )
369 h->mb.b_lossless = 1;
370 h->param.analyse.b_transform_8x8 = 0;
371 h->param.i_cqm_preset = X264_CQM_FLAT;
372 h->param.psz_cqm_file = NULL;
373 h->param.rc.f_ip_factor = 1;
374 h->param.rc.f_pb_factor = 1;
375 h->param.analyse.b_psnr = 0;
376 h->param.analyse.i_chroma_qp_offset = 0;
377 h->param.analyse.i_trellis = 0;
378 h->param.analyse.b_fast_pskip = 0;
379 h->param.analyse.i_noise_reduction = 0;
382 if( ( h->param.i_width % 16 || h->param.i_height % 16 ) && !h->mb.b_lossless )
384 x264_log( h, X264_LOG_WARNING,
385 "width or height not divisible by 16 (%dx%d), compression will suffer.\n",
386 h->param.i_width, h->param.i_height );
389 h->param.i_frame_reference = x264_clip3( h->param.i_frame_reference, 1, 16 );
390 if( h->param.i_keyint_max <= 0 )
391 h->param.i_keyint_max = 1;
392 h->param.i_keyint_min = x264_clip3( h->param.i_keyint_min, 1, h->param.i_keyint_max/2+1 );
394 h->param.i_bframe = x264_clip3( h->param.i_bframe, 0, X264_BFRAME_MAX );
395 h->param.i_bframe_bias = x264_clip3( h->param.i_bframe_bias, -90, 100 );
396 h->param.b_bframe_pyramid = h->param.b_bframe_pyramid && h->param.i_bframe > 1;
397 h->param.b_bframe_adaptive = h->param.b_bframe_adaptive && h->param.i_bframe > 0;
398 h->mb.b_direct_auto_write = h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_AUTO
400 && ( h->param.rc.b_stat_write || !h->param.rc.b_stat_read );
402 h->param.i_deblocking_filter_alphac0 = x264_clip3( h->param.i_deblocking_filter_alphac0, -6, 6 );
403 h->param.i_deblocking_filter_beta = x264_clip3( h->param.i_deblocking_filter_beta, -6, 6 );
405 h->param.i_cabac_init_idc = x264_clip3( h->param.i_cabac_init_idc, 0, 2 );
407 if( h->param.i_cqm_preset < X264_CQM_FLAT || h->param.i_cqm_preset > X264_CQM_CUSTOM )
408 h->param.i_cqm_preset = X264_CQM_FLAT;
410 if( h->param.analyse.i_me_method < X264_ME_DIA ||
411 h->param.analyse.i_me_method > X264_ME_ESA )
412 h->param.analyse.i_me_method = X264_ME_HEX;
413 if( h->param.analyse.i_me_range < 4 )
414 h->param.analyse.i_me_range = 4;
415 if( h->param.analyse.i_me_range > 16 && h->param.analyse.i_me_method <= X264_ME_HEX )
416 h->param.analyse.i_me_range = 16;
417 h->param.analyse.i_subpel_refine = x264_clip3( h->param.analyse.i_subpel_refine, 1, 6 );
418 h->param.analyse.b_bframe_rdo = h->param.analyse.b_bframe_rdo && h->param.analyse.i_subpel_refine >= 6;
419 h->param.analyse.b_mixed_references = h->param.analyse.b_mixed_references && h->param.i_frame_reference > 1;
420 h->param.analyse.inter &= X264_ANALYSE_PSUB16x16|X264_ANALYSE_PSUB8x8|X264_ANALYSE_BSUB16x16|
421 X264_ANALYSE_I4x4|X264_ANALYSE_I8x8;
422 h->param.analyse.intra &= X264_ANALYSE_I4x4|X264_ANALYSE_I8x8;
423 if( !(h->param.analyse.inter & X264_ANALYSE_PSUB16x16) )
424 h->param.analyse.inter &= ~X264_ANALYSE_PSUB8x8;
425 if( !h->param.analyse.b_transform_8x8 )
427 h->param.analyse.inter &= ~X264_ANALYSE_I8x8;
428 h->param.analyse.intra &= ~X264_ANALYSE_I8x8;
430 h->param.analyse.i_chroma_qp_offset = x264_clip3(h->param.analyse.i_chroma_qp_offset, -12, 12);
431 if( !h->param.b_cabac )
432 h->param.analyse.i_trellis = 0;
433 h->param.analyse.i_trellis = x264_clip3( h->param.analyse.i_trellis, 0, 2 );
434 h->param.analyse.i_noise_reduction = x264_clip3( h->param.analyse.i_noise_reduction, 0, 1<<16 );
437 const x264_level_t *l = x264_levels;
438 while( l->level_idc != 0 && l->level_idc != h->param.i_level_idc )
440 if( l->level_idc == 0 )
442 x264_log( h, X264_LOG_ERROR, "invalid level_idc: %d\n", h->param.i_level_idc );
445 if( h->param.analyse.i_mv_range <= 0 )
446 h->param.analyse.i_mv_range = l->mv_range;
448 h->param.analyse.i_mv_range = x264_clip3(h->param.analyse.i_mv_range, 32, 2048);
451 if( h->param.rc.f_qblur < 0 )
452 h->param.rc.f_qblur = 0;
453 if( h->param.rc.f_complexity_blur < 0 )
454 h->param.rc.f_complexity_blur = 0;
456 /* ensure the booleans are 0 or 1 so they can be used in math */
457 #define BOOLIFY(x) h->param.x = !!h->param.x
459 BOOLIFY( b_deblocking_filter );
460 BOOLIFY( analyse.b_transform_8x8 );
461 BOOLIFY( analyse.b_weighted_bipred );
462 BOOLIFY( analyse.b_bidir_me );
463 BOOLIFY( analyse.b_chroma_me );
464 BOOLIFY( analyse.b_fast_pskip );
466 BOOLIFY( rc.b_stat_write );
467 BOOLIFY( rc.b_stat_read );
473 /****************************************************************************
475 ****************************************************************************/
476 x264_t *x264_encoder_open ( x264_param_t *param )
478 x264_t *h = x264_malloc( sizeof( x264_t ) );
481 memset( h, 0, sizeof( x264_t ) );
483 /* Create a copy of param */
484 memcpy( &h->param, param, sizeof( x264_param_t ) );
486 if( x264_validate_parameters( h ) < 0 )
492 if( h->param.psz_cqm_file )
493 if( x264_cqm_parse_file( h, h->param.psz_cqm_file ) < 0 )
499 if( h->param.rc.psz_stat_out )
500 h->param.rc.psz_stat_out = strdup( h->param.rc.psz_stat_out );
501 if( h->param.rc.psz_stat_in )
502 h->param.rc.psz_stat_in = strdup( h->param.rc.psz_stat_in );
503 if( h->param.rc.psz_rc_eq )
504 h->param.rc.psz_rc_eq = strdup( h->param.rc.psz_rc_eq );
507 if( h->param.vui.i_sar_width > 0 && h->param.vui.i_sar_height > 0 )
509 int i_w = param->vui.i_sar_width;
510 int i_h = param->vui.i_sar_height;
511 int a = i_w, b = i_h;
523 while( i_w > 65535 || i_h > 65535 )
529 h->param.vui.i_sar_width = 0;
530 h->param.vui.i_sar_height = 0;
531 if( i_w == 0 || i_h == 0 )
533 x264_log( h, X264_LOG_ERROR, "cannot create valid sample aspect ratio\n" );
535 else if( i_w == i_h )
537 x264_log( h, X264_LOG_INFO, "no need for a SAR\n" );
541 x264_log( h, X264_LOG_INFO, "using SAR=%d/%d\n", i_w, i_h );
542 h->param.vui.i_sar_width = i_w;
543 h->param.vui.i_sar_height = i_h;
550 h->out.i_bitstream = X264_MAX( 1000000, h->param.i_width * h->param.i_height * 1.7
551 * ( h->param.rc.b_cbr ? pow( 0.5, h->param.rc.i_qp_min )
552 : pow( 0.5, h->param.rc.i_qp_constant ) * X264_MAX( 1, h->param.rc.f_ip_factor )));
553 h->out.p_bitstream = x264_malloc( h->out.i_bitstream );
559 h->sps = &h->sps_array[0];
560 x264_sps_init( h->sps, 0, &h->param );
562 h->pps = &h->pps_array[0];
563 x264_pps_init( h->pps, 0, &h->param, h->sps);
565 x264_validate_levels( h );
569 h->mb.i_mb_count = h->sps->i_mb_width * h->sps->i_mb_height;
572 h->frames.i_delay = h->param.i_bframe;
573 h->frames.i_max_ref0 = h->param.i_frame_reference;
574 h->frames.i_max_ref1 = h->sps->vui.i_num_reorder_frames;
575 h->frames.i_max_dpb = h->sps->vui.i_max_dec_frame_buffering + 1;
576 h->frames.b_have_lowres = !h->param.rc.b_stat_read
577 && ( h->param.rc.b_cbr || h->param.rc.i_rf_constant || h->param.b_bframe_adaptive );
579 for( i = 0; i < X264_BFRAME_MAX + 3; i++ )
581 h->frames.current[i] = NULL;
582 h->frames.next[i] = NULL;
583 h->frames.unused[i] = NULL;
585 for( i = 0; i < 1 + h->frames.i_delay; i++ )
587 h->frames.unused[i] = x264_frame_new( h );
589 for( i = 0; i < h->frames.i_max_dpb; i++ )
591 h->frames.reference[i] = x264_frame_new( h );
593 h->frames.reference[h->frames.i_max_dpb] = NULL;
594 h->frames.i_last_idr = - h->param.i_keyint_max;
595 h->frames.i_input = 0;
596 h->frames.last_nonb = NULL;
601 h->fdec = h->frames.reference[0];
603 x264_macroblock_cache_init( h );
606 /* init CPU functions */
607 x264_predict_16x16_init( h->param.cpu, h->predict_16x16 );
608 x264_predict_8x8c_init( h->param.cpu, h->predict_8x8c );
609 x264_predict_8x8_init( h->param.cpu, h->predict_8x8 );
610 x264_predict_4x4_init( h->param.cpu, h->predict_4x4 );
612 x264_pixel_init( h->param.cpu, &h->pixf );
613 x264_dct_init( h->param.cpu, &h->dctf );
614 x264_mc_init( h->param.cpu, &h->mc );
615 x264_csp_init( h->param.cpu, h->param.i_csp, &h->csp );
616 x264_quant_init( h, h->param.cpu, &h->quantf );
617 x264_deblock_init( h->param.cpu, &h->loopf );
619 memcpy( h->pixf.mbcmp,
620 ( h->mb.b_lossless || h->param.analyse.i_subpel_refine <= 1 ) ? h->pixf.sad : h->pixf.satd,
621 sizeof(h->pixf.mbcmp) );
624 if( x264_ratecontrol_new( h ) < 0 )
627 x264_log( h, X264_LOG_INFO, "using cpu capabilities %s%s%s%s%s%s\n",
628 param->cpu&X264_CPU_MMX ? "MMX " : "",
629 param->cpu&X264_CPU_MMXEXT ? "MMXEXT " : "",
630 param->cpu&X264_CPU_SSE ? "SSE " : "",
631 param->cpu&X264_CPU_SSE2 ? "SSE2 " : "",
632 param->cpu&X264_CPU_3DNOW ? "3DNow! " : "",
633 param->cpu&X264_CPU_ALTIVEC ? "Altivec " : "" );
637 for( i = 1; i < param->i_threads; i++ )
638 h->thread[i] = x264_malloc( sizeof(x264_t) );
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_reference_update( x264_t *h )
846 /* apply deblocking filter to the current decoded picture */
847 if( !h->sh.i_disable_deblocking_filter_idc )
849 TIMER_START( i_mtime_filter );
850 x264_frame_deblocking_filter( h, h->sh.i_type );
851 TIMER_STOP( i_mtime_filter );
854 x264_frame_expand_border( h->fdec );
856 /* create filtered images */
857 x264_frame_filter( h->param.cpu, h->fdec );
859 /* expand border of filtered images */
860 x264_frame_expand_border_filtered( h->fdec );
862 /* move lowres copy of the image to the ref frame */
863 for( i = 0; i < 4; i++)
864 XCHG( uint8_t*, h->fdec->lowres[i], h->fenc->lowres[i] );
866 /* adaptive B decision needs a pointer, since it can't use the ref lists */
867 if( h->sh.i_type != SLICE_TYPE_B )
868 h->frames.last_nonb = h->fdec;
870 /* move frame in the buffer */
871 h->fdec = h->frames.reference[h->frames.i_max_dpb-1];
872 for( i = h->frames.i_max_dpb-1; i > 0; i-- )
874 h->frames.reference[i] = h->frames.reference[i-1];
876 h->frames.reference[0] = h->fdec;
879 static inline void x264_reference_reset( x264_t *h )
883 /* reset ref pictures */
884 for( i = 1; i < h->frames.i_max_dpb; i++ )
886 h->frames.reference[i]->i_poc = -1;
888 h->frames.reference[0]->i_poc = 0;
891 static inline void x264_slice_init( x264_t *h, int i_nal_type, int i_slice_type, int i_global_qp )
893 /* ------------------------ Create slice header ----------------------- */
894 if( i_nal_type == NAL_SLICE_IDR )
896 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 );
899 h->i_idr_pic_id = ( h->i_idr_pic_id + 1 ) % 65536;
903 x264_slice_header_init( h, &h->sh, h->sps, h->pps, i_slice_type, -1, h->i_frame_num - 1, i_global_qp );
905 /* always set the real higher num of ref frame used */
906 h->sh.b_num_ref_idx_override = 1;
907 h->sh.i_num_ref_idx_l0_active = h->i_ref0 <= 0 ? 1 : h->i_ref0;
908 h->sh.i_num_ref_idx_l1_active = h->i_ref1 <= 0 ? 1 : h->i_ref1;
911 h->fdec->i_frame_num = h->sh.i_frame_num;
913 if( h->sps->i_poc_type == 0 )
915 h->sh.i_poc_lsb = h->fdec->i_poc & ( (1 << h->sps->i_log2_max_poc_lsb) - 1 );
916 h->sh.i_delta_poc_bottom = 0; /* XXX won't work for field */
918 else if( h->sps->i_poc_type == 1 )
920 /* FIXME TODO FIXME */
924 /* Nothing to do ? */
927 x264_macroblock_slice_init( h );
930 static int x264_slice_write( x264_t *h )
937 memset( &h->stat.frame, 0, sizeof(h->stat.frame) );
940 x264_nal_start( h, h->i_nal_type, h->i_nal_ref_idc );
943 x264_slice_header_write( &h->out.bs, &h->sh, h->i_nal_ref_idc );
944 if( h->param.b_cabac )
946 /* alignment needed */
947 bs_align_1( &h->out.bs );
950 x264_cabac_context_init( &h->cabac, h->sh.i_type, h->sh.i_qp, h->sh.i_cabac_init_idc );
951 x264_cabac_encode_init ( &h->cabac, &h->out.bs );
953 h->mb.i_last_qp = h->sh.i_qp;
954 h->mb.i_last_dqp = 0;
956 for( mb_xy = h->sh.i_first_mb, i_skip = 0; mb_xy < h->sh.i_last_mb; mb_xy++ )
958 const int i_mb_y = mb_xy / h->sps->i_mb_width;
959 const int i_mb_x = mb_xy % h->sps->i_mb_width;
961 int mb_spos = bs_pos(&h->out.bs);
964 x264_macroblock_cache_load( h, i_mb_x, i_mb_y );
966 /* analyse parameters
967 * Slice I: choose I_4x4 or I_16x16 mode
968 * Slice P: choose between using P mode or intra (4x4 or 16x16)
970 TIMER_START( i_mtime_analyse );
971 x264_macroblock_analyse( h );
972 TIMER_STOP( i_mtime_analyse );
974 /* encode this macrobock -> be carefull it can change the mb type to P_SKIP if needed */
975 TIMER_START( i_mtime_encode );
976 x264_macroblock_encode( h );
977 TIMER_STOP( i_mtime_encode );
979 TIMER_START( i_mtime_write );
980 if( h->param.b_cabac )
982 if( mb_xy > h->sh.i_first_mb )
983 x264_cabac_encode_terminal( &h->cabac, 0 );
985 if( IS_SKIP( h->mb.i_type ) )
986 x264_cabac_mb_skip( h, 1 );
989 if( h->sh.i_type != SLICE_TYPE_I )
990 x264_cabac_mb_skip( h, 0 );
991 x264_macroblock_write_cabac( h, &h->cabac );
996 if( IS_SKIP( h->mb.i_type ) )
1000 if( h->sh.i_type != SLICE_TYPE_I )
1002 bs_write_ue( &h->out.bs, i_skip ); /* skip run */
1005 x264_macroblock_write_cavlc( h, &h->out.bs );
1008 TIMER_STOP( i_mtime_write );
1011 if( h->param.b_visualize )
1012 x264_visualize_mb( h );
1016 x264_macroblock_cache_save( h );
1018 /* accumulate mb stats */
1019 h->stat.frame.i_mb_count[h->mb.i_type]++;
1020 if( !IS_SKIP(h->mb.i_type) && !IS_INTRA(h->mb.i_type) && !IS_DIRECT(h->mb.i_type) )
1022 if( h->mb.i_partition != D_8x8 )
1023 h->stat.frame.i_mb_count_size[ x264_mb_partition_pixel_table[ h->mb.i_partition ] ] += 4;
1025 for( i = 0; i < 4; i++ )
1026 h->stat.frame.i_mb_count_size[ x264_mb_partition_pixel_table[ h->mb.i_sub_partition[i] ] ] ++;
1027 if( h->param.i_frame_reference > 1 )
1029 for( i = 0; i < 4; i++ )
1031 int i_ref = h->mb.cache.ref[0][ x264_scan8[4*i] ];
1033 h->stat.frame.i_mb_count_ref[i_ref] ++;
1037 if( h->mb.i_cbp_luma && !IS_INTRA(h->mb.i_type) )
1039 h->stat.frame.i_mb_count_8x8dct[0] ++;
1040 h->stat.frame.i_mb_count_8x8dct[1] += h->mb.b_transform_8x8;
1043 if( h->mb.b_variable_qp )
1044 x264_ratecontrol_mb(h, bs_pos(&h->out.bs) - mb_spos);
1047 if( h->param.b_cabac )
1050 x264_cabac_encode_terminal( &h->cabac, 1 );
1052 else if( i_skip > 0 )
1054 bs_write_ue( &h->out.bs, i_skip ); /* last skip run */
1057 if( h->param.b_cabac )
1059 x264_cabac_encode_flush( &h->cabac );
1064 /* rbsp_slice_trailing_bits */
1065 bs_rbsp_trailing( &h->out.bs );
1070 /* Compute misc bits */
1071 h->stat.frame.i_misc_bits = bs_pos( &h->out.bs )
1073 - h->stat.frame.i_itex_bits
1074 - h->stat.frame.i_ptex_bits
1075 - h->stat.frame.i_hdr_bits;
1080 static inline int x264_slices_write( x264_t *h )
1085 if( h->param.b_visualize )
1086 x264_visualize_init( h );
1089 if( h->param.i_threads == 1 )
1091 x264_ratecontrol_threads_start( h );
1092 x264_slice_write( h );
1093 i_frame_size = h->out.nal[h->out.i_nal-1].i_payload;
1097 int i_nal = h->out.i_nal;
1098 int i_bs_size = h->out.i_bitstream / h->param.i_threads;
1100 /* duplicate contexts */
1101 for( i = 0; i < h->param.i_threads; i++ )
1103 x264_t *t = h->thread[i];
1106 memcpy( t, h, sizeof(x264_t) );
1107 t->out.p_bitstream += i*i_bs_size;
1108 bs_init( &t->out.bs, t->out.p_bitstream, i_bs_size );
1109 t->i_thread_num = i;
1111 t->sh.i_first_mb = (i * h->sps->i_mb_height / h->param.i_threads) * h->sps->i_mb_width;
1112 t->sh.i_last_mb = ((i+1) * h->sps->i_mb_height / h->param.i_threads) * h->sps->i_mb_width;
1113 t->out.i_nal = i_nal + i;
1115 x264_ratecontrol_threads_start( h );
1120 pthread_t handles[X264_SLICE_MAX];
1122 for( i = 0; i < h->param.i_threads; i++ )
1123 pthread_create( &handles[i], NULL, (void*)x264_slice_write, (void*)h->thread[i] );
1124 for( i = 0; i < h->param.i_threads; i++ )
1125 pthread_join( handles[i], &status );
1128 for( i = 0; i < h->param.i_threads; i++ )
1129 x264_slice_write( h->thread[i] );
1132 /* merge contexts */
1133 i_frame_size = h->out.nal[i_nal].i_payload;
1134 for( i = 1; i < h->param.i_threads; i++ )
1137 x264_t *t = h->thread[i];
1138 h->out.nal[i_nal+i] = t->out.nal[i_nal+i];
1139 i_frame_size += t->out.nal[i_nal+i].i_payload;
1140 // all entries in stat.frame are ints
1141 for( j = 0; j < sizeof(h->stat.frame) / sizeof(int); j++ )
1142 ((int*)&h->stat.frame)[j] += ((int*)&t->stat.frame)[j];
1144 h->out.i_nal = i_nal + h->param.i_threads;
1148 if( h->param.b_visualize )
1150 x264_visualize_show( h );
1151 x264_visualize_close( h );
1155 return i_frame_size;
1158 /****************************************************************************
1159 * x264_encoder_encode:
1160 * XXX: i_poc : is the poc of the current given picture
1161 * i_frame : is the number of the frame being coded
1162 * ex: type frame poc
1170 ****************************************************************************/
1171 int x264_encoder_encode( x264_t *h,
1172 x264_nal_t **pp_nal, int *pi_nal,
1173 x264_picture_t *pic_in,
1174 x264_picture_t *pic_out )
1176 x264_frame_t *frame_psnr = h->fdec; /* just to keep the current decoded frame for psnr calculation */
1186 char psz_message[80];
1193 /* ------------------- Setup new frame from picture -------------------- */
1194 TIMER_START( i_mtime_encode_frame );
1195 if( pic_in != NULL )
1197 /* 1: Copy the picture to a frame and move it to a buffer */
1198 x264_frame_t *fenc = x264_frame_get( h->frames.unused );
1200 x264_frame_copy_picture( h, fenc, pic_in );
1202 if( h->param.i_width % 16 || h->param.i_height % 16 )
1203 x264_frame_expand_border_mod16( h, fenc );
1205 fenc->i_frame = h->frames.i_input++;
1207 x264_frame_put( h->frames.next, fenc );
1209 if( h->frames.b_have_lowres )
1210 x264_frame_init_lowres( h->param.cpu, fenc );
1212 if( h->frames.i_input <= h->frames.i_delay )
1214 /* Nothing yet to encode */
1215 /* waiting for filling bframe buffer */
1216 pic_out->i_type = X264_TYPE_AUTO;
1221 if( h->frames.current[0] == NULL )
1224 /* 2: Select frame types */
1225 if( h->frames.next[0] == NULL )
1228 x264_slicetype_decide( h );
1230 /* 3: move some B-frames and 1 non-B to encode queue */
1231 while( IS_X264_TYPE_B( h->frames.next[bframes]->i_type ) )
1233 x264_frame_put( h->frames.current, x264_frame_get( &h->frames.next[bframes] ) );
1234 /* FIXME: when max B-frames > 3, BREF may no longer be centered after GOP closing */
1235 if( h->param.b_bframe_pyramid && bframes > 1 )
1237 x264_frame_t *mid = x264_frame_get( &h->frames.next[bframes/2] );
1238 mid->i_type = X264_TYPE_BREF;
1239 x264_frame_put( h->frames.current, mid );
1243 x264_frame_put( h->frames.current, x264_frame_get( h->frames.next ) );
1245 TIMER_STOP( i_mtime_encode_frame );
1247 /* ------------------- Get frame to be encoded ------------------------- */
1248 /* 4: get picture to encode */
1249 h->fenc = x264_frame_get( h->frames.current );
1250 if( h->fenc == NULL )
1252 /* Nothing yet to encode (ex: waiting for I/P with B frames) */
1253 /* waiting for filling bframe buffer */
1254 pic_out->i_type = X264_TYPE_AUTO;
1260 if( h->fenc->i_type == X264_TYPE_IDR )
1262 h->frames.i_last_idr = h->fenc->i_frame;
1265 /* ------------------- Setup frame context ----------------------------- */
1266 /* 5: Init data dependant of frame type */
1267 TIMER_START( i_mtime_encode_frame );
1268 if( h->fenc->i_type == X264_TYPE_IDR )
1270 /* reset ref pictures */
1271 x264_reference_reset( h );
1273 i_nal_type = NAL_SLICE_IDR;
1274 i_nal_ref_idc = NAL_PRIORITY_HIGHEST;
1275 i_slice_type = SLICE_TYPE_I;
1277 else if( h->fenc->i_type == X264_TYPE_I )
1279 i_nal_type = NAL_SLICE;
1280 i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
1281 i_slice_type = SLICE_TYPE_I;
1283 else if( h->fenc->i_type == X264_TYPE_P )
1285 i_nal_type = NAL_SLICE;
1286 i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
1287 i_slice_type = SLICE_TYPE_P;
1289 else if( h->fenc->i_type == X264_TYPE_BREF )
1291 i_nal_type = NAL_SLICE;
1292 i_nal_ref_idc = NAL_PRIORITY_HIGH; /* maybe add MMCO to forget it? -> low */
1293 i_slice_type = SLICE_TYPE_B;
1297 i_nal_type = NAL_SLICE;
1298 i_nal_ref_idc = NAL_PRIORITY_DISPOSABLE;
1299 i_slice_type = SLICE_TYPE_B;
1303 h->fenc->i_poc = 2 * (h->fenc->i_frame - h->frames.i_last_idr);
1304 h->fdec->i_type = h->fenc->i_type;
1305 h->fdec->i_frame = h->fenc->i_frame;
1306 h->fenc->b_kept_as_ref =
1307 h->fdec->b_kept_as_ref = i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE;
1311 /* ------------------- Init ----------------------------- */
1312 /* build ref list 0/1 */
1313 x264_reference_build_list( h, h->fdec->i_poc, i_slice_type );
1315 /* Init the rate control */
1316 x264_ratecontrol_start( h, i_slice_type, h->fenc->i_qpplus1 );
1317 i_global_qp = x264_ratecontrol_qp( h );
1319 pic_out->i_qpplus1 =
1320 h->fdec->i_qpplus1 = i_global_qp + 1;
1322 if( i_slice_type == SLICE_TYPE_B )
1323 x264_macroblock_bipred_init( h );
1325 if( h->fenc->b_kept_as_ref )
1328 /* ------------------------ Create slice header ----------------------- */
1329 x264_slice_init( h, i_nal_type, i_slice_type, i_global_qp );
1331 /* ---------------------- Write the bitstream -------------------------- */
1332 /* Init bitstream context */
1334 bs_init( &h->out.bs, h->out.p_bitstream, h->out.i_bitstream );
1339 if(i_slice_type == SLICE_TYPE_I)
1341 else if(i_slice_type == SLICE_TYPE_P)
1343 else if(i_slice_type == SLICE_TYPE_B)
1348 x264_nal_start(h, NAL_AUD, NAL_PRIORITY_DISPOSABLE);
1349 bs_write(&h->out.bs, 3, pic_type);
1350 bs_rbsp_trailing(&h->out.bs);
1354 h->i_nal_type = i_nal_type;
1355 h->i_nal_ref_idc = i_nal_ref_idc;
1357 /* Write SPS and PPS */
1358 if( i_nal_type == NAL_SLICE_IDR && h->param.b_repeat_headers )
1360 if( h->fenc->i_frame == 0 )
1362 /* identify ourself */
1363 x264_nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
1364 x264_sei_version_write( h, &h->out.bs );
1368 /* generate sequence parameters */
1369 x264_nal_start( h, NAL_SPS, NAL_PRIORITY_HIGHEST );
1370 x264_sps_write( &h->out.bs, h->sps );
1373 /* generate picture parameters */
1374 x264_nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
1375 x264_pps_write( &h->out.bs, h->pps );
1380 i_frame_size = x264_slices_write( h );
1382 /* restore CPU state (before using float again) */
1383 x264_cpu_restore( h->param.cpu );
1385 if( i_slice_type == SLICE_TYPE_P && !h->param.rc.b_stat_read
1386 && h->param.i_scenecut_threshold >= 0 )
1388 const int *mbs = h->stat.frame.i_mb_count;
1389 int i_mb_i = mbs[I_16x16] + mbs[I_8x8] + mbs[I_4x4];
1390 int i_mb_p = mbs[P_L0] + mbs[P_8x8];
1391 int i_mb_s = mbs[P_SKIP];
1392 int i_mb = h->sps->i_mb_width * h->sps->i_mb_height;
1393 int64_t i_inter_cost = h->stat.frame.i_inter_cost;
1394 int64_t i_intra_cost = h->stat.frame.i_intra_cost;
1397 int i_gop_size = h->fenc->i_frame - h->frames.i_last_idr;
1398 float f_thresh_max = h->param.i_scenecut_threshold / 100.0;
1399 /* magic numbers pulled out of thin air */
1400 float f_thresh_min = f_thresh_max * h->param.i_keyint_min
1401 / ( h->param.i_keyint_max * 4 );
1402 if( h->param.i_keyint_min == h->param.i_keyint_max )
1403 f_thresh_min= f_thresh_max;
1405 /* macroblock_analyse() doesn't further analyse skipped mbs,
1406 * so we have to guess their cost */
1408 i_intra_cost = i_intra_cost * i_mb / (i_mb - i_mb_s);
1410 if( i_gop_size < h->param.i_keyint_min / 4 )
1411 f_bias = f_thresh_min / 4;
1412 else if( i_gop_size <= h->param.i_keyint_min )
1413 f_bias = f_thresh_min * i_gop_size / h->param.i_keyint_min;
1416 f_bias = f_thresh_min
1417 + ( f_thresh_max - f_thresh_min )
1418 * ( i_gop_size - h->param.i_keyint_min )
1419 / ( h->param.i_keyint_max - h->param.i_keyint_min );
1421 f_bias = X264_MIN( f_bias, 1.0 );
1423 /* Bad P will be reencoded as I */
1424 if( i_mb_s < i_mb &&
1425 i_inter_cost >= (1.0 - f_bias) * i_intra_cost )
1429 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",
1431 (double)i_intra_cost, (double)i_inter_cost,
1432 (double)i_inter_cost / i_intra_cost,
1434 i_mb_i, i_mb_p, i_mb_s );
1436 /* Restore frame num */
1439 for( b = 0; h->frames.current[b] && IS_X264_TYPE_B( h->frames.current[b]->i_type ); b++ );
1442 /* If using B-frames, force GOP to be closed.
1443 * Even if this frame is going to be I and not IDR, forcing a
1444 * P-frame before the scenecut will probably help compression.
1446 * We don't yet know exactly which frame is the scene cut, so
1447 * we can't assign an I-frame. Instead, change the previous
1448 * B-frame to P, and rearrange coding order. */
1450 if( h->param.b_bframe_adaptive || b > 1 )
1451 h->fenc->i_type = X264_TYPE_AUTO;
1452 x264_frame_sort_pts( h->frames.current );
1453 x264_frame_push( h->frames.next, h->fenc );
1454 h->fenc = h->frames.current[b-1];
1455 h->frames.current[b-1] = NULL;
1456 h->fenc->i_type = X264_TYPE_P;
1457 x264_frame_sort_dts( h->frames.current );
1459 /* Do IDR if needed */
1460 else if( i_gop_size >= h->param.i_keyint_min )
1467 /* Reinit field of fenc */
1468 h->fenc->i_type = X264_TYPE_IDR;
1471 /* Put enqueued frames back in the pool */
1472 while( (tmp = x264_frame_get( h->frames.current ) ) != NULL )
1473 x264_frame_put( h->frames.next, tmp );
1474 x264_frame_sort_pts( h->frames.next );
1478 h->fenc->i_type = X264_TYPE_I;
1484 /* End bitstream, set output */
1485 *pi_nal = h->out.i_nal;
1486 *pp_nal = h->out.nal;
1488 /* Set output picture properties */
1489 if( i_slice_type == SLICE_TYPE_I )
1490 pic_out->i_type = i_nal_type == NAL_SLICE_IDR ? X264_TYPE_IDR : X264_TYPE_I;
1491 else if( i_slice_type == SLICE_TYPE_P )
1492 pic_out->i_type = X264_TYPE_P;
1494 pic_out->i_type = X264_TYPE_B;
1495 pic_out->i_pts = h->fenc->i_pts;
1497 pic_out->img.i_plane = h->fdec->i_plane;
1498 for(i = 0; i < 4; i++){
1499 pic_out->img.i_stride[i] = h->fdec->i_stride[i];
1500 pic_out->img.plane[i] = h->fdec->plane[i];
1503 /* ---------------------- Update encoder state ------------------------- */
1506 x264_cpu_restore( h->param.cpu );
1507 x264_ratecontrol_end( h, i_frame_size * 8 );
1509 /* handle references */
1510 if( i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE )
1511 x264_reference_update( h );
1512 x264_frame_put( h->frames.unused, h->fenc );
1514 /* increase frame count */
1517 /* restore CPU state (before using float again) */
1518 x264_cpu_restore( h->param.cpu );
1520 x264_noise_reduction_update( h );
1522 TIMER_STOP( i_mtime_encode_frame );
1524 /* ---------------------- Compute/Print statistics --------------------- */
1526 h->stat.i_slice_count[i_slice_type]++;
1527 h->stat.i_slice_size[i_slice_type] += i_frame_size + NALU_OVERHEAD;
1528 h->stat.i_slice_qp[i_slice_type] += i_global_qp;
1530 for( i = 0; i < 19; i++ )
1531 h->stat.i_mb_count[h->sh.i_type][i] += h->stat.frame.i_mb_count[i];
1532 for( i = 0; i < 2; i++ )
1533 h->stat.i_mb_count_8x8dct[i] += h->stat.frame.i_mb_count_8x8dct[i];
1534 if( h->sh.i_type != SLICE_TYPE_I )
1536 for( i = 0; i < 7; i++ )
1537 h->stat.i_mb_count_size[h->sh.i_type][i] += h->stat.frame.i_mb_count_size[i];
1538 for( i = 0; i < 16; i++ )
1539 h->stat.i_mb_count_ref[h->sh.i_type][i] += h->stat.frame.i_mb_count_ref[i];
1541 if( i_slice_type == SLICE_TYPE_B )
1543 h->stat.i_direct_frames[ h->sh.b_direct_spatial_mv_pred ] ++;
1544 if( h->mb.b_direct_auto_write )
1546 //FIXME somewhat arbitrary time constants
1547 if( h->stat.i_direct_score[0] + h->stat.i_direct_score[1] > h->mb.i_mb_count )
1549 for( i = 0; i < 2; i++ )
1550 h->stat.i_direct_score[i] = h->stat.i_direct_score[i] * 9/10;
1552 for( i = 0; i < 2; i++ )
1553 h->stat.i_direct_score[i] += h->stat.frame.i_direct_score[i];
1557 if( h->param.analyse.b_psnr )
1559 int64_t i_sqe_y, i_sqe_u, i_sqe_v;
1562 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 );
1563 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);
1564 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);
1565 x264_cpu_restore( h->param.cpu );
1567 h->stat.i_sqe_global[i_slice_type] += i_sqe_y + i_sqe_u + i_sqe_v;
1568 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 );
1569 h->stat.f_psnr_mean_y[i_slice_type] += x264_psnr( i_sqe_y, h->param.i_width * h->param.i_height );
1570 h->stat.f_psnr_mean_u[i_slice_type] += x264_psnr( i_sqe_u, h->param.i_width * h->param.i_height / 4 );
1571 h->stat.f_psnr_mean_v[i_slice_type] += x264_psnr( i_sqe_v, h->param.i_width * h->param.i_height / 4 );
1573 snprintf( psz_message, 80, " PSNR Y:%2.2f U:%2.2f V:%2.2f",
1574 x264_psnr( i_sqe_y, h->param.i_width * h->param.i_height ),
1575 x264_psnr( i_sqe_u, h->param.i_width * h->param.i_height / 4),
1576 x264_psnr( i_sqe_v, h->param.i_width * h->param.i_height / 4) );
1577 psz_message[79] = '\0';
1581 psz_message[0] = '\0';
1584 x264_log( h, X264_LOG_DEBUG,
1585 "frame=%4d QP=%i NAL=%d Slice:%c Poc:%-3d I:%-4d P:%-4d SKIP:%-4d size=%d bytes%s\n",
1589 i_slice_type == SLICE_TYPE_I ? 'I' : (i_slice_type == SLICE_TYPE_P ? 'P' : 'B' ),
1591 h->stat.frame.i_mb_count_i,
1592 h->stat.frame.i_mb_count_p,
1593 h->stat.frame.i_mb_count_skip,
1598 #ifdef DEBUG_MB_TYPE
1600 static const char mb_chars[] = { 'i', 'i', 'I', 'C', 'P', '8', 'S',
1601 'D', '<', 'X', 'B', 'X', '>', 'B', 'B', 'B', 'B', '8', 'S' };
1603 for( mb_xy = 0; mb_xy < h->sps->i_mb_width * h->sps->i_mb_height; mb_xy++ )
1605 if( h->mb.type[mb_xy] < 19 && h->mb.type[mb_xy] >= 0 )
1606 fprintf( stderr, "%c ", mb_chars[ h->mb.type[mb_xy] ] );
1608 fprintf( stderr, "? " );
1610 if( (mb_xy+1) % h->sps->i_mb_width == 0 )
1611 fprintf( stderr, "\n" );
1616 #ifdef DEBUG_DUMP_FRAME
1617 /* Dump reconstructed frame */
1618 x264_frame_dump( h, frame_psnr, "fdec.yuv" );
1623 /****************************************************************************
1624 * x264_encoder_close:
1625 ****************************************************************************/
1626 void x264_encoder_close ( x264_t *h )
1628 #ifdef DEBUG_BENCHMARK
1629 int64_t i_mtime_total = i_mtime_analyse + i_mtime_encode + i_mtime_write + i_mtime_filter + 1;
1631 int64_t i_yuv_size = 3 * h->param.i_width * h->param.i_height / 2;
1634 #ifdef DEBUG_BENCHMARK
1635 x264_log( h, X264_LOG_INFO,
1636 "analyse=%d(%lldms) encode=%d(%lldms) write=%d(%lldms) filter=%d(%lldms)\n",
1637 (int)(100*i_mtime_analyse/i_mtime_total), i_mtime_analyse/1000,
1638 (int)(100*i_mtime_encode/i_mtime_total), i_mtime_encode/1000,
1639 (int)(100*i_mtime_write/i_mtime_total), i_mtime_write/1000,
1640 (int)(100*i_mtime_filter/i_mtime_total), i_mtime_filter/1000 );
1643 /* Slices used and PSNR */
1644 for( i=0; i<5; i++ )
1646 static const int slice_order[] = { SLICE_TYPE_I, SLICE_TYPE_SI, SLICE_TYPE_P, SLICE_TYPE_SP, SLICE_TYPE_B };
1647 static const char *slice_name[] = { "P", "B", "I", "SP", "SI" };
1648 int i_slice = slice_order[i];
1650 if( h->stat.i_slice_count[i_slice] > 0 )
1652 const int i_count = h->stat.i_slice_count[i_slice];
1653 if( h->param.analyse.b_psnr )
1655 x264_log( h, X264_LOG_INFO,
1656 "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",
1657 slice_name[i_slice],
1659 (double)h->stat.i_slice_qp[i_slice] / i_count,
1660 (double)h->stat.i_slice_size[i_slice] / i_count,
1661 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,
1662 h->stat.f_psnr_average[i_slice] / i_count,
1663 x264_psnr( h->stat.i_sqe_global[i_slice], i_count * i_yuv_size ) );
1667 x264_log( h, X264_LOG_INFO,
1668 "slice %s:%-5d Avg QP:%5.2f size:%6.0f\n",
1669 slice_name[i_slice],
1671 (double)h->stat.i_slice_qp[i_slice] / i_count,
1672 (double)h->stat.i_slice_size[i_slice] / i_count );
1678 if( h->stat.i_slice_count[SLICE_TYPE_I] > 0 )
1680 const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_I];
1681 const double i_count = h->stat.i_slice_count[SLICE_TYPE_I] * h->mb.i_mb_count / 100.0;
1682 x264_log( h, X264_LOG_INFO,
1683 "mb I I16..4: %4.1f%% %4.1f%% %4.1f%%\n",
1684 i_mb_count[I_16x16]/ i_count,
1685 i_mb_count[I_8x8] / i_count,
1686 i_mb_count[I_4x4] / i_count );
1688 if( h->stat.i_slice_count[SLICE_TYPE_P] > 0 )
1690 const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_P];
1691 const int64_t *i_mb_size = h->stat.i_mb_count_size[SLICE_TYPE_P];
1692 const double i_count = h->stat.i_slice_count[SLICE_TYPE_P] * h->mb.i_mb_count / 100.0;
1693 x264_log( h, X264_LOG_INFO,
1694 "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",
1695 i_mb_count[I_16x16]/ i_count,
1696 i_mb_count[I_8x8] / i_count,
1697 i_mb_count[I_4x4] / i_count,
1698 i_mb_size[PIXEL_16x16] / (i_count*4),
1699 (i_mb_size[PIXEL_16x8] + i_mb_size[PIXEL_8x16]) / (i_count*4),
1700 i_mb_size[PIXEL_8x8] / (i_count*4),
1701 (i_mb_size[PIXEL_8x4] + i_mb_size[PIXEL_4x8]) / (i_count*4),
1702 i_mb_size[PIXEL_4x4] / (i_count*4),
1703 i_mb_count[P_SKIP] / i_count );
1705 if( h->stat.i_slice_count[SLICE_TYPE_B] > 0 )
1707 const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_B];
1708 const int64_t *i_mb_size = h->stat.i_mb_count_size[SLICE_TYPE_B];
1709 const double i_count = h->stat.i_slice_count[SLICE_TYPE_B] * h->mb.i_mb_count / 100.0;
1710 x264_log( h, X264_LOG_INFO,
1711 "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",
1712 i_mb_count[I_16x16] / i_count,
1713 i_mb_count[I_8x8] / i_count,
1714 i_mb_count[I_4x4] / i_count,
1715 i_mb_size[PIXEL_16x16] / (i_count*4),
1716 (i_mb_size[PIXEL_16x8] + i_mb_size[PIXEL_8x16]) / (i_count*4),
1717 i_mb_size[PIXEL_8x8] / (i_count*4),
1718 i_mb_count[B_DIRECT] / i_count,
1719 i_mb_count[B_SKIP] / i_count );
1722 x264_ratecontrol_summary( h );
1724 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 )
1726 const int i_count = h->stat.i_slice_count[SLICE_TYPE_I] +
1727 h->stat.i_slice_count[SLICE_TYPE_P] +
1728 h->stat.i_slice_count[SLICE_TYPE_B];
1729 float fps = (float) h->param.i_fps_num / h->param.i_fps_den;
1730 #define SUM3(p) (p[SLICE_TYPE_I] + p[SLICE_TYPE_P] + p[SLICE_TYPE_B])
1731 #define SUM3b(p,o) (p[SLICE_TYPE_I][o] + p[SLICE_TYPE_P][o] + p[SLICE_TYPE_B][o])
1732 float f_bitrate = fps * SUM3(h->stat.i_slice_size) / i_count / 125;
1734 if( h->param.analyse.b_transform_8x8 )
1736 int64_t i_i8x8 = SUM3b( h->stat.i_mb_count, I_8x8 );
1737 int64_t i_intra = i_i8x8 + SUM3b( h->stat.i_mb_count, I_4x4 )
1738 + SUM3b( h->stat.i_mb_count, I_16x16 );
1739 x264_log( h, X264_LOG_INFO, "8x8 transform intra:%.1f%% inter:%.1f%%\n",
1740 100. * i_i8x8 / i_intra,
1741 100. * h->stat.i_mb_count_8x8dct[1] / h->stat.i_mb_count_8x8dct[0] );
1744 if( h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_AUTO
1745 && h->stat.i_slice_count[SLICE_TYPE_B] )
1747 x264_log( h, X264_LOG_INFO, "direct mvs spatial:%.1f%% temporal:%.1f%%\n",
1748 h->stat.i_direct_frames[1] * 100. / h->stat.i_slice_count[SLICE_TYPE_B],
1749 h->stat.i_direct_frames[0] * 100. / h->stat.i_slice_count[SLICE_TYPE_B] );
1752 if( h->param.i_frame_reference > 1 )
1755 for( i_slice = 0; i_slice < 2; i_slice++ )
1761 for( i = 0; i < h->param.i_frame_reference; i++ )
1762 if( h->stat.i_mb_count_ref[i_slice][i] )
1764 i_den += h->stat.i_mb_count_ref[i_slice][i];
1769 for( i = 0; i <= i_max; i++ )
1770 p += sprintf( p, " %4.1f%%", 100. * h->stat.i_mb_count_ref[i_slice][i] / i_den );
1771 x264_log( h, X264_LOG_INFO, "ref %c %s\n", i_slice==SLICE_TYPE_P ? 'P' : 'B', buf );
1775 if( h->param.analyse.b_psnr )
1776 x264_log( h, X264_LOG_INFO,
1777 "PSNR Mean Y:%6.3f U:%6.3f V:%6.3f Avg:%6.3f Global:%6.3f kb/s:%.2f\n",
1778 SUM3( h->stat.f_psnr_mean_y ) / i_count,
1779 SUM3( h->stat.f_psnr_mean_u ) / i_count,
1780 SUM3( h->stat.f_psnr_mean_v ) / i_count,
1781 SUM3( h->stat.f_psnr_average ) / i_count,
1782 x264_psnr( SUM3( h->stat.i_sqe_global ), i_count * i_yuv_size ),
1785 x264_log( h, X264_LOG_INFO, "kb/s:%.1f\n", f_bitrate );
1789 for( i = 0; i < X264_BFRAME_MAX + 3; i++ )
1791 if( h->frames.current[i] ) x264_frame_delete( h->frames.current[i] );
1792 if( h->frames.next[i] ) x264_frame_delete( h->frames.next[i] );
1793 if( h->frames.unused[i] ) x264_frame_delete( h->frames.unused[i] );
1796 for( i = 0; i < h->frames.i_max_dpb; i++ )
1798 x264_frame_delete( h->frames.reference[i] );
1802 x264_ratecontrol_delete( h );
1805 if( h->param.rc.psz_stat_out )
1806 free( h->param.rc.psz_stat_out );
1807 if( h->param.rc.psz_stat_in )
1808 free( h->param.rc.psz_stat_in );
1809 if( h->param.rc.psz_rc_eq )
1810 free( h->param.rc.psz_rc_eq );
1812 x264_macroblock_cache_end( h );
1813 x264_free( h->out.p_bitstream );
1814 for( i = 1; i < h->param.i_threads; i++ )
1815 x264_free( h->thread[i] );