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