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