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