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