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