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