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