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