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