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