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.i_rf_constant > 0 )
356 h->param.rc.i_qp_constant = h->param.rc.i_rf_constant;
357 h->param.rc.i_rf_constant = x264_clip3( h->param.rc.i_rf_constant, 0, 51 );
358 h->param.rc.i_qp_constant = x264_clip3( h->param.rc.i_qp_constant, 0, 51 );
359 if( !h->param.rc.b_cbr && h->param.rc.i_qp_constant == 0 )
361 h->mb.b_lossless = 1;
362 h->param.analyse.b_transform_8x8 = 0;
363 h->param.i_cqm_preset = X264_CQM_FLAT;
364 h->param.psz_cqm_file = NULL;
365 h->param.rc.f_ip_factor = 1;
366 h->param.rc.f_pb_factor = 1;
367 h->param.analyse.b_psnr = 0;
370 if( ( h->param.i_width % 16 || h->param.i_height % 16 ) && !h->mb.b_lossless )
372 x264_log( h, X264_LOG_WARNING,
373 "width or height not divisible by 16 (%dx%d), compression will suffer.\n",
374 h->param.i_width, h->param.i_height );
377 h->param.i_frame_reference = x264_clip3( h->param.i_frame_reference, 1, 16 );
378 if( h->param.i_keyint_max <= 0 )
379 h->param.i_keyint_max = 1;
380 h->param.i_keyint_min = x264_clip3( h->param.i_keyint_min, 1, h->param.i_keyint_max/2+1 );
382 h->param.i_bframe = x264_clip3( h->param.i_bframe, 0, X264_BFRAME_MAX );
383 h->param.i_bframe_bias = x264_clip3( h->param.i_bframe_bias, -90, 100 );
384 h->param.b_bframe_pyramid = h->param.b_bframe_pyramid && h->param.i_bframe > 1;
385 h->param.b_bframe_adaptive = h->param.b_bframe_adaptive && h->param.i_bframe > 0;
387 h->param.i_deblocking_filter_alphac0 = x264_clip3( h->param.i_deblocking_filter_alphac0, -6, 6 );
388 h->param.i_deblocking_filter_beta = x264_clip3( h->param.i_deblocking_filter_beta, -6, 6 );
390 h->param.i_cabac_init_idc = x264_clip3( h->param.i_cabac_init_idc, 0, 2 );
392 if( h->param.i_cqm_preset < X264_CQM_FLAT || h->param.i_cqm_preset > X264_CQM_CUSTOM )
393 h->param.i_cqm_preset = X264_CQM_FLAT;
395 if( h->param.analyse.i_me_method < X264_ME_DIA ||
396 h->param.analyse.i_me_method > X264_ME_ESA )
397 h->param.analyse.i_me_method = X264_ME_HEX;
398 if( h->param.analyse.i_me_range < 4 )
399 h->param.analyse.i_me_range = 4;
400 if( h->param.analyse.i_me_range > 16 && h->param.analyse.i_me_method <= X264_ME_HEX )
401 h->param.analyse.i_me_range = 16;
402 h->param.analyse.i_subpel_refine = x264_clip3( h->param.analyse.i_subpel_refine, 1, 6 );
403 if( !(h->param.analyse.inter & X264_ANALYSE_PSUB16x16) )
404 h->param.analyse.inter &= ~X264_ANALYSE_PSUB8x8;
405 if( !h->param.analyse.b_transform_8x8 )
407 h->param.analyse.inter &= ~X264_ANALYSE_I8x8;
408 h->param.analyse.intra &= ~X264_ANALYSE_I8x8;
410 h->param.analyse.i_chroma_qp_offset = x264_clip3(h->param.analyse.i_chroma_qp_offset, -12, 12);
411 h->param.analyse.i_mv_range = x264_clip3(h->param.analyse.i_mv_range, 32, 2048);
412 if( !h->param.b_cabac )
413 h->param.analyse.i_trellis = 0;
415 if( h->param.rc.f_qblur < 0 )
416 h->param.rc.f_qblur = 0;
417 if( h->param.rc.f_complexity_blur < 0 )
418 h->param.rc.f_complexity_blur = 0;
423 /****************************************************************************
425 ****************************************************************************/
426 x264_t *x264_encoder_open ( x264_param_t *param )
428 x264_t *h = x264_malloc( sizeof( x264_t ) );
431 memset( h, 0, sizeof( x264_t ) );
433 /* Create a copy of param */
434 memcpy( &h->param, param, sizeof( x264_param_t ) );
436 if( x264_validate_parameters( h ) < 0 )
442 if( h->param.psz_cqm_file )
443 if( x264_cqm_parse_file( h, h->param.psz_cqm_file ) < 0 )
449 if( h->param.rc.psz_stat_out )
450 h->param.rc.psz_stat_out = strdup( h->param.rc.psz_stat_out );
451 if( h->param.rc.psz_stat_in )
452 h->param.rc.psz_stat_in = strdup( h->param.rc.psz_stat_in );
453 if( h->param.rc.psz_rc_eq )
454 h->param.rc.psz_rc_eq = strdup( h->param.rc.psz_rc_eq );
457 if( h->param.vui.i_sar_width > 0 && h->param.vui.i_sar_height > 0 )
459 int i_w = param->vui.i_sar_width;
460 int i_h = param->vui.i_sar_height;
461 int a = i_w, b = i_h;
473 while( i_w > 65535 || i_h > 65535 )
479 h->param.vui.i_sar_width = 0;
480 h->param.vui.i_sar_height = 0;
481 if( i_w == 0 || i_h == 0 )
483 x264_log( h, X264_LOG_ERROR, "cannot create valid sample aspect ratio\n" );
485 else if( i_w == i_h )
487 x264_log( h, X264_LOG_INFO, "no need for a SAR\n" );
491 x264_log( h, X264_LOG_INFO, "using SAR=%d/%d\n", i_w, i_h );
492 h->param.vui.i_sar_width = i_w;
493 h->param.vui.i_sar_height = i_h;
500 h->out.i_bitstream = X264_MAX( 1000000, h->param.i_width * h->param.i_height * 1.7
501 * ( h->param.rc.b_cbr ? pow( 0.5, h->param.rc.i_qp_min )
502 : pow( 0.5, h->param.rc.i_qp_constant ) * X264_MAX( 1, h->param.rc.f_ip_factor )));
503 h->out.p_bitstream = x264_malloc( h->out.i_bitstream );
509 h->sps = &h->sps_array[0];
510 x264_sps_init( h->sps, 0, &h->param );
512 h->pps = &h->pps_array[0];
513 x264_pps_init( h->pps, 0, &h->param, h->sps);
517 h->mb.i_mb_count = h->sps->i_mb_width * h->sps->i_mb_height;
520 h->frames.i_delay = h->param.i_bframe;
521 h->frames.i_max_ref0 = h->param.i_frame_reference;
522 h->frames.i_max_ref1 = h->sps->vui.i_num_reorder_frames;
523 h->frames.i_max_dpb = h->sps->vui.i_max_dec_frame_buffering + 1;
524 h->frames.b_have_lowres = !h->param.rc.b_stat_read
525 && ( h->param.rc.b_cbr || h->param.rc.i_rf_constant || h->param.b_bframe_adaptive );
527 for( i = 0; i < X264_BFRAME_MAX + 3; i++ )
529 h->frames.current[i] = NULL;
530 h->frames.next[i] = NULL;
531 h->frames.unused[i] = NULL;
533 for( i = 0; i < 1 + h->frames.i_delay; i++ )
535 h->frames.unused[i] = x264_frame_new( h );
537 for( i = 0; i < h->frames.i_max_dpb; i++ )
539 h->frames.reference[i] = x264_frame_new( h );
541 h->frames.reference[h->frames.i_max_dpb] = NULL;
542 h->frames.i_last_idr = - h->param.i_keyint_max;
543 h->frames.i_input = 0;
544 h->frames.last_nonb = NULL;
549 h->fdec = h->frames.reference[0];
551 x264_macroblock_cache_init( h );
554 /* init CPU functions */
555 x264_predict_16x16_init( h->param.cpu, h->predict_16x16 );
556 x264_predict_8x8c_init( h->param.cpu, h->predict_8x8c );
557 x264_predict_8x8_init( h->param.cpu, h->predict_8x8 );
558 x264_predict_4x4_init( h->param.cpu, h->predict_4x4 );
560 x264_pixel_init( h->param.cpu, &h->pixf );
561 x264_dct_init( h->param.cpu, &h->dctf );
562 x264_mc_init( h->param.cpu, &h->mc );
563 x264_csp_init( h->param.cpu, h->param.i_csp, &h->csp );
564 x264_quant_init( h, h->param.cpu, &h->quantf );
565 x264_deblock_init( h->param.cpu, &h->loopf );
567 memcpy( h->pixf.mbcmp,
568 ( h->mb.b_lossless || h->param.analyse.i_subpel_refine <= 1 ) ? h->pixf.sad : h->pixf.satd,
569 sizeof(h->pixf.mbcmp) );
572 if( x264_ratecontrol_new( h ) < 0 )
575 x264_log( h, X264_LOG_INFO, "using cpu capabilities %s%s%s%s%s%s\n",
576 param->cpu&X264_CPU_MMX ? "MMX " : "",
577 param->cpu&X264_CPU_MMXEXT ? "MMXEXT " : "",
578 param->cpu&X264_CPU_SSE ? "SSE " : "",
579 param->cpu&X264_CPU_SSE2 ? "SSE2 " : "",
580 param->cpu&X264_CPU_3DNOW ? "3DNow! " : "",
581 param->cpu&X264_CPU_ALTIVEC ? "Altivec " : "" );
584 for( i = 1; i < param->i_threads; i++ )
585 h->thread[i] = x264_malloc( sizeof(x264_t) );
590 /****************************************************************************
591 * x264_encoder_reconfig:
592 ****************************************************************************/
593 int x264_encoder_reconfig( x264_t *h, x264_param_t *param )
595 h->param.i_bframe_bias = param->i_bframe_bias;
596 h->param.i_deblocking_filter_alphac0 = param->i_deblocking_filter_alphac0;
597 h->param.i_deblocking_filter_beta = param->i_deblocking_filter_beta;
598 h->param.analyse.i_me_method = param->analyse.i_me_method;
599 h->param.analyse.i_me_range = param->analyse.i_me_range;
600 h->param.analyse.i_subpel_refine = param->analyse.i_subpel_refine;
601 h->param.analyse.i_trellis = param->analyse.i_trellis;
602 h->param.analyse.intra = param->analyse.intra;
603 h->param.analyse.inter = param->analyse.inter;
604 if( h->sps->b_direct8x8_inference && h->param.i_bframe
605 && h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_TEMPORAL )
606 h->param.analyse.inter &= ~X264_ANALYSE_PSUB8x8;
608 memcpy( h->pixf.mbcmp,
609 ( h->mb.b_lossless || h->param.analyse.i_subpel_refine <= 1 ) ? h->pixf.sad : h->pixf.satd,
610 sizeof(h->pixf.mbcmp) );
612 return x264_validate_parameters( h );
616 static void x264_nal_start( x264_t *h, int i_type, int i_ref_idc )
618 x264_nal_t *nal = &h->out.nal[h->out.i_nal];
620 nal->i_ref_idc = i_ref_idc;
621 nal->i_type = i_type;
623 bs_align_0( &h->out.bs ); /* not needed */
626 nal->p_payload= &h->out.p_bitstream[bs_pos( &h->out.bs) / 8];
628 static void x264_nal_end( x264_t *h )
630 x264_nal_t *nal = &h->out.nal[h->out.i_nal];
632 bs_align_0( &h->out.bs ); /* not needed */
634 nal->i_payload = &h->out.p_bitstream[bs_pos( &h->out.bs)/8] - nal->p_payload;
639 /****************************************************************************
640 * x264_encoder_headers:
641 ****************************************************************************/
642 int x264_encoder_headers( x264_t *h, x264_nal_t **pp_nal, int *pi_nal )
644 /* init bitstream context */
646 bs_init( &h->out.bs, h->out.p_bitstream, h->out.i_bitstream );
648 /* Put SPS and PPS */
649 if( h->i_frame == 0 )
651 /* identify ourself */
652 x264_nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
653 x264_sei_version_write( &h->out.bs );
656 /* generate sequence parameters */
657 x264_nal_start( h, NAL_SPS, NAL_PRIORITY_HIGHEST );
658 x264_sps_write( &h->out.bs, h->sps );
661 /* generate picture parameters */
662 x264_nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
663 x264_pps_write( &h->out.bs, h->pps );
667 *pi_nal = h->out.i_nal;
668 *pp_nal = &h->out.nal[0];
674 static void x264_frame_put( x264_frame_t *list[X264_BFRAME_MAX], x264_frame_t *frame )
677 while( list[i] ) i++;
681 static void x264_frame_push( x264_frame_t *list[X264_BFRAME_MAX], x264_frame_t *frame )
684 while( list[i] ) i++;
690 static x264_frame_t *x264_frame_get( x264_frame_t *list[X264_BFRAME_MAX+1] )
692 x264_frame_t *frame = list[0];
694 for( i = 0; list[i]; i++ )
699 static void x264_frame_sort( x264_frame_t *list[X264_BFRAME_MAX+1], int b_dts )
704 for( i = 0; list[i+1]; i++ )
706 int dtype = list[i]->i_type - list[i+1]->i_type;
707 int dtime = list[i]->i_frame - list[i+1]->i_frame;
708 int swap = b_dts ? dtype > 0 || ( dtype == 0 && dtime > 0 )
712 XCHG( x264_frame_t*, list[i], list[i+1] );
718 #define x264_frame_sort_dts(list) x264_frame_sort(list, 1)
719 #define x264_frame_sort_pts(list) x264_frame_sort(list, 0)
721 static inline void x264_reference_build_list( x264_t *h, int i_poc, int i_slice_type )
726 /* build ref list 0/1 */
729 for( i = 1; i < h->frames.i_max_dpb; i++ )
731 if( h->frames.reference[i]->i_poc >= 0 )
733 if( h->frames.reference[i]->i_poc < i_poc )
735 h->fref0[h->i_ref0++] = h->frames.reference[i];
737 else if( h->frames.reference[i]->i_poc > i_poc )
739 h->fref1[h->i_ref1++] = h->frames.reference[i];
744 /* Order ref0 from higher to lower poc */
748 for( i = 0; i < h->i_ref0 - 1; i++ )
750 if( h->fref0[i]->i_poc < h->fref0[i+1]->i_poc )
752 XCHG( x264_frame_t*, h->fref0[i], h->fref0[i+1] );
758 /* Order ref1 from lower to higher poc (bubble sort) for B-frame */
762 for( i = 0; i < h->i_ref1 - 1; i++ )
764 if( h->fref1[i]->i_poc > h->fref1[i+1]->i_poc )
766 XCHG( x264_frame_t*, h->fref1[i], h->fref1[i+1] );
773 /* In the standard, a P-frame's ref list is sorted by frame_num.
774 * We use POC, but check whether explicit reordering is needed */
775 h->b_ref_reorder[0] =
776 h->b_ref_reorder[1] = 0;
777 if( i_slice_type == SLICE_TYPE_P )
779 for( i = 0; i < h->i_ref0 - 1; i++ )
780 if( h->fref0[i]->i_frame_num < h->fref0[i+1]->i_frame_num )
782 h->b_ref_reorder[0] = 1;
787 h->i_ref1 = X264_MIN( h->i_ref1, h->frames.i_max_ref1 );
788 h->i_ref0 = X264_MIN( h->i_ref0, h->frames.i_max_ref0 );
789 h->i_ref0 = X264_MIN( h->i_ref0, 16 - h->i_ref1 );
792 static inline void x264_reference_update( x264_t *h )
796 /* apply deblocking filter to the current decoded picture */
797 if( !h->sh.i_disable_deblocking_filter_idc )
799 TIMER_START( i_mtime_filter );
800 x264_frame_deblocking_filter( h, h->sh.i_type );
801 TIMER_STOP( i_mtime_filter );
804 x264_frame_expand_border( h->fdec );
806 /* create filtered images */
807 x264_frame_filter( h->param.cpu, h->fdec );
809 /* expand border of filtered images */
810 x264_frame_expand_border_filtered( h->fdec );
812 /* move lowres copy of the image to the ref frame */
813 for( i = 0; i < 4; i++)
814 XCHG( uint8_t*, h->fdec->lowres[i], h->fenc->lowres[i] );
816 /* adaptive B decision needs a pointer, since it can't use the ref lists */
817 if( h->sh.i_type != SLICE_TYPE_B )
818 h->frames.last_nonb = h->fdec;
820 /* move frame in the buffer */
821 h->fdec = h->frames.reference[h->frames.i_max_dpb-1];
822 for( i = h->frames.i_max_dpb-1; i > 0; i-- )
824 h->frames.reference[i] = h->frames.reference[i-1];
826 h->frames.reference[0] = h->fdec;
829 static inline void x264_reference_reset( x264_t *h )
833 /* reset ref pictures */
834 for( i = 1; i < h->frames.i_max_dpb; i++ )
836 h->frames.reference[i]->i_poc = -1;
838 h->frames.reference[0]->i_poc = 0;
841 static inline void x264_slice_init( x264_t *h, int i_nal_type, int i_slice_type, int i_global_qp )
843 /* ------------------------ Create slice header ----------------------- */
844 if( i_nal_type == NAL_SLICE_IDR )
846 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 );
849 h->i_idr_pic_id = ( h->i_idr_pic_id + 1 ) % 65536;
853 x264_slice_header_init( h, &h->sh, h->sps, h->pps, i_slice_type, -1, h->i_frame_num - 1, i_global_qp );
855 /* always set the real higher num of ref frame used */
856 h->sh.b_num_ref_idx_override = 1;
857 h->sh.i_num_ref_idx_l0_active = h->i_ref0 <= 0 ? 1 : h->i_ref0;
858 h->sh.i_num_ref_idx_l1_active = h->i_ref1 <= 0 ? 1 : h->i_ref1;
861 h->fdec->i_frame_num = h->sh.i_frame_num;
863 if( h->sps->i_poc_type == 0 )
865 h->sh.i_poc_lsb = h->fdec->i_poc & ( (1 << h->sps->i_log2_max_poc_lsb) - 1 );
866 h->sh.i_delta_poc_bottom = 0; /* XXX won't work for field */
868 else if( h->sps->i_poc_type == 1 )
870 /* FIXME TODO FIXME */
874 /* Nothing to do ? */
877 x264_macroblock_slice_init( h );
880 static int x264_slice_write( x264_t *h )
887 memset( &h->stat.frame, 0, sizeof(h->stat.frame) );
890 x264_nal_start( h, h->i_nal_type, h->i_nal_ref_idc );
893 x264_slice_header_write( &h->out.bs, &h->sh, h->i_nal_ref_idc );
894 if( h->param.b_cabac )
896 /* alignment needed */
897 bs_align_1( &h->out.bs );
900 x264_cabac_context_init( &h->cabac, h->sh.i_type, h->sh.i_qp, h->sh.i_cabac_init_idc );
901 x264_cabac_encode_init ( &h->cabac, &h->out.bs );
903 h->mb.i_last_qp = h->sh.i_qp;
904 h->mb.i_last_dqp = 0;
906 for( mb_xy = h->sh.i_first_mb, i_skip = 0; mb_xy < h->sh.i_last_mb; mb_xy++ )
908 const int i_mb_y = mb_xy / h->sps->i_mb_width;
909 const int i_mb_x = mb_xy % h->sps->i_mb_width;
911 int mb_spos = bs_pos(&h->out.bs);
914 x264_macroblock_cache_load( h, i_mb_x, i_mb_y );
916 /* analyse parameters
917 * Slice I: choose I_4x4 or I_16x16 mode
918 * Slice P: choose between using P mode or intra (4x4 or 16x16)
920 TIMER_START( i_mtime_analyse );
921 x264_macroblock_analyse( h );
922 TIMER_STOP( i_mtime_analyse );
924 /* encode this macrobock -> be carefull it can change the mb type to P_SKIP if needed */
925 TIMER_START( i_mtime_encode );
926 x264_macroblock_encode( h );
927 TIMER_STOP( i_mtime_encode );
929 TIMER_START( i_mtime_write );
930 if( h->param.b_cabac )
932 if( mb_xy > h->sh.i_first_mb )
933 x264_cabac_encode_terminal( &h->cabac, 0 );
935 if( IS_SKIP( h->mb.i_type ) )
936 x264_cabac_mb_skip( h, 1 );
939 if( h->sh.i_type != SLICE_TYPE_I )
940 x264_cabac_mb_skip( h, 0 );
941 x264_macroblock_write_cabac( h, &h->cabac );
946 if( IS_SKIP( h->mb.i_type ) )
950 if( h->sh.i_type != SLICE_TYPE_I )
952 bs_write_ue( &h->out.bs, i_skip ); /* skip run */
955 x264_macroblock_write_cavlc( h, &h->out.bs );
958 TIMER_STOP( i_mtime_write );
961 if( h->param.b_visualize )
962 x264_visualize_mb( h );
966 x264_macroblock_cache_save( h );
968 /* accumulate mb stats */
969 h->stat.frame.i_mb_count[h->mb.i_type]++;
970 if( !IS_SKIP(h->mb.i_type) && !IS_INTRA(h->mb.i_type) && !IS_DIRECT(h->mb.i_type) )
972 if( h->mb.i_partition != D_8x8 )
973 h->stat.frame.i_mb_count_size[ x264_mb_partition_pixel_table[ h->mb.i_partition ] ] += 4;
975 for( i = 0; i < 4; i++ )
976 h->stat.frame.i_mb_count_size[ x264_mb_partition_pixel_table[ h->mb.i_sub_partition[i] ] ] ++;
977 if( h->param.i_frame_reference > 1 )
979 for( i = 0; i < 4; i++ )
981 int i_ref = h->mb.cache.ref[0][ x264_scan8[4*i] ];
983 h->stat.frame.i_mb_count_ref[i_ref] ++;
987 if( h->mb.i_cbp_luma && !IS_INTRA(h->mb.i_type) )
989 h->stat.frame.i_mb_count_8x8dct[0] ++;
990 h->stat.frame.i_mb_count_8x8dct[1] += h->mb.b_transform_8x8;
993 if( h->mb.b_variable_qp )
994 x264_ratecontrol_mb(h, bs_pos(&h->out.bs) - mb_spos);
997 if( h->param.b_cabac )
1000 x264_cabac_encode_terminal( &h->cabac, 1 );
1002 else if( i_skip > 0 )
1004 bs_write_ue( &h->out.bs, i_skip ); /* last skip run */
1007 if( h->param.b_cabac )
1009 x264_cabac_encode_flush( &h->cabac );
1014 /* rbsp_slice_trailing_bits */
1015 bs_rbsp_trailing( &h->out.bs );
1020 /* Compute misc bits */
1021 h->stat.frame.i_misc_bits = bs_pos( &h->out.bs )
1023 - h->stat.frame.i_itex_bits
1024 - h->stat.frame.i_ptex_bits
1025 - h->stat.frame.i_hdr_bits;
1030 static inline int x264_slices_write( x264_t *h )
1035 if( h->param.b_visualize )
1036 x264_visualize_init( h );
1039 if( h->param.i_threads == 1 )
1041 x264_slice_write( h );
1042 i_frame_size = h->out.nal[h->out.i_nal-1].i_payload;
1046 int i_nal = h->out.i_nal;
1047 int i_bs_size = h->out.i_bitstream / h->param.i_threads;
1049 /* duplicate contexts */
1050 for( i = 0; i < h->param.i_threads; i++ )
1052 x264_t *t = h->thread[i];
1055 memcpy( t, h, sizeof(x264_t) );
1056 t->out.p_bitstream += i*i_bs_size;
1057 bs_init( &t->out.bs, t->out.p_bitstream, i_bs_size );
1059 t->sh.i_first_mb = (i * h->sps->i_mb_height / h->param.i_threads) * h->sps->i_mb_width;
1060 t->sh.i_last_mb = ((i+1) * h->sps->i_mb_height / h->param.i_threads) * h->sps->i_mb_width;
1061 t->out.i_nal = i_nal + i;
1067 pthread_t handles[X264_SLICE_MAX];
1069 for( i = 0; i < h->param.i_threads; i++ )
1070 pthread_create( &handles[i], NULL, (void*)x264_slice_write, (void*)h->thread[i] );
1071 for( i = 0; i < h->param.i_threads; i++ )
1072 pthread_join( handles[i], &status );
1075 for( i = 0; i < h->param.i_threads; i++ )
1076 x264_slice_write( h->thread[i] );
1079 /* merge contexts */
1080 i_frame_size = h->out.nal[i_nal].i_payload;
1081 for( i = 1; i < h->param.i_threads; i++ )
1084 x264_t *t = h->thread[i];
1085 h->out.nal[i_nal+i] = t->out.nal[i_nal+i];
1086 i_frame_size += t->out.nal[i_nal+i].i_payload;
1087 // all entries in stat.frame are ints
1088 for( j = 0; j < sizeof(h->stat.frame) / sizeof(int); j++ )
1089 ((int*)&h->stat.frame)[j] += ((int*)&t->stat.frame)[j];
1091 h->out.i_nal = i_nal + h->param.i_threads;
1095 if( h->param.b_visualize )
1097 x264_visualize_show( h );
1098 x264_visualize_close( h );
1102 return i_frame_size;
1105 /****************************************************************************
1106 * x264_encoder_encode:
1107 * XXX: i_poc : is the poc of the current given picture
1108 * i_frame : is the number of the frame being coded
1109 * ex: type frame poc
1117 ****************************************************************************/
1118 int x264_encoder_encode( x264_t *h,
1119 x264_nal_t **pp_nal, int *pi_nal,
1120 x264_picture_t *pic_in,
1121 x264_picture_t *pic_out )
1123 x264_frame_t *frame_psnr = h->fdec; /* just to keep the current decoded frame for psnr calculation */
1133 char psz_message[80];
1140 /* ------------------- Setup new frame from picture -------------------- */
1141 TIMER_START( i_mtime_encode_frame );
1142 if( pic_in != NULL )
1144 /* 1: Copy the picture to a frame and move it to a buffer */
1145 x264_frame_t *fenc = x264_frame_get( h->frames.unused );
1147 x264_frame_copy_picture( h, fenc, pic_in );
1149 if( h->param.i_width % 16 || h->param.i_height % 16 )
1150 x264_frame_expand_border_mod16( h, fenc );
1152 fenc->i_frame = h->frames.i_input++;
1154 x264_frame_put( h->frames.next, fenc );
1156 if( h->frames.b_have_lowres )
1157 x264_frame_init_lowres( h->param.cpu, fenc );
1159 if( h->frames.i_input <= h->frames.i_delay )
1161 /* Nothing yet to encode */
1162 /* waiting for filling bframe buffer */
1163 pic_out->i_type = X264_TYPE_AUTO;
1168 if( h->frames.current[0] == NULL )
1171 /* 2: Select frame types */
1172 if( h->frames.next[0] == NULL )
1175 x264_slicetype_decide( h );
1177 /* 3: move some B-frames and 1 non-B to encode queue */
1178 while( IS_X264_TYPE_B( h->frames.next[bframes]->i_type ) )
1180 x264_frame_put( h->frames.current, x264_frame_get( &h->frames.next[bframes] ) );
1181 /* FIXME: when max B-frames > 3, BREF may no longer be centered after GOP closing */
1182 if( h->param.b_bframe_pyramid && bframes > 1 )
1184 x264_frame_t *mid = x264_frame_get( &h->frames.next[bframes/2] );
1185 mid->i_type = X264_TYPE_BREF;
1186 x264_frame_put( h->frames.current, mid );
1190 x264_frame_put( h->frames.current, x264_frame_get( h->frames.next ) );
1192 TIMER_STOP( i_mtime_encode_frame );
1194 /* ------------------- Get frame to be encoded ------------------------- */
1195 /* 4: get picture to encode */
1196 h->fenc = x264_frame_get( h->frames.current );
1197 if( h->fenc == NULL )
1199 /* Nothing yet to encode (ex: waiting for I/P with B frames) */
1200 /* waiting for filling bframe buffer */
1201 pic_out->i_type = X264_TYPE_AUTO;
1207 if( h->fenc->i_type == X264_TYPE_IDR )
1209 h->frames.i_last_idr = h->fenc->i_frame;
1212 /* ------------------- Setup frame context ----------------------------- */
1213 /* 5: Init data dependant of frame type */
1214 TIMER_START( i_mtime_encode_frame );
1215 if( h->fenc->i_type == X264_TYPE_IDR )
1217 /* reset ref pictures */
1218 x264_reference_reset( h );
1220 i_nal_type = NAL_SLICE_IDR;
1221 i_nal_ref_idc = NAL_PRIORITY_HIGHEST;
1222 i_slice_type = SLICE_TYPE_I;
1224 else if( h->fenc->i_type == X264_TYPE_I )
1226 i_nal_type = NAL_SLICE;
1227 i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
1228 i_slice_type = SLICE_TYPE_I;
1230 else if( h->fenc->i_type == X264_TYPE_P )
1232 i_nal_type = NAL_SLICE;
1233 i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
1234 i_slice_type = SLICE_TYPE_P;
1236 else if( h->fenc->i_type == X264_TYPE_BREF )
1238 i_nal_type = NAL_SLICE;
1239 i_nal_ref_idc = NAL_PRIORITY_HIGH; /* maybe add MMCO to forget it? -> low */
1240 i_slice_type = SLICE_TYPE_B;
1244 i_nal_type = NAL_SLICE;
1245 i_nal_ref_idc = NAL_PRIORITY_DISPOSABLE;
1246 i_slice_type = SLICE_TYPE_B;
1250 h->fenc->i_poc = 2 * (h->fenc->i_frame - h->frames.i_last_idr);
1251 h->fdec->i_type = h->fenc->i_type;
1252 h->fdec->i_frame = h->fenc->i_frame;
1253 h->fenc->b_kept_as_ref =
1254 h->fdec->b_kept_as_ref = i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE;
1258 /* ------------------- Init ----------------------------- */
1259 /* build ref list 0/1 */
1260 x264_reference_build_list( h, h->fdec->i_poc, i_slice_type );
1262 /* Init the rate control */
1263 x264_ratecontrol_start( h, i_slice_type, h->fenc->i_qpplus1 );
1264 i_global_qp = x264_ratecontrol_qp( h );
1266 pic_out->i_qpplus1 =
1267 h->fdec->i_qpplus1 = i_global_qp + 1;
1269 if( i_slice_type == SLICE_TYPE_B )
1270 x264_macroblock_bipred_init( h );
1272 if( h->fenc->b_kept_as_ref )
1275 /* ------------------------ Create slice header ----------------------- */
1276 x264_slice_init( h, i_nal_type, i_slice_type, i_global_qp );
1278 /* ---------------------- Write the bitstream -------------------------- */
1279 /* Init bitstream context */
1281 bs_init( &h->out.bs, h->out.p_bitstream, h->out.i_bitstream );
1286 if(i_slice_type == SLICE_TYPE_I)
1288 else if(i_slice_type == SLICE_TYPE_P)
1290 else if(i_slice_type == SLICE_TYPE_B)
1295 x264_nal_start(h, NAL_AUD, NAL_PRIORITY_DISPOSABLE);
1296 bs_write(&h->out.bs, 3, pic_type);
1297 bs_rbsp_trailing(&h->out.bs);
1301 h->i_nal_type = i_nal_type;
1302 h->i_nal_ref_idc = i_nal_ref_idc;
1304 /* Write SPS and PPS */
1305 if( i_nal_type == NAL_SLICE_IDR )
1307 if( h->fenc->i_frame == 0 )
1309 /* identify ourself */
1310 x264_nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
1311 x264_sei_version_write( &h->out.bs );
1315 /* generate sequence parameters */
1316 x264_nal_start( h, NAL_SPS, NAL_PRIORITY_HIGHEST );
1317 x264_sps_write( &h->out.bs, h->sps );
1320 /* generate picture parameters */
1321 x264_nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
1322 x264_pps_write( &h->out.bs, h->pps );
1327 i_frame_size = x264_slices_write( h );
1329 /* restore CPU state (before using float again) */
1330 x264_cpu_restore( h->param.cpu );
1332 if( i_slice_type == SLICE_TYPE_P && !h->param.rc.b_stat_read
1333 && h->param.i_scenecut_threshold >= 0 )
1335 const int *mbs = h->stat.frame.i_mb_count;
1336 int i_mb_i = mbs[I_16x16] + mbs[I_8x8] + mbs[I_4x4];
1337 int i_mb_p = mbs[P_L0] + mbs[P_8x8];
1338 int i_mb_s = mbs[P_SKIP];
1339 int i_mb = h->sps->i_mb_width * h->sps->i_mb_height;
1340 int64_t i_inter_cost = h->stat.frame.i_inter_cost;
1341 int64_t i_intra_cost = h->stat.frame.i_intra_cost;
1344 int i_gop_size = h->fenc->i_frame - h->frames.i_last_idr;
1345 float f_thresh_max = h->param.i_scenecut_threshold / 100.0;
1346 /* magic numbers pulled out of thin air */
1347 float f_thresh_min = f_thresh_max * h->param.i_keyint_min
1348 / ( h->param.i_keyint_max * 4 );
1349 if( h->param.i_keyint_min == h->param.i_keyint_max )
1350 f_thresh_min= f_thresh_max;
1352 /* macroblock_analyse() doesn't further analyse skipped mbs,
1353 * so we have to guess their cost */
1355 i_intra_cost = i_intra_cost * i_mb / (i_mb - i_mb_s);
1357 if( i_gop_size < h->param.i_keyint_min / 4 )
1358 f_bias = f_thresh_min / 4;
1359 else if( i_gop_size <= h->param.i_keyint_min )
1360 f_bias = f_thresh_min * i_gop_size / h->param.i_keyint_min;
1363 f_bias = f_thresh_min
1364 + ( f_thresh_max - f_thresh_min )
1365 * ( i_gop_size - h->param.i_keyint_min )
1366 / ( h->param.i_keyint_max - h->param.i_keyint_min );
1368 f_bias = X264_MIN( f_bias, 1.0 );
1370 /* Bad P will be reencoded as I */
1371 if( i_mb_s < i_mb &&
1372 i_inter_cost >= (1.0 - f_bias) * i_intra_cost )
1376 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",
1378 (double)i_intra_cost, (double)i_inter_cost,
1379 (double)i_inter_cost / i_intra_cost,
1381 i_mb_i, i_mb_p, i_mb_s );
1383 /* Restore frame num */
1386 for( b = 0; h->frames.current[b] && IS_X264_TYPE_B( h->frames.current[b]->i_type ); b++ );
1389 /* If using B-frames, force GOP to be closed.
1390 * Even if this frame is going to be I and not IDR, forcing a
1391 * P-frame before the scenecut will probably help compression.
1393 * We don't yet know exactly which frame is the scene cut, so
1394 * we can't assign an I-frame. Instead, change the previous
1395 * B-frame to P, and rearrange coding order. */
1397 if( h->param.b_bframe_adaptive || b > 1 )
1398 h->fenc->i_type = X264_TYPE_AUTO;
1399 x264_frame_sort_pts( h->frames.current );
1400 x264_frame_push( h->frames.next, h->fenc );
1401 h->fenc = h->frames.current[b-1];
1402 h->frames.current[b-1] = NULL;
1403 h->fenc->i_type = X264_TYPE_P;
1404 x264_frame_sort_dts( h->frames.current );
1406 /* Do IDR if needed */
1407 else if( i_gop_size >= h->param.i_keyint_min )
1414 /* Reinit field of fenc */
1415 h->fenc->i_type = X264_TYPE_IDR;
1418 /* Put enqueued frames back in the pool */
1419 while( (tmp = x264_frame_get( h->frames.current ) ) != NULL )
1420 x264_frame_put( h->frames.next, tmp );
1421 x264_frame_sort_pts( h->frames.next );
1425 h->fenc->i_type = X264_TYPE_I;
1431 /* End bitstream, set output */
1432 *pi_nal = h->out.i_nal;
1433 *pp_nal = h->out.nal;
1435 /* Set output picture properties */
1436 if( i_slice_type == SLICE_TYPE_I )
1437 pic_out->i_type = i_nal_type == NAL_SLICE_IDR ? X264_TYPE_IDR : X264_TYPE_I;
1438 else if( i_slice_type == SLICE_TYPE_P )
1439 pic_out->i_type = X264_TYPE_P;
1441 pic_out->i_type = X264_TYPE_B;
1442 pic_out->i_pts = h->fenc->i_pts;
1444 pic_out->img.i_plane = h->fdec->i_plane;
1445 for(i = 0; i < 4; i++){
1446 pic_out->img.i_stride[i] = h->fdec->i_stride[i];
1447 pic_out->img.plane[i] = h->fdec->plane[i];
1450 /* ---------------------- Update encoder state ------------------------- */
1452 /* handle references */
1453 if( i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE )
1455 x264_reference_update( h );
1458 /* increase frame count */
1461 /* restore CPU state (before using float again) */
1462 /* XXX: not needed? (done above) */
1463 x264_cpu_restore( h->param.cpu );
1466 x264_ratecontrol_end( h, i_frame_size * 8 );
1468 x264_frame_put( h->frames.unused, h->fenc );
1470 TIMER_STOP( i_mtime_encode_frame );
1472 /* ---------------------- Compute/Print statistics --------------------- */
1474 h->stat.i_slice_count[i_slice_type]++;
1475 h->stat.i_slice_size[i_slice_type] += i_frame_size + NALU_OVERHEAD;
1476 h->stat.i_slice_qp[i_slice_type] += i_global_qp;
1478 for( i = 0; i < 19; i++ )
1479 h->stat.i_mb_count[h->sh.i_type][i] += h->stat.frame.i_mb_count[i];
1480 for( i = 0; i < 2; i++ )
1481 h->stat.i_mb_count_8x8dct[i] += h->stat.frame.i_mb_count_8x8dct[i];
1482 if( h->sh.i_type != SLICE_TYPE_I )
1484 for( i = 0; i < 7; i++ )
1485 h->stat.i_mb_count_size[h->sh.i_type][i] += h->stat.frame.i_mb_count_size[i];
1486 for( i = 0; i < 16; i++ )
1487 h->stat.i_mb_count_ref[h->sh.i_type][i] += h->stat.frame.i_mb_count_ref[i];
1490 if( h->param.analyse.b_psnr )
1492 int64_t i_sqe_y, i_sqe_u, i_sqe_v;
1495 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 );
1496 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);
1497 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);
1498 x264_cpu_restore( h->param.cpu );
1500 h->stat.i_sqe_global[i_slice_type] += i_sqe_y + i_sqe_u + i_sqe_v;
1501 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 );
1502 h->stat.f_psnr_mean_y[i_slice_type] += x264_psnr( i_sqe_y, h->param.i_width * h->param.i_height );
1503 h->stat.f_psnr_mean_u[i_slice_type] += x264_psnr( i_sqe_u, h->param.i_width * h->param.i_height / 4 );
1504 h->stat.f_psnr_mean_v[i_slice_type] += x264_psnr( i_sqe_v, h->param.i_width * h->param.i_height / 4 );
1506 snprintf( psz_message, 80, " PSNR Y:%2.2f U:%2.2f V:%2.2f",
1507 x264_psnr( i_sqe_y, h->param.i_width * h->param.i_height ),
1508 x264_psnr( i_sqe_u, h->param.i_width * h->param.i_height / 4),
1509 x264_psnr( i_sqe_v, h->param.i_width * h->param.i_height / 4) );
1510 psz_message[79] = '\0';
1514 psz_message[0] = '\0';
1517 x264_log( h, X264_LOG_DEBUG,
1518 "frame=%4d QP=%i NAL=%d Slice:%c Poc:%-3d I:%-4d P:%-4d SKIP:%-4d size=%d bytes%s\n",
1522 i_slice_type == SLICE_TYPE_I ? 'I' : (i_slice_type == SLICE_TYPE_P ? 'P' : 'B' ),
1524 h->stat.frame.i_mb_count_i,
1525 h->stat.frame.i_mb_count_p,
1526 h->stat.frame.i_mb_count_skip,
1531 #ifdef DEBUG_MB_TYPE
1533 static const char mb_chars[] = { 'i', 'i', 'I', 'C', 'P', '8', 'S',
1534 'D', '<', 'X', 'B', 'X', '>', 'B', 'B', 'B', 'B', '8', 'S' };
1536 for( mb_xy = 0; mb_xy < h->sps->i_mb_width * h->sps->i_mb_height; mb_xy++ )
1538 if( h->mb.type[mb_xy] < 19 && h->mb.type[mb_xy] >= 0 )
1539 fprintf( stderr, "%c ", mb_chars[ h->mb.type[mb_xy] ] );
1541 fprintf( stderr, "? " );
1543 if( (mb_xy+1) % h->sps->i_mb_width == 0 )
1544 fprintf( stderr, "\n" );
1549 #ifdef DEBUG_DUMP_FRAME
1550 /* Dump reconstructed frame */
1551 x264_frame_dump( h, frame_psnr, "fdec.yuv" );
1556 /****************************************************************************
1557 * x264_encoder_close:
1558 ****************************************************************************/
1559 void x264_encoder_close ( x264_t *h )
1561 #ifdef DEBUG_BENCHMARK
1562 int64_t i_mtime_total = i_mtime_analyse + i_mtime_encode + i_mtime_write + i_mtime_filter + 1;
1564 int64_t i_yuv_size = 3 * h->param.i_width * h->param.i_height / 2;
1567 #ifdef DEBUG_BENCHMARK
1568 x264_log( h, X264_LOG_INFO,
1569 "analyse=%d(%lldms) encode=%d(%lldms) write=%d(%lldms) filter=%d(%lldms)\n",
1570 (int)(100*i_mtime_analyse/i_mtime_total), i_mtime_analyse/1000,
1571 (int)(100*i_mtime_encode/i_mtime_total), i_mtime_encode/1000,
1572 (int)(100*i_mtime_write/i_mtime_total), i_mtime_write/1000,
1573 (int)(100*i_mtime_filter/i_mtime_total), i_mtime_filter/1000 );
1576 /* Slices used and PSNR */
1577 for( i=0; i<5; i++ )
1579 static const int slice_order[] = { SLICE_TYPE_I, SLICE_TYPE_SI, SLICE_TYPE_P, SLICE_TYPE_SP, SLICE_TYPE_B };
1580 static const char *slice_name[] = { "P", "B", "I", "SP", "SI" };
1581 int i_slice = slice_order[i];
1583 if( h->stat.i_slice_count[i_slice] > 0 )
1585 const int i_count = h->stat.i_slice_count[i_slice];
1586 if( h->param.analyse.b_psnr )
1588 x264_log( h, X264_LOG_INFO,
1589 "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",
1590 slice_name[i_slice],
1592 (double)h->stat.i_slice_qp[i_slice] / i_count,
1593 (double)h->stat.i_slice_size[i_slice] / i_count,
1594 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,
1595 h->stat.f_psnr_average[i_slice] / i_count,
1596 x264_psnr( h->stat.i_sqe_global[i_slice], i_count * i_yuv_size ) );
1600 x264_log( h, X264_LOG_INFO,
1601 "slice %s:%-5d Avg QP:%5.2f size:%6.0f\n",
1602 slice_name[i_slice],
1604 (double)h->stat.i_slice_qp[i_slice] / i_count,
1605 (double)h->stat.i_slice_size[i_slice] / i_count );
1611 if( h->stat.i_slice_count[SLICE_TYPE_I] > 0 )
1613 const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_I];
1614 const double i_count = h->stat.i_slice_count[SLICE_TYPE_I] * h->mb.i_mb_count / 100.0;
1615 x264_log( h, X264_LOG_INFO,
1616 "mb I I16..4: %4.1f%% %4.1f%% %4.1f%%\n",
1617 i_mb_count[I_16x16]/ i_count,
1618 i_mb_count[I_8x8] / i_count,
1619 i_mb_count[I_4x4] / i_count );
1621 if( h->stat.i_slice_count[SLICE_TYPE_P] > 0 )
1623 const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_P];
1624 const int64_t *i_mb_size = h->stat.i_mb_count_size[SLICE_TYPE_P];
1625 const double i_count = h->stat.i_slice_count[SLICE_TYPE_P] * h->mb.i_mb_count / 100.0;
1626 x264_log( h, X264_LOG_INFO,
1627 "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",
1628 i_mb_count[I_16x16]/ i_count,
1629 i_mb_count[I_8x8] / i_count,
1630 i_mb_count[I_4x4] / i_count,
1631 i_mb_size[PIXEL_16x16] / (i_count*4),
1632 (i_mb_size[PIXEL_16x8] + i_mb_size[PIXEL_8x16]) / (i_count*4),
1633 i_mb_size[PIXEL_8x8] / (i_count*4),
1634 (i_mb_size[PIXEL_8x4] + i_mb_size[PIXEL_4x8]) / (i_count*4),
1635 i_mb_size[PIXEL_4x4] / (i_count*4),
1636 i_mb_count[P_SKIP] / i_count );
1638 if( h->stat.i_slice_count[SLICE_TYPE_B] > 0 )
1640 const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_B];
1641 const int64_t *i_mb_size = h->stat.i_mb_count_size[SLICE_TYPE_B];
1642 const double i_count = h->stat.i_slice_count[SLICE_TYPE_B] * h->mb.i_mb_count / 100.0;
1643 x264_log( h, X264_LOG_INFO,
1644 "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",
1645 i_mb_count[I_16x16] / i_count,
1646 i_mb_count[I_8x8] / i_count,
1647 i_mb_count[I_4x4] / i_count,
1648 i_mb_size[PIXEL_16x16] / (i_count*4),
1649 (i_mb_size[PIXEL_16x8] + i_mb_size[PIXEL_8x16]) / (i_count*4),
1650 i_mb_size[PIXEL_8x8] / (i_count*4),
1651 i_mb_count[B_DIRECT] / i_count,
1652 i_mb_count[B_SKIP] / i_count );
1655 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 )
1657 const int i_count = h->stat.i_slice_count[SLICE_TYPE_I] +
1658 h->stat.i_slice_count[SLICE_TYPE_P] +
1659 h->stat.i_slice_count[SLICE_TYPE_B];
1660 float fps = (float) h->param.i_fps_num / h->param.i_fps_den;
1661 #define SUM3(p) (p[SLICE_TYPE_I] + p[SLICE_TYPE_P] + p[SLICE_TYPE_B])
1662 #define SUM3b(p,o) (p[SLICE_TYPE_I][o] + p[SLICE_TYPE_P][o] + p[SLICE_TYPE_B][o])
1663 float f_bitrate = fps * SUM3(h->stat.i_slice_size) / i_count / 125;
1665 if( h->param.analyse.b_transform_8x8 )
1667 int64_t i_i8x8 = SUM3b( h->stat.i_mb_count, I_8x8 );
1668 int64_t i_intra = i_i8x8 + SUM3b( h->stat.i_mb_count, I_4x4 )
1669 + SUM3b( h->stat.i_mb_count, I_16x16 );
1670 x264_log( h, X264_LOG_INFO, "8x8 transform intra:%.1f%% inter:%.1f%%\n",
1671 100. * i_i8x8 / i_intra,
1672 100. * h->stat.i_mb_count_8x8dct[1] / h->stat.i_mb_count_8x8dct[0] );
1675 if( h->param.i_frame_reference > 1 )
1678 for( i_slice = 0; i_slice < 2; i_slice++ )
1684 for( i = 0; i < h->param.i_frame_reference; i++ )
1685 if( h->stat.i_mb_count_ref[i_slice][i] )
1687 i_den += h->stat.i_mb_count_ref[i_slice][i];
1692 for( i = 0; i <= i_max; i++ )
1693 p += sprintf( p, " %4.1f%%", 100. * h->stat.i_mb_count_ref[i_slice][i] / i_den );
1694 x264_log( h, X264_LOG_INFO, "ref %c %s\n", i_slice==SLICE_TYPE_P ? 'P' : 'B', buf );
1698 if( h->param.analyse.b_psnr )
1699 x264_log( h, X264_LOG_INFO,
1700 "PSNR Mean Y:%6.3f U:%6.3f V:%6.3f Avg:%6.3f Global:%6.3f kb/s:%.2f\n",
1701 SUM3( h->stat.f_psnr_mean_y ) / i_count,
1702 SUM3( h->stat.f_psnr_mean_u ) / i_count,
1703 SUM3( h->stat.f_psnr_mean_v ) / i_count,
1704 SUM3( h->stat.f_psnr_average ) / i_count,
1705 x264_psnr( SUM3( h->stat.i_sqe_global ), i_count * i_yuv_size ),
1708 x264_log( h, X264_LOG_INFO, "kb/s:%.1f\n", f_bitrate );
1712 for( i = 0; i < X264_BFRAME_MAX + 3; i++ )
1714 if( h->frames.current[i] ) x264_frame_delete( h->frames.current[i] );
1715 if( h->frames.next[i] ) x264_frame_delete( h->frames.next[i] );
1716 if( h->frames.unused[i] ) x264_frame_delete( h->frames.unused[i] );
1719 for( i = 0; i < h->frames.i_max_dpb; i++ )
1721 x264_frame_delete( h->frames.reference[i] );
1725 x264_ratecontrol_delete( h );
1728 if( h->param.rc.psz_stat_out )
1729 free( h->param.rc.psz_stat_out );
1730 if( h->param.rc.psz_stat_in )
1731 free( h->param.rc.psz_stat_in );
1732 if( h->param.rc.psz_rc_eq )
1733 free( h->param.rc.psz_rc_eq );
1735 x264_macroblock_cache_end( h );
1736 x264_free( h->out.p_bitstream );
1737 for( i = 1; i < h->param.i_threads; i++ )
1738 x264_free( h->thread[i] );