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