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