]> git.sesse.net Git - x264/blob - encoder/encoder.c
8x8 transform and 8x8 intra prediction.
[x264] / encoder / encoder.c
1 /*****************************************************************************
2  * x264: h264 encoder
3  *****************************************************************************
4  * Copyright (C) 2003 Laurent Aimar
5  * $Id: encoder.c,v 1.1 2004/06/03 19:27:08 fenrir Exp $
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
22  *****************************************************************************/
23
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <string.h>
27 #include <math.h>
28
29 #if HAVE_PTHREAD
30 #ifdef SYS_BEOS
31 #include <kernel/OS.h>
32 #define pthread_t               thread_id
33 #define pthread_create(t,u,f,d) *(t)=spawn_thread(f,"",10,d)
34 #define pthread_join(t,s)       wait_for_thread(t,(long*)s)
35 #else
36 #include <pthread.h>
37 #endif
38 #endif
39
40 #include "common/common.h"
41 #include "common/cpu.h"
42
43 #include "set.h"
44 #include "analyse.h"
45 #include "ratecontrol.h"
46 #include "macroblock.h"
47
48 #if VISUALIZE
49 #include "common/visualize.h"
50 #endif
51
52 //#define DEBUG_MB_TYPE
53 #define DEBUG_DUMP_FRAME
54 //#define DEBUG_BENCHMARK
55
56 #ifdef DEBUG_BENCHMARK
57 static int64_t i_mtime_encode_frame = 0;
58 static int64_t i_mtime_analyse = 0;
59 static int64_t i_mtime_encode = 0;
60 static int64_t i_mtime_write = 0;
61 static int64_t i_mtime_filter = 0;
62 #define TIMER_START( d ) \
63     { \
64         int64_t d##start = x264_mdate();
65
66 #define TIMER_STOP( d ) \
67         d += x264_mdate() - d##start;\
68     }
69 #else
70 #define TIMER_START( d )
71 #define TIMER_STOP( d )
72 #endif
73
74 #define NALU_OVERHEAD 5 // startcode + NAL type costs 5 bytes per frame
75
76 /****************************************************************************
77  *
78  ******************************* x264 libs **********************************
79  *
80  ****************************************************************************/
81 static int64_t x264_sqe( x264_t *h, uint8_t *pix1, int i_pix_stride, uint8_t *pix2, int i_pix2_stride, int i_width, int i_height )
82 {
83     int64_t i_sqe = 0;
84     int x, y;
85
86 #define SSD(size) i_sqe += h->pixf.ssd[size]( pix1+y*i_pix_stride+x, i_pix_stride, \
87                                               pix2+y*i_pix2_stride+x, i_pix2_stride );
88     for( y = 0; y < i_height-15; y += 16 )
89     {
90         for( x = 0; x < i_width-15; x += 16 )
91             SSD(PIXEL_16x16);
92         if( x < i_width-7 )
93             SSD(PIXEL_8x16);
94     }
95     if( y < i_height-7 )
96         for( x = 0; x < i_width-7; x += 8 )
97             SSD(PIXEL_8x8);
98 #undef SSD
99     x264_cpu_restore( h->param.cpu );
100
101     return i_sqe;
102 }
103
104 static float x264_psnr( int64_t i_sqe, int64_t i_size )
105 {
106     double f_mse = (double)i_sqe / ((double)65025.0 * (double)i_size);
107     if( f_mse <= 0.0000000001 ) /* Max 100dB */
108         return 100;
109
110     return (float)(-10.0 * log( f_mse ) / log( 10.0 ));
111 }
112
113 #ifdef DEBUG_DUMP_FRAME
114 static void x264_frame_dump( x264_t *h, x264_frame_t *fr, char *name )
115 {
116     FILE * f = fopen( name, "a" );
117     int i, y;
118
119     fseek( f, 0, SEEK_END );
120
121     for( i = 0; i < fr->i_plane; i++ )
122     {
123         for( y = 0; y < h->param.i_height / ( i == 0 ? 1 : 2 ); y++ )
124         {
125             fwrite( &fr->plane[i][y*fr->i_stride[i]], 1, h->param.i_width / ( i == 0 ? 1 : 2 ), f );
126         }
127     }
128     fclose( f );
129 }
130 #endif
131
132
133 /* Fill "default" values */
134 static void x264_slice_header_init( x264_t *h, x264_slice_header_t *sh,
135                                     x264_sps_t *sps, x264_pps_t *pps,
136                                     int i_type, int i_idr_pic_id, int i_frame, int i_qp )
137 {
138     x264_param_t *param = &h->param;
139     int i;
140
141     /* First we fill all field */
142     sh->sps = sps;
143     sh->pps = pps;
144
145     sh->i_type      = i_type;
146     sh->i_first_mb  = 0;
147     sh->i_last_mb   = h->sps->i_mb_width * h->sps->i_mb_height;
148     sh->i_pps_id    = pps->i_id;
149
150     sh->i_frame_num = i_frame;
151
152     sh->b_field_pic = 0;    /* Not field support for now */
153     sh->b_bottom_field = 1; /* not yet used */
154
155     sh->i_idr_pic_id = i_idr_pic_id;
156
157     /* poc stuff, fixed later */
158     sh->i_poc_lsb = 0;
159     sh->i_delta_poc_bottom = 0;
160     sh->i_delta_poc[0] = 0;
161     sh->i_delta_poc[1] = 0;
162
163     sh->i_redundant_pic_cnt = 0;
164
165     sh->b_direct_spatial_mv_pred = ( param->analyse.i_direct_mv_pred == X264_DIRECT_PRED_SPATIAL );
166
167     sh->b_num_ref_idx_override = 0;
168     sh->i_num_ref_idx_l0_active = 1;
169     sh->i_num_ref_idx_l1_active = 1;
170
171     sh->b_ref_pic_list_reordering_l0 = h->b_ref_reorder[0];
172     sh->b_ref_pic_list_reordering_l1 = h->b_ref_reorder[1];
173
174     /* If the ref list isn't in the default order, construct reordering header */
175     /* List1 reordering isn't needed yet */
176     if( sh->b_ref_pic_list_reordering_l0 )
177     {
178         int pred_frame_num = i_frame;
179         for( i = 0; i < h->i_ref0; i++ )
180         {
181             int diff = h->fref0[i]->i_frame_num - pred_frame_num;
182             if( diff == 0 )
183                 x264_log( h, X264_LOG_ERROR, "diff frame num == 0\n" );
184             sh->ref_pic_list_order[0][i].idc = ( diff > 0 );
185             sh->ref_pic_list_order[0][i].arg = abs( diff ) - 1;
186             pred_frame_num = h->fref0[i]->i_frame_num;
187         }
188     }
189
190     sh->i_cabac_init_idc = param->i_cabac_init_idc;
191
192     sh->i_qp_delta = i_qp - pps->i_pic_init_qp;
193     sh->b_sp_for_swidth = 0;
194     sh->i_qs_delta = 0;
195
196     /* If effective qp <= 15, deblocking would have no effect anyway */
197     if( param->b_deblocking_filter
198         && ( h->mb.b_variable_qp
199         || 15 < i_qp + X264_MAX(param->i_deblocking_filter_alphac0, param->i_deblocking_filter_beta) ) )
200     {
201         sh->i_disable_deblocking_filter_idc = 0;
202     }
203     else
204     {
205         sh->i_disable_deblocking_filter_idc = 1;
206     }
207     sh->i_alpha_c0_offset = param->i_deblocking_filter_alphac0 << 1;
208     sh->i_beta_offset = param->i_deblocking_filter_beta << 1;
209 }
210
211 static void x264_slice_header_write( bs_t *s, x264_slice_header_t *sh, int i_nal_ref_idc )
212 {
213     int i;
214
215     bs_write_ue( s, sh->i_first_mb );
216     bs_write_ue( s, sh->i_type + 5 );   /* same type things */
217     bs_write_ue( s, sh->i_pps_id );
218     bs_write( s, sh->sps->i_log2_max_frame_num, sh->i_frame_num );
219
220     if( sh->i_idr_pic_id >= 0 ) /* NAL IDR */
221     {
222         bs_write_ue( s, sh->i_idr_pic_id );
223     }
224
225     if( sh->sps->i_poc_type == 0 )
226     {
227         bs_write( s, sh->sps->i_log2_max_poc_lsb, sh->i_poc_lsb );
228         if( sh->pps->b_pic_order && !sh->b_field_pic )
229         {
230             bs_write_se( s, sh->i_delta_poc_bottom );
231         }
232     }
233     else if( sh->sps->i_poc_type == 1 && !sh->sps->b_delta_pic_order_always_zero )
234     {
235         bs_write_se( s, sh->i_delta_poc[0] );
236         if( sh->pps->b_pic_order && !sh->b_field_pic )
237         {
238             bs_write_se( s, sh->i_delta_poc[1] );
239         }
240     }
241
242     if( sh->pps->b_redundant_pic_cnt )
243     {
244         bs_write_ue( s, sh->i_redundant_pic_cnt );
245     }
246
247     if( sh->i_type == SLICE_TYPE_B )
248     {
249         bs_write1( s, sh->b_direct_spatial_mv_pred );
250     }
251     if( sh->i_type == SLICE_TYPE_P || sh->i_type == SLICE_TYPE_SP || sh->i_type == SLICE_TYPE_B )
252     {
253         bs_write1( s, sh->b_num_ref_idx_override );
254         if( sh->b_num_ref_idx_override )
255         {
256             bs_write_ue( s, sh->i_num_ref_idx_l0_active - 1 );
257             if( sh->i_type == SLICE_TYPE_B )
258             {
259                 bs_write_ue( s, sh->i_num_ref_idx_l1_active - 1 );
260             }
261         }
262     }
263
264     /* ref pic list reordering */
265     if( sh->i_type != SLICE_TYPE_I )
266     {
267         bs_write1( s, sh->b_ref_pic_list_reordering_l0 );
268         if( sh->b_ref_pic_list_reordering_l0 )
269         {
270             for( i = 0; i < sh->i_num_ref_idx_l0_active; i++ )
271             {
272                 bs_write_ue( s, sh->ref_pic_list_order[0][i].idc );
273                 bs_write_ue( s, sh->ref_pic_list_order[0][i].arg );
274                         
275             }
276             bs_write_ue( s, 3 );
277         }
278     }
279     if( sh->i_type == SLICE_TYPE_B )
280     {
281         bs_write1( s, sh->b_ref_pic_list_reordering_l1 );
282         if( sh->b_ref_pic_list_reordering_l1 )
283         {
284             for( i = 0; i < sh->i_num_ref_idx_l1_active; i++ )
285             {
286                 bs_write_ue( s, sh->ref_pic_list_order[1][i].idc );
287                 bs_write_ue( s, sh->ref_pic_list_order[1][i].arg );
288             }
289             bs_write_ue( s, 3 );
290         }
291     }
292
293     if( ( sh->pps->b_weighted_pred && ( sh->i_type == SLICE_TYPE_P || sh->i_type == SLICE_TYPE_SP ) ) ||
294         ( sh->pps->b_weighted_bipred == 1 && sh->i_type == SLICE_TYPE_B ) )
295     {
296         /* FIXME */
297     }
298
299     if( i_nal_ref_idc != 0 )
300     {
301         if( sh->i_idr_pic_id >= 0 )
302         {
303             bs_write1( s, 0 );  /* no output of prior pics flag */
304             bs_write1( s, 0 );  /* long term reference flag */
305         }
306         else
307         {
308             bs_write1( s, 0 );  /* adaptive_ref_pic_marking_mode_flag */
309             /* FIXME */
310         }
311     }
312
313     if( sh->pps->b_cabac && sh->i_type != SLICE_TYPE_I )
314     {
315         bs_write_ue( s, sh->i_cabac_init_idc );
316     }
317     bs_write_se( s, sh->i_qp_delta );      /* slice qp delta */
318 #if 0
319     if( sh->i_type == SLICE_TYPE_SP || sh->i_type == SLICE_TYPE_SI )
320     {
321         if( sh->i_type == SLICE_TYPE_SP )
322         {
323             bs_write1( s, sh->b_sp_for_swidth );
324         }
325         bs_write_se( s, sh->i_qs_delta );
326     }
327 #endif
328
329     if( sh->pps->b_deblocking_filter_control )
330     {
331         bs_write_ue( s, sh->i_disable_deblocking_filter_idc );
332         if( sh->i_disable_deblocking_filter_idc != 1 )
333         {
334             bs_write_se( s, sh->i_alpha_c0_offset >> 1 );
335             bs_write_se( s, sh->i_beta_offset >> 1 );
336         }
337     }
338 }
339
340 /****************************************************************************
341  *
342  ****************************************************************************
343  ****************************** External API*********************************
344  ****************************************************************************
345  *
346  ****************************************************************************/
347
348 static int x264_validate_parameters( x264_t *h )
349 {
350     if( h->param.i_width <= 0 || h->param.i_height <= 0 )
351     {
352         x264_log( h, X264_LOG_ERROR, "invalid width x height (%dx%d)\n",
353                   h->param.i_width, h->param.i_height );
354         return -1;
355     }
356
357     if( h->param.i_width % 16 != 0 || h->param.i_height % 16 != 0 )
358     {
359         x264_log( h, X264_LOG_ERROR, "width %% 16 != 0 or height %% 16 != 0 (%dx%d)\n",
360                   h->param.i_width, h->param.i_height );
361         return -1;
362     }
363     if( h->param.i_csp != X264_CSP_I420 )
364     {
365         x264_log( h, X264_LOG_ERROR, "invalid CSP (only I420 supported)\n" );
366         return -1;
367     }
368
369     h->param.i_threads = x264_clip3( h->param.i_threads, 1, X264_SLICE_MAX );
370     h->param.i_threads = X264_MIN( h->param.i_threads, h->param.i_height / 16 );
371 #if !(HAVE_PTHREAD)
372     if( h->param.i_threads > 1 )
373     {
374         x264_log( h, X264_LOG_WARNING, "not compiled with pthread support!\n");
375         x264_log( h, X264_LOG_WARNING, "multislicing anyway, but you won't see any speed gain.\n" );
376     }
377 #endif
378
379     h->param.i_frame_reference = x264_clip3( h->param.i_frame_reference, 1, 16 );
380     if( h->param.i_keyint_max <= 0 )
381         h->param.i_keyint_max = 1;
382     h->param.i_keyint_min = x264_clip3( h->param.i_keyint_min, 1, h->param.i_keyint_max/2+1 );
383
384     h->param.i_bframe = x264_clip3( h->param.i_bframe, 0, X264_BFRAME_MAX );
385     h->param.i_bframe_bias = x264_clip3( h->param.i_bframe_bias, -90, 100 );
386     h->param.b_bframe_pyramid = h->param.b_bframe_pyramid && h->param.i_bframe > 1;
387     h->frames.i_delay = h->param.i_bframe;
388     h->frames.i_max_ref0 = h->param.i_frame_reference;
389     h->frames.i_max_ref1 = h->param.b_bframe_pyramid ? 2
390                             : h->param.i_bframe ? 1 : 0;
391     h->frames.i_max_dpb = X264_MIN( 16, h->frames.i_max_ref0 + h->frames.i_max_ref1 ) + 1;
392
393     h->param.i_deblocking_filter_alphac0 = x264_clip3( h->param.i_deblocking_filter_alphac0, -6, 6 );
394     h->param.i_deblocking_filter_beta    = x264_clip3( h->param.i_deblocking_filter_beta, -6, 6 );
395
396     h->param.i_cabac_init_idc = x264_clip3( h->param.i_cabac_init_idc, -1, 2 );
397     /* don't yet support merging of cabac stats */
398     if( h->param.i_threads > 1 && h->param.i_cabac_init_idc == -1 )
399         h->param.i_cabac_init_idc = 0;
400
401     if( h->param.analyse.i_me_method < X264_ME_DIA ||
402         h->param.analyse.i_me_method > X264_ME_ESA )
403         h->param.analyse.i_me_method = X264_ME_HEX;
404     if( h->param.analyse.i_me_range < 4 )
405         h->param.analyse.i_me_range = 4;
406     if( h->param.analyse.i_me_range > 16 && h->param.analyse.i_me_method <= X264_ME_HEX )
407         h->param.analyse.i_me_range = 16;
408     h->param.analyse.i_subpel_refine = x264_clip3( h->param.analyse.i_subpel_refine, 1, 5 );
409     if( !(h->param.analyse.inter & X264_ANALYSE_PSUB16x16) )
410         h->param.analyse.inter &= ~X264_ANALYSE_PSUB8x8;
411     if( !h->param.analyse.b_transform_8x8 )
412     {
413         h->param.analyse.inter &= ~X264_ANALYSE_I8x8;
414         h->param.analyse.intra &= ~X264_ANALYSE_I8x8;
415     }
416     h->param.analyse.i_chroma_qp_offset = x264_clip3(h->param.analyse.i_chroma_qp_offset, -12, 12);
417     h->param.analyse.i_mv_range = x264_clip3(h->param.analyse.i_mv_range, 32, 2048);
418
419     if( h->param.rc.f_qblur < 0 )
420         h->param.rc.f_qblur = 0;
421     if( h->param.rc.f_complexity_blur < 0 )
422         h->param.rc.f_complexity_blur = 0;
423     h->param.rc.i_qp_constant = x264_clip3(h->param.rc.i_qp_constant, 0, 51);
424
425     return 0;
426 }
427
428 /****************************************************************************
429  * x264_encoder_open:
430  ****************************************************************************/
431 x264_t *x264_encoder_open   ( x264_param_t *param )
432 {
433     x264_t *h = x264_malloc( sizeof( x264_t ) );
434     int i;
435
436     memset( h, 0, sizeof( x264_t ) );
437
438     /* Create a copy of param */
439     memcpy( &h->param, param, sizeof( x264_param_t ) );
440
441     if( x264_validate_parameters( h ) < 0 )
442     {
443         x264_free( h );
444         return NULL;
445     }
446
447     if( h->param.rc.psz_stat_out )
448         h->param.rc.psz_stat_out = strdup( h->param.rc.psz_stat_out );
449     if( h->param.rc.psz_stat_in )
450         h->param.rc.psz_stat_in = strdup( h->param.rc.psz_stat_in );
451     if( h->param.rc.psz_rc_eq )
452         h->param.rc.psz_rc_eq = strdup( h->param.rc.psz_rc_eq );
453
454     /* VUI */
455     if( h->param.vui.i_sar_width > 0 && h->param.vui.i_sar_height > 0 )
456     {
457         int i_w = param->vui.i_sar_width;
458         int i_h = param->vui.i_sar_height;
459         int a = i_w, b = i_h;
460
461         while( b != 0 )
462         {
463             int t = a;
464
465             a = b;
466             b = t % b;
467         }
468
469         i_w /= a;
470         i_h /= a;
471         while( i_w > 65535 || i_h > 65535 )
472         {
473             i_w /= 2;
474             i_h /= 2;
475         }
476
477         h->param.vui.i_sar_width = 0;
478         h->param.vui.i_sar_height = 0;
479         if( i_w == 0 || i_h == 0 )
480         {
481             x264_log( h, X264_LOG_ERROR, "cannot create valid sample aspect ratio\n" );
482         }
483         else if( i_w == i_h )
484         {
485             x264_log( h, X264_LOG_INFO, "no need for a SAR\n" );
486         }
487         else
488         {
489             x264_log( h, X264_LOG_INFO, "using SAR=%d/%d\n", i_w, i_h );
490             h->param.vui.i_sar_width = i_w;
491             h->param.vui.i_sar_height = i_h;
492         }
493     }
494
495
496     /* Init x264_t */
497     h->out.i_nal = 0;
498     h->out.i_bitstream = 1000000; /* FIXME estimate max size (idth/height) */
499     h->out.p_bitstream = x264_malloc( h->out.i_bitstream );
500
501     h->i_frame = 0;
502     h->i_frame_num = 0;
503     h->i_idr_pic_id = 0;
504
505     h->sps = &h->sps_array[0];
506     x264_sps_init( h->sps, 0, &h->param );
507
508     h->pps = &h->pps_array[0];
509     x264_pps_init( h->pps, 0, &h->param, h->sps);
510     
511     h->mb.i_mb_count = h->sps->i_mb_width * h->sps->i_mb_height;
512
513     /* Init frames. */
514     for( i = 0; i < X264_BFRAME_MAX + 3; i++ )
515     {
516         h->frames.current[i] = NULL;
517         h->frames.next[i]    = NULL;
518         h->frames.unused[i]  = NULL;
519     }
520     for( i = 0; i < 1 + h->frames.i_delay; i++ )
521     {
522         h->frames.unused[i] =  x264_frame_new( h );
523     }
524     for( i = 0; i < h->frames.i_max_dpb; i++ )
525     {
526         h->frames.reference[i] = x264_frame_new( h );
527     }
528     h->frames.reference[h->frames.i_max_dpb] = NULL;
529     h->frames.i_last_idr = - h->param.i_keyint_max;
530     h->frames.i_input    = 0;
531     h->frames.last_nonb  = NULL;
532
533     h->i_ref0 = 0;
534     h->i_ref1 = 0;
535
536     h->fdec = h->frames.reference[0];
537
538     /* init mb cache */
539     x264_macroblock_cache_init( h );
540
541     /* init cabac adaptive model */
542     x264_cabac_model_init( &h->cabac );
543
544     /* init CPU functions */
545     x264_predict_16x16_init( h->param.cpu, h->predict_16x16 );
546     x264_predict_8x8c_init( h->param.cpu, h->predict_8x8c );
547     x264_predict_8x8_init( h->param.cpu, h->predict_8x8 );
548     x264_predict_4x4_init( h->param.cpu, h->predict_4x4 );
549
550     x264_pixel_init( h->param.cpu, &h->pixf );
551     x264_dct_init( h->param.cpu, &h->dctf );
552     x264_mc_init( h->param.cpu, &h->mc );
553     x264_csp_init( h->param.cpu, h->param.i_csp, &h->csp );
554
555     /* rate control */
556     if( x264_ratecontrol_new( h ) < 0 )
557         return NULL;
558
559     x264_log( h, X264_LOG_INFO, "using cpu capabilities %s%s%s%s%s%s\n",
560              param->cpu&X264_CPU_MMX ? "MMX " : "",
561              param->cpu&X264_CPU_MMXEXT ? "MMXEXT " : "",
562              param->cpu&X264_CPU_SSE ? "SSE " : "",
563              param->cpu&X264_CPU_SSE2 ? "SSE2 " : "",
564              param->cpu&X264_CPU_3DNOW ? "3DNow! " : "",
565              param->cpu&X264_CPU_ALTIVEC ? "Altivec " : "" );
566
567     h->thread[0] = h;
568     for( i = 1; i < param->i_threads; i++ )
569         h->thread[i] = x264_malloc( sizeof(x264_t) );
570
571     return h;
572 }
573
574 /****************************************************************************
575  * x264_encoder_reconfig:
576  ****************************************************************************/
577 int x264_encoder_reconfig( x264_t *h, x264_param_t *param )
578 {
579     h->param.i_bframe_bias = param->i_bframe_bias;
580     h->param.i_deblocking_filter_alphac0 = param->i_deblocking_filter_alphac0;
581     h->param.i_deblocking_filter_beta    = param->i_deblocking_filter_beta;
582     h->param.analyse.i_me_method = param->analyse.i_me_method;
583     h->param.analyse.i_me_range = param->analyse.i_me_range;
584     h->param.analyse.i_subpel_refine = param->analyse.i_subpel_refine;
585     h->param.analyse.intra = param->analyse.intra;
586     h->param.analyse.inter = param->analyse.inter;
587     if( h->sps->b_direct8x8_inference && h->param.i_bframe
588         && h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_TEMPORAL )
589         h->param.analyse.inter &= ~X264_ANALYSE_PSUB8x8;
590     return x264_validate_parameters( h );
591 }
592
593 /* internal usage */
594 static void x264_nal_start( x264_t *h, int i_type, int i_ref_idc )
595 {
596     x264_nal_t *nal = &h->out.nal[h->out.i_nal];
597
598     nal->i_ref_idc = i_ref_idc;
599     nal->i_type    = i_type;
600
601     bs_align_0( &h->out.bs );   /* not needed */
602
603     nal->i_payload= 0;
604     nal->p_payload= &h->out.p_bitstream[bs_pos( &h->out.bs) / 8];
605 }
606 static void x264_nal_end( x264_t *h )
607 {
608     x264_nal_t *nal = &h->out.nal[h->out.i_nal];
609
610     bs_align_0( &h->out.bs );   /* not needed */
611
612     nal->i_payload = &h->out.p_bitstream[bs_pos( &h->out.bs)/8] - nal->p_payload;
613
614     h->out.i_nal++;
615 }
616
617 /****************************************************************************
618  * x264_encoder_headers:
619  ****************************************************************************/
620 int x264_encoder_headers( x264_t *h, x264_nal_t **pp_nal, int *pi_nal )
621 {
622     /* init bitstream context */
623     h->out.i_nal = 0;
624     bs_init( &h->out.bs, h->out.p_bitstream, h->out.i_bitstream );
625
626     /* Put SPS and PPS */
627     if( h->i_frame == 0 )
628     {
629         /* identify ourself */
630         x264_nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
631         x264_sei_version_write( &h->out.bs );
632         x264_nal_end( h );
633
634         /* generate sequence parameters */
635         x264_nal_start( h, NAL_SPS, NAL_PRIORITY_HIGHEST );
636         x264_sps_write( &h->out.bs, h->sps );
637         x264_nal_end( h );
638
639         /* generate picture parameters */
640         x264_nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
641         x264_pps_write( &h->out.bs, h->pps );
642         x264_nal_end( h );
643     }
644     /* now set output*/
645     *pi_nal = h->out.i_nal;
646     *pp_nal = &h->out.nal[0];
647
648     return 0;
649 }
650
651
652 static void x264_frame_put( x264_frame_t *list[X264_BFRAME_MAX], x264_frame_t *frame )
653 {
654     int i = 0;
655     while( list[i] ) i++;
656     list[i] = frame;
657 }
658
659 static void x264_frame_push( x264_frame_t *list[X264_BFRAME_MAX], x264_frame_t *frame )
660 {
661     int i = 0;
662     while( list[i] ) i++;
663     while( i-- )
664         list[i+1] = list[i];
665     list[0] = frame;
666 }
667
668 static x264_frame_t *x264_frame_get( x264_frame_t *list[X264_BFRAME_MAX+1] )
669 {
670     x264_frame_t *frame = list[0];
671     int i;
672     for( i = 0; list[i]; i++ )
673         list[i] = list[i+1];
674     return frame;
675 }
676
677 static void x264_frame_sort( x264_frame_t *list[X264_BFRAME_MAX+1], int b_dts )
678 {
679     int i, b_ok;
680     do {
681         b_ok = 1;
682         for( i = 0; list[i+1]; i++ )
683         {
684             int dtype = list[i]->i_type - list[i+1]->i_type;
685             int dtime = list[i]->i_frame - list[i+1]->i_frame;
686             int swap = b_dts ? dtype > 0 || ( dtype == 0 && dtime > 0 )
687                              : dtime > 0;
688             if( swap )
689             {
690                 x264_frame_t *tmp = list[i+1];
691                 list[i+1] = list[i];
692                 list[i] = tmp;
693                 b_ok = 0;
694             }
695         }
696     } while( !b_ok );
697 }
698 #define x264_frame_sort_dts(list) x264_frame_sort(list, 1)
699 #define x264_frame_sort_pts(list) x264_frame_sort(list, 0)
700
701 static inline void x264_reference_build_list( x264_t *h, int i_poc, int i_slice_type )
702 {
703     int i;
704     int b_ok;
705
706     /* build ref list 0/1 */
707     h->i_ref0 = 0;
708     h->i_ref1 = 0;
709     for( i = 1; i < h->frames.i_max_dpb; i++ )
710     {
711         if( h->frames.reference[i]->i_poc >= 0 )
712         {
713             if( h->frames.reference[i]->i_poc < i_poc )
714             {
715                 h->fref0[h->i_ref0++] = h->frames.reference[i];
716             }
717             else if( h->frames.reference[i]->i_poc > i_poc )
718             {
719                 h->fref1[h->i_ref1++] = h->frames.reference[i];
720             }
721         }
722     }
723
724     /* Order ref0 from higher to lower poc */
725     do
726     {
727         b_ok = 1;
728         for( i = 0; i < h->i_ref0 - 1; i++ )
729         {
730             if( h->fref0[i]->i_poc < h->fref0[i+1]->i_poc )
731             {
732                 x264_frame_t *tmp = h->fref0[i+1];
733
734                 h->fref0[i+1] = h->fref0[i];
735                 h->fref0[i] = tmp;
736                 b_ok = 0;
737                 break;
738             }
739         }
740     } while( !b_ok );
741     /* Order ref1 from lower to higher poc (bubble sort) for B-frame */
742     do
743     {
744         b_ok = 1;
745         for( i = 0; i < h->i_ref1 - 1; i++ )
746         {
747             if( h->fref1[i]->i_poc > h->fref1[i+1]->i_poc )
748             {
749                 x264_frame_t *tmp = h->fref1[i+1];
750
751                 h->fref1[i+1] = h->fref1[i];
752                 h->fref1[i] = tmp;
753                 b_ok = 0;
754                 break;
755             }
756         }
757     } while( !b_ok );
758
759     /* In the standard, a P-frame's ref list is sorted by frame_num.
760      * We use POC, but check whether explicit reordering is needed */
761     h->b_ref_reorder[0] =
762     h->b_ref_reorder[1] = 0;
763     if( i_slice_type == SLICE_TYPE_P )
764     {
765         for( i = 0; i < h->i_ref0 - 1; i++ )
766             if( h->fref0[i]->i_frame_num < h->fref0[i+1]->i_frame_num )
767             {
768                 h->b_ref_reorder[0] = 1;
769                 break;
770             }
771     }
772
773     h->i_ref1 = X264_MIN( h->i_ref1, h->frames.i_max_ref1 );
774     h->i_ref0 = X264_MIN( h->i_ref0, h->frames.i_max_ref0 );
775     h->i_ref0 = X264_MIN( h->i_ref0, 16 - h->i_ref1 );
776 }
777
778 static inline void x264_reference_update( x264_t *h )
779 {
780     int i;
781
782     /* apply deblocking filter to the current decoded picture */
783     if( !h->sh.i_disable_deblocking_filter_idc )
784     {
785         TIMER_START( i_mtime_filter );
786         x264_frame_deblocking_filter( h, h->sh.i_type );
787         TIMER_STOP( i_mtime_filter );
788     }
789     /* expand border */
790     x264_frame_expand_border( h->fdec );
791
792     /* create filtered images */
793     x264_frame_filter( h->param.cpu, h->fdec );
794
795     /* expand border of filtered images */
796     x264_frame_expand_border_filtered( h->fdec );
797
798     /* move lowres copy of the image to the ref frame */
799     for( i = 0; i < 4; i++)
800     {
801         uint8_t *tmp = h->fdec->lowres[i];
802         h->fdec->lowres[i] = h->fenc->lowres[i];
803         h->fenc->lowres[i] = tmp;
804     }
805
806     /* adaptive B decision needs a pointer, since it can't use the ref lists */
807     if( h->sh.i_type != SLICE_TYPE_B )
808         h->frames.last_nonb = h->fdec;
809
810     /* move frame in the buffer */
811     /* FIXME: override to forget earliest pts, not earliest dts */
812     h->fdec = h->frames.reference[h->frames.i_max_dpb-1];
813     for( i = h->frames.i_max_dpb-1; i > 0; i-- )
814     {
815         h->frames.reference[i] = h->frames.reference[i-1];
816     }
817     h->frames.reference[0] = h->fdec;
818 }
819
820 static inline void x264_reference_reset( x264_t *h )
821 {
822     int i;
823
824     /* reset ref pictures */
825     for( i = 1; i < h->frames.i_max_dpb; i++ )
826     {
827         h->frames.reference[i]->i_poc = -1;
828     }
829     h->frames.reference[0]->i_poc = 0;
830 }
831
832 static inline void x264_slice_init( x264_t *h, int i_nal_type, int i_slice_type, int i_global_qp )
833 {
834     /* ------------------------ Create slice header  ----------------------- */
835     if( i_nal_type == NAL_SLICE_IDR )
836     {
837         x264_slice_header_init( h, &h->sh, h->sps, h->pps, i_slice_type, h->i_idr_pic_id, h->i_frame_num - 1, i_global_qp );
838
839         /* increment id */
840         h->i_idr_pic_id = ( h->i_idr_pic_id + 1 ) % 65536;
841     }
842     else
843     {
844         x264_slice_header_init( h, &h->sh, h->sps, h->pps, i_slice_type, -1, h->i_frame_num - 1, i_global_qp );
845
846         /* always set the real higher num of ref frame used */
847         h->sh.b_num_ref_idx_override = 1;
848         h->sh.i_num_ref_idx_l0_active = h->i_ref0 <= 0 ? 1 : h->i_ref0;
849         h->sh.i_num_ref_idx_l1_active = h->i_ref1 <= 0 ? 1 : h->i_ref1;
850     }
851
852     h->fdec->i_frame_num = h->sh.i_frame_num;
853
854     if( h->sps->i_poc_type == 0 )
855     {
856         h->sh.i_poc_lsb = h->fdec->i_poc & ( (1 << h->sps->i_log2_max_poc_lsb) - 1 );
857         h->sh.i_delta_poc_bottom = 0;   /* XXX won't work for field */
858     }
859     else if( h->sps->i_poc_type == 1 )
860     {
861         /* FIXME TODO FIXME */
862     }
863     else
864     {
865         /* Nothing to do ? */
866     }
867
868     /* get adapative cabac model if needed */
869     if( h->param.b_cabac )
870     {
871         if( h->param.i_cabac_init_idc == -1 )
872         {
873             h->sh.i_cabac_init_idc = x264_cabac_model_get( &h->cabac, i_slice_type );
874         }
875     }
876
877     x264_macroblock_slice_init( h );
878 }
879
880 static int x264_slice_write( x264_t *h )
881 {
882     int i_skip;
883     int mb_xy;
884
885     /* init stats */
886     memset( &h->stat.frame, 0, sizeof(h->stat.frame) );
887
888     /* Slice */
889     x264_nal_start( h, h->i_nal_type, h->i_nal_ref_idc );
890
891     /* Slice header */
892     x264_slice_header_write( &h->out.bs, &h->sh, h->i_nal_ref_idc );
893     if( h->param.b_cabac )
894     {
895         /* alignment needed */
896         bs_align_1( &h->out.bs );
897
898         /* init cabac */
899         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 );
900         x264_cabac_encode_init ( &h->cabac, &h->out.bs );
901     }
902     h->mb.i_last_qp = h->pps->i_pic_init_qp + h->sh.i_qp_delta;
903     h->mb.i_last_dqp = 0;
904
905     for( mb_xy = h->sh.i_first_mb, i_skip = 0; mb_xy < h->sh.i_last_mb; mb_xy++ )
906     {
907         const int i_mb_y = mb_xy / h->sps->i_mb_width;
908         const int i_mb_x = mb_xy % h->sps->i_mb_width;
909
910         int mb_spos = bs_pos(&h->out.bs);
911
912         /* load cache */
913         x264_macroblock_cache_load( h, i_mb_x, i_mb_y );
914
915         /* analyse parameters
916          * Slice I: choose I_4x4 or I_16x16 mode
917          * Slice P: choose between using P mode or intra (4x4 or 16x16)
918          * */
919         TIMER_START( i_mtime_analyse );
920         x264_macroblock_analyse( h );
921         TIMER_STOP( i_mtime_analyse );
922
923         /* encode this macrobock -> be carefull it can change the mb type to P_SKIP if needed */
924         TIMER_START( i_mtime_encode );
925         x264_macroblock_encode( h );
926         TIMER_STOP( i_mtime_encode );
927
928         TIMER_START( i_mtime_write );
929         if( h->param.b_cabac )
930         {
931             if( mb_xy > h->sh.i_first_mb )
932                 x264_cabac_encode_terminal( &h->cabac, 0 );
933
934             if( IS_SKIP( h->mb.i_type ) )
935                 x264_cabac_mb_skip( h, 1 );
936             else
937             {
938                 if( h->sh.i_type != SLICE_TYPE_I )
939                     x264_cabac_mb_skip( h, 0 );
940                 x264_macroblock_write_cabac( h, &h->out.bs );
941             }
942         }
943         else
944         {
945             if( IS_SKIP( h->mb.i_type ) )
946                 i_skip++;
947             else
948             {
949                 if( h->sh.i_type != SLICE_TYPE_I )
950                 {
951                     bs_write_ue( &h->out.bs, i_skip );  /* skip run */
952                     i_skip = 0;
953                 }
954                 x264_macroblock_write_cavlc( h, &h->out.bs );
955             }
956         }
957         TIMER_STOP( i_mtime_write );
958
959 #if VISUALIZE
960         if( h->param.b_visualize )
961             x264_visualize_mb( h );
962 #endif
963
964         /* save cache */
965         x264_macroblock_cache_save( h );
966
967         h->stat.frame.i_mb_count[h->mb.i_type]++;
968
969         if( h->mb.b_variable_qp )
970             x264_ratecontrol_mb(h, bs_pos(&h->out.bs) - mb_spos);
971     }
972
973     if( h->param.b_cabac )
974     {
975         /* end of slice */
976         x264_cabac_encode_terminal( &h->cabac, 1 );
977     }
978     else if( i_skip > 0 )
979     {
980         bs_write_ue( &h->out.bs, i_skip );  /* last skip run */
981     }
982
983     if( h->param.b_cabac )
984     {
985         int i_cabac_word;
986         x264_cabac_encode_flush( &h->cabac );
987         /* TODO cabac stuffing things (p209) */
988         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;
989
990         while( i_cabac_word > 0 )
991         {
992             bs_write( &h->out.bs, 16, 0x0000 );
993             i_cabac_word--;
994         }
995     }
996     else
997     {
998         /* rbsp_slice_trailing_bits */
999         bs_rbsp_trailing( &h->out.bs );
1000     }
1001
1002     x264_nal_end( h );
1003
1004     /* Compute misc bits */
1005     h->stat.frame.i_misc_bits = bs_pos( &h->out.bs )
1006                               + NALU_OVERHEAD * 8
1007                               - h->stat.frame.i_itex_bits
1008                               - h->stat.frame.i_ptex_bits
1009                               - h->stat.frame.i_hdr_bits;
1010
1011     return 0;
1012 }
1013
1014 static inline int x264_slices_write( x264_t *h )
1015 {
1016     int i_frame_size;
1017
1018 #if VISUALIZE
1019     if( h->param.b_visualize )
1020         x264_visualize_init( h );
1021 #endif
1022
1023     if( h->param.i_threads == 1 )
1024     {
1025         x264_slice_write( h );
1026         i_frame_size = h->out.nal[h->out.i_nal-1].i_payload;
1027     }
1028     else
1029     {
1030         int i_nal = h->out.i_nal;
1031         int i_bs_size = h->out.i_bitstream / h->param.i_threads;
1032         int i;
1033         /* duplicate contexts */
1034         for( i = 0; i < h->param.i_threads; i++ )
1035         {
1036             x264_t *t = h->thread[i];
1037             if( i > 0 )
1038             {
1039                 memcpy( t, h, sizeof(x264_t) );
1040                 t->out.p_bitstream += i*i_bs_size;
1041                 bs_init( &t->out.bs, t->out.p_bitstream, i_bs_size );
1042             }
1043             t->sh.i_first_mb = (i    * h->sps->i_mb_height / h->param.i_threads) * h->sps->i_mb_width;
1044             t->sh.i_last_mb = ((i+1) * h->sps->i_mb_height / h->param.i_threads) * h->sps->i_mb_width;
1045             t->out.i_nal = i_nal + i;
1046         }
1047
1048         /* dispatch */
1049 #if HAVE_PTHREAD
1050         {
1051             pthread_t handles[X264_SLICE_MAX];
1052             void *status;
1053             for( i = 0; i < h->param.i_threads; i++ )
1054                 pthread_create( &handles[i], NULL, (void*)x264_slice_write, (void*)h->thread[i] );
1055             for( i = 0; i < h->param.i_threads; i++ )
1056                 pthread_join( handles[i], &status );
1057         }
1058 #else
1059         for( i = 0; i < h->param.i_threads; i++ )
1060             x264_slice_write( h->thread[i] );
1061 #endif
1062
1063         /* merge contexts */
1064         i_frame_size = h->out.nal[i_nal].i_payload;
1065         for( i = 1; i < h->param.i_threads; i++ )
1066         {
1067             int j;
1068             x264_t *t = h->thread[i];
1069             h->out.nal[i_nal+i] = t->out.nal[i_nal+i];
1070             i_frame_size += t->out.nal[i_nal+i].i_payload;
1071             // all entries in stat.frame are ints
1072             for( j = 0; j < sizeof(h->stat.frame) / sizeof(int); j++ )
1073                 ((int*)&h->stat.frame)[j] += ((int*)&t->stat.frame)[j];
1074         }
1075         h->out.i_nal = i_nal + h->param.i_threads;
1076     }
1077
1078 #if VISUALIZE
1079     if( h->param.b_visualize )
1080     {
1081         x264_visualize_show( h );
1082         x264_visualize_close( h );
1083     }
1084 #endif
1085
1086     return i_frame_size;
1087 }
1088
1089 /****************************************************************************
1090  * x264_encoder_encode:
1091  *  XXX: i_poc   : is the poc of the current given picture
1092  *       i_frame : is the number of the frame being coded
1093  *  ex:  type frame poc
1094  *       I      0   2*0
1095  *       P      1   2*3
1096  *       B      2   2*1
1097  *       B      3   2*2
1098  *       P      4   2*6
1099  *       B      5   2*4
1100  *       B      6   2*5
1101  ****************************************************************************/
1102 int     x264_encoder_encode( x264_t *h,
1103                              x264_nal_t **pp_nal, int *pi_nal,
1104                              x264_picture_t *pic_in,
1105                              x264_picture_t *pic_out )
1106 {
1107     x264_frame_t   *frame_psnr = h->fdec; /* just to keep the current decoded frame for psnr calculation */
1108     int     i_nal_type;
1109     int     i_nal_ref_idc;
1110     int     i_slice_type;
1111     int     i_frame_size;
1112
1113     int i;
1114
1115     int   i_global_qp;
1116
1117     char psz_message[80];
1118
1119     /* no data out */
1120     *pi_nal = 0;
1121     *pp_nal = NULL;
1122
1123
1124     /* ------------------- Setup new frame from picture -------------------- */
1125     TIMER_START( i_mtime_encode_frame );
1126     if( pic_in != NULL )
1127     {
1128         /* 1: Copy the picture to a frame and move it to a buffer */
1129         x264_frame_t *fenc = x264_frame_get( h->frames.unused );
1130
1131         x264_frame_copy_picture( h, fenc, pic_in );
1132
1133         fenc->i_frame = h->frames.i_input++;
1134
1135         x264_frame_put( h->frames.next, fenc );
1136
1137         x264_frame_init_lowres( h->param.cpu, fenc );
1138
1139         if( h->frames.i_input <= h->frames.i_delay )
1140         {
1141             /* Nothing yet to encode */
1142             /* waiting for filling bframe buffer */
1143             pic_out->i_type = X264_TYPE_AUTO;
1144             return 0;
1145         }
1146     }
1147
1148     if( h->frames.current[0] == NULL )
1149     {
1150         int bframes = 0;
1151         /* 2: Select frame types */
1152         if( h->frames.next[0] == NULL )
1153             return 0;
1154
1155         x264_slicetype_decide( h );
1156
1157         /* 3: move some B-frames and 1 non-B to encode queue */
1158         while( IS_X264_TYPE_B( h->frames.next[bframes]->i_type ) )
1159             bframes++;
1160         x264_frame_put( h->frames.current, x264_frame_get( &h->frames.next[bframes] ) );
1161         /* FIXME: when max B-frames > 3, BREF may no longer be centered after GOP closing */
1162         if( h->param.b_bframe_pyramid && bframes > 1 )
1163         {
1164             x264_frame_t *mid = x264_frame_get( &h->frames.next[bframes/2] );
1165             mid->i_type = X264_TYPE_BREF;
1166             x264_frame_put( h->frames.current, mid );
1167             bframes--;
1168         }
1169         while( bframes-- )
1170             x264_frame_put( h->frames.current, x264_frame_get( h->frames.next ) );
1171     }
1172     TIMER_STOP( i_mtime_encode_frame );
1173
1174     /* ------------------- Get frame to be encoded ------------------------- */
1175     /* 4: get picture to encode */
1176     h->fenc = x264_frame_get( h->frames.current );
1177     if( h->fenc == NULL )
1178     {
1179         /* Nothing yet to encode (ex: waiting for I/P with B frames) */
1180         /* waiting for filling bframe buffer */
1181         pic_out->i_type = X264_TYPE_AUTO;
1182         return 0;
1183     }
1184
1185 do_encode:
1186
1187     if( h->fenc->i_type == X264_TYPE_IDR )
1188     {
1189         h->frames.i_last_idr = h->fenc->i_frame;
1190     }
1191
1192     /* ------------------- Setup frame context ----------------------------- */
1193     /* 5: Init data dependant of frame type */
1194     TIMER_START( i_mtime_encode_frame );
1195     if( h->fenc->i_type == X264_TYPE_IDR )
1196     {
1197         /* reset ref pictures */
1198         x264_reference_reset( h );
1199
1200         i_nal_type    = NAL_SLICE_IDR;
1201         i_nal_ref_idc = NAL_PRIORITY_HIGHEST;
1202         i_slice_type = SLICE_TYPE_I;
1203     }
1204     else if( h->fenc->i_type == X264_TYPE_I )
1205     {
1206         i_nal_type    = NAL_SLICE;
1207         i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
1208         i_slice_type = SLICE_TYPE_I;
1209     }
1210     else if( h->fenc->i_type == X264_TYPE_P )
1211     {
1212         i_nal_type    = NAL_SLICE;
1213         i_nal_ref_idc = NAL_PRIORITY_HIGH; /* Not completely true but for now it is (as all I/P are kept as ref)*/
1214         i_slice_type = SLICE_TYPE_P;
1215     }
1216     else if( h->fenc->i_type == X264_TYPE_BREF )
1217     {
1218         i_nal_type    = NAL_SLICE;
1219         i_nal_ref_idc = NAL_PRIORITY_HIGH; /* maybe add MMCO to forget it? -> low */
1220         i_slice_type = SLICE_TYPE_B;
1221     }
1222     else    /* B frame */
1223     {
1224         i_nal_type    = NAL_SLICE;
1225         i_nal_ref_idc = NAL_PRIORITY_DISPOSABLE;
1226         i_slice_type = SLICE_TYPE_B;
1227     }
1228
1229     h->fdec->i_poc =
1230     h->fenc->i_poc = 2 * (h->fenc->i_frame - h->frames.i_last_idr);
1231     h->fdec->i_type = h->fenc->i_type;
1232     h->fdec->i_frame = h->fenc->i_frame;
1233     h->fenc->b_kept_as_ref =
1234     h->fdec->b_kept_as_ref = i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE;
1235
1236
1237
1238     /* ------------------- Init                ----------------------------- */
1239     /* build ref list 0/1 */
1240     x264_reference_build_list( h, h->fdec->i_poc, i_slice_type );
1241
1242     /* Init the rate control */
1243     x264_ratecontrol_start( h, i_slice_type, h->fenc->i_qpplus1 );
1244     i_global_qp = x264_ratecontrol_qp( h );
1245
1246     pic_out->i_qpplus1 =
1247     h->fdec->i_qpplus1 = i_global_qp + 1;
1248
1249     if( i_slice_type == SLICE_TYPE_B )
1250         x264_macroblock_bipred_init( h );
1251
1252     /* increase frame num but only once for B frame */
1253     if( i_slice_type != SLICE_TYPE_B || h->sh.i_type != SLICE_TYPE_B )
1254     {
1255         h->i_frame_num++;
1256     }
1257
1258     /* ------------------------ Create slice header  ----------------------- */
1259     x264_slice_init( h, i_nal_type, i_slice_type, i_global_qp );
1260
1261     /* ---------------------- Write the bitstream -------------------------- */
1262     /* Init bitstream context */
1263     h->out.i_nal = 0;
1264     bs_init( &h->out.bs, h->out.p_bitstream, h->out.i_bitstream );
1265
1266     if(h->param.b_aud){
1267         int pic_type;
1268
1269         if(i_slice_type == SLICE_TYPE_I)
1270             pic_type = 0;
1271         else if(i_slice_type == SLICE_TYPE_P)
1272             pic_type = 1;
1273         else if(i_slice_type == SLICE_TYPE_B)
1274             pic_type = 2;
1275         else
1276             pic_type = 7;
1277
1278         x264_nal_start(h, NAL_AUD, NAL_PRIORITY_DISPOSABLE);
1279         bs_write(&h->out.bs, 3, pic_type);
1280         bs_rbsp_trailing(&h->out.bs);
1281         x264_nal_end(h);
1282     }
1283
1284     h->i_nal_type = i_nal_type;
1285     h->i_nal_ref_idc = i_nal_ref_idc;
1286
1287     /* Write SPS and PPS */
1288     if( i_nal_type == NAL_SLICE_IDR )
1289     {
1290         if( h->fenc->i_frame == 0 )
1291         {
1292             /* identify ourself */
1293             x264_nal_start( h, NAL_SEI, NAL_PRIORITY_DISPOSABLE );
1294             x264_sei_version_write( &h->out.bs );
1295             x264_nal_end( h );
1296         }
1297
1298         /* generate sequence parameters */
1299         x264_nal_start( h, NAL_SPS, NAL_PRIORITY_HIGHEST );
1300         x264_sps_write( &h->out.bs, h->sps );
1301         x264_nal_end( h );
1302
1303         /* generate picture parameters */
1304         x264_nal_start( h, NAL_PPS, NAL_PRIORITY_HIGHEST );
1305         x264_pps_write( &h->out.bs, h->pps );
1306         x264_nal_end( h );
1307     }
1308
1309     /* Write frame */
1310     i_frame_size = x264_slices_write( h );
1311
1312     /* restore CPU state (before using float again) */
1313     x264_cpu_restore( h->param.cpu );
1314
1315     if( i_slice_type == SLICE_TYPE_P && !h->param.rc.b_stat_read 
1316         && h->param.i_scenecut_threshold >= 0 )
1317     {
1318         int i_mb_i = h->stat.frame.i_mb_count[I_4x4] + h->stat.frame.i_mb_count[I_16x16];
1319         int i_mb_p = h->stat.frame.i_mb_count[P_L0] + h->stat.frame.i_mb_count[P_8x8];
1320         int i_mb_s = h->stat.frame.i_mb_count[P_SKIP];
1321         int i_mb   = h->sps->i_mb_width * h->sps->i_mb_height;
1322         int64_t i_inter_cost = h->stat.frame.i_inter_cost;
1323         int64_t i_intra_cost = h->stat.frame.i_intra_cost;
1324
1325         float f_bias;
1326         int i_gop_size = h->fenc->i_frame - h->frames.i_last_idr;
1327         float f_thresh_max = h->param.i_scenecut_threshold / 100.0;
1328         /* magic numbers pulled out of thin air */
1329         float f_thresh_min = f_thresh_max * h->param.i_keyint_min
1330                              / ( h->param.i_keyint_max * 4 );
1331         if( h->param.i_keyint_min == h->param.i_keyint_max )
1332              f_thresh_min= f_thresh_max;
1333
1334         /* macroblock_analyse() doesn't further analyse skipped mbs,
1335          * so we have to guess their cost */
1336         if( i_mb_s < i_mb )
1337             i_intra_cost = i_intra_cost * i_mb / (i_mb - i_mb_s);
1338
1339         if( i_gop_size < h->param.i_keyint_min / 4 )
1340             f_bias = f_thresh_min / 4;
1341         else if( i_gop_size <= h->param.i_keyint_min )
1342             f_bias = f_thresh_min * i_gop_size / h->param.i_keyint_min;
1343         else
1344         {
1345             f_bias = f_thresh_min
1346                      + ( f_thresh_max - f_thresh_min )
1347                        * ( i_gop_size - h->param.i_keyint_min )
1348                        / ( h->param.i_keyint_max - h->param.i_keyint_min );
1349         }
1350         f_bias = X264_MIN( f_bias, 1.0 );
1351
1352         /* Bad P will be reencoded as I */
1353         if( i_mb_s < i_mb &&
1354             i_inter_cost >= (1.0 - f_bias) * i_intra_cost )
1355         {
1356             int b;
1357
1358             x264_log( h, X264_LOG_DEBUG, "scene cut at %d size=%d Icost:%.0f Pcost:%.0f ratio:%.3f bias=%.3f lastIDR:%d (I:%d P:%d Skip:%d)\n",
1359                       h->fenc->i_frame, i_frame_size,
1360                       (double)i_intra_cost, (double)i_inter_cost,
1361                       (double)i_inter_cost / i_intra_cost,
1362                       f_bias, i_gop_size,
1363                       i_mb_i, i_mb_p, i_mb_s );
1364
1365             /* Restore frame num */
1366             h->i_frame_num--;
1367
1368             for( b = 0; h->frames.current[b] && IS_X264_TYPE_B( h->frames.current[b]->i_type ); b++ );
1369             if( b > 0 )
1370             {
1371                 /* If using B-frames, force GOP to be closed.
1372                  * Even if this frame is going to be I and not IDR, forcing a
1373                  * P-frame before the scenecut will probably help compression.
1374                  * 
1375                  * We don't yet know exactly which frame is the scene cut, so
1376                  * we can't assign an I-frame. Instead, change the previous
1377                  * B-frame to P, and rearrange coding order. */
1378
1379                 if( h->param.b_bframe_adaptive || b > 1 )
1380                     h->fenc->i_type = X264_TYPE_AUTO;
1381                 x264_frame_sort_pts( h->frames.current );
1382                 x264_frame_push( h->frames.next, h->fenc );
1383                 h->fenc = h->frames.current[b-1];
1384                 h->frames.current[b-1] = NULL;
1385                 h->fenc->i_type = X264_TYPE_P;
1386                 x264_frame_sort_dts( h->frames.current );
1387             }
1388             /* Do IDR if needed */
1389             else if( i_gop_size >= h->param.i_keyint_min )
1390             {
1391                 x264_frame_t *tmp;
1392
1393                 /* Reset */
1394                 h->i_frame_num = 0;
1395
1396                 /* Reinit field of fenc */
1397                 h->fenc->i_type = X264_TYPE_IDR;
1398                 h->fenc->i_poc = 0;
1399
1400                 /* Put enqueued frames back in the pool */
1401                 while( (tmp = x264_frame_get( h->frames.current ) ) != NULL )
1402                     x264_frame_put( h->frames.next, tmp );
1403                 x264_frame_sort_pts( h->frames.next );
1404             }
1405             else
1406             {
1407                 h->fenc->i_type = X264_TYPE_I;
1408             }
1409             goto do_encode;
1410         }
1411     }
1412
1413     /* End bitstream, set output  */
1414     *pi_nal = h->out.i_nal;
1415     *pp_nal = h->out.nal;
1416
1417     /* Set output picture properties */
1418     if( i_slice_type == SLICE_TYPE_I )
1419         pic_out->i_type = i_nal_type == NAL_SLICE_IDR ? X264_TYPE_IDR : X264_TYPE_I;
1420     else if( i_slice_type == SLICE_TYPE_P )
1421         pic_out->i_type = X264_TYPE_P;
1422     else
1423         pic_out->i_type = X264_TYPE_B;
1424     pic_out->i_pts = h->fenc->i_pts;
1425
1426     pic_out->img.i_plane = h->fdec->i_plane;
1427     for(i = 0; i < 4; i++){
1428         pic_out->img.i_stride[i] = h->fdec->i_stride[i];
1429         pic_out->img.plane[i] = h->fdec->plane[i];
1430     }
1431
1432     /* ---------------------- Update encoder state ------------------------- */
1433     /* update cabac */
1434     if( h->param.b_cabac && h->param.i_cabac_init_idc == -1 )
1435     {
1436         x264_cabac_model_update( &h->cabac, i_slice_type, h->sh.pps->i_pic_init_qp + h->sh.i_qp_delta );
1437     }
1438
1439     /* handle references */
1440     if( i_nal_ref_idc != NAL_PRIORITY_DISPOSABLE )
1441     {
1442         x264_reference_update( h );
1443     }
1444
1445     /* increase frame count */
1446     h->i_frame++;
1447
1448     /* restore CPU state (before using float again) */
1449     /* XXX: not needed? (done above) */
1450     x264_cpu_restore( h->param.cpu );
1451
1452     /* update rc */
1453     x264_ratecontrol_end( h, i_frame_size * 8 );
1454
1455     x264_frame_put( h->frames.unused, h->fenc );
1456
1457     TIMER_STOP( i_mtime_encode_frame );
1458
1459     /* ---------------------- Compute/Print statistics --------------------- */
1460     /* Slice stat */
1461     h->stat.i_slice_count[i_slice_type]++;
1462     h->stat.i_slice_size[i_slice_type] += i_frame_size + NALU_OVERHEAD;
1463     h->stat.i_slice_qp[i_slice_type] += i_global_qp;
1464
1465     for( i = 0; i < 19; i++ )
1466     {
1467         h->stat.i_mb_count[h->sh.i_type][i] += h->stat.frame.i_mb_count[i];
1468     }
1469
1470     if( h->param.analyse.b_psnr )
1471     {
1472         int64_t i_sqe_y, i_sqe_u, i_sqe_v;
1473
1474         /* PSNR */
1475         i_sqe_y = x264_sqe( h, 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 );
1476         i_sqe_u = x264_sqe( h, 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);
1477         i_sqe_v = x264_sqe( h, 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);
1478
1479         h->stat.i_sqe_global[i_slice_type] += i_sqe_y + i_sqe_u + i_sqe_v;
1480         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 );
1481         h->stat.f_psnr_mean_y[i_slice_type] += x264_psnr( i_sqe_y, h->param.i_width * h->param.i_height );
1482         h->stat.f_psnr_mean_u[i_slice_type] += x264_psnr( i_sqe_u, h->param.i_width * h->param.i_height / 4 );
1483         h->stat.f_psnr_mean_v[i_slice_type] += x264_psnr( i_sqe_v, h->param.i_width * h->param.i_height / 4 );
1484
1485         snprintf( psz_message, 80, " PSNR Y:%2.2f U:%2.2f V:%2.2f",
1486                   x264_psnr( i_sqe_y, h->param.i_width * h->param.i_height ),
1487                   x264_psnr( i_sqe_u, h->param.i_width * h->param.i_height / 4),
1488                   x264_psnr( i_sqe_v, h->param.i_width * h->param.i_height / 4) );
1489         psz_message[79] = '\0';
1490     }
1491     else
1492     {
1493         psz_message[0] = '\0';
1494     }
1495     
1496     x264_log( h, X264_LOG_DEBUG,
1497                   "frame=%4d QP=%i NAL=%d Slice:%c Poc:%-3d I4:%-4d I8:%-4d I16:%-4d P:%-4d SKIP:%-4d size=%d bytes%s\n",
1498               h->i_frame - 1,
1499               i_global_qp,
1500               i_nal_ref_idc,
1501               i_slice_type == SLICE_TYPE_I ? 'I' : (i_slice_type == SLICE_TYPE_P ? 'P' : 'B' ),
1502               frame_psnr->i_poc,
1503               h->stat.frame.i_mb_count[I_4x4],
1504               h->stat.frame.i_mb_count[I_8x8],
1505               h->stat.frame.i_mb_count[I_16x16],
1506               h->stat.frame.i_mb_count_p,
1507               h->stat.frame.i_mb_count_skip,
1508               i_frame_size,
1509               psz_message );
1510
1511
1512 #ifdef DEBUG_MB_TYPE
1513 {
1514     static const char mb_chars[] = { 'i', 'i', 'I', 'C', 'P', '8', 'S',
1515         'D', '<', 'X', 'B', 'X', '>', 'B', 'B', 'B', 'B', '8', 'S' };
1516     int mb_xy;
1517     for( mb_xy = 0; mb_xy < h->sps->i_mb_width * h->sps->i_mb_height; mb_xy++ )
1518     {
1519         if( h->mb.type[mb_xy] < 19 && h->mb.type[mb_xy] >= 0 )
1520             fprintf( stderr, "%c ", mb_chars[ h->mb.type[mb_xy] ] );
1521         else
1522             fprintf( stderr, "? " );
1523
1524         if( (mb_xy+1) % h->sps->i_mb_width == 0 )
1525             fprintf( stderr, "\n" );
1526     }
1527 }
1528 #endif
1529
1530 #ifdef DEBUG_DUMP_FRAME
1531     /* Dump reconstructed frame */
1532     x264_frame_dump( h, frame_psnr, "fdec.yuv" );
1533 #endif
1534 #if 0
1535     if( h->i_ref0 > 0 )
1536     {
1537         x264_frame_dump( h, h->fref0[0], "ref0.yuv" );
1538     }
1539     if( h->i_ref1 > 0 )
1540     {
1541         x264_frame_dump( h, h->fref1[0], "ref1.yuv" );
1542     }
1543 #endif
1544     return 0;
1545 }
1546
1547 /****************************************************************************
1548  * x264_encoder_close:
1549  ****************************************************************************/
1550 void    x264_encoder_close  ( x264_t *h )
1551 {
1552 #ifdef DEBUG_BENCHMARK
1553     int64_t i_mtime_total = i_mtime_analyse + i_mtime_encode + i_mtime_write + i_mtime_filter + 1;
1554 #endif
1555     int64_t i_yuv_size = 3 * h->param.i_width * h->param.i_height / 2;
1556     int i;
1557
1558 #ifdef DEBUG_BENCHMARK
1559     x264_log( h, X264_LOG_INFO,
1560               "analyse=%d(%lldms) encode=%d(%lldms) write=%d(%lldms) filter=%d(%lldms)\n",
1561               (int)(100*i_mtime_analyse/i_mtime_total), i_mtime_analyse/1000,
1562               (int)(100*i_mtime_encode/i_mtime_total), i_mtime_encode/1000,
1563               (int)(100*i_mtime_write/i_mtime_total), i_mtime_write/1000,
1564               (int)(100*i_mtime_filter/i_mtime_total), i_mtime_filter/1000 );
1565 #endif
1566
1567     /* Slices used and PSNR */
1568     for( i=0; i<5; i++ )
1569     {
1570         static const int slice_order[] = { SLICE_TYPE_I, SLICE_TYPE_SI, SLICE_TYPE_P, SLICE_TYPE_SP, SLICE_TYPE_B };
1571         static const char *slice_name[] = { "P", "B", "I", "SP", "SI" };
1572         int i_slice = slice_order[i];
1573
1574         if( h->stat.i_slice_count[i_slice] > 0 )
1575         {
1576             const int i_count = h->stat.i_slice_count[i_slice];
1577             if( h->param.analyse.b_psnr )
1578             {
1579                 x264_log( h, X264_LOG_INFO,
1580                           "slice %s:%-4d Avg QP:%5.2f Avg size:%6.0f PSNR Mean Y:%5.2f U:%5.2f V:%5.2f Avg:%5.2f Global:%5.2f\n",
1581                           slice_name[i_slice],
1582                           i_count,
1583                           (double)h->stat.i_slice_qp[i_slice] / i_count,
1584                           (double)h->stat.i_slice_size[i_slice] / i_count,
1585                           h->stat.f_psnr_mean_y[i_slice] / i_count, h->stat.f_psnr_mean_u[i_slice] / i_count, h->stat.f_psnr_mean_v[i_slice] / i_count,
1586                           h->stat.f_psnr_average[i_slice] / i_count,
1587                           x264_psnr( h->stat.i_sqe_global[i_slice], i_count * i_yuv_size ) );
1588             }
1589             else
1590             {
1591                 x264_log( h, X264_LOG_INFO,
1592                           "slice %s:%-4d Avg QP:%5.2f Avg size:%6.0f\n",
1593                           slice_name[i_slice],
1594                           i_count,
1595                           (double)h->stat.i_slice_qp[i_slice] / i_count,
1596                           (double)h->stat.i_slice_size[i_slice] / i_count );
1597             }
1598         }
1599     }
1600
1601     /* MB types used */
1602     if( h->stat.i_slice_count[SLICE_TYPE_I] > 0 )
1603     {
1604         const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_I];
1605         const double i_count = h->stat.i_slice_count[SLICE_TYPE_I] * h->mb.i_mb_count / 100.0;
1606         x264_log( h, X264_LOG_INFO,
1607                   "slice I   Avg I4x4:%.1f%%  I8x8:%.1f%%  I16x16:%.1f%%\n",
1608                   i_mb_count[I_4x4]  / i_count,
1609                   i_mb_count[I_8x8]  / i_count,
1610                   i_mb_count[I_16x16]/ i_count );
1611     }
1612     if( h->stat.i_slice_count[SLICE_TYPE_P] > 0 )
1613     {
1614         const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_P];
1615         const double i_count = h->stat.i_slice_count[SLICE_TYPE_P] * h->mb.i_mb_count / 100.0;
1616         x264_log( h, X264_LOG_INFO,
1617                   "slice P   Avg I4x4:%.1f%%  I8x8:%.1f%%  I16x16:%.1f%%  P:%.1f%%  P8x8:%.1f%%  PSKIP:%.1f%%\n",
1618                   i_mb_count[I_4x4]  / i_count,
1619                   i_mb_count[I_8x8]  / i_count,
1620                   i_mb_count[I_16x16]/ i_count,
1621                   i_mb_count[P_L0]   / i_count,
1622                   i_mb_count[P_8x8]  / i_count,
1623                   i_mb_count[P_SKIP] / i_count );
1624     }
1625     if( h->stat.i_slice_count[SLICE_TYPE_B] > 0 )
1626     {
1627         const int64_t *i_mb_count = h->stat.i_mb_count[SLICE_TYPE_B];
1628         const double i_count = h->stat.i_slice_count[SLICE_TYPE_B] * h->mb.i_mb_count / 100.0;
1629         x264_log( h, X264_LOG_INFO,
1630                   "slice B   Avg I4x4:%.1f%%  I8x8:%.1f%%  I16x16:%.1f%%  P:%.1f%%  B:%.1f%%  B8x8:%.1f%%  DIRECT:%.1f%%  BSKIP:%.1f%%\n",
1631                   i_mb_count[I_4x4]    / i_count,
1632                   i_mb_count[I_8x8]    / i_count,
1633                   i_mb_count[I_16x16]  / i_count,
1634                   (i_mb_count[B_L0_L0] + i_mb_count[B_L1_L1] + i_mb_count[B_L1_L0] + i_mb_count[B_L0_L1]) / i_count,
1635                   (i_mb_count[B_BI_BI] + i_mb_count[B_L0_BI] + i_mb_count[B_L1_BI] + i_mb_count[B_BI_L0] + i_mb_count[B_BI_L1]) / i_count,
1636                   i_mb_count[B_8x8]    / i_count,
1637                   i_mb_count[B_DIRECT] / i_count,
1638                   i_mb_count[B_SKIP]   / i_count );
1639     }
1640
1641     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 )
1642     {
1643         const int i_count = h->stat.i_slice_count[SLICE_TYPE_I] +
1644                             h->stat.i_slice_count[SLICE_TYPE_P] +
1645                             h->stat.i_slice_count[SLICE_TYPE_B];
1646         float fps = (float) h->param.i_fps_num / h->param.i_fps_den;
1647
1648         if( h->param.analyse.b_psnr )
1649             x264_log( h, X264_LOG_INFO,
1650                       "PSNR Mean Y:%5.2f U:%5.2f V:%5.2f Avg:%5.2f Global:%5.2f kb/s:%.1f\n",
1651                       (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,
1652                       (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,
1653                       (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,
1654
1655                       (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,
1656
1657                       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],
1658                                  i_count * i_yuv_size ),
1659                       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 );
1660         else
1661             x264_log( h, X264_LOG_INFO,
1662                       "kb/s:%.1f\n",
1663                       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 );
1664     }
1665
1666     /* frames */
1667     for( i = 0; i < X264_BFRAME_MAX + 3; i++ )
1668     {
1669         if( h->frames.current[i] ) x264_frame_delete( h->frames.current[i] );
1670         if( h->frames.next[i] )    x264_frame_delete( h->frames.next[i] );
1671         if( h->frames.unused[i] )  x264_frame_delete( h->frames.unused[i] );
1672     }
1673     /* ref frames */
1674     for( i = 0; i < h->frames.i_max_dpb; i++ )
1675     {
1676         x264_frame_delete( h->frames.reference[i] );
1677     }
1678
1679     /* rc */
1680     x264_ratecontrol_delete( h );
1681
1682     /* param */
1683     if( h->param.rc.psz_stat_out )
1684         free( h->param.rc.psz_stat_out );
1685     if( h->param.rc.psz_stat_in )
1686         free( h->param.rc.psz_stat_in );
1687     if( h->param.rc.psz_rc_eq )
1688         free( h->param.rc.psz_rc_eq );
1689
1690     x264_macroblock_cache_end( h );
1691     x264_free( h->out.p_bitstream );
1692     for( i = 1; i < h->param.i_threads; i++ )
1693         x264_free( h->thread[i] );
1694     x264_free( h );
1695 }
1696