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