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