* all: Patches by Loren Merritt:
[x262.git] / 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 "../core/common.h"
31 #include "../core/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 = 1;
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;
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     {
337         h->param.i_idrframe = 1;
338     }
339     if( h->param.i_iframe <= 0 )
340     {
341         h->param.i_iframe = 1;
342     }
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     if( param->analyse.i_subpel_refine < 0 )
351         param->analyse.i_subpel_refine = 0;
352     if( param->analyse.i_subpel_refine > 5 )
353         param->analyse.i_subpel_refine = 5;
354
355     /* VUI */
356     if( h->param.vui.i_sar_width > 0 && h->param.vui.i_sar_height > 0 )
357     {
358         int i_w = param->vui.i_sar_width;
359         int i_h = param->vui.i_sar_height;
360         int a = i_w, b = i_h;
361
362         while( b != 0 )
363         {
364             int t = a;
365
366             a = b;
367             b = t % b;
368         }
369
370         i_w /= a;
371         i_h /= a;
372         while( i_w > 65535 || i_h > 65535 )
373         {
374             i_w /= 2;
375             i_h /= 2;
376         }
377
378         h->param.vui.i_sar_width = 0;
379         h->param.vui.i_sar_height = 0;
380         if( i_w == 0 || i_h == 0 )
381         {
382             x264_log( h, X264_LOG_ERROR, "cannot create valid sample aspect ratio\n" );
383         }
384         else if( i_w == i_h )
385         {
386             x264_log( h, X264_LOG_INFO, "no need for a SAR\n" );
387         }
388         else
389         {
390             x264_log( h, X264_LOG_INFO, "using SAR=%d/%d\n", i_w, i_h );
391             h->param.vui.i_sar_width = i_w;
392             h->param.vui.i_sar_height = i_h;
393         }
394     }
395
396
397     /* Init x264_t */
398     h->out.i_nal = 0;
399     h->out.i_bitstream = 1000000; /* FIXME estimate max size (idth/height) */
400     h->out.p_bitstream = x264_malloc( h->out.i_bitstream );
401
402     h->i_frame = 0;
403     h->i_frame_num = 0;
404     h->i_poc   = 0;
405     h->i_idr_pic_id = 0;
406
407     h->sps = &h->sps_array[0];
408     x264_sps_init( h->sps, 0, &h->param );
409
410     h->pps = &h->pps_array[0];
411     x264_pps_init( h->pps, 0, &h->param, h->sps);
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     h->stat.i_slice_count[SLICE_TYPE_I] = 0;
463     h->stat.i_slice_count[SLICE_TYPE_P] = 0;
464     h->stat.i_slice_count[SLICE_TYPE_B] = 0;
465     h->stat.i_slice_size[SLICE_TYPE_I] = 0;
466     h->stat.i_slice_size[SLICE_TYPE_P] = 0;
467     h->stat.i_slice_size[SLICE_TYPE_B] = 0;
468
469     h->stat.i_sqe_global[SLICE_TYPE_I] = 0;
470     h->stat.f_psnr_average[SLICE_TYPE_I] = 0.0;
471     h->stat.f_psnr_mean_y[SLICE_TYPE_I] = h->stat.f_psnr_mean_u[SLICE_TYPE_I] = h->stat.f_psnr_mean_v[SLICE_TYPE_I] = 0.0;
472
473     h->stat.i_sqe_global[SLICE_TYPE_P] = 0;
474     h->stat.f_psnr_average[SLICE_TYPE_P] = 0.0;
475     h->stat.f_psnr_mean_y[SLICE_TYPE_P] = h->stat.f_psnr_mean_u[SLICE_TYPE_P] = h->stat.f_psnr_mean_v[SLICE_TYPE_P] = 0.0;
476
477     h->stat.i_sqe_global[SLICE_TYPE_B] = 0;
478     h->stat.f_psnr_average[SLICE_TYPE_B] = 0.0;
479     h->stat.f_psnr_mean_y[SLICE_TYPE_B] = h->stat.f_psnr_mean_u[SLICE_TYPE_B] = h->stat.f_psnr_mean_v[SLICE_TYPE_B] = 0.0;
480
481     for( i = 0; i < 17; i++ )
482     {
483         h->stat.i_mb_count[SLICE_TYPE_I][i] = 0;
484         h->stat.i_mb_count[SLICE_TYPE_P][i] = 0;
485         h->stat.i_mb_count[SLICE_TYPE_B][i] = 0;
486     }
487
488     x264_log( h, X264_LOG_INFO, "using cpu capabilities %s%s%s%s%s%s\n",
489              param->cpu&X264_CPU_MMX ? "MMX " : "",
490              param->cpu&X264_CPU_MMXEXT ? "MMXEXT " : "",
491              param->cpu&X264_CPU_SSE ? "SSE " : "",
492              param->cpu&X264_CPU_SSE2 ? "SSE2 " : "",
493              param->cpu&X264_CPU_3DNOW ? "3DNow! " : "",
494              param->cpu&X264_CPU_ALTIVEC ? "Altivec " : "" );
495
496     return h;
497 }
498
499 /* internal usage */
500 static void x264_nal_start( x264_t *h, int i_type, int i_ref_idc )
501 {
502     x264_nal_t *nal = &h->out.nal[h->out.i_nal];
503
504     nal->i_ref_idc = i_ref_idc;
505     nal->i_type    = i_type;
506
507     bs_align_0( &h->out.bs );   /* not needed */
508
509     nal->i_payload= 0;
510     nal->p_payload= &h->out.p_bitstream[bs_pos( &h->out.bs) / 8];
511 }
512 static void x264_nal_end( x264_t *h )
513 {
514     x264_nal_t *nal = &h->out.nal[h->out.i_nal];
515
516     bs_align_0( &h->out.bs );   /* not needed */
517
518     nal->i_payload = &h->out.p_bitstream[bs_pos( &h->out.bs)/8] - nal->p_payload;
519
520     h->out.i_nal++;
521 }
522
523 /****************************************************************************
524  * x264_encoder_headers:
525  ****************************************************************************/
526 int x264_encoder_headers( x264_t *h, x264_nal_t **pp_nal, int *pi_nal )
527 {
528     /* init bitstream context */
529     h->out.i_nal = 0;
530     bs_init( &h->out.bs, h->out.p_bitstream, h->out.i_bitstream );
531
532     /* Put SPS and PPS */
533     if( h->i_frame == 0 )
534     {
535         /* generate sequence parameters */
536         x264_nal_start( h, NAL_SPS, NAL_PRIORITY_HIGHEST );
537         x264_sps_write( &h->out.bs, h->sps );
538         x264_nal_end( h );
539
540         /* generate picture parameters */
541         x264_nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
542         x264_pps_write( &h->out.bs, h->pps );
543         x264_nal_end( h );
544     }
545     /* now set output*/
546     *pi_nal = h->out.i_nal;
547     *pp_nal = &h->out.nal[0];
548
549     return 0;
550 }
551
552
553 static void x264_frame_put( x264_frame_t *list[X264_BFRAME_MAX], x264_frame_t *frame )
554 {
555     int i = 0;
556
557     while( list[i] != NULL ) i++;
558
559     list[i] = frame;
560 }
561
562 static x264_frame_t *x264_frame_get( x264_frame_t *list[X264_BFRAME_MAX+1] )
563 {
564     x264_frame_t *frame = list[0];
565     int i;
566
567     for( i = 0; i < X264_BFRAME_MAX; i++ )
568     {
569         list[i] = list[i+1];
570     }
571     list[X264_BFRAME_MAX] = NULL;
572
573     return frame;
574 }
575
576 static inline void x264_reference_build_list( x264_t *h, int i_poc )
577 {
578     int i;
579     int b_ok;
580
581     /* build ref list 0/1 */
582     h->i_ref0 = 0;
583     h->i_ref1 = 0;
584     for( i = 1; i < h->param.i_frame_reference+2; i++ )
585     {
586         if( h->frames.reference[i]->i_poc >= 0 )
587         {
588             if( h->frames.reference[i]->i_poc < i_poc )
589             {
590                 h->fref0[h->i_ref0++] = h->frames.reference[i];
591             }
592             else if( h->frames.reference[i]->i_poc > i_poc )
593             {
594                 h->fref1[h->i_ref1++] = h->frames.reference[i];
595             }
596         }
597     }
598     /* Order ref0 from higher to lower poc */
599     do
600     {
601         b_ok = 1;
602         for( i = 0; i < h->i_ref0 - 1; i++ )
603         {
604             if( h->fref0[i]->i_poc < h->fref0[i+1]->i_poc )
605             {
606                 x264_frame_t *tmp = h->fref0[i+1];
607
608                 h->fref0[i+1] = h->fref0[i];
609                 h->fref0[i] = tmp;
610                 b_ok = 0;
611                 break;
612             }
613         }
614     } while( !b_ok );
615     /* Order ref1 from lower to higher poc (bubble sort) for B-frame */
616     do
617     {
618         b_ok = 1;
619         for( i = 0; i < h->i_ref1 - 1; i++ )
620         {
621             if( h->fref1[i]->i_poc > h->fref1[i+1]->i_poc )
622             {
623                 x264_frame_t *tmp = h->fref1[i+1];
624
625                 h->fref1[i+1] = h->fref1[i];
626                 h->fref1[i] = tmp;
627                 b_ok = 0;
628                 break;
629             }
630         }
631     } while( !b_ok );
632
633     if( h->i_ref0 > h->param.i_frame_reference )
634     {
635         h->i_ref0 = h->param.i_frame_reference;
636     }
637     if( h->i_ref1 > 1 )
638     {
639         h->i_ref1 = 1;
640     }
641 }
642
643 static inline void x264_reference_update( x264_t *h )
644 {
645     int i;
646
647     /* apply deblocking filter to the current decoded picture */
648     if( h->param.b_deblocking_filter )
649     {
650         TIMER_START( i_mtime_filter );
651         x264_frame_deblocking_filter( h, h->sh.i_type );
652         TIMER_STOP( i_mtime_filter );
653     }
654     /* expand border */
655     x264_frame_expand_border( h->fdec );
656
657     /* move frame in the buffer */
658     h->fdec = h->frames.reference[h->param.i_frame_reference+1];
659     for( i = h->param.i_frame_reference+1; i > 0; i-- )
660     {
661         h->frames.reference[i] = h->frames.reference[i-1];
662     }
663     h->frames.reference[0] = h->fdec;
664 }
665
666 static inline void x264_reference_reset( x264_t *h )
667 {
668     int i;
669
670     /* reset ref pictures */
671     for( i = 1; i < h->param.i_frame_reference+2; i++ )
672     {
673         h->frames.reference[i]->i_poc = -1;
674     }
675     h->frames.reference[0]->i_poc = 0;
676 }
677
678 static inline void x264_slice_init( x264_t *h, int i_nal_type, int i_slice_type, int i_global_qp )
679 {
680     /* ------------------------ Create slice header  ----------------------- */
681     if( i_nal_type == NAL_SLICE_IDR )
682     {
683         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 );
684
685         /* increment id */
686         h->i_idr_pic_id = ( h->i_idr_pic_id + 1 ) % 65536;
687     }
688     else
689     {
690         x264_slice_header_init( &h->sh, &h->param, h->sps, h->pps, i_slice_type, -1, h->i_frame_num - 1 );
691
692         /* always set the real higher num of ref frame used */
693         h->sh.b_num_ref_idx_override = 1;
694         h->sh.i_num_ref_idx_l0_active = h->i_ref0 <= 0 ? 1 : h->i_ref0;
695         h->sh.i_num_ref_idx_l1_active = h->i_ref1 <= 0 ? 1 : h->i_ref1;
696     }
697
698     if( h->sps->i_poc_type == 0 )
699     {
700         h->sh.i_poc_lsb = h->fdec->i_poc & ( (1 << h->sps->i_log2_max_poc_lsb) - 1 );
701         h->sh.i_delta_poc_bottom = 0;   /* XXX won't work for field */
702     }
703     else if( h->sps->i_poc_type == 1 )
704     {
705         /* FIXME TODO FIXME */
706     }
707     else
708     {
709         /* Nothing to do ? */
710     }
711
712     /* global qp */
713     h->sh.i_qp_delta = i_global_qp - h->pps->i_pic_init_qp;
714
715     /* get adapative cabac model if needed */
716     if( h->param.b_cabac )
717     {
718         if( h->param.i_cabac_init_idc == -1 )
719         {
720             h->sh.i_cabac_init_idc = x264_cabac_model_get( &h->cabac, i_slice_type );
721         }
722     }
723 }
724
725 static inline void x264_slice_write( x264_t *h, int i_nal_type, int i_nal_ref_idc )
726 {
727     int i_skip;
728     int mb_xy;
729     int i;
730
731     /* Init stats */
732     h->stat.frame.i_hdr_bits  =
733     h->stat.frame.i_itex_bits =
734     h->stat.frame.i_ptex_bits =
735     h->stat.frame.i_misc_bits = 0;
736     for( i = 0; i < 17; i++ )
737         h->stat.frame.i_mb_count[i] = 0;
738
739     /* Slice */
740     x264_nal_start( h, i_nal_type, i_nal_ref_idc );
741
742     /* Slice header */
743     x264_slice_header_write( &h->out.bs, &h->sh, i_nal_ref_idc );
744     if( h->param.b_cabac )
745     {
746         /* alignment needed */
747         bs_align_1( &h->out.bs );
748
749         /* init cabac */
750         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 );
751         x264_cabac_encode_init ( &h->cabac, &h->out.bs );
752     }
753     h->mb.i_last_qp = h->pps->i_pic_init_qp + h->sh.i_qp_delta;
754     h->mb.i_last_dqp = 0;
755
756     for( mb_xy = 0, i_skip = 0; mb_xy < h->sps->i_mb_width * h->sps->i_mb_height; mb_xy++ )
757     {
758         const int i_mb_y = mb_xy / h->sps->i_mb_width;
759         const int i_mb_x = mb_xy % h->sps->i_mb_width;
760
761         int mb_spos = bs_pos(&h->out.bs);
762
763         /* load cache */
764         x264_macroblock_cache_load( h, i_mb_x, i_mb_y );
765
766         /* analyse parameters
767          * Slice I: choose I_4x4 or I_16x16 mode
768          * Slice P: choose between using P mode or intra (4x4 or 16x16)
769          * */
770         TIMER_START( i_mtime_analyse );
771         x264_macroblock_analyse( h );
772         TIMER_STOP( i_mtime_analyse );
773
774         /* encode this macrobock -> be carefull it can change the mb type to P_SKIP if needed */
775         TIMER_START( i_mtime_encode );
776         x264_macroblock_encode( h );
777         TIMER_STOP( i_mtime_encode );
778
779         TIMER_START( i_mtime_write );
780         if( IS_SKIP( h->mb.i_type ) )
781         {
782             if( h->param.b_cabac )
783             {
784                 if( mb_xy > 0 )
785                 {
786                     /* not end_of_slice_flag */
787                     x264_cabac_encode_terminal( &h->cabac, 0 );
788                 }
789
790                 x264_cabac_mb_skip( h, 1 );
791             }
792             else
793             {
794                 i_skip++;
795             }
796         }
797         else
798         {
799             if( h->param.b_cabac )
800             {
801                 if( mb_xy > 0 )
802                 {
803                     /* not end_of_slice_flag */
804                     x264_cabac_encode_terminal( &h->cabac, 0 );
805                 }
806                 if( h->sh.i_type != SLICE_TYPE_I )
807                 {
808                     x264_cabac_mb_skip( h, 0 );
809                 }
810                 x264_macroblock_write_cabac( h, &h->out.bs );
811             }
812             else
813             {
814                 if( h->sh.i_type != SLICE_TYPE_I )
815                 {
816                     bs_write_ue( &h->out.bs, i_skip );  /* skip run */
817                     i_skip = 0;
818                 }
819                 x264_macroblock_write_cavlc( h, &h->out.bs );
820             }
821         }
822         TIMER_STOP( i_mtime_write );
823
824         /* save cache */
825         x264_macroblock_cache_save( h );
826
827         h->stat.frame.i_mb_count[h->mb.i_type]++;
828
829         x264_ratecontrol_mb(h, bs_pos(&h->out.bs) - mb_spos);
830     }
831
832     if( h->param.b_cabac )
833     {
834         /* end of slice */
835         x264_cabac_encode_terminal( &h->cabac, 1 );
836     }
837     else if( i_skip > 0 )
838     {
839         bs_write_ue( &h->out.bs, i_skip );  /* last skip run */
840     }
841
842     if( h->param.b_cabac )
843     {
844         int i_cabac_word;
845         x264_cabac_encode_flush( &h->cabac );
846         /* TODO cabac stuffing things (p209) */
847         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;
848
849         while( i_cabac_word > 0 )
850         {
851             bs_write( &h->out.bs, 16, 0x0000 );
852             i_cabac_word--;
853         }
854     }
855     else
856     {
857         /* rbsp_slice_trailing_bits */
858         bs_rbsp_trailing( &h->out.bs );
859     }
860
861     x264_nal_end( h );
862
863     /* Compute misc bits */
864     h->stat.frame.i_misc_bits = bs_pos( &h->out.bs )
865                               - h->stat.frame.i_itex_bits
866                               - h->stat.frame.i_ptex_bits
867                               - h->stat.frame.i_hdr_bits;
868 }
869
870 /****************************************************************************
871  * x264_encoder_encode:
872  *  XXX: i_poc   : is the poc of the current given picture
873  *       i_frame : is the number of the frame being coded
874  *  ex:  type frame poc
875  *       I      0   2*0
876  *       P      1   2*3
877  *       B      2   2*1
878  *       B      3   2*2
879  *       P      4   2*6
880  *       B      5   2*4
881  *       B      6   2*5
882  ****************************************************************************/
883 int     x264_encoder_encode( x264_t *h,
884                              x264_nal_t **pp_nal, int *pi_nal,
885                              x264_picture_t *pic )
886 {
887     x264_frame_t   *frame_psnr = h->fdec; /* just to keep the current decoded frame for psnr calculation */
888     int     i_nal_type;
889     int     i_nal_ref_idc;
890     int     i_slice_type;
891
892     int i;
893
894     int   i_global_qp;
895
896     /* no data out */
897     *pi_nal = 0;
898     *pp_nal = NULL;
899
900
901     /* ------------------- Setup new frame from picture -------------------- */
902     TIMER_START( i_mtime_encode_frame );
903     if( pic != NULL )
904     {
905         /* Copy the picture to a frame, init the frame and move it to a buffer */
906         /* 1: get a frame */
907         x264_frame_t *fenc = x264_frame_get( h->frames.unused );
908
909         x264_frame_copy_picture( h, fenc, pic );
910
911         fenc->i_frame = h->frames.i_input++;
912
913         /* 2: get its type */
914         if( h->param.rc.b_stat_read )
915         {
916             /* XXX: trusts that the first pass used compatible B and IDR frequencies */
917             fenc->i_type = x264_ratecontrol_slice_type( h, fenc->i_frame );
918             if( fenc->i_type == X264_TYPE_I && h->frames.next[0] == NULL &&
919                 h->frames.i_last_idr + 1 >= h->param.i_idrframe )
920             {
921                 fenc->i_type = X264_TYPE_IDR;
922                 h->i_poc       = 0;
923                 h->i_frame_num = 0;
924             }
925         }
926         else if( ( h->frames.i_last_i + 1 >= h->param.i_iframe && h->frames.i_last_idr + 1 >= h->param.i_idrframe ) ||
927             pic->i_type == X264_TYPE_IDR )
928         {
929             /* IDR */
930             fenc->i_type = X264_TYPE_IDR;
931
932             h->i_poc       = 0;
933             h->i_frame_num = 0;
934
935             /* Last schedule B frames need to be encoded as P */
936             if( h->frames.next[0] != NULL )
937             {
938                 x264_frame_t *tmp;
939                 int i = 0;
940
941                 while( h->frames.next[i+1] != NULL ) i++;
942                 h->frames.next[i]->i_type = X264_TYPE_P;
943
944                 /* remove this P from next */
945                 tmp = h->frames.next[i];
946                 h->frames.next[i] = NULL;
947
948                 /* move this P + Bs to current */
949                 x264_frame_put( h->frames.current, tmp );
950                 while( ( tmp = x264_frame_get( h->frames.next ) ) )
951                 {
952                     x264_frame_put( h->frames.current, tmp );
953                 }
954             }
955         }
956         else if( h->param.i_bframe > 0 )
957         {
958             if( h->frames.i_last_i  + 1 >= h->param.i_iframe )
959                 fenc->i_type = X264_TYPE_I;
960             else if( h->frames.next[h->param.i_bframe-1] != NULL )
961                 fenc->i_type = X264_TYPE_P;
962             else if( pic->i_type == X264_TYPE_AUTO )
963                 fenc->i_type = X264_TYPE_B;
964             else
965                 fenc->i_type = pic->i_type;
966         }
967         else
968         {
969             if( pic->i_type == X264_TYPE_AUTO )
970             {
971                 if( h->frames.i_last_i + 1 >= h->param.i_iframe )
972                     fenc->i_type = X264_TYPE_I;
973                 else
974                     fenc->i_type = X264_TYPE_P;
975             }
976             else
977             {
978                 fenc->i_type = pic->i_type;
979             }
980         }
981
982         fenc->i_poc = h->i_poc;
983
984         /* 3: Update current/next */
985         if( fenc->i_type == X264_TYPE_B )
986         {
987             x264_frame_put( h->frames.next, fenc );
988         }
989         else
990         {
991             x264_frame_put( h->frames.current, fenc );
992             while( ( fenc = x264_frame_get( h->frames.next ) ) )
993             {
994                 x264_frame_put( h->frames.current, fenc );
995             }
996         }
997         h->i_poc += 2;
998     }
999     else    /* No more picture, begin encoding of last frames */
1000     {
1001         /* Move all next frames to current and mark the last one as a P */
1002         x264_frame_t *tmp;
1003         int i = -1;
1004         while( h->frames.next[i+1] != NULL ) i++;
1005         if( i >= 0 )
1006         {
1007             h->frames.next[i]->i_type = X264_TYPE_P;
1008             tmp = h->frames.next[i];
1009             h->frames.next[i] = NULL;
1010
1011             x264_frame_put( h->frames.current, tmp );
1012             while( ( tmp = x264_frame_get( h->frames.next ) ) )
1013             {
1014                 x264_frame_put( h->frames.current, tmp );
1015             }
1016         }
1017     }
1018     TIMER_STOP( i_mtime_encode_frame );
1019
1020     /* ------------------- Get frame to be encoded ------------------------- */
1021     /* 4: get picture to encode */
1022     h->fenc = x264_frame_get( h->frames.current );
1023     if( h->fenc == NULL )
1024     {
1025         /* Nothing yet to encode (ex: waiting for I/P with B frames) */
1026         /* waiting for filling bframe buffer */
1027         pic->i_type = X264_TYPE_AUTO;
1028         return 0;
1029     }
1030     x264_frame_put( h->frames.unused, h->fenc );  /* Safe to do it now, we don't use frames.unused for the rest */
1031
1032 do_encode:
1033
1034     if( h->fenc->i_type == X264_TYPE_IDR )
1035     {
1036         h->frames.i_last_idr = 0;
1037         h->frames.i_last_i = 0;
1038     }
1039     else if( h->fenc->i_type == X264_TYPE_I )
1040     {
1041         h->frames.i_last_idr++;
1042         h->frames.i_last_i = 0;
1043     }
1044     else
1045     {
1046         h->frames.i_last_i++;
1047     }
1048
1049     /* ------------------- Setup frame context ----------------------------- */
1050     /* 5: Init data dependant of frame type */
1051     TIMER_START( i_mtime_encode_frame );
1052     if( h->fenc->i_type == X264_TYPE_IDR )
1053     {
1054         /* reset ref pictures */
1055         x264_reference_reset( h );
1056
1057         i_nal_type    = NAL_SLICE_IDR;
1058         i_nal_ref_idc = NAL_PRIORITY_HIGHEST;
1059         i_slice_type = SLICE_TYPE_I;
1060     }
1061     else if( h->fenc->i_type == X264_TYPE_I )
1062     {
1063         i_nal_type    = NAL_SLICE;
1064         i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
1065         i_slice_type = SLICE_TYPE_I;
1066     }
1067     else if( h->fenc->i_type == X264_TYPE_P )
1068     {
1069         i_nal_type    = NAL_SLICE;
1070         i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
1071         i_slice_type = SLICE_TYPE_P;
1072     }
1073     else    /* B frame */
1074     {
1075         i_nal_type    = NAL_SLICE;
1076         i_nal_ref_idc = NAL_PRIORITY_DISPOSABLE;
1077         i_slice_type = SLICE_TYPE_B;
1078     }
1079
1080     pic->i_type     =
1081     h->fdec->i_type = h->fenc->i_type;
1082     h->fdec->i_poc  = h->fenc->i_poc;
1083
1084
1085
1086     /* ------------------- Init                ----------------------------- */
1087     /* Init the rate control */
1088     x264_ratecontrol_start( h, i_slice_type );
1089     i_global_qp = x264_ratecontrol_qp( h );
1090     if( h->fenc->i_qpplus1 > 0 )
1091     {
1092         i_global_qp = x264_clip3( h->fenc->i_qpplus1 - 1, 0, 51 );
1093     }
1094
1095     /* build ref list 0/1 */
1096     x264_reference_build_list( h, h->fdec->i_poc );
1097
1098     /* increase frame num but only once for B frame */
1099     if( i_slice_type != SLICE_TYPE_B || h->sh.i_type != SLICE_TYPE_B )
1100     {
1101         h->i_frame_num++;
1102     }
1103
1104     /* ------------------------ Create slice header  ----------------------- */
1105     x264_slice_init( h, i_nal_type, i_slice_type, i_global_qp );
1106
1107     /* ---------------------- Write the bitstream -------------------------- */
1108     /* Init bitstream context */
1109     h->out.i_nal = 0;
1110     bs_init( &h->out.bs, h->out.p_bitstream, h->out.i_bitstream );
1111
1112     /* Write SPS and PPS */
1113     if( i_nal_type == NAL_SLICE_IDR )
1114     {
1115         /* generate sequence parameters */
1116         x264_nal_start( h, NAL_SPS, NAL_PRIORITY_HIGHEST );
1117         x264_sps_write( &h->out.bs, h->sps );
1118         x264_nal_end( h );
1119
1120         /* generate picture parameters */
1121         x264_nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
1122         x264_pps_write( &h->out.bs, h->pps );
1123         x264_nal_end( h );
1124     }
1125
1126     /* Write the slice */
1127     x264_slice_write( h, i_nal_type, i_nal_ref_idc );
1128
1129     /* XXX: this scene cut won't work with B frame (it may never create IDR -> bad) */
1130     if( i_slice_type != SLICE_TYPE_I && !h->param.rc.b_stat_read )
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   = h->sps->i_mb_width * h->sps->i_mb_height;
1136         if( h->param.i_iframe > 0 )
1137             i_bias = 30 * X264_MIN( 3*h->frames.i_last_i, h->param.i_iframe )  / h->param.i_iframe;
1138         else
1139             i_bias = 15;
1140
1141         /* Bad P will be reencoded as I */
1142         if( i_slice_type == SLICE_TYPE_P &&
1143             100 * i_mb_i >= (100 - i_bias) * i_mb )
1144             /*
1145             h->out.nal[h->out.i_nal-1].i_payload > h->i_last_intra_size +
1146             h->i_last_intra_size * (3+h->i_last_intra_qp - i_global_qp) / 16 &&
1147             i_mb_count[I_4x4] + i_mb_count[I_16x16] > i_mb_count[P_SKIP] + i_mb_count[P_L0]/2 &&
1148             h->out.nal[h->out.i_nal-1].i_payload > 2 * h->i_last_inter_size &&
1149             h->frames.i_last_i > 4)*/
1150         {
1151
1152             x264_log( h, X264_LOG_DEBUG, "scene cut at %d size=%d last I:%d last P:%d Intra:%d Inter=%d Ratio=%d Bias=%d (Skip:%d PL0:%d)\n",
1153                       h->i_frame - 1,
1154                       h->out.nal[h->out.i_nal-1].i_payload,
1155                       h->i_last_intra_size, h->i_last_inter_size,
1156                       i_mb_i, i_mb - i_mb_i, 100 * i_mb_i / i_mb, i_bias,
1157                       h->stat.frame.i_mb_count[P_SKIP],
1158                       h->stat.frame.i_mb_count[P_L0] );
1159
1160             /* Restore frame num */
1161             h->i_frame_num--;
1162
1163             /* Do IDR if needed and if we can (won't work with B frames) */
1164             if( h->frames.next[0] == NULL &&
1165                 h->frames.i_last_idr + 1 >= h->param.i_idrframe )
1166             {
1167                 /* Reset */
1168                 h->i_poc       = 0;
1169                 h->i_frame_num = 0;
1170
1171                 /* Reinit field of fenc */
1172                 h->fenc->i_type = X264_TYPE_IDR;
1173                 h->fenc->i_poc = h->i_poc;
1174
1175                 /* Next Poc */
1176                 h->i_poc += 2;
1177             }
1178             else
1179             {
1180                 h->fenc->i_type = X264_TYPE_I;
1181             }
1182             goto do_encode;
1183         }
1184         h->i_last_inter_size = h->out.nal[h->out.i_nal-1].i_payload;
1185     }
1186     else
1187     {
1188         h->i_last_intra_size = h->out.nal[h->out.i_nal-1].i_payload;
1189         h->i_last_intra_qp = i_global_qp;
1190     }
1191
1192     /* End bitstream, set output  */
1193     *pi_nal = h->out.i_nal;
1194     *pp_nal = &h->out.nal[0];
1195
1196     /* Set output picture properties */
1197     if( i_slice_type == SLICE_TYPE_I )
1198         pic->i_type = i_nal_type == NAL_SLICE_IDR ? X264_TYPE_IDR : X264_TYPE_I;
1199     else if( i_slice_type == SLICE_TYPE_P )
1200         pic->i_type = X264_TYPE_P;
1201     else
1202         pic->i_type = X264_TYPE_B;
1203     pic->i_pts = h->fenc->i_pts;
1204
1205     /* ---------------------- Update encoder state ------------------------- */
1206     /* update cabac */
1207     if( h->param.b_cabac )
1208     {
1209         x264_cabac_model_update( &h->cabac, i_slice_type, h->sh.pps->i_pic_init_qp + h->sh.i_qp_delta );
1210     }
1211
1212     /* handle references */
1213     if( i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE )
1214     {
1215         x264_reference_update( h );
1216     }
1217
1218     /* increase frame count */
1219     h->i_frame++;
1220
1221     /* restore CPU state (before using float again) */
1222     x264_cpu_restore( h->param.cpu );
1223
1224     /* update rc */
1225     x264_ratecontrol_end( h, h->out.nal[h->out.i_nal-1].i_payload * 8 );
1226
1227     TIMER_STOP( i_mtime_encode_frame );
1228
1229     /* ---------------------- Compute/Print statistics --------------------- */
1230     /* Slice stat */
1231     h->stat.i_slice_count[i_slice_type]++;
1232     h->stat.i_slice_size[i_slice_type] += bs_pos( &h->out.bs) / 8;
1233
1234     for( i = 0; i < 17; i++ )
1235     {
1236         h->stat.i_mb_count[h->sh.i_type][i] += h->stat.frame.i_mb_count[i];
1237     }
1238
1239     if( h->param.analyse.b_psnr )
1240     {
1241         int64_t i_sqe_y, i_sqe_u, i_sqe_v;
1242
1243         /* PSNR */
1244         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 );
1245         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);
1246         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);
1247
1248         h->stat.i_sqe_global[i_slice_type] += i_sqe_y + i_sqe_u + i_sqe_v;
1249         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 );
1250         h->stat.f_psnr_mean_y[i_slice_type] += x264_psnr( i_sqe_y, h->param.i_width * h->param.i_height );
1251         h->stat.f_psnr_mean_u[i_slice_type] += x264_psnr( i_sqe_u, h->param.i_width * h->param.i_height / 4 );
1252         h->stat.f_psnr_mean_v[i_slice_type] += x264_psnr( i_sqe_v, h->param.i_width * h->param.i_height / 4 );
1253
1254         x264_log( h, X264_LOG_DEBUG,
1255                   "frame=%4d QP=%i NAL=%d Slice:%c Poc:%-3d I4x4:%-5d I16x16:%-5d P:%-5d SKIP:%-3d size=%d bytes PSNR Y:%2.2f U:%2.2f V:%2.2f\n",
1256                   h->i_frame - 1,
1257                   i_global_qp,
1258                   i_nal_ref_idc,
1259                   i_slice_type == SLICE_TYPE_I ? 'I' : (i_slice_type == SLICE_TYPE_P ? 'P' : 'B' ),
1260                   frame_psnr->i_poc,
1261                   h->stat.frame.i_mb_count[I_4x4],
1262                   h->stat.frame.i_mb_count[I_16x16],
1263                   h->stat.frame.i_mb_count[P_L0] + h->stat.frame.i_mb_count[P_8x8],
1264                   h->stat.frame.i_mb_count[P_SKIP],
1265                   h->out.nal[h->out.i_nal-1].i_payload,
1266                   x264_psnr( i_sqe_y, h->param.i_width * h->param.i_height ),
1267                   x264_psnr( i_sqe_u, h->param.i_width * h->param.i_height / 4),
1268                   x264_psnr( i_sqe_v, h->param.i_width * h->param.i_height / 4) );
1269     }
1270     else
1271     {
1272         x264_log( h, X264_LOG_DEBUG,
1273                   "frame=%4d QP=%i NAL=%d Slice:%c Poc:%-3d I4x4:%-5d I16x16:%-5d P:%-5d SKIP:%-3d size=%d bytes\n",
1274                   h->i_frame - 1,
1275                   i_global_qp,
1276                   i_nal_ref_idc,
1277                   i_slice_type == SLICE_TYPE_I ? 'I' : (i_slice_type == SLICE_TYPE_P ? 'P' : 'B' ),
1278                   frame_psnr->i_poc,
1279                   h->stat.frame.i_mb_count[I_4x4],
1280                   h->stat.frame.i_mb_count[I_16x16],
1281                   h->stat.frame.i_mb_count[P_L0] + h->stat.frame.i_mb_count[P_8x8],
1282                   h->stat.frame.i_mb_count[P_SKIP],
1283                   h->out.nal[h->out.i_nal-1].i_payload );
1284     }
1285
1286
1287 #ifdef DEBUG_MB_TYPE
1288     for( mb_xy = 0; mb_xy < h->sps->i_mb_width * h->sps->i_mb_height; mb_xy++ )
1289     {
1290         const int i_mb_y = mb_xy / h->sps->i_mb_width;
1291         const int i_mb_x = mb_xy % h->sps->i_mb_width;
1292
1293         if( i_mb_y > 0 && i_mb_x == 0 )
1294             fprintf( stderr, "\n" );
1295
1296         if( h->mb.type[mb_xy] == I_4x4 )
1297             fprintf( stderr, "i" );
1298         else if( h->mb.type[mb_xy] == I_16x16 )
1299             fprintf( stderr, "I" );
1300         else if( h->mb.type[mb_xy] == P_SKIP )
1301             fprintf( stderr, "S" );
1302         else if( h->mb.type[mb_xy] == P_8x8 )
1303             fprintf( stderr, "8" );
1304         else if( h->mb.type[mb_xy] == P_L0 )
1305             fprintf( stderr, "P" );
1306         else
1307             fprintf( stderr, "?" );
1308
1309         fprintf( stderr, " " );
1310     }
1311 #endif
1312
1313 #ifdef DEBUG_DUMP_FRAME
1314     /* Dump reconstructed frame */
1315     x264_frame_dump( h, frame_psnr, "fdec.yuv" );
1316 #endif
1317 #if 0
1318     if( h->i_ref0 > 0 )
1319     {
1320         x264_frame_dump( h, h->fref0[0], "ref0.yuv" );
1321     }
1322     if( h->i_ref1 > 0 )
1323     {
1324         x264_frame_dump( h, h->fref1[0], "ref1.yuv" );
1325     }
1326 #endif
1327     return 0;
1328 }
1329
1330 /****************************************************************************
1331  * x264_encoder_close:
1332  ****************************************************************************/
1333 void    x264_encoder_close  ( x264_t *h )
1334 {
1335     int64_t i_mtime_total = i_mtime_analyse + i_mtime_encode + i_mtime_write + i_mtime_filter + 1;
1336     int64_t i_yuv_size = 3 * h->param.i_width * h->param.i_height / 2;
1337     int i;
1338
1339     x264_log( h, X264_LOG_INFO,
1340               "analyse=%d(%lldms) encode=%d(%lldms) write=%d(%lldms) filter=%d(%lldms)\n",
1341               (int)(100*i_mtime_analyse/i_mtime_total), i_mtime_analyse/1000,
1342               (int)(100*i_mtime_encode/i_mtime_total), i_mtime_encode/1000,
1343               (int)(100*i_mtime_write/i_mtime_total), i_mtime_write/1000,
1344               (int)(100*i_mtime_filter/i_mtime_total), i_mtime_filter/1000 );
1345
1346     /* Slices used and PNSR */
1347     if( h->stat.i_slice_count[SLICE_TYPE_I] > 0 )
1348     {
1349         const int i_count = h->stat.i_slice_count[SLICE_TYPE_I];
1350         x264_log( h, X264_LOG_INFO,
1351                   "slice I:%-4d Avg size:%-5d PSNR Mean Y:%5.2f U:%5.2f V:%5.2f Avg:%5.2f Global:%5.2f MSE*Size:%5.3f\n",
1352                    i_count,
1353                    h->stat.i_slice_size[SLICE_TYPE_I] / i_count,
1354                    h->stat.f_psnr_mean_y[SLICE_TYPE_I] / i_count, h->stat.f_psnr_mean_u[SLICE_TYPE_I] / i_count, h->stat.f_psnr_mean_v[SLICE_TYPE_I] / i_count,
1355                    h->stat.f_psnr_average[SLICE_TYPE_I] / i_count,
1356                    x264_psnr( h->stat.i_sqe_global[SLICE_TYPE_I], i_count * i_yuv_size ),
1357                    x264_mse( h->stat.i_sqe_global[SLICE_TYPE_I], i_count * i_yuv_size ) * h->stat.i_slice_size[SLICE_TYPE_I] / i_count );
1358     }
1359     if( h->stat.i_slice_count[SLICE_TYPE_P] > 0 )
1360     {
1361         const int i_count = h->stat.i_slice_count[SLICE_TYPE_P];
1362         x264_log( h, X264_LOG_INFO,
1363                   "slice P:%-4d Avg size:%-5d PSNR Mean Y:%5.2f U:%5.2f V:%5.2f Avg:%5.2f Global:%5.2f MSE*Size:%5.3f\n",
1364                   i_count,
1365                   h->stat.i_slice_size[SLICE_TYPE_P] / i_count,
1366                   h->stat.f_psnr_mean_y[SLICE_TYPE_P] / i_count, h->stat.f_psnr_mean_u[SLICE_TYPE_P] / i_count, h->stat.f_psnr_mean_v[SLICE_TYPE_P] / i_count,
1367                   h->stat.f_psnr_average[SLICE_TYPE_P] / i_count,
1368                   x264_psnr( h->stat.i_sqe_global[SLICE_TYPE_P], i_count * i_yuv_size ),
1369                   x264_mse( h->stat.i_sqe_global[SLICE_TYPE_P], i_count * i_yuv_size ) * h->stat.i_slice_size[SLICE_TYPE_P] / i_count );
1370     }
1371     if( h->stat.i_slice_count[SLICE_TYPE_B] > 0 )
1372     {
1373         const int i_count = h->stat.i_slice_count[SLICE_TYPE_B];
1374         x264_log( h, X264_LOG_INFO,
1375                   "slice B:%-4d Avg size:%-5d PSNR Mean Y:%5.2f U:%5.2f V:%5.2f Avg:%5.2f Global:%5.2f MSE*Size:%5.3f\n",
1376                    h->stat.i_slice_count[SLICE_TYPE_B],
1377                    h->stat.i_slice_size[SLICE_TYPE_B] / i_count,
1378                    h->stat.f_psnr_mean_y[SLICE_TYPE_B] / i_count, h->stat.f_psnr_mean_u[SLICE_TYPE_B] / i_count, h->stat.f_psnr_mean_v[SLICE_TYPE_B] / i_count,
1379                    h->stat.f_psnr_average[SLICE_TYPE_B] / i_count,
1380                    x264_psnr( h->stat.i_sqe_global[SLICE_TYPE_B], i_count * i_yuv_size ),
1381                    x264_mse( h->stat.i_sqe_global[SLICE_TYPE_B], i_count * i_yuv_size ) * h->stat.i_slice_size[SLICE_TYPE_B] / i_count );
1382     }
1383
1384     /* MB types used */
1385     if( h->stat.i_slice_count[SLICE_TYPE_I] > 0 )
1386     {
1387         const int i_count =  h->stat.i_slice_count[SLICE_TYPE_I];
1388         x264_log( h, X264_LOG_INFO,
1389                   "slice I      Avg I4x4:%-5d I16x16:%-5d\n",
1390                   h->stat.i_mb_count[SLICE_TYPE_I][I_4x4]  / i_count,
1391                   h->stat.i_mb_count[SLICE_TYPE_I][I_16x16]/ i_count );
1392     }
1393     if( h->stat.i_slice_count[SLICE_TYPE_P] > 0 )
1394     {
1395         const int i_count = h->stat.i_slice_count[SLICE_TYPE_P];
1396         x264_log( h, X264_LOG_INFO,
1397                   "slice P      Avg I4x4:%-5d I16x16:%-5d P:%-5d P8x8:%-5d PSKIP:%-5d\n",
1398                   h->stat.i_mb_count[SLICE_TYPE_P][I_4x4]  / i_count,
1399                   h->stat.i_mb_count[SLICE_TYPE_P][I_16x16]/ i_count,
1400                   h->stat.i_mb_count[SLICE_TYPE_P][P_L0] / i_count,
1401                   h->stat.i_mb_count[SLICE_TYPE_P][P_8x8] / i_count,
1402                   h->stat.i_mb_count[SLICE_TYPE_P][P_SKIP] /i_count );
1403     }
1404
1405     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 )
1406     {
1407         const int i_count = h->stat.i_slice_count[SLICE_TYPE_I] +
1408                             h->stat.i_slice_count[SLICE_TYPE_P] +
1409                             h->stat.i_slice_count[SLICE_TYPE_B];
1410         float fps = (float) h->param.i_fps_num / h->param.i_fps_den;
1411
1412         if( h->param.analyse.b_psnr )
1413             x264_log( h, X264_LOG_INFO,
1414                       "PSNR Mean Y:%5.2f U:%5.2f V:%5.2f Avg:%5.2f Global:%5.2f kb/s:%.1f fps:%.3f\n",
1415                       (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,
1416                       (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,
1417                       (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,
1418
1419                       (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,
1420
1421                       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],
1422                                  i_count * i_yuv_size ),
1423                       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,
1424                       (double)1000000.0 * (double)i_count / (double)i_mtime_encode_frame );
1425         else
1426             x264_log( h, X264_LOG_INFO,
1427                       "kb/s:%.1f fps:%.3f\n",
1428                       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,
1429                       (double)1000000.0 * (double)i_count / (double)i_mtime_encode_frame );
1430     }
1431
1432     /* frames */
1433     for( i = 0; i < X264_BFRAME_MAX + 1; i++ )
1434     {
1435         if( h->frames.current[i] ) x264_frame_delete( h->frames.current[i] );
1436         if( h->frames.next[i] )    x264_frame_delete( h->frames.next[i] );
1437         if( h->frames.unused[i] )  x264_frame_delete( h->frames.unused[i] );
1438     }
1439     /* ref frames */
1440     for( i = 0; i < h->param.i_frame_reference+2; i++ )
1441     {
1442         x264_frame_delete( h->frames.reference[i] );
1443     }
1444
1445     /* param */
1446     if( h->param.rc.psz_stat_out )
1447         free( h->param.rc.psz_stat_out );
1448     if( h->param.rc.psz_stat_in )
1449         free( h->param.rc.psz_stat_in );
1450     if( h->param.rc.psz_rc_eq )
1451         free( h->param.rc.psz_rc_eq );
1452
1453     /* rc */
1454     x264_ratecontrol_delete( h );
1455
1456     x264_macroblock_cache_end( h );
1457     x264_free( h->out.p_bitstream );
1458     x264_free( h );
1459 }
1460