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