]> git.sesse.net Git - x264/blob - encoder/encoder.c
encoder/encoder.c: gcc < 3 compile fix
[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 float 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 pr 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     /* move frame in the buffer */
670     h->fdec = h->frames.reference[h->param.i_frame_reference+1];
671     for( i = h->param.i_frame_reference+1; i > 0; i-- )
672     {
673         h->frames.reference[i] = h->frames.reference[i-1];
674     }
675     h->frames.reference[0] = h->fdec;
676 }
677
678 static inline void x264_reference_reset( x264_t *h )
679 {
680     int i;
681
682     /* reset ref pictures */
683     for( i = 1; i < h->param.i_frame_reference+2; i++ )
684     {
685         h->frames.reference[i]->i_poc = -1;
686     }
687     h->frames.reference[0]->i_poc = 0;
688 }
689
690 static inline void x264_slice_init( x264_t *h, int i_nal_type, int i_slice_type, int i_global_qp )
691 {
692     /* ------------------------ Create slice header  ----------------------- */
693     if( i_nal_type == NAL_SLICE_IDR )
694     {
695         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 );
696
697         /* increment id */
698         h->i_idr_pic_id = ( h->i_idr_pic_id + 1 ) % 65536;
699     }
700     else
701     {
702         x264_slice_header_init( &h->sh, &h->param, h->sps, h->pps, i_slice_type, -1, h->i_frame_num - 1 );
703
704         /* always set the real higher num of ref frame used */
705         h->sh.b_num_ref_idx_override = 1;
706         h->sh.i_num_ref_idx_l0_active = h->i_ref0 <= 0 ? 1 : h->i_ref0;
707         h->sh.i_num_ref_idx_l1_active = h->i_ref1 <= 0 ? 1 : h->i_ref1;
708     }
709
710     if( h->sps->i_poc_type == 0 )
711     {
712         h->sh.i_poc_lsb = h->fdec->i_poc & ( (1 << h->sps->i_log2_max_poc_lsb) - 1 );
713         h->sh.i_delta_poc_bottom = 0;   /* XXX won't work for field */
714     }
715     else if( h->sps->i_poc_type == 1 )
716     {
717         /* FIXME TODO FIXME */
718     }
719     else
720     {
721         /* Nothing to do ? */
722     }
723
724     /* global qp */
725     h->sh.i_qp_delta = i_global_qp - h->pps->i_pic_init_qp;
726
727     /* get adapative cabac model if needed */
728     if( h->param.b_cabac )
729     {
730         if( h->param.i_cabac_init_idc == -1 )
731         {
732             h->sh.i_cabac_init_idc = x264_cabac_model_get( &h->cabac, i_slice_type );
733         }
734     }
735
736     x264_macroblock_slice_init( h );
737 }
738
739 static inline void x264_slice_write( x264_t *h, int i_nal_type, int i_nal_ref_idc )
740 {
741     int i_skip;
742     int mb_xy;
743     int i;
744
745     /* Init stats */
746     h->stat.frame.i_hdr_bits  =
747     h->stat.frame.i_itex_bits =
748     h->stat.frame.i_ptex_bits =
749     h->stat.frame.i_misc_bits =
750     h->stat.frame.i_intra_cost =
751     h->stat.frame.i_inter_cost = 0;
752     for( i = 0; i < 18; i++ )
753         h->stat.frame.i_mb_count[i] = 0;
754
755     /* Slice */
756     x264_nal_start( h, i_nal_type, i_nal_ref_idc );
757
758     /* Slice header */
759     x264_slice_header_write( &h->out.bs, &h->sh, i_nal_ref_idc );
760     if( h->param.b_cabac )
761     {
762         /* alignment needed */
763         bs_align_1( &h->out.bs );
764
765         /* init cabac */
766         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 );
767         x264_cabac_encode_init ( &h->cabac, &h->out.bs );
768     }
769     h->mb.i_last_qp = h->pps->i_pic_init_qp + h->sh.i_qp_delta;
770     h->mb.i_last_dqp = 0;
771
772     for( mb_xy = 0, i_skip = 0; mb_xy < h->sps->i_mb_width * h->sps->i_mb_height; mb_xy++ )
773     {
774         const int i_mb_y = mb_xy / h->sps->i_mb_width;
775         const int i_mb_x = mb_xy % h->sps->i_mb_width;
776
777         int mb_spos = bs_pos(&h->out.bs);
778
779         /* load cache */
780         x264_macroblock_cache_load( h, i_mb_x, i_mb_y );
781
782         /* analyse parameters
783          * Slice I: choose I_4x4 or I_16x16 mode
784          * Slice P: choose between using P mode or intra (4x4 or 16x16)
785          * */
786         TIMER_START( i_mtime_analyse );
787         x264_macroblock_analyse( h );
788         TIMER_STOP( i_mtime_analyse );
789
790         /* encode this macrobock -> be carefull it can change the mb type to P_SKIP if needed */
791         TIMER_START( i_mtime_encode );
792         x264_macroblock_encode( h );
793         TIMER_STOP( i_mtime_encode );
794
795         TIMER_START( i_mtime_write );
796         if( IS_SKIP( h->mb.i_type ) )
797         {
798             if( h->param.b_cabac )
799             {
800                 if( mb_xy > 0 )
801                 {
802                     /* not end_of_slice_flag */
803                     x264_cabac_encode_terminal( &h->cabac, 0 );
804                 }
805
806                 x264_cabac_mb_skip( h, 1 );
807             }
808             else
809             {
810                 i_skip++;
811             }
812         }
813         else
814         {
815             if( h->param.b_cabac )
816             {
817                 if( mb_xy > 0 )
818                 {
819                     /* not end_of_slice_flag */
820                     x264_cabac_encode_terminal( &h->cabac, 0 );
821                 }
822                 if( h->sh.i_type != SLICE_TYPE_I )
823                 {
824                     x264_cabac_mb_skip( h, 0 );
825                 }
826                 x264_macroblock_write_cabac( h, &h->out.bs );
827             }
828             else
829             {
830                 if( h->sh.i_type != SLICE_TYPE_I )
831                 {
832                     bs_write_ue( &h->out.bs, i_skip );  /* skip run */
833                     i_skip = 0;
834                 }
835                 x264_macroblock_write_cavlc( h, &h->out.bs );
836             }
837         }
838         TIMER_STOP( i_mtime_write );
839
840         /* save cache */
841         x264_macroblock_cache_save( h );
842
843         h->stat.frame.i_mb_count[h->mb.i_type]++;
844
845         x264_ratecontrol_mb(h, bs_pos(&h->out.bs) - mb_spos);
846     }
847
848     if( h->param.b_cabac )
849     {
850         /* end of slice */
851         x264_cabac_encode_terminal( &h->cabac, 1 );
852     }
853     else if( i_skip > 0 )
854     {
855         bs_write_ue( &h->out.bs, i_skip );  /* last skip run */
856     }
857
858     if( h->param.b_cabac )
859     {
860         int i_cabac_word;
861         x264_cabac_encode_flush( &h->cabac );
862         /* TODO cabac stuffing things (p209) */
863         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;
864
865         while( i_cabac_word > 0 )
866         {
867             bs_write( &h->out.bs, 16, 0x0000 );
868             i_cabac_word--;
869         }
870     }
871     else
872     {
873         /* rbsp_slice_trailing_bits */
874         bs_rbsp_trailing( &h->out.bs );
875     }
876
877     x264_nal_end( h );
878
879     /* Compute misc bits */
880     h->stat.frame.i_misc_bits = bs_pos( &h->out.bs )
881                               - h->stat.frame.i_itex_bits
882                               - h->stat.frame.i_ptex_bits
883                               - h->stat.frame.i_hdr_bits;
884 }
885
886 /****************************************************************************
887  * x264_encoder_encode:
888  *  XXX: i_poc   : is the poc of the current given picture
889  *       i_frame : is the number of the frame being coded
890  *  ex:  type frame poc
891  *       I      0   2*0
892  *       P      1   2*3
893  *       B      2   2*1
894  *       B      3   2*2
895  *       P      4   2*6
896  *       B      5   2*4
897  *       B      6   2*5
898  ****************************************************************************/
899 int     x264_encoder_encode( x264_t *h,
900                              x264_nal_t **pp_nal, int *pi_nal,
901                              x264_picture_t *pic )
902 {
903     x264_frame_t   *frame_psnr = h->fdec; /* just to keep the current decoded frame for psnr calculation */
904     int     i_nal_type;
905     int     i_nal_ref_idc;
906     int     i_slice_type;
907
908     int i;
909
910     int   i_global_qp;
911
912     char psz_message[80];
913
914     /* no data out */
915     *pi_nal = 0;
916     *pp_nal = NULL;
917
918
919     /* ------------------- Setup new frame from picture -------------------- */
920     TIMER_START( i_mtime_encode_frame );
921     if( pic != NULL )
922     {
923         /* 1: Copy the picture to a frame and move it to a buffer */
924         x264_frame_t *fenc = x264_frame_get( h->frames.unused );
925
926         x264_frame_copy_picture( h, fenc, pic );
927
928         fenc->i_frame = h->frames.i_input++;
929
930         x264_frame_put( h->frames.next, fenc );
931
932         if( h->frames.i_input <= h->param.i_bframe )
933         {
934             /* Nothing yet to encode */
935             /* waiting for filling bframe buffer */
936             pic->i_type = X264_TYPE_AUTO;
937             return 0;
938         }
939     }
940
941     if( h->frames.current[0] == NULL )
942     {
943         /* 2: Select frame types */
944         x264_frame_t *frm;
945         int bframes;
946
947         if( h->frames.next[0] == NULL )
948             return 0;
949
950         if( h->param.rc.b_stat_read )
951         {
952             /* Use the frame types from the first pass */
953             for( i = 0; h->frames.next[i] != NULL; i++ )
954                 h->frames.next[i]->i_type =
955                     x264_ratecontrol_slice_type( h, h->frames.next[i]->i_frame );
956         }
957
958         for( bframes = 0;; bframes++ )
959         {
960             frm = h->frames.next[bframes];
961
962             /* Limit GOP size */
963             if( frm->i_frame - h->frames.i_last_idr >= h->param.i_keyint_max )
964             {
965                 if( frm->i_type == X264_TYPE_AUTO )
966                     frm->i_type = X264_TYPE_IDR;
967                 if( frm->i_type != X264_TYPE_IDR )
968                     x264_log( h, X264_LOG_ERROR, "specified frame type (%d) is not compatible with keyframe interval\n", frm->i_type );
969             }
970             if( frm->i_type == X264_TYPE_IDR )
971             {
972                 h->i_poc = 0;
973                 h->i_frame_num = 0;
974
975                 /* Close GOP */
976                 if( bframes > 0 )
977                 {
978                     bframes--;
979                     h->frames.next[bframes]->i_type = X264_TYPE_P;
980                 }
981             }
982
983             if( bframes == h->param.i_bframe
984                 || h->frames.next[bframes+1] == NULL )
985             {
986                 if( frm->i_type == X264_TYPE_B )
987                     x264_log( h, X264_LOG_ERROR, "specified frame type is not compatible with max B-frames\n" );
988                 if(    frm->i_type == X264_TYPE_AUTO
989                     || frm->i_type == X264_TYPE_B )
990                     frm->i_type = X264_TYPE_P;
991             }
992
993             frm->i_poc = h->i_poc;
994             h->i_poc += 2;
995
996             if( frm->i_type != X264_TYPE_AUTO && frm->i_type != X264_TYPE_B )
997                 break;
998
999             frm->i_type = X264_TYPE_B;
1000         }
1001
1002         /* 3: move some B-frames and 1 non-B to encode queue */
1003         x264_frame_put( h->frames.current, h->frames.next[bframes] );
1004         while( bframes-- )
1005             x264_frame_put( h->frames.current, x264_frame_get( h->frames.next ) );
1006         x264_frame_get( h->frames.next );
1007     }
1008     TIMER_STOP( i_mtime_encode_frame );
1009
1010     /* ------------------- Get frame to be encoded ------------------------- */
1011     /* 4: get picture to encode */
1012     h->fenc = x264_frame_get( h->frames.current );
1013     if( h->fenc == NULL )
1014     {
1015         /* Nothing yet to encode (ex: waiting for I/P with B frames) */
1016         /* waiting for filling bframe buffer */
1017         pic->i_type = X264_TYPE_AUTO;
1018         return 0;
1019     }
1020
1021 do_encode:
1022
1023     if( h->fenc->i_type == X264_TYPE_IDR )
1024     {
1025         h->frames.i_last_idr = h->fenc->i_frame;
1026     }
1027
1028     /* ------------------- Setup frame context ----------------------------- */
1029     /* 5: Init data dependant of frame type */
1030     TIMER_START( i_mtime_encode_frame );
1031     if( h->fenc->i_type == X264_TYPE_IDR )
1032     {
1033         /* reset ref pictures */
1034         x264_reference_reset( h );
1035
1036         i_nal_type    = NAL_SLICE_IDR;
1037         i_nal_ref_idc = NAL_PRIORITY_HIGHEST;
1038         i_slice_type = SLICE_TYPE_I;
1039     }
1040     else if( h->fenc->i_type == X264_TYPE_I )
1041     {
1042         i_nal_type    = NAL_SLICE;
1043         i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
1044         i_slice_type = SLICE_TYPE_I;
1045     }
1046     else if( h->fenc->i_type == X264_TYPE_P )
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_P;
1051     }
1052     else    /* B frame */
1053     {
1054         i_nal_type    = NAL_SLICE;
1055         i_nal_ref_idc = NAL_PRIORITY_DISPOSABLE;
1056         i_slice_type = SLICE_TYPE_B;
1057     }
1058
1059     pic->i_type     =
1060     h->fdec->i_type = h->fenc->i_type;
1061     h->fdec->i_poc  = h->fenc->i_poc;
1062     h->fdec->i_frame = h->fenc->i_frame;
1063
1064
1065
1066     /* ------------------- Init                ----------------------------- */
1067     /* Init the rate control */
1068     x264_ratecontrol_start( h, i_slice_type );
1069     i_global_qp = x264_ratecontrol_qp( h );
1070     if( h->fenc->i_qpplus1 > 0 )
1071     {
1072         i_global_qp = x264_clip3( h->fenc->i_qpplus1 - 1, 0, 51 );
1073     }
1074
1075     /* build ref list 0/1 */
1076     x264_reference_build_list( h, h->fdec->i_poc );
1077
1078     /* increase frame num but only once for B frame */
1079     if( i_slice_type != SLICE_TYPE_B || h->sh.i_type != SLICE_TYPE_B )
1080     {
1081         h->i_frame_num++;
1082     }
1083
1084     /* ------------------------ Create slice header  ----------------------- */
1085     x264_slice_init( h, i_nal_type, i_slice_type, i_global_qp );
1086
1087     /* ---------------------- Write the bitstream -------------------------- */
1088     /* Init bitstream context */
1089     h->out.i_nal = 0;
1090     bs_init( &h->out.bs, h->out.p_bitstream, h->out.i_bitstream );
1091
1092     /* Write SPS and PPS */
1093     if( i_nal_type == NAL_SLICE_IDR )
1094     {
1095         /* generate sequence parameters */
1096         x264_nal_start( h, NAL_SPS, NAL_PRIORITY_HIGHEST );
1097         x264_sps_write( &h->out.bs, h->sps );
1098         x264_nal_end( h );
1099
1100         /* generate picture parameters */
1101         x264_nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
1102         x264_pps_write( &h->out.bs, h->pps );
1103         x264_nal_end( h );
1104     }
1105
1106     /* Write the slice */
1107     x264_slice_write( h, i_nal_type, i_nal_ref_idc );
1108
1109     /* restore CPU state (before using float again) */
1110     x264_cpu_restore( h->param.cpu );
1111
1112     /* XXX: this scene cut won't work with B frame (it may never create IDR -> bad) */
1113     if( i_slice_type == SLICE_TYPE_P && !h->param.rc.b_stat_read 
1114         && h->param.i_scenecut_threshold >= 0 )
1115     {
1116         int i_mb_i = h->stat.frame.i_mb_count[I_4x4] + h->stat.frame.i_mb_count[I_16x16];
1117         int i_mb_p = h->stat.frame.i_mb_count[P_L0] + h->stat.frame.i_mb_count[P_8x8];
1118         int i_mb_s = h->stat.frame.i_mb_count[P_SKIP];
1119         int i_mb   = h->sps->i_mb_width * h->sps->i_mb_height;
1120         int64_t i_inter_cost = h->stat.frame.i_inter_cost;
1121         int64_t i_intra_cost = h->stat.frame.i_intra_cost;
1122
1123         float f_bias;
1124         int i_gop_size = h->fenc->i_frame - h->frames.i_last_idr;
1125         float f_thresh_max = h->param.i_scenecut_threshold / 100.0;
1126         /* ratio of 10 pulled out of thin air */
1127         float f_thresh_min = f_thresh_max * h->param.i_keyint_min
1128                              / ( h->param.i_keyint_max * 4 );
1129         if( h->param.i_keyint_min == h->param.i_keyint_max )
1130              f_thresh_min= f_thresh_max;
1131
1132         /* macroblock_analyse() doesn't further analyse skipped mbs,
1133          * so we have to guess their cost */
1134         if( i_mb_s < i_mb )
1135             i_intra_cost = i_intra_cost * i_mb / (i_mb - i_mb_s);
1136
1137         if( i_gop_size < h->param.i_keyint_min / 4 )
1138             f_bias = f_thresh_min / 4;
1139         else if( i_gop_size <= h->param.i_keyint_min )
1140             f_bias = f_thresh_min * i_gop_size / h->param.i_keyint_min;
1141         else
1142         {
1143             f_bias = f_thresh_min
1144                      + ( f_thresh_max - f_thresh_min )
1145                        * ( i_gop_size - h->param.i_keyint_min )
1146                        / ( h->param.i_keyint_max - h->param.i_keyint_min );
1147         }
1148         f_bias = X264_MIN( f_bias, 1.0 );
1149
1150         /* Bad P will be reencoded as I */
1151         if( i_mb_s < i_mb &&
1152             i_inter_cost >= (1.0 - f_bias) * i_intra_cost )
1153             /* i_mb_i >= (1.0 - f_bias) * i_mb ) */
1154             /*
1155             h->out.nal[h->out.i_nal-1].i_payload > h->i_last_intra_size +
1156             h->i_last_intra_size * (3+h->i_last_intra_qp - i_global_qp) / 16 &&
1157             i_mb_count[I_4x4] + i_mb_count[I_16x16] > i_mb_count[P_SKIP] + i_mb_count[P_L0]/2 &&
1158             h->out.nal[h->out.i_nal-1].i_payload > 2 * h->i_last_inter_size &&
1159             h->frames.i_last_i > 4)*/
1160         {
1161
1162             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",
1163                       h->fenc->i_frame,
1164                       h->out.nal[h->out.i_nal-1].i_payload,
1165                       (double)i_intra_cost, (double)i_inter_cost,
1166                       (double)i_inter_cost / i_intra_cost,
1167                       f_bias, i_gop_size,
1168                       i_mb_i, i_mb_p, i_mb_s );
1169
1170             /* Restore frame num */
1171             h->i_frame_num--;
1172
1173             for( i = 0; h->frames.current[i] && h->frames.current[i]->i_type == X264_TYPE_B; i++ );
1174             if( i > 0 )
1175             {
1176                 /* If using B-frames, force GOP to be closed.
1177                  * Even if this frame is going to be I and not IDR, forcing a
1178                  * P-frame before the scenecut will probably help compression.
1179                  * 
1180                  * We don't yet know exactly which frame is the scene cut, so
1181                  * we can't assign an I-frame. Instead, change the previous
1182                  * B-frame to P, and rearrange coding order. */
1183
1184                 x264_frame_t *tmp = h->frames.current[i-1];
1185                 h->frames.current[i-1] = h->fenc;
1186                 h->fenc = tmp;
1187                 h->fenc->i_type = X264_TYPE_P;
1188             }
1189             /* Do IDR if needed */
1190             else if( i_gop_size >= h->param.i_keyint_min )
1191             {
1192                 x264_frame_t *tmp;
1193
1194                 /* Reset */
1195                 h->i_poc       = 0;
1196                 h->i_frame_num = 0;
1197
1198                 /* Reinit field of fenc */
1199                 h->fenc->i_type = X264_TYPE_IDR;
1200                 h->fenc->i_poc = 0;
1201
1202                 /* Next Poc */
1203                 h->i_poc += 2;
1204
1205                 /* Put enqueued frames back in the pool */
1206                 while( (tmp = x264_frame_get( h->frames.current ) ) != NULL )
1207                     x264_frame_put( h->frames.next, tmp );
1208                 x264_frame_sort( h->frames.next );
1209             }
1210             else
1211             {
1212                 h->fenc->i_type = X264_TYPE_I;
1213             }
1214             goto do_encode;
1215         }
1216         h->i_last_inter_size = h->out.nal[h->out.i_nal-1].i_payload;
1217     }
1218     else
1219     {
1220         h->i_last_intra_size = h->out.nal[h->out.i_nal-1].i_payload;
1221         h->i_last_intra_qp = i_global_qp;
1222     }
1223
1224     /* End bitstream, set output  */
1225     *pi_nal = h->out.i_nal;
1226     *pp_nal = &h->out.nal[0];
1227
1228     /* Set output picture properties */
1229     if( i_slice_type == SLICE_TYPE_I )
1230         pic->i_type = i_nal_type == NAL_SLICE_IDR ? X264_TYPE_IDR : X264_TYPE_I;
1231     else if( i_slice_type == SLICE_TYPE_P )
1232         pic->i_type = X264_TYPE_P;
1233     else
1234         pic->i_type = X264_TYPE_B;
1235     pic->i_pts = h->fenc->i_pts;
1236
1237     /* ---------------------- Update encoder state ------------------------- */
1238     /* update cabac */
1239     if( h->param.b_cabac )
1240     {
1241         x264_cabac_model_update( &h->cabac, i_slice_type, h->sh.pps->i_pic_init_qp + h->sh.i_qp_delta );
1242     }
1243
1244     /* handle references */
1245     if( i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE )
1246     {
1247         x264_reference_update( h );
1248     }
1249
1250     /* increase frame count */
1251     h->i_frame++;
1252
1253     /* restore CPU state (before using float again) */
1254     /* XXX: not needed? (done above) */
1255     x264_cpu_restore( h->param.cpu );
1256
1257     /* update rc */
1258     x264_ratecontrol_end( h, h->out.nal[h->out.i_nal-1].i_payload * 8 );
1259
1260     x264_frame_put( h->frames.unused, h->fenc );
1261
1262     TIMER_STOP( i_mtime_encode_frame );
1263
1264     /* ---------------------- Compute/Print statistics --------------------- */
1265     /* Slice stat */
1266     h->stat.i_slice_count[i_slice_type]++;
1267     h->stat.i_slice_size[i_slice_type] += bs_pos( &h->out.bs) / 8;
1268     h->stat.i_slice_qp[i_slice_type] += i_global_qp;
1269
1270     for( i = 0; i < 18; i++ )
1271     {
1272         h->stat.i_mb_count[h->sh.i_type][i] += h->stat.frame.i_mb_count[i];
1273     }
1274
1275     if( h->param.analyse.b_psnr )
1276     {
1277         int64_t i_sqe_y, i_sqe_u, i_sqe_v;
1278
1279         /* PSNR */
1280         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 );
1281         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);
1282         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);
1283
1284         h->stat.i_sqe_global[i_slice_type] += i_sqe_y + i_sqe_u + i_sqe_v;
1285         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 );
1286         h->stat.f_psnr_mean_y[i_slice_type] += x264_psnr( i_sqe_y, h->param.i_width * h->param.i_height );
1287         h->stat.f_psnr_mean_u[i_slice_type] += x264_psnr( i_sqe_u, h->param.i_width * h->param.i_height / 4 );
1288         h->stat.f_psnr_mean_v[i_slice_type] += x264_psnr( i_sqe_v, h->param.i_width * h->param.i_height / 4 );
1289
1290         snprintf( psz_message, 80, " PSNR Y:%2.2f U:%2.2f V:%2.2f",
1291                   x264_psnr( i_sqe_y, h->param.i_width * h->param.i_height ),
1292                   x264_psnr( i_sqe_u, h->param.i_width * h->param.i_height / 4),
1293                   x264_psnr( i_sqe_v, h->param.i_width * h->param.i_height / 4) );
1294         psz_message[79] = '\0';
1295     }
1296     else
1297     {
1298         psz_message[0] = '\0';
1299     }
1300     
1301     x264_log( h, X264_LOG_DEBUG,
1302                   "frame=%4d QP=%i NAL=%d Slice:%c Poc:%-3d I4x4:%-4d I16x16:%-4d P:%-4d SKIP:%-4d size=%d bytes%s\n",
1303               h->i_frame - 1,
1304               i_global_qp,
1305               i_nal_ref_idc,
1306               i_slice_type == SLICE_TYPE_I ? 'I' : (i_slice_type == SLICE_TYPE_P ? 'P' : 'B' ),
1307               frame_psnr->i_poc,
1308               h->stat.frame.i_mb_count[I_4x4],
1309               h->stat.frame.i_mb_count[I_16x16],
1310               h->stat.frame.i_mb_count_p,
1311               h->stat.frame.i_mb_count_skip,
1312               h->out.nal[h->out.i_nal-1].i_payload,
1313               psz_message );
1314
1315
1316 #ifdef DEBUG_MB_TYPE
1317 {
1318     static const char mb_chars[] = { 'i', 'I', 'C', 'P', '8', 'S',
1319         'D', '<', 'X', 'B', 'X', '>', 'B', 'B', 'B', 'B', '8', 'S' };
1320     int mb_xy;
1321     for( mb_xy = 0; mb_xy < h->sps->i_mb_width * h->sps->i_mb_height; mb_xy++ )
1322     {
1323         if( h->mb.type[mb_xy] < 18 && h->mb.type[mb_xy] >= 0 )
1324             fprintf( stderr, "%c ", mb_chars[ h->mb.type[mb_xy] ] );
1325         else
1326             fprintf( stderr, "? " );
1327
1328         if( (mb_xy+1) % h->sps->i_mb_width == 0 )
1329             fprintf( stderr, "\n" );
1330     }
1331 }
1332 #endif
1333
1334 #ifdef DEBUG_DUMP_FRAME
1335     /* Dump reconstructed frame */
1336     x264_frame_dump( h, frame_psnr, "fdec.yuv" );
1337 #endif
1338 #if 0
1339     if( h->i_ref0 > 0 )
1340     {
1341         x264_frame_dump( h, h->fref0[0], "ref0.yuv" );
1342     }
1343     if( h->i_ref1 > 0 )
1344     {
1345         x264_frame_dump( h, h->fref1[0], "ref1.yuv" );
1346     }
1347 #endif
1348     return 0;
1349 }
1350
1351 /****************************************************************************
1352  * x264_encoder_close:
1353  ****************************************************************************/
1354 void    x264_encoder_close  ( x264_t *h )
1355 {
1356 #ifdef DEBUG_BENCHMARK
1357     int64_t i_mtime_total = i_mtime_analyse + i_mtime_encode + i_mtime_write + i_mtime_filter + 1;
1358 #endif
1359     int64_t i_yuv_size = 3 * h->param.i_width * h->param.i_height / 2;
1360     int i;
1361
1362 #ifdef DEBUG_BENCHMARK
1363     x264_log( h, X264_LOG_INFO,
1364               "analyse=%d(%lldms) encode=%d(%lldms) write=%d(%lldms) filter=%d(%lldms)\n",
1365               (int)(100*i_mtime_analyse/i_mtime_total), i_mtime_analyse/1000,
1366               (int)(100*i_mtime_encode/i_mtime_total), i_mtime_encode/1000,
1367               (int)(100*i_mtime_write/i_mtime_total), i_mtime_write/1000,
1368               (int)(100*i_mtime_filter/i_mtime_total), i_mtime_filter/1000 );
1369 #endif
1370
1371     /* Slices used and PSNR */
1372     for( i=0; i<5; i++ )
1373     {
1374         static const int slice_order[] = { SLICE_TYPE_I, SLICE_TYPE_SI, SLICE_TYPE_P, SLICE_TYPE_SP, SLICE_TYPE_B };
1375         static const char *slice_name[] = { "P", "B", "I", "SP", "SI" };
1376         int i_slice = slice_order[i];
1377
1378         if( h->stat.i_slice_count[i_slice] > 0 )
1379         {
1380             const int i_count = h->stat.i_slice_count[i_slice];
1381             if( h->param.analyse.b_psnr )
1382             {
1383                 x264_log( h, X264_LOG_INFO,
1384                           "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",
1385                           slice_name[i_slice],
1386                           i_count,
1387                           (double)h->stat.i_slice_qp[i_slice] / i_count,
1388                           (double)h->stat.i_slice_size[i_slice] / i_count,
1389                           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,
1390                           h->stat.f_psnr_average[i_slice] / i_count,
1391                           x264_psnr( h->stat.i_sqe_global[i_slice], i_count * i_yuv_size ),
1392                           x264_mse( h->stat.i_sqe_global[i_slice], i_count * i_yuv_size ) * h->stat.i_slice_size[i_slice] / i_count );
1393             }
1394             else
1395             {
1396                 x264_log( h, X264_LOG_INFO,
1397                           "slice %s:%-4d Avg QP:%5.2f Avg size:%6.0f\n",
1398                           slice_name[i_slice],
1399                           i_count,
1400                           (double)h->stat.i_slice_qp[i_slice] / i_count,
1401                           (double)h->stat.i_slice_size[i_slice] / i_count );
1402             }
1403         }
1404     }
1405
1406     /* MB types used */
1407     if( h->stat.i_slice_count[SLICE_TYPE_I] > 0 )
1408     {
1409         const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_I];
1410         const double i_count = h->stat.i_slice_count[SLICE_TYPE_I] * h->mb.i_mb_count / 100.0;
1411         x264_log( h, X264_LOG_INFO,
1412                   "slice I   Avg I4x4:%.1f%%  I16x16:%.1f%%\n",
1413                   i_mb_count[I_4x4]  / i_count,
1414                   i_mb_count[I_16x16]/ i_count );
1415     }
1416     if( h->stat.i_slice_count[SLICE_TYPE_P] > 0 )
1417     {
1418         const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_P];
1419         const double i_count = h->stat.i_slice_count[SLICE_TYPE_P] * h->mb.i_mb_count / 100.0;
1420         x264_log( h, X264_LOG_INFO,
1421                   "slice P   Avg I4x4:%.1f%%  I16x16:%.1f%%  P:%.1f%%  P8x8:%.1f%%  PSKIP:%.1f%%\n",
1422                   i_mb_count[I_4x4]  / i_count,
1423                   i_mb_count[I_16x16]/ i_count,
1424                   i_mb_count[P_L0]   / i_count,
1425                   i_mb_count[P_8x8]  / i_count,
1426                   i_mb_count[P_SKIP] / i_count );
1427     }
1428     if( h->stat.i_slice_count[SLICE_TYPE_B] > 0 )
1429     {
1430         const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_B];
1431         const double i_count = h->stat.i_slice_count[SLICE_TYPE_B] * h->mb.i_mb_count / 100.0;
1432         x264_log( h, X264_LOG_INFO,
1433                   "slice B   Avg I4x4:%.1f%%  I16x16:%.1f%%  P:%.1f%%  B:%.1f%%  B8x8:%.1f%%  DIRECT:%.1f%%  BSKIP:%.1f%%\n",
1434                   i_mb_count[I_4x4]    / i_count,
1435                   i_mb_count[I_16x16]  / i_count,
1436                   (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,
1437                   (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,
1438                   i_mb_count[B_8x8]    / i_count,
1439                   i_mb_count[B_DIRECT] / i_count,
1440                   i_mb_count[B_SKIP]   / i_count );
1441     }
1442
1443     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 )
1444     {
1445         const int i_count = h->stat.i_slice_count[SLICE_TYPE_I] +
1446                             h->stat.i_slice_count[SLICE_TYPE_P] +
1447                             h->stat.i_slice_count[SLICE_TYPE_B];
1448         float fps = (float) h->param.i_fps_num / h->param.i_fps_den;
1449
1450         if( h->param.analyse.b_psnr )
1451             x264_log( h, X264_LOG_INFO,
1452                       "PSNR Mean Y:%5.2f U:%5.2f V:%5.2f Avg:%5.2f Global:%5.2f kb/s:%.1f\n",
1453                       (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,
1454                       (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,
1455                       (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,
1456
1457                       (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,
1458
1459                       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],
1460                                  i_count * i_yuv_size ),
1461                       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 );
1462         else
1463             x264_log( h, X264_LOG_INFO,
1464                       "kb/s:%.1f\n",
1465                       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 );
1466     }
1467
1468     /* frames */
1469     for( i = 0; i < X264_BFRAME_MAX + 1; i++ )
1470     {
1471         if( h->frames.current[i] ) x264_frame_delete( h->frames.current[i] );
1472         if( h->frames.next[i] )    x264_frame_delete( h->frames.next[i] );
1473         if( h->frames.unused[i] )  x264_frame_delete( h->frames.unused[i] );
1474     }
1475     /* ref frames */
1476     for( i = 0; i < h->param.i_frame_reference+2; i++ )
1477     {
1478         x264_frame_delete( h->frames.reference[i] );
1479     }
1480
1481     /* param */
1482     if( h->param.rc.psz_stat_out )
1483         free( h->param.rc.psz_stat_out );
1484     if( h->param.rc.psz_stat_in )
1485         free( h->param.rc.psz_stat_in );
1486     if( h->param.rc.psz_rc_eq )
1487         free( h->param.rc.psz_rc_eq );
1488
1489     /* rc */
1490     x264_ratecontrol_delete( h );
1491
1492     x264_macroblock_cache_end( h );
1493     x264_free( h->out.p_bitstream );
1494     x264_free( h );
1495 }
1496