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