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 int64_t x264_sqe( x264_t *h, uint8_t *pix1, int i_pix_stride, uint8_t *pix2, int i_pix2_stride, int i_width, int i_height )
95 #define SSD(size) i_sqe += h->pixf.ssd[size]( pix1+y*i_pix_stride+x, i_pix_stride, \
96 pix2+y*i_pix2_stride+x, i_pix2_stride );
97 for( y = 0; y < i_height-15; y += 16 )
99 for( x = 0; x < i_width-15; x += 16 )
105 for( x = 0; x < i_width-7; x += 8 )
108 x264_cpu_restore( h->param.cpu );
113 static float x264_psnr( int64_t i_sqe, int64_t i_size )
115 double f_mse = (double)i_sqe / ((double)65025.0 * (double)i_size);
116 if( f_mse <= 0.0000000001 ) /* Max 100dB */
119 return (float)(-10.0 * log( f_mse ) / log( 10.0 ));
122 #ifdef DEBUG_DUMP_FRAME
123 static void x264_frame_dump( x264_t *h, x264_frame_t *fr, char *name )
125 FILE * f = fopen( name, "a" );
128 fseek( f, 0, SEEK_END );
130 for( i = 0; i < fr->i_plane; i++ )
132 for( y = 0; y < h->param.i_height / ( i == 0 ? 1 : 2 ); y++ )
134 fwrite( &fr->plane[i][y*fr->i_stride[i]], 1, h->param.i_width / ( i == 0 ? 1 : 2 ), f );
142 /* Fill "default" values */
143 static void x264_slice_header_init( x264_t *h, x264_slice_header_t *sh,
144 x264_sps_t *sps, x264_pps_t *pps,
145 int i_type, int i_idr_pic_id, int i_frame, int i_qp )
147 x264_param_t *param = &h->param;
150 /* First we fill all field */
156 sh->i_last_mb = h->sps->i_mb_width * h->sps->i_mb_height;
157 sh->i_pps_id = pps->i_id;
159 sh->i_frame_num = i_frame;
161 sh->b_field_pic = 0; /* Not field support for now */
162 sh->b_bottom_field = 1; /* not yet used */
164 sh->i_idr_pic_id = i_idr_pic_id;
166 /* poc stuff, fixed later */
168 sh->i_delta_poc_bottom = 0;
169 sh->i_delta_poc[0] = 0;
170 sh->i_delta_poc[1] = 0;
172 sh->i_redundant_pic_cnt = 0;
174 sh->b_direct_spatial_mv_pred = ( param->analyse.i_direct_mv_pred == X264_DIRECT_PRED_SPATIAL );
176 sh->b_num_ref_idx_override = 0;
177 sh->i_num_ref_idx_l0_active = 1;
178 sh->i_num_ref_idx_l1_active = 1;
180 sh->b_ref_pic_list_reordering_l0 = h->b_ref_reorder[0];
181 sh->b_ref_pic_list_reordering_l1 = h->b_ref_reorder[1];
183 /* If the ref list isn't in the default order, construct reordering header */
184 /* List1 reordering isn't needed yet */
185 if( sh->b_ref_pic_list_reordering_l0 )
187 int pred_frame_num = i_frame;
188 for( i = 0; i < h->i_ref0; i++ )
190 int diff = h->fref0[i]->i_frame_num - pred_frame_num;
192 x264_log( h, X264_LOG_ERROR, "diff frame num == 0\n" );
193 sh->ref_pic_list_order[0][i].idc = ( diff > 0 );
194 sh->ref_pic_list_order[0][i].arg = abs( diff ) - 1;
195 pred_frame_num = h->fref0[i]->i_frame_num;
199 sh->i_cabac_init_idc = param->i_cabac_init_idc;
202 sh->i_qp_delta = i_qp - pps->i_pic_init_qp;
203 sh->b_sp_for_swidth = 0;
206 /* If effective qp <= 15, deblocking would have no effect anyway */
207 if( param->b_deblocking_filter
208 && ( h->mb.b_variable_qp
209 || 15 < i_qp + X264_MAX(param->i_deblocking_filter_alphac0, param->i_deblocking_filter_beta) ) )
211 sh->i_disable_deblocking_filter_idc = 0;
215 sh->i_disable_deblocking_filter_idc = 1;
217 sh->i_alpha_c0_offset = param->i_deblocking_filter_alphac0 << 1;
218 sh->i_beta_offset = param->i_deblocking_filter_beta << 1;
221 static void x264_slice_header_write( bs_t *s, x264_slice_header_t *sh, int i_nal_ref_idc )
225 bs_write_ue( s, sh->i_first_mb );
226 bs_write_ue( s, sh->i_type + 5 ); /* same type things */
227 bs_write_ue( s, sh->i_pps_id );
228 bs_write( s, sh->sps->i_log2_max_frame_num, sh->i_frame_num );
230 if( sh->i_idr_pic_id >= 0 ) /* NAL IDR */
232 bs_write_ue( s, sh->i_idr_pic_id );
235 if( sh->sps->i_poc_type == 0 )
237 bs_write( s, sh->sps->i_log2_max_poc_lsb, sh->i_poc_lsb );
238 if( sh->pps->b_pic_order && !sh->b_field_pic )
240 bs_write_se( s, sh->i_delta_poc_bottom );
243 else if( sh->sps->i_poc_type == 1 && !sh->sps->b_delta_pic_order_always_zero )
245 bs_write_se( s, sh->i_delta_poc[0] );
246 if( sh->pps->b_pic_order && !sh->b_field_pic )
248 bs_write_se( s, sh->i_delta_poc[1] );
252 if( sh->pps->b_redundant_pic_cnt )
254 bs_write_ue( s, sh->i_redundant_pic_cnt );
257 if( sh->i_type == SLICE_TYPE_B )
259 bs_write1( s, sh->b_direct_spatial_mv_pred );
261 if( sh->i_type == SLICE_TYPE_P || sh->i_type == SLICE_TYPE_SP || sh->i_type == SLICE_TYPE_B )
263 bs_write1( s, sh->b_num_ref_idx_override );
264 if( sh->b_num_ref_idx_override )
266 bs_write_ue( s, sh->i_num_ref_idx_l0_active - 1 );
267 if( sh->i_type == SLICE_TYPE_B )
269 bs_write_ue( s, sh->i_num_ref_idx_l1_active - 1 );
274 /* ref pic list reordering */
275 if( sh->i_type != SLICE_TYPE_I )
277 bs_write1( s, sh->b_ref_pic_list_reordering_l0 );
278 if( sh->b_ref_pic_list_reordering_l0 )
280 for( i = 0; i < sh->i_num_ref_idx_l0_active; i++ )
282 bs_write_ue( s, sh->ref_pic_list_order[0][i].idc );
283 bs_write_ue( s, sh->ref_pic_list_order[0][i].arg );
289 if( sh->i_type == SLICE_TYPE_B )
291 bs_write1( s, sh->b_ref_pic_list_reordering_l1 );
292 if( sh->b_ref_pic_list_reordering_l1 )
294 for( i = 0; i < sh->i_num_ref_idx_l1_active; i++ )
296 bs_write_ue( s, sh->ref_pic_list_order[1][i].idc );
297 bs_write_ue( s, sh->ref_pic_list_order[1][i].arg );
303 if( ( sh->pps->b_weighted_pred && ( sh->i_type == SLICE_TYPE_P || sh->i_type == SLICE_TYPE_SP ) ) ||
304 ( sh->pps->b_weighted_bipred == 1 && sh->i_type == SLICE_TYPE_B ) )
309 if( i_nal_ref_idc != 0 )
311 if( sh->i_idr_pic_id >= 0 )
313 bs_write1( s, 0 ); /* no output of prior pics flag */
314 bs_write1( s, 0 ); /* long term reference flag */
318 bs_write1( s, 0 ); /* adaptive_ref_pic_marking_mode_flag */
322 if( sh->pps->b_cabac && sh->i_type != SLICE_TYPE_I )
324 bs_write_ue( s, sh->i_cabac_init_idc );
326 bs_write_se( s, sh->i_qp_delta ); /* slice qp delta */
328 if( sh->i_type == SLICE_TYPE_SP || sh->i_type == SLICE_TYPE_SI )
330 if( sh->i_type == SLICE_TYPE_SP )
332 bs_write1( s, sh->b_sp_for_swidth );
334 bs_write_se( s, sh->i_qs_delta );
338 if( sh->pps->b_deblocking_filter_control )
340 bs_write_ue( s, sh->i_disable_deblocking_filter_idc );
341 if( sh->i_disable_deblocking_filter_idc != 1 )
343 bs_write_se( s, sh->i_alpha_c0_offset >> 1 );
344 bs_write_se( s, sh->i_beta_offset >> 1 );
349 /****************************************************************************
351 ****************************************************************************
352 ****************************** External API*********************************
353 ****************************************************************************
355 ****************************************************************************/
357 static int x264_validate_parameters( x264_t *h )
359 if( h->param.i_width <= 0 || h->param.i_height <= 0 )
361 x264_log( h, X264_LOG_ERROR, "invalid width x height (%dx%d)\n",
362 h->param.i_width, h->param.i_height );
366 if( h->param.i_width % 16 != 0 || h->param.i_height % 16 != 0 )
368 x264_log( h, X264_LOG_ERROR, "width %% 16 != 0 or height %% 16 != 0 (%dx%d)\n",
369 h->param.i_width, h->param.i_height );
372 if( h->param.i_csp != X264_CSP_I420 )
374 x264_log( h, X264_LOG_ERROR, "invalid CSP (only I420 supported)\n" );
378 h->param.i_threads = x264_clip3( h->param.i_threads, 1, X264_SLICE_MAX );
379 h->param.i_threads = X264_MIN( h->param.i_threads, h->param.i_height / 16 );
381 if( h->param.i_threads > 1 )
383 x264_log( h, X264_LOG_WARNING, "not compiled with pthread support!\n");
384 x264_log( h, X264_LOG_WARNING, "multislicing anyway, but you won't see any speed gain.\n" );
388 if( !h->param.rc.b_cbr && h->param.rc.i_qp_constant == 0 )
390 h->mb.b_lossless = 1;
391 h->param.analyse.b_transform_8x8 = 0;
392 h->param.i_cqm_preset = X264_CQM_FLAT;
393 h->param.psz_cqm_file = NULL;
394 h->param.rc.f_ip_factor = 1;
395 h->param.rc.f_pb_factor = 1;
396 h->param.analyse.b_psnr = 0;
399 h->param.i_frame_reference = x264_clip3( h->param.i_frame_reference, 1, 16 );
400 if( h->param.i_keyint_max <= 0 )
401 h->param.i_keyint_max = 1;
402 h->param.i_keyint_min = x264_clip3( h->param.i_keyint_min, 1, h->param.i_keyint_max/2+1 );
404 h->param.i_bframe = x264_clip3( h->param.i_bframe, 0, X264_BFRAME_MAX );
405 h->param.i_bframe_bias = x264_clip3( h->param.i_bframe_bias, -90, 100 );
406 h->param.b_bframe_pyramid = h->param.b_bframe_pyramid && h->param.i_bframe > 1;
408 h->param.i_deblocking_filter_alphac0 = x264_clip3( h->param.i_deblocking_filter_alphac0, -6, 6 );
409 h->param.i_deblocking_filter_beta = x264_clip3( h->param.i_deblocking_filter_beta, -6, 6 );
411 h->param.i_cabac_init_idc = x264_clip3( h->param.i_cabac_init_idc, -1, 2 );
412 /* don't yet support merging of cabac stats */
413 if( h->param.i_threads > 1 && h->param.i_cabac_init_idc == -1 )
414 h->param.i_cabac_init_idc = 0;
416 if( h->param.i_cqm_preset < X264_CQM_FLAT || h->param.i_cqm_preset > X264_CQM_CUSTOM )
417 h->param.i_cqm_preset = X264_CQM_FLAT;
419 if( h->param.analyse.i_me_method < X264_ME_DIA ||
420 h->param.analyse.i_me_method > X264_ME_ESA )
421 h->param.analyse.i_me_method = X264_ME_HEX;
422 if( h->param.analyse.i_me_range < 4 )
423 h->param.analyse.i_me_range = 4;
424 if( h->param.analyse.i_me_range > 16 && h->param.analyse.i_me_method <= X264_ME_HEX )
425 h->param.analyse.i_me_range = 16;
426 h->param.analyse.i_subpel_refine = x264_clip3( h->param.analyse.i_subpel_refine, 1, 6 );
427 if( !(h->param.analyse.inter & X264_ANALYSE_PSUB16x16) )
428 h->param.analyse.inter &= ~X264_ANALYSE_PSUB8x8;
429 if( !h->param.analyse.b_transform_8x8 )
431 h->param.analyse.inter &= ~X264_ANALYSE_I8x8;
432 h->param.analyse.intra &= ~X264_ANALYSE_I8x8;
434 h->param.analyse.i_chroma_qp_offset = x264_clip3(h->param.analyse.i_chroma_qp_offset, -12, 12);
435 h->param.analyse.i_mv_range = x264_clip3(h->param.analyse.i_mv_range, 32, 2048);
437 if( h->param.rc.f_qblur < 0 )
438 h->param.rc.f_qblur = 0;
439 if( h->param.rc.f_complexity_blur < 0 )
440 h->param.rc.f_complexity_blur = 0;
441 h->param.rc.i_qp_constant = x264_clip3(h->param.rc.i_qp_constant, 0, 51);
446 /****************************************************************************
448 ****************************************************************************/
449 x264_t *x264_encoder_open ( x264_param_t *param )
451 x264_t *h = x264_malloc( sizeof( x264_t ) );
454 memset( h, 0, sizeof( x264_t ) );
456 /* Create a copy of param */
457 memcpy( &h->param, param, sizeof( x264_param_t ) );
459 if( x264_validate_parameters( h ) < 0 )
465 if( h->param.psz_cqm_file )
466 if( x264_cqm_parse_file( h, h->param.psz_cqm_file ) < 0 )
472 if( h->param.rc.psz_stat_out )
473 h->param.rc.psz_stat_out = strdup( h->param.rc.psz_stat_out );
474 if( h->param.rc.psz_stat_in )
475 h->param.rc.psz_stat_in = strdup( h->param.rc.psz_stat_in );
476 if( h->param.rc.psz_rc_eq )
477 h->param.rc.psz_rc_eq = strdup( h->param.rc.psz_rc_eq );
480 if( h->param.vui.i_sar_width > 0 && h->param.vui.i_sar_height > 0 )
482 int i_w = param->vui.i_sar_width;
483 int i_h = param->vui.i_sar_height;
484 int a = i_w, b = i_h;
496 while( i_w > 65535 || i_h > 65535 )
502 h->param.vui.i_sar_width = 0;
503 h->param.vui.i_sar_height = 0;
504 if( i_w == 0 || i_h == 0 )
506 x264_log( h, X264_LOG_ERROR, "cannot create valid sample aspect ratio\n" );
508 else if( i_w == i_h )
510 x264_log( h, X264_LOG_INFO, "no need for a SAR\n" );
514 x264_log( h, X264_LOG_INFO, "using SAR=%d/%d\n", i_w, i_h );
515 h->param.vui.i_sar_width = i_w;
516 h->param.vui.i_sar_height = i_h;
523 h->out.i_bitstream = X264_MAX( 1000000, h->param.i_width * h->param.i_height * 1.7
524 * ( h->param.rc.b_cbr ? pow( 0.5, h->param.rc.i_qp_min )
525 : pow( 0.5, h->param.rc.i_qp_constant ) * X264_MAX( 1, h->param.rc.f_ip_factor )));
526 h->out.p_bitstream = x264_malloc( h->out.i_bitstream );
532 h->sps = &h->sps_array[0];
533 x264_sps_init( h->sps, 0, &h->param );
535 h->pps = &h->pps_array[0];
536 x264_pps_init( h->pps, 0, &h->param, h->sps);
540 h->mb.i_mb_count = h->sps->i_mb_width * h->sps->i_mb_height;
543 h->frames.i_delay = h->param.i_bframe;
544 h->frames.i_max_ref0 = h->param.i_frame_reference;
545 h->frames.i_max_ref1 = h->sps->vui.i_num_reorder_frames;
546 h->frames.i_max_dpb = h->sps->vui.i_max_dec_frame_buffering + 1;
548 for( i = 0; i < X264_BFRAME_MAX + 3; i++ )
550 h->frames.current[i] = NULL;
551 h->frames.next[i] = NULL;
552 h->frames.unused[i] = NULL;
554 for( i = 0; i < 1 + h->frames.i_delay; i++ )
556 h->frames.unused[i] = x264_frame_new( h );
558 for( i = 0; i < h->frames.i_max_dpb; i++ )
560 h->frames.reference[i] = x264_frame_new( h );
562 h->frames.reference[h->frames.i_max_dpb] = NULL;
563 h->frames.i_last_idr = - h->param.i_keyint_max;
564 h->frames.i_input = 0;
565 h->frames.last_nonb = NULL;
570 h->fdec = h->frames.reference[0];
573 x264_macroblock_cache_init( h );
575 /* init cabac adaptive model */
576 x264_cabac_model_init( &h->cabac );
578 /* init CPU functions */
579 x264_predict_16x16_init( h->param.cpu, h->predict_16x16 );
580 x264_predict_8x8c_init( h->param.cpu, h->predict_8x8c );
581 x264_predict_8x8_init( h->param.cpu, h->predict_8x8 );
582 x264_predict_4x4_init( h->param.cpu, h->predict_4x4 );
584 x264_pixel_init( h->param.cpu, &h->pixf );
585 x264_dct_init( h->param.cpu, &h->dctf );
586 x264_mc_init( h->param.cpu, &h->mc );
587 x264_csp_init( h->param.cpu, h->param.i_csp, &h->csp );
588 x264_quant_init( h, h->param.cpu, &h->quantf );
590 memcpy( h->pixf.mbcmp,
591 ( h->mb.b_lossless || h->param.analyse.i_subpel_refine <= 1 ) ? h->pixf.sad : h->pixf.satd,
592 sizeof(h->pixf.mbcmp) );
595 if( x264_ratecontrol_new( h ) < 0 )
598 x264_log( h, X264_LOG_INFO, "using cpu capabilities %s%s%s%s%s%s\n",
599 param->cpu&X264_CPU_MMX ? "MMX " : "",
600 param->cpu&X264_CPU_MMXEXT ? "MMXEXT " : "",
601 param->cpu&X264_CPU_SSE ? "SSE " : "",
602 param->cpu&X264_CPU_SSE2 ? "SSE2 " : "",
603 param->cpu&X264_CPU_3DNOW ? "3DNow! " : "",
604 param->cpu&X264_CPU_ALTIVEC ? "Altivec " : "" );
607 for( i = 1; i < param->i_threads; i++ )
608 h->thread[i] = x264_malloc( sizeof(x264_t) );
613 /****************************************************************************
614 * x264_encoder_reconfig:
615 ****************************************************************************/
616 int x264_encoder_reconfig( x264_t *h, x264_param_t *param )
618 h->param.i_bframe_bias = param->i_bframe_bias;
619 h->param.i_deblocking_filter_alphac0 = param->i_deblocking_filter_alphac0;
620 h->param.i_deblocking_filter_beta = param->i_deblocking_filter_beta;
621 h->param.analyse.i_me_method = param->analyse.i_me_method;
622 h->param.analyse.i_me_range = param->analyse.i_me_range;
623 h->param.analyse.i_subpel_refine = param->analyse.i_subpel_refine;
624 h->param.analyse.intra = param->analyse.intra;
625 h->param.analyse.inter = param->analyse.inter;
626 if( h->sps->b_direct8x8_inference && h->param.i_bframe
627 && h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_TEMPORAL )
628 h->param.analyse.inter &= ~X264_ANALYSE_PSUB8x8;
630 memcpy( h->pixf.mbcmp,
631 ( h->mb.b_lossless || h->param.analyse.i_subpel_refine <= 1 ) ? h->pixf.sad : h->pixf.satd,
632 sizeof(h->pixf.mbcmp) );
634 return x264_validate_parameters( h );
638 static void x264_nal_start( x264_t *h, int i_type, int i_ref_idc )
640 x264_nal_t *nal = &h->out.nal[h->out.i_nal];
642 nal->i_ref_idc = i_ref_idc;
643 nal->i_type = i_type;
645 bs_align_0( &h->out.bs ); /* not needed */
648 nal->p_payload= &h->out.p_bitstream[bs_pos( &h->out.bs) / 8];
650 static void x264_nal_end( x264_t *h )
652 x264_nal_t *nal = &h->out.nal[h->out.i_nal];
654 bs_align_0( &h->out.bs ); /* not needed */
656 nal->i_payload = &h->out.p_bitstream[bs_pos( &h->out.bs)/8] - nal->p_payload;
661 /****************************************************************************
662 * x264_encoder_headers:
663 ****************************************************************************/
664 int x264_encoder_headers( x264_t *h, x264_nal_t **pp_nal, int *pi_nal )
666 /* init bitstream context */
668 bs_init( &h->out.bs, h->out.p_bitstream, h->out.i_bitstream );
670 /* Put SPS and PPS */
671 if( h->i_frame == 0 )
673 /* identify ourself */
674 x264_nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
675 x264_sei_version_write( &h->out.bs );
678 /* generate sequence parameters */
679 x264_nal_start( h, NAL_SPS, NAL_PRIORITY_HIGHEST );
680 x264_sps_write( &h->out.bs, h->sps );
683 /* generate picture parameters */
684 x264_nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
685 x264_pps_write( &h->out.bs, h->pps );
689 *pi_nal = h->out.i_nal;
690 *pp_nal = &h->out.nal[0];
696 static void x264_frame_put( x264_frame_t *list[X264_BFRAME_MAX], x264_frame_t *frame )
699 while( list[i] ) i++;
703 static void x264_frame_push( x264_frame_t *list[X264_BFRAME_MAX], x264_frame_t *frame )
706 while( list[i] ) i++;
712 static x264_frame_t *x264_frame_get( x264_frame_t *list[X264_BFRAME_MAX+1] )
714 x264_frame_t *frame = list[0];
716 for( i = 0; list[i]; i++ )
721 static void x264_frame_sort( x264_frame_t *list[X264_BFRAME_MAX+1], int b_dts )
726 for( i = 0; list[i+1]; i++ )
728 int dtype = list[i]->i_type - list[i+1]->i_type;
729 int dtime = list[i]->i_frame - list[i+1]->i_frame;
730 int swap = b_dts ? dtype > 0 || ( dtype == 0 && dtime > 0 )
734 x264_frame_t *tmp = list[i+1];
742 #define x264_frame_sort_dts(list) x264_frame_sort(list, 1)
743 #define x264_frame_sort_pts(list) x264_frame_sort(list, 0)
745 static inline void x264_reference_build_list( x264_t *h, int i_poc, int i_slice_type )
750 /* build ref list 0/1 */
753 for( i = 1; i < h->frames.i_max_dpb; i++ )
755 if( h->frames.reference[i]->i_poc >= 0 )
757 if( h->frames.reference[i]->i_poc < i_poc )
759 h->fref0[h->i_ref0++] = h->frames.reference[i];
761 else if( h->frames.reference[i]->i_poc > i_poc )
763 h->fref1[h->i_ref1++] = h->frames.reference[i];
768 /* Order ref0 from higher to lower poc */
772 for( i = 0; i < h->i_ref0 - 1; i++ )
774 if( h->fref0[i]->i_poc < h->fref0[i+1]->i_poc )
776 x264_frame_t *tmp = h->fref0[i+1];
778 h->fref0[i+1] = h->fref0[i];
785 /* Order ref1 from lower to higher poc (bubble sort) for B-frame */
789 for( i = 0; i < h->i_ref1 - 1; i++ )
791 if( h->fref1[i]->i_poc > h->fref1[i+1]->i_poc )
793 x264_frame_t *tmp = h->fref1[i+1];
795 h->fref1[i+1] = h->fref1[i];
803 /* In the standard, a P-frame's ref list is sorted by frame_num.
804 * We use POC, but check whether explicit reordering is needed */
805 h->b_ref_reorder[0] =
806 h->b_ref_reorder[1] = 0;
807 if( i_slice_type == SLICE_TYPE_P )
809 for( i = 0; i < h->i_ref0 - 1; i++ )
810 if( h->fref0[i]->i_frame_num < h->fref0[i+1]->i_frame_num )
812 h->b_ref_reorder[0] = 1;
817 h->i_ref1 = X264_MIN( h->i_ref1, h->frames.i_max_ref1 );
818 h->i_ref0 = X264_MIN( h->i_ref0, h->frames.i_max_ref0 );
819 h->i_ref0 = X264_MIN( h->i_ref0, 16 - h->i_ref1 );
822 static inline void x264_reference_update( x264_t *h )
826 /* apply deblocking filter to the current decoded picture */
827 if( !h->sh.i_disable_deblocking_filter_idc )
829 TIMER_START( i_mtime_filter );
830 x264_frame_deblocking_filter( h, h->sh.i_type );
831 TIMER_STOP( i_mtime_filter );
834 x264_frame_expand_border( h->fdec );
836 /* create filtered images */
837 x264_frame_filter( h->param.cpu, h->fdec );
839 /* expand border of filtered images */
840 x264_frame_expand_border_filtered( h->fdec );
842 /* move lowres copy of the image to the ref frame */
843 for( i = 0; i < 4; i++)
845 uint8_t *tmp = h->fdec->lowres[i];
846 h->fdec->lowres[i] = h->fenc->lowres[i];
847 h->fenc->lowres[i] = tmp;
850 /* adaptive B decision needs a pointer, since it can't use the ref lists */
851 if( h->sh.i_type != SLICE_TYPE_B )
852 h->frames.last_nonb = h->fdec;
854 /* move frame in the buffer */
855 h->fdec = h->frames.reference[h->frames.i_max_dpb-1];
856 for( i = h->frames.i_max_dpb-1; i > 0; i-- )
858 h->frames.reference[i] = h->frames.reference[i-1];
860 h->frames.reference[0] = h->fdec;
863 static inline void x264_reference_reset( x264_t *h )
867 /* reset ref pictures */
868 for( i = 1; i < h->frames.i_max_dpb; i++ )
870 h->frames.reference[i]->i_poc = -1;
872 h->frames.reference[0]->i_poc = 0;
875 static inline void x264_slice_init( x264_t *h, int i_nal_type, int i_slice_type, int i_global_qp )
877 /* ------------------------ Create slice header ----------------------- */
878 if( i_nal_type == NAL_SLICE_IDR )
880 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 );
883 h->i_idr_pic_id = ( h->i_idr_pic_id + 1 ) % 65536;
887 x264_slice_header_init( h, &h->sh, h->sps, h->pps, i_slice_type, -1, h->i_frame_num - 1, i_global_qp );
889 /* always set the real higher num of ref frame used */
890 h->sh.b_num_ref_idx_override = 1;
891 h->sh.i_num_ref_idx_l0_active = h->i_ref0 <= 0 ? 1 : h->i_ref0;
892 h->sh.i_num_ref_idx_l1_active = h->i_ref1 <= 0 ? 1 : h->i_ref1;
895 h->fdec->i_frame_num = h->sh.i_frame_num;
897 if( h->sps->i_poc_type == 0 )
899 h->sh.i_poc_lsb = h->fdec->i_poc & ( (1 << h->sps->i_log2_max_poc_lsb) - 1 );
900 h->sh.i_delta_poc_bottom = 0; /* XXX won't work for field */
902 else if( h->sps->i_poc_type == 1 )
904 /* FIXME TODO FIXME */
908 /* Nothing to do ? */
911 /* get adapative cabac model if needed */
912 if( h->param.b_cabac )
914 if( h->param.i_cabac_init_idc == -1 )
916 h->sh.i_cabac_init_idc = x264_cabac_model_get( &h->cabac, i_slice_type );
920 x264_macroblock_slice_init( h );
923 static int x264_slice_write( x264_t *h )
930 memset( &h->stat.frame, 0, sizeof(h->stat.frame) );
933 x264_nal_start( h, h->i_nal_type, h->i_nal_ref_idc );
936 x264_slice_header_write( &h->out.bs, &h->sh, h->i_nal_ref_idc );
937 if( h->param.b_cabac )
939 /* alignment needed */
940 bs_align_1( &h->out.bs );
943 x264_cabac_context_init( &h->cabac, h->sh.i_type, h->sh.i_qp, h->sh.i_cabac_init_idc );
944 x264_cabac_encode_init ( &h->cabac, &h->out.bs );
946 h->mb.i_last_qp = h->sh.i_qp;
947 h->mb.i_last_dqp = 0;
949 for( mb_xy = h->sh.i_first_mb, i_skip = 0; mb_xy < h->sh.i_last_mb; mb_xy++ )
951 const int i_mb_y = mb_xy / h->sps->i_mb_width;
952 const int i_mb_x = mb_xy % h->sps->i_mb_width;
954 int mb_spos = bs_pos(&h->out.bs);
957 x264_macroblock_cache_load( h, i_mb_x, i_mb_y );
959 /* analyse parameters
960 * Slice I: choose I_4x4 or I_16x16 mode
961 * Slice P: choose between using P mode or intra (4x4 or 16x16)
963 TIMER_START( i_mtime_analyse );
964 x264_macroblock_analyse( h );
965 TIMER_STOP( i_mtime_analyse );
967 /* encode this macrobock -> be carefull it can change the mb type to P_SKIP if needed */
968 TIMER_START( i_mtime_encode );
969 x264_macroblock_encode( h );
970 TIMER_STOP( i_mtime_encode );
972 TIMER_START( i_mtime_write );
973 if( h->param.b_cabac )
975 if( mb_xy > h->sh.i_first_mb )
976 x264_cabac_encode_terminal( &h->cabac, 0 );
978 if( IS_SKIP( h->mb.i_type ) )
979 x264_cabac_mb_skip( h, 1 );
982 if( h->sh.i_type != SLICE_TYPE_I )
983 x264_cabac_mb_skip( h, 0 );
984 x264_macroblock_write_cabac( h, &h->cabac );
989 if( IS_SKIP( h->mb.i_type ) )
993 if( h->sh.i_type != SLICE_TYPE_I )
995 bs_write_ue( &h->out.bs, i_skip ); /* skip run */
998 x264_macroblock_write_cavlc( h, &h->out.bs );
1001 TIMER_STOP( i_mtime_write );
1004 if( h->param.b_visualize )
1005 x264_visualize_mb( h );
1009 x264_macroblock_cache_save( h );
1011 /* accumulate mb stats */
1012 h->stat.frame.i_mb_count[h->mb.i_type]++;
1013 if( !IS_SKIP(h->mb.i_type) && !IS_INTRA(h->mb.i_type) && !IS_DIRECT(h->mb.i_type) )
1015 if( h->mb.i_partition != D_8x8 )
1016 h->stat.frame.i_mb_count_size[ x264_mb_partition_pixel_table[ h->mb.i_partition ] ] += 4;
1018 for( i = 0; i < 4; i++ )
1019 h->stat.frame.i_mb_count_size[ x264_mb_partition_pixel_table[ h->mb.i_sub_partition[i] ] ] ++;
1020 if( h->param.i_frame_reference > 1 )
1022 for( i = 0; i < 4; i++ )
1024 int i_ref = h->mb.cache.ref[0][ x264_scan8[4*i] ];
1026 h->stat.frame.i_mb_count_ref[i_ref] ++;
1030 if( h->mb.i_cbp_luma && !IS_INTRA(h->mb.i_type) )
1032 h->stat.frame.i_mb_count_8x8dct[0] ++;
1033 h->stat.frame.i_mb_count_8x8dct[1] += h->mb.b_transform_8x8;
1036 if( h->mb.b_variable_qp )
1037 x264_ratecontrol_mb(h, bs_pos(&h->out.bs) - mb_spos);
1040 if( h->param.b_cabac )
1043 x264_cabac_encode_terminal( &h->cabac, 1 );
1045 else if( i_skip > 0 )
1047 bs_write_ue( &h->out.bs, i_skip ); /* last skip run */
1050 if( h->param.b_cabac )
1053 x264_cabac_encode_flush( &h->cabac );
1054 /* TODO cabac stuffing things (p209) */
1055 i_cabac_word = (((3 * h->cabac.i_sym_cnt - 3 * 96 * h->sps->i_mb_width * h->sps->i_mb_height)/32) - bs_pos( &h->out.bs)/8)/3;
1057 while( i_cabac_word > 0 )
1059 bs_write( &h->out.bs, 16, 0x0000 );
1065 /* rbsp_slice_trailing_bits */
1066 bs_rbsp_trailing( &h->out.bs );
1071 /* Compute misc bits */
1072 h->stat.frame.i_misc_bits = bs_pos( &h->out.bs )
1074 - h->stat.frame.i_itex_bits
1075 - h->stat.frame.i_ptex_bits
1076 - h->stat.frame.i_hdr_bits;
1081 static inline int x264_slices_write( x264_t *h )
1086 if( h->param.b_visualize )
1087 x264_visualize_init( h );
1090 if( h->param.i_threads == 1 )
1092 x264_slice_write( h );
1093 i_frame_size = h->out.nal[h->out.i_nal-1].i_payload;
1097 int i_nal = h->out.i_nal;
1098 int i_bs_size = h->out.i_bitstream / h->param.i_threads;
1100 /* duplicate contexts */
1101 for( i = 0; i < h->param.i_threads; i++ )
1103 x264_t *t = h->thread[i];
1106 memcpy( t, h, sizeof(x264_t) );
1107 t->out.p_bitstream += i*i_bs_size;
1108 bs_init( &t->out.bs, t->out.p_bitstream, i_bs_size );
1110 t->sh.i_first_mb = (i * h->sps->i_mb_height / h->param.i_threads) * h->sps->i_mb_width;
1111 t->sh.i_last_mb = ((i+1) * h->sps->i_mb_height / h->param.i_threads) * h->sps->i_mb_width;
1112 t->out.i_nal = i_nal + i;
1118 pthread_t handles[X264_SLICE_MAX];
1120 for( i = 0; i < h->param.i_threads; i++ )
1121 pthread_create( &handles[i], NULL, (void*)x264_slice_write, (void*)h->thread[i] );
1122 for( i = 0; i < h->param.i_threads; i++ )
1123 pthread_join( handles[i], &status );
1126 for( i = 0; i < h->param.i_threads; i++ )
1127 x264_slice_write( h->thread[i] );
1130 /* merge contexts */
1131 i_frame_size = h->out.nal[i_nal].i_payload;
1132 for( i = 1; i < h->param.i_threads; i++ )
1135 x264_t *t = h->thread[i];
1136 h->out.nal[i_nal+i] = t->out.nal[i_nal+i];
1137 i_frame_size += t->out.nal[i_nal+i].i_payload;
1138 // all entries in stat.frame are ints
1139 for( j = 0; j < sizeof(h->stat.frame) / sizeof(int); j++ )
1140 ((int*)&h->stat.frame)[j] += ((int*)&t->stat.frame)[j];
1142 h->out.i_nal = i_nal + h->param.i_threads;
1146 if( h->param.b_visualize )
1148 x264_visualize_show( h );
1149 x264_visualize_close( h );
1153 return i_frame_size;
1156 /****************************************************************************
1157 * x264_encoder_encode:
1158 * XXX: i_poc : is the poc of the current given picture
1159 * i_frame : is the number of the frame being coded
1160 * ex: type frame poc
1168 ****************************************************************************/
1169 int x264_encoder_encode( x264_t *h,
1170 x264_nal_t **pp_nal, int *pi_nal,
1171 x264_picture_t *pic_in,
1172 x264_picture_t *pic_out )
1174 x264_frame_t *frame_psnr = h->fdec; /* just to keep the current decoded frame for psnr calculation */
1184 char psz_message[80];
1191 /* ------------------- Setup new frame from picture -------------------- */
1192 TIMER_START( i_mtime_encode_frame );
1193 if( pic_in != NULL )
1195 /* 1: Copy the picture to a frame and move it to a buffer */
1196 x264_frame_t *fenc = x264_frame_get( h->frames.unused );
1198 x264_frame_copy_picture( h, fenc, pic_in );
1200 fenc->i_frame = h->frames.i_input++;
1202 x264_frame_put( h->frames.next, fenc );
1204 x264_frame_init_lowres( h->param.cpu, fenc );
1206 if( h->frames.i_input <= h->frames.i_delay )
1208 /* Nothing yet to encode */
1209 /* waiting for filling bframe buffer */
1210 pic_out->i_type = X264_TYPE_AUTO;
1215 if( h->frames.current[0] == NULL )
1218 /* 2: Select frame types */
1219 if( h->frames.next[0] == NULL )
1222 x264_slicetype_decide( h );
1224 /* 3: move some B-frames and 1 non-B to encode queue */
1225 while( IS_X264_TYPE_B( h->frames.next[bframes]->i_type ) )
1227 x264_frame_put( h->frames.current, x264_frame_get( &h->frames.next[bframes] ) );
1228 /* FIXME: when max B-frames > 3, BREF may no longer be centered after GOP closing */
1229 if( h->param.b_bframe_pyramid && bframes > 1 )
1231 x264_frame_t *mid = x264_frame_get( &h->frames.next[bframes/2] );
1232 mid->i_type = X264_TYPE_BREF;
1233 x264_frame_put( h->frames.current, mid );
1237 x264_frame_put( h->frames.current, x264_frame_get( h->frames.next ) );
1239 TIMER_STOP( i_mtime_encode_frame );
1241 /* ------------------- Get frame to be encoded ------------------------- */
1242 /* 4: get picture to encode */
1243 h->fenc = x264_frame_get( h->frames.current );
1244 if( h->fenc == NULL )
1246 /* Nothing yet to encode (ex: waiting for I/P with B frames) */
1247 /* waiting for filling bframe buffer */
1248 pic_out->i_type = X264_TYPE_AUTO;
1254 if( h->fenc->i_type == X264_TYPE_IDR )
1256 h->frames.i_last_idr = h->fenc->i_frame;
1259 /* ------------------- Setup frame context ----------------------------- */
1260 /* 5: Init data dependant of frame type */
1261 TIMER_START( i_mtime_encode_frame );
1262 if( h->fenc->i_type == X264_TYPE_IDR )
1264 /* reset ref pictures */
1265 x264_reference_reset( h );
1267 i_nal_type = NAL_SLICE_IDR;
1268 i_nal_ref_idc = NAL_PRIORITY_HIGHEST;
1269 i_slice_type = SLICE_TYPE_I;
1271 else if( h->fenc->i_type == X264_TYPE_I )
1273 i_nal_type = NAL_SLICE;
1274 i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
1275 i_slice_type = SLICE_TYPE_I;
1277 else if( h->fenc->i_type == X264_TYPE_P )
1279 i_nal_type = NAL_SLICE;
1280 i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
1281 i_slice_type = SLICE_TYPE_P;
1283 else if( h->fenc->i_type == X264_TYPE_BREF )
1285 i_nal_type = NAL_SLICE;
1286 i_nal_ref_idc = NAL_PRIORITY_HIGH; /* maybe add MMCO to forget it? -> low */
1287 i_slice_type = SLICE_TYPE_B;
1291 i_nal_type = NAL_SLICE;
1292 i_nal_ref_idc = NAL_PRIORITY_DISPOSABLE;
1293 i_slice_type = SLICE_TYPE_B;
1297 h->fenc->i_poc = 2 * (h->fenc->i_frame - h->frames.i_last_idr);
1298 h->fdec->i_type = h->fenc->i_type;
1299 h->fdec->i_frame = h->fenc->i_frame;
1300 h->fenc->b_kept_as_ref =
1301 h->fdec->b_kept_as_ref = i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE;
1305 /* ------------------- Init ----------------------------- */
1306 /* build ref list 0/1 */
1307 x264_reference_build_list( h, h->fdec->i_poc, i_slice_type );
1309 /* Init the rate control */
1310 x264_ratecontrol_start( h, i_slice_type, h->fenc->i_qpplus1 );
1311 i_global_qp = x264_ratecontrol_qp( h );
1313 pic_out->i_qpplus1 =
1314 h->fdec->i_qpplus1 = i_global_qp + 1;
1316 if( i_slice_type == SLICE_TYPE_B )
1317 x264_macroblock_bipred_init( h );
1319 if( h->fenc->b_kept_as_ref )
1322 /* ------------------------ Create slice header ----------------------- */
1323 x264_slice_init( h, i_nal_type, i_slice_type, i_global_qp );
1325 /* ---------------------- Write the bitstream -------------------------- */
1326 /* Init bitstream context */
1328 bs_init( &h->out.bs, h->out.p_bitstream, h->out.i_bitstream );
1333 if(i_slice_type == SLICE_TYPE_I)
1335 else if(i_slice_type == SLICE_TYPE_P)
1337 else if(i_slice_type == SLICE_TYPE_B)
1342 x264_nal_start(h, NAL_AUD, NAL_PRIORITY_DISPOSABLE);
1343 bs_write(&h->out.bs, 3, pic_type);
1344 bs_rbsp_trailing(&h->out.bs);
1348 h->i_nal_type = i_nal_type;
1349 h->i_nal_ref_idc = i_nal_ref_idc;
1351 /* Write SPS and PPS */
1352 if( i_nal_type == NAL_SLICE_IDR )
1354 if( h->fenc->i_frame == 0 )
1356 /* identify ourself */
1357 x264_nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
1358 x264_sei_version_write( &h->out.bs );
1362 /* generate sequence parameters */
1363 x264_nal_start( h, NAL_SPS, NAL_PRIORITY_HIGHEST );
1364 x264_sps_write( &h->out.bs, h->sps );
1367 /* generate picture parameters */
1368 x264_nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
1369 x264_pps_write( &h->out.bs, h->pps );
1374 i_frame_size = x264_slices_write( h );
1376 /* restore CPU state (before using float again) */
1377 x264_cpu_restore( h->param.cpu );
1379 if( i_slice_type == SLICE_TYPE_P && !h->param.rc.b_stat_read
1380 && h->param.i_scenecut_threshold >= 0 )
1382 const int *mbs = h->stat.frame.i_mb_count;
1383 int i_mb_i = mbs[I_16x16] + mbs[I_8x8] + mbs[I_4x4];
1384 int i_mb_p = mbs[P_L0] + mbs[P_8x8];
1385 int i_mb_s = mbs[P_SKIP];
1386 int i_mb = h->sps->i_mb_width * h->sps->i_mb_height;
1387 int64_t i_inter_cost = h->stat.frame.i_inter_cost;
1388 int64_t i_intra_cost = h->stat.frame.i_intra_cost;
1391 int i_gop_size = h->fenc->i_frame - h->frames.i_last_idr;
1392 float f_thresh_max = h->param.i_scenecut_threshold / 100.0;
1393 /* magic numbers pulled out of thin air */
1394 float f_thresh_min = f_thresh_max * h->param.i_keyint_min
1395 / ( h->param.i_keyint_max * 4 );
1396 if( h->param.i_keyint_min == h->param.i_keyint_max )
1397 f_thresh_min= f_thresh_max;
1399 /* macroblock_analyse() doesn't further analyse skipped mbs,
1400 * so we have to guess their cost */
1402 i_intra_cost = i_intra_cost * i_mb / (i_mb - i_mb_s);
1404 if( i_gop_size < h->param.i_keyint_min / 4 )
1405 f_bias = f_thresh_min / 4;
1406 else if( i_gop_size <= h->param.i_keyint_min )
1407 f_bias = f_thresh_min * i_gop_size / h->param.i_keyint_min;
1410 f_bias = f_thresh_min
1411 + ( f_thresh_max - f_thresh_min )
1412 * ( i_gop_size - h->param.i_keyint_min )
1413 / ( h->param.i_keyint_max - h->param.i_keyint_min );
1415 f_bias = X264_MIN( f_bias, 1.0 );
1417 /* Bad P will be reencoded as I */
1418 if( i_mb_s < i_mb &&
1419 i_inter_cost >= (1.0 - f_bias) * i_intra_cost )
1423 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",
1425 (double)i_intra_cost, (double)i_inter_cost,
1426 (double)i_inter_cost / i_intra_cost,
1428 i_mb_i, i_mb_p, i_mb_s );
1430 /* Restore frame num */
1433 for( b = 0; h->frames.current[b] && IS_X264_TYPE_B( h->frames.current[b]->i_type ); b++ );
1436 /* If using B-frames, force GOP to be closed.
1437 * Even if this frame is going to be I and not IDR, forcing a
1438 * P-frame before the scenecut will probably help compression.
1440 * We don't yet know exactly which frame is the scene cut, so
1441 * we can't assign an I-frame. Instead, change the previous
1442 * B-frame to P, and rearrange coding order. */
1444 if( h->param.b_bframe_adaptive || b > 1 )
1445 h->fenc->i_type = X264_TYPE_AUTO;
1446 x264_frame_sort_pts( h->frames.current );
1447 x264_frame_push( h->frames.next, h->fenc );
1448 h->fenc = h->frames.current[b-1];
1449 h->frames.current[b-1] = NULL;
1450 h->fenc->i_type = X264_TYPE_P;
1451 x264_frame_sort_dts( h->frames.current );
1453 /* Do IDR if needed */
1454 else if( i_gop_size >= h->param.i_keyint_min )
1461 /* Reinit field of fenc */
1462 h->fenc->i_type = X264_TYPE_IDR;
1465 /* Put enqueued frames back in the pool */
1466 while( (tmp = x264_frame_get( h->frames.current ) ) != NULL )
1467 x264_frame_put( h->frames.next, tmp );
1468 x264_frame_sort_pts( h->frames.next );
1472 h->fenc->i_type = X264_TYPE_I;
1478 /* End bitstream, set output */
1479 *pi_nal = h->out.i_nal;
1480 *pp_nal = h->out.nal;
1482 /* Set output picture properties */
1483 if( i_slice_type == SLICE_TYPE_I )
1484 pic_out->i_type = i_nal_type == NAL_SLICE_IDR ? X264_TYPE_IDR : X264_TYPE_I;
1485 else if( i_slice_type == SLICE_TYPE_P )
1486 pic_out->i_type = X264_TYPE_P;
1488 pic_out->i_type = X264_TYPE_B;
1489 pic_out->i_pts = h->fenc->i_pts;
1491 pic_out->img.i_plane = h->fdec->i_plane;
1492 for(i = 0; i < 4; i++){
1493 pic_out->img.i_stride[i] = h->fdec->i_stride[i];
1494 pic_out->img.plane[i] = h->fdec->plane[i];
1497 /* ---------------------- Update encoder state ------------------------- */
1499 if( h->param.b_cabac && h->param.i_cabac_init_idc == -1 )
1501 x264_cabac_model_update( &h->cabac, i_slice_type, h->sh.i_qp );
1504 /* handle references */
1505 if( i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE )
1507 x264_reference_update( h );
1510 /* increase frame count */
1513 /* restore CPU state (before using float again) */
1514 /* XXX: not needed? (done above) */
1515 x264_cpu_restore( h->param.cpu );
1518 x264_ratecontrol_end( h, i_frame_size * 8 );
1520 x264_frame_put( h->frames.unused, h->fenc );
1522 TIMER_STOP( i_mtime_encode_frame );
1524 /* ---------------------- Compute/Print statistics --------------------- */
1526 h->stat.i_slice_count[i_slice_type]++;
1527 h->stat.i_slice_size[i_slice_type] += i_frame_size + NALU_OVERHEAD;
1528 h->stat.i_slice_qp[i_slice_type] += i_global_qp;
1530 for( i = 0; i < 19; i++ )
1531 h->stat.i_mb_count[h->sh.i_type][i] += h->stat.frame.i_mb_count[i];
1532 for( i = 0; i < 2; i++ )
1533 h->stat.i_mb_count_8x8dct[i] += h->stat.frame.i_mb_count_8x8dct[i];
1534 if( h->sh.i_type != SLICE_TYPE_I )
1536 for( i = 0; i < 7; i++ )
1537 h->stat.i_mb_count_size[h->sh.i_type][i] += h->stat.frame.i_mb_count_size[i];
1538 for( i = 0; i < 16; i++ )
1539 h->stat.i_mb_count_ref[h->sh.i_type][i] += h->stat.frame.i_mb_count_ref[i];
1542 if( h->param.analyse.b_psnr )
1544 int64_t i_sqe_y, i_sqe_u, i_sqe_v;
1547 i_sqe_y = x264_sqe( h, 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 );
1548 i_sqe_u = x264_sqe( h, 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);
1549 i_sqe_v = x264_sqe( h, 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);
1551 h->stat.i_sqe_global[i_slice_type] += i_sqe_y + i_sqe_u + i_sqe_v;
1552 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 );
1553 h->stat.f_psnr_mean_y[i_slice_type] += x264_psnr( i_sqe_y, h->param.i_width * h->param.i_height );
1554 h->stat.f_psnr_mean_u[i_slice_type] += x264_psnr( i_sqe_u, h->param.i_width * h->param.i_height / 4 );
1555 h->stat.f_psnr_mean_v[i_slice_type] += x264_psnr( i_sqe_v, h->param.i_width * h->param.i_height / 4 );
1557 snprintf( psz_message, 80, " PSNR Y:%2.2f U:%2.2f V:%2.2f",
1558 x264_psnr( i_sqe_y, h->param.i_width * h->param.i_height ),
1559 x264_psnr( i_sqe_u, h->param.i_width * h->param.i_height / 4),
1560 x264_psnr( i_sqe_v, h->param.i_width * h->param.i_height / 4) );
1561 psz_message[79] = '\0';
1565 psz_message[0] = '\0';
1568 x264_log( h, X264_LOG_DEBUG,
1569 "frame=%4d QP=%i NAL=%d Slice:%c Poc:%-3d I:%-4d P:%-4d SKIP:%-4d size=%d bytes%s\n",
1573 i_slice_type == SLICE_TYPE_I ? 'I' : (i_slice_type == SLICE_TYPE_P ? 'P' : 'B' ),
1575 h->stat.frame.i_mb_count_i,
1576 h->stat.frame.i_mb_count_p,
1577 h->stat.frame.i_mb_count_skip,
1582 #ifdef DEBUG_MB_TYPE
1584 static const char mb_chars[] = { 'i', 'i', 'I', 'C', 'P', '8', 'S',
1585 'D', '<', 'X', 'B', 'X', '>', 'B', 'B', 'B', 'B', '8', 'S' };
1587 for( mb_xy = 0; mb_xy < h->sps->i_mb_width * h->sps->i_mb_height; mb_xy++ )
1589 if( h->mb.type[mb_xy] < 19 && h->mb.type[mb_xy] >= 0 )
1590 fprintf( stderr, "%c ", mb_chars[ h->mb.type[mb_xy] ] );
1592 fprintf( stderr, "? " );
1594 if( (mb_xy+1) % h->sps->i_mb_width == 0 )
1595 fprintf( stderr, "\n" );
1600 #ifdef DEBUG_DUMP_FRAME
1601 /* Dump reconstructed frame */
1602 x264_frame_dump( h, frame_psnr, "fdec.yuv" );
1607 x264_frame_dump( h, h->fref0[0], "ref0.yuv" );
1611 x264_frame_dump( h, h->fref1[0], "ref1.yuv" );
1617 /****************************************************************************
1618 * x264_encoder_close:
1619 ****************************************************************************/
1620 void x264_encoder_close ( x264_t *h )
1622 #ifdef DEBUG_BENCHMARK
1623 int64_t i_mtime_total = i_mtime_analyse + i_mtime_encode + i_mtime_write + i_mtime_filter + 1;
1625 int64_t i_yuv_size = 3 * h->param.i_width * h->param.i_height / 2;
1628 #ifdef DEBUG_BENCHMARK
1629 x264_log( h, X264_LOG_INFO,
1630 "analyse=%d(%lldms) encode=%d(%lldms) write=%d(%lldms) filter=%d(%lldms)\n",
1631 (int)(100*i_mtime_analyse/i_mtime_total), i_mtime_analyse/1000,
1632 (int)(100*i_mtime_encode/i_mtime_total), i_mtime_encode/1000,
1633 (int)(100*i_mtime_write/i_mtime_total), i_mtime_write/1000,
1634 (int)(100*i_mtime_filter/i_mtime_total), i_mtime_filter/1000 );
1637 /* Slices used and PSNR */
1638 for( i=0; i<5; i++ )
1640 static const int slice_order[] = { SLICE_TYPE_I, SLICE_TYPE_SI, SLICE_TYPE_P, SLICE_TYPE_SP, SLICE_TYPE_B };
1641 static const char *slice_name[] = { "P", "B", "I", "SP", "SI" };
1642 int i_slice = slice_order[i];
1644 if( h->stat.i_slice_count[i_slice] > 0 )
1646 const int i_count = h->stat.i_slice_count[i_slice];
1647 if( h->param.analyse.b_psnr )
1649 x264_log( h, X264_LOG_INFO,
1650 "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",
1651 slice_name[i_slice],
1653 (double)h->stat.i_slice_qp[i_slice] / i_count,
1654 (double)h->stat.i_slice_size[i_slice] / i_count,
1655 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,
1656 h->stat.f_psnr_average[i_slice] / i_count,
1657 x264_psnr( h->stat.i_sqe_global[i_slice], i_count * i_yuv_size ) );
1661 x264_log( h, X264_LOG_INFO,
1662 "slice %s:%-5d Avg QP:%5.2f size:%6.0f\n",
1663 slice_name[i_slice],
1665 (double)h->stat.i_slice_qp[i_slice] / i_count,
1666 (double)h->stat.i_slice_size[i_slice] / i_count );
1672 if( h->stat.i_slice_count[SLICE_TYPE_I] > 0 )
1674 const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_I];
1675 const double i_count = h->stat.i_slice_count[SLICE_TYPE_I] * h->mb.i_mb_count / 100.0;
1676 x264_log( h, X264_LOG_INFO,
1677 "mb I I16..4: %4.1f%% %4.1f%% %4.1f%%\n",
1678 i_mb_count[I_16x16]/ i_count,
1679 i_mb_count[I_8x8] / i_count,
1680 i_mb_count[I_4x4] / i_count );
1682 if( h->stat.i_slice_count[SLICE_TYPE_P] > 0 )
1684 const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_P];
1685 const int64_t *i_mb_size = h->stat.i_mb_count_size[SLICE_TYPE_P];
1686 const double i_count = h->stat.i_slice_count[SLICE_TYPE_P] * h->mb.i_mb_count / 100.0;
1687 x264_log( h, X264_LOG_INFO,
1688 "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",
1689 i_mb_count[I_16x16]/ i_count,
1690 i_mb_count[I_8x8] / i_count,
1691 i_mb_count[I_4x4] / i_count,
1692 i_mb_size[PIXEL_16x16] / (i_count*4),
1693 (i_mb_size[PIXEL_16x8] + i_mb_size[PIXEL_8x16]) / (i_count*4),
1694 i_mb_size[PIXEL_8x8] / (i_count*4),
1695 (i_mb_size[PIXEL_8x4] + i_mb_size[PIXEL_4x8]) / (i_count*4),
1696 i_mb_size[PIXEL_4x4] / (i_count*4),
1697 i_mb_count[P_SKIP] / i_count );
1699 if( h->stat.i_slice_count[SLICE_TYPE_B] > 0 )
1701 const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_B];
1702 const int64_t *i_mb_size = h->stat.i_mb_count_size[SLICE_TYPE_B];
1703 const double i_count = h->stat.i_slice_count[SLICE_TYPE_B] * h->mb.i_mb_count / 100.0;
1704 x264_log( h, X264_LOG_INFO,
1705 "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",
1706 i_mb_count[I_16x16] / i_count,
1707 i_mb_count[I_8x8] / i_count,
1708 i_mb_count[I_4x4] / i_count,
1709 i_mb_size[PIXEL_16x16] / (i_count*4),
1710 (i_mb_size[PIXEL_16x8] + i_mb_size[PIXEL_8x16]) / (i_count*4),
1711 i_mb_size[PIXEL_8x8] / (i_count*4),
1712 i_mb_count[B_DIRECT] / i_count,
1713 i_mb_count[B_SKIP] / i_count );
1716 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 )
1718 const int i_count = h->stat.i_slice_count[SLICE_TYPE_I] +
1719 h->stat.i_slice_count[SLICE_TYPE_P] +
1720 h->stat.i_slice_count[SLICE_TYPE_B];
1721 float fps = (float) h->param.i_fps_num / h->param.i_fps_den;
1722 #define SUM3(p) (p[SLICE_TYPE_I] + p[SLICE_TYPE_P] + p[SLICE_TYPE_B])
1723 #define SUM3b(p,o) (p[SLICE_TYPE_I][o] + p[SLICE_TYPE_P][o] + p[SLICE_TYPE_B][o])
1724 float f_bitrate = fps * SUM3(h->stat.i_slice_size) / i_count / 125;
1726 if( h->param.analyse.b_transform_8x8 )
1728 int64_t i_i8x8 = SUM3b( h->stat.i_mb_count, I_8x8 );
1729 int64_t i_intra = i_i8x8 + SUM3b( h->stat.i_mb_count, I_4x4 )
1730 + SUM3b( h->stat.i_mb_count, I_16x16 );
1731 x264_log( h, X264_LOG_INFO, "8x8 transform intra:%.1f%% inter:%.1f%%\n",
1732 100. * i_i8x8 / i_intra,
1733 100. * h->stat.i_mb_count_8x8dct[1] / h->stat.i_mb_count_8x8dct[0] );
1736 if( h->param.i_frame_reference > 1 )
1739 for( i_slice = 0; i_slice < 2; i_slice++ )
1745 for( i = 0; i < h->param.i_frame_reference; i++ )
1746 if( h->stat.i_mb_count_ref[i_slice][i] )
1748 i_den += h->stat.i_mb_count_ref[i_slice][i];
1753 for( i = 0; i <= i_max; i++ )
1754 p += sprintf( p, " %4.1f%%", 100. * h->stat.i_mb_count_ref[i_slice][i] / i_den );
1755 x264_log( h, X264_LOG_INFO, "ref %c %s\n", i_slice==SLICE_TYPE_P ? 'P' : 'B', buf );
1759 if( h->param.analyse.b_psnr )
1760 x264_log( h, X264_LOG_INFO,
1761 "PSNR Mean Y:%6.3f U:%6.3f V:%6.3f Avg:%6.3f Global:%6.3f kb/s:%.2f\n",
1762 SUM3( h->stat.f_psnr_mean_y ) / i_count,
1763 SUM3( h->stat.f_psnr_mean_u ) / i_count,
1764 SUM3( h->stat.f_psnr_mean_v ) / i_count,
1765 SUM3( h->stat.f_psnr_average ) / i_count,
1766 x264_psnr( SUM3( h->stat.i_sqe_global ), i_count * i_yuv_size ),
1769 x264_log( h, X264_LOG_INFO, "kb/s:%.1f\n", f_bitrate );
1773 for( i = 0; i < X264_BFRAME_MAX + 3; i++ )
1775 if( h->frames.current[i] ) x264_frame_delete( h->frames.current[i] );
1776 if( h->frames.next[i] ) x264_frame_delete( h->frames.next[i] );
1777 if( h->frames.unused[i] ) x264_frame_delete( h->frames.unused[i] );
1780 for( i = 0; i < h->frames.i_max_dpb; i++ )
1782 x264_frame_delete( h->frames.reference[i] );
1786 x264_ratecontrol_delete( h );
1789 if( h->param.rc.psz_stat_out )
1790 free( h->param.rc.psz_stat_out );
1791 if( h->param.rc.psz_stat_in )
1792 free( h->param.rc.psz_stat_in );
1793 if( h->param.rc.psz_rc_eq )
1794 free( h->param.rc.psz_rc_eq );
1796 x264_macroblock_cache_end( h );
1797 x264_free( h->out.p_bitstream );
1798 for( i = 1; i < h->param.i_threads; i++ )
1799 x264_free( h->thread[i] );