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