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