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