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