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