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