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