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