]> git.sesse.net Git - x264/blob - encoder/encoder.c
457a34d15aedbba58016ca9d57ed32935b375bd0
[x264] / encoder / encoder.c
1 /*****************************************************************************
2  * x264: h264 encoder
3  *****************************************************************************
4  * Copyright (C) 2003 Laurent Aimar
5  * $Id: encoder.c,v 1.1 2004/06/03 19:27:08 fenrir Exp $
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
22  *****************************************************************************/
23
24 #include <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.i_rf_constant > 0 )
356         h->param.rc.i_qp_constant = h->param.rc.i_rf_constant;
357     h->param.rc.i_rf_constant = x264_clip3( h->param.rc.i_rf_constant, 0, 51 );
358     h->param.rc.i_qp_constant = x264_clip3( h->param.rc.i_qp_constant, 0, 51 );
359     if( !h->param.rc.b_cbr && h->param.rc.i_qp_constant == 0 )
360     {
361         h->mb.b_lossless = 1;
362         h->param.analyse.b_transform_8x8 = 0;
363         h->param.i_cqm_preset = X264_CQM_FLAT;
364         h->param.psz_cqm_file = NULL;
365         h->param.rc.f_ip_factor = 1;
366         h->param.rc.f_pb_factor = 1;
367         h->param.analyse.b_psnr = 0;
368         h->param.analyse.i_chroma_qp_offset = 0;
369     }
370
371     if( ( h->param.i_width % 16 || h->param.i_height % 16 ) && !h->mb.b_lossless )
372     {
373         x264_log( h, X264_LOG_WARNING, 
374                   "width or height not divisible by 16 (%dx%d), compression will suffer.\n",
375                   h->param.i_width, h->param.i_height );
376     }
377
378     h->param.i_frame_reference = x264_clip3( h->param.i_frame_reference, 1, 16 );
379     if( h->param.i_keyint_max <= 0 )
380         h->param.i_keyint_max = 1;
381     h->param.i_keyint_min = x264_clip3( h->param.i_keyint_min, 1, h->param.i_keyint_max/2+1 );
382
383     h->param.i_bframe = x264_clip3( h->param.i_bframe, 0, X264_BFRAME_MAX );
384     h->param.i_bframe_bias = x264_clip3( h->param.i_bframe_bias, -90, 100 );
385     h->param.b_bframe_pyramid = h->param.b_bframe_pyramid && h->param.i_bframe > 1;
386     h->param.b_bframe_adaptive = h->param.b_bframe_adaptive && h->param.i_bframe > 0;
387
388     h->param.i_deblocking_filter_alphac0 = x264_clip3( h->param.i_deblocking_filter_alphac0, -6, 6 );
389     h->param.i_deblocking_filter_beta    = x264_clip3( h->param.i_deblocking_filter_beta, -6, 6 );
390
391     h->param.i_cabac_init_idc = x264_clip3( h->param.i_cabac_init_idc, 0, 2 );
392
393     if( h->param.i_cqm_preset < X264_CQM_FLAT || h->param.i_cqm_preset > X264_CQM_CUSTOM )
394         h->param.i_cqm_preset = X264_CQM_FLAT;
395
396     if( h->param.analyse.i_me_method < X264_ME_DIA ||
397         h->param.analyse.i_me_method > X264_ME_ESA )
398         h->param.analyse.i_me_method = X264_ME_HEX;
399     if( h->param.analyse.i_me_range < 4 )
400         h->param.analyse.i_me_range = 4;
401     if( h->param.analyse.i_me_range > 16 && h->param.analyse.i_me_method <= X264_ME_HEX )
402         h->param.analyse.i_me_range = 16;
403     h->param.analyse.i_subpel_refine = x264_clip3( h->param.analyse.i_subpel_refine, 1, 6 );
404     if( !(h->param.analyse.inter & X264_ANALYSE_PSUB16x16) )
405         h->param.analyse.inter &= ~X264_ANALYSE_PSUB8x8;
406     if( !h->param.analyse.b_transform_8x8 )
407     {
408         h->param.analyse.inter &= ~X264_ANALYSE_I8x8;
409         h->param.analyse.intra &= ~X264_ANALYSE_I8x8;
410     }
411     h->param.analyse.i_chroma_qp_offset = x264_clip3(h->param.analyse.i_chroma_qp_offset, -12, 12);
412     if( !h->param.b_cabac )
413         h->param.analyse.i_trellis = 0;
414
415     {
416         const x264_level_t *l = x264_levels;
417         while( l->level_idc != 0 && l->level_idc != h->param.i_level_idc )
418             l++;
419         if( l->level_idc == 0 )
420         {
421             x264_log( h, X264_LOG_ERROR, "invalid level_idc: %d\n", h->param.i_level_idc );
422             return -1;
423         }
424         if( h->param.analyse.i_mv_range <= 0 )
425             h->param.analyse.i_mv_range = l->mv_range;
426         else
427             h->param.analyse.i_mv_range = x264_clip3(h->param.analyse.i_mv_range, 32, 2048);
428     }
429
430     if( h->param.rc.f_qblur < 0 )
431         h->param.rc.f_qblur = 0;
432     if( h->param.rc.f_complexity_blur < 0 )
433         h->param.rc.f_complexity_blur = 0;
434
435     return 0;
436 }
437
438 /****************************************************************************
439  * x264_encoder_open:
440  ****************************************************************************/
441 x264_t *x264_encoder_open   ( x264_param_t *param )
442 {
443     x264_t *h = x264_malloc( sizeof( x264_t ) );
444     int i;
445
446     memset( h, 0, sizeof( x264_t ) );
447
448     /* Create a copy of param */
449     memcpy( &h->param, param, sizeof( x264_param_t ) );
450
451     if( x264_validate_parameters( h ) < 0 )
452     {
453         x264_free( h );
454         return NULL;
455     }
456
457     if( h->param.psz_cqm_file )
458         if( x264_cqm_parse_file( h, h->param.psz_cqm_file ) < 0 )
459         {
460             x264_free( h );
461             return NULL;
462         }
463
464     if( h->param.rc.psz_stat_out )
465         h->param.rc.psz_stat_out = strdup( h->param.rc.psz_stat_out );
466     if( h->param.rc.psz_stat_in )
467         h->param.rc.psz_stat_in = strdup( h->param.rc.psz_stat_in );
468     if( h->param.rc.psz_rc_eq )
469         h->param.rc.psz_rc_eq = strdup( h->param.rc.psz_rc_eq );
470
471     /* VUI */
472     if( h->param.vui.i_sar_width > 0 && h->param.vui.i_sar_height > 0 )
473     {
474         int i_w = param->vui.i_sar_width;
475         int i_h = param->vui.i_sar_height;
476         int a = i_w, b = i_h;
477
478         while( b != 0 )
479         {
480             int t = a;
481
482             a = b;
483             b = t % b;
484         }
485
486         i_w /= a;
487         i_h /= a;
488         while( i_w > 65535 || i_h > 65535 )
489         {
490             i_w /= 2;
491             i_h /= 2;
492         }
493
494         h->param.vui.i_sar_width = 0;
495         h->param.vui.i_sar_height = 0;
496         if( i_w == 0 || i_h == 0 )
497         {
498             x264_log( h, X264_LOG_ERROR, "cannot create valid sample aspect ratio\n" );
499         }
500         else if( i_w == i_h )
501         {
502             x264_log( h, X264_LOG_INFO, "no need for a SAR\n" );
503         }
504         else
505         {
506             x264_log( h, X264_LOG_INFO, "using SAR=%d/%d\n", i_w, i_h );
507             h->param.vui.i_sar_width = i_w;
508             h->param.vui.i_sar_height = i_h;
509         }
510     }
511
512
513     /* Init x264_t */
514     h->out.i_nal = 0;
515     h->out.i_bitstream = X264_MAX( 1000000, h->param.i_width * h->param.i_height * 1.7
516         * ( h->param.rc.b_cbr ? pow( 0.5, h->param.rc.i_qp_min )
517           : pow( 0.5, h->param.rc.i_qp_constant ) * X264_MAX( 1, h->param.rc.f_ip_factor )));
518     h->out.p_bitstream = x264_malloc( h->out.i_bitstream );
519
520     h->i_frame = 0;
521     h->i_frame_num = 0;
522     h->i_idr_pic_id = 0;
523
524     h->sps = &h->sps_array[0];
525     x264_sps_init( h->sps, 0, &h->param );
526
527     h->pps = &h->pps_array[0];
528     x264_pps_init( h->pps, 0, &h->param, h->sps);
529
530     x264_validate_levels( h );
531
532     x264_cqm_init( h );
533     
534     h->mb.i_mb_count = h->sps->i_mb_width * h->sps->i_mb_height;
535
536     /* Init frames. */
537     h->frames.i_delay = h->param.i_bframe;
538     h->frames.i_max_ref0 = h->param.i_frame_reference;
539     h->frames.i_max_ref1 = h->sps->vui.i_num_reorder_frames;
540     h->frames.i_max_dpb  = h->sps->vui.i_max_dec_frame_buffering + 1;
541     h->frames.b_have_lowres = !h->param.rc.b_stat_read
542         && ( h->param.rc.b_cbr || h->param.rc.i_rf_constant || h->param.b_bframe_adaptive );
543
544     for( i = 0; i < X264_BFRAME_MAX + 3; i++ )
545     {
546         h->frames.current[i] = NULL;
547         h->frames.next[i]    = NULL;
548         h->frames.unused[i]  = NULL;
549     }
550     for( i = 0; i < 1 + h->frames.i_delay; i++ )
551     {
552         h->frames.unused[i] =  x264_frame_new( h );
553     }
554     for( i = 0; i < h->frames.i_max_dpb; i++ )
555     {
556         h->frames.reference[i] = x264_frame_new( h );
557     }
558     h->frames.reference[h->frames.i_max_dpb] = NULL;
559     h->frames.i_last_idr = - h->param.i_keyint_max;
560     h->frames.i_input    = 0;
561     h->frames.last_nonb  = NULL;
562
563     h->i_ref0 = 0;
564     h->i_ref1 = 0;
565
566     h->fdec = h->frames.reference[0];
567
568     x264_macroblock_cache_init( h );
569     x264_rdo_init( );
570
571     /* init CPU functions */
572     x264_predict_16x16_init( h->param.cpu, h->predict_16x16 );
573     x264_predict_8x8c_init( h->param.cpu, h->predict_8x8c );
574     x264_predict_8x8_init( h->param.cpu, h->predict_8x8 );
575     x264_predict_4x4_init( h->param.cpu, h->predict_4x4 );
576
577     x264_pixel_init( h->param.cpu, &h->pixf );
578     x264_dct_init( h->param.cpu, &h->dctf );
579     x264_mc_init( h->param.cpu, &h->mc );
580     x264_csp_init( h->param.cpu, h->param.i_csp, &h->csp );
581     x264_quant_init( h, h->param.cpu, &h->quantf );
582     x264_deblock_init( h->param.cpu, &h->loopf );
583
584     memcpy( h->pixf.mbcmp,
585             ( h->mb.b_lossless || h->param.analyse.i_subpel_refine <= 1 ) ? h->pixf.sad : h->pixf.satd,
586             sizeof(h->pixf.mbcmp) );
587
588     /* rate control */
589     if( x264_ratecontrol_new( h ) < 0 )
590         return NULL;
591
592     x264_log( h, X264_LOG_INFO, "using cpu capabilities %s%s%s%s%s%s\n",
593              param->cpu&X264_CPU_MMX ? "MMX " : "",
594              param->cpu&X264_CPU_MMXEXT ? "MMXEXT " : "",
595              param->cpu&X264_CPU_SSE ? "SSE " : "",
596              param->cpu&X264_CPU_SSE2 ? "SSE2 " : "",
597              param->cpu&X264_CPU_3DNOW ? "3DNow! " : "",
598              param->cpu&X264_CPU_ALTIVEC ? "Altivec " : "" );
599
600     h->thread[0] = h;
601     for( i = 1; i < param->i_threads; i++ )
602         h->thread[i] = x264_malloc( sizeof(x264_t) );
603
604     return h;
605 }
606
607 /****************************************************************************
608  * x264_encoder_reconfig:
609  ****************************************************************************/
610 int x264_encoder_reconfig( x264_t *h, x264_param_t *param )
611 {
612     h->param.i_bframe_bias = param->i_bframe_bias;
613     h->param.i_deblocking_filter_alphac0 = param->i_deblocking_filter_alphac0;
614     h->param.i_deblocking_filter_beta    = param->i_deblocking_filter_beta;
615     h->param.analyse.i_me_method = param->analyse.i_me_method;
616     h->param.analyse.i_me_range = param->analyse.i_me_range;
617     h->param.analyse.i_subpel_refine = param->analyse.i_subpel_refine;
618     h->param.analyse.i_trellis = param->analyse.i_trellis;
619     h->param.analyse.intra = param->analyse.intra;
620     h->param.analyse.inter = param->analyse.inter;
621     if( h->sps->b_direct8x8_inference && h->param.i_bframe
622         && h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_TEMPORAL )
623         h->param.analyse.inter &= ~X264_ANALYSE_PSUB8x8;
624
625     memcpy( h->pixf.mbcmp,
626             ( h->mb.b_lossless || h->param.analyse.i_subpel_refine <= 1 ) ? h->pixf.sad : h->pixf.satd,
627             sizeof(h->pixf.mbcmp) );
628
629     return x264_validate_parameters( h );
630 }
631
632 /* internal usage */
633 static void x264_nal_start( x264_t *h, int i_type, int i_ref_idc )
634 {
635     x264_nal_t *nal = &h->out.nal[h->out.i_nal];
636
637     nal->i_ref_idc = i_ref_idc;
638     nal->i_type    = i_type;
639
640     bs_align_0( &h->out.bs );   /* not needed */
641
642     nal->i_payload= 0;
643     nal->p_payload= &h->out.p_bitstream[bs_pos( &h->out.bs) / 8];
644 }
645 static void x264_nal_end( x264_t *h )
646 {
647     x264_nal_t *nal = &h->out.nal[h->out.i_nal];
648
649     bs_align_0( &h->out.bs );   /* not needed */
650
651     nal->i_payload = &h->out.p_bitstream[bs_pos( &h->out.bs)/8] - nal->p_payload;
652
653     h->out.i_nal++;
654 }
655
656 /****************************************************************************
657  * x264_encoder_headers:
658  ****************************************************************************/
659 int x264_encoder_headers( x264_t *h, x264_nal_t **pp_nal, int *pi_nal )
660 {
661     /* init bitstream context */
662     h->out.i_nal = 0;
663     bs_init( &h->out.bs, h->out.p_bitstream, h->out.i_bitstream );
664
665     /* Put SPS and PPS */
666     if( h->i_frame == 0 )
667     {
668         /* identify ourself */
669         x264_nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
670         x264_sei_version_write( &h->out.bs );
671         x264_nal_end( h );
672
673         /* generate sequence parameters */
674         x264_nal_start( h, NAL_SPS, NAL_PRIORITY_HIGHEST );
675         x264_sps_write( &h->out.bs, h->sps );
676         x264_nal_end( h );
677
678         /* generate picture parameters */
679         x264_nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
680         x264_pps_write( &h->out.bs, h->pps );
681         x264_nal_end( h );
682     }
683     /* now set output*/
684     *pi_nal = h->out.i_nal;
685     *pp_nal = &h->out.nal[0];
686
687     return 0;
688 }
689
690
691 static void x264_frame_put( x264_frame_t *list[X264_BFRAME_MAX], x264_frame_t *frame )
692 {
693     int i = 0;
694     while( list[i] ) i++;
695     list[i] = frame;
696 }
697
698 static void x264_frame_push( x264_frame_t *list[X264_BFRAME_MAX], x264_frame_t *frame )
699 {
700     int i = 0;
701     while( list[i] ) i++;
702     while( i-- )
703         list[i+1] = list[i];
704     list[0] = frame;
705 }
706
707 static x264_frame_t *x264_frame_get( x264_frame_t *list[X264_BFRAME_MAX+1] )
708 {
709     x264_frame_t *frame = list[0];
710     int i;
711     for( i = 0; list[i]; i++ )
712         list[i] = list[i+1];
713     return frame;
714 }
715
716 static void x264_frame_sort( x264_frame_t *list[X264_BFRAME_MAX+1], int b_dts )
717 {
718     int i, b_ok;
719     do {
720         b_ok = 1;
721         for( i = 0; list[i+1]; i++ )
722         {
723             int dtype = list[i]->i_type - list[i+1]->i_type;
724             int dtime = list[i]->i_frame - list[i+1]->i_frame;
725             int swap = b_dts ? dtype > 0 || ( dtype == 0 && dtime > 0 )
726                              : dtime > 0;
727             if( swap )
728             {
729                 XCHG( x264_frame_t*, list[i], list[i+1] );
730                 b_ok = 0;
731             }
732         }
733     } while( !b_ok );
734 }
735 #define x264_frame_sort_dts(list) x264_frame_sort(list, 1)
736 #define x264_frame_sort_pts(list) x264_frame_sort(list, 0)
737
738 static inline void x264_reference_build_list( x264_t *h, int i_poc, int i_slice_type )
739 {
740     int i;
741     int b_ok;
742
743     /* build ref list 0/1 */
744     h->i_ref0 = 0;
745     h->i_ref1 = 0;
746     for( i = 1; i < h->frames.i_max_dpb; i++ )
747     {
748         if( h->frames.reference[i]->i_poc >= 0 )
749         {
750             if( h->frames.reference[i]->i_poc < i_poc )
751             {
752                 h->fref0[h->i_ref0++] = h->frames.reference[i];
753             }
754             else if( h->frames.reference[i]->i_poc > i_poc )
755             {
756                 h->fref1[h->i_ref1++] = h->frames.reference[i];
757             }
758         }
759     }
760
761     /* Order ref0 from higher to lower poc */
762     do
763     {
764         b_ok = 1;
765         for( i = 0; i < h->i_ref0 - 1; i++ )
766         {
767             if( h->fref0[i]->i_poc < h->fref0[i+1]->i_poc )
768             {
769                 XCHG( x264_frame_t*, h->fref0[i], h->fref0[i+1] );
770                 b_ok = 0;
771                 break;
772             }
773         }
774     } while( !b_ok );
775     /* Order ref1 from lower to higher poc (bubble sort) for B-frame */
776     do
777     {
778         b_ok = 1;
779         for( i = 0; i < h->i_ref1 - 1; i++ )
780         {
781             if( h->fref1[i]->i_poc > h->fref1[i+1]->i_poc )
782             {
783                 XCHG( x264_frame_t*, h->fref1[i], h->fref1[i+1] );
784                 b_ok = 0;
785                 break;
786             }
787         }
788     } while( !b_ok );
789
790     /* In the standard, a P-frame's ref list is sorted by frame_num.
791      * We use POC, but check whether explicit reordering is needed */
792     h->b_ref_reorder[0] =
793     h->b_ref_reorder[1] = 0;
794     if( i_slice_type == SLICE_TYPE_P )
795     {
796         for( i = 0; i < h->i_ref0 - 1; i++ )
797             if( h->fref0[i]->i_frame_num < h->fref0[i+1]->i_frame_num )
798             {
799                 h->b_ref_reorder[0] = 1;
800                 break;
801             }
802     }
803
804     h->i_ref1 = X264_MIN( h->i_ref1, h->frames.i_max_ref1 );
805     h->i_ref0 = X264_MIN( h->i_ref0, h->frames.i_max_ref0 );
806     h->i_ref0 = X264_MIN( h->i_ref0, 16 - h->i_ref1 );
807 }
808
809 static inline void x264_reference_update( x264_t *h )
810 {
811     int i;
812
813     /* apply deblocking filter to the current decoded picture */
814     if( !h->sh.i_disable_deblocking_filter_idc )
815     {
816         TIMER_START( i_mtime_filter );
817         x264_frame_deblocking_filter( h, h->sh.i_type );
818         TIMER_STOP( i_mtime_filter );
819     }
820     /* expand border */
821     x264_frame_expand_border( h->fdec );
822
823     /* create filtered images */
824     x264_frame_filter( h->param.cpu, h->fdec );
825
826     /* expand border of filtered images */
827     x264_frame_expand_border_filtered( h->fdec );
828
829     /* move lowres copy of the image to the ref frame */
830     for( i = 0; i < 4; i++)
831         XCHG( uint8_t*, h->fdec->lowres[i], h->fenc->lowres[i] );
832
833     /* adaptive B decision needs a pointer, since it can't use the ref lists */
834     if( h->sh.i_type != SLICE_TYPE_B )
835         h->frames.last_nonb = h->fdec;
836
837     /* move frame in the buffer */
838     h->fdec = h->frames.reference[h->frames.i_max_dpb-1];
839     for( i = h->frames.i_max_dpb-1; i > 0; i-- )
840     {
841         h->frames.reference[i] = h->frames.reference[i-1];
842     }
843     h->frames.reference[0] = h->fdec;
844 }
845
846 static inline void x264_reference_reset( x264_t *h )
847 {
848     int i;
849
850     /* reset ref pictures */
851     for( i = 1; i < h->frames.i_max_dpb; i++ )
852     {
853         h->frames.reference[i]->i_poc = -1;
854     }
855     h->frames.reference[0]->i_poc = 0;
856 }
857
858 static inline void x264_slice_init( x264_t *h, int i_nal_type, int i_slice_type, int i_global_qp )
859 {
860     /* ------------------------ Create slice header  ----------------------- */
861     if( i_nal_type == NAL_SLICE_IDR )
862     {
863         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 );
864
865         /* increment id */
866         h->i_idr_pic_id = ( h->i_idr_pic_id + 1 ) % 65536;
867     }
868     else
869     {
870         x264_slice_header_init( h, &h->sh, h->sps, h->pps, i_slice_type, -1, h->i_frame_num - 1, i_global_qp );
871
872         /* always set the real higher num of ref frame used */
873         h->sh.b_num_ref_idx_override = 1;
874         h->sh.i_num_ref_idx_l0_active = h->i_ref0 <= 0 ? 1 : h->i_ref0;
875         h->sh.i_num_ref_idx_l1_active = h->i_ref1 <= 0 ? 1 : h->i_ref1;
876     }
877
878     h->fdec->i_frame_num = h->sh.i_frame_num;
879
880     if( h->sps->i_poc_type == 0 )
881     {
882         h->sh.i_poc_lsb = h->fdec->i_poc & ( (1 << h->sps->i_log2_max_poc_lsb) - 1 );
883         h->sh.i_delta_poc_bottom = 0;   /* XXX won't work for field */
884     }
885     else if( h->sps->i_poc_type == 1 )
886     {
887         /* FIXME TODO FIXME */
888     }
889     else
890     {
891         /* Nothing to do ? */
892     }
893
894     x264_macroblock_slice_init( h );
895 }
896
897 static int x264_slice_write( x264_t *h )
898 {
899     int i_skip;
900     int mb_xy;
901     int i;
902
903     /* init stats */
904     memset( &h->stat.frame, 0, sizeof(h->stat.frame) );
905
906     /* Slice */
907     x264_nal_start( h, h->i_nal_type, h->i_nal_ref_idc );
908
909     /* Slice header */
910     x264_slice_header_write( &h->out.bs, &h->sh, h->i_nal_ref_idc );
911     if( h->param.b_cabac )
912     {
913         /* alignment needed */
914         bs_align_1( &h->out.bs );
915
916         /* init cabac */
917         x264_cabac_context_init( &h->cabac, h->sh.i_type, h->sh.i_qp, h->sh.i_cabac_init_idc );
918         x264_cabac_encode_init ( &h->cabac, &h->out.bs );
919     }
920     h->mb.i_last_qp = h->sh.i_qp;
921     h->mb.i_last_dqp = 0;
922
923     for( mb_xy = h->sh.i_first_mb, i_skip = 0; mb_xy < h->sh.i_last_mb; mb_xy++ )
924     {
925         const int i_mb_y = mb_xy / h->sps->i_mb_width;
926         const int i_mb_x = mb_xy % h->sps->i_mb_width;
927
928         int mb_spos = bs_pos(&h->out.bs);
929
930         /* load cache */
931         x264_macroblock_cache_load( h, i_mb_x, i_mb_y );
932
933         /* analyse parameters
934          * Slice I: choose I_4x4 or I_16x16 mode
935          * Slice P: choose between using P mode or intra (4x4 or 16x16)
936          * */
937         TIMER_START( i_mtime_analyse );
938         x264_macroblock_analyse( h );
939         TIMER_STOP( i_mtime_analyse );
940
941         /* encode this macrobock -> be carefull it can change the mb type to P_SKIP if needed */
942         TIMER_START( i_mtime_encode );
943         x264_macroblock_encode( h );
944         TIMER_STOP( i_mtime_encode );
945
946         TIMER_START( i_mtime_write );
947         if( h->param.b_cabac )
948         {
949             if( mb_xy > h->sh.i_first_mb )
950                 x264_cabac_encode_terminal( &h->cabac, 0 );
951
952             if( IS_SKIP( h->mb.i_type ) )
953                 x264_cabac_mb_skip( h, 1 );
954             else
955             {
956                 if( h->sh.i_type != SLICE_TYPE_I )
957                     x264_cabac_mb_skip( h, 0 );
958                 x264_macroblock_write_cabac( h, &h->cabac );
959             }
960         }
961         else
962         {
963             if( IS_SKIP( h->mb.i_type ) )
964                 i_skip++;
965             else
966             {
967                 if( h->sh.i_type != SLICE_TYPE_I )
968                 {
969                     bs_write_ue( &h->out.bs, i_skip );  /* skip run */
970                     i_skip = 0;
971                 }
972                 x264_macroblock_write_cavlc( h, &h->out.bs );
973             }
974         }
975         TIMER_STOP( i_mtime_write );
976
977 #if VISUALIZE
978         if( h->param.b_visualize )
979             x264_visualize_mb( h );
980 #endif
981
982         /* save cache */
983         x264_macroblock_cache_save( h );
984
985         /* accumulate mb stats */
986         h->stat.frame.i_mb_count[h->mb.i_type]++;
987         if( !IS_SKIP(h->mb.i_type) && !IS_INTRA(h->mb.i_type) && !IS_DIRECT(h->mb.i_type) )
988         {
989             if( h->mb.i_partition != D_8x8 )
990                 h->stat.frame.i_mb_count_size[ x264_mb_partition_pixel_table[ h->mb.i_partition ] ] += 4;
991             else
992                 for( i = 0; i < 4; i++ )
993                     h->stat.frame.i_mb_count_size[ x264_mb_partition_pixel_table[ h->mb.i_sub_partition[i] ] ] ++;
994             if( h->param.i_frame_reference > 1 )
995             {
996                 for( i = 0; i < 4; i++ )
997                 {
998                     int i_ref = h->mb.cache.ref[0][ x264_scan8[4*i] ];
999                     if( i_ref >= 0 )
1000                         h->stat.frame.i_mb_count_ref[i_ref] ++;
1001                 }
1002             }
1003         }
1004         if( h->mb.i_cbp_luma && !IS_INTRA(h->mb.i_type) )
1005         {
1006             h->stat.frame.i_mb_count_8x8dct[0] ++;
1007             h->stat.frame.i_mb_count_8x8dct[1] += h->mb.b_transform_8x8;
1008         }
1009
1010         if( h->mb.b_variable_qp )
1011             x264_ratecontrol_mb(h, bs_pos(&h->out.bs) - mb_spos);
1012     }
1013
1014     if( h->param.b_cabac )
1015     {
1016         /* end of slice */
1017         x264_cabac_encode_terminal( &h->cabac, 1 );
1018     }
1019     else if( i_skip > 0 )
1020     {
1021         bs_write_ue( &h->out.bs, i_skip );  /* last skip run */
1022     }
1023
1024     if( h->param.b_cabac )
1025     {
1026         x264_cabac_encode_flush( &h->cabac );
1027
1028     }
1029     else
1030     {
1031         /* rbsp_slice_trailing_bits */
1032         bs_rbsp_trailing( &h->out.bs );
1033     }
1034
1035     x264_nal_end( h );
1036
1037     /* Compute misc bits */
1038     h->stat.frame.i_misc_bits = bs_pos( &h->out.bs )
1039                               + NALU_OVERHEAD * 8
1040                               - h->stat.frame.i_itex_bits
1041                               - h->stat.frame.i_ptex_bits
1042                               - h->stat.frame.i_hdr_bits;
1043
1044     return 0;
1045 }
1046
1047 static inline int x264_slices_write( x264_t *h )
1048 {
1049     int i_frame_size;
1050
1051 #if VISUALIZE
1052     if( h->param.b_visualize )
1053         x264_visualize_init( h );
1054 #endif
1055
1056     if( h->param.i_threads == 1 )
1057     {
1058         x264_slice_write( h );
1059         i_frame_size = h->out.nal[h->out.i_nal-1].i_payload;
1060     }
1061     else
1062     {
1063         int i_nal = h->out.i_nal;
1064         int i_bs_size = h->out.i_bitstream / h->param.i_threads;
1065         int i;
1066         /* duplicate contexts */
1067         for( i = 0; i < h->param.i_threads; i++ )
1068         {
1069             x264_t *t = h->thread[i];
1070             if( i > 0 )
1071             {
1072                 memcpy( t, h, sizeof(x264_t) );
1073                 t->out.p_bitstream += i*i_bs_size;
1074                 bs_init( &t->out.bs, t->out.p_bitstream, i_bs_size );
1075             }
1076             t->sh.i_first_mb = (i    * h->sps->i_mb_height / h->param.i_threads) * h->sps->i_mb_width;
1077             t->sh.i_last_mb = ((i+1) * h->sps->i_mb_height / h->param.i_threads) * h->sps->i_mb_width;
1078             t->out.i_nal = i_nal + i;
1079         }
1080
1081         /* dispatch */
1082 #if HAVE_PTHREAD
1083         {
1084             pthread_t handles[X264_SLICE_MAX];
1085             void *status;
1086             for( i = 0; i < h->param.i_threads; i++ )
1087                 pthread_create( &handles[i], NULL, (void*)x264_slice_write, (void*)h->thread[i] );
1088             for( i = 0; i < h->param.i_threads; i++ )
1089                 pthread_join( handles[i], &status );
1090         }
1091 #else
1092         for( i = 0; i < h->param.i_threads; i++ )
1093             x264_slice_write( h->thread[i] );
1094 #endif
1095
1096         /* merge contexts */
1097         i_frame_size = h->out.nal[i_nal].i_payload;
1098         for( i = 1; i < h->param.i_threads; i++ )
1099         {
1100             int j;
1101             x264_t *t = h->thread[i];
1102             h->out.nal[i_nal+i] = t->out.nal[i_nal+i];
1103             i_frame_size += t->out.nal[i_nal+i].i_payload;
1104             // all entries in stat.frame are ints
1105             for( j = 0; j < sizeof(h->stat.frame) / sizeof(int); j++ )
1106                 ((int*)&h->stat.frame)[j] += ((int*)&t->stat.frame)[j];
1107         }
1108         h->out.i_nal = i_nal + h->param.i_threads;
1109     }
1110
1111 #if VISUALIZE
1112     if( h->param.b_visualize )
1113     {
1114         x264_visualize_show( h );
1115         x264_visualize_close( h );
1116     }
1117 #endif
1118
1119     return i_frame_size;
1120 }
1121
1122 /****************************************************************************
1123  * x264_encoder_encode:
1124  *  XXX: i_poc   : is the poc of the current given picture
1125  *       i_frame : is the number of the frame being coded
1126  *  ex:  type frame poc
1127  *       I      0   2*0
1128  *       P      1   2*3
1129  *       B      2   2*1
1130  *       B      3   2*2
1131  *       P      4   2*6
1132  *       B      5   2*4
1133  *       B      6   2*5
1134  ****************************************************************************/
1135 int     x264_encoder_encode( x264_t *h,
1136                              x264_nal_t **pp_nal, int *pi_nal,
1137                              x264_picture_t *pic_in,
1138                              x264_picture_t *pic_out )
1139 {
1140     x264_frame_t   *frame_psnr = h->fdec; /* just to keep the current decoded frame for psnr calculation */
1141     int     i_nal_type;
1142     int     i_nal_ref_idc;
1143     int     i_slice_type;
1144     int     i_frame_size;
1145
1146     int i;
1147
1148     int   i_global_qp;
1149
1150     char psz_message[80];
1151
1152     /* no data out */
1153     *pi_nal = 0;
1154     *pp_nal = NULL;
1155
1156
1157     /* ------------------- Setup new frame from picture -------------------- */
1158     TIMER_START( i_mtime_encode_frame );
1159     if( pic_in != NULL )
1160     {
1161         /* 1: Copy the picture to a frame and move it to a buffer */
1162         x264_frame_t *fenc = x264_frame_get( h->frames.unused );
1163
1164         x264_frame_copy_picture( h, fenc, pic_in );
1165
1166         if( h->param.i_width % 16 || h->param.i_height % 16 )
1167             x264_frame_expand_border_mod16( h, fenc );
1168
1169         fenc->i_frame = h->frames.i_input++;
1170
1171         x264_frame_put( h->frames.next, fenc );
1172
1173         if( h->frames.b_have_lowres )
1174             x264_frame_init_lowres( h->param.cpu, fenc );
1175
1176         if( h->frames.i_input <= h->frames.i_delay )
1177         {
1178             /* Nothing yet to encode */
1179             /* waiting for filling bframe buffer */
1180             pic_out->i_type = X264_TYPE_AUTO;
1181             return 0;
1182         }
1183     }
1184
1185     if( h->frames.current[0] == NULL )
1186     {
1187         int bframes = 0;
1188         /* 2: Select frame types */
1189         if( h->frames.next[0] == NULL )
1190             return 0;
1191
1192         x264_slicetype_decide( h );
1193
1194         /* 3: move some B-frames and 1 non-B to encode queue */
1195         while( IS_X264_TYPE_B( h->frames.next[bframes]->i_type ) )
1196             bframes++;
1197         x264_frame_put( h->frames.current, x264_frame_get( &h->frames.next[bframes] ) );
1198         /* FIXME: when max B-frames > 3, BREF may no longer be centered after GOP closing */
1199         if( h->param.b_bframe_pyramid && bframes > 1 )
1200         {
1201             x264_frame_t *mid = x264_frame_get( &h->frames.next[bframes/2] );
1202             mid->i_type = X264_TYPE_BREF;
1203             x264_frame_put( h->frames.current, mid );
1204             bframes--;
1205         }
1206         while( bframes-- )
1207             x264_frame_put( h->frames.current, x264_frame_get( h->frames.next ) );
1208     }
1209     TIMER_STOP( i_mtime_encode_frame );
1210
1211     /* ------------------- Get frame to be encoded ------------------------- */
1212     /* 4: get picture to encode */
1213     h->fenc = x264_frame_get( h->frames.current );
1214     if( h->fenc == NULL )
1215     {
1216         /* Nothing yet to encode (ex: waiting for I/P with B frames) */
1217         /* waiting for filling bframe buffer */
1218         pic_out->i_type = X264_TYPE_AUTO;
1219         return 0;
1220     }
1221
1222 do_encode:
1223
1224     if( h->fenc->i_type == X264_TYPE_IDR )
1225     {
1226         h->frames.i_last_idr = h->fenc->i_frame;
1227     }
1228
1229     /* ------------------- Setup frame context ----------------------------- */
1230     /* 5: Init data dependant of frame type */
1231     TIMER_START( i_mtime_encode_frame );
1232     if( h->fenc->i_type == X264_TYPE_IDR )
1233     {
1234         /* reset ref pictures */
1235         x264_reference_reset( h );
1236
1237         i_nal_type    = NAL_SLICE_IDR;
1238         i_nal_ref_idc = NAL_PRIORITY_HIGHEST;
1239         i_slice_type = SLICE_TYPE_I;
1240     }
1241     else if( h->fenc->i_type == X264_TYPE_I )
1242     {
1243         i_nal_type    = NAL_SLICE;
1244         i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
1245         i_slice_type = SLICE_TYPE_I;
1246     }
1247     else if( h->fenc->i_type == X264_TYPE_P )
1248     {
1249         i_nal_type    = NAL_SLICE;
1250         i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
1251         i_slice_type = SLICE_TYPE_P;
1252     }
1253     else if( h->fenc->i_type == X264_TYPE_BREF )
1254     {
1255         i_nal_type    = NAL_SLICE;
1256         i_nal_ref_idc = NAL_PRIORITY_HIGH; /* maybe add MMCO to forget it? -> low */
1257         i_slice_type = SLICE_TYPE_B;
1258     }
1259     else    /* B frame */
1260     {
1261         i_nal_type    = NAL_SLICE;
1262         i_nal_ref_idc = NAL_PRIORITY_DISPOSABLE;
1263         i_slice_type = SLICE_TYPE_B;
1264     }
1265
1266     h->fdec->i_poc =
1267     h->fenc->i_poc = 2 * (h->fenc->i_frame - h->frames.i_last_idr);
1268     h->fdec->i_type = h->fenc->i_type;
1269     h->fdec->i_frame = h->fenc->i_frame;
1270     h->fenc->b_kept_as_ref =
1271     h->fdec->b_kept_as_ref = i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE;
1272
1273
1274
1275     /* ------------------- Init                ----------------------------- */
1276     /* build ref list 0/1 */
1277     x264_reference_build_list( h, h->fdec->i_poc, i_slice_type );
1278
1279     /* Init the rate control */
1280     x264_ratecontrol_start( h, i_slice_type, h->fenc->i_qpplus1 );
1281     i_global_qp = x264_ratecontrol_qp( h );
1282
1283     pic_out->i_qpplus1 =
1284     h->fdec->i_qpplus1 = i_global_qp + 1;
1285
1286     if( i_slice_type == SLICE_TYPE_B )
1287         x264_macroblock_bipred_init( h );
1288
1289     if( h->fenc->b_kept_as_ref )
1290         h->i_frame_num++;
1291
1292     /* ------------------------ Create slice header  ----------------------- */
1293     x264_slice_init( h, i_nal_type, i_slice_type, i_global_qp );
1294
1295     /* ---------------------- Write the bitstream -------------------------- */
1296     /* Init bitstream context */
1297     h->out.i_nal = 0;
1298     bs_init( &h->out.bs, h->out.p_bitstream, h->out.i_bitstream );
1299
1300     if(h->param.b_aud){
1301         int pic_type;
1302
1303         if(i_slice_type == SLICE_TYPE_I)
1304             pic_type = 0;
1305         else if(i_slice_type == SLICE_TYPE_P)
1306             pic_type = 1;
1307         else if(i_slice_type == SLICE_TYPE_B)
1308             pic_type = 2;
1309         else
1310             pic_type = 7;
1311
1312         x264_nal_start(h, NAL_AUD, NAL_PRIORITY_DISPOSABLE);
1313         bs_write(&h->out.bs, 3, pic_type);
1314         bs_rbsp_trailing(&h->out.bs);
1315         x264_nal_end(h);
1316     }
1317
1318     h->i_nal_type = i_nal_type;
1319     h->i_nal_ref_idc = i_nal_ref_idc;
1320
1321     /* Write SPS and PPS */
1322     if( i_nal_type == NAL_SLICE_IDR )
1323     {
1324         if( h->fenc->i_frame == 0 )
1325         {
1326             /* identify ourself */
1327             x264_nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
1328             x264_sei_version_write( &h->out.bs );
1329             x264_nal_end( h );
1330         }
1331
1332         /* generate sequence parameters */
1333         x264_nal_start( h, NAL_SPS, NAL_PRIORITY_HIGHEST );
1334         x264_sps_write( &h->out.bs, h->sps );
1335         x264_nal_end( h );
1336
1337         /* generate picture parameters */
1338         x264_nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
1339         x264_pps_write( &h->out.bs, h->pps );
1340         x264_nal_end( h );
1341     }
1342
1343     /* Write frame */
1344     i_frame_size = x264_slices_write( h );
1345
1346     /* restore CPU state (before using float again) */
1347     x264_cpu_restore( h->param.cpu );
1348
1349     if( i_slice_type == SLICE_TYPE_P && !h->param.rc.b_stat_read 
1350         && h->param.i_scenecut_threshold >= 0 )
1351     {
1352         const int *mbs = h->stat.frame.i_mb_count;
1353         int i_mb_i = mbs[I_16x16] + mbs[I_8x8] + mbs[I_4x4];
1354         int i_mb_p = mbs[P_L0] + mbs[P_8x8];
1355         int i_mb_s = mbs[P_SKIP];
1356         int i_mb   = h->sps->i_mb_width * h->sps->i_mb_height;
1357         int64_t i_inter_cost = h->stat.frame.i_inter_cost;
1358         int64_t i_intra_cost = h->stat.frame.i_intra_cost;
1359
1360         float f_bias;
1361         int i_gop_size = h->fenc->i_frame - h->frames.i_last_idr;
1362         float f_thresh_max = h->param.i_scenecut_threshold / 100.0;
1363         /* magic numbers pulled out of thin air */
1364         float f_thresh_min = f_thresh_max * h->param.i_keyint_min
1365                              / ( h->param.i_keyint_max * 4 );
1366         if( h->param.i_keyint_min == h->param.i_keyint_max )
1367              f_thresh_min= f_thresh_max;
1368
1369         /* macroblock_analyse() doesn't further analyse skipped mbs,
1370          * so we have to guess their cost */
1371         if( i_mb_s < i_mb )
1372             i_intra_cost = i_intra_cost * i_mb / (i_mb - i_mb_s);
1373
1374         if( i_gop_size < h->param.i_keyint_min / 4 )
1375             f_bias = f_thresh_min / 4;
1376         else if( i_gop_size <= h->param.i_keyint_min )
1377             f_bias = f_thresh_min * i_gop_size / h->param.i_keyint_min;
1378         else
1379         {
1380             f_bias = f_thresh_min
1381                      + ( f_thresh_max - f_thresh_min )
1382                        * ( i_gop_size - h->param.i_keyint_min )
1383                        / ( h->param.i_keyint_max - h->param.i_keyint_min );
1384         }
1385         f_bias = X264_MIN( f_bias, 1.0 );
1386
1387         /* Bad P will be reencoded as I */
1388         if( i_mb_s < i_mb &&
1389             i_inter_cost >= (1.0 - f_bias) * i_intra_cost )
1390         {
1391             int b;
1392
1393             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",
1394                       h->fenc->i_frame,
1395                       (double)i_intra_cost, (double)i_inter_cost,
1396                       (double)i_inter_cost / i_intra_cost,
1397                       f_bias, i_gop_size,
1398                       i_mb_i, i_mb_p, i_mb_s );
1399
1400             /* Restore frame num */
1401             h->i_frame_num--;
1402
1403             for( b = 0; h->frames.current[b] && IS_X264_TYPE_B( h->frames.current[b]->i_type ); b++ );
1404             if( b > 0 )
1405             {
1406                 /* If using B-frames, force GOP to be closed.
1407                  * Even if this frame is going to be I and not IDR, forcing a
1408                  * P-frame before the scenecut will probably help compression.
1409                  * 
1410                  * We don't yet know exactly which frame is the scene cut, so
1411                  * we can't assign an I-frame. Instead, change the previous
1412                  * B-frame to P, and rearrange coding order. */
1413
1414                 if( h->param.b_bframe_adaptive || b > 1 )
1415                     h->fenc->i_type = X264_TYPE_AUTO;
1416                 x264_frame_sort_pts( h->frames.current );
1417                 x264_frame_push( h->frames.next, h->fenc );
1418                 h->fenc = h->frames.current[b-1];
1419                 h->frames.current[b-1] = NULL;
1420                 h->fenc->i_type = X264_TYPE_P;
1421                 x264_frame_sort_dts( h->frames.current );
1422             }
1423             /* Do IDR if needed */
1424             else if( i_gop_size >= h->param.i_keyint_min )
1425             {
1426                 x264_frame_t *tmp;
1427
1428                 /* Reset */
1429                 h->i_frame_num = 0;
1430
1431                 /* Reinit field of fenc */
1432                 h->fenc->i_type = X264_TYPE_IDR;
1433                 h->fenc->i_poc = 0;
1434
1435                 /* Put enqueued frames back in the pool */
1436                 while( (tmp = x264_frame_get( h->frames.current ) ) != NULL )
1437                     x264_frame_put( h->frames.next, tmp );
1438                 x264_frame_sort_pts( h->frames.next );
1439             }
1440             else
1441             {
1442                 h->fenc->i_type = X264_TYPE_I;
1443             }
1444             goto do_encode;
1445         }
1446     }
1447
1448     /* End bitstream, set output  */
1449     *pi_nal = h->out.i_nal;
1450     *pp_nal = h->out.nal;
1451
1452     /* Set output picture properties */
1453     if( i_slice_type == SLICE_TYPE_I )
1454         pic_out->i_type = i_nal_type == NAL_SLICE_IDR ? X264_TYPE_IDR : X264_TYPE_I;
1455     else if( i_slice_type == SLICE_TYPE_P )
1456         pic_out->i_type = X264_TYPE_P;
1457     else
1458         pic_out->i_type = X264_TYPE_B;
1459     pic_out->i_pts = h->fenc->i_pts;
1460
1461     pic_out->img.i_plane = h->fdec->i_plane;
1462     for(i = 0; i < 4; i++){
1463         pic_out->img.i_stride[i] = h->fdec->i_stride[i];
1464         pic_out->img.plane[i] = h->fdec->plane[i];
1465     }
1466
1467     /* ---------------------- Update encoder state ------------------------- */
1468
1469     /* handle references */
1470     if( i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE )
1471     {
1472         x264_reference_update( h );
1473     }
1474
1475     /* increase frame count */
1476     h->i_frame++;
1477
1478     /* restore CPU state (before using float again) */
1479     /* XXX: not needed? (done above) */
1480     x264_cpu_restore( h->param.cpu );
1481
1482     /* update rc */
1483     x264_ratecontrol_end( h, i_frame_size * 8 );
1484
1485     x264_frame_put( h->frames.unused, h->fenc );
1486
1487     TIMER_STOP( i_mtime_encode_frame );
1488
1489     /* ---------------------- Compute/Print statistics --------------------- */
1490     /* Slice stat */
1491     h->stat.i_slice_count[i_slice_type]++;
1492     h->stat.i_slice_size[i_slice_type] += i_frame_size + NALU_OVERHEAD;
1493     h->stat.i_slice_qp[i_slice_type] += i_global_qp;
1494
1495     for( i = 0; i < 19; i++ )
1496         h->stat.i_mb_count[h->sh.i_type][i] += h->stat.frame.i_mb_count[i];
1497     for( i = 0; i < 2; i++ )
1498         h->stat.i_mb_count_8x8dct[i] += h->stat.frame.i_mb_count_8x8dct[i];
1499     if( h->sh.i_type != SLICE_TYPE_I )
1500     {
1501         for( i = 0; i < 7; i++ )
1502             h->stat.i_mb_count_size[h->sh.i_type][i] += h->stat.frame.i_mb_count_size[i];
1503         for( i = 0; i < 16; i++ )
1504             h->stat.i_mb_count_ref[h->sh.i_type][i] += h->stat.frame.i_mb_count_ref[i];
1505     }
1506
1507     if( h->param.analyse.b_psnr )
1508     {
1509         int64_t i_sqe_y, i_sqe_u, i_sqe_v;
1510
1511         /* PSNR */
1512         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 );
1513         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);
1514         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);
1515         x264_cpu_restore( h->param.cpu );
1516
1517         h->stat.i_sqe_global[i_slice_type] += i_sqe_y + i_sqe_u + i_sqe_v;
1518         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 );
1519         h->stat.f_psnr_mean_y[i_slice_type] += x264_psnr( i_sqe_y, h->param.i_width * h->param.i_height );
1520         h->stat.f_psnr_mean_u[i_slice_type] += x264_psnr( i_sqe_u, h->param.i_width * h->param.i_height / 4 );
1521         h->stat.f_psnr_mean_v[i_slice_type] += x264_psnr( i_sqe_v, h->param.i_width * h->param.i_height / 4 );
1522
1523         snprintf( psz_message, 80, " PSNR Y:%2.2f U:%2.2f V:%2.2f",
1524                   x264_psnr( i_sqe_y, h->param.i_width * h->param.i_height ),
1525                   x264_psnr( i_sqe_u, h->param.i_width * h->param.i_height / 4),
1526                   x264_psnr( i_sqe_v, h->param.i_width * h->param.i_height / 4) );
1527         psz_message[79] = '\0';
1528     }
1529     else
1530     {
1531         psz_message[0] = '\0';
1532     }
1533     
1534     x264_log( h, X264_LOG_DEBUG,
1535                   "frame=%4d QP=%i NAL=%d Slice:%c Poc:%-3d I:%-4d P:%-4d SKIP:%-4d size=%d bytes%s\n",
1536               h->i_frame - 1,
1537               i_global_qp,
1538               i_nal_ref_idc,
1539               i_slice_type == SLICE_TYPE_I ? 'I' : (i_slice_type == SLICE_TYPE_P ? 'P' : 'B' ),
1540               frame_psnr->i_poc,
1541               h->stat.frame.i_mb_count_i,
1542               h->stat.frame.i_mb_count_p,
1543               h->stat.frame.i_mb_count_skip,
1544               i_frame_size,
1545               psz_message );
1546
1547
1548 #ifdef DEBUG_MB_TYPE
1549 {
1550     static const char mb_chars[] = { 'i', 'i', 'I', 'C', 'P', '8', 'S',
1551         'D', '<', 'X', 'B', 'X', '>', 'B', 'B', 'B', 'B', '8', 'S' };
1552     int mb_xy;
1553     for( mb_xy = 0; mb_xy < h->sps->i_mb_width * h->sps->i_mb_height; mb_xy++ )
1554     {
1555         if( h->mb.type[mb_xy] < 19 && h->mb.type[mb_xy] >= 0 )
1556             fprintf( stderr, "%c ", mb_chars[ h->mb.type[mb_xy] ] );
1557         else
1558             fprintf( stderr, "? " );
1559
1560         if( (mb_xy+1) % h->sps->i_mb_width == 0 )
1561             fprintf( stderr, "\n" );
1562     }
1563 }
1564 #endif
1565
1566 #ifdef DEBUG_DUMP_FRAME
1567     /* Dump reconstructed frame */
1568     x264_frame_dump( h, frame_psnr, "fdec.yuv" );
1569 #endif
1570     return 0;
1571 }
1572
1573 /****************************************************************************
1574  * x264_encoder_close:
1575  ****************************************************************************/
1576 void    x264_encoder_close  ( x264_t *h )
1577 {
1578 #ifdef DEBUG_BENCHMARK
1579     int64_t i_mtime_total = i_mtime_analyse + i_mtime_encode + i_mtime_write + i_mtime_filter + 1;
1580 #endif
1581     int64_t i_yuv_size = 3 * h->param.i_width * h->param.i_height / 2;
1582     int i;
1583
1584 #ifdef DEBUG_BENCHMARK
1585     x264_log( h, X264_LOG_INFO,
1586               "analyse=%d(%lldms) encode=%d(%lldms) write=%d(%lldms) filter=%d(%lldms)\n",
1587               (int)(100*i_mtime_analyse/i_mtime_total), i_mtime_analyse/1000,
1588               (int)(100*i_mtime_encode/i_mtime_total), i_mtime_encode/1000,
1589               (int)(100*i_mtime_write/i_mtime_total), i_mtime_write/1000,
1590               (int)(100*i_mtime_filter/i_mtime_total), i_mtime_filter/1000 );
1591 #endif
1592
1593     /* Slices used and PSNR */
1594     for( i=0; i<5; i++ )
1595     {
1596         static const int slice_order[] = { SLICE_TYPE_I, SLICE_TYPE_SI, SLICE_TYPE_P, SLICE_TYPE_SP, SLICE_TYPE_B };
1597         static const char *slice_name[] = { "P", "B", "I", "SP", "SI" };
1598         int i_slice = slice_order[i];
1599
1600         if( h->stat.i_slice_count[i_slice] > 0 )
1601         {
1602             const int i_count = h->stat.i_slice_count[i_slice];
1603             if( h->param.analyse.b_psnr )
1604             {
1605                 x264_log( h, X264_LOG_INFO,
1606                           "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",
1607                           slice_name[i_slice],
1608                           i_count,
1609                           (double)h->stat.i_slice_qp[i_slice] / i_count,
1610                           (double)h->stat.i_slice_size[i_slice] / i_count,
1611                           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,
1612                           h->stat.f_psnr_average[i_slice] / i_count,
1613                           x264_psnr( h->stat.i_sqe_global[i_slice], i_count * i_yuv_size ) );
1614             }
1615             else
1616             {
1617                 x264_log( h, X264_LOG_INFO,
1618                           "slice %s:%-5d Avg QP:%5.2f  size:%6.0f\n",
1619                           slice_name[i_slice],
1620                           i_count,
1621                           (double)h->stat.i_slice_qp[i_slice] / i_count,
1622                           (double)h->stat.i_slice_size[i_slice] / i_count );
1623             }
1624         }
1625     }
1626
1627     /* MB types used */
1628     if( h->stat.i_slice_count[SLICE_TYPE_I] > 0 )
1629     {
1630         const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_I];
1631         const double i_count = h->stat.i_slice_count[SLICE_TYPE_I] * h->mb.i_mb_count / 100.0;
1632         x264_log( h, X264_LOG_INFO,
1633                   "mb I  I16..4: %4.1f%% %4.1f%% %4.1f%%\n",
1634                   i_mb_count[I_16x16]/ i_count,
1635                   i_mb_count[I_8x8]  / i_count,
1636                   i_mb_count[I_4x4]  / i_count );
1637     }
1638     if( h->stat.i_slice_count[SLICE_TYPE_P] > 0 )
1639     {
1640         const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_P];
1641         const int64_t *i_mb_size = h->stat.i_mb_count_size[SLICE_TYPE_P];
1642         const double i_count = h->stat.i_slice_count[SLICE_TYPE_P] * h->mb.i_mb_count / 100.0;
1643         x264_log( h, X264_LOG_INFO,
1644                   "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",
1645                   i_mb_count[I_16x16]/ i_count,
1646                   i_mb_count[I_8x8]  / i_count,
1647                   i_mb_count[I_4x4]  / i_count,
1648                   i_mb_size[PIXEL_16x16] / (i_count*4),
1649                   (i_mb_size[PIXEL_16x8] + i_mb_size[PIXEL_8x16]) / (i_count*4),
1650                   i_mb_size[PIXEL_8x8] / (i_count*4),
1651                   (i_mb_size[PIXEL_8x4] + i_mb_size[PIXEL_4x8]) / (i_count*4),
1652                   i_mb_size[PIXEL_4x4] / (i_count*4),
1653                   i_mb_count[P_SKIP] / i_count );
1654     }
1655     if( h->stat.i_slice_count[SLICE_TYPE_B] > 0 )
1656     {
1657         const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_B];
1658         const int64_t *i_mb_size = h->stat.i_mb_count_size[SLICE_TYPE_B];
1659         const double i_count = h->stat.i_slice_count[SLICE_TYPE_B] * h->mb.i_mb_count / 100.0;
1660         x264_log( h, X264_LOG_INFO,
1661                   "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",
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                   i_mb_size[PIXEL_16x16] / (i_count*4),
1666                   (i_mb_size[PIXEL_16x8] + i_mb_size[PIXEL_8x16]) / (i_count*4),
1667                   i_mb_size[PIXEL_8x8] / (i_count*4),
1668                   i_mb_count[B_DIRECT] / i_count,
1669                   i_mb_count[B_SKIP]   / i_count );
1670     }
1671
1672     x264_ratecontrol_summary( h );
1673
1674     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 )
1675     {
1676         const int i_count = h->stat.i_slice_count[SLICE_TYPE_I] +
1677                             h->stat.i_slice_count[SLICE_TYPE_P] +
1678                             h->stat.i_slice_count[SLICE_TYPE_B];
1679         float fps = (float) h->param.i_fps_num / h->param.i_fps_den;
1680 #define SUM3(p) (p[SLICE_TYPE_I] + p[SLICE_TYPE_P] + p[SLICE_TYPE_B])
1681 #define SUM3b(p,o) (p[SLICE_TYPE_I][o] + p[SLICE_TYPE_P][o] + p[SLICE_TYPE_B][o])
1682         float f_bitrate = fps * SUM3(h->stat.i_slice_size) / i_count / 125;
1683
1684         if( h->param.analyse.b_transform_8x8 )
1685         {
1686             int64_t i_i8x8 = SUM3b( h->stat.i_mb_count, I_8x8 );
1687             int64_t i_intra = i_i8x8 + SUM3b( h->stat.i_mb_count, I_4x4 )
1688                                      + SUM3b( h->stat.i_mb_count, I_16x16 );
1689             x264_log( h, X264_LOG_INFO, "8x8 transform  intra:%.1f%%  inter:%.1f%%\n",
1690                       100. * i_i8x8 / i_intra,
1691                       100. * h->stat.i_mb_count_8x8dct[1] / h->stat.i_mb_count_8x8dct[0] );
1692         }
1693
1694         if( h->param.i_frame_reference > 1 )
1695         {
1696             int i_slice;
1697             for( i_slice = 0; i_slice < 2; i_slice++ )
1698             {
1699                 char buf[200];
1700                 char *p = buf;
1701                 int64_t i_den = 0;
1702                 int i_max = 0;
1703                 for( i = 0; i < h->param.i_frame_reference; i++ )
1704                     if( h->stat.i_mb_count_ref[i_slice][i] )
1705                     {
1706                         i_den += h->stat.i_mb_count_ref[i_slice][i];
1707                         i_max = i;
1708                     }
1709                 if( i_max == 0 )
1710                     continue;
1711                 for( i = 0; i <= i_max; i++ )
1712                     p += sprintf( p, " %4.1f%%", 100. * h->stat.i_mb_count_ref[i_slice][i] / i_den );
1713                 x264_log( h, X264_LOG_INFO, "ref %c %s\n", i_slice==SLICE_TYPE_P ? 'P' : 'B', buf );
1714             }
1715         }
1716
1717         if( h->param.analyse.b_psnr )
1718             x264_log( h, X264_LOG_INFO,
1719                       "PSNR Mean Y:%6.3f U:%6.3f V:%6.3f Avg:%6.3f Global:%6.3f kb/s:%.2f\n",
1720                       SUM3( h->stat.f_psnr_mean_y ) / i_count,
1721                       SUM3( h->stat.f_psnr_mean_u ) / i_count,
1722                       SUM3( h->stat.f_psnr_mean_v ) / i_count,
1723                       SUM3( h->stat.f_psnr_average ) / i_count,
1724                       x264_psnr( SUM3( h->stat.i_sqe_global ), i_count * i_yuv_size ),
1725                       f_bitrate );
1726         else
1727             x264_log( h, X264_LOG_INFO, "kb/s:%.1f\n", f_bitrate );
1728     }
1729
1730     /* frames */
1731     for( i = 0; i < X264_BFRAME_MAX + 3; i++ )
1732     {
1733         if( h->frames.current[i] ) x264_frame_delete( h->frames.current[i] );
1734         if( h->frames.next[i] )    x264_frame_delete( h->frames.next[i] );
1735         if( h->frames.unused[i] )  x264_frame_delete( h->frames.unused[i] );
1736     }
1737     /* ref frames */
1738     for( i = 0; i < h->frames.i_max_dpb; i++ )
1739     {
1740         x264_frame_delete( h->frames.reference[i] );
1741     }
1742
1743     /* rc */
1744     x264_ratecontrol_delete( h );
1745
1746     /* param */
1747     if( h->param.rc.psz_stat_out )
1748         free( h->param.rc.psz_stat_out );
1749     if( h->param.rc.psz_stat_in )
1750         free( h->param.rc.psz_stat_in );
1751     if( h->param.rc.psz_rc_eq )
1752         free( h->param.rc.psz_rc_eq );
1753
1754     x264_macroblock_cache_end( h );
1755     x264_free( h->out.p_bitstream );
1756     for( i = 1; i < h->param.i_threads; i++ )
1757         x264_free( h->thread[i] );
1758     x264_free( h );
1759 }
1760