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