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