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 *****************************************************************************/
31 #define pthread_t HANDLE
32 #define pthread_create(t,u,f,d) *(t)=CreateThread(NULL,0,f,d,0,NULL)
33 #define pthread_join(t,s) { WaitForSingleObject(t,INFINITE); \
35 #define HAVE_PTHREAD 1
37 #elif defined(SYS_BEOS)
38 #include <kernel/OS.h>
39 #define pthread_t thread_id
40 #define pthread_create(t,u,f,d) { *(t)=spawn_thread(f,"",10,d); \
41 resume_thread(*(t)); }
42 #define pthread_join(t,s) wait_for_thread(t,(long*)s)
43 #define HAVE_PTHREAD 1
49 #include "common/common.h"
50 #include "common/cpu.h"
54 #include "ratecontrol.h"
55 #include "macroblock.h"
58 #include "common/visualize.h"
61 //#define DEBUG_MB_TYPE
62 //#define DEBUG_DUMP_FRAME
63 //#define DEBUG_BENCHMARK
65 #ifdef DEBUG_BENCHMARK
66 static int64_t i_mtime_encode_frame = 0;
67 static int64_t i_mtime_analyse = 0;
68 static int64_t i_mtime_encode = 0;
69 static int64_t i_mtime_write = 0;
70 static int64_t i_mtime_filter = 0;
71 #define TIMER_START( d ) \
73 int64_t d##start = x264_mdate();
75 #define TIMER_STOP( d ) \
76 d += x264_mdate() - d##start;\
79 #define TIMER_START( d )
80 #define TIMER_STOP( d )
83 #define NALU_OVERHEAD 5 // startcode + NAL type costs 5 bytes per frame
85 /****************************************************************************
87 ******************************* x264 libs **********************************
89 ****************************************************************************/
90 static float x264_psnr( int64_t i_sqe, int64_t i_size )
92 double f_mse = (double)i_sqe / ((double)65025.0 * (double)i_size);
93 if( f_mse <= 0.0000000001 ) /* Max 100dB */
96 return (float)(-10.0 * log( f_mse ) / log( 10.0 ));
99 #ifdef DEBUG_DUMP_FRAME
100 static void x264_frame_dump( x264_t *h, x264_frame_t *fr, char *name )
102 FILE * f = fopen( name, "a" );
105 fseek( f, 0, SEEK_END );
107 for( i = 0; i < fr->i_plane; i++ )
109 for( y = 0; y < h->param.i_height / ( i == 0 ? 1 : 2 ); y++ )
111 fwrite( &fr->plane[i][y*fr->i_stride[i]], 1, h->param.i_width / ( i == 0 ? 1 : 2 ), f );
119 /* Fill "default" values */
120 static void x264_slice_header_init( x264_t *h, x264_slice_header_t *sh,
121 x264_sps_t *sps, x264_pps_t *pps,
122 int i_type, int i_idr_pic_id, int i_frame, int i_qp )
124 x264_param_t *param = &h->param;
127 /* First we fill all field */
133 sh->i_last_mb = h->sps->i_mb_width * h->sps->i_mb_height;
134 sh->i_pps_id = pps->i_id;
136 sh->i_frame_num = i_frame;
138 sh->b_field_pic = 0; /* Not field support for now */
139 sh->b_bottom_field = 1; /* not yet used */
141 sh->i_idr_pic_id = i_idr_pic_id;
143 /* poc stuff, fixed later */
145 sh->i_delta_poc_bottom = 0;
146 sh->i_delta_poc[0] = 0;
147 sh->i_delta_poc[1] = 0;
149 sh->i_redundant_pic_cnt = 0;
151 sh->b_direct_spatial_mv_pred = ( param->analyse.i_direct_mv_pred == X264_DIRECT_PRED_SPATIAL );
153 sh->b_num_ref_idx_override = 0;
154 sh->i_num_ref_idx_l0_active = 1;
155 sh->i_num_ref_idx_l1_active = 1;
157 sh->b_ref_pic_list_reordering_l0 = h->b_ref_reorder[0];
158 sh->b_ref_pic_list_reordering_l1 = h->b_ref_reorder[1];
160 /* If the ref list isn't in the default order, construct reordering header */
161 /* List1 reordering isn't needed yet */
162 if( sh->b_ref_pic_list_reordering_l0 )
164 int pred_frame_num = i_frame;
165 for( i = 0; i < h->i_ref0; i++ )
167 int diff = h->fref0[i]->i_frame_num - pred_frame_num;
169 x264_log( h, X264_LOG_ERROR, "diff frame num == 0\n" );
170 sh->ref_pic_list_order[0][i].idc = ( diff > 0 );
171 sh->ref_pic_list_order[0][i].arg = abs( diff ) - 1;
172 pred_frame_num = h->fref0[i]->i_frame_num;
176 sh->i_cabac_init_idc = param->i_cabac_init_idc;
179 sh->i_qp_delta = i_qp - pps->i_pic_init_qp;
180 sh->b_sp_for_swidth = 0;
183 /* If effective qp <= 15, deblocking would have no effect anyway */
184 if( param->b_deblocking_filter
185 && ( h->mb.b_variable_qp
186 || 15 < i_qp + X264_MAX(param->i_deblocking_filter_alphac0, param->i_deblocking_filter_beta) ) )
188 sh->i_disable_deblocking_filter_idc = 0;
192 sh->i_disable_deblocking_filter_idc = 1;
194 sh->i_alpha_c0_offset = param->i_deblocking_filter_alphac0 << 1;
195 sh->i_beta_offset = param->i_deblocking_filter_beta << 1;
198 static void x264_slice_header_write( bs_t *s, x264_slice_header_t *sh, int i_nal_ref_idc )
202 bs_write_ue( s, sh->i_first_mb );
203 bs_write_ue( s, sh->i_type + 5 ); /* same type things */
204 bs_write_ue( s, sh->i_pps_id );
205 bs_write( s, sh->sps->i_log2_max_frame_num, sh->i_frame_num );
207 if( sh->i_idr_pic_id >= 0 ) /* NAL IDR */
209 bs_write_ue( s, sh->i_idr_pic_id );
212 if( sh->sps->i_poc_type == 0 )
214 bs_write( s, sh->sps->i_log2_max_poc_lsb, sh->i_poc_lsb );
215 if( sh->pps->b_pic_order && !sh->b_field_pic )
217 bs_write_se( s, sh->i_delta_poc_bottom );
220 else if( sh->sps->i_poc_type == 1 && !sh->sps->b_delta_pic_order_always_zero )
222 bs_write_se( s, sh->i_delta_poc[0] );
223 if( sh->pps->b_pic_order && !sh->b_field_pic )
225 bs_write_se( s, sh->i_delta_poc[1] );
229 if( sh->pps->b_redundant_pic_cnt )
231 bs_write_ue( s, sh->i_redundant_pic_cnt );
234 if( sh->i_type == SLICE_TYPE_B )
236 bs_write1( s, sh->b_direct_spatial_mv_pred );
238 if( sh->i_type == SLICE_TYPE_P || sh->i_type == SLICE_TYPE_SP || sh->i_type == SLICE_TYPE_B )
240 bs_write1( s, sh->b_num_ref_idx_override );
241 if( sh->b_num_ref_idx_override )
243 bs_write_ue( s, sh->i_num_ref_idx_l0_active - 1 );
244 if( sh->i_type == SLICE_TYPE_B )
246 bs_write_ue( s, sh->i_num_ref_idx_l1_active - 1 );
251 /* ref pic list reordering */
252 if( sh->i_type != SLICE_TYPE_I )
254 bs_write1( s, sh->b_ref_pic_list_reordering_l0 );
255 if( sh->b_ref_pic_list_reordering_l0 )
257 for( i = 0; i < sh->i_num_ref_idx_l0_active; i++ )
259 bs_write_ue( s, sh->ref_pic_list_order[0][i].idc );
260 bs_write_ue( s, sh->ref_pic_list_order[0][i].arg );
266 if( sh->i_type == SLICE_TYPE_B )
268 bs_write1( s, sh->b_ref_pic_list_reordering_l1 );
269 if( sh->b_ref_pic_list_reordering_l1 )
271 for( i = 0; i < sh->i_num_ref_idx_l1_active; i++ )
273 bs_write_ue( s, sh->ref_pic_list_order[1][i].idc );
274 bs_write_ue( s, sh->ref_pic_list_order[1][i].arg );
280 if( ( sh->pps->b_weighted_pred && ( sh->i_type == SLICE_TYPE_P || sh->i_type == SLICE_TYPE_SP ) ) ||
281 ( sh->pps->b_weighted_bipred == 1 && sh->i_type == SLICE_TYPE_B ) )
286 if( i_nal_ref_idc != 0 )
288 if( sh->i_idr_pic_id >= 0 )
290 bs_write1( s, 0 ); /* no output of prior pics flag */
291 bs_write1( s, 0 ); /* long term reference flag */
295 bs_write1( s, 0 ); /* adaptive_ref_pic_marking_mode_flag */
299 if( sh->pps->b_cabac && sh->i_type != SLICE_TYPE_I )
301 bs_write_ue( s, sh->i_cabac_init_idc );
303 bs_write_se( s, sh->i_qp_delta ); /* slice qp delta */
305 if( sh->pps->b_deblocking_filter_control )
307 bs_write_ue( s, sh->i_disable_deblocking_filter_idc );
308 if( sh->i_disable_deblocking_filter_idc != 1 )
310 bs_write_se( s, sh->i_alpha_c0_offset >> 1 );
311 bs_write_se( s, sh->i_beta_offset >> 1 );
316 /****************************************************************************
318 ****************************************************************************
319 ****************************** External API*********************************
320 ****************************************************************************
322 ****************************************************************************/
324 static int x264_validate_parameters( x264_t *h )
326 if( h->param.i_width <= 0 || h->param.i_height <= 0 )
328 x264_log( h, X264_LOG_ERROR, "invalid width x height (%dx%d)\n",
329 h->param.i_width, h->param.i_height );
333 if( h->param.i_width % 2 || h->param.i_height % 2 )
335 x264_log( h, X264_LOG_ERROR, "width or height not divisible by 2 (%dx%d)\n",
336 h->param.i_width, h->param.i_height );
339 if( h->param.i_csp != X264_CSP_I420 )
341 x264_log( h, X264_LOG_ERROR, "invalid CSP (only I420 supported)\n" );
345 h->param.i_threads = x264_clip3( h->param.i_threads, 1, X264_SLICE_MAX );
346 h->param.i_threads = X264_MIN( h->param.i_threads, (h->param.i_height + 15) / 16 );
348 if( h->param.i_threads > 1 )
350 x264_log( h, X264_LOG_WARNING, "not compiled with pthread support!\n");
351 x264_log( h, X264_LOG_WARNING, "multislicing anyway, but you won't see any speed gain.\n" );
355 if( h->param.rc.b_cbr )
356 h->param.rc.i_rf_constant = 0;
357 if( h->param.rc.i_rf_constant > 0 )
358 h->param.rc.i_qp_constant = h->param.rc.i_rf_constant;
359 h->param.rc.i_rf_constant = x264_clip3( h->param.rc.i_rf_constant, 0, 51 );
360 h->param.rc.i_qp_constant = x264_clip3( h->param.rc.i_qp_constant, 0, 51 );
361 if( !h->param.rc.b_cbr && h->param.rc.i_qp_constant == 0 )
363 h->mb.b_lossless = 1;
364 h->param.analyse.b_transform_8x8 = 0;
365 h->param.i_cqm_preset = X264_CQM_FLAT;
366 h->param.psz_cqm_file = NULL;
367 h->param.rc.f_ip_factor = 1;
368 h->param.rc.f_pb_factor = 1;
369 h->param.analyse.b_psnr = 0;
370 h->param.analyse.i_chroma_qp_offset = 0;
371 h->param.analyse.i_trellis = 0;
372 h->param.analyse.b_fast_pskip = 0;
373 h->param.analyse.i_noise_reduction = 0;
376 if( ( h->param.i_width % 16 || h->param.i_height % 16 ) && !h->mb.b_lossless )
378 x264_log( h, X264_LOG_WARNING,
379 "width or height not divisible by 16 (%dx%d), compression will suffer.\n",
380 h->param.i_width, h->param.i_height );
383 h->param.i_frame_reference = x264_clip3( h->param.i_frame_reference, 1, 16 );
384 if( h->param.i_keyint_max <= 0 )
385 h->param.i_keyint_max = 1;
386 h->param.i_keyint_min = x264_clip3( h->param.i_keyint_min, 1, h->param.i_keyint_max/2+1 );
388 h->param.i_bframe = x264_clip3( h->param.i_bframe, 0, X264_BFRAME_MAX );
389 h->param.i_bframe_bias = x264_clip3( h->param.i_bframe_bias, -90, 100 );
390 h->param.b_bframe_pyramid = h->param.b_bframe_pyramid && h->param.i_bframe > 1;
391 h->param.b_bframe_adaptive = h->param.b_bframe_adaptive && h->param.i_bframe > 0;
393 h->param.i_deblocking_filter_alphac0 = x264_clip3( h->param.i_deblocking_filter_alphac0, -6, 6 );
394 h->param.i_deblocking_filter_beta = x264_clip3( h->param.i_deblocking_filter_beta, -6, 6 );
396 h->param.i_cabac_init_idc = x264_clip3( h->param.i_cabac_init_idc, 0, 2 );
398 if( h->param.i_cqm_preset < X264_CQM_FLAT || h->param.i_cqm_preset > X264_CQM_CUSTOM )
399 h->param.i_cqm_preset = X264_CQM_FLAT;
401 if( h->param.analyse.i_me_method < X264_ME_DIA ||
402 h->param.analyse.i_me_method > X264_ME_ESA )
403 h->param.analyse.i_me_method = X264_ME_HEX;
404 if( h->param.analyse.i_me_range < 4 )
405 h->param.analyse.i_me_range = 4;
406 if( h->param.analyse.i_me_range > 16 && h->param.analyse.i_me_method <= X264_ME_HEX )
407 h->param.analyse.i_me_range = 16;
408 h->param.analyse.i_subpel_refine = x264_clip3( h->param.analyse.i_subpel_refine, 1, 6 );
409 h->param.analyse.b_bframe_rdo = h->param.analyse.b_bframe_rdo && h->param.analyse.i_subpel_refine >= 6;
410 h->param.analyse.b_mixed_references = h->param.analyse.b_mixed_references && h->param.i_frame_reference > 1;
411 h->param.analyse.inter &= X264_ANALYSE_PSUB16x16|X264_ANALYSE_PSUB8x8|X264_ANALYSE_BSUB16x16|
412 X264_ANALYSE_I4x4|X264_ANALYSE_I8x8;
413 h->param.analyse.intra &= X264_ANALYSE_I4x4|X264_ANALYSE_I8x8;
414 if( !(h->param.analyse.inter & X264_ANALYSE_PSUB16x16) )
415 h->param.analyse.inter &= ~X264_ANALYSE_PSUB8x8;
416 if( !h->param.analyse.b_transform_8x8 )
418 h->param.analyse.inter &= ~X264_ANALYSE_I8x8;
419 h->param.analyse.intra &= ~X264_ANALYSE_I8x8;
421 h->param.analyse.i_chroma_qp_offset = x264_clip3(h->param.analyse.i_chroma_qp_offset, -12, 12);
422 if( !h->param.b_cabac )
423 h->param.analyse.i_trellis = 0;
424 h->param.analyse.i_trellis = x264_clip3( h->param.analyse.i_trellis, 0, 2 );
425 h->param.analyse.i_noise_reduction = x264_clip3( h->param.analyse.i_noise_reduction, 0, 1<<16 );
428 const x264_level_t *l = x264_levels;
429 while( l->level_idc != 0 && l->level_idc != h->param.i_level_idc )
431 if( l->level_idc == 0 )
433 x264_log( h, X264_LOG_ERROR, "invalid level_idc: %d\n", h->param.i_level_idc );
436 if( h->param.analyse.i_mv_range <= 0 )
437 h->param.analyse.i_mv_range = l->mv_range;
439 h->param.analyse.i_mv_range = x264_clip3(h->param.analyse.i_mv_range, 32, 2048);
442 if( h->param.rc.f_qblur < 0 )
443 h->param.rc.f_qblur = 0;
444 if( h->param.rc.f_complexity_blur < 0 )
445 h->param.rc.f_complexity_blur = 0;
447 /* ensure the booleans are 0 or 1 so they can be used in math */
448 #define BOOLIFY(x) h->param.x = !!h->param.x
450 BOOLIFY( b_deblocking_filter );
451 BOOLIFY( analyse.b_transform_8x8 );
452 BOOLIFY( analyse.b_weighted_bipred );
453 BOOLIFY( analyse.b_bidir_me );
454 BOOLIFY( analyse.b_chroma_me );
455 BOOLIFY( analyse.b_fast_pskip );
457 BOOLIFY( rc.b_stat_write );
458 BOOLIFY( rc.b_stat_read );
464 /****************************************************************************
466 ****************************************************************************/
467 x264_t *x264_encoder_open ( x264_param_t *param )
469 x264_t *h = x264_malloc( sizeof( x264_t ) );
472 memset( h, 0, sizeof( x264_t ) );
474 /* Create a copy of param */
475 memcpy( &h->param, param, sizeof( x264_param_t ) );
477 if( x264_validate_parameters( h ) < 0 )
483 if( h->param.psz_cqm_file )
484 if( x264_cqm_parse_file( h, h->param.psz_cqm_file ) < 0 )
490 if( h->param.rc.psz_stat_out )
491 h->param.rc.psz_stat_out = strdup( h->param.rc.psz_stat_out );
492 if( h->param.rc.psz_stat_in )
493 h->param.rc.psz_stat_in = strdup( h->param.rc.psz_stat_in );
494 if( h->param.rc.psz_rc_eq )
495 h->param.rc.psz_rc_eq = strdup( h->param.rc.psz_rc_eq );
498 if( h->param.vui.i_sar_width > 0 && h->param.vui.i_sar_height > 0 )
500 int i_w = param->vui.i_sar_width;
501 int i_h = param->vui.i_sar_height;
502 int a = i_w, b = i_h;
514 while( i_w > 65535 || i_h > 65535 )
520 h->param.vui.i_sar_width = 0;
521 h->param.vui.i_sar_height = 0;
522 if( i_w == 0 || i_h == 0 )
524 x264_log( h, X264_LOG_ERROR, "cannot create valid sample aspect ratio\n" );
526 else if( i_w == i_h )
528 x264_log( h, X264_LOG_INFO, "no need for a SAR\n" );
532 x264_log( h, X264_LOG_INFO, "using SAR=%d/%d\n", i_w, i_h );
533 h->param.vui.i_sar_width = i_w;
534 h->param.vui.i_sar_height = i_h;
541 h->out.i_bitstream = X264_MAX( 1000000, h->param.i_width * h->param.i_height * 1.7
542 * ( h->param.rc.b_cbr ? pow( 0.5, h->param.rc.i_qp_min )
543 : pow( 0.5, h->param.rc.i_qp_constant ) * X264_MAX( 1, h->param.rc.f_ip_factor )));
544 h->out.p_bitstream = x264_malloc( h->out.i_bitstream );
550 h->sps = &h->sps_array[0];
551 x264_sps_init( h->sps, 0, &h->param );
553 h->pps = &h->pps_array[0];
554 x264_pps_init( h->pps, 0, &h->param, h->sps);
556 x264_validate_levels( h );
560 h->mb.i_mb_count = h->sps->i_mb_width * h->sps->i_mb_height;
563 h->frames.i_delay = h->param.i_bframe;
564 h->frames.i_max_ref0 = h->param.i_frame_reference;
565 h->frames.i_max_ref1 = h->sps->vui.i_num_reorder_frames;
566 h->frames.i_max_dpb = h->sps->vui.i_max_dec_frame_buffering + 1;
567 h->frames.b_have_lowres = !h->param.rc.b_stat_read
568 && ( h->param.rc.b_cbr || h->param.rc.i_rf_constant || h->param.b_bframe_adaptive );
570 for( i = 0; i < X264_BFRAME_MAX + 3; i++ )
572 h->frames.current[i] = NULL;
573 h->frames.next[i] = NULL;
574 h->frames.unused[i] = NULL;
576 for( i = 0; i < 1 + h->frames.i_delay; i++ )
578 h->frames.unused[i] = x264_frame_new( h );
580 for( i = 0; i < h->frames.i_max_dpb; i++ )
582 h->frames.reference[i] = x264_frame_new( h );
584 h->frames.reference[h->frames.i_max_dpb] = NULL;
585 h->frames.i_last_idr = - h->param.i_keyint_max;
586 h->frames.i_input = 0;
587 h->frames.last_nonb = NULL;
592 h->fdec = h->frames.reference[0];
594 x264_macroblock_cache_init( h );
597 /* init CPU functions */
598 x264_predict_16x16_init( h->param.cpu, h->predict_16x16 );
599 x264_predict_8x8c_init( h->param.cpu, h->predict_8x8c );
600 x264_predict_8x8_init( h->param.cpu, h->predict_8x8 );
601 x264_predict_4x4_init( h->param.cpu, h->predict_4x4 );
603 x264_pixel_init( h->param.cpu, &h->pixf );
604 x264_dct_init( h->param.cpu, &h->dctf );
605 x264_mc_init( h->param.cpu, &h->mc );
606 x264_csp_init( h->param.cpu, h->param.i_csp, &h->csp );
607 x264_quant_init( h, h->param.cpu, &h->quantf );
608 x264_deblock_init( h->param.cpu, &h->loopf );
610 memcpy( h->pixf.mbcmp,
611 ( h->mb.b_lossless || h->param.analyse.i_subpel_refine <= 1 ) ? h->pixf.sad : h->pixf.satd,
612 sizeof(h->pixf.mbcmp) );
615 if( x264_ratecontrol_new( h ) < 0 )
618 x264_log( h, X264_LOG_INFO, "using cpu capabilities %s%s%s%s%s%s\n",
619 param->cpu&X264_CPU_MMX ? "MMX " : "",
620 param->cpu&X264_CPU_MMXEXT ? "MMXEXT " : "",
621 param->cpu&X264_CPU_SSE ? "SSE " : "",
622 param->cpu&X264_CPU_SSE2 ? "SSE2 " : "",
623 param->cpu&X264_CPU_3DNOW ? "3DNow! " : "",
624 param->cpu&X264_CPU_ALTIVEC ? "Altivec " : "" );
627 for( i = 1; i < param->i_threads; i++ )
628 h->thread[i] = x264_malloc( sizeof(x264_t) );
633 /****************************************************************************
634 * x264_encoder_reconfig:
635 ****************************************************************************/
636 int x264_encoder_reconfig( x264_t *h, x264_param_t *param )
638 h->param.i_bframe_bias = param->i_bframe_bias;
639 h->param.i_deblocking_filter_alphac0 = param->i_deblocking_filter_alphac0;
640 h->param.i_deblocking_filter_beta = param->i_deblocking_filter_beta;
641 h->param.analyse.i_me_method = param->analyse.i_me_method;
642 h->param.analyse.i_me_range = param->analyse.i_me_range;
643 h->param.analyse.i_subpel_refine = param->analyse.i_subpel_refine;
644 h->param.analyse.i_trellis = param->analyse.i_trellis;
645 h->param.analyse.intra = param->analyse.intra;
646 h->param.analyse.inter = param->analyse.inter;
647 if( h->sps->b_direct8x8_inference && h->param.i_bframe
648 && h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_TEMPORAL )
649 h->param.analyse.inter &= ~X264_ANALYSE_PSUB8x8;
651 memcpy( h->pixf.mbcmp,
652 ( h->mb.b_lossless || h->param.analyse.i_subpel_refine <= 1 ) ? h->pixf.sad : h->pixf.satd,
653 sizeof(h->pixf.mbcmp) );
655 return x264_validate_parameters( h );
659 static void x264_nal_start( x264_t *h, int i_type, int i_ref_idc )
661 x264_nal_t *nal = &h->out.nal[h->out.i_nal];
663 nal->i_ref_idc = i_ref_idc;
664 nal->i_type = i_type;
666 bs_align_0( &h->out.bs ); /* not needed */
669 nal->p_payload= &h->out.p_bitstream[bs_pos( &h->out.bs) / 8];
671 static void x264_nal_end( x264_t *h )
673 x264_nal_t *nal = &h->out.nal[h->out.i_nal];
675 bs_align_0( &h->out.bs ); /* not needed */
677 nal->i_payload = &h->out.p_bitstream[bs_pos( &h->out.bs)/8] - nal->p_payload;
682 /****************************************************************************
683 * x264_encoder_headers:
684 ****************************************************************************/
685 int x264_encoder_headers( x264_t *h, x264_nal_t **pp_nal, int *pi_nal )
687 /* init bitstream context */
689 bs_init( &h->out.bs, h->out.p_bitstream, h->out.i_bitstream );
691 /* Put SPS and PPS */
692 if( h->i_frame == 0 )
694 /* identify ourself */
695 x264_nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
696 x264_sei_version_write( h, &h->out.bs );
699 /* generate sequence parameters */
700 x264_nal_start( h, NAL_SPS, NAL_PRIORITY_HIGHEST );
701 x264_sps_write( &h->out.bs, h->sps );
704 /* generate picture parameters */
705 x264_nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
706 x264_pps_write( &h->out.bs, h->pps );
710 *pi_nal = h->out.i_nal;
711 *pp_nal = &h->out.nal[0];
717 static void x264_frame_put( x264_frame_t *list[X264_BFRAME_MAX], x264_frame_t *frame )
720 while( list[i] ) i++;
724 static void x264_frame_push( x264_frame_t *list[X264_BFRAME_MAX], x264_frame_t *frame )
727 while( list[i] ) i++;
733 static x264_frame_t *x264_frame_get( x264_frame_t *list[X264_BFRAME_MAX+1] )
735 x264_frame_t *frame = list[0];
737 for( i = 0; list[i]; i++ )
742 static void x264_frame_sort( x264_frame_t *list[X264_BFRAME_MAX+1], int b_dts )
747 for( i = 0; list[i+1]; i++ )
749 int dtype = list[i]->i_type - list[i+1]->i_type;
750 int dtime = list[i]->i_frame - list[i+1]->i_frame;
751 int swap = b_dts ? dtype > 0 || ( dtype == 0 && dtime > 0 )
755 XCHG( x264_frame_t*, list[i], list[i+1] );
761 #define x264_frame_sort_dts(list) x264_frame_sort(list, 1)
762 #define x264_frame_sort_pts(list) x264_frame_sort(list, 0)
764 static inline void x264_reference_build_list( x264_t *h, int i_poc, int i_slice_type )
769 /* build ref list 0/1 */
772 for( i = 1; i < h->frames.i_max_dpb; i++ )
774 if( h->frames.reference[i]->i_poc >= 0 )
776 if( h->frames.reference[i]->i_poc < i_poc )
778 h->fref0[h->i_ref0++] = h->frames.reference[i];
780 else if( h->frames.reference[i]->i_poc > i_poc )
782 h->fref1[h->i_ref1++] = h->frames.reference[i];
787 /* Order ref0 from higher to lower poc */
791 for( i = 0; i < h->i_ref0 - 1; i++ )
793 if( h->fref0[i]->i_poc < h->fref0[i+1]->i_poc )
795 XCHG( x264_frame_t*, h->fref0[i], h->fref0[i+1] );
801 /* Order ref1 from lower to higher poc (bubble sort) for B-frame */
805 for( i = 0; i < h->i_ref1 - 1; i++ )
807 if( h->fref1[i]->i_poc > h->fref1[i+1]->i_poc )
809 XCHG( x264_frame_t*, h->fref1[i], h->fref1[i+1] );
816 /* In the standard, a P-frame's ref list is sorted by frame_num.
817 * We use POC, but check whether explicit reordering is needed */
818 h->b_ref_reorder[0] =
819 h->b_ref_reorder[1] = 0;
820 if( i_slice_type == SLICE_TYPE_P )
822 for( i = 0; i < h->i_ref0 - 1; i++ )
823 if( h->fref0[i]->i_frame_num < h->fref0[i+1]->i_frame_num )
825 h->b_ref_reorder[0] = 1;
830 h->i_ref1 = X264_MIN( h->i_ref1, h->frames.i_max_ref1 );
831 h->i_ref0 = X264_MIN( h->i_ref0, h->frames.i_max_ref0 );
832 h->i_ref0 = X264_MIN( h->i_ref0, 16 - h->i_ref1 );
835 static inline void x264_reference_update( x264_t *h )
839 /* apply deblocking filter to the current decoded picture */
840 if( !h->sh.i_disable_deblocking_filter_idc )
842 TIMER_START( i_mtime_filter );
843 x264_frame_deblocking_filter( h, h->sh.i_type );
844 TIMER_STOP( i_mtime_filter );
847 x264_frame_expand_border( h->fdec );
849 /* create filtered images */
850 x264_frame_filter( h->param.cpu, h->fdec );
852 /* expand border of filtered images */
853 x264_frame_expand_border_filtered( h->fdec );
855 /* move lowres copy of the image to the ref frame */
856 for( i = 0; i < 4; i++)
857 XCHG( uint8_t*, h->fdec->lowres[i], h->fenc->lowres[i] );
859 /* adaptive B decision needs a pointer, since it can't use the ref lists */
860 if( h->sh.i_type != SLICE_TYPE_B )
861 h->frames.last_nonb = h->fdec;
863 /* move frame in the buffer */
864 h->fdec = h->frames.reference[h->frames.i_max_dpb-1];
865 for( i = h->frames.i_max_dpb-1; i > 0; i-- )
867 h->frames.reference[i] = h->frames.reference[i-1];
869 h->frames.reference[0] = h->fdec;
872 static inline void x264_reference_reset( x264_t *h )
876 /* reset ref pictures */
877 for( i = 1; i < h->frames.i_max_dpb; i++ )
879 h->frames.reference[i]->i_poc = -1;
881 h->frames.reference[0]->i_poc = 0;
884 static inline void x264_slice_init( x264_t *h, int i_nal_type, int i_slice_type, int i_global_qp )
886 /* ------------------------ Create slice header ----------------------- */
887 if( i_nal_type == NAL_SLICE_IDR )
889 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 );
892 h->i_idr_pic_id = ( h->i_idr_pic_id + 1 ) % 65536;
896 x264_slice_header_init( h, &h->sh, h->sps, h->pps, i_slice_type, -1, h->i_frame_num - 1, i_global_qp );
898 /* always set the real higher num of ref frame used */
899 h->sh.b_num_ref_idx_override = 1;
900 h->sh.i_num_ref_idx_l0_active = h->i_ref0 <= 0 ? 1 : h->i_ref0;
901 h->sh.i_num_ref_idx_l1_active = h->i_ref1 <= 0 ? 1 : h->i_ref1;
904 h->fdec->i_frame_num = h->sh.i_frame_num;
906 if( h->sps->i_poc_type == 0 )
908 h->sh.i_poc_lsb = h->fdec->i_poc & ( (1 << h->sps->i_log2_max_poc_lsb) - 1 );
909 h->sh.i_delta_poc_bottom = 0; /* XXX won't work for field */
911 else if( h->sps->i_poc_type == 1 )
913 /* FIXME TODO FIXME */
917 /* Nothing to do ? */
920 x264_macroblock_slice_init( h );
923 static int x264_slice_write( x264_t *h )
930 memset( &h->stat.frame, 0, sizeof(h->stat.frame) );
933 x264_nal_start( h, h->i_nal_type, h->i_nal_ref_idc );
936 x264_slice_header_write( &h->out.bs, &h->sh, h->i_nal_ref_idc );
937 if( h->param.b_cabac )
939 /* alignment needed */
940 bs_align_1( &h->out.bs );
943 x264_cabac_context_init( &h->cabac, h->sh.i_type, h->sh.i_qp, h->sh.i_cabac_init_idc );
944 x264_cabac_encode_init ( &h->cabac, &h->out.bs );
946 h->mb.i_last_qp = h->sh.i_qp;
947 h->mb.i_last_dqp = 0;
949 for( mb_xy = h->sh.i_first_mb, i_skip = 0; mb_xy < h->sh.i_last_mb; mb_xy++ )
951 const int i_mb_y = mb_xy / h->sps->i_mb_width;
952 const int i_mb_x = mb_xy % h->sps->i_mb_width;
954 int mb_spos = bs_pos(&h->out.bs);
957 x264_macroblock_cache_load( h, i_mb_x, i_mb_y );
959 /* analyse parameters
960 * Slice I: choose I_4x4 or I_16x16 mode
961 * Slice P: choose between using P mode or intra (4x4 or 16x16)
963 TIMER_START( i_mtime_analyse );
964 x264_macroblock_analyse( h );
965 TIMER_STOP( i_mtime_analyse );
967 /* encode this macrobock -> be carefull it can change the mb type to P_SKIP if needed */
968 TIMER_START( i_mtime_encode );
969 x264_macroblock_encode( h );
970 TIMER_STOP( i_mtime_encode );
972 TIMER_START( i_mtime_write );
973 if( h->param.b_cabac )
975 if( mb_xy > h->sh.i_first_mb )
976 x264_cabac_encode_terminal( &h->cabac, 0 );
978 if( IS_SKIP( h->mb.i_type ) )
979 x264_cabac_mb_skip( h, 1 );
982 if( h->sh.i_type != SLICE_TYPE_I )
983 x264_cabac_mb_skip( h, 0 );
984 x264_macroblock_write_cabac( h, &h->cabac );
989 if( IS_SKIP( h->mb.i_type ) )
993 if( h->sh.i_type != SLICE_TYPE_I )
995 bs_write_ue( &h->out.bs, i_skip ); /* skip run */
998 x264_macroblock_write_cavlc( h, &h->out.bs );
1001 TIMER_STOP( i_mtime_write );
1004 if( h->param.b_visualize )
1005 x264_visualize_mb( h );
1009 x264_macroblock_cache_save( h );
1011 /* accumulate mb stats */
1012 h->stat.frame.i_mb_count[h->mb.i_type]++;
1013 if( !IS_SKIP(h->mb.i_type) && !IS_INTRA(h->mb.i_type) && !IS_DIRECT(h->mb.i_type) )
1015 if( h->mb.i_partition != D_8x8 )
1016 h->stat.frame.i_mb_count_size[ x264_mb_partition_pixel_table[ h->mb.i_partition ] ] += 4;
1018 for( i = 0; i < 4; i++ )
1019 h->stat.frame.i_mb_count_size[ x264_mb_partition_pixel_table[ h->mb.i_sub_partition[i] ] ] ++;
1020 if( h->param.i_frame_reference > 1 )
1022 for( i = 0; i < 4; i++ )
1024 int i_ref = h->mb.cache.ref[0][ x264_scan8[4*i] ];
1026 h->stat.frame.i_mb_count_ref[i_ref] ++;
1030 if( h->mb.i_cbp_luma && !IS_INTRA(h->mb.i_type) )
1032 h->stat.frame.i_mb_count_8x8dct[0] ++;
1033 h->stat.frame.i_mb_count_8x8dct[1] += h->mb.b_transform_8x8;
1036 if( h->mb.b_variable_qp )
1037 x264_ratecontrol_mb(h, bs_pos(&h->out.bs) - mb_spos);
1040 if( h->param.b_cabac )
1043 x264_cabac_encode_terminal( &h->cabac, 1 );
1045 else if( i_skip > 0 )
1047 bs_write_ue( &h->out.bs, i_skip ); /* last skip run */
1050 if( h->param.b_cabac )
1052 x264_cabac_encode_flush( &h->cabac );
1057 /* rbsp_slice_trailing_bits */
1058 bs_rbsp_trailing( &h->out.bs );
1063 /* Compute misc bits */
1064 h->stat.frame.i_misc_bits = bs_pos( &h->out.bs )
1066 - h->stat.frame.i_itex_bits
1067 - h->stat.frame.i_ptex_bits
1068 - h->stat.frame.i_hdr_bits;
1073 static inline int x264_slices_write( x264_t *h )
1078 if( h->param.b_visualize )
1079 x264_visualize_init( h );
1082 if( h->param.i_threads == 1 )
1084 x264_slice_write( h );
1085 i_frame_size = h->out.nal[h->out.i_nal-1].i_payload;
1089 int i_nal = h->out.i_nal;
1090 int i_bs_size = h->out.i_bitstream / h->param.i_threads;
1092 /* duplicate contexts */
1093 for( i = 0; i < h->param.i_threads; i++ )
1095 x264_t *t = h->thread[i];
1098 memcpy( t, h, sizeof(x264_t) );
1099 t->out.p_bitstream += i*i_bs_size;
1100 bs_init( &t->out.bs, t->out.p_bitstream, i_bs_size );
1102 t->sh.i_first_mb = (i * h->sps->i_mb_height / h->param.i_threads) * h->sps->i_mb_width;
1103 t->sh.i_last_mb = ((i+1) * h->sps->i_mb_height / h->param.i_threads) * h->sps->i_mb_width;
1104 t->out.i_nal = i_nal + i;
1110 pthread_t handles[X264_SLICE_MAX];
1112 for( i = 0; i < h->param.i_threads; i++ )
1113 pthread_create( &handles[i], NULL, (void*)x264_slice_write, (void*)h->thread[i] );
1114 for( i = 0; i < h->param.i_threads; i++ )
1115 pthread_join( handles[i], &status );
1118 for( i = 0; i < h->param.i_threads; i++ )
1119 x264_slice_write( h->thread[i] );
1122 /* merge contexts */
1123 i_frame_size = h->out.nal[i_nal].i_payload;
1124 for( i = 1; i < h->param.i_threads; i++ )
1127 x264_t *t = h->thread[i];
1128 h->out.nal[i_nal+i] = t->out.nal[i_nal+i];
1129 i_frame_size += t->out.nal[i_nal+i].i_payload;
1130 // all entries in stat.frame are ints
1131 for( j = 0; j < sizeof(h->stat.frame) / sizeof(int); j++ )
1132 ((int*)&h->stat.frame)[j] += ((int*)&t->stat.frame)[j];
1134 h->out.i_nal = i_nal + h->param.i_threads;
1138 if( h->param.b_visualize )
1140 x264_visualize_show( h );
1141 x264_visualize_close( h );
1145 return i_frame_size;
1148 /****************************************************************************
1149 * x264_encoder_encode:
1150 * XXX: i_poc : is the poc of the current given picture
1151 * i_frame : is the number of the frame being coded
1152 * ex: type frame poc
1160 ****************************************************************************/
1161 int x264_encoder_encode( x264_t *h,
1162 x264_nal_t **pp_nal, int *pi_nal,
1163 x264_picture_t *pic_in,
1164 x264_picture_t *pic_out )
1166 x264_frame_t *frame_psnr = h->fdec; /* just to keep the current decoded frame for psnr calculation */
1176 char psz_message[80];
1183 /* ------------------- Setup new frame from picture -------------------- */
1184 TIMER_START( i_mtime_encode_frame );
1185 if( pic_in != NULL )
1187 /* 1: Copy the picture to a frame and move it to a buffer */
1188 x264_frame_t *fenc = x264_frame_get( h->frames.unused );
1190 x264_frame_copy_picture( h, fenc, pic_in );
1192 if( h->param.i_width % 16 || h->param.i_height % 16 )
1193 x264_frame_expand_border_mod16( h, fenc );
1195 fenc->i_frame = h->frames.i_input++;
1197 x264_frame_put( h->frames.next, fenc );
1199 if( h->frames.b_have_lowres )
1200 x264_frame_init_lowres( h->param.cpu, fenc );
1202 if( h->frames.i_input <= h->frames.i_delay )
1204 /* Nothing yet to encode */
1205 /* waiting for filling bframe buffer */
1206 pic_out->i_type = X264_TYPE_AUTO;
1211 if( h->frames.current[0] == NULL )
1214 /* 2: Select frame types */
1215 if( h->frames.next[0] == NULL )
1218 x264_slicetype_decide( h );
1220 /* 3: move some B-frames and 1 non-B to encode queue */
1221 while( IS_X264_TYPE_B( h->frames.next[bframes]->i_type ) )
1223 x264_frame_put( h->frames.current, x264_frame_get( &h->frames.next[bframes] ) );
1224 /* FIXME: when max B-frames > 3, BREF may no longer be centered after GOP closing */
1225 if( h->param.b_bframe_pyramid && bframes > 1 )
1227 x264_frame_t *mid = x264_frame_get( &h->frames.next[bframes/2] );
1228 mid->i_type = X264_TYPE_BREF;
1229 x264_frame_put( h->frames.current, mid );
1233 x264_frame_put( h->frames.current, x264_frame_get( h->frames.next ) );
1235 TIMER_STOP( i_mtime_encode_frame );
1237 /* ------------------- Get frame to be encoded ------------------------- */
1238 /* 4: get picture to encode */
1239 h->fenc = x264_frame_get( h->frames.current );
1240 if( h->fenc == NULL )
1242 /* Nothing yet to encode (ex: waiting for I/P with B frames) */
1243 /* waiting for filling bframe buffer */
1244 pic_out->i_type = X264_TYPE_AUTO;
1250 if( h->fenc->i_type == X264_TYPE_IDR )
1252 h->frames.i_last_idr = h->fenc->i_frame;
1255 /* ------------------- Setup frame context ----------------------------- */
1256 /* 5: Init data dependant of frame type */
1257 TIMER_START( i_mtime_encode_frame );
1258 if( h->fenc->i_type == X264_TYPE_IDR )
1260 /* reset ref pictures */
1261 x264_reference_reset( h );
1263 i_nal_type = NAL_SLICE_IDR;
1264 i_nal_ref_idc = NAL_PRIORITY_HIGHEST;
1265 i_slice_type = SLICE_TYPE_I;
1267 else if( h->fenc->i_type == X264_TYPE_I )
1269 i_nal_type = NAL_SLICE;
1270 i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
1271 i_slice_type = SLICE_TYPE_I;
1273 else if( h->fenc->i_type == X264_TYPE_P )
1275 i_nal_type = NAL_SLICE;
1276 i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
1277 i_slice_type = SLICE_TYPE_P;
1279 else if( h->fenc->i_type == X264_TYPE_BREF )
1281 i_nal_type = NAL_SLICE;
1282 i_nal_ref_idc = NAL_PRIORITY_HIGH; /* maybe add MMCO to forget it? -> low */
1283 i_slice_type = SLICE_TYPE_B;
1287 i_nal_type = NAL_SLICE;
1288 i_nal_ref_idc = NAL_PRIORITY_DISPOSABLE;
1289 i_slice_type = SLICE_TYPE_B;
1293 h->fenc->i_poc = 2 * (h->fenc->i_frame - h->frames.i_last_idr);
1294 h->fdec->i_type = h->fenc->i_type;
1295 h->fdec->i_frame = h->fenc->i_frame;
1296 h->fenc->b_kept_as_ref =
1297 h->fdec->b_kept_as_ref = i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE;
1301 /* ------------------- Init ----------------------------- */
1302 /* build ref list 0/1 */
1303 x264_reference_build_list( h, h->fdec->i_poc, i_slice_type );
1305 /* Init the rate control */
1306 x264_ratecontrol_start( h, i_slice_type, h->fenc->i_qpplus1 );
1307 i_global_qp = x264_ratecontrol_qp( h );
1309 pic_out->i_qpplus1 =
1310 h->fdec->i_qpplus1 = i_global_qp + 1;
1312 if( i_slice_type == SLICE_TYPE_B )
1313 x264_macroblock_bipred_init( h );
1315 if( h->fenc->b_kept_as_ref )
1318 /* ------------------------ Create slice header ----------------------- */
1319 x264_slice_init( h, i_nal_type, i_slice_type, i_global_qp );
1321 /* ---------------------- Write the bitstream -------------------------- */
1322 /* Init bitstream context */
1324 bs_init( &h->out.bs, h->out.p_bitstream, h->out.i_bitstream );
1329 if(i_slice_type == SLICE_TYPE_I)
1331 else if(i_slice_type == SLICE_TYPE_P)
1333 else if(i_slice_type == SLICE_TYPE_B)
1338 x264_nal_start(h, NAL_AUD, NAL_PRIORITY_DISPOSABLE);
1339 bs_write(&h->out.bs, 3, pic_type);
1340 bs_rbsp_trailing(&h->out.bs);
1344 h->i_nal_type = i_nal_type;
1345 h->i_nal_ref_idc = i_nal_ref_idc;
1347 /* Write SPS and PPS */
1348 if( i_nal_type == NAL_SLICE_IDR && h->param.b_repeat_headers )
1350 if( h->fenc->i_frame == 0 )
1352 /* identify ourself */
1353 x264_nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
1354 x264_sei_version_write( h, &h->out.bs );
1358 /* generate sequence parameters */
1359 x264_nal_start( h, NAL_SPS, NAL_PRIORITY_HIGHEST );
1360 x264_sps_write( &h->out.bs, h->sps );
1363 /* generate picture parameters */
1364 x264_nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
1365 x264_pps_write( &h->out.bs, h->pps );
1370 i_frame_size = x264_slices_write( h );
1372 /* restore CPU state (before using float again) */
1373 x264_cpu_restore( h->param.cpu );
1375 if( i_slice_type == SLICE_TYPE_P && !h->param.rc.b_stat_read
1376 && h->param.i_scenecut_threshold >= 0 )
1378 const int *mbs = h->stat.frame.i_mb_count;
1379 int i_mb_i = mbs[I_16x16] + mbs[I_8x8] + mbs[I_4x4];
1380 int i_mb_p = mbs[P_L0] + mbs[P_8x8];
1381 int i_mb_s = mbs[P_SKIP];
1382 int i_mb = h->sps->i_mb_width * h->sps->i_mb_height;
1383 int64_t i_inter_cost = h->stat.frame.i_inter_cost;
1384 int64_t i_intra_cost = h->stat.frame.i_intra_cost;
1387 int i_gop_size = h->fenc->i_frame - h->frames.i_last_idr;
1388 float f_thresh_max = h->param.i_scenecut_threshold / 100.0;
1389 /* magic numbers pulled out of thin air */
1390 float f_thresh_min = f_thresh_max * h->param.i_keyint_min
1391 / ( h->param.i_keyint_max * 4 );
1392 if( h->param.i_keyint_min == h->param.i_keyint_max )
1393 f_thresh_min= f_thresh_max;
1395 /* macroblock_analyse() doesn't further analyse skipped mbs,
1396 * so we have to guess their cost */
1398 i_intra_cost = i_intra_cost * i_mb / (i_mb - i_mb_s);
1400 if( i_gop_size < h->param.i_keyint_min / 4 )
1401 f_bias = f_thresh_min / 4;
1402 else if( i_gop_size <= h->param.i_keyint_min )
1403 f_bias = f_thresh_min * i_gop_size / h->param.i_keyint_min;
1406 f_bias = f_thresh_min
1407 + ( f_thresh_max - f_thresh_min )
1408 * ( i_gop_size - h->param.i_keyint_min )
1409 / ( h->param.i_keyint_max - h->param.i_keyint_min );
1411 f_bias = X264_MIN( f_bias, 1.0 );
1413 /* Bad P will be reencoded as I */
1414 if( i_mb_s < i_mb &&
1415 i_inter_cost >= (1.0 - f_bias) * i_intra_cost )
1419 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",
1421 (double)i_intra_cost, (double)i_inter_cost,
1422 (double)i_inter_cost / i_intra_cost,
1424 i_mb_i, i_mb_p, i_mb_s );
1426 /* Restore frame num */
1429 for( b = 0; h->frames.current[b] && IS_X264_TYPE_B( h->frames.current[b]->i_type ); b++ );
1432 /* If using B-frames, force GOP to be closed.
1433 * Even if this frame is going to be I and not IDR, forcing a
1434 * P-frame before the scenecut will probably help compression.
1436 * We don't yet know exactly which frame is the scene cut, so
1437 * we can't assign an I-frame. Instead, change the previous
1438 * B-frame to P, and rearrange coding order. */
1440 if( h->param.b_bframe_adaptive || b > 1 )
1441 h->fenc->i_type = X264_TYPE_AUTO;
1442 x264_frame_sort_pts( h->frames.current );
1443 x264_frame_push( h->frames.next, h->fenc );
1444 h->fenc = h->frames.current[b-1];
1445 h->frames.current[b-1] = NULL;
1446 h->fenc->i_type = X264_TYPE_P;
1447 x264_frame_sort_dts( h->frames.current );
1449 /* Do IDR if needed */
1450 else if( i_gop_size >= h->param.i_keyint_min )
1457 /* Reinit field of fenc */
1458 h->fenc->i_type = X264_TYPE_IDR;
1461 /* Put enqueued frames back in the pool */
1462 while( (tmp = x264_frame_get( h->frames.current ) ) != NULL )
1463 x264_frame_put( h->frames.next, tmp );
1464 x264_frame_sort_pts( h->frames.next );
1468 h->fenc->i_type = X264_TYPE_I;
1474 /* End bitstream, set output */
1475 *pi_nal = h->out.i_nal;
1476 *pp_nal = h->out.nal;
1478 /* Set output picture properties */
1479 if( i_slice_type == SLICE_TYPE_I )
1480 pic_out->i_type = i_nal_type == NAL_SLICE_IDR ? X264_TYPE_IDR : X264_TYPE_I;
1481 else if( i_slice_type == SLICE_TYPE_P )
1482 pic_out->i_type = X264_TYPE_P;
1484 pic_out->i_type = X264_TYPE_B;
1485 pic_out->i_pts = h->fenc->i_pts;
1487 pic_out->img.i_plane = h->fdec->i_plane;
1488 for(i = 0; i < 4; i++){
1489 pic_out->img.i_stride[i] = h->fdec->i_stride[i];
1490 pic_out->img.plane[i] = h->fdec->plane[i];
1493 /* ---------------------- Update encoder state ------------------------- */
1495 /* handle references */
1496 if( i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE )
1498 x264_reference_update( h );
1501 /* increase frame count */
1504 /* restore CPU state (before using float again) */
1505 /* XXX: not needed? (done above) */
1506 x264_cpu_restore( h->param.cpu );
1509 x264_ratecontrol_end( h, i_frame_size * 8 );
1511 x264_frame_put( h->frames.unused, h->fenc );
1513 x264_noise_reduction_update( h );
1515 TIMER_STOP( i_mtime_encode_frame );
1517 /* ---------------------- Compute/Print statistics --------------------- */
1519 h->stat.i_slice_count[i_slice_type]++;
1520 h->stat.i_slice_size[i_slice_type] += i_frame_size + NALU_OVERHEAD;
1521 h->stat.i_slice_qp[i_slice_type] += i_global_qp;
1523 for( i = 0; i < 19; i++ )
1524 h->stat.i_mb_count[h->sh.i_type][i] += h->stat.frame.i_mb_count[i];
1525 for( i = 0; i < 2; i++ )
1526 h->stat.i_mb_count_8x8dct[i] += h->stat.frame.i_mb_count_8x8dct[i];
1527 if( h->sh.i_type != SLICE_TYPE_I )
1529 for( i = 0; i < 7; i++ )
1530 h->stat.i_mb_count_size[h->sh.i_type][i] += h->stat.frame.i_mb_count_size[i];
1531 for( i = 0; i < 16; i++ )
1532 h->stat.i_mb_count_ref[h->sh.i_type][i] += h->stat.frame.i_mb_count_ref[i];
1535 if( h->param.analyse.b_psnr )
1537 int64_t i_sqe_y, i_sqe_u, i_sqe_v;
1540 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 );
1541 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);
1542 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);
1543 x264_cpu_restore( h->param.cpu );
1545 h->stat.i_sqe_global[i_slice_type] += i_sqe_y + i_sqe_u + i_sqe_v;
1546 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 );
1547 h->stat.f_psnr_mean_y[i_slice_type] += x264_psnr( i_sqe_y, h->param.i_width * h->param.i_height );
1548 h->stat.f_psnr_mean_u[i_slice_type] += x264_psnr( i_sqe_u, h->param.i_width * h->param.i_height / 4 );
1549 h->stat.f_psnr_mean_v[i_slice_type] += x264_psnr( i_sqe_v, h->param.i_width * h->param.i_height / 4 );
1551 snprintf( psz_message, 80, " PSNR Y:%2.2f U:%2.2f V:%2.2f",
1552 x264_psnr( i_sqe_y, h->param.i_width * h->param.i_height ),
1553 x264_psnr( i_sqe_u, h->param.i_width * h->param.i_height / 4),
1554 x264_psnr( i_sqe_v, h->param.i_width * h->param.i_height / 4) );
1555 psz_message[79] = '\0';
1559 psz_message[0] = '\0';
1562 x264_log( h, X264_LOG_DEBUG,
1563 "frame=%4d QP=%i NAL=%d Slice:%c Poc:%-3d I:%-4d P:%-4d SKIP:%-4d size=%d bytes%s\n",
1567 i_slice_type == SLICE_TYPE_I ? 'I' : (i_slice_type == SLICE_TYPE_P ? 'P' : 'B' ),
1569 h->stat.frame.i_mb_count_i,
1570 h->stat.frame.i_mb_count_p,
1571 h->stat.frame.i_mb_count_skip,
1576 #ifdef DEBUG_MB_TYPE
1578 static const char mb_chars[] = { 'i', 'i', 'I', 'C', 'P', '8', 'S',
1579 'D', '<', 'X', 'B', 'X', '>', 'B', 'B', 'B', 'B', '8', 'S' };
1581 for( mb_xy = 0; mb_xy < h->sps->i_mb_width * h->sps->i_mb_height; mb_xy++ )
1583 if( h->mb.type[mb_xy] < 19 && h->mb.type[mb_xy] >= 0 )
1584 fprintf( stderr, "%c ", mb_chars[ h->mb.type[mb_xy] ] );
1586 fprintf( stderr, "? " );
1588 if( (mb_xy+1) % h->sps->i_mb_width == 0 )
1589 fprintf( stderr, "\n" );
1594 #ifdef DEBUG_DUMP_FRAME
1595 /* Dump reconstructed frame */
1596 x264_frame_dump( h, frame_psnr, "fdec.yuv" );
1601 /****************************************************************************
1602 * x264_encoder_close:
1603 ****************************************************************************/
1604 void x264_encoder_close ( x264_t *h )
1606 #ifdef DEBUG_BENCHMARK
1607 int64_t i_mtime_total = i_mtime_analyse + i_mtime_encode + i_mtime_write + i_mtime_filter + 1;
1609 int64_t i_yuv_size = 3 * h->param.i_width * h->param.i_height / 2;
1612 #ifdef DEBUG_BENCHMARK
1613 x264_log( h, X264_LOG_INFO,
1614 "analyse=%d(%lldms) encode=%d(%lldms) write=%d(%lldms) filter=%d(%lldms)\n",
1615 (int)(100*i_mtime_analyse/i_mtime_total), i_mtime_analyse/1000,
1616 (int)(100*i_mtime_encode/i_mtime_total), i_mtime_encode/1000,
1617 (int)(100*i_mtime_write/i_mtime_total), i_mtime_write/1000,
1618 (int)(100*i_mtime_filter/i_mtime_total), i_mtime_filter/1000 );
1621 /* Slices used and PSNR */
1622 for( i=0; i<5; i++ )
1624 static const int slice_order[] = { SLICE_TYPE_I, SLICE_TYPE_SI, SLICE_TYPE_P, SLICE_TYPE_SP, SLICE_TYPE_B };
1625 static const char *slice_name[] = { "P", "B", "I", "SP", "SI" };
1626 int i_slice = slice_order[i];
1628 if( h->stat.i_slice_count[i_slice] > 0 )
1630 const int i_count = h->stat.i_slice_count[i_slice];
1631 if( h->param.analyse.b_psnr )
1633 x264_log( h, X264_LOG_INFO,
1634 "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",
1635 slice_name[i_slice],
1637 (double)h->stat.i_slice_qp[i_slice] / i_count,
1638 (double)h->stat.i_slice_size[i_slice] / i_count,
1639 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,
1640 h->stat.f_psnr_average[i_slice] / i_count,
1641 x264_psnr( h->stat.i_sqe_global[i_slice], i_count * i_yuv_size ) );
1645 x264_log( h, X264_LOG_INFO,
1646 "slice %s:%-5d Avg QP:%5.2f size:%6.0f\n",
1647 slice_name[i_slice],
1649 (double)h->stat.i_slice_qp[i_slice] / i_count,
1650 (double)h->stat.i_slice_size[i_slice] / i_count );
1656 if( h->stat.i_slice_count[SLICE_TYPE_I] > 0 )
1658 const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_I];
1659 const double i_count = h->stat.i_slice_count[SLICE_TYPE_I] * h->mb.i_mb_count / 100.0;
1660 x264_log( h, X264_LOG_INFO,
1661 "mb I I16..4: %4.1f%% %4.1f%% %4.1f%%\n",
1662 i_mb_count[I_16x16]/ i_count,
1663 i_mb_count[I_8x8] / i_count,
1664 i_mb_count[I_4x4] / i_count );
1666 if( h->stat.i_slice_count[SLICE_TYPE_P] > 0 )
1668 const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_P];
1669 const int64_t *i_mb_size = h->stat.i_mb_count_size[SLICE_TYPE_P];
1670 const double i_count = h->stat.i_slice_count[SLICE_TYPE_P] * h->mb.i_mb_count / 100.0;
1671 x264_log( h, X264_LOG_INFO,
1672 "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",
1673 i_mb_count[I_16x16]/ i_count,
1674 i_mb_count[I_8x8] / i_count,
1675 i_mb_count[I_4x4] / i_count,
1676 i_mb_size[PIXEL_16x16] / (i_count*4),
1677 (i_mb_size[PIXEL_16x8] + i_mb_size[PIXEL_8x16]) / (i_count*4),
1678 i_mb_size[PIXEL_8x8] / (i_count*4),
1679 (i_mb_size[PIXEL_8x4] + i_mb_size[PIXEL_4x8]) / (i_count*4),
1680 i_mb_size[PIXEL_4x4] / (i_count*4),
1681 i_mb_count[P_SKIP] / i_count );
1683 if( h->stat.i_slice_count[SLICE_TYPE_B] > 0 )
1685 const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_B];
1686 const int64_t *i_mb_size = h->stat.i_mb_count_size[SLICE_TYPE_B];
1687 const double i_count = h->stat.i_slice_count[SLICE_TYPE_B] * h->mb.i_mb_count / 100.0;
1688 x264_log( h, X264_LOG_INFO,
1689 "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",
1690 i_mb_count[I_16x16] / i_count,
1691 i_mb_count[I_8x8] / i_count,
1692 i_mb_count[I_4x4] / i_count,
1693 i_mb_size[PIXEL_16x16] / (i_count*4),
1694 (i_mb_size[PIXEL_16x8] + i_mb_size[PIXEL_8x16]) / (i_count*4),
1695 i_mb_size[PIXEL_8x8] / (i_count*4),
1696 i_mb_count[B_DIRECT] / i_count,
1697 i_mb_count[B_SKIP] / i_count );
1700 x264_ratecontrol_summary( h );
1702 if( h->stat.i_slice_count[SLICE_TYPE_I] + h->stat.i_slice_count[SLICE_TYPE_P] + h->stat.i_slice_count[SLICE_TYPE_B] > 0 )
1704 const int i_count = h->stat.i_slice_count[SLICE_TYPE_I] +
1705 h->stat.i_slice_count[SLICE_TYPE_P] +
1706 h->stat.i_slice_count[SLICE_TYPE_B];
1707 float fps = (float) h->param.i_fps_num / h->param.i_fps_den;
1708 #define SUM3(p) (p[SLICE_TYPE_I] + p[SLICE_TYPE_P] + p[SLICE_TYPE_B])
1709 #define SUM3b(p,o) (p[SLICE_TYPE_I][o] + p[SLICE_TYPE_P][o] + p[SLICE_TYPE_B][o])
1710 float f_bitrate = fps * SUM3(h->stat.i_slice_size) / i_count / 125;
1712 if( h->param.analyse.b_transform_8x8 )
1714 int64_t i_i8x8 = SUM3b( h->stat.i_mb_count, I_8x8 );
1715 int64_t i_intra = i_i8x8 + SUM3b( h->stat.i_mb_count, I_4x4 )
1716 + SUM3b( h->stat.i_mb_count, I_16x16 );
1717 x264_log( h, X264_LOG_INFO, "8x8 transform intra:%.1f%% inter:%.1f%%\n",
1718 100. * i_i8x8 / i_intra,
1719 100. * h->stat.i_mb_count_8x8dct[1] / h->stat.i_mb_count_8x8dct[0] );
1722 if( h->param.i_frame_reference > 1 )
1725 for( i_slice = 0; i_slice < 2; i_slice++ )
1731 for( i = 0; i < h->param.i_frame_reference; i++ )
1732 if( h->stat.i_mb_count_ref[i_slice][i] )
1734 i_den += h->stat.i_mb_count_ref[i_slice][i];
1739 for( i = 0; i <= i_max; i++ )
1740 p += sprintf( p, " %4.1f%%", 100. * h->stat.i_mb_count_ref[i_slice][i] / i_den );
1741 x264_log( h, X264_LOG_INFO, "ref %c %s\n", i_slice==SLICE_TYPE_P ? 'P' : 'B', buf );
1745 if( h->param.analyse.b_psnr )
1746 x264_log( h, X264_LOG_INFO,
1747 "PSNR Mean Y:%6.3f U:%6.3f V:%6.3f Avg:%6.3f Global:%6.3f kb/s:%.2f\n",
1748 SUM3( h->stat.f_psnr_mean_y ) / i_count,
1749 SUM3( h->stat.f_psnr_mean_u ) / i_count,
1750 SUM3( h->stat.f_psnr_mean_v ) / i_count,
1751 SUM3( h->stat.f_psnr_average ) / i_count,
1752 x264_psnr( SUM3( h->stat.i_sqe_global ), i_count * i_yuv_size ),
1755 x264_log( h, X264_LOG_INFO, "kb/s:%.1f\n", f_bitrate );
1759 for( i = 0; i < X264_BFRAME_MAX + 3; i++ )
1761 if( h->frames.current[i] ) x264_frame_delete( h->frames.current[i] );
1762 if( h->frames.next[i] ) x264_frame_delete( h->frames.next[i] );
1763 if( h->frames.unused[i] ) x264_frame_delete( h->frames.unused[i] );
1766 for( i = 0; i < h->frames.i_max_dpb; i++ )
1768 x264_frame_delete( h->frames.reference[i] );
1772 x264_ratecontrol_delete( h );
1775 if( h->param.rc.psz_stat_out )
1776 free( h->param.rc.psz_stat_out );
1777 if( h->param.rc.psz_stat_in )
1778 free( h->param.rc.psz_stat_in );
1779 if( h->param.rc.psz_rc_eq )
1780 free( h->param.rc.psz_rc_eq );
1782 x264_macroblock_cache_end( h );
1783 x264_free( h->out.p_bitstream );
1784 for( i = 1; i < h->param.i_threads; i++ )
1785 x264_free( h->thread[i] );