]> git.sesse.net Git - x264/blob - encoder/encoder.c
don't treat vbv_maxrate as a minrate too if it's higher than target average bitrate.
[x264] / encoder / encoder.c
1 /*****************************************************************************
2  * x264: h264 encoder
3  *****************************************************************************
4  * Copyright (C) 2003 Laurent Aimar
5  * $Id: encoder.c,v 1.1 2004/06/03 19:27:08 fenrir Exp $
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *
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.
13  *
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.
18  *
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  *****************************************************************************/
23
24 #include <stdio.h>
25 #include <string.h>
26 #include <math.h>
27
28 #include "common/common.h"
29 #include "common/cpu.h"
30
31 #include "set.h"
32 #include "analyse.h"
33 #include "ratecontrol.h"
34 #include "macroblock.h"
35
36 #if VISUALIZE
37 #include "common/visualize.h"
38 #endif
39
40 //#define DEBUG_MB_TYPE
41 //#define DEBUG_DUMP_FRAME
42 //#define DEBUG_BENCHMARK
43
44 #ifdef DEBUG_BENCHMARK
45 static int64_t i_mtime_encode_frame = 0;
46 static int64_t i_mtime_analyse = 0;
47 static int64_t i_mtime_encode = 0;
48 static int64_t i_mtime_write = 0;
49 static int64_t i_mtime_filter = 0;
50 #define TIMER_START( d ) \
51     { \
52         int64_t d##start = x264_mdate();
53
54 #define TIMER_STOP( d ) \
55         d += x264_mdate() - d##start;\
56     }
57 #else
58 #define TIMER_START( d )
59 #define TIMER_STOP( d )
60 #endif
61
62 #define NALU_OVERHEAD 5 // startcode + NAL type costs 5 bytes per frame
63
64 /****************************************************************************
65  *
66  ******************************* x264 libs **********************************
67  *
68  ****************************************************************************/
69 static float x264_psnr( int64_t i_sqe, int64_t i_size )
70 {
71     double f_mse = (double)i_sqe / ((double)65025.0 * (double)i_size);
72     if( f_mse <= 0.0000000001 ) /* Max 100dB */
73         return 100;
74
75     return (float)(-10.0 * log( f_mse ) / log( 10.0 ));
76 }
77
78 #ifdef DEBUG_DUMP_FRAME
79 static void x264_frame_dump( x264_t *h, x264_frame_t *fr, char *name )
80 {
81     FILE *f = fopen( name, "r+b" );
82     int i, y;
83     if( !f )
84         return;
85
86     /* Write the frame in display order */
87     fseek( f, fr->i_frame * h->param.i_height * h->param.i_width * 3 / 2, SEEK_SET );
88
89     for( i = 0; i < fr->i_plane; i++ )
90     {
91         for( y = 0; y < h->param.i_height / ( i == 0 ? 1 : 2 ); y++ )
92         {
93             fwrite( &fr->plane[i][y*fr->i_stride[i]], 1, h->param.i_width / ( i == 0 ? 1 : 2 ), f );
94         }
95     }
96     fclose( f );
97 }
98 #endif
99
100
101 /* Fill "default" values */
102 static void x264_slice_header_init( x264_t *h, x264_slice_header_t *sh,
103                                     x264_sps_t *sps, x264_pps_t *pps,
104                                     int i_type, int i_idr_pic_id, int i_frame, int i_qp )
105 {
106     x264_param_t *param = &h->param;
107     int i;
108
109     /* First we fill all field */
110     sh->sps = sps;
111     sh->pps = pps;
112
113     sh->i_type      = i_type;
114     sh->i_first_mb  = 0;
115     sh->i_last_mb   = h->sps->i_mb_width * h->sps->i_mb_height;
116     sh->i_pps_id    = pps->i_id;
117
118     sh->i_frame_num = i_frame;
119
120     sh->b_mbaff = h->param.b_interlaced;
121     sh->b_field_pic = 0;    /* no field support for now */
122     sh->b_bottom_field = 0; /* not yet used */
123
124     sh->i_idr_pic_id = i_idr_pic_id;
125
126     /* poc stuff, fixed later */
127     sh->i_poc_lsb = 0;
128     sh->i_delta_poc_bottom = 0;
129     sh->i_delta_poc[0] = 0;
130     sh->i_delta_poc[1] = 0;
131
132     sh->i_redundant_pic_cnt = 0;
133
134     if( !h->mb.b_direct_auto_read )
135     {
136         if( h->mb.b_direct_auto_write )
137             sh->b_direct_spatial_mv_pred = ( h->stat.i_direct_score[1] > h->stat.i_direct_score[0] );
138         else
139             sh->b_direct_spatial_mv_pred = ( param->analyse.i_direct_mv_pred == X264_DIRECT_PRED_SPATIAL );
140     }
141     /* else b_direct_spatial_mv_pred was read from the 2pass statsfile */
142
143     sh->b_num_ref_idx_override = 0;
144     sh->i_num_ref_idx_l0_active = 1;
145     sh->i_num_ref_idx_l1_active = 1;
146
147     sh->b_ref_pic_list_reordering_l0 = h->b_ref_reorder[0];
148     sh->b_ref_pic_list_reordering_l1 = h->b_ref_reorder[1];
149
150     /* If the ref list isn't in the default order, construct reordering header */
151     /* List1 reordering isn't needed yet */
152     if( sh->b_ref_pic_list_reordering_l0 )
153     {
154         int pred_frame_num = i_frame;
155         for( i = 0; i < h->i_ref0; i++ )
156         {
157             int diff = h->fref0[i]->i_frame_num - pred_frame_num;
158             if( diff == 0 )
159                 x264_log( h, X264_LOG_ERROR, "diff frame num == 0\n" );
160             sh->ref_pic_list_order[0][i].idc = ( diff > 0 );
161             sh->ref_pic_list_order[0][i].arg = abs( diff ) - 1;
162             pred_frame_num = h->fref0[i]->i_frame_num;
163         }
164     }
165
166     sh->i_cabac_init_idc = param->i_cabac_init_idc;
167
168     sh->i_qp = i_qp;
169     sh->i_qp_delta = i_qp - pps->i_pic_init_qp;
170     sh->b_sp_for_swidth = 0;
171     sh->i_qs_delta = 0;
172
173     /* If effective qp <= 15, deblocking would have no effect anyway */
174     if( param->b_deblocking_filter
175         && ( h->mb.b_variable_qp
176         || 15 < i_qp + 2 * X264_MAX(param->i_deblocking_filter_alphac0, param->i_deblocking_filter_beta) ) )
177     {
178         sh->i_disable_deblocking_filter_idc = 0;
179     }
180     else
181     {
182         sh->i_disable_deblocking_filter_idc = 1;
183     }
184     sh->i_alpha_c0_offset = param->i_deblocking_filter_alphac0 << 1;
185     sh->i_beta_offset = param->i_deblocking_filter_beta << 1;
186 }
187
188 static void x264_slice_header_write( bs_t *s, x264_slice_header_t *sh, int i_nal_ref_idc )
189 {
190     int i;
191
192     if( sh->b_mbaff )
193     {
194         assert( sh->i_first_mb % (2*sh->sps->i_mb_width) == 0 );
195         bs_write_ue( s, sh->i_first_mb >> 1 );
196     }
197     else
198         bs_write_ue( s, sh->i_first_mb );
199
200     bs_write_ue( s, sh->i_type + 5 );   /* same type things */
201     bs_write_ue( s, sh->i_pps_id );
202     bs_write( s, sh->sps->i_log2_max_frame_num, sh->i_frame_num );
203
204     if( !sh->sps->b_frame_mbs_only )
205     {
206         bs_write1( s, sh->b_field_pic );
207         if ( sh->b_field_pic )
208             bs_write1( s, sh->b_bottom_field );
209     }
210
211     if( sh->i_idr_pic_id >= 0 ) /* NAL IDR */
212     {
213         bs_write_ue( s, sh->i_idr_pic_id );
214     }
215
216     if( sh->sps->i_poc_type == 0 )
217     {
218         bs_write( s, sh->sps->i_log2_max_poc_lsb, sh->i_poc_lsb );
219         if( sh->pps->b_pic_order && !sh->b_field_pic )
220         {
221             bs_write_se( s, sh->i_delta_poc_bottom );
222         }
223     }
224     else if( sh->sps->i_poc_type == 1 && !sh->sps->b_delta_pic_order_always_zero )
225     {
226         bs_write_se( s, sh->i_delta_poc[0] );
227         if( sh->pps->b_pic_order && !sh->b_field_pic )
228         {
229             bs_write_se( s, sh->i_delta_poc[1] );
230         }
231     }
232
233     if( sh->pps->b_redundant_pic_cnt )
234     {
235         bs_write_ue( s, sh->i_redundant_pic_cnt );
236     }
237
238     if( sh->i_type == SLICE_TYPE_B )
239     {
240         bs_write1( s, sh->b_direct_spatial_mv_pred );
241     }
242     if( sh->i_type == SLICE_TYPE_P || sh->i_type == SLICE_TYPE_SP || sh->i_type == SLICE_TYPE_B )
243     {
244         bs_write1( s, sh->b_num_ref_idx_override );
245         if( sh->b_num_ref_idx_override )
246         {
247             bs_write_ue( s, sh->i_num_ref_idx_l0_active - 1 );
248             if( sh->i_type == SLICE_TYPE_B )
249             {
250                 bs_write_ue( s, sh->i_num_ref_idx_l1_active - 1 );
251             }
252         }
253     }
254
255     /* ref pic list reordering */
256     if( sh->i_type != SLICE_TYPE_I )
257     {
258         bs_write1( s, sh->b_ref_pic_list_reordering_l0 );
259         if( sh->b_ref_pic_list_reordering_l0 )
260         {
261             for( i = 0; i < sh->i_num_ref_idx_l0_active; i++ )
262             {
263                 bs_write_ue( s, sh->ref_pic_list_order[0][i].idc );
264                 bs_write_ue( s, sh->ref_pic_list_order[0][i].arg );
265                         
266             }
267             bs_write_ue( s, 3 );
268         }
269     }
270     if( sh->i_type == SLICE_TYPE_B )
271     {
272         bs_write1( s, sh->b_ref_pic_list_reordering_l1 );
273         if( sh->b_ref_pic_list_reordering_l1 )
274         {
275             for( i = 0; i < sh->i_num_ref_idx_l1_active; i++ )
276             {
277                 bs_write_ue( s, sh->ref_pic_list_order[1][i].idc );
278                 bs_write_ue( s, sh->ref_pic_list_order[1][i].arg );
279             }
280             bs_write_ue( s, 3 );
281         }
282     }
283
284     if( ( sh->pps->b_weighted_pred && ( sh->i_type == SLICE_TYPE_P || sh->i_type == SLICE_TYPE_SP ) ) ||
285         ( sh->pps->b_weighted_bipred == 1 && sh->i_type == SLICE_TYPE_B ) )
286     {
287         /* FIXME */
288     }
289
290     if( i_nal_ref_idc != 0 )
291     {
292         if( sh->i_idr_pic_id >= 0 )
293         {
294             bs_write1( s, 0 );  /* no output of prior pics flag */
295             bs_write1( s, 0 );  /* long term reference flag */
296         }
297         else
298         {
299             bs_write1( s, 0 );  /* adaptive_ref_pic_marking_mode_flag */
300         }
301     }
302
303     if( sh->pps->b_cabac && sh->i_type != SLICE_TYPE_I )
304     {
305         bs_write_ue( s, sh->i_cabac_init_idc );
306     }
307     bs_write_se( s, sh->i_qp_delta );      /* slice qp delta */
308
309     if( sh->pps->b_deblocking_filter_control )
310     {
311         bs_write_ue( s, sh->i_disable_deblocking_filter_idc );
312         if( sh->i_disable_deblocking_filter_idc != 1 )
313         {
314             bs_write_se( s, sh->i_alpha_c0_offset >> 1 );
315             bs_write_se( s, sh->i_beta_offset >> 1 );
316         }
317     }
318 }
319
320 /****************************************************************************
321  *
322  ****************************************************************************
323  ****************************** External API*********************************
324  ****************************************************************************
325  *
326  ****************************************************************************/
327
328 static int x264_validate_parameters( x264_t *h )
329 {
330     if( h->param.i_width <= 0 || h->param.i_height <= 0 )
331     {
332         x264_log( h, X264_LOG_ERROR, "invalid width x height (%dx%d)\n",
333                   h->param.i_width, h->param.i_height );
334         return -1;
335     }
336
337     if( h->param.i_width % 2 || h->param.i_height % 2 )
338     {
339         x264_log( h, X264_LOG_ERROR, "width or height not divisible by 2 (%dx%d)\n",
340                   h->param.i_width, h->param.i_height );
341         return -1;
342     }
343     if( h->param.i_csp != X264_CSP_I420 )
344     {
345         x264_log( h, X264_LOG_ERROR, "invalid CSP (only I420 supported)\n" );
346         return -1;
347     }
348
349     if( h->param.i_threads == 0 )
350         h->param.i_threads = x264_cpu_num_processors();
351     h->param.i_threads = x264_clip3( h->param.i_threads, 1, X264_SLICE_MAX );
352     h->param.i_threads = X264_MIN( h->param.i_threads, (h->param.i_height + 15) >> (4 + h->param.b_interlaced) );
353 #ifndef HAVE_PTHREAD
354     if( h->param.i_threads > 1 )
355     {
356         x264_log( h, X264_LOG_WARNING, "not compiled with pthread support!\n");
357         x264_log( h, X264_LOG_WARNING, "multislicing anyway, but you won't see any speed gain.\n" );
358     }
359 #endif
360
361     if( h->param.b_interlaced )
362     {
363         if( h->param.analyse.i_me_method == X264_ME_ESA )
364         {
365             x264_log( h, X264_LOG_WARNING, "interlace + me=esa is not implemented\n" );
366             h->param.analyse.i_me_method = X264_ME_UMH;
367         }
368         if( h->param.analyse.i_direct_mv_pred > X264_DIRECT_PRED_SPATIAL )
369         {
370             x264_log( h, X264_LOG_WARNING, "interlace + direct=temporal is not implemented\n" );
371             h->param.analyse.i_direct_mv_pred = X264_DIRECT_PRED_SPATIAL;
372         }
373     }
374
375     if( h->param.rc.i_rc_method < 0 || h->param.rc.i_rc_method > 2 )
376     {
377         x264_log( h, X264_LOG_ERROR, "invalid RC method\n" );
378         return -1;
379     }
380     h->param.rc.f_rf_constant = x264_clip3f( h->param.rc.f_rf_constant, 0, 51 );
381     h->param.rc.i_qp_constant = x264_clip3( h->param.rc.i_qp_constant, 0, 51 );
382     if( h->param.rc.i_rc_method == X264_RC_CRF )
383         h->param.rc.i_qp_constant = h->param.rc.f_rf_constant;
384     if( (h->param.rc.i_rc_method == X264_RC_CQP || h->param.rc.i_rc_method == X264_RC_CRF)
385         && h->param.rc.i_qp_constant == 0 )
386     {
387         h->mb.b_lossless = 1;
388         h->param.i_cqm_preset = X264_CQM_FLAT;
389         h->param.psz_cqm_file = NULL;
390         h->param.rc.i_rc_method = X264_RC_CQP;
391         h->param.rc.f_ip_factor = 1;
392         h->param.rc.f_pb_factor = 1;
393         h->param.analyse.b_transform_8x8 = 0;
394         h->param.analyse.b_psnr = 0;
395         h->param.analyse.b_ssim = 0;
396         h->param.analyse.i_chroma_qp_offset = 0;
397         h->param.analyse.i_trellis = 0;
398         h->param.analyse.b_fast_pskip = 0;
399         h->param.analyse.i_noise_reduction = 0;
400         h->param.analyse.i_subpel_refine = x264_clip3( h->param.analyse.i_subpel_refine, 1, 6 );
401     }
402
403     if( ( h->param.i_width % 16 || h->param.i_height % 16 ) && !h->mb.b_lossless )
404     {
405         x264_log( h, X264_LOG_WARNING, 
406                   "width or height not divisible by 16 (%dx%d), compression will suffer.\n",
407                   h->param.i_width, h->param.i_height );
408     }
409
410     h->param.i_frame_reference = x264_clip3( h->param.i_frame_reference, 1, 16 );
411     if( h->param.i_keyint_max <= 0 )
412         h->param.i_keyint_max = 1;
413     h->param.i_keyint_min = x264_clip3( h->param.i_keyint_min, 1, h->param.i_keyint_max/2+1 );
414
415     h->param.i_bframe = x264_clip3( h->param.i_bframe, 0, X264_BFRAME_MAX );
416     h->param.i_bframe_bias = x264_clip3( h->param.i_bframe_bias, -90, 100 );
417     h->param.b_bframe_pyramid = h->param.b_bframe_pyramid && h->param.i_bframe > 1;
418     h->param.b_bframe_adaptive = h->param.b_bframe_adaptive && h->param.i_bframe > 0;
419     h->param.analyse.b_weighted_bipred = h->param.analyse.b_weighted_bipred && h->param.i_bframe > 0;
420     h->mb.b_direct_auto_write = h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_AUTO
421                                 && h->param.i_bframe
422                                 && ( h->param.rc.b_stat_write || !h->param.rc.b_stat_read );
423
424     h->param.i_deblocking_filter_alphac0 = x264_clip3( h->param.i_deblocking_filter_alphac0, -6, 6 );
425     h->param.i_deblocking_filter_beta    = x264_clip3( h->param.i_deblocking_filter_beta, -6, 6 );
426     h->param.analyse.i_luma_deadzone[0] = x264_clip3( h->param.analyse.i_luma_deadzone[0], 0, 32 );
427     h->param.analyse.i_luma_deadzone[1] = x264_clip3( h->param.analyse.i_luma_deadzone[1], 0, 32 );
428     h->mb.i_luma_deadzone[0] = 32 - h->param.analyse.i_luma_deadzone[0];
429     h->mb.i_luma_deadzone[1] = 32 - h->param.analyse.i_luma_deadzone[1];
430
431     h->param.i_cabac_init_idc = x264_clip3( h->param.i_cabac_init_idc, 0, 2 );
432
433     if( h->param.i_cqm_preset < X264_CQM_FLAT || h->param.i_cqm_preset > X264_CQM_CUSTOM )
434         h->param.i_cqm_preset = X264_CQM_FLAT;
435
436     if( h->param.analyse.i_me_method < X264_ME_DIA ||
437         h->param.analyse.i_me_method > X264_ME_ESA )
438         h->param.analyse.i_me_method = X264_ME_HEX;
439     if( h->param.analyse.i_me_range < 4 )
440         h->param.analyse.i_me_range = 4;
441     if( h->param.analyse.i_me_range > 16 && h->param.analyse.i_me_method <= X264_ME_HEX )
442         h->param.analyse.i_me_range = 16;
443     h->param.analyse.i_subpel_refine = x264_clip3( h->param.analyse.i_subpel_refine, 1, 7 );
444     h->param.analyse.b_bframe_rdo = h->param.analyse.b_bframe_rdo && h->param.analyse.i_subpel_refine >= 6;
445     h->param.analyse.b_mixed_references = h->param.analyse.b_mixed_references && h->param.i_frame_reference > 1;
446     h->param.analyse.inter &= X264_ANALYSE_PSUB16x16|X264_ANALYSE_PSUB8x8|X264_ANALYSE_BSUB16x16|
447                               X264_ANALYSE_I4x4|X264_ANALYSE_I8x8;
448     h->param.analyse.intra &= X264_ANALYSE_I4x4|X264_ANALYSE_I8x8;
449     if( !(h->param.analyse.inter & X264_ANALYSE_PSUB16x16) )
450         h->param.analyse.inter &= ~X264_ANALYSE_PSUB8x8;
451     if( !h->param.analyse.b_transform_8x8 )
452     {
453         h->param.analyse.inter &= ~X264_ANALYSE_I8x8;
454         h->param.analyse.intra &= ~X264_ANALYSE_I8x8;
455     }
456     h->param.analyse.i_chroma_qp_offset = x264_clip3(h->param.analyse.i_chroma_qp_offset, -12, 12);
457     if( !h->param.b_cabac )
458         h->param.analyse.i_trellis = 0;
459     h->param.analyse.i_trellis = x264_clip3( h->param.analyse.i_trellis, 0, 2 );
460     h->param.analyse.i_noise_reduction = x264_clip3( h->param.analyse.i_noise_reduction, 0, 1<<16 );
461
462     {
463         const x264_level_t *l = x264_levels;
464         while( l->level_idc != 0 && l->level_idc != h->param.i_level_idc )
465             l++;
466         if( l->level_idc == 0 )
467         {
468             x264_log( h, X264_LOG_ERROR, "invalid level_idc: %d\n", h->param.i_level_idc );
469             return -1;
470         }
471         if( h->param.analyse.i_mv_range <= 0 )
472             h->param.analyse.i_mv_range = l->mv_range;
473         else
474             h->param.analyse.i_mv_range = x264_clip3(h->param.analyse.i_mv_range, 32, 2048);
475         if( h->param.analyse.i_direct_8x8_inference < 0 )
476             h->param.analyse.i_direct_8x8_inference = l->direct8x8;
477     }
478
479     if( h->param.rc.f_qblur < 0 )
480         h->param.rc.f_qblur = 0;
481     if( h->param.rc.f_complexity_blur < 0 )
482         h->param.rc.f_complexity_blur = 0;
483
484     h->param.i_sps_id &= 31;
485
486     if( h->param.i_log_level < X264_LOG_INFO )
487     {
488         h->param.analyse.b_psnr = 0;
489         h->param.analyse.b_ssim = 0;
490     }
491
492     /* ensure the booleans are 0 or 1 so they can be used in math */
493 #define BOOLIFY(x) h->param.x = !!h->param.x
494     BOOLIFY( b_cabac );
495     BOOLIFY( b_deblocking_filter );
496     BOOLIFY( b_interlaced );
497     BOOLIFY( analyse.b_transform_8x8 );
498     BOOLIFY( analyse.i_direct_8x8_inference );
499     BOOLIFY( analyse.b_bidir_me );
500     BOOLIFY( analyse.b_chroma_me );
501     BOOLIFY( analyse.b_fast_pskip );
502     BOOLIFY( rc.b_stat_write );
503     BOOLIFY( rc.b_stat_read );
504 #undef BOOLIFY
505
506     return 0;
507 }
508
509 static void mbcmp_init( x264_t *h )
510 {
511     memcpy( h->pixf.mbcmp,
512             ( h->mb.b_lossless || h->param.analyse.i_subpel_refine <= 1 ) ? h->pixf.sad : h->pixf.satd,
513             sizeof(h->pixf.mbcmp) );
514 }
515
516 /****************************************************************************
517  * x264_encoder_open:
518  ****************************************************************************/
519 x264_t *x264_encoder_open   ( x264_param_t *param )
520 {
521     x264_t *h = x264_malloc( sizeof( x264_t ) );
522     int i;
523
524     memset( h, 0, sizeof( x264_t ) );
525
526     /* Create a copy of param */
527     memcpy( &h->param, param, sizeof( x264_param_t ) );
528
529     if( x264_validate_parameters( h ) < 0 )
530     {
531         x264_free( h );
532         return NULL;
533     }
534
535     if( h->param.psz_cqm_file )
536         if( x264_cqm_parse_file( h, h->param.psz_cqm_file ) < 0 )
537         {
538             x264_free( h );
539             return NULL;
540         }
541
542     if( h->param.rc.psz_stat_out )
543         h->param.rc.psz_stat_out = strdup( h->param.rc.psz_stat_out );
544     if( h->param.rc.psz_stat_in )
545         h->param.rc.psz_stat_in = strdup( h->param.rc.psz_stat_in );
546     if( h->param.rc.psz_rc_eq )
547         h->param.rc.psz_rc_eq = strdup( h->param.rc.psz_rc_eq );
548
549     /* VUI */
550     if( h->param.vui.i_sar_width > 0 && h->param.vui.i_sar_height > 0 )
551     {
552         int i_w = param->vui.i_sar_width;
553         int i_h = param->vui.i_sar_height;
554
555         x264_reduce_fraction( &i_w, &i_h );
556
557         while( i_w > 65535 || i_h > 65535 )
558         {
559             i_w /= 2;
560             i_h /= 2;
561         }
562
563         h->param.vui.i_sar_width = 0;
564         h->param.vui.i_sar_height = 0;
565         if( i_w == 0 || i_h == 0 )
566         {
567             x264_log( h, X264_LOG_WARNING, "cannot create valid sample aspect ratio\n" );
568         }
569         else
570         {
571             x264_log( h, X264_LOG_INFO, "using SAR=%d/%d\n", i_w, i_h );
572             h->param.vui.i_sar_width = i_w;
573             h->param.vui.i_sar_height = i_h;
574         }
575     }
576
577     x264_reduce_fraction( &h->param.i_fps_num, &h->param.i_fps_den );
578
579     /* Init x264_t */
580     h->out.i_nal = 0;
581     h->out.i_bitstream = X264_MAX( 1000000, h->param.i_width * h->param.i_height * 1.7
582         * ( h->param.rc.i_rc_method == X264_RC_ABR ? pow( 0.5, h->param.rc.i_qp_min )
583           : pow( 0.5, h->param.rc.i_qp_constant ) * X264_MAX( 1, h->param.rc.f_ip_factor )));
584     h->out.p_bitstream = x264_malloc( h->out.i_bitstream );
585
586     h->i_frame = 0;
587     h->i_frame_num = 0;
588     h->i_idr_pic_id = 0;
589
590     h->sps = &h->sps_array[0];
591     x264_sps_init( h->sps, h->param.i_sps_id, &h->param );
592
593     h->pps = &h->pps_array[0];
594     x264_pps_init( h->pps, h->param.i_sps_id, &h->param, h->sps);
595
596     x264_validate_levels( h );
597
598     x264_cqm_init( h );
599     
600     h->mb.i_mb_count = h->sps->i_mb_width * h->sps->i_mb_height;
601
602     /* Init frames. */
603     h->frames.i_delay = h->param.i_bframe;
604     h->frames.i_max_ref0 = h->param.i_frame_reference;
605     h->frames.i_max_ref1 = h->sps->vui.i_num_reorder_frames;
606     h->frames.i_max_dpb  = h->sps->vui.i_max_dec_frame_buffering + 1;
607     h->frames.b_have_lowres = !h->param.rc.b_stat_read
608         && ( h->param.rc.i_rc_method == X264_RC_ABR
609           || h->param.rc.i_rc_method == X264_RC_CRF
610           || h->param.b_bframe_adaptive );
611
612     for( i = 0; i < X264_BFRAME_MAX + 3; i++ )
613     {
614         h->frames.current[i] = NULL;
615         h->frames.next[i]    = NULL;
616         h->frames.unused[i]  = NULL;
617     }
618     for( i = 0; i < 1 + h->frames.i_delay; i++ )
619     {
620         h->frames.unused[i] =  x264_frame_new( h );
621         if( !h->frames.unused[i] )
622             return NULL;
623     }
624     for( i = 0; i < h->frames.i_max_dpb; i++ )
625     {
626         h->frames.reference[i] = x264_frame_new( h );
627         if( !h->frames.reference[i] )
628             return NULL;
629     }
630     h->frames.reference[h->frames.i_max_dpb] = NULL;
631     h->frames.i_last_idr = - h->param.i_keyint_max;
632     h->frames.i_input    = 0;
633     h->frames.last_nonb  = NULL;
634
635     h->i_ref0 = 0;
636     h->i_ref1 = 0;
637
638     h->fdec = h->frames.reference[0];
639
640     if( x264_macroblock_cache_init( h ) < 0 )
641         return NULL;
642     x264_rdo_init( );
643
644     /* init CPU functions */
645     x264_predict_16x16_init( h->param.cpu, h->predict_16x16 );
646     x264_predict_8x8c_init( h->param.cpu, h->predict_8x8c );
647     x264_predict_8x8_init( h->param.cpu, h->predict_8x8 );
648     x264_predict_4x4_init( h->param.cpu, h->predict_4x4 );
649
650     x264_pixel_init( h->param.cpu, &h->pixf );
651     x264_dct_init( h->param.cpu, &h->dctf );
652     x264_zigzag_init( h->param.cpu, &h->zigzagf, h->param.b_interlaced );
653     x264_mc_init( h->param.cpu, &h->mc );
654     x264_csp_init( h->param.cpu, h->param.i_csp, &h->csp );
655     x264_quant_init( h, h->param.cpu, &h->quantf );
656     x264_deblock_init( h->param.cpu, &h->loopf );
657     x264_dct_init_weights();
658
659     mbcmp_init( h );
660
661     /* rate control */
662     if( x264_ratecontrol_new( h ) < 0 )
663         return NULL;
664
665     x264_log( h, X264_LOG_INFO, "using cpu capabilities %s%s%s%s%s%s\n",
666              param->cpu&X264_CPU_MMX ? "MMX " : "",
667              param->cpu&X264_CPU_MMXEXT ? "MMXEXT " : "",
668              param->cpu&X264_CPU_SSE ? "SSE " : "",
669              param->cpu&X264_CPU_SSE2 ? "SSE2 " : "",
670              param->cpu&X264_CPU_3DNOW ? "3DNow! " : "",
671              param->cpu&X264_CPU_ALTIVEC ? "Altivec " : "" );
672
673     h->thread[0] = h;
674     h->i_thread_num = 0;
675     for( i = 1; i < h->param.i_threads; i++ )
676         h->thread[i] = x264_malloc( sizeof(x264_t) );
677
678 #ifdef DEBUG_DUMP_FRAME
679     {
680         /* create or truncate the reconstructed video file */
681         FILE *f = fopen( "fdec.yuv", "w" );
682         if( f )
683             fclose( f );
684         else
685         {
686             x264_log( h, X264_LOG_ERROR, "can't write to fdec.yuv\n" );
687             x264_free( h );
688             return NULL;
689         }
690     }
691 #endif
692
693     return h;
694 }
695
696 /****************************************************************************
697  * x264_encoder_reconfig:
698  ****************************************************************************/
699 int x264_encoder_reconfig( x264_t *h, x264_param_t *param )
700 {
701 #define COPY(var) h->param.var = param->var
702     COPY( i_frame_reference ); // but never uses more refs than initially specified
703     COPY( i_bframe_bias );
704     COPY( i_scenecut_threshold );
705     COPY( b_deblocking_filter );
706     COPY( i_deblocking_filter_alphac0 );
707     COPY( i_deblocking_filter_beta );
708     COPY( analyse.intra );
709     COPY( analyse.inter );
710     COPY( analyse.i_direct_mv_pred );
711     COPY( analyse.i_me_method );
712     COPY( analyse.i_me_range );
713     COPY( analyse.i_noise_reduction );
714     COPY( analyse.i_subpel_refine );
715     COPY( analyse.i_trellis );
716     COPY( analyse.b_bidir_me );
717     COPY( analyse.b_bframe_rdo );
718     COPY( analyse.b_chroma_me );
719     COPY( analyse.b_dct_decimate );
720     COPY( analyse.b_fast_pskip );
721     COPY( analyse.b_mixed_references );
722 #undef COPY
723
724     if( h->pps->b_transform_8x8_mode )
725         h->param.analyse.b_transform_8x8 = param->analyse.b_transform_8x8;
726
727     mbcmp_init( h );
728
729     return x264_validate_parameters( h );
730 }
731
732 /* internal usage */
733 static void x264_nal_start( x264_t *h, int i_type, int i_ref_idc )
734 {
735     x264_nal_t *nal = &h->out.nal[h->out.i_nal];
736
737     nal->i_ref_idc = i_ref_idc;
738     nal->i_type    = i_type;
739
740     bs_align_0( &h->out.bs );   /* not needed */
741
742     nal->i_payload= 0;
743     nal->p_payload= &h->out.p_bitstream[bs_pos( &h->out.bs) / 8];
744 }
745 static void x264_nal_end( x264_t *h )
746 {
747     x264_nal_t *nal = &h->out.nal[h->out.i_nal];
748
749     bs_align_0( &h->out.bs );   /* not needed */
750
751     nal->i_payload = &h->out.p_bitstream[bs_pos( &h->out.bs)/8] - nal->p_payload;
752
753     h->out.i_nal++;
754 }
755
756 /****************************************************************************
757  * x264_encoder_headers:
758  ****************************************************************************/
759 int x264_encoder_headers( x264_t *h, x264_nal_t **pp_nal, int *pi_nal )
760 {
761     /* init bitstream context */
762     h->out.i_nal = 0;
763     bs_init( &h->out.bs, h->out.p_bitstream, h->out.i_bitstream );
764
765     /* Put SPS and PPS */
766     if( h->i_frame == 0 )
767     {
768         /* identify ourself */
769         x264_nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
770         x264_sei_version_write( h, &h->out.bs );
771         x264_nal_end( h );
772
773         /* generate sequence parameters */
774         x264_nal_start( h, NAL_SPS, NAL_PRIORITY_HIGHEST );
775         x264_sps_write( &h->out.bs, h->sps );
776         x264_nal_end( h );
777
778         /* generate picture parameters */
779         x264_nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
780         x264_pps_write( &h->out.bs, h->pps );
781         x264_nal_end( h );
782     }
783     /* now set output*/
784     *pi_nal = h->out.i_nal;
785     *pp_nal = &h->out.nal[0];
786
787     return 0;
788 }
789
790
791 static void x264_frame_put( x264_frame_t *list[X264_BFRAME_MAX], x264_frame_t *frame )
792 {
793     int i = 0;
794     while( list[i] ) i++;
795     list[i] = frame;
796 }
797
798 static void x264_frame_push( x264_frame_t *list[X264_BFRAME_MAX], x264_frame_t *frame )
799 {
800     int i = 0;
801     while( list[i] ) i++;
802     while( i-- )
803         list[i+1] = list[i];
804     list[0] = frame;
805 }
806
807 static x264_frame_t *x264_frame_get( x264_frame_t *list[X264_BFRAME_MAX+1] )
808 {
809     x264_frame_t *frame = list[0];
810     int i;
811     for( i = 0; list[i]; i++ )
812         list[i] = list[i+1];
813     return frame;
814 }
815
816 static void x264_frame_sort( x264_frame_t *list[X264_BFRAME_MAX+1], int b_dts )
817 {
818     int i, b_ok;
819     do {
820         b_ok = 1;
821         for( i = 0; list[i+1]; i++ )
822         {
823             int dtype = list[i]->i_type - list[i+1]->i_type;
824             int dtime = list[i]->i_frame - list[i+1]->i_frame;
825             int swap = b_dts ? dtype > 0 || ( dtype == 0 && dtime > 0 )
826                              : dtime > 0;
827             if( swap )
828             {
829                 XCHG( x264_frame_t*, list[i], list[i+1] );
830                 b_ok = 0;
831             }
832         }
833     } while( !b_ok );
834 }
835 #define x264_frame_sort_dts(list) x264_frame_sort(list, 1)
836 #define x264_frame_sort_pts(list) x264_frame_sort(list, 0)
837
838 static inline void x264_reference_build_list( x264_t *h, int i_poc, int i_slice_type )
839 {
840     int i;
841     int b_ok;
842
843     /* build ref list 0/1 */
844     h->i_ref0 = 0;
845     h->i_ref1 = 0;
846     for( i = 1; i < h->frames.i_max_dpb; i++ )
847     {
848         if( h->frames.reference[i]->i_poc >= 0 )
849         {
850             if( h->frames.reference[i]->i_poc < i_poc )
851             {
852                 h->fref0[h->i_ref0++] = h->frames.reference[i];
853             }
854             else if( h->frames.reference[i]->i_poc > i_poc )
855             {
856                 h->fref1[h->i_ref1++] = h->frames.reference[i];
857             }
858         }
859     }
860
861     /* Order ref0 from higher to lower poc */
862     do
863     {
864         b_ok = 1;
865         for( i = 0; i < h->i_ref0 - 1; i++ )
866         {
867             if( h->fref0[i]->i_poc < h->fref0[i+1]->i_poc )
868             {
869                 XCHG( x264_frame_t*, h->fref0[i], h->fref0[i+1] );
870                 b_ok = 0;
871                 break;
872             }
873         }
874     } while( !b_ok );
875     /* Order ref1 from lower to higher poc (bubble sort) for B-frame */
876     do
877     {
878         b_ok = 1;
879         for( i = 0; i < h->i_ref1 - 1; i++ )
880         {
881             if( h->fref1[i]->i_poc > h->fref1[i+1]->i_poc )
882             {
883                 XCHG( x264_frame_t*, h->fref1[i], h->fref1[i+1] );
884                 b_ok = 0;
885                 break;
886             }
887         }
888     } while( !b_ok );
889
890     /* In the standard, a P-frame's ref list is sorted by frame_num.
891      * We use POC, but check whether explicit reordering is needed */
892     h->b_ref_reorder[0] =
893     h->b_ref_reorder[1] = 0;
894     if( i_slice_type == SLICE_TYPE_P )
895     {
896         for( i = 0; i < h->i_ref0 - 1; i++ )
897             if( h->fref0[i]->i_frame_num < h->fref0[i+1]->i_frame_num )
898             {
899                 h->b_ref_reorder[0] = 1;
900                 break;
901             }
902     }
903
904     h->i_ref1 = X264_MIN( h->i_ref1, h->frames.i_max_ref1 );
905     h->i_ref0 = X264_MIN( h->i_ref0, h->frames.i_max_ref0 );
906     h->i_ref0 = X264_MIN( h->i_ref0, h->param.i_frame_reference ); // if reconfig() has lowered the limit
907     h->i_ref0 = X264_MIN( h->i_ref0, 16 - h->i_ref1 );
908     h->mb.pic.i_fref[0] = h->i_ref0;
909     h->mb.pic.i_fref[1] = h->i_ref1;
910 }
911
912 static inline void x264_fdec_deblock( x264_t *h )
913 {
914     /* apply deblocking filter to the current decoded picture */
915     if( !h->sh.i_disable_deblocking_filter_idc )
916     {
917         TIMER_START( i_mtime_filter );
918         x264_frame_deblocking_filter( h, h->sh.i_type );
919         TIMER_STOP( i_mtime_filter );
920     }
921 }
922
923 static inline void x264_reference_update( x264_t *h )
924 {
925     int i;
926
927     x264_fdec_deblock( h );
928
929     /* expand border */
930     x264_frame_expand_border( h, h->fdec );
931
932     /* create filtered images */
933     x264_frame_filter( h->param.cpu, h->fdec, h->sh.b_mbaff );
934
935     /* expand border of filtered images */
936     x264_frame_expand_border_filtered( h, h->fdec );
937
938     /* move lowres copy of the image to the ref frame */
939     for( i = 0; i < 4; i++)
940     {
941         XCHG( uint8_t*, h->fdec->lowres[i], h->fenc->lowres[i] );
942         XCHG( uint8_t*, h->fdec->buffer_lowres[i], h->fenc->buffer_lowres[i] );
943     }
944
945     /* adaptive B decision needs a pointer, since it can't use the ref lists */
946     if( h->sh.i_type != SLICE_TYPE_B )
947         h->frames.last_nonb = h->fdec;
948
949     /* move frame in the buffer */
950     h->fdec = h->frames.reference[h->frames.i_max_dpb-1];
951     for( i = h->frames.i_max_dpb-1; i > 0; i-- )
952     {
953         h->frames.reference[i] = h->frames.reference[i-1];
954     }
955     h->frames.reference[0] = h->fdec;
956 }
957
958 static inline void x264_reference_reset( x264_t *h )
959 {
960     int i;
961
962     /* reset ref pictures */
963     for( i = 1; i < h->frames.i_max_dpb; i++ )
964     {
965         h->frames.reference[i]->i_poc = -1;
966     }
967     h->frames.reference[0]->i_poc = 0;
968 }
969
970 static inline void x264_slice_init( x264_t *h, int i_nal_type, int i_slice_type, int i_global_qp )
971 {
972     /* ------------------------ Create slice header  ----------------------- */
973     if( i_nal_type == NAL_SLICE_IDR )
974     {
975         x264_slice_header_init( h, &h->sh, h->sps, h->pps, i_slice_type, h->i_idr_pic_id, h->i_frame_num, i_global_qp );
976
977         /* increment id */
978         h->i_idr_pic_id = ( h->i_idr_pic_id + 1 ) % 65536;
979     }
980     else
981     {
982         x264_slice_header_init( h, &h->sh, h->sps, h->pps, i_slice_type, -1, h->i_frame_num, i_global_qp );
983
984         /* always set the real higher num of ref frame used */
985         h->sh.b_num_ref_idx_override = 1;
986         h->sh.i_num_ref_idx_l0_active = h->i_ref0 <= 0 ? 1 : h->i_ref0;
987         h->sh.i_num_ref_idx_l1_active = h->i_ref1 <= 0 ? 1 : h->i_ref1;
988     }
989
990     h->fdec->i_frame_num = h->sh.i_frame_num;
991
992     if( h->sps->i_poc_type == 0 )
993     {
994         h->sh.i_poc_lsb = h->fdec->i_poc & ( (1 << h->sps->i_log2_max_poc_lsb) - 1 );
995         h->sh.i_delta_poc_bottom = 0;   /* XXX won't work for field */
996     }
997     else if( h->sps->i_poc_type == 1 )
998     {
999         /* FIXME TODO FIXME */
1000     }
1001     else
1002     {
1003         /* Nothing to do ? */
1004     }
1005
1006     x264_macroblock_slice_init( h );
1007 }
1008
1009 static int x264_slice_write( x264_t *h )
1010 {
1011     int i_skip;
1012     int mb_xy;
1013     int i;
1014
1015     /* init stats */
1016     memset( &h->stat.frame, 0, sizeof(h->stat.frame) );
1017
1018     /* Slice */
1019     x264_nal_start( h, h->i_nal_type, h->i_nal_ref_idc );
1020
1021     /* Slice header */
1022     x264_slice_header_write( &h->out.bs, &h->sh, h->i_nal_ref_idc );
1023     if( h->param.b_cabac )
1024     {
1025         /* alignment needed */
1026         bs_align_1( &h->out.bs );
1027
1028         /* init cabac */
1029         x264_cabac_context_init( &h->cabac, h->sh.i_type, h->sh.i_qp, h->sh.i_cabac_init_idc );
1030         x264_cabac_encode_init ( &h->cabac, &h->out.bs );
1031     }
1032     h->mb.i_last_qp = h->sh.i_qp;
1033     h->mb.i_last_dqp = 0;
1034
1035     for( mb_xy = h->sh.i_first_mb, i_skip = 0; mb_xy < h->sh.i_last_mb; )
1036     {
1037         const int i_mb_y = mb_xy / h->sps->i_mb_width;
1038         const int i_mb_x = mb_xy % h->sps->i_mb_width;
1039
1040         int mb_spos = bs_pos(&h->out.bs);
1041
1042         /* load cache */
1043         x264_macroblock_cache_load( h, i_mb_x, i_mb_y );
1044
1045         /* analyse parameters
1046          * Slice I: choose I_4x4 or I_16x16 mode
1047          * Slice P: choose between using P mode or intra (4x4 or 16x16)
1048          * */
1049         TIMER_START( i_mtime_analyse );
1050         x264_macroblock_analyse( h );
1051         TIMER_STOP( i_mtime_analyse );
1052
1053         /* encode this macroblock -> be careful it can change the mb type to P_SKIP if needed */
1054         TIMER_START( i_mtime_encode );
1055         x264_macroblock_encode( h );
1056         TIMER_STOP( i_mtime_encode );
1057
1058         TIMER_START( i_mtime_write );
1059         if( h->param.b_cabac )
1060         {
1061             if( mb_xy > h->sh.i_first_mb && !(h->sh.b_mbaff && (i_mb_y&1)) )
1062                 x264_cabac_encode_terminal( &h->cabac, 0 );
1063
1064             if( IS_SKIP( h->mb.i_type ) )
1065                 x264_cabac_mb_skip( h, 1 );
1066             else
1067             {
1068                 if( h->sh.i_type != SLICE_TYPE_I )
1069                     x264_cabac_mb_skip( h, 0 );
1070                 x264_macroblock_write_cabac( h, &h->cabac );
1071             }
1072         }
1073         else
1074         {
1075             if( IS_SKIP( h->mb.i_type ) )
1076                 i_skip++;
1077             else
1078             {
1079                 if( h->sh.i_type != SLICE_TYPE_I )
1080                 {
1081                     bs_write_ue( &h->out.bs, i_skip );  /* skip run */
1082                     i_skip = 0;
1083                 }
1084                 x264_macroblock_write_cavlc( h, &h->out.bs );
1085             }
1086         }
1087         TIMER_STOP( i_mtime_write );
1088
1089 #if VISUALIZE
1090         if( h->param.b_visualize )
1091             x264_visualize_mb( h );
1092 #endif
1093
1094         /* save cache */
1095         x264_macroblock_cache_save( h );
1096
1097         /* accumulate mb stats */
1098         h->stat.frame.i_mb_count[h->mb.i_type]++;
1099         if( !IS_SKIP(h->mb.i_type) && !IS_INTRA(h->mb.i_type) && !IS_DIRECT(h->mb.i_type) )
1100         {
1101             if( h->mb.i_partition != D_8x8 )
1102                 h->stat.frame.i_mb_count_size[ x264_mb_partition_pixel_table[ h->mb.i_partition ] ] += 4;
1103             else
1104                 for( i = 0; i < 4; i++ )
1105                     h->stat.frame.i_mb_count_size[ x264_mb_partition_pixel_table[ h->mb.i_sub_partition[i] ] ] ++;
1106             if( h->param.i_frame_reference > 1 )
1107             {
1108                 for( i = 0; i < 4; i++ )
1109                 {
1110                     int i_ref = h->mb.cache.ref[0][ x264_scan8[4*i] ];
1111                     if( i_ref >= 0 )
1112                         h->stat.frame.i_mb_count_ref[i_ref] ++;
1113                 }
1114             }
1115         }
1116         if( h->mb.i_cbp_luma && !IS_INTRA(h->mb.i_type) )
1117         {
1118             h->stat.frame.i_mb_count_8x8dct[0] ++;
1119             h->stat.frame.i_mb_count_8x8dct[1] += h->mb.b_transform_8x8;
1120         }
1121
1122         if( h->mb.b_variable_qp )
1123             x264_ratecontrol_mb(h, bs_pos(&h->out.bs) - mb_spos);
1124
1125         if( h->sh.b_mbaff )
1126         {
1127             if( (i_mb_y&1) && i_mb_x == h->sps->i_mb_width - 1 )
1128                 mb_xy++;
1129             else if( i_mb_y&1 )
1130                 mb_xy += 1 - h->sps->i_mb_width;
1131             else
1132                 mb_xy += h->sps->i_mb_width;
1133         }
1134         else
1135             mb_xy++;
1136     }
1137
1138     if( h->param.b_cabac )
1139     {
1140         /* end of slice */
1141         x264_cabac_encode_terminal( &h->cabac, 1 );
1142     }
1143     else if( i_skip > 0 )
1144     {
1145         bs_write_ue( &h->out.bs, i_skip );  /* last skip run */
1146     }
1147
1148     if( h->param.b_cabac )
1149     {
1150         x264_cabac_encode_flush( &h->cabac );
1151
1152     }
1153     else
1154     {
1155         /* rbsp_slice_trailing_bits */
1156         bs_rbsp_trailing( &h->out.bs );
1157     }
1158
1159     x264_nal_end( h );
1160
1161     /* Compute misc bits */
1162     h->stat.frame.i_misc_bits = bs_pos( &h->out.bs )
1163                               + NALU_OVERHEAD * 8
1164                               - h->stat.frame.i_itex_bits
1165                               - h->stat.frame.i_ptex_bits
1166                               - h->stat.frame.i_hdr_bits;
1167
1168     return 0;
1169 }
1170
1171 static inline int x264_slices_write( x264_t *h )
1172 {
1173     int i_frame_size;
1174
1175 #if VISUALIZE
1176     if( h->param.b_visualize )
1177         x264_visualize_init( h );
1178 #endif
1179
1180     if( h->param.i_threads == 1 )
1181     {
1182         x264_ratecontrol_threads_start( h );
1183         x264_slice_write( h );
1184         i_frame_size = h->out.nal[h->out.i_nal-1].i_payload;
1185     }
1186     else
1187     {
1188         int i_nal = h->out.i_nal;
1189         int i_bs_size = h->out.i_bitstream / h->param.i_threads;
1190         int i;
1191         /* duplicate contexts */
1192         for( i = 0; i < h->param.i_threads; i++ )
1193         {
1194             x264_t *t = h->thread[i];
1195             int mb_height = h->sps->i_mb_height >> h->sh.b_mbaff;
1196             int mb_width = h->sps->i_mb_width << h->sh.b_mbaff;
1197             if( i > 0 )
1198             {
1199                 memcpy( t, h, sizeof(x264_t) );
1200                 t->out.p_bitstream += i*i_bs_size;
1201                 bs_init( &t->out.bs, t->out.p_bitstream, i_bs_size );
1202                 t->i_thread_num = i;
1203             }
1204             t->sh.i_first_mb = (i    * mb_height / h->param.i_threads) * mb_width;
1205             t->sh.i_last_mb = ((i+1) * mb_height / h->param.i_threads) * mb_width;
1206             t->out.i_nal = i_nal + i;
1207         }
1208         x264_ratecontrol_threads_start( h );
1209
1210         /* dispatch */
1211 #ifdef HAVE_PTHREAD
1212         {
1213             pthread_t handles[X264_SLICE_MAX];
1214             for( i = 0; i < h->param.i_threads; i++ )
1215                 pthread_create( &handles[i], NULL, (void*)x264_slice_write, (void*)h->thread[i] );
1216             for( i = 0; i < h->param.i_threads; i++ )
1217                 pthread_join( handles[i], NULL );
1218         }
1219 #else
1220         for( i = 0; i < h->param.i_threads; i++ )
1221             x264_slice_write( h->thread[i] );
1222 #endif
1223
1224         /* merge contexts */
1225         i_frame_size = h->out.nal[i_nal].i_payload;
1226         for( i = 1; i < h->param.i_threads; i++ )
1227         {
1228             int j;
1229             x264_t *t = h->thread[i];
1230             h->out.nal[i_nal+i] = t->out.nal[i_nal+i];
1231             i_frame_size += t->out.nal[i_nal+i].i_payload;
1232             // all entries in stat.frame are ints
1233             for( j = 0; j < sizeof(h->stat.frame) / sizeof(int); j++ )
1234                 ((int*)&h->stat.frame)[j] += ((int*)&t->stat.frame)[j];
1235         }
1236         h->out.i_nal = i_nal + h->param.i_threads;
1237     }
1238
1239 #if VISUALIZE
1240     if( h->param.b_visualize )
1241     {
1242         x264_visualize_show( h );
1243         x264_visualize_close( h );
1244     }
1245 #endif
1246
1247     return i_frame_size;
1248 }
1249
1250 /****************************************************************************
1251  * x264_encoder_encode:
1252  *  XXX: i_poc   : is the poc of the current given picture
1253  *       i_frame : is the number of the frame being coded
1254  *  ex:  type frame poc
1255  *       I      0   2*0
1256  *       P      1   2*3
1257  *       B      2   2*1
1258  *       B      3   2*2
1259  *       P      4   2*6
1260  *       B      5   2*4
1261  *       B      6   2*5
1262  ****************************************************************************/
1263 int     x264_encoder_encode( x264_t *h,
1264                              x264_nal_t **pp_nal, int *pi_nal,
1265                              x264_picture_t *pic_in,
1266                              x264_picture_t *pic_out )
1267 {
1268     x264_frame_t   *frame_psnr = h->fdec; /* just to keep the current decoded frame for psnr calculation */
1269     int     i_nal_type;
1270     int     i_nal_ref_idc;
1271     int     i_slice_type;
1272     int     i_frame_size;
1273
1274     int i;
1275
1276     int   i_global_qp;
1277
1278     char psz_message[80];
1279
1280     /* no data out */
1281     *pi_nal = 0;
1282     *pp_nal = NULL;
1283
1284
1285     /* ------------------- Setup new frame from picture -------------------- */
1286     TIMER_START( i_mtime_encode_frame );
1287     if( pic_in != NULL )
1288     {
1289         /* 1: Copy the picture to a frame and move it to a buffer */
1290         x264_frame_t *fenc = x264_frame_get( h->frames.unused );
1291
1292         x264_frame_copy_picture( h, fenc, pic_in );
1293
1294         if( h->param.i_width != 16 * h->sps->i_mb_width ||
1295             h->param.i_height != 16 * h->sps->i_mb_height )
1296             x264_frame_expand_border_mod16( h, fenc );
1297
1298         fenc->i_frame = h->frames.i_input++;
1299
1300         x264_frame_put( h->frames.next, fenc );
1301
1302         if( h->frames.b_have_lowres )
1303             x264_frame_init_lowres( h->param.cpu, fenc );
1304
1305         if( h->frames.i_input <= h->frames.i_delay )
1306         {
1307             /* Nothing yet to encode */
1308             /* waiting for filling bframe buffer */
1309             pic_out->i_type = X264_TYPE_AUTO;
1310             return 0;
1311         }
1312     }
1313
1314     if( h->frames.current[0] == NULL )
1315     {
1316         int bframes = 0;
1317         /* 2: Select frame types */
1318         if( h->frames.next[0] == NULL )
1319             return 0;
1320
1321         x264_slicetype_decide( h );
1322
1323         /* 3: move some B-frames and 1 non-B to encode queue */
1324         while( IS_X264_TYPE_B( h->frames.next[bframes]->i_type ) )
1325             bframes++;
1326         x264_frame_put( h->frames.current, x264_frame_get( &h->frames.next[bframes] ) );
1327         /* FIXME: when max B-frames > 3, BREF may no longer be centered after GOP closing */
1328         if( h->param.b_bframe_pyramid && bframes > 1 )
1329         {
1330             x264_frame_t *mid = x264_frame_get( &h->frames.next[bframes/2] );
1331             mid->i_type = X264_TYPE_BREF;
1332             x264_frame_put( h->frames.current, mid );
1333             bframes--;
1334         }
1335         while( bframes-- )
1336             x264_frame_put( h->frames.current, x264_frame_get( h->frames.next ) );
1337     }
1338     TIMER_STOP( i_mtime_encode_frame );
1339
1340     /* ------------------- Get frame to be encoded ------------------------- */
1341     /* 4: get picture to encode */
1342     h->fenc = x264_frame_get( h->frames.current );
1343     if( h->fenc == NULL )
1344     {
1345         /* Nothing yet to encode (ex: waiting for I/P with B frames) */
1346         /* waiting for filling bframe buffer */
1347         pic_out->i_type = X264_TYPE_AUTO;
1348         return 0;
1349     }
1350
1351 do_encode:
1352
1353     if( h->fenc->i_type == X264_TYPE_IDR )
1354     {
1355         h->frames.i_last_idr = h->fenc->i_frame;
1356     }
1357
1358     /* ------------------- Setup frame context ----------------------------- */
1359     /* 5: Init data dependent of frame type */
1360     TIMER_START( i_mtime_encode_frame );
1361     if( h->fenc->i_type == X264_TYPE_IDR )
1362     {
1363         /* reset ref pictures */
1364         x264_reference_reset( h );
1365
1366         i_nal_type    = NAL_SLICE_IDR;
1367         i_nal_ref_idc = NAL_PRIORITY_HIGHEST;
1368         i_slice_type = SLICE_TYPE_I;
1369     }
1370     else if( h->fenc->i_type == X264_TYPE_I )
1371     {
1372         i_nal_type    = NAL_SLICE;
1373         i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
1374         i_slice_type = SLICE_TYPE_I;
1375     }
1376     else if( h->fenc->i_type == X264_TYPE_P )
1377     {
1378         i_nal_type    = NAL_SLICE;
1379         i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
1380         i_slice_type = SLICE_TYPE_P;
1381     }
1382     else if( h->fenc->i_type == X264_TYPE_BREF )
1383     {
1384         i_nal_type    = NAL_SLICE;
1385         i_nal_ref_idc = NAL_PRIORITY_HIGH; /* maybe add MMCO to forget it? -> low */
1386         i_slice_type = SLICE_TYPE_B;
1387     }
1388     else    /* B frame */
1389     {
1390         i_nal_type    = NAL_SLICE;
1391         i_nal_ref_idc = NAL_PRIORITY_DISPOSABLE;
1392         i_slice_type = SLICE_TYPE_B;
1393     }
1394
1395     h->fdec->i_poc =
1396     h->fenc->i_poc = 2 * (h->fenc->i_frame - h->frames.i_last_idr);
1397     h->fdec->i_type = h->fenc->i_type;
1398     h->fdec->i_frame = h->fenc->i_frame;
1399     h->fenc->b_kept_as_ref =
1400     h->fdec->b_kept_as_ref = i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE;
1401
1402
1403
1404     /* ------------------- Init                ----------------------------- */
1405     /* build ref list 0/1 */
1406     x264_reference_build_list( h, h->fdec->i_poc, i_slice_type );
1407
1408     /* Init the rate control */
1409     x264_ratecontrol_start( h, i_slice_type, h->fenc->i_qpplus1 );
1410     i_global_qp = x264_ratecontrol_qp( h );
1411
1412     pic_out->i_qpplus1 =
1413     h->fdec->i_qpplus1 = i_global_qp + 1;
1414
1415     if( i_slice_type == SLICE_TYPE_B )
1416         x264_macroblock_bipred_init( h );
1417
1418     /* ------------------------ Create slice header  ----------------------- */
1419     x264_slice_init( h, i_nal_type, i_slice_type, i_global_qp );
1420
1421     if( h->fenc->b_kept_as_ref )
1422         h->i_frame_num++;
1423
1424     /* ---------------------- Write the bitstream -------------------------- */
1425     /* Init bitstream context */
1426     h->out.i_nal = 0;
1427     bs_init( &h->out.bs, h->out.p_bitstream, h->out.i_bitstream );
1428
1429     if(h->param.b_aud){
1430         int pic_type;
1431
1432         if(i_slice_type == SLICE_TYPE_I)
1433             pic_type = 0;
1434         else if(i_slice_type == SLICE_TYPE_P)
1435             pic_type = 1;
1436         else if(i_slice_type == SLICE_TYPE_B)
1437             pic_type = 2;
1438         else
1439             pic_type = 7;
1440
1441         x264_nal_start(h, NAL_AUD, NAL_PRIORITY_DISPOSABLE);
1442         bs_write(&h->out.bs, 3, pic_type);
1443         bs_rbsp_trailing(&h->out.bs);
1444         x264_nal_end(h);
1445     }
1446
1447     h->i_nal_type = i_nal_type;
1448     h->i_nal_ref_idc = i_nal_ref_idc;
1449
1450     /* Write SPS and PPS */
1451     if( i_nal_type == NAL_SLICE_IDR && h->param.b_repeat_headers )
1452     {
1453         if( h->fenc->i_frame == 0 )
1454         {
1455             /* identify ourself */
1456             x264_nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
1457             x264_sei_version_write( h, &h->out.bs );
1458             x264_nal_end( h );
1459         }
1460
1461         /* generate sequence parameters */
1462         x264_nal_start( h, NAL_SPS, NAL_PRIORITY_HIGHEST );
1463         x264_sps_write( &h->out.bs, h->sps );
1464         x264_nal_end( h );
1465
1466         /* generate picture parameters */
1467         x264_nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
1468         x264_pps_write( &h->out.bs, h->pps );
1469         x264_nal_end( h );
1470     }
1471
1472     /* Write frame */
1473     i_frame_size = x264_slices_write( h );
1474
1475     /* restore CPU state (before using float again) */
1476     x264_cpu_restore( h->param.cpu );
1477
1478     if( i_slice_type == SLICE_TYPE_P && !h->param.rc.b_stat_read 
1479         && h->param.i_scenecut_threshold >= 0 )
1480     {
1481         const int *mbs = h->stat.frame.i_mb_count;
1482         int i_mb_i = mbs[I_16x16] + mbs[I_8x8] + mbs[I_4x4];
1483         int i_mb_p = mbs[P_L0] + mbs[P_8x8];
1484         int i_mb_s = mbs[P_SKIP];
1485         int i_mb   = h->sps->i_mb_width * h->sps->i_mb_height;
1486         int64_t i_inter_cost = h->stat.frame.i_inter_cost;
1487         int64_t i_intra_cost = h->stat.frame.i_intra_cost;
1488
1489         float f_bias;
1490         int i_gop_size = h->fenc->i_frame - h->frames.i_last_idr;
1491         float f_thresh_max = h->param.i_scenecut_threshold / 100.0;
1492         /* magic numbers pulled out of thin air */
1493         float f_thresh_min = f_thresh_max * h->param.i_keyint_min
1494                              / ( h->param.i_keyint_max * 4 );
1495         if( h->param.i_keyint_min == h->param.i_keyint_max )
1496              f_thresh_min= f_thresh_max;
1497
1498         /* macroblock_analyse() doesn't further analyse skipped mbs,
1499          * so we have to guess their cost */
1500         if( i_mb_s < i_mb )
1501             i_intra_cost = i_intra_cost * i_mb / (i_mb - i_mb_s);
1502
1503         if( i_gop_size < h->param.i_keyint_min / 4 )
1504             f_bias = f_thresh_min / 4;
1505         else if( i_gop_size <= h->param.i_keyint_min )
1506             f_bias = f_thresh_min * i_gop_size / h->param.i_keyint_min;
1507         else
1508         {
1509             f_bias = f_thresh_min
1510                      + ( f_thresh_max - f_thresh_min )
1511                        * ( i_gop_size - h->param.i_keyint_min )
1512                        / ( h->param.i_keyint_max - h->param.i_keyint_min );
1513         }
1514         f_bias = X264_MIN( f_bias, 1.0 );
1515
1516         /* Bad P will be reencoded as I */
1517         if( i_mb_s < i_mb &&
1518             i_inter_cost >= (1.0 - f_bias) * i_intra_cost )
1519         {
1520             int b;
1521
1522             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",
1523                       h->fenc->i_frame,
1524                       (double)i_intra_cost, (double)i_inter_cost,
1525                       (double)i_inter_cost / i_intra_cost,
1526                       f_bias, i_gop_size,
1527                       i_mb_i, i_mb_p, i_mb_s );
1528
1529             /* Restore frame num */
1530             h->i_frame_num--;
1531
1532             for( b = 0; h->frames.current[b] && IS_X264_TYPE_B( h->frames.current[b]->i_type ); b++ );
1533             if( b > 0 )
1534             {
1535                 /* If using B-frames, force GOP to be closed.
1536                  * Even if this frame is going to be I and not IDR, forcing a
1537                  * P-frame before the scenecut will probably help compression.
1538                  * 
1539                  * We don't yet know exactly which frame is the scene cut, so
1540                  * we can't assign an I-frame. Instead, change the previous
1541                  * B-frame to P, and rearrange coding order. */
1542
1543                 if( h->param.b_bframe_adaptive || b > 1 )
1544                     h->fenc->i_type = X264_TYPE_AUTO;
1545                 x264_frame_sort_pts( h->frames.current );
1546                 x264_frame_push( h->frames.next, h->fenc );
1547                 h->fenc = h->frames.current[b-1];
1548                 h->frames.current[b-1] = NULL;
1549                 h->fenc->i_type = X264_TYPE_P;
1550                 x264_frame_sort_dts( h->frames.current );
1551             }
1552             /* Do IDR if needed */
1553             else if( i_gop_size >= h->param.i_keyint_min )
1554             {
1555                 x264_frame_t *tmp;
1556
1557                 /* Reset */
1558                 h->i_frame_num = 0;
1559
1560                 /* Reinit field of fenc */
1561                 h->fenc->i_type = X264_TYPE_IDR;
1562                 h->fenc->i_poc = 0;
1563
1564                 /* Put enqueued frames back in the pool */
1565                 while( (tmp = x264_frame_get( h->frames.current ) ) != NULL )
1566                     x264_frame_put( h->frames.next, tmp );
1567                 x264_frame_sort_pts( h->frames.next );
1568             }
1569             else
1570             {
1571                 h->fenc->i_type = X264_TYPE_I;
1572             }
1573             goto do_encode;
1574         }
1575     }
1576
1577     /* End bitstream, set output  */
1578     *pi_nal = h->out.i_nal;
1579     *pp_nal = h->out.nal;
1580
1581     /* Set output picture properties */
1582     if( i_slice_type == SLICE_TYPE_I )
1583         pic_out->i_type = i_nal_type == NAL_SLICE_IDR ? X264_TYPE_IDR : X264_TYPE_I;
1584     else if( i_slice_type == SLICE_TYPE_P )
1585         pic_out->i_type = X264_TYPE_P;
1586     else
1587         pic_out->i_type = X264_TYPE_B;
1588     pic_out->i_pts = h->fenc->i_pts;
1589
1590     pic_out->img.i_plane = h->fdec->i_plane;
1591     for(i = 0; i < 4; i++){
1592         pic_out->img.i_stride[i] = h->fdec->i_stride[i];
1593         pic_out->img.plane[i] = h->fdec->plane[i];
1594     }
1595
1596     /* ---------------------- Update encoder state ------------------------- */
1597
1598     /* update rc */
1599     x264_cpu_restore( h->param.cpu );
1600     x264_ratecontrol_end( h, i_frame_size * 8 );
1601
1602     /* handle references */
1603     if( i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE && h->param.i_keyint_max > 1 )
1604         x264_reference_update( h );
1605 #ifdef DEBUG_DUMP_FRAME
1606     else
1607         x264_fdec_deblock( h );
1608 #endif
1609     x264_frame_put( h->frames.unused, h->fenc );
1610
1611     /* increase frame count */
1612     h->i_frame++;
1613
1614     /* restore CPU state (before using float again) */
1615     x264_cpu_restore( h->param.cpu );
1616
1617     x264_noise_reduction_update( h );
1618
1619     TIMER_STOP( i_mtime_encode_frame );
1620
1621     /* ---------------------- Compute/Print statistics --------------------- */
1622     /* Slice stat */
1623     h->stat.i_slice_count[i_slice_type]++;
1624     h->stat.i_slice_size[i_slice_type] += i_frame_size + NALU_OVERHEAD;
1625     h->stat.i_slice_qp[i_slice_type] += i_global_qp;
1626
1627     for( i = 0; i < X264_MBTYPE_MAX; i++ )
1628         h->stat.i_mb_count[h->sh.i_type][i] += h->stat.frame.i_mb_count[i];
1629     for( i = 0; i < 2; i++ )
1630         h->stat.i_mb_count_8x8dct[i] += h->stat.frame.i_mb_count_8x8dct[i];
1631     if( h->sh.i_type != SLICE_TYPE_I )
1632     {
1633         for( i = 0; i < 7; i++ )
1634             h->stat.i_mb_count_size[h->sh.i_type][i] += h->stat.frame.i_mb_count_size[i];
1635         for( i = 0; i < 32; i++ )
1636             h->stat.i_mb_count_ref[h->sh.i_type][i] += h->stat.frame.i_mb_count_ref[i];
1637     }
1638     if( i_slice_type == SLICE_TYPE_B )
1639     {
1640         h->stat.i_direct_frames[ h->sh.b_direct_spatial_mv_pred ] ++;
1641         if( h->mb.b_direct_auto_write )
1642         {
1643             //FIXME somewhat arbitrary time constants
1644             if( h->stat.i_direct_score[0] + h->stat.i_direct_score[1] > h->mb.i_mb_count )
1645             {
1646                 for( i = 0; i < 2; i++ )
1647                     h->stat.i_direct_score[i] = h->stat.i_direct_score[i] * 9/10;
1648             }
1649             for( i = 0; i < 2; i++ )
1650                 h->stat.i_direct_score[i] += h->stat.frame.i_direct_score[i];
1651         }
1652     }
1653
1654     psz_message[0] = '\0';
1655     if( h->param.analyse.b_psnr )
1656     {
1657         int64_t sqe[3];
1658
1659         for( i=0; i<3; i++ )
1660         {
1661             sqe[i] = x264_pixel_ssd_wxh( &h->pixf,
1662                          frame_psnr->plane[i], frame_psnr->i_stride[i],
1663                          h->fenc->plane[i], h->fenc->i_stride[i],
1664                          h->param.i_width >> !!i, h->param.i_height >> !!i );
1665         }
1666         x264_cpu_restore( h->param.cpu );
1667
1668         h->stat.i_sqe_global[i_slice_type] += sqe[0] + sqe[1] + sqe[2];
1669         h->stat.f_psnr_average[i_slice_type] += x264_psnr( sqe[0] + sqe[1] + sqe[2], 3 * h->param.i_width * h->param.i_height / 2 );
1670         h->stat.f_psnr_mean_y[i_slice_type] += x264_psnr( sqe[0], h->param.i_width * h->param.i_height );
1671         h->stat.f_psnr_mean_u[i_slice_type] += x264_psnr( sqe[1], h->param.i_width * h->param.i_height / 4 );
1672         h->stat.f_psnr_mean_v[i_slice_type] += x264_psnr( sqe[2], h->param.i_width * h->param.i_height / 4 );
1673
1674         snprintf( psz_message, 80, " PSNR Y:%5.2f U:%5.2f V:%5.2f",
1675                   x264_psnr( sqe[0], h->param.i_width * h->param.i_height ),
1676                   x264_psnr( sqe[1], h->param.i_width * h->param.i_height / 4),
1677                   x264_psnr( sqe[2], h->param.i_width * h->param.i_height / 4) );
1678     }
1679
1680     if( h->param.analyse.b_ssim )
1681     {
1682         // offset by 2 pixels to avoid alignment of ssim blocks with dct blocks
1683         float ssim_y = x264_pixel_ssim_wxh( &h->pixf,
1684                          frame_psnr->plane[0] + 2+2*frame_psnr->i_stride[0], frame_psnr->i_stride[0],
1685                          h->fenc->plane[0] + 2+2*h->fenc->i_stride[0], h->fenc->i_stride[0],
1686                          h->param.i_width-2, h->param.i_height-2 );
1687         h->stat.f_ssim_mean_y[i_slice_type] += ssim_y;
1688         snprintf( psz_message + strlen(psz_message), 80 - strlen(psz_message),
1689                   " SSIM Y:%.5f", ssim_y );
1690     }
1691     psz_message[79] = '\0';
1692     
1693     x264_log( h, X264_LOG_DEBUG,
1694                   "frame=%4d QP=%i NAL=%d Slice:%c Poc:%-3d I:%-4d P:%-4d SKIP:%-4d size=%d bytes%s\n",
1695               h->i_frame - 1,
1696               i_global_qp,
1697               i_nal_ref_idc,
1698               i_slice_type == SLICE_TYPE_I ? 'I' : (i_slice_type == SLICE_TYPE_P ? 'P' : 'B' ),
1699               frame_psnr->i_poc,
1700               h->stat.frame.i_mb_count_i,
1701               h->stat.frame.i_mb_count_p,
1702               h->stat.frame.i_mb_count_skip,
1703               i_frame_size,
1704               psz_message );
1705
1706
1707 #ifdef DEBUG_MB_TYPE
1708 {
1709     static const char mb_chars[] = { 'i', 'i', 'I', 'C', 'P', '8', 'S',
1710         'D', '<', 'X', 'B', 'X', '>', 'B', 'B', 'B', 'B', '8', 'S' };
1711     int mb_xy;
1712     for( mb_xy = 0; mb_xy < h->sps->i_mb_width * h->sps->i_mb_height; mb_xy++ )
1713     {
1714         if( h->mb.type[mb_xy] < X264_MBTYPE_MAX && h->mb.type[mb_xy] >= 0 )
1715             fprintf( stderr, "%c ", mb_chars[ h->mb.type[mb_xy] ] );
1716         else
1717             fprintf( stderr, "? " );
1718
1719         if( (mb_xy+1) % h->sps->i_mb_width == 0 )
1720             fprintf( stderr, "\n" );
1721     }
1722 }
1723 #endif
1724
1725 #ifdef DEBUG_DUMP_FRAME
1726     /* Dump reconstructed frame */
1727     x264_frame_dump( h, frame_psnr, "fdec.yuv" );
1728 #endif
1729     return 0;
1730 }
1731
1732 /****************************************************************************
1733  * x264_encoder_close:
1734  ****************************************************************************/
1735 void    x264_encoder_close  ( x264_t *h )
1736 {
1737 #ifdef DEBUG_BENCHMARK
1738     int64_t i_mtime_total = i_mtime_analyse + i_mtime_encode + i_mtime_write + i_mtime_filter + 1;
1739 #endif
1740     int64_t i_yuv_size = 3 * h->param.i_width * h->param.i_height / 2;
1741     int i;
1742
1743 #ifdef DEBUG_BENCHMARK
1744     x264_log( h, X264_LOG_INFO,
1745               "analyse=%d(%lldms) encode=%d(%lldms) write=%d(%lldms) filter=%d(%lldms)\n",
1746               (int)(100*i_mtime_analyse/i_mtime_total), i_mtime_analyse/1000,
1747               (int)(100*i_mtime_encode/i_mtime_total), i_mtime_encode/1000,
1748               (int)(100*i_mtime_write/i_mtime_total), i_mtime_write/1000,
1749               (int)(100*i_mtime_filter/i_mtime_total), i_mtime_filter/1000 );
1750 #endif
1751
1752     /* Slices used and PSNR */
1753     for( i=0; i<5; i++ )
1754     {
1755         static const int slice_order[] = { SLICE_TYPE_I, SLICE_TYPE_SI, SLICE_TYPE_P, SLICE_TYPE_SP, SLICE_TYPE_B };
1756         static const char *slice_name[] = { "P", "B", "I", "SP", "SI" };
1757         int i_slice = slice_order[i];
1758
1759         if( h->stat.i_slice_count[i_slice] > 0 )
1760         {
1761             const int i_count = h->stat.i_slice_count[i_slice];
1762             if( h->param.analyse.b_psnr )
1763             {
1764                 x264_log( h, X264_LOG_INFO,
1765                           "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",
1766                           slice_name[i_slice],
1767                           i_count,
1768                           (double)h->stat.i_slice_qp[i_slice] / i_count,
1769                           (double)h->stat.i_slice_size[i_slice] / i_count,
1770                           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,
1771                           h->stat.f_psnr_average[i_slice] / i_count,
1772                           x264_psnr( h->stat.i_sqe_global[i_slice], i_count * i_yuv_size ) );
1773             }
1774             else
1775             {
1776                 x264_log( h, X264_LOG_INFO,
1777                           "slice %s:%-5d Avg QP:%5.2f  size:%6.0f\n",
1778                           slice_name[i_slice],
1779                           i_count,
1780                           (double)h->stat.i_slice_qp[i_slice] / i_count,
1781                           (double)h->stat.i_slice_size[i_slice] / i_count );
1782             }
1783         }
1784     }
1785
1786     /* MB types used */
1787     if( h->stat.i_slice_count[SLICE_TYPE_I] > 0 )
1788     {
1789         const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_I];
1790         const double i_count = h->stat.i_slice_count[SLICE_TYPE_I] * h->mb.i_mb_count / 100.0;
1791         x264_log( h, X264_LOG_INFO,
1792                   "mb I  I16..4: %4.1f%% %4.1f%% %4.1f%%\n",
1793                   i_mb_count[I_16x16]/ i_count,
1794                   i_mb_count[I_8x8]  / i_count,
1795                   i_mb_count[I_4x4]  / i_count );
1796     }
1797     if( h->stat.i_slice_count[SLICE_TYPE_P] > 0 )
1798     {
1799         const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_P];
1800         const int64_t *i_mb_size = h->stat.i_mb_count_size[SLICE_TYPE_P];
1801         const double i_count = h->stat.i_slice_count[SLICE_TYPE_P] * h->mb.i_mb_count / 100.0;
1802         x264_log( h, X264_LOG_INFO,
1803                   "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",
1804                   i_mb_count[I_16x16]/ i_count,
1805                   i_mb_count[I_8x8]  / i_count,
1806                   i_mb_count[I_4x4]  / i_count,
1807                   i_mb_size[PIXEL_16x16] / (i_count*4),
1808                   (i_mb_size[PIXEL_16x8] + i_mb_size[PIXEL_8x16]) / (i_count*4),
1809                   i_mb_size[PIXEL_8x8] / (i_count*4),
1810                   (i_mb_size[PIXEL_8x4] + i_mb_size[PIXEL_4x8]) / (i_count*4),
1811                   i_mb_size[PIXEL_4x4] / (i_count*4),
1812                   i_mb_count[P_SKIP] / i_count );
1813     }
1814     if( h->stat.i_slice_count[SLICE_TYPE_B] > 0 )
1815     {
1816         const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_B];
1817         const int64_t *i_mb_size = h->stat.i_mb_count_size[SLICE_TYPE_B];
1818         const double i_count = h->stat.i_slice_count[SLICE_TYPE_B] * h->mb.i_mb_count / 100.0;
1819         x264_log( h, X264_LOG_INFO,
1820                   "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",
1821                   i_mb_count[I_16x16]  / i_count,
1822                   i_mb_count[I_8x8]    / i_count,
1823                   i_mb_count[I_4x4]    / i_count,
1824                   i_mb_size[PIXEL_16x16] / (i_count*4),
1825                   (i_mb_size[PIXEL_16x8] + i_mb_size[PIXEL_8x16]) / (i_count*4),
1826                   i_mb_size[PIXEL_8x8] / (i_count*4),
1827                   i_mb_count[B_DIRECT] / i_count,
1828                   i_mb_count[B_SKIP]   / i_count );
1829     }
1830
1831     x264_ratecontrol_summary( h );
1832
1833     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 )
1834     {
1835         const int i_count = h->stat.i_slice_count[SLICE_TYPE_I] +
1836                             h->stat.i_slice_count[SLICE_TYPE_P] +
1837                             h->stat.i_slice_count[SLICE_TYPE_B];
1838         float fps = (float) h->param.i_fps_num / h->param.i_fps_den;
1839 #define SUM3(p) (p[SLICE_TYPE_I] + p[SLICE_TYPE_P] + p[SLICE_TYPE_B])
1840 #define SUM3b(p,o) (p[SLICE_TYPE_I][o] + p[SLICE_TYPE_P][o] + p[SLICE_TYPE_B][o])
1841         float f_bitrate = fps * SUM3(h->stat.i_slice_size) / i_count / 125;
1842
1843         if( h->pps->b_transform_8x8_mode )
1844         {
1845             int64_t i_i8x8 = SUM3b( h->stat.i_mb_count, I_8x8 );
1846             int64_t i_intra = i_i8x8 + SUM3b( h->stat.i_mb_count, I_4x4 )
1847                                      + SUM3b( h->stat.i_mb_count, I_16x16 );
1848             x264_log( h, X264_LOG_INFO, "8x8 transform  intra:%.1f%%  inter:%.1f%%\n",
1849                       100. * i_i8x8 / i_intra,
1850                       100. * h->stat.i_mb_count_8x8dct[1] / h->stat.i_mb_count_8x8dct[0] );
1851         }
1852
1853         if( h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_AUTO
1854             && h->stat.i_slice_count[SLICE_TYPE_B] )
1855         {
1856             x264_log( h, X264_LOG_INFO, "direct mvs  spatial:%.1f%%  temporal:%.1f%%\n",
1857                       h->stat.i_direct_frames[1] * 100. / h->stat.i_slice_count[SLICE_TYPE_B],
1858                       h->stat.i_direct_frames[0] * 100. / h->stat.i_slice_count[SLICE_TYPE_B] );
1859         }
1860
1861         if( h->frames.i_max_ref0 > 1 )
1862         {
1863             int i_slice;
1864             for( i_slice = 0; i_slice < 2; i_slice++ )
1865             {
1866                 char buf[200];
1867                 char *p = buf;
1868                 int64_t i_den = 0;
1869                 int i_max = 0;
1870                 for( i = 0; i < h->frames.i_max_ref0 << h->param.b_interlaced; i++ )
1871                     if( h->stat.i_mb_count_ref[i_slice][i] )
1872                     {
1873                         i_den += h->stat.i_mb_count_ref[i_slice][i];
1874                         i_max = i;
1875                     }
1876                 if( i_max == 0 )
1877                     continue;
1878                 for( i = 0; i <= i_max; i++ )
1879                     p += sprintf( p, " %4.1f%%", 100. * h->stat.i_mb_count_ref[i_slice][i] / i_den );
1880                 x264_log( h, X264_LOG_INFO, "ref %c %s\n", i_slice==SLICE_TYPE_P ? 'P' : 'B', buf );
1881             }
1882         }
1883
1884         if( h->param.analyse.b_ssim )
1885         {
1886             x264_log( h, X264_LOG_INFO,
1887                       "SSIM Mean Y:%.7f\n",
1888                       SUM3( h->stat.f_ssim_mean_y ) / i_count );
1889         }
1890         if( h->param.analyse.b_psnr )
1891         {
1892             x264_log( h, X264_LOG_INFO,
1893                       "PSNR Mean Y:%6.3f U:%6.3f V:%6.3f Avg:%6.3f Global:%6.3f kb/s:%.2f\n",
1894                       SUM3( h->stat.f_psnr_mean_y ) / i_count,
1895                       SUM3( h->stat.f_psnr_mean_u ) / i_count,
1896                       SUM3( h->stat.f_psnr_mean_v ) / i_count,
1897                       SUM3( h->stat.f_psnr_average ) / i_count,
1898                       x264_psnr( SUM3( h->stat.i_sqe_global ), i_count * i_yuv_size ),
1899                       f_bitrate );
1900         }
1901         else
1902             x264_log( h, X264_LOG_INFO, "kb/s:%.1f\n", f_bitrate );
1903     }
1904
1905     /* frames */
1906     for( i = 0; i < X264_BFRAME_MAX + 3; i++ )
1907     {
1908         if( h->frames.current[i] ) x264_frame_delete( h->frames.current[i] );
1909         if( h->frames.next[i] )    x264_frame_delete( h->frames.next[i] );
1910         if( h->frames.unused[i] )  x264_frame_delete( h->frames.unused[i] );
1911     }
1912     /* ref frames */
1913     for( i = 0; i < h->frames.i_max_dpb; i++ )
1914     {
1915         x264_frame_delete( h->frames.reference[i] );
1916     }
1917
1918     /* rc */
1919     x264_ratecontrol_delete( h );
1920
1921     /* param */
1922     if( h->param.rc.psz_stat_out )
1923         free( h->param.rc.psz_stat_out );
1924     if( h->param.rc.psz_stat_in )
1925         free( h->param.rc.psz_stat_in );
1926     if( h->param.rc.psz_rc_eq )
1927         free( h->param.rc.psz_rc_eq );
1928
1929     x264_cqm_delete( h );
1930     x264_macroblock_cache_end( h );
1931     x264_free( h->out.p_bitstream );
1932     for( i = 1; i < h->param.i_threads; i++ )
1933         x264_free( h->thread[i] );
1934     x264_free( h );
1935 }