1 /*****************************************************************************
3 *****************************************************************************
4 * Copyright (C) 2003-2008 x264 project
6 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
7 * Loren Merritt <lorenm@u.washington.edu>
8 * Fiona Glaser <fiona@x264.com>
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA.
23 *****************************************************************************/
27 #include "common/common.h"
28 #include "common/cpu.h"
32 #include "ratecontrol.h"
33 #include "macroblock.h"
36 #include "common/visualize.h"
39 //#define DEBUG_MB_TYPE
41 #define NALU_OVERHEAD 5 // startcode + NAL type costs 5 bytes per frame
43 #define bs_write_ue bs_write_ue_big
45 static int x264_encoder_frame_end( x264_t *h, x264_t *thread_current,
46 x264_nal_t **pp_nal, int *pi_nal,
47 x264_picture_t *pic_out );
49 /****************************************************************************
51 ******************************* x264 libs **********************************
53 ****************************************************************************/
54 static float x264_psnr( int64_t i_sqe, int64_t i_size )
56 double f_mse = (double)i_sqe / ((double)65025.0 * (double)i_size);
57 if( f_mse <= 0.0000000001 ) /* Max 100dB */
60 return (float)(-10.0 * log( f_mse ) / log( 10.0 ));
63 static void x264_frame_dump( x264_t *h )
65 FILE *f = fopen( h->param.psz_dump_yuv, "r+b" );
69 /* Write the frame in display order */
70 fseek( f, h->fdec->i_frame * h->param.i_height * h->param.i_width * 3/2, SEEK_SET );
71 for( i = 0; i < h->fdec->i_plane; i++ )
72 for( y = 0; y < h->param.i_height >> !!i; y++ )
73 fwrite( &h->fdec->plane[i][y*h->fdec->i_stride[i]], 1, h->param.i_width >> !!i, f );
78 /* Fill "default" values */
79 static void x264_slice_header_init( x264_t *h, x264_slice_header_t *sh,
80 x264_sps_t *sps, x264_pps_t *pps,
81 int i_idr_pic_id, int i_frame, int i_qp )
83 x264_param_t *param = &h->param;
86 /* First we fill all field */
91 sh->i_last_mb = h->mb.i_mb_count - 1;
92 sh->i_pps_id = pps->i_id;
94 sh->i_frame_num = i_frame;
96 sh->b_mbaff = h->param.b_interlaced;
97 sh->b_field_pic = 0; /* no field support for now */
98 sh->b_bottom_field = 0; /* not yet used */
100 sh->i_idr_pic_id = i_idr_pic_id;
102 /* poc stuff, fixed later */
104 sh->i_delta_poc_bottom = 0;
105 sh->i_delta_poc[0] = 0;
106 sh->i_delta_poc[1] = 0;
108 sh->i_redundant_pic_cnt = 0;
110 if( !h->mb.b_direct_auto_read )
112 if( h->mb.b_direct_auto_write )
113 sh->b_direct_spatial_mv_pred = ( h->stat.i_direct_score[1] > h->stat.i_direct_score[0] );
115 sh->b_direct_spatial_mv_pred = ( param->analyse.i_direct_mv_pred == X264_DIRECT_PRED_SPATIAL );
117 /* else b_direct_spatial_mv_pred was read from the 2pass statsfile */
119 sh->b_num_ref_idx_override = 0;
120 sh->i_num_ref_idx_l0_active = 1;
121 sh->i_num_ref_idx_l1_active = 1;
123 sh->b_ref_pic_list_reordering_l0 = h->b_ref_reorder[0];
124 sh->b_ref_pic_list_reordering_l1 = h->b_ref_reorder[1];
126 /* If the ref list isn't in the default order, construct reordering header */
127 /* List1 reordering isn't needed yet */
128 if( sh->b_ref_pic_list_reordering_l0 )
130 int pred_frame_num = i_frame;
131 for( i = 0; i < h->i_ref0; i++ )
133 int diff = h->fref0[i]->i_frame_num - pred_frame_num;
135 x264_log( h, X264_LOG_ERROR, "diff frame num == 0\n" );
136 sh->ref_pic_list_order[0][i].idc = ( diff > 0 );
137 sh->ref_pic_list_order[0][i].arg = abs( diff ) - 1;
138 pred_frame_num = h->fref0[i]->i_frame_num;
142 sh->i_cabac_init_idc = param->i_cabac_init_idc;
145 sh->i_qp_delta = i_qp - pps->i_pic_init_qp;
146 sh->b_sp_for_swidth = 0;
149 /* If effective qp <= 15, deblocking would have no effect anyway */
150 if( param->b_deblocking_filter
151 && ( h->mb.b_variable_qp
152 || 15 < i_qp + 2 * X264_MIN(param->i_deblocking_filter_alphac0, param->i_deblocking_filter_beta) ) )
154 sh->i_disable_deblocking_filter_idc = 0;
158 sh->i_disable_deblocking_filter_idc = 1;
160 sh->i_alpha_c0_offset = param->i_deblocking_filter_alphac0 << 1;
161 sh->i_beta_offset = param->i_deblocking_filter_beta << 1;
164 static void x264_slice_header_write( bs_t *s, x264_slice_header_t *sh, int i_nal_ref_idc )
170 assert( sh->i_first_mb % (2*sh->sps->i_mb_width) == 0 );
171 bs_write_ue( s, sh->i_first_mb >> 1 );
174 bs_write_ue( s, sh->i_first_mb );
176 bs_write_ue( s, sh->i_type + 5 ); /* same type things */
177 bs_write_ue( s, sh->i_pps_id );
178 bs_write( s, sh->sps->i_log2_max_frame_num, sh->i_frame_num & ((1<<sh->sps->i_log2_max_frame_num)-1) );
180 if( !sh->sps->b_frame_mbs_only )
182 bs_write1( s, sh->b_field_pic );
183 if( sh->b_field_pic )
184 bs_write1( s, sh->b_bottom_field );
187 if( sh->i_idr_pic_id >= 0 ) /* NAL IDR */
189 bs_write_ue( s, sh->i_idr_pic_id );
192 if( sh->sps->i_poc_type == 0 )
194 bs_write( s, sh->sps->i_log2_max_poc_lsb, sh->i_poc_lsb & ((1<<sh->sps->i_log2_max_poc_lsb)-1) );
195 if( sh->pps->b_pic_order && !sh->b_field_pic )
197 bs_write_se( s, sh->i_delta_poc_bottom );
200 else if( sh->sps->i_poc_type == 1 && !sh->sps->b_delta_pic_order_always_zero )
202 bs_write_se( s, sh->i_delta_poc[0] );
203 if( sh->pps->b_pic_order && !sh->b_field_pic )
205 bs_write_se( s, sh->i_delta_poc[1] );
209 if( sh->pps->b_redundant_pic_cnt )
211 bs_write_ue( s, sh->i_redundant_pic_cnt );
214 if( sh->i_type == SLICE_TYPE_B )
216 bs_write1( s, sh->b_direct_spatial_mv_pred );
218 if( sh->i_type == SLICE_TYPE_P || sh->i_type == SLICE_TYPE_SP || sh->i_type == SLICE_TYPE_B )
220 bs_write1( s, sh->b_num_ref_idx_override );
221 if( sh->b_num_ref_idx_override )
223 bs_write_ue( s, sh->i_num_ref_idx_l0_active - 1 );
224 if( sh->i_type == SLICE_TYPE_B )
226 bs_write_ue( s, sh->i_num_ref_idx_l1_active - 1 );
231 /* ref pic list reordering */
232 if( sh->i_type != SLICE_TYPE_I )
234 bs_write1( s, sh->b_ref_pic_list_reordering_l0 );
235 if( sh->b_ref_pic_list_reordering_l0 )
237 for( i = 0; i < sh->i_num_ref_idx_l0_active; i++ )
239 bs_write_ue( s, sh->ref_pic_list_order[0][i].idc );
240 bs_write_ue( s, sh->ref_pic_list_order[0][i].arg );
246 if( sh->i_type == SLICE_TYPE_B )
248 bs_write1( s, sh->b_ref_pic_list_reordering_l1 );
249 if( sh->b_ref_pic_list_reordering_l1 )
251 for( i = 0; i < sh->i_num_ref_idx_l1_active; i++ )
253 bs_write_ue( s, sh->ref_pic_list_order[1][i].idc );
254 bs_write_ue( s, sh->ref_pic_list_order[1][i].arg );
260 if( ( sh->pps->b_weighted_pred && ( sh->i_type == SLICE_TYPE_P || sh->i_type == SLICE_TYPE_SP ) ) ||
261 ( sh->pps->b_weighted_bipred == 1 && sh->i_type == SLICE_TYPE_B ) )
266 if( i_nal_ref_idc != 0 )
268 if( sh->i_idr_pic_id >= 0 )
270 bs_write1( s, 0 ); /* no output of prior pics flag */
271 bs_write1( s, 0 ); /* long term reference flag */
275 bs_write1( s, sh->i_mmco_command_count > 0 ); /* adaptive_ref_pic_marking_mode_flag */
276 if( sh->i_mmco_command_count > 0 )
279 for( i = 0; i < sh->i_mmco_command_count; i++ )
281 bs_write_ue( s, 1 ); /* mark short term ref as unused */
282 bs_write_ue( s, sh->mmco[i].i_difference_of_pic_nums - 1 );
284 bs_write_ue( s, 0 ); /* end command list */
289 if( sh->pps->b_cabac && sh->i_type != SLICE_TYPE_I )
291 bs_write_ue( s, sh->i_cabac_init_idc );
293 bs_write_se( s, sh->i_qp_delta ); /* slice qp delta */
295 if( sh->pps->b_deblocking_filter_control )
297 bs_write_ue( s, sh->i_disable_deblocking_filter_idc );
298 if( sh->i_disable_deblocking_filter_idc != 1 )
300 bs_write_se( s, sh->i_alpha_c0_offset >> 1 );
301 bs_write_se( s, sh->i_beta_offset >> 1 );
306 /* If we are within a reasonable distance of the end of the memory allocated for the bitstream, */
307 /* reallocate, adding an arbitrary amount of space (100 kilobytes). */
308 static int x264_bitstream_check_buffer( x264_t *h )
310 uint8_t *bs_bak = h->out.p_bitstream;
311 if( ( h->param.b_cabac && (h->cabac.p_end - h->cabac.p < 2500) )
312 || ( h->out.bs.p_end - h->out.bs.p < 2500 ) )
317 h->out.i_bitstream += 100000;
318 CHECKED_MALLOC( h->out.p_bitstream, h->out.i_bitstream );
319 h->mc.memcpy_aligned( h->out.p_bitstream, bs_bak, (h->out.i_bitstream - 100000) & ~15 );
320 delta = h->out.p_bitstream - bs_bak;
322 h->out.bs.p_start += delta;
323 h->out.bs.p += delta;
324 h->out.bs.p_end = h->out.p_bitstream + h->out.i_bitstream;
326 h->cabac.p_start += delta;
328 h->cabac.p_end = h->out.p_bitstream + h->out.i_bitstream;
330 for( i = 0; i <= h->out.i_nal; i++ )
331 h->out.nal[i].p_payload += delta;
340 /****************************************************************************
342 ****************************************************************************
343 ****************************** External API*********************************
344 ****************************************************************************
346 ****************************************************************************/
348 static int x264_validate_parameters( x264_t *h )
351 if( !(x264_cpu_detect() & X264_CPU_SSE) )
353 x264_log( h, X264_LOG_ERROR, "your cpu does not support SSE1, but x264 was compiled with asm support\n");
354 x264_log( h, X264_LOG_ERROR, "to run x264, recompile without asm support (configure --disable-asm)\n");
358 if( h->param.i_width <= 0 || h->param.i_height <= 0 )
360 x264_log( h, X264_LOG_ERROR, "invalid width x height (%dx%d)\n",
361 h->param.i_width, h->param.i_height );
365 if( h->param.i_width % 2 || h->param.i_height % 2 )
367 x264_log( h, X264_LOG_ERROR, "width or height not divisible by 2 (%dx%d)\n",
368 h->param.i_width, h->param.i_height );
371 if( h->param.i_csp != X264_CSP_I420 )
373 x264_log( h, X264_LOG_ERROR, "invalid CSP (only I420 supported)\n" );
377 if( h->param.i_threads == X264_THREADS_AUTO )
378 h->param.i_threads = x264_cpu_num_processors() * 3/2;
379 h->param.i_threads = x264_clip3( h->param.i_threads, 1, X264_THREAD_MAX );
380 if( h->param.i_threads > 1 )
383 x264_log( h, X264_LOG_WARNING, "not compiled with pthread support!\n");
384 h->param.i_threads = 1;
388 if( h->param.b_interlaced )
390 if( h->param.analyse.i_me_method >= X264_ME_ESA )
392 x264_log( h, X264_LOG_WARNING, "interlace + me=esa is not implemented\n" );
393 h->param.analyse.i_me_method = X264_ME_UMH;
395 if( h->param.analyse.i_direct_mv_pred > X264_DIRECT_PRED_SPATIAL )
397 x264_log( h, X264_LOG_WARNING, "interlace + direct=temporal is not implemented\n" );
398 h->param.analyse.i_direct_mv_pred = X264_DIRECT_PRED_SPATIAL;
402 /* Detect default ffmpeg settings and terminate with an error. */
405 score += h->param.analyse.i_me_range == 0;
406 score += h->param.rc.i_qp_step == 3;
407 score += h->param.i_keyint_max == 12;
408 score += h->param.rc.i_qp_min == 2;
409 score += h->param.rc.i_qp_max == 31;
410 score += h->param.rc.f_qcompress == 0.5;
411 score += fabs(h->param.rc.f_ip_factor - 1.25) < 0.01;
412 score += fabs(h->param.rc.f_pb_factor - 1.25) < 0.01;
413 score += h->param.analyse.inter == 0 && h->param.analyse.i_subpel_refine == 8;
416 x264_log( h, X264_LOG_ERROR, "broken ffmpeg default settings detected\n" );
417 x264_log( h, X264_LOG_ERROR, "use an encoding preset (vpre)\n" );
422 if( h->param.rc.i_rc_method < 0 || h->param.rc.i_rc_method > 2 )
424 x264_log( h, X264_LOG_ERROR, "no ratecontrol method specified\n" );
427 h->param.rc.f_rf_constant = x264_clip3f( h->param.rc.f_rf_constant, 0, 51 );
428 h->param.rc.i_qp_constant = x264_clip3( h->param.rc.i_qp_constant, 0, 51 );
429 if( h->param.rc.i_rc_method == X264_RC_CRF )
431 h->param.rc.i_qp_constant = h->param.rc.f_rf_constant;
432 h->param.rc.i_bitrate = 0;
434 if( (h->param.rc.i_rc_method == X264_RC_CQP || h->param.rc.i_rc_method == X264_RC_CRF)
435 && h->param.rc.i_qp_constant == 0 )
437 h->mb.b_lossless = 1;
438 h->param.i_cqm_preset = X264_CQM_FLAT;
439 h->param.psz_cqm_file = NULL;
440 h->param.rc.i_rc_method = X264_RC_CQP;
441 h->param.rc.f_ip_factor = 1;
442 h->param.rc.f_pb_factor = 1;
443 h->param.analyse.b_psnr = 0;
444 h->param.analyse.b_ssim = 0;
445 h->param.analyse.i_chroma_qp_offset = 0;
446 h->param.analyse.i_trellis = 0;
447 h->param.analyse.b_fast_pskip = 0;
448 h->param.analyse.i_noise_reduction = 0;
449 h->param.analyse.f_psy_rd = 0;
450 h->param.i_bframe = 0;
451 /* 8x8dct is not useful at all in CAVLC lossless */
452 if( !h->param.b_cabac )
453 h->param.analyse.b_transform_8x8 = 0;
455 if( h->param.rc.i_rc_method == X264_RC_CQP )
457 float qp_p = h->param.rc.i_qp_constant;
458 float qp_i = qp_p - 6*log(h->param.rc.f_ip_factor)/log(2);
459 float qp_b = qp_p + 6*log(h->param.rc.f_pb_factor)/log(2);
460 h->param.rc.i_qp_min = x264_clip3( (int)(X264_MIN3( qp_p, qp_i, qp_b )), 0, 51 );
461 h->param.rc.i_qp_max = x264_clip3( (int)(X264_MAX3( qp_p, qp_i, qp_b ) + .999), 0, 51 );
462 h->param.rc.i_aq_mode = 0;
463 h->param.rc.b_mb_tree = 0;
465 h->param.rc.i_qp_max = x264_clip3( h->param.rc.i_qp_max, 0, 51 );
466 h->param.rc.i_qp_min = x264_clip3( h->param.rc.i_qp_min, 0, h->param.rc.i_qp_max );
468 if( ( h->param.i_width % 16 || h->param.i_height % 16 )
469 && h->param.i_height != 1080 && !h->mb.b_lossless )
471 // There's nothing special about 1080 in that the warning still applies to it,
472 // but chances are the user can't help it if his content is already 1080p,
473 // so there's no point in warning in that case.
474 x264_log( h, X264_LOG_WARNING,
475 "width or height not divisible by 16 (%dx%d), compression will suffer.\n",
476 h->param.i_width, h->param.i_height );
479 int max_slices = (h->param.i_height+((16<<h->param.b_interlaced)-1))/(16<<h->param.b_interlaced);
480 h->param.i_slice_count = x264_clip3( h->param.i_slice_count, 0, max_slices );
481 h->param.i_slice_max_size = X264_MAX( h->param.i_slice_max_size, 0 );
482 h->param.i_slice_max_mbs = X264_MAX( h->param.i_slice_max_mbs, 0 );
483 if( h->param.b_interlaced && h->param.i_slice_max_size )
485 x264_log( h, X264_LOG_WARNING, "interlaced + slice-max-size is not implemented\n" );
486 h->param.i_slice_max_size = 0;
488 if( h->param.b_interlaced && h->param.i_slice_max_mbs )
490 x264_log( h, X264_LOG_WARNING, "interlaced + slice-max-mbs is not implemented\n" );
491 h->param.i_slice_max_mbs = 0;
493 if( h->param.i_slice_max_mbs || h->param.i_slice_max_size )
494 h->param.i_slice_count = 0;
496 h->param.i_frame_reference = x264_clip3( h->param.i_frame_reference, 1, 16 );
497 if( h->param.i_keyint_max <= 0 )
498 h->param.i_keyint_max = 1;
499 if( h->param.i_scenecut_threshold < 0 )
500 h->param.i_scenecut_threshold = 0;
501 h->param.i_keyint_min = x264_clip3( h->param.i_keyint_min, 1, h->param.i_keyint_max/2+1 );
502 if( !h->param.analyse.i_subpel_refine && h->param.analyse.i_direct_mv_pred > X264_DIRECT_PRED_SPATIAL )
504 x264_log( h, X264_LOG_WARNING, "subme=0 + direct=temporal is not supported\n" );
505 h->param.analyse.i_direct_mv_pred = X264_DIRECT_PRED_SPATIAL;
507 h->param.i_bframe = x264_clip3( h->param.i_bframe, 0, X264_BFRAME_MAX );
508 if( h->param.i_keyint_max == 1 )
509 h->param.i_bframe = 0;
510 h->param.i_bframe_bias = x264_clip3( h->param.i_bframe_bias, -90, 100 );
511 if( h->param.i_bframe <= 1 )
512 h->param.i_bframe_pyramid = X264_B_PYRAMID_NONE;
513 h->param.i_bframe_pyramid = x264_clip3( h->param.i_bframe_pyramid, X264_B_PYRAMID_NONE, X264_B_PYRAMID_NORMAL );
514 if( !h->param.i_bframe )
516 h->param.i_bframe_adaptive = X264_B_ADAPT_NONE;
517 h->param.analyse.i_direct_mv_pred = 0;
518 h->param.analyse.b_weighted_bipred = 0;
520 h->param.rc.i_lookahead = x264_clip3( h->param.rc.i_lookahead, 0, X264_LOOKAHEAD_MAX );
522 int maxrate = X264_MAX( h->param.rc.i_vbv_max_bitrate, h->param.rc.i_bitrate );
523 float bufsize = maxrate ? (float)h->param.rc.i_vbv_buffer_size / maxrate : 0;
524 float fps = h->param.i_fps_num > 0 && h->param.i_fps_den > 0 ? (float) h->param.i_fps_num / h->param.i_fps_den : 25.0;
525 h->param.rc.i_lookahead = X264_MIN( h->param.rc.i_lookahead, X264_MAX( h->param.i_keyint_max, bufsize*fps ) );
528 h->param.rc.f_qcompress = x264_clip3f( h->param.rc.f_qcompress, 0.0, 1.0 );
529 if( !h->param.rc.i_lookahead || h->param.i_keyint_max == 1 || h->param.rc.f_qcompress == 1 )
530 h->param.rc.b_mb_tree = 0;
531 if( h->param.rc.b_stat_read )
532 h->param.rc.i_lookahead = 0;
534 if( h->param.i_sync_lookahead )
535 h->param.i_sync_lookahead = x264_clip3( h->param.i_sync_lookahead, h->param.i_threads + h->param.i_bframe, X264_LOOKAHEAD_MAX );
536 if( h->param.rc.b_stat_read || h->param.i_threads == 1 )
537 h->param.i_sync_lookahead = 0;
539 h->param.i_sync_lookahead = 0;
542 h->mb.b_direct_auto_write = h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_AUTO
544 && ( h->param.rc.b_stat_write || !h->param.rc.b_stat_read );
546 h->param.i_deblocking_filter_alphac0 = x264_clip3( h->param.i_deblocking_filter_alphac0, -6, 6 );
547 h->param.i_deblocking_filter_beta = x264_clip3( h->param.i_deblocking_filter_beta, -6, 6 );
548 h->param.analyse.i_luma_deadzone[0] = x264_clip3( h->param.analyse.i_luma_deadzone[0], 0, 32 );
549 h->param.analyse.i_luma_deadzone[1] = x264_clip3( h->param.analyse.i_luma_deadzone[1], 0, 32 );
551 h->param.i_cabac_init_idc = x264_clip3( h->param.i_cabac_init_idc, 0, 2 );
553 if( h->param.i_cqm_preset < X264_CQM_FLAT || h->param.i_cqm_preset > X264_CQM_CUSTOM )
554 h->param.i_cqm_preset = X264_CQM_FLAT;
556 if( h->param.analyse.i_me_method < X264_ME_DIA ||
557 h->param.analyse.i_me_method > X264_ME_TESA )
558 h->param.analyse.i_me_method = X264_ME_HEX;
559 if( h->param.analyse.i_me_range < 4 )
560 h->param.analyse.i_me_range = 4;
561 if( h->param.analyse.i_me_range > 16 && h->param.analyse.i_me_method <= X264_ME_HEX )
562 h->param.analyse.i_me_range = 16;
563 if( h->param.analyse.i_me_method == X264_ME_TESA &&
564 (h->mb.b_lossless || h->param.analyse.i_subpel_refine <= 1) )
565 h->param.analyse.i_me_method = X264_ME_ESA;
566 h->param.analyse.i_subpel_refine = x264_clip3( h->param.analyse.i_subpel_refine, 0, 10 );
567 h->param.analyse.b_mixed_references = h->param.analyse.b_mixed_references && h->param.i_frame_reference > 1;
568 h->param.analyse.inter &= X264_ANALYSE_PSUB16x16|X264_ANALYSE_PSUB8x8|X264_ANALYSE_BSUB16x16|
569 X264_ANALYSE_I4x4|X264_ANALYSE_I8x8;
570 h->param.analyse.intra &= X264_ANALYSE_I4x4|X264_ANALYSE_I8x8;
571 if( !(h->param.analyse.inter & X264_ANALYSE_PSUB16x16) )
572 h->param.analyse.inter &= ~X264_ANALYSE_PSUB8x8;
573 if( !h->param.analyse.b_transform_8x8 )
575 h->param.analyse.inter &= ~X264_ANALYSE_I8x8;
576 h->param.analyse.intra &= ~X264_ANALYSE_I8x8;
578 h->param.analyse.i_chroma_qp_offset = x264_clip3(h->param.analyse.i_chroma_qp_offset, -12, 12);
579 if( !h->param.b_cabac )
580 h->param.analyse.i_trellis = 0;
581 h->param.analyse.i_trellis = x264_clip3( h->param.analyse.i_trellis, 0, 2 );
582 if( !h->param.analyse.b_psy )
584 h->param.analyse.f_psy_rd = 0;
585 h->param.analyse.f_psy_trellis = 0;
587 if( !h->param.analyse.i_trellis )
588 h->param.analyse.f_psy_trellis = 0;
589 h->param.analyse.f_psy_rd = x264_clip3f( h->param.analyse.f_psy_rd, 0, 10 );
590 h->param.analyse.f_psy_trellis = x264_clip3f( h->param.analyse.f_psy_trellis, 0, 10 );
591 if( h->param.analyse.i_subpel_refine < 6 )
592 h->param.analyse.f_psy_rd = 0;
593 h->mb.i_psy_rd = FIX8( h->param.analyse.f_psy_rd );
594 /* Psy RDO increases overall quantizers to improve the quality of luma--this indirectly hurts chroma quality */
595 /* so we lower the chroma QP offset to compensate */
596 /* This can be triggered repeatedly on multiple calls to parameter_validate, but since encoding
597 * uses the pps chroma qp offset not the param chroma qp offset, this is not a problem. */
599 h->param.analyse.i_chroma_qp_offset -= h->param.analyse.f_psy_rd < 0.25 ? 1 : 2;
600 h->mb.i_psy_trellis = FIX8( h->param.analyse.f_psy_trellis / 4 );
601 /* Psy trellis has a similar effect. */
602 if( h->mb.i_psy_trellis )
603 h->param.analyse.i_chroma_qp_offset -= h->param.analyse.f_psy_trellis < 0.25 ? 1 : 2;
605 h->mb.i_psy_trellis = 0;
606 h->param.analyse.i_chroma_qp_offset = x264_clip3(h->param.analyse.i_chroma_qp_offset, -12, 12);
607 h->param.rc.i_aq_mode = x264_clip3( h->param.rc.i_aq_mode, 0, 2 );
608 h->param.rc.f_aq_strength = x264_clip3f( h->param.rc.f_aq_strength, 0, 3 );
609 if( h->param.rc.f_aq_strength == 0 )
610 h->param.rc.i_aq_mode = 0;
611 /* MB-tree requires AQ to be on, even if the strength is zero. */
612 if( !h->param.rc.i_aq_mode && h->param.rc.b_mb_tree )
614 h->param.rc.i_aq_mode = 1;
615 h->param.rc.f_aq_strength = 0;
617 if( h->param.rc.b_mb_tree && h->param.i_bframe_pyramid )
619 x264_log( h, X264_LOG_WARNING, "b-pyramid + mb-tree is not supported\n" );
620 h->param.i_bframe_pyramid = X264_B_PYRAMID_NONE;
622 h->param.analyse.i_noise_reduction = x264_clip3( h->param.analyse.i_noise_reduction, 0, 1<<16 );
623 if( h->param.analyse.i_subpel_refine == 10 && (h->param.analyse.i_trellis != 2 || !h->param.rc.i_aq_mode) )
624 h->param.analyse.i_subpel_refine = 9;
627 const x264_level_t *l = x264_levels;
628 if( h->param.i_level_idc < 0 )
630 int maxrate_bak = h->param.rc.i_vbv_max_bitrate;
631 if( h->param.rc.i_rc_method == X264_RC_ABR && h->param.rc.i_vbv_buffer_size <= 0 )
632 h->param.rc.i_vbv_max_bitrate = h->param.rc.i_bitrate * 2;
633 h->sps = h->sps_array;
634 x264_sps_init( h->sps, h->param.i_sps_id, &h->param );
635 do h->param.i_level_idc = l->level_idc;
636 while( l[1].level_idc && x264_validate_levels( h, 0 ) && l++ );
637 h->param.rc.i_vbv_max_bitrate = maxrate_bak;
641 while( l->level_idc && l->level_idc != h->param.i_level_idc )
643 if( l->level_idc == 0 )
645 x264_log( h, X264_LOG_ERROR, "invalid level_idc: %d\n", h->param.i_level_idc );
649 if( h->param.analyse.i_mv_range <= 0 )
650 h->param.analyse.i_mv_range = l->mv_range >> h->param.b_interlaced;
652 h->param.analyse.i_mv_range = x264_clip3(h->param.analyse.i_mv_range, 32, 512 >> h->param.b_interlaced);
655 if( h->param.i_threads > 1 )
657 int r = h->param.analyse.i_mv_range_thread;
661 // half of the available space is reserved and divided evenly among the threads,
662 // the rest is allocated to whichever thread is far enough ahead to use it.
663 // reserving more space increases quality for some videos, but costs more time
664 // in thread synchronization.
665 int max_range = (h->param.i_height + X264_THREAD_HEIGHT) / h->param.i_threads - X264_THREAD_HEIGHT;
668 r = X264_MAX( r, h->param.analyse.i_me_range );
669 r = X264_MIN( r, h->param.analyse.i_mv_range );
670 // round up to use the whole mb row
671 r2 = (r & ~15) + ((-X264_THREAD_HEIGHT) & 15);
674 x264_log( h, X264_LOG_DEBUG, "using mv_range_thread = %d\n", r2 );
675 h->param.analyse.i_mv_range_thread = r2;
678 if( h->param.rc.f_qblur < 0 )
679 h->param.rc.f_qblur = 0;
680 if( h->param.rc.f_complexity_blur < 0 )
681 h->param.rc.f_complexity_blur = 0;
683 h->param.i_sps_id &= 31;
685 if( h->param.i_log_level < X264_LOG_INFO )
687 h->param.analyse.b_psnr = 0;
688 h->param.analyse.b_ssim = 0;
691 /* ensure the booleans are 0 or 1 so they can be used in math */
692 #define BOOLIFY(x) h->param.x = !!h->param.x
694 BOOLIFY( b_deblocking_filter );
695 BOOLIFY( b_interlaced );
696 BOOLIFY( analyse.b_transform_8x8 );
697 BOOLIFY( analyse.b_chroma_me );
698 BOOLIFY( analyse.b_fast_pskip );
699 BOOLIFY( rc.b_stat_write );
700 BOOLIFY( rc.b_stat_read );
701 BOOLIFY( rc.b_mb_tree );
707 static void mbcmp_init( x264_t *h )
709 int satd = !h->mb.b_lossless && h->param.analyse.i_subpel_refine > 1;
710 memcpy( h->pixf.mbcmp, satd ? h->pixf.satd : h->pixf.sad_aligned, sizeof(h->pixf.mbcmp) );
711 memcpy( h->pixf.mbcmp_unaligned, satd ? h->pixf.satd : h->pixf.sad, sizeof(h->pixf.mbcmp_unaligned) );
712 h->pixf.intra_mbcmp_x3_16x16 = satd ? h->pixf.intra_satd_x3_16x16 : h->pixf.intra_sad_x3_16x16;
713 h->pixf.intra_mbcmp_x3_8x8c = satd ? h->pixf.intra_satd_x3_8x8c : h->pixf.intra_sad_x3_8x8c;
714 h->pixf.intra_mbcmp_x3_4x4 = satd ? h->pixf.intra_satd_x3_4x4 : h->pixf.intra_sad_x3_4x4;
715 satd &= h->param.analyse.i_me_method == X264_ME_TESA;
716 memcpy( h->pixf.fpelcmp, satd ? h->pixf.satd : h->pixf.sad, sizeof(h->pixf.fpelcmp) );
717 memcpy( h->pixf.fpelcmp_x3, satd ? h->pixf.satd_x3 : h->pixf.sad_x3, sizeof(h->pixf.fpelcmp_x3) );
718 memcpy( h->pixf.fpelcmp_x4, satd ? h->pixf.satd_x4 : h->pixf.sad_x4, sizeof(h->pixf.fpelcmp_x4) );
721 static void x264_set_aspect_ratio( x264_t *h, x264_param_t *param, int initial )
724 if( param->vui.i_sar_width > 0 && param->vui.i_sar_height > 0 )
726 int i_w = param->vui.i_sar_width;
727 int i_h = param->vui.i_sar_height;
728 int old_w = h->param.vui.i_sar_width;
729 int old_h = h->param.vui.i_sar_height;
731 x264_reduce_fraction( &i_w, &i_h );
733 while( i_w > 65535 || i_h > 65535 )
739 x264_reduce_fraction( &i_w, &i_h );
741 if( i_w != old_w || i_h != old_h || initial )
743 h->param.vui.i_sar_width = 0;
744 h->param.vui.i_sar_height = 0;
745 if( i_w == 0 || i_h == 0 )
746 x264_log( h, X264_LOG_WARNING, "cannot create valid sample aspect ratio\n" );
749 x264_log( h, initial?X264_LOG_INFO:X264_LOG_DEBUG, "using SAR=%d/%d\n", i_w, i_h );
750 h->param.vui.i_sar_width = i_w;
751 h->param.vui.i_sar_height = i_h;
757 /****************************************************************************
759 ****************************************************************************/
760 x264_t *x264_encoder_open( x264_param_t *param )
764 int i, qp, i_slicetype_length;
766 CHECKED_MALLOCZERO( h, sizeof(x264_t) );
768 /* Create a copy of param */
769 memcpy( &h->param, param, sizeof(x264_param_t) );
771 if( param->param_free )
772 param->param_free( param );
774 if( x264_validate_parameters( h ) < 0 )
777 if( h->param.psz_cqm_file )
778 if( x264_cqm_parse_file( h, h->param.psz_cqm_file ) < 0 )
781 if( h->param.rc.psz_stat_out )
782 h->param.rc.psz_stat_out = strdup( h->param.rc.psz_stat_out );
783 if( h->param.rc.psz_stat_in )
784 h->param.rc.psz_stat_in = strdup( h->param.rc.psz_stat_in );
786 x264_set_aspect_ratio( h, param, 1 );
788 x264_reduce_fraction( &h->param.i_fps_num, &h->param.i_fps_den );
795 h->sps = &h->sps_array[0];
796 x264_sps_init( h->sps, h->param.i_sps_id, &h->param );
798 h->pps = &h->pps_array[0];
799 x264_pps_init( h->pps, h->param.i_sps_id, &h->param, h->sps );
801 x264_validate_levels( h, 1 );
803 h->chroma_qp_table = i_chroma_qp_table + 12 + h->pps->i_chroma_qp_index_offset;
805 if( x264_cqm_init( h ) < 0 )
808 h->mb.i_mb_count = h->sps->i_mb_width * h->sps->i_mb_height;
811 if( h->param.i_bframe_adaptive == X264_B_ADAPT_TRELLIS )
812 h->frames.i_delay = X264_MAX(h->param.i_bframe,3)*4;
814 h->frames.i_delay = h->param.i_bframe;
815 if( h->param.rc.b_mb_tree || h->param.rc.i_vbv_buffer_size )
816 h->frames.i_delay = X264_MAX( h->frames.i_delay, h->param.rc.i_lookahead );
817 i_slicetype_length = h->frames.i_delay;
818 h->frames.i_delay += h->param.i_threads - 1;
819 h->frames.i_delay = X264_MIN( h->frames.i_delay, X264_LOOKAHEAD_MAX );
820 h->frames.i_delay += h->param.i_sync_lookahead;
822 h->frames.i_max_ref0 = h->param.i_frame_reference;
823 h->frames.i_max_ref1 = h->sps->vui.i_num_reorder_frames;
824 h->frames.i_max_dpb = h->sps->vui.i_max_dec_frame_buffering;
825 h->frames.b_have_lowres = !h->param.rc.b_stat_read
826 && ( h->param.rc.i_rc_method == X264_RC_ABR
827 || h->param.rc.i_rc_method == X264_RC_CRF
828 || h->param.i_bframe_adaptive
829 || h->param.i_scenecut_threshold
830 || h->param.rc.b_mb_tree );
831 h->frames.b_have_lowres |= h->param.rc.b_stat_read && h->param.rc.i_vbv_buffer_size > 0;
832 h->frames.b_have_sub8x8_esa = !!(h->param.analyse.inter & X264_ANALYSE_PSUB8x8);
834 h->frames.i_last_idr = - h->param.i_keyint_max;
835 h->frames.i_input = 0;
837 CHECKED_MALLOCZERO( h->frames.unused[0], (h->frames.i_delay + 3) * sizeof(x264_frame_t *) );
838 /* Allocate room for max refs plus a few extra just in case. */
839 CHECKED_MALLOCZERO( h->frames.unused[1], (h->param.i_threads + 20) * sizeof(x264_frame_t *) );
840 CHECKED_MALLOCZERO( h->frames.current, (h->param.i_sync_lookahead + h->param.i_bframe
841 + h->param.i_threads + 3) * sizeof(x264_frame_t *) );
848 /* init CPU functions */
849 x264_predict_16x16_init( h->param.cpu, h->predict_16x16 );
850 x264_predict_8x8c_init( h->param.cpu, h->predict_8x8c );
851 x264_predict_8x8_init( h->param.cpu, h->predict_8x8, &h->predict_8x8_filter );
852 x264_predict_4x4_init( h->param.cpu, h->predict_4x4 );
853 if( !h->param.b_cabac )
854 x264_init_vlc_tables();
855 x264_pixel_init( h->param.cpu, &h->pixf );
856 x264_dct_init( h->param.cpu, &h->dctf );
857 x264_zigzag_init( h->param.cpu, &h->zigzagf, h->param.b_interlaced );
858 x264_mc_init( h->param.cpu, &h->mc );
859 x264_quant_init( h, h->param.cpu, &h->quantf );
860 x264_deblock_init( h->param.cpu, &h->loopf );
861 x264_dct_init_weights();
865 p = buf + sprintf( buf, "using cpu capabilities:" );
866 for( i=0; x264_cpu_names[i].flags; i++ )
868 if( !strcmp(x264_cpu_names[i].name, "SSE2")
869 && param->cpu & (X264_CPU_SSE2_IS_FAST|X264_CPU_SSE2_IS_SLOW) )
871 if( !strcmp(x264_cpu_names[i].name, "SSE3")
872 && (param->cpu & X264_CPU_SSSE3 || !(param->cpu & X264_CPU_CACHELINE_64)) )
874 if( !strcmp(x264_cpu_names[i].name, "SSE4.1")
875 && (param->cpu & X264_CPU_SSE42) )
877 if( (param->cpu & x264_cpu_names[i].flags) == x264_cpu_names[i].flags
878 && (!i || x264_cpu_names[i].flags != x264_cpu_names[i-1].flags) )
879 p += sprintf( p, " %s", x264_cpu_names[i].name );
882 p += sprintf( p, " none!" );
883 x264_log( h, X264_LOG_INFO, "%s\n", buf );
885 for( qp = h->param.rc.i_qp_min; qp <= h->param.rc.i_qp_max; qp++ )
886 if( x264_analyse_init_costs( h, qp ) )
888 if( x264_analyse_init_costs( h, X264_LOOKAHEAD_QP ) )
890 if( h->cost_mv[1][2013] != 24 )
892 x264_log( h, X264_LOG_ERROR, "MV cost test failed: x264 has been miscompiled!\n" );
897 h->out.i_bitstream = X264_MAX( 1000000, h->param.i_width * h->param.i_height * 4
898 * ( h->param.rc.i_rc_method == X264_RC_ABR ? pow( 0.95, h->param.rc.i_qp_min )
899 : pow( 0.95, h->param.rc.i_qp_constant ) * X264_MAX( 1, h->param.rc.f_ip_factor )));
901 CHECKED_MALLOC( h->nal_buffer, h->out.i_bitstream * 3/2 + 4 );
902 h->nal_buffer_size = h->out.i_bitstream * 3/2 + 4;
906 for( i = 1; i < h->param.i_threads + !!h->param.i_sync_lookahead; i++ )
907 CHECKED_MALLOC( h->thread[i], sizeof(x264_t) );
909 for( i = 0; i < h->param.i_threads; i++ )
913 h->thread[i]->fdec = x264_frame_pop_unused( h, 1 );
914 if( !h->thread[i]->fdec )
916 CHECKED_MALLOC( h->thread[i]->out.p_bitstream, h->out.i_bitstream );
917 /* Start each thread with room for 8 NAL units; it'll realloc later if needed. */
918 CHECKED_MALLOC( h->thread[i]->out.nal, 8*sizeof(x264_nal_t) );
919 h->thread[i]->out.i_nals_allocated = 8;
920 if( x264_macroblock_cache_init( h->thread[i] ) < 0 )
924 if( x264_lookahead_init( h, i_slicetype_length ) )
927 if( x264_ratecontrol_new( h ) < 0 )
930 if( h->param.psz_dump_yuv )
932 /* create or truncate the reconstructed video file */
933 FILE *f = fopen( h->param.psz_dump_yuv, "w" );
938 x264_log( h, X264_LOG_ERROR, "dump_yuv: can't write to %s\n", h->param.psz_dump_yuv );
943 x264_log( h, X264_LOG_INFO, "profile %s, level %d.%d\n",
944 h->sps->i_profile_idc == PROFILE_BASELINE ? "Baseline" :
945 h->sps->i_profile_idc == PROFILE_MAIN ? "Main" :
946 h->sps->i_profile_idc == PROFILE_HIGH ? "High" :
947 "High 4:4:4 Predictive", h->sps->i_level_idc/10, h->sps->i_level_idc%10 );
955 /****************************************************************************
956 * x264_encoder_reconfig:
957 ****************************************************************************/
958 int x264_encoder_reconfig( x264_t *h, x264_param_t *param )
960 h = h->thread[h->i_thread_phase];
961 x264_set_aspect_ratio( h, param, 0 );
962 #define COPY(var) h->param.var = param->var
963 COPY( i_frame_reference ); // but never uses more refs than initially specified
964 COPY( i_bframe_bias );
965 if( h->param.i_scenecut_threshold )
966 COPY( i_scenecut_threshold ); // can't turn it on or off, only vary the threshold
967 COPY( b_deblocking_filter );
968 COPY( i_deblocking_filter_alphac0 );
969 COPY( i_deblocking_filter_beta );
970 COPY( analyse.intra );
971 COPY( analyse.inter );
972 COPY( analyse.i_direct_mv_pred );
973 /* Scratch buffer prevents me_range from being increased for esa/tesa */
974 if( h->param.analyse.i_me_method < X264_ME_ESA || param->analyse.i_me_range < h->param.analyse.i_me_range )
975 COPY( analyse.i_me_range );
976 COPY( analyse.i_noise_reduction );
977 /* We can't switch out of subme=0 during encoding. */
978 if( h->param.analyse.i_subpel_refine )
979 COPY( analyse.i_subpel_refine );
980 COPY( analyse.i_trellis );
981 COPY( analyse.b_chroma_me );
982 COPY( analyse.b_dct_decimate );
983 COPY( analyse.b_fast_pskip );
984 COPY( analyse.b_mixed_references );
985 COPY( analyse.f_psy_rd );
986 COPY( analyse.f_psy_trellis );
987 // can only twiddle these if they were enabled to begin with:
988 if( h->param.analyse.i_me_method >= X264_ME_ESA || param->analyse.i_me_method < X264_ME_ESA )
989 COPY( analyse.i_me_method );
990 if( h->param.analyse.i_me_method >= X264_ME_ESA && !h->frames.b_have_sub8x8_esa )
991 h->param.analyse.inter &= ~X264_ANALYSE_PSUB8x8;
992 if( h->pps->b_transform_8x8_mode )
993 COPY( analyse.b_transform_8x8 );
994 if( h->frames.i_max_ref1 > 1 )
995 COPY( i_bframe_pyramid );
996 COPY( i_slice_max_size );
997 COPY( i_slice_max_mbs );
998 COPY( i_slice_count );
1003 return x264_validate_parameters( h );
1006 /* internal usage */
1007 static void x264_nal_start( x264_t *h, int i_type, int i_ref_idc )
1009 x264_nal_t *nal = &h->out.nal[h->out.i_nal];
1011 nal->i_ref_idc = i_ref_idc;
1012 nal->i_type = i_type;
1015 nal->p_payload= &h->out.p_bitstream[bs_pos( &h->out.bs ) / 8];
1017 static int x264_nal_end( x264_t *h )
1019 x264_nal_t *nal = &h->out.nal[h->out.i_nal];
1020 nal->i_payload = &h->out.p_bitstream[bs_pos( &h->out.bs ) / 8] - nal->p_payload;
1023 /* if number of allocated nals is not enough, re-allocate a larger one. */
1024 if( h->out.i_nal >= h->out.i_nals_allocated )
1026 x264_nal_t *new_out = x264_malloc( sizeof(x264_nal_t) * (h->out.i_nals_allocated*2) );
1029 memcpy( new_out, h->out.nal, sizeof(x264_nal_t) * (h->out.i_nals_allocated) );
1030 x264_free( h->out.nal );
1031 h->out.nal = new_out;
1032 h->out.i_nals_allocated *= 2;
1037 static int x264_encoder_encapsulate_nals( x264_t *h )
1039 int nal_size = 0, i;
1040 for( i = 0; i < h->out.i_nal; i++ )
1041 nal_size += h->out.nal[i].i_payload;
1043 /* Worst-case NAL unit escaping: reallocate the buffer if it's too small. */
1044 if( h->nal_buffer_size < nal_size * 3/2 + h->out.i_nal * 4 )
1046 uint8_t *buf = x264_malloc( nal_size * 2 + h->out.i_nal * 4 );
1049 x264_free( h->nal_buffer );
1050 h->nal_buffer = buf;
1053 uint8_t *nal_buffer = h->nal_buffer;
1055 for( i = 0; i < h->out.i_nal; i++ )
1057 int size = x264_nal_encode( nal_buffer, h->param.b_annexb, &h->out.nal[i] );
1058 h->out.nal[i].i_payload = size;
1059 h->out.nal[i].p_payload = nal_buffer;
1063 return nal_buffer - h->nal_buffer;
1066 /****************************************************************************
1067 * x264_encoder_headers:
1068 ****************************************************************************/
1069 int x264_encoder_headers( x264_t *h, x264_nal_t **pp_nal, int *pi_nal )
1072 /* init bitstream context */
1074 bs_init( &h->out.bs, h->out.p_bitstream, h->out.i_bitstream );
1076 /* Write SEI, SPS and PPS. */
1077 x264_nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
1078 if( x264_sei_version_write( h, &h->out.bs ) )
1080 if( x264_nal_end( h ) )
1083 /* generate sequence parameters */
1084 x264_nal_start( h, NAL_SPS, NAL_PRIORITY_HIGHEST );
1085 x264_sps_write( &h->out.bs, h->sps );
1086 if( x264_nal_end( h ) )
1089 /* generate picture parameters */
1090 x264_nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
1091 x264_pps_write( &h->out.bs, h->pps );
1092 if( x264_nal_end( h ) )
1094 bs_flush( &h->out.bs );
1096 frame_size = x264_encoder_encapsulate_nals( h );
1099 *pi_nal = h->out.i_nal;
1100 *pp_nal = &h->out.nal[0];
1106 /* Check to see whether we have chosen a reference list ordering different
1107 * from the standard's default. */
1108 static inline void x264_reference_check_reorder( x264_t *h )
1111 for( i = 0; i < h->i_ref0 - 1; i++ )
1112 /* P and B-frames use different default orders. */
1113 if( h->sh.i_type == SLICE_TYPE_P ? h->fref0[i]->i_frame_num < h->fref0[i+1]->i_frame_num
1114 : h->fref0[i]->i_poc < h->fref0[i+1]->i_poc )
1116 h->b_ref_reorder[0] = 1;
1121 static inline void x264_reference_build_list( x264_t *h, int i_poc )
1126 /* build ref list 0/1 */
1129 for( i = 0; h->frames.reference[i]; i++ )
1131 if( h->frames.reference[i]->i_poc < i_poc )
1133 h->fref0[h->i_ref0++] = h->frames.reference[i];
1135 else if( h->frames.reference[i]->i_poc > i_poc )
1137 h->fref1[h->i_ref1++] = h->frames.reference[i];
1141 /* Order ref0 from higher to lower poc */
1145 for( i = 0; i < h->i_ref0 - 1; i++ )
1147 if( h->fref0[i]->i_poc < h->fref0[i+1]->i_poc )
1149 XCHG( x264_frame_t*, h->fref0[i], h->fref0[i+1] );
1156 if( h->sh.i_mmco_remove_from_end )
1157 for( i = h->i_ref0-1; i >= h->i_ref0 - h->sh.i_mmco_remove_from_end; i-- )
1159 int diff = h->i_frame_num - h->fref0[i]->i_frame_num;
1160 h->sh.mmco[h->sh.i_mmco_command_count].i_poc = h->fref0[i]->i_poc;
1161 h->sh.mmco[h->sh.i_mmco_command_count++].i_difference_of_pic_nums = diff;
1164 /* Order ref1 from lower to higher poc (bubble sort) for B-frame */
1168 for( i = 0; i < h->i_ref1 - 1; i++ )
1170 if( h->fref1[i]->i_poc > h->fref1[i+1]->i_poc )
1172 XCHG( x264_frame_t*, h->fref1[i], h->fref1[i+1] );
1179 x264_reference_check_reorder( h );
1181 h->i_ref1 = X264_MIN( h->i_ref1, h->frames.i_max_ref1 );
1182 h->i_ref0 = X264_MIN( h->i_ref0, h->frames.i_max_ref0 );
1183 h->i_ref0 = X264_MIN( h->i_ref0, h->param.i_frame_reference ); // if reconfig() has lowered the limit
1184 assert( h->i_ref0 + h->i_ref1 <= 16 );
1185 h->mb.pic.i_fref[0] = h->i_ref0;
1186 h->mb.pic.i_fref[1] = h->i_ref1;
1189 static void x264_fdec_filter_row( x264_t *h, int mb_y )
1191 /* mb_y is the mb to be encoded next, not the mb to be filtered here */
1192 int b_hpel = h->fdec->b_kept_as_ref;
1193 int b_deblock = !h->sh.i_disable_deblocking_filter_idc;
1194 int b_end = mb_y == h->sps->i_mb_height;
1195 int min_y = mb_y - (1 << h->sh.b_mbaff);
1196 int max_y = b_end ? h->sps->i_mb_height : mb_y;
1197 b_deblock &= b_hpel || h->param.psz_dump_yuv;
1198 if( mb_y & h->sh.b_mbaff )
1206 for( j=0; j<=h->sh.b_mbaff; j++ )
1207 for( i=0; i<3; i++ )
1209 memcpy( h->mb.intra_border_backup[j][i],
1210 h->fdec->plane[i] + ((mb_y*16 >> !!i) + j - 1 - h->sh.b_mbaff) * h->fdec->i_stride[i],
1211 h->sps->i_mb_width*16 >> !!i );
1218 for( y = min_y; y < max_y; y += (1 << h->sh.b_mbaff) )
1219 x264_frame_deblock_row( h, y );
1224 x264_frame_expand_border( h, h->fdec, min_y, b_end );
1225 if( h->param.analyse.i_subpel_refine )
1227 x264_frame_filter( h, h->fdec, min_y, b_end );
1228 x264_frame_expand_border_filtered( h, h->fdec, min_y, b_end );
1232 if( h->param.i_threads > 1 && h->fdec->b_kept_as_ref )
1234 x264_frame_cond_broadcast( h->fdec, mb_y*16 + (b_end ? 10000 : -(X264_THREAD_HEIGHT << h->sh.b_mbaff)) );
1237 min_y = X264_MAX( min_y*16-8, 0 );
1238 max_y = b_end ? h->param.i_height : mb_y*16-8;
1240 if( h->param.analyse.b_psnr )
1243 for( i=0; i<3; i++ )
1244 h->stat.frame.i_ssd[i] +=
1245 x264_pixel_ssd_wxh( &h->pixf,
1246 h->fdec->plane[i] + (min_y>>!!i) * h->fdec->i_stride[i], h->fdec->i_stride[i],
1247 h->fenc->plane[i] + (min_y>>!!i) * h->fenc->i_stride[i], h->fenc->i_stride[i],
1248 h->param.i_width >> !!i, (max_y-min_y) >> !!i );
1251 if( h->param.analyse.b_ssim )
1254 /* offset by 2 pixels to avoid alignment of ssim blocks with dct blocks,
1255 * and overlap by 4 */
1256 min_y += min_y == 0 ? 2 : -6;
1257 h->stat.frame.f_ssim +=
1258 x264_pixel_ssim_wxh( &h->pixf,
1259 h->fdec->plane[0] + 2+min_y*h->fdec->i_stride[0], h->fdec->i_stride[0],
1260 h->fenc->plane[0] + 2+min_y*h->fenc->i_stride[0], h->fenc->i_stride[0],
1261 h->param.i_width-2, max_y-min_y, h->scratch_buffer );
1265 static inline int x264_reference_update( x264_t *h )
1268 if( !h->fdec->b_kept_as_ref )
1270 if( h->param.i_threads > 1 )
1272 x264_frame_push_unused( h, h->fdec );
1273 h->fdec = x264_frame_pop_unused( h, 1 );
1280 /* apply mmco from previous frame. */
1281 for( i = 0; i < h->sh.i_mmco_command_count; i++ )
1282 for( j = 0; h->frames.reference[j]; j++ )
1283 if( h->frames.reference[j]->i_poc == h->sh.mmco[i].i_poc )
1284 x264_frame_push_unused( h, x264_frame_shift( &h->frames.reference[j] ) );
1286 /* move frame in the buffer */
1287 x264_frame_push( h->frames.reference, h->fdec );
1288 if( h->frames.reference[h->sps->i_num_ref_frames] )
1289 x264_frame_push_unused( h, x264_frame_shift( h->frames.reference ) );
1290 h->fdec = x264_frame_pop_unused( h, 1 );
1296 static inline void x264_reference_reset( x264_t *h )
1298 while( h->frames.reference[0] )
1299 x264_frame_push_unused( h, x264_frame_pop( h->frames.reference ) );
1304 static inline void x264_reference_hierarchy_reset( x264_t *h )
1307 int b_hasdelayframe = 0;
1308 if( !h->param.i_bframe_pyramid )
1311 /* look for delay frames -- chain must only contain frames that are disposable */
1312 for( i = 0; h->frames.current[i] && IS_DISPOSABLE( h->frames.current[i]->i_type ); i++ )
1313 b_hasdelayframe |= h->frames.current[i]->i_dts
1314 != h->frames.current[i]->i_frame + h->sps->vui.i_num_reorder_frames;
1316 if( h->param.i_bframe_pyramid != X264_B_PYRAMID_STRICT && !b_hasdelayframe )
1319 /* Remove last BREF. There will never be old BREFs in the
1320 * dpb during a BREF decode when pyramid == STRICT */
1321 for( ref = 0; h->frames.reference[ref]; ref++ )
1323 if( h->param.i_bframe_pyramid == X264_B_PYRAMID_STRICT
1324 && h->frames.reference[ref]->i_type == X264_TYPE_BREF )
1326 int diff = h->i_frame_num - h->frames.reference[ref]->i_frame_num;
1327 h->sh.mmco[h->sh.i_mmco_command_count++].i_difference_of_pic_nums = diff;
1328 x264_frame_push_unused( h, x264_frame_pop( h->frames.reference ) );
1329 h->b_ref_reorder[0] = 1;
1334 /* Prepare to room in the dpb for the delayed display time of the later b-frame's */
1335 h->sh.i_mmco_remove_from_end = X264_MAX( ref + 2 - h->frames.i_max_dpb, 0 );
1338 static inline void x264_slice_init( x264_t *h, int i_nal_type, int i_global_qp )
1340 /* ------------------------ Create slice header ----------------------- */
1341 if( i_nal_type == NAL_SLICE_IDR )
1343 x264_slice_header_init( h, &h->sh, h->sps, h->pps, h->i_idr_pic_id, h->i_frame_num, i_global_qp );
1346 h->i_idr_pic_id = ( h->i_idr_pic_id + 1 ) % 65536;
1350 x264_slice_header_init( h, &h->sh, h->sps, h->pps, -1, h->i_frame_num, i_global_qp );
1352 /* always set the real higher num of ref frame used */
1353 h->sh.b_num_ref_idx_override = 1;
1354 h->sh.i_num_ref_idx_l0_active = h->i_ref0 <= 0 ? 1 : h->i_ref0;
1355 h->sh.i_num_ref_idx_l1_active = h->i_ref1 <= 0 ? 1 : h->i_ref1;
1358 h->fdec->i_frame_num = h->sh.i_frame_num;
1360 if( h->sps->i_poc_type == 0 )
1362 h->sh.i_poc_lsb = h->fdec->i_poc & ( (1 << h->sps->i_log2_max_poc_lsb) - 1 );
1363 h->sh.i_delta_poc_bottom = 0; /* XXX won't work for field */
1365 else if( h->sps->i_poc_type == 1 )
1367 /* FIXME TODO FIXME */
1371 /* Nothing to do ? */
1374 x264_macroblock_slice_init( h );
1377 static int x264_slice_write( x264_t *h )
1380 int mb_xy, i_mb_x, i_mb_y;
1381 int i, i_list, i_ref, i_skip_bak = 0; /* Shut up GCC. */
1383 x264_cabac_t cabac_bak;
1384 uint8_t cabac_prevbyte_bak = 0; /* Shut up GCC. */
1385 /* Assume no more than 3 bytes of NALU escaping. */
1386 int slice_max_size = h->param.i_slice_max_size > 0 ? (h->param.i_slice_max_size-3-NALU_OVERHEAD)*8 : INT_MAX;
1387 int starting_bits = bs_pos(&h->out.bs);
1390 x264_nal_start( h, h->i_nal_type, h->i_nal_ref_idc );
1393 x264_slice_header_write( &h->out.bs, &h->sh, h->i_nal_ref_idc );
1394 if( h->param.b_cabac )
1396 /* alignment needed */
1397 bs_align_1( &h->out.bs );
1400 x264_cabac_context_init( &h->cabac, h->sh.i_type, h->sh.i_qp, h->sh.i_cabac_init_idc );
1401 x264_cabac_encode_init ( &h->cabac, h->out.bs.p, h->out.bs.p_end );
1403 h->mb.i_last_qp = h->sh.i_qp;
1404 h->mb.i_last_dqp = 0;
1406 i_mb_y = h->sh.i_first_mb / h->sps->i_mb_width;
1407 i_mb_x = h->sh.i_first_mb % h->sps->i_mb_width;
1410 while( (mb_xy = i_mb_x + i_mb_y * h->sps->i_mb_width) <= h->sh.i_last_mb )
1412 int mb_spos = bs_pos(&h->out.bs) + x264_cabac_pos(&h->cabac);
1413 if( h->param.i_slice_max_size > 0 )
1415 /* We don't need the contexts because flushing the CABAC encoder has no context
1416 * dependency and macroblocks are only re-encoded in the case where a slice is
1417 * ended (and thus the content of all contexts are thrown away). */
1418 if( h->param.b_cabac )
1420 memcpy( &cabac_bak, &h->cabac, offsetof(x264_cabac_t, f8_bits_encoded) );
1421 /* x264's CABAC writer modifies the previous byte during carry, so it has to be
1423 cabac_prevbyte_bak = h->cabac.p[-1];
1428 i_skip_bak = i_skip;
1432 if( i_mb_x == 0 && !h->mb.b_reencode_mb )
1433 x264_fdec_filter_row( h, i_mb_y );
1436 x264_macroblock_cache_load( h, i_mb_x, i_mb_y );
1438 x264_macroblock_analyse( h );
1440 /* encode this macroblock -> be careful it can change the mb type to P_SKIP if needed */
1441 x264_macroblock_encode( h );
1443 if( x264_bitstream_check_buffer( h ) )
1446 if( h->param.b_cabac )
1448 if( mb_xy > h->sh.i_first_mb && !(h->sh.b_mbaff && (i_mb_y&1)) )
1449 x264_cabac_encode_terminal( &h->cabac );
1451 if( IS_SKIP( h->mb.i_type ) )
1452 x264_cabac_mb_skip( h, 1 );
1455 if( h->sh.i_type != SLICE_TYPE_I )
1456 x264_cabac_mb_skip( h, 0 );
1457 x264_macroblock_write_cabac( h, &h->cabac );
1462 if( IS_SKIP( h->mb.i_type ) )
1466 if( h->sh.i_type != SLICE_TYPE_I )
1468 bs_write_ue( &h->out.bs, i_skip ); /* skip run */
1471 x264_macroblock_write_cavlc( h, &h->out.bs );
1475 int total_bits = bs_pos(&h->out.bs) + x264_cabac_pos(&h->cabac);
1476 int mb_size = total_bits - mb_spos;
1478 /* We'll just re-encode this last macroblock if we go over the max slice size. */
1479 if( total_bits - starting_bits > slice_max_size && !h->mb.b_reencode_mb )
1481 if( mb_xy != h->sh.i_first_mb )
1483 if( h->param.b_cabac )
1485 memcpy( &h->cabac, &cabac_bak, offsetof(x264_cabac_t, f8_bits_encoded) );
1486 h->cabac.p[-1] = cabac_prevbyte_bak;
1491 i_skip = i_skip_bak;
1493 h->mb.b_reencode_mb = 1;
1494 h->sh.i_last_mb = mb_xy-1;
1499 h->sh.i_last_mb = mb_xy;
1500 h->mb.b_reencode_mb = 0;
1504 h->mb.b_reencode_mb = 0;
1507 if( h->param.b_visualize )
1508 x264_visualize_mb( h );
1512 x264_macroblock_cache_save( h );
1514 /* accumulate mb stats */
1515 h->stat.frame.i_mb_count[h->mb.i_type]++;
1517 if( !IS_INTRA(h->mb.i_type) && !IS_SKIP(h->mb.i_type) && !IS_DIRECT(h->mb.i_type) )
1519 if( h->mb.i_partition != D_8x8 )
1520 h->stat.frame.i_mb_partition[h->mb.i_partition] += 4;
1522 for( i = 0; i < 4; i++ )
1523 h->stat.frame.i_mb_partition[h->mb.i_sub_partition[i]] ++;
1524 if( h->param.i_frame_reference > 1 )
1525 for( i_list = 0; i_list <= (h->sh.i_type == SLICE_TYPE_B); i_list++ )
1526 for( i = 0; i < 4; i++ )
1528 i_ref = h->mb.cache.ref[i_list][ x264_scan8[4*i] ];
1530 h->stat.frame.i_mb_count_ref[i_list][i_ref] ++;
1534 if( h->param.i_log_level >= X264_LOG_INFO )
1536 if( h->mb.i_cbp_luma || h->mb.i_cbp_chroma )
1538 int cbpsum = (h->mb.i_cbp_luma&1) + ((h->mb.i_cbp_luma>>1)&1)
1539 + ((h->mb.i_cbp_luma>>2)&1) + (h->mb.i_cbp_luma>>3);
1540 int b_intra = IS_INTRA(h->mb.i_type);
1541 h->stat.frame.i_mb_cbp[!b_intra + 0] += cbpsum;
1542 h->stat.frame.i_mb_cbp[!b_intra + 2] += h->mb.i_cbp_chroma >= 1;
1543 h->stat.frame.i_mb_cbp[!b_intra + 4] += h->mb.i_cbp_chroma == 2;
1545 if( h->mb.i_cbp_luma && !IS_INTRA(h->mb.i_type) )
1547 h->stat.frame.i_mb_count_8x8dct[0] ++;
1548 h->stat.frame.i_mb_count_8x8dct[1] += h->mb.b_transform_8x8;
1550 if( IS_INTRA(h->mb.i_type) && h->mb.i_type != I_PCM )
1552 if( h->mb.i_type == I_16x16 )
1553 h->stat.frame.i_mb_pred_mode[0][h->mb.i_intra16x16_pred_mode]++;
1554 else if( h->mb.i_type == I_8x8 )
1555 for( i = 0; i < 16; i += 4 )
1556 h->stat.frame.i_mb_pred_mode[1][h->mb.cache.intra4x4_pred_mode[x264_scan8[i]]]++;
1557 else //if( h->mb.i_type == I_4x4 )
1558 for( i = 0; i < 16; i++ )
1559 h->stat.frame.i_mb_pred_mode[2][h->mb.cache.intra4x4_pred_mode[x264_scan8[i]]]++;
1563 x264_ratecontrol_mb( h, mb_size );
1567 i_mb_x += i_mb_y & 1;
1568 i_mb_y ^= i_mb_x < h->sps->i_mb_width;
1572 if( i_mb_x == h->sps->i_mb_width )
1579 if( h->param.b_cabac )
1581 x264_cabac_encode_flush( h, &h->cabac );
1582 h->out.bs.p = h->cabac.p;
1587 bs_write_ue( &h->out.bs, i_skip ); /* last skip run */
1588 /* rbsp_slice_trailing_bits */
1589 bs_rbsp_trailing( &h->out.bs );
1590 bs_flush( &h->out.bs );
1592 if( x264_nal_end( h ) )
1595 if( h->sh.i_last_mb == h->mb.i_mb_count-1 )
1597 h->stat.frame.i_misc_bits = bs_pos( &h->out.bs )
1598 + (h->out.i_nal*NALU_OVERHEAD * 8)
1599 - h->stat.frame.i_tex_bits
1600 - h->stat.frame.i_mv_bits;
1601 x264_fdec_filter_row( h, h->sps->i_mb_height );
1607 static void x264_thread_sync_context( x264_t *dst, x264_t *src )
1613 // reference counting
1614 for( f = src->frames.reference; *f; f++ )
1615 (*f)->i_reference_count++;
1616 for( f = dst->frames.reference; *f; f++ )
1617 x264_frame_push_unused( src, *f );
1618 src->fdec->i_reference_count++;
1619 x264_frame_push_unused( src, dst->fdec );
1621 // copy everything except the per-thread pointers and the constants.
1622 memcpy( &dst->i_frame, &src->i_frame, offsetof(x264_t, mb.type) - offsetof(x264_t, i_frame) );
1623 dst->param = src->param;
1624 dst->stat = src->stat;
1627 static void x264_thread_sync_stat( x264_t *dst, x264_t *src )
1631 memcpy( &dst->stat.i_frame_count, &src->stat.i_frame_count, sizeof(dst->stat) - sizeof(dst->stat.frame) );
1634 static void *x264_slices_write( x264_t *h )
1636 int i_slice_num = 0;
1637 if( h->param.i_sync_lookahead )
1638 x264_lower_thread_priority( 10 );
1641 /* Misalign mask has to be set separately for each thread. */
1642 if( h->param.cpu&X264_CPU_SSE_MISALIGN )
1643 x264_cpu_mask_misalign_sse();
1647 if( h->param.b_visualize )
1648 if( x264_visualize_init( h ) )
1653 memset( &h->stat.frame, 0, sizeof(h->stat.frame) );
1654 h->mb.b_reencode_mb = 0;
1655 while( h->sh.i_first_mb < h->mb.i_mb_count )
1657 h->sh.i_last_mb = h->mb.i_mb_count - 1;
1658 if( h->param.i_slice_max_mbs )
1659 h->sh.i_last_mb = h->sh.i_first_mb + h->param.i_slice_max_mbs - 1;
1660 else if( h->param.i_slice_count )
1664 double height = h->sps->i_mb_height >> h->param.b_interlaced;
1665 int width = h->sps->i_mb_width << h->param.b_interlaced;
1666 h->sh.i_last_mb = (int)(height * i_slice_num / h->param.i_slice_count + 0.5) * width - 1;
1668 h->sh.i_last_mb = X264_MIN( h->sh.i_last_mb, h->mb.i_mb_count - 1 );
1669 if( x264_stack_align( x264_slice_write, h ) )
1671 h->sh.i_first_mb = h->sh.i_last_mb + 1;
1675 if( h->param.b_visualize )
1677 x264_visualize_show( h );
1678 x264_visualize_close( h );
1685 /****************************************************************************
1686 * x264_encoder_encode:
1687 * XXX: i_poc : is the poc of the current given picture
1688 * i_frame : is the number of the frame being coded
1689 * ex: type frame poc
1697 ****************************************************************************/
1698 int x264_encoder_encode( x264_t *h,
1699 x264_nal_t **pp_nal, int *pi_nal,
1700 x264_picture_t *pic_in,
1701 x264_picture_t *pic_out )
1703 x264_t *thread_current, *thread_prev, *thread_oldest;
1709 if( h->param.i_threads > 1)
1711 thread_prev = h->thread[ h->i_thread_phase ];
1712 h->i_thread_phase = (h->i_thread_phase + 1) % h->param.i_threads;
1713 thread_current = h->thread[ h->i_thread_phase ];
1714 thread_oldest = h->thread[ (h->i_thread_phase + 1) % h->param.i_threads ];
1715 x264_thread_sync_context( thread_current, thread_prev );
1716 x264_thread_sync_ratecontrol( thread_current, thread_prev, thread_oldest );
1718 // fprintf(stderr, "current: %p prev: %p oldest: %p \n", thread_current, thread_prev, thread_oldest);
1726 // ok to call this before encoding any frames, since the initial values of fdec have b_kept_as_ref=0
1727 if( x264_reference_update( h ) )
1729 h->fdec->i_lines_completed = -1;
1735 /* ------------------- Setup new frame from picture -------------------- */
1736 if( pic_in != NULL )
1738 /* 1: Copy the picture to a frame and move it to a buffer */
1739 x264_frame_t *fenc = x264_frame_pop_unused( h, 0 );
1743 if( x264_frame_copy_picture( h, fenc, pic_in ) < 0 )
1746 if( h->param.i_width != 16 * h->sps->i_mb_width ||
1747 h->param.i_height != 16 * h->sps->i_mb_height )
1748 x264_frame_expand_border_mod16( h, fenc );
1750 fenc->i_frame = h->frames.i_input++;
1752 if( h->frames.b_have_lowres )
1753 x264_frame_init_lowres( h, fenc );
1755 if( h->param.rc.b_mb_tree && h->param.rc.b_stat_read )
1757 if( x264_macroblock_tree_read( h, fenc ) )
1760 else if( h->param.rc.i_aq_mode )
1761 x264_adaptive_quant_frame( h, fenc );
1763 /* 2: Place the frame into the queue for its slice type decision */
1764 x264_lookahead_put_frame( h, fenc );
1766 if( h->frames.i_input <= h->frames.i_delay + 1 - h->param.i_threads )
1768 /* Nothing yet to encode, waiting for filling of buffers */
1769 pic_out->i_type = X264_TYPE_AUTO;
1775 /* signal kills for lookahead thread */
1776 h->lookahead->b_exit_thread = 1;
1777 x264_pthread_cond_broadcast( &h->lookahead->ifbuf.cv_fill );
1781 /* 3: The picture is analyzed in the lookahead */
1782 if( !h->frames.current[0] )
1783 x264_lookahead_get_frames( h );
1785 if( !h->frames.current[0] && x264_lookahead_is_empty( h ) )
1786 return x264_encoder_frame_end( thread_oldest, thread_current, pp_nal, pi_nal, pic_out );
1788 /* ------------------- Get frame to be encoded ------------------------- */
1789 /* 4: get picture to encode */
1790 h->fenc = x264_frame_shift( h->frames.current );
1791 if( h->fenc->param )
1793 x264_encoder_reconfig( h, h->fenc->param );
1794 if( h->fenc->param->param_free )
1795 h->fenc->param->param_free( h->fenc->param );
1798 if( h->fenc->i_type == X264_TYPE_IDR )
1800 h->frames.i_last_idr = h->fenc->i_frame;
1803 h->sh.i_mmco_command_count = 0;
1804 h->sh.i_mmco_remove_from_end = 0;
1805 h->b_ref_reorder[0] =
1806 h->b_ref_reorder[1] = 0;
1808 /* ------------------- Setup frame context ----------------------------- */
1809 /* 5: Init data dependent of frame type */
1810 if( h->fenc->i_type == X264_TYPE_IDR )
1812 /* reset ref pictures */
1813 i_nal_type = NAL_SLICE_IDR;
1814 i_nal_ref_idc = NAL_PRIORITY_HIGHEST;
1815 h->sh.i_type = SLICE_TYPE_I;
1816 x264_reference_reset( h );
1818 else if( h->fenc->i_type == X264_TYPE_I )
1820 i_nal_type = NAL_SLICE;
1821 i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
1822 h->sh.i_type = SLICE_TYPE_I;
1823 x264_reference_hierarchy_reset( h );
1825 else if( h->fenc->i_type == X264_TYPE_P )
1827 i_nal_type = NAL_SLICE;
1828 i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
1829 h->sh.i_type = SLICE_TYPE_P;
1830 x264_reference_hierarchy_reset( h );
1832 else if( h->fenc->i_type == X264_TYPE_BREF )
1834 i_nal_type = NAL_SLICE;
1835 i_nal_ref_idc = h->param.i_bframe_pyramid == X264_B_PYRAMID_STRICT ? NAL_PRIORITY_LOW : NAL_PRIORITY_HIGH;
1836 h->sh.i_type = SLICE_TYPE_B;
1837 x264_reference_hierarchy_reset( h );
1841 i_nal_type = NAL_SLICE;
1842 i_nal_ref_idc = NAL_PRIORITY_DISPOSABLE;
1843 h->sh.i_type = SLICE_TYPE_B;
1847 h->fenc->i_poc = 2 * (h->fenc->i_frame - h->frames.i_last_idr);
1848 h->fdec->i_type = h->fenc->i_type;
1849 h->fdec->i_frame = h->fenc->i_frame;
1850 h->fenc->b_kept_as_ref =
1851 h->fdec->b_kept_as_ref = i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE && h->param.i_keyint_max > 1;
1855 /* ------------------- Init ----------------------------- */
1856 /* build ref list 0/1 */
1857 x264_reference_build_list( h, h->fdec->i_poc );
1859 /* ---------------------- Write the bitstream -------------------------- */
1860 /* Init bitstream context */
1862 bs_init( &h->out.bs, h->out.p_bitstream, h->out.i_bitstream );
1864 if( h->param.b_aud )
1868 if( h->sh.i_type == SLICE_TYPE_I )
1870 else if( h->sh.i_type == SLICE_TYPE_P )
1872 else if( h->sh.i_type == SLICE_TYPE_B )
1877 x264_nal_start( h, NAL_AUD, NAL_PRIORITY_DISPOSABLE );
1878 bs_write( &h->out.bs, 3, pic_type );
1879 bs_rbsp_trailing( &h->out.bs );
1880 if( x264_nal_end( h ) )
1884 h->i_nal_type = i_nal_type;
1885 h->i_nal_ref_idc = i_nal_ref_idc;
1887 int overhead = NALU_OVERHEAD;
1889 /* Write SPS and PPS */
1890 if( i_nal_type == NAL_SLICE_IDR && h->param.b_repeat_headers )
1892 if( h->fenc->i_frame == 0 )
1894 /* identify ourself */
1895 x264_nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
1896 if( x264_sei_version_write( h, &h->out.bs ) )
1898 if( x264_nal_end( h ) )
1900 overhead += h->out.nal[h->out.i_nal-1].i_payload + NALU_OVERHEAD;
1903 /* generate sequence parameters */
1904 x264_nal_start( h, NAL_SPS, NAL_PRIORITY_HIGHEST );
1905 x264_sps_write( &h->out.bs, h->sps );
1906 if( x264_nal_end( h ) )
1908 overhead += h->out.nal[h->out.i_nal-1].i_payload + NALU_OVERHEAD;
1910 /* generate picture parameters */
1911 x264_nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
1912 x264_pps_write( &h->out.bs, h->pps );
1913 if( x264_nal_end( h ) )
1915 overhead += h->out.nal[h->out.i_nal-1].i_payload + NALU_OVERHEAD;
1918 /* Init the rate control */
1919 /* FIXME: Include slice header bit cost. */
1920 x264_ratecontrol_start( h, h->fenc->i_qpplus1, overhead*8 );
1921 i_global_qp = x264_ratecontrol_qp( h );
1923 pic_out->i_qpplus1 =
1924 h->fdec->i_qpplus1 = i_global_qp + 1;
1926 if( h->param.rc.b_stat_read && h->sh.i_type != SLICE_TYPE_I )
1928 x264_reference_build_list_optimal( h );
1929 x264_reference_check_reorder( h );
1932 if( h->sh.i_type == SLICE_TYPE_B )
1933 x264_macroblock_bipred_init( h );
1935 /* ------------------------ Create slice header ----------------------- */
1936 x264_slice_init( h, i_nal_type, i_global_qp );
1938 if( i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE )
1942 if( h->param.i_threads > 1 )
1944 if( x264_pthread_create( &h->thread_handle, NULL, (void*)x264_slices_write, h ) )
1946 h->b_thread_active = 1;
1949 if( (intptr_t)x264_slices_write( h ) )
1952 return x264_encoder_frame_end( thread_oldest, thread_current, pp_nal, pi_nal, pic_out );
1955 static int x264_encoder_frame_end( x264_t *h, x264_t *thread_current,
1956 x264_nal_t **pp_nal, int *pi_nal,
1957 x264_picture_t *pic_out )
1959 int i, j, i_list, frame_size;
1960 char psz_message[80];
1962 if( h->b_thread_active )
1965 x264_pthread_join( h->thread_handle, &ret );
1967 return (intptr_t)ret;
1968 h->b_thread_active = 0;
1972 pic_out->i_type = X264_TYPE_AUTO;
1976 x264_frame_push_unused( thread_current, h->fenc );
1978 /* End bitstream, set output */
1979 *pi_nal = h->out.i_nal;
1980 *pp_nal = h->out.nal;
1982 frame_size = x264_encoder_encapsulate_nals( h );
1986 /* Set output picture properties */
1987 if( h->sh.i_type == SLICE_TYPE_I )
1988 pic_out->i_type = h->i_nal_type == NAL_SLICE_IDR ? X264_TYPE_IDR : X264_TYPE_I;
1989 else if( h->sh.i_type == SLICE_TYPE_P )
1990 pic_out->i_type = X264_TYPE_P;
1992 pic_out->i_type = X264_TYPE_B;
1993 pic_out->i_pts = h->fenc->i_pts;
1995 pic_out->img.i_plane = h->fdec->i_plane;
1996 for(i = 0; i < 3; i++)
1998 pic_out->img.i_stride[i] = h->fdec->i_stride[i];
1999 pic_out->img.plane[i] = h->fdec->plane[i];
2002 /* ---------------------- Update encoder state ------------------------- */
2006 if( x264_ratecontrol_end( h, frame_size * 8 ) < 0 )
2009 x264_noise_reduction_update( thread_current );
2011 /* ---------------------- Compute/Print statistics --------------------- */
2012 x264_thread_sync_stat( h, h->thread[0] );
2015 h->stat.i_frame_count[h->sh.i_type]++;
2016 h->stat.i_frame_size[h->sh.i_type] += frame_size;
2017 h->stat.f_frame_qp[h->sh.i_type] += h->fdec->f_qp_avg_aq;
2019 for( i = 0; i < X264_MBTYPE_MAX; i++ )
2020 h->stat.i_mb_count[h->sh.i_type][i] += h->stat.frame.i_mb_count[i];
2021 for( i = 0; i < X264_PARTTYPE_MAX; i++ )
2022 h->stat.i_mb_partition[h->sh.i_type][i] += h->stat.frame.i_mb_partition[i];
2023 for( i = 0; i < 2; i++ )
2024 h->stat.i_mb_count_8x8dct[i] += h->stat.frame.i_mb_count_8x8dct[i];
2025 for( i = 0; i < 6; i++ )
2026 h->stat.i_mb_cbp[i] += h->stat.frame.i_mb_cbp[i];
2027 for( i = 0; i < 3; i++ )
2028 for( j = 0; j < 13; j++ )
2029 h->stat.i_mb_pred_mode[i][j] += h->stat.frame.i_mb_pred_mode[i][j];
2030 if( h->sh.i_type != SLICE_TYPE_I )
2031 for( i_list = 0; i_list < 2; i_list++ )
2032 for( i = 0; i < 32; i++ )
2033 h->stat.i_mb_count_ref[h->sh.i_type][i_list][i] += h->stat.frame.i_mb_count_ref[i_list][i];
2034 if( h->sh.i_type == SLICE_TYPE_P )
2035 h->stat.i_consecutive_bframes[h->fdec->i_frame - h->fref0[0]->i_frame - 1]++;
2036 if( h->sh.i_type == SLICE_TYPE_B )
2038 h->stat.i_direct_frames[ h->sh.b_direct_spatial_mv_pred ] ++;
2039 if( h->mb.b_direct_auto_write )
2041 //FIXME somewhat arbitrary time constants
2042 if( h->stat.i_direct_score[0] + h->stat.i_direct_score[1] > h->mb.i_mb_count )
2044 for( i = 0; i < 2; i++ )
2045 h->stat.i_direct_score[i] = h->stat.i_direct_score[i] * 9/10;
2047 for( i = 0; i < 2; i++ )
2048 h->stat.i_direct_score[i] += h->stat.frame.i_direct_score[i];
2052 psz_message[0] = '\0';
2053 if( h->param.analyse.b_psnr )
2056 h->stat.frame.i_ssd[0],
2057 h->stat.frame.i_ssd[1],
2058 h->stat.frame.i_ssd[2],
2061 h->stat.i_ssd_global[h->sh.i_type] += ssd[0] + ssd[1] + ssd[2];
2062 h->stat.f_psnr_average[h->sh.i_type] += x264_psnr( ssd[0] + ssd[1] + ssd[2], 3 * h->param.i_width * h->param.i_height / 2 );
2063 h->stat.f_psnr_mean_y[h->sh.i_type] += x264_psnr( ssd[0], h->param.i_width * h->param.i_height );
2064 h->stat.f_psnr_mean_u[h->sh.i_type] += x264_psnr( ssd[1], h->param.i_width * h->param.i_height / 4 );
2065 h->stat.f_psnr_mean_v[h->sh.i_type] += x264_psnr( ssd[2], h->param.i_width * h->param.i_height / 4 );
2067 snprintf( psz_message, 80, " PSNR Y:%5.2f U:%5.2f V:%5.2f",
2068 x264_psnr( ssd[0], h->param.i_width * h->param.i_height ),
2069 x264_psnr( ssd[1], h->param.i_width * h->param.i_height / 4),
2070 x264_psnr( ssd[2], h->param.i_width * h->param.i_height / 4) );
2073 if( h->param.analyse.b_ssim )
2075 double ssim_y = h->stat.frame.f_ssim
2076 / (((h->param.i_width-6)>>2) * ((h->param.i_height-6)>>2));
2077 h->stat.f_ssim_mean_y[h->sh.i_type] += ssim_y;
2078 snprintf( psz_message + strlen(psz_message), 80 - strlen(psz_message),
2079 " SSIM Y:%.5f", ssim_y );
2081 psz_message[79] = '\0';
2083 x264_log( h, X264_LOG_DEBUG,
2084 "frame=%4d QP=%.2f NAL=%d Slice:%c Poc:%-3d I:%-4d P:%-4d SKIP:%-4d size=%d bytes%s\n",
2086 h->fdec->f_qp_avg_aq,
2088 h->sh.i_type == SLICE_TYPE_I ? 'I' : (h->sh.i_type == SLICE_TYPE_P ? 'P' : 'B' ),
2090 h->stat.frame.i_mb_count_i,
2091 h->stat.frame.i_mb_count_p,
2092 h->stat.frame.i_mb_count_skip,
2096 // keep stats all in one place
2097 x264_thread_sync_stat( h->thread[0], h );
2098 // for the use of the next frame
2099 x264_thread_sync_stat( thread_current, h );
2101 #ifdef DEBUG_MB_TYPE
2103 static const char mb_chars[] = { 'i', 'i', 'I', 'C', 'P', '8', 'S',
2104 'D', '<', 'X', 'B', 'X', '>', 'B', 'B', 'B', 'B', '8', 'S' };
2106 for( mb_xy = 0; mb_xy < h->sps->i_mb_width * h->sps->i_mb_height; mb_xy++ )
2108 if( h->mb.type[mb_xy] < X264_MBTYPE_MAX && h->mb.type[mb_xy] >= 0 )
2109 fprintf( stderr, "%c ", mb_chars[ h->mb.type[mb_xy] ] );
2111 fprintf( stderr, "? " );
2113 if( (mb_xy+1) % h->sps->i_mb_width == 0 )
2114 fprintf( stderr, "\n" );
2119 if( h->param.psz_dump_yuv )
2120 x264_frame_dump( h );
2125 static void x264_print_intra( int64_t *i_mb_count, double i_count, int b_print_pcm, char *intra )
2127 intra += sprintf( intra, "I16..4%s: %4.1f%% %4.1f%% %4.1f%%",
2128 b_print_pcm ? "..PCM" : "",
2129 i_mb_count[I_16x16]/ i_count,
2130 i_mb_count[I_8x8] / i_count,
2131 i_mb_count[I_4x4] / i_count );
2133 sprintf( intra, " %4.1f%%", i_mb_count[I_PCM] / i_count );
2136 /****************************************************************************
2137 * x264_encoder_close:
2138 ****************************************************************************/
2139 void x264_encoder_close ( x264_t *h )
2141 int64_t i_yuv_size = 3 * h->param.i_width * h->param.i_height / 2;
2142 int64_t i_mb_count_size[2][7] = {{0}};
2144 int i, j, i_list, i_type;
2145 int b_print_pcm = h->stat.i_mb_count[SLICE_TYPE_I][I_PCM]
2146 || h->stat.i_mb_count[SLICE_TYPE_P][I_PCM]
2147 || h->stat.i_mb_count[SLICE_TYPE_B][I_PCM];
2149 x264_lookahead_delete( h );
2151 for( i=0; i<h->param.i_threads; i++ )
2153 // don't strictly have to wait for the other threads, but it's simpler than canceling them
2154 if( h->thread[i]->b_thread_active )
2156 x264_pthread_join( h->thread[i]->thread_handle, NULL );
2157 assert( h->thread[i]->fenc->i_reference_count == 1 );
2158 x264_frame_delete( h->thread[i]->fenc );
2162 if( h->param.i_threads > 1 )
2164 x264_t *thread_prev;
2166 thread_prev = h->thread[h->i_thread_phase];
2167 x264_thread_sync_ratecontrol( h, thread_prev, h );
2168 x264_thread_sync_ratecontrol( thread_prev, thread_prev, h );
2169 h->i_frame = thread_prev->i_frame + 1 - h->param.i_threads;
2173 /* Slices used and PSNR */
2174 for( i=0; i<5; i++ )
2176 static const int slice_order[] = { SLICE_TYPE_I, SLICE_TYPE_SI, SLICE_TYPE_P, SLICE_TYPE_SP, SLICE_TYPE_B };
2177 static const char *slice_name[] = { "P", "B", "I", "SP", "SI" };
2178 int i_slice = slice_order[i];
2180 if( h->stat.i_frame_count[i_slice] > 0 )
2182 const int i_count = h->stat.i_frame_count[i_slice];
2183 if( h->param.analyse.b_psnr )
2185 x264_log( h, X264_LOG_INFO,
2186 "frame %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",
2187 slice_name[i_slice],
2189 h->stat.f_frame_qp[i_slice] / i_count,
2190 (double)h->stat.i_frame_size[i_slice] / i_count,
2191 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,
2192 h->stat.f_psnr_average[i_slice] / i_count,
2193 x264_psnr( h->stat.i_ssd_global[i_slice], i_count * i_yuv_size ) );
2197 x264_log( h, X264_LOG_INFO,
2198 "frame %s:%-5d Avg QP:%5.2f size:%6.0f\n",
2199 slice_name[i_slice],
2201 h->stat.f_frame_qp[i_slice] / i_count,
2202 (double)h->stat.i_frame_size[i_slice] / i_count );
2206 if( h->param.i_bframe && h->stat.i_frame_count[SLICE_TYPE_P] )
2210 // weight by number of frames (including the P-frame) that are in a sequence of N B-frames
2211 for( i=0; i<=h->param.i_bframe; i++ )
2212 den += (i+1) * h->stat.i_consecutive_bframes[i];
2213 for( i=0; i<=h->param.i_bframe; i++ )
2214 p += sprintf( p, " %4.1f%%", 100. * (i+1) * h->stat.i_consecutive_bframes[i] / den );
2215 x264_log( h, X264_LOG_INFO, "consecutive B-frames:%s\n", buf );
2218 for( i_type = 0; i_type < 2; i_type++ )
2219 for( i = 0; i < X264_PARTTYPE_MAX; i++ )
2221 if( i == D_DIRECT_8x8 ) continue; /* direct is counted as its own type */
2222 i_mb_count_size[i_type][x264_mb_partition_pixel_table[i]] += h->stat.i_mb_partition[i_type][i];
2226 if( h->stat.i_frame_count[SLICE_TYPE_I] > 0 )
2228 int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_I];
2229 double i_count = h->stat.i_frame_count[SLICE_TYPE_I] * h->mb.i_mb_count / 100.0;
2230 x264_print_intra( i_mb_count, i_count, b_print_pcm, buf );
2231 x264_log( h, X264_LOG_INFO, "mb I %s\n", buf );
2233 if( h->stat.i_frame_count[SLICE_TYPE_P] > 0 )
2235 int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_P];
2236 double i_count = h->stat.i_frame_count[SLICE_TYPE_P] * h->mb.i_mb_count / 100.0;
2237 int64_t *i_mb_size = i_mb_count_size[SLICE_TYPE_P];
2238 x264_print_intra( i_mb_count, i_count, b_print_pcm, buf );
2239 x264_log( h, X264_LOG_INFO,
2240 "mb P %s P16..4: %4.1f%% %4.1f%% %4.1f%% %4.1f%% %4.1f%% skip:%4.1f%%\n",
2242 i_mb_size[PIXEL_16x16] / (i_count*4),
2243 (i_mb_size[PIXEL_16x8] + i_mb_size[PIXEL_8x16]) / (i_count*4),
2244 i_mb_size[PIXEL_8x8] / (i_count*4),
2245 (i_mb_size[PIXEL_8x4] + i_mb_size[PIXEL_4x8]) / (i_count*4),
2246 i_mb_size[PIXEL_4x4] / (i_count*4),
2247 i_mb_count[P_SKIP] / i_count );
2249 if( h->stat.i_frame_count[SLICE_TYPE_B] > 0 )
2251 int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_B];
2252 double i_count = h->stat.i_frame_count[SLICE_TYPE_B] * h->mb.i_mb_count / 100.0;
2253 double i_mb_list_count;
2254 int64_t *i_mb_size = i_mb_count_size[SLICE_TYPE_B];
2255 int64_t list_count[3] = {0}; /* 0 == L0, 1 == L1, 2 == BI */
2256 x264_print_intra( i_mb_count, i_count, b_print_pcm, buf );
2257 for( i = 0; i < X264_PARTTYPE_MAX; i++ )
2258 for( j = 0; j < 2; j++ )
2260 int l0 = x264_mb_type_list_table[i][0][j];
2261 int l1 = x264_mb_type_list_table[i][1][j];
2263 list_count[l1+l0*l1] += h->stat.i_mb_count[SLICE_TYPE_B][i] * 2;
2265 list_count[0] += h->stat.i_mb_partition[SLICE_TYPE_B][D_L0_8x8];
2266 list_count[1] += h->stat.i_mb_partition[SLICE_TYPE_B][D_L1_8x8];
2267 list_count[2] += h->stat.i_mb_partition[SLICE_TYPE_B][D_BI_8x8];
2268 i_mb_count[B_DIRECT] += (h->stat.i_mb_partition[SLICE_TYPE_B][D_DIRECT_8x8]+2)/4;
2269 i_mb_list_count = (list_count[0] + list_count[1] + list_count[2]) / 100.0;
2270 x264_log( h, X264_LOG_INFO,
2271 "mb B %s B16..8: %4.1f%% %4.1f%% %4.1f%% direct:%4.1f%% skip:%4.1f%% L0:%4.1f%% L1:%4.1f%% BI:%4.1f%%\n",
2273 i_mb_size[PIXEL_16x16] / (i_count*4),
2274 (i_mb_size[PIXEL_16x8] + i_mb_size[PIXEL_8x16]) / (i_count*4),
2275 i_mb_size[PIXEL_8x8] / (i_count*4),
2276 i_mb_count[B_DIRECT] / i_count,
2277 i_mb_count[B_SKIP] / i_count,
2278 list_count[0] / i_mb_list_count,
2279 list_count[1] / i_mb_list_count,
2280 list_count[2] / i_mb_list_count );
2283 x264_ratecontrol_summary( h );
2285 if( h->stat.i_frame_count[SLICE_TYPE_I] + h->stat.i_frame_count[SLICE_TYPE_P] + h->stat.i_frame_count[SLICE_TYPE_B] > 0 )
2287 #define SUM3(p) (p[SLICE_TYPE_I] + p[SLICE_TYPE_P] + p[SLICE_TYPE_B])
2288 #define SUM3b(p,o) (p[SLICE_TYPE_I][o] + p[SLICE_TYPE_P][o] + p[SLICE_TYPE_B][o])
2289 int64_t i_i8x8 = SUM3b( h->stat.i_mb_count, I_8x8 );
2290 int64_t i_intra = i_i8x8 + SUM3b( h->stat.i_mb_count, I_4x4 )
2291 + SUM3b( h->stat.i_mb_count, I_16x16 );
2292 int64_t i_all_intra = i_intra + SUM3b( h->stat.i_mb_count, I_PCM);
2293 const int i_count = h->stat.i_frame_count[SLICE_TYPE_I] +
2294 h->stat.i_frame_count[SLICE_TYPE_P] +
2295 h->stat.i_frame_count[SLICE_TYPE_B];
2296 int64_t i_mb_count = i_count * h->mb.i_mb_count;
2297 float fps = (float) h->param.i_fps_num / h->param.i_fps_den;
2298 float f_bitrate = fps * SUM3(h->stat.i_frame_size) / i_count / 125;
2300 if( h->pps->b_transform_8x8_mode )
2303 if( h->stat.i_mb_count_8x8dct[0] )
2304 sprintf( buf, " inter:%.1f%%", 100. * h->stat.i_mb_count_8x8dct[1] / h->stat.i_mb_count_8x8dct[0] );
2305 x264_log( h, X264_LOG_INFO, "8x8 transform intra:%.1f%%%s\n", 100. * i_i8x8 / i_intra, buf );
2308 if( h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_AUTO
2309 && h->stat.i_frame_count[SLICE_TYPE_B] )
2311 x264_log( h, X264_LOG_INFO, "direct mvs spatial:%.1f%% temporal:%.1f%%\n",
2312 h->stat.i_direct_frames[1] * 100. / h->stat.i_frame_count[SLICE_TYPE_B],
2313 h->stat.i_direct_frames[0] * 100. / h->stat.i_frame_count[SLICE_TYPE_B] );
2317 if( i_mb_count != i_all_intra )
2318 sprintf( buf, " inter: %.1f%% %.1f%% %.1f%%",
2319 h->stat.i_mb_cbp[1] * 100.0 / ((i_mb_count - i_all_intra)*4),
2320 h->stat.i_mb_cbp[3] * 100.0 / ((i_mb_count - i_all_intra) ),
2321 h->stat.i_mb_cbp[5] * 100.0 / ((i_mb_count - i_all_intra)) );
2322 x264_log( h, X264_LOG_INFO, "coded y,uvDC,uvAC intra: %.1f%% %.1f%% %.1f%%%s\n",
2323 h->stat.i_mb_cbp[0] * 100.0 / (i_all_intra*4),
2324 h->stat.i_mb_cbp[2] * 100.0 / (i_all_intra ),
2325 h->stat.i_mb_cbp[4] * 100.0 / (i_all_intra ), buf );
2327 int64_t fixed_pred_modes[3][9] = {{0}};
2328 int64_t sum_pred_modes[3] = {0};
2329 for( i = 0; i <= I_PRED_16x16_DC_128; i++ )
2331 fixed_pred_modes[0][x264_mb_pred_mode16x16_fix[i]] += h->stat.i_mb_pred_mode[0][i];
2332 sum_pred_modes[0] += h->stat.i_mb_pred_mode[0][i];
2334 if( sum_pred_modes[0] )
2335 x264_log( h, X264_LOG_INFO, "i16 v,h,dc,p: %2.0f%% %2.0f%% %2.0f%% %2.0f%%\n",
2336 fixed_pred_modes[0][0] * 100.0 / sum_pred_modes[0],
2337 fixed_pred_modes[0][1] * 100.0 / sum_pred_modes[0],
2338 fixed_pred_modes[0][2] * 100.0 / sum_pred_modes[0],
2339 fixed_pred_modes[0][3] * 100.0 / sum_pred_modes[0] );
2340 for( i = 1; i <= 2; i++ )
2342 for( j = 0; j <= I_PRED_8x8_DC_128; j++ )
2344 fixed_pred_modes[i][x264_mb_pred_mode4x4_fix(j)] += h->stat.i_mb_pred_mode[i][j];
2345 sum_pred_modes[i] += h->stat.i_mb_pred_mode[i][j];
2347 if( sum_pred_modes[i] )
2348 x264_log( h, X264_LOG_INFO, "i%d v,h,dc,ddl,ddr,vr,hd,vl,hu: %2.0f%% %2.0f%% %2.0f%% %2.0f%% %2.0f%% %2.0f%% %2.0f%% %2.0f%% %2.0f%%\n", (3-i)*4,
2349 fixed_pred_modes[i][0] * 100.0 / sum_pred_modes[i],
2350 fixed_pred_modes[i][1] * 100.0 / sum_pred_modes[i],
2351 fixed_pred_modes[i][2] * 100.0 / sum_pred_modes[i],
2352 fixed_pred_modes[i][3] * 100.0 / sum_pred_modes[i],
2353 fixed_pred_modes[i][4] * 100.0 / sum_pred_modes[i],
2354 fixed_pred_modes[i][5] * 100.0 / sum_pred_modes[i],
2355 fixed_pred_modes[i][6] * 100.0 / sum_pred_modes[i],
2356 fixed_pred_modes[i][7] * 100.0 / sum_pred_modes[i],
2357 fixed_pred_modes[i][8] * 100.0 / sum_pred_modes[i] );
2360 for( i_list = 0; i_list < 2; i_list++ )
2363 for( i_slice = 0; i_slice < 2; i_slice++ )
2368 for( i = 0; i < 32; i++ )
2369 if( h->stat.i_mb_count_ref[i_slice][i_list][i] )
2371 i_den += h->stat.i_mb_count_ref[i_slice][i_list][i];
2376 for( i = 0; i <= i_max; i++ )
2377 p += sprintf( p, " %4.1f%%", 100. * h->stat.i_mb_count_ref[i_slice][i_list][i] / i_den );
2378 x264_log( h, X264_LOG_INFO, "ref %c L%d:%s\n", "PB"[i_slice], i_list, buf );
2382 if( h->param.analyse.b_ssim )
2384 x264_log( h, X264_LOG_INFO,
2385 "SSIM Mean Y:%.7f\n",
2386 SUM3( h->stat.f_ssim_mean_y ) / i_count );
2388 if( h->param.analyse.b_psnr )
2390 x264_log( h, X264_LOG_INFO,
2391 "PSNR Mean Y:%6.3f U:%6.3f V:%6.3f Avg:%6.3f Global:%6.3f kb/s:%.2f\n",
2392 SUM3( h->stat.f_psnr_mean_y ) / i_count,
2393 SUM3( h->stat.f_psnr_mean_u ) / i_count,
2394 SUM3( h->stat.f_psnr_mean_v ) / i_count,
2395 SUM3( h->stat.f_psnr_average ) / i_count,
2396 x264_psnr( SUM3( h->stat.i_ssd_global ), i_count * i_yuv_size ),
2400 x264_log( h, X264_LOG_INFO, "kb/s:%.2f\n", f_bitrate );
2404 x264_ratecontrol_delete( h );
2407 if( h->param.rc.psz_stat_out )
2408 free( h->param.rc.psz_stat_out );
2409 if( h->param.rc.psz_stat_in )
2410 free( h->param.rc.psz_stat_in );
2412 x264_cqm_delete( h );
2413 x264_free( h->nal_buffer );
2414 x264_analyse_free_costs( h );
2416 if( h->param.i_threads > 1)
2417 h = h->thread[h->i_thread_phase];
2420 x264_frame_delete_list( h->frames.unused[0] );
2421 x264_frame_delete_list( h->frames.unused[1] );
2422 x264_frame_delete_list( h->frames.current );
2426 for( i = h->param.i_threads - 1; i >= 0; i-- )
2428 x264_frame_t **frame;
2430 for( frame = h->thread[i]->frames.reference; *frame; frame++ )
2432 assert( (*frame)->i_reference_count > 0 );
2433 (*frame)->i_reference_count--;
2434 if( (*frame)->i_reference_count == 0 )
2435 x264_frame_delete( *frame );
2437 frame = &h->thread[i]->fdec;
2438 assert( (*frame)->i_reference_count > 0 );
2439 (*frame)->i_reference_count--;
2440 if( (*frame)->i_reference_count == 0 )
2441 x264_frame_delete( *frame );
2443 x264_macroblock_cache_end( h->thread[i] );
2444 x264_free( h->thread[i]->out.p_bitstream );
2445 x264_free( h->thread[i]->out.nal);
2446 x264_free( h->thread[i] );
2450 /****************************************************************************
2451 * x264_encoder_delayed_frames:
2452 ****************************************************************************/
2453 int x264_encoder_delayed_frames( x264_t *h )
2455 int delayed_frames = 0;
2457 for( i=0; i<h->param.i_threads; i++ )
2458 delayed_frames += h->thread[i]->b_thread_active;
2459 h = h->thread[h->i_thread_phase];
2460 for( i=0; h->frames.current[i]; i++ )
2462 x264_pthread_mutex_lock( &h->lookahead->ofbuf.mutex );
2463 x264_pthread_mutex_lock( &h->lookahead->ifbuf.mutex );
2464 x264_pthread_mutex_lock( &h->lookahead->next.mutex );
2465 delayed_frames += h->lookahead->ifbuf.i_size + h->lookahead->next.i_size + h->lookahead->ofbuf.i_size;
2466 x264_pthread_mutex_unlock( &h->lookahead->next.mutex );
2467 x264_pthread_mutex_unlock( &h->lookahead->ifbuf.mutex );
2468 x264_pthread_mutex_unlock( &h->lookahead->ofbuf.mutex );
2469 return delayed_frames;