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