]> git.sesse.net Git - x264/blob - common/common.h
wrong reference frames were used with refs>=14 + pyramid (regression in r607)
[x264] / common / common.h
1 /*****************************************************************************
2  * common.h: h264 encoder
3  *****************************************************************************
4  * Copyright (C) 2003 Laurent Aimar
5  * $Id: common.h,v 1.1 2004/06/03 19:27:06 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 #ifndef _COMMON_H
25 #define _COMMON_H 1
26
27 #ifdef HAVE_STDINT_H
28 #include <stdint.h>
29 #else
30 #include <inttypes.h>
31 #endif
32 #include <stdarg.h>
33 #include <stdlib.h>
34 #include <assert.h>
35
36 #ifdef _MSC_VER
37 #define snprintf _snprintf
38 #define X264_VERSION "" // no configure script for msvc
39 #endif
40
41 /* alloca: force 16byte alignment */
42 #ifdef _MSC_VER
43 #define x264_alloca(x) (void*)(((intptr_t)_alloca((x)+15)+15)&~15)
44 #else
45 #define x264_alloca(x) (void*)(((intptr_t) alloca((x)+15)+15)&~15)
46 #endif
47
48 /* threads */
49 #if defined(__WIN32__) && defined(HAVE_PTHREAD)
50 #include <pthread.h>
51 #define USE_CONDITION_VAR
52
53 #elif defined(SYS_BEOS)
54 #include <kernel/OS.h>
55 #define pthread_t               thread_id
56 #define pthread_create(t,u,f,d) { *(t)=spawn_thread(f,"",10,d); \
57                                   resume_thread(*(t)); }
58 #define pthread_join(t,s)       { long tmp; \
59                                   wait_for_thread(t,(s)?(long*)(s):&tmp); }
60 #ifndef usleep
61 #define usleep(t)               snooze(t)
62 #endif
63 #define HAVE_PTHREAD 1
64
65 #elif defined(HAVE_PTHREAD)
66 #include <pthread.h>
67 #define USE_CONDITION_VAR
68 #else
69 #define pthread_t               int
70 #define pthread_create(t,u,f,d)
71 #define pthread_join(t,s)
72 #endif //SYS_*
73
74 #ifndef USE_CONDITION_VAR
75 #define pthread_mutex_t         int
76 #define pthread_mutex_init(m,f)
77 #define pthread_mutex_destroy(m)
78 #define pthread_mutex_lock(m)
79 #define pthread_mutex_unlock(m)
80 #define pthread_cond_t          int
81 #define pthread_cond_init(c,f)
82 #define pthread_cond_destroy(c)
83 #define pthread_cond_broadcast(c)
84 #define pthread_cond_wait(c,m)  usleep(100)
85 #endif
86
87 /****************************************************************************
88  * Macros
89  ****************************************************************************/
90 #define X264_MIN(a,b) ( (a)<(b) ? (a) : (b) )
91 #define X264_MAX(a,b) ( (a)>(b) ? (a) : (b) )
92 #define X264_MIN3(a,b,c) X264_MIN((a),X264_MIN((b),(c)))
93 #define X264_MAX3(a,b,c) X264_MAX((a),X264_MAX((b),(c)))
94 #define X264_MIN4(a,b,c,d) X264_MIN((a),X264_MIN3((b),(c),(d)))
95 #define X264_MAX4(a,b,c,d) X264_MAX((a),X264_MAX3((b),(c),(d)))
96 #define XCHG(type,a,b) { type t = a; a = b; b = t; }
97 #define FIX8(f) ((int)(f*(1<<8)+.5))
98
99 #ifndef offsetof
100 #define offsetof(T,F) ((unsigned int)((char *)&((T *)0)->F))
101 #endif
102
103 #if defined(__GNUC__) && (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ > 0)
104 #define UNUSED __attribute__((unused))
105 #else
106 #define UNUSED
107 #endif
108
109 #define CHECKED_MALLOC( var, size )\
110 {\
111     var = x264_malloc( size );\
112     if( !var )\
113     {\
114         x264_log( h, X264_LOG_ERROR, "malloc failed\n" );\
115         goto fail;\
116     }\
117 }
118
119 #define X264_BFRAME_MAX 16
120 #define X264_THREAD_MAX 16
121 #define X264_SLICE_MAX 4
122 #define X264_NAL_MAX (4 + X264_SLICE_MAX)
123 #define X264_THREAD_HEIGHT 24 // number of pixels (per thread) in progress at any given time. could theoretically be as low as 22
124
125 /****************************************************************************
126  * Includes
127  ****************************************************************************/
128 #include "x264.h"
129 #include "bs.h"
130 #include "set.h"
131 #include "predict.h"
132 #include "pixel.h"
133 #include "mc.h"
134 #include "frame.h"
135 #include "dct.h"
136 #include "cabac.h"
137 #include "csp.h"
138 #include "quant.h"
139
140 /****************************************************************************
141  * Generals functions
142  ****************************************************************************/
143 /* x264_malloc : will do or emulate a memalign
144  * XXX you HAVE TO use x264_free for buffer allocated
145  * with x264_malloc
146  */
147 void *x264_malloc( int );
148 void *x264_realloc( void *p, int i_size );
149 void  x264_free( void * );
150
151 /* x264_slurp_file: malloc space for the whole file and read it */
152 char *x264_slurp_file( const char *filename );
153
154 /* mdate: return the current date in microsecond */
155 int64_t x264_mdate( void );
156
157 /* x264_param2string: return a (malloced) string containing most of
158  * the encoding options */
159 char *x264_param2string( x264_param_t *p, int b_res );
160
161 /* log */
162 void x264_log( x264_t *h, int i_level, const char *psz_fmt, ... );
163
164 void x264_reduce_fraction( int *n, int *d );
165
166 static inline int x264_clip3( int v, int i_min, int i_max )
167 {
168     return ( (v < i_min) ? i_min : (v > i_max) ? i_max : v );
169 }
170
171 static inline float x264_clip3f( float v, float f_min, float f_max )
172 {
173     return ( (v < f_min) ? f_min : (v > f_max) ? f_max : v );
174 }
175
176 static inline int x264_median( int a, int b, int c )
177 {
178     int min = a, max =a;
179     if( b < min )
180         min = b;
181     else
182         max = b;    /* no need to do 'b > max' (more consuming than always doing affectation) */
183
184     if( c < min )
185         min = c;
186     else if( c > max )
187         max = c;
188
189     return a + b + c - min - max;
190 }
191
192
193 /****************************************************************************
194  *
195  ****************************************************************************/
196 enum slice_type_e
197 {
198     SLICE_TYPE_P  = 0,
199     SLICE_TYPE_B  = 1,
200     SLICE_TYPE_I  = 2,
201     SLICE_TYPE_SP = 3,
202     SLICE_TYPE_SI = 4
203 };
204
205 static const char slice_type_to_char[] = { 'P', 'B', 'I', 'S', 'S' };
206
207 typedef struct
208 {
209     x264_sps_t *sps;
210     x264_pps_t *pps;
211
212     int i_type;
213     int i_first_mb;
214     int i_last_mb;
215
216     int i_pps_id;
217
218     int i_frame_num;
219
220     int b_mbaff;
221     int b_field_pic;
222     int b_bottom_field;
223
224     int i_idr_pic_id;   /* -1 if nal_type != 5 */
225
226     int i_poc_lsb;
227     int i_delta_poc_bottom;
228
229     int i_delta_poc[2];
230     int i_redundant_pic_cnt;
231
232     int b_direct_spatial_mv_pred;
233
234     int b_num_ref_idx_override;
235     int i_num_ref_idx_l0_active;
236     int i_num_ref_idx_l1_active;
237
238     int b_ref_pic_list_reordering_l0;
239     int b_ref_pic_list_reordering_l1;
240     struct {
241         int idc;
242         int arg;
243     } ref_pic_list_order[2][16];
244
245     int i_cabac_init_idc;
246
247     int i_qp;
248     int i_qp_delta;
249     int b_sp_for_swidth;
250     int i_qs_delta;
251
252     /* deblocking filter */
253     int i_disable_deblocking_filter_idc;
254     int i_alpha_c0_offset;
255     int i_beta_offset;
256
257 } x264_slice_header_t;
258
259 /* From ffmpeg
260  */
261 #define X264_SCAN8_SIZE (6*8)
262 #define X264_SCAN8_0 (4+1*8)
263
264 static const int x264_scan8[16+2*4] =
265 {
266     /* Luma */
267     4+1*8, 5+1*8, 4+2*8, 5+2*8,
268     6+1*8, 7+1*8, 6+2*8, 7+2*8,
269     4+3*8, 5+3*8, 4+4*8, 5+4*8,
270     6+3*8, 7+3*8, 6+4*8, 7+4*8,
271
272     /* Cb */
273     1+1*8, 2+1*8,
274     1+2*8, 2+2*8,
275
276     /* Cr */
277     1+4*8, 2+4*8,
278     1+5*8, 2+5*8,
279 };
280 /*
281    0 1 2 3 4 5 6 7
282  0
283  1   B B   L L L L
284  2   B B   L L L L
285  3         L L L L
286  4   R R   L L L L
287  5   R R
288 */
289
290 typedef struct x264_ratecontrol_t   x264_ratecontrol_t;
291 typedef struct x264_vlc_table_t     x264_vlc_table_t;
292
293 struct x264_t
294 {
295     /* encoder parameters */
296     x264_param_t    param;
297
298     x264_t          *thread[X264_THREAD_MAX];
299     pthread_t       thread_handle;
300     int             b_thread_active;
301     int             i_thread_phase; /* which thread to use for the next frame */
302
303     /* bitstream output */
304     struct
305     {
306         int         i_nal;
307         x264_nal_t  nal[X264_NAL_MAX];
308         int         i_bitstream;    /* size of p_bitstream */
309         uint8_t     *p_bitstream;   /* will hold data for all nal */
310         bs_t        bs;
311         int         i_frame_size;
312     } out;
313
314     /* frame number/poc */
315     int             i_frame;
316
317     int             i_frame_offset; /* decoding only */
318     int             i_frame_num;    /* decoding only */
319     int             i_poc_msb;      /* decoding only */
320     int             i_poc_lsb;      /* decoding only */
321     int             i_poc;          /* decoding only */
322
323     int             i_thread_num;   /* threads only */
324     int             i_nal_type;     /* threads only */
325     int             i_nal_ref_idc;  /* threads only */
326
327     /* We use only one SPS and one PPS */
328     x264_sps_t      sps_array[1];
329     x264_sps_t      *sps;
330     x264_pps_t      pps_array[1];
331     x264_pps_t      *pps;
332     int             i_idr_pic_id;
333
334     int             (*dequant4_mf[4])[4][4]; /* [4][6][4][4] */
335     int             (*dequant8_mf[2])[8][8]; /* [2][6][8][8] */
336     int             (*quant4_mf[4])[4][4];   /* [4][6][4][4] */
337     int             (*quant8_mf[2])[8][8];   /* [2][6][8][8] */
338     int             (*unquant4_mf[4])[16];   /* [4][52][16] */
339     int             (*unquant8_mf[2])[64];   /* [2][52][64] */
340
341     uint32_t        nr_residual_sum[2][64];
342     uint32_t        nr_offset[2][64];
343     uint32_t        nr_count[2];
344
345     /* Slice header */
346     x264_slice_header_t sh;
347
348     /* cabac context */
349     x264_cabac_t    cabac;
350
351     struct
352     {
353         /* Frames to be encoded (whose types have been decided) */
354         x264_frame_t *current[X264_BFRAME_MAX+3];
355         /* Temporary buffer (frames types not yet decided) */
356         x264_frame_t *next[X264_BFRAME_MAX+3];
357         /* Unused frames */
358         x264_frame_t *unused[X264_BFRAME_MAX + X264_THREAD_MAX*2 + 16+4];
359         /* For adaptive B decision */
360         x264_frame_t *last_nonb;
361
362         /* frames used for reference + sentinels */
363         x264_frame_t *reference[16+2];
364
365         int i_last_idr; /* Frame number of the last IDR */
366
367         int i_input;    /* Number of input frames already accepted */
368
369         int i_max_dpb;  /* Number of frames allocated in the decoded picture buffer */
370         int i_max_ref0;
371         int i_max_ref1;
372         int i_delay;    /* Number of frames buffered for B reordering */
373         int b_have_lowres;  /* Whether 1/2 resolution luma planes are being used */
374     } frames;
375
376     /* current frame being encoded */
377     x264_frame_t    *fenc;
378
379     /* frame being reconstructed */
380     x264_frame_t    *fdec;
381
382     /* references lists */
383     int             i_ref0;
384     x264_frame_t    *fref0[16+3];     /* ref list 0 */
385     int             i_ref1;
386     x264_frame_t    *fref1[16+3];     /* ref list 1 */
387     int             b_ref_reorder[2];
388
389
390
391     /* Current MB DCT coeffs */
392     struct
393     {
394         DECLARE_ALIGNED( int, luma16x16_dc[16], 16 );
395         DECLARE_ALIGNED( int, chroma_dc[2][4], 16 );
396         // FIXME merge with union
397         DECLARE_ALIGNED( int, luma8x8[4][64], 16 );
398         union
399         {
400             DECLARE_ALIGNED( int, residual_ac[15], 16 );
401             DECLARE_ALIGNED( int, luma4x4[16], 16 );
402         } block[16+8];
403     } dct;
404
405     /* MB table and cache for current frame/mb */
406     struct
407     {
408         int     i_mb_count;                 /* number of mbs in a frame */
409
410         /* Strides */
411         int     i_mb_stride;
412         int     i_b8_stride;
413         int     i_b4_stride;
414
415         /* Current index */
416         int     i_mb_x;
417         int     i_mb_y;
418         int     i_mb_xy;
419         int     i_b8_xy;
420         int     i_b4_xy;
421         
422         /* Search parameters */
423         int     i_me_method;
424         int     i_subpel_refine;
425         int     b_chroma_me;
426         int     b_trellis;
427         int     b_noise_reduction;
428
429         int     b_interlaced;
430
431         /* Inverted luma quantization deadzone */
432         int     i_luma_deadzone[2]; // {inter, intra}
433
434         /* Allowed qpel MV range to stay within the picture + emulated edge pixels */
435         int     mv_min[2];
436         int     mv_max[2];
437         /* Subpel MV range for motion search.
438          * same mv_min/max but includes levels' i_mv_range. */
439         int     mv_min_spel[2];
440         int     mv_max_spel[2];
441         /* Fullpel MV range for motion search */
442         int     mv_min_fpel[2];
443         int     mv_max_fpel[2];
444
445         /* neighboring MBs */
446         unsigned int i_neighbour;
447         unsigned int i_neighbour8[4];       /* neighbours of each 8x8 or 4x4 block that are available */
448         unsigned int i_neighbour4[16];      /* at the time the block is coded */
449         int     i_mb_type_top; 
450         int     i_mb_type_left; 
451         int     i_mb_type_topleft; 
452         int     i_mb_type_topright; 
453         int     i_mb_prev_xy;
454         int     i_mb_top_xy;
455
456         /* mb table */
457         int8_t  *type;                      /* mb type */
458         int8_t  *qp;                        /* mb qp */
459         int16_t *cbp;                       /* mb cbp: 0x0?: luma, 0x?0: chroma, 0x100: luma dc, 0x0200 and 0x0400: chroma dc  (all set for PCM)*/
460         int8_t  (*intra4x4_pred_mode)[7];   /* intra4x4 pred mode. for non I4x4 set to I_PRED_4x4_DC(2) */
461         uint8_t (*non_zero_count)[16+4+4];  /* nzc. for I_PCM set to 16 */
462         int8_t  *chroma_pred_mode;          /* chroma_pred_mode. cabac only. for non intra I_PRED_CHROMA_DC(0) */
463         int16_t (*mv[2])[2];                /* mb mv. set to 0 for intra mb */
464         int16_t (*mvd[2])[2];               /* mb mv difference with predict. set to 0 if intra. cabac only */
465         int8_t   *ref[2];                   /* mb ref. set to -1 if non used (intra or Lx only) */
466         int16_t (*mvr[2][32])[2];           /* 16x16 mv for each possible ref */
467         int8_t  *skipbp;                    /* block pattern for SKIP or DIRECT (sub)mbs. B-frames + cabac only */
468         int8_t  *mb_transform_size;         /* transform_size_8x8_flag of each mb */
469         uint8_t *intra_border_backup[2][3]; /* bottom pixels of the previous mb row, used for intra prediction after the framebuffer has been deblocked */
470
471         /* current value */
472         int     i_type;
473         int     i_partition;
474         int     i_sub_partition[4];
475         int     b_transform_8x8;
476
477         int     i_cbp_luma;
478         int     i_cbp_chroma;
479
480         int     i_intra16x16_pred_mode;
481         int     i_chroma_pred_mode;
482
483         struct
484         {
485             /* space for p_fenc and p_fdec */
486 #define FENC_STRIDE 16
487 #define FDEC_STRIDE 32
488             DECLARE_ALIGNED( uint8_t, fenc_buf[24*FENC_STRIDE], 16 );
489             DECLARE_ALIGNED( uint8_t, fdec_buf[27*FDEC_STRIDE], 16 );
490
491             /* pointer over mb of the frame to be compressed */
492             uint8_t *p_fenc[3];
493
494             /* pointer over mb of the frame to be reconstructed  */
495             uint8_t *p_fdec[3];
496
497             /* pointer over mb of the references */
498             int i_fref[2];
499             uint8_t *p_fref[2][32][4+2]; /* last: lN, lH, lV, lHV, cU, cV */
500             uint16_t *p_integral[2][16];
501
502             /* fref stride */
503             int     i_stride[3];
504         } pic;
505
506         /* cache */
507         struct
508         {
509             /* real intra4x4_pred_mode if I_4X4 or I_8X8, I_PRED_4x4_DC if mb available, -1 if not */
510             int     intra4x4_pred_mode[X264_SCAN8_SIZE];
511
512             /* i_non_zero_count if available else 0x80 */
513             int     non_zero_count[X264_SCAN8_SIZE];
514
515             /* -1 if unused, -2 if unavailable */
516             int8_t  ref[2][X264_SCAN8_SIZE];
517
518             /* 0 if not available */
519             int16_t mv[2][X264_SCAN8_SIZE][2];
520             int16_t mvd[2][X264_SCAN8_SIZE][2];
521
522             /* 1 if SKIP or DIRECT. set only for B-frames + CABAC */
523             int8_t  skip[X264_SCAN8_SIZE];
524
525             int16_t direct_mv[2][X264_SCAN8_SIZE][2];
526             int8_t  direct_ref[2][X264_SCAN8_SIZE];
527             int     pskip_mv[2];
528
529             /* number of neighbors (top and left) that used 8x8 dct */
530             int     i_neighbour_transform_size;
531             int     b_transform_8x8_allowed;
532             int     i_neighbour_interlaced;
533         } cache;
534
535         /* */
536         int     i_qp;       /* current qp */
537         int     i_chroma_qp;
538         int     i_last_qp;  /* last qp */
539         int     i_last_dqp; /* last delta qp */
540         int     b_variable_qp; /* whether qp is allowed to vary per macroblock */
541         int     b_lossless;
542         int     b_direct_auto_read; /* take stats for --direct auto from the 2pass log */
543         int     b_direct_auto_write; /* analyse direct modes, to use and/or save */
544
545         /* B_direct and weighted prediction */
546         int     dist_scale_factor[16][2];
547         int     bipred_weight[32][4];
548         /* maps fref1[0]'s ref indices into the current list0 */
549         int     map_col_to_list0_buf[2]; // for negative indices
550         int     map_col_to_list0[16];
551     } mb;
552
553     /* rate control encoding only */
554     x264_ratecontrol_t *rc;
555
556     /* stats */
557     struct
558     {
559         /* Current frame stats */
560         struct
561         {
562             /* Headers bits (MV+Ref+MB Block Type */
563             int i_hdr_bits;
564             /* Texture bits (Intra/Predicted) */
565             int i_itex_bits;
566             int i_ptex_bits;
567             /* ? */
568             int i_misc_bits;
569             /* MB type counts */
570             int i_mb_count[19];
571             int i_mb_count_i;
572             int i_mb_count_p;
573             int i_mb_count_skip;
574             int i_mb_count_8x8dct[2];
575             int i_mb_count_size[7];
576             int i_mb_count_ref[32];
577             /* Estimated (SATD) cost as Intra/Predicted frame */
578             /* XXX: both omit the cost of MBs coded as P_SKIP */
579             int i_intra_cost;
580             int i_inter_cost;
581             int i_mbs_analysed;
582             /* Adaptive direct mv pred */
583             int i_direct_score[2];
584         } frame;
585
586         /* Cumulated stats */
587
588         /* per slice info */
589         int     i_slice_count[5];
590         int64_t i_slice_size[5];
591         int     i_slice_qp[5];
592         /* */
593         int64_t i_sqe_global[5];
594         float   f_psnr_average[5];
595         float   f_psnr_mean_y[5];
596         float   f_psnr_mean_u[5];
597         float   f_psnr_mean_v[5];
598         float   f_ssim_mean_y[5];
599         /* */
600         int64_t i_mb_count[5][19];
601         int64_t i_mb_count_8x8dct[2];
602         int64_t i_mb_count_size[2][7];
603         int64_t i_mb_count_ref[2][32];
604         /* */
605         int     i_direct_score[2];
606         int     i_direct_frames[2];
607
608     } stat;
609
610     /* CPU functions dependents */
611     x264_predict_t      predict_16x16[4+3];
612     x264_predict_t      predict_8x8c[4+3];
613     x264_predict8x8_t   predict_8x8[9+3];
614     x264_predict_t      predict_4x4[9+3];
615
616     x264_pixel_function_t pixf;
617     x264_mc_functions_t   mc;
618     x264_dct_function_t   dctf;
619     x264_zigzag_function_t zigzagf;
620     x264_csp_function_t   csp;
621     x264_quant_function_t quantf;
622     x264_deblock_function_t loopf;
623
624     /* vlc table for decoding purpose only */
625     x264_vlc_table_t *x264_coeff_token_lookup[5];
626     x264_vlc_table_t *x264_level_prefix_lookup;
627     x264_vlc_table_t *x264_total_zeros_lookup[15];
628     x264_vlc_table_t *x264_total_zeros_dc_lookup[3];
629     x264_vlc_table_t *x264_run_before_lookup[7];
630
631 #if VISUALIZE
632     struct visualize_t *visualize;
633 #endif
634 };
635
636 // included at the end because it needs x264_t
637 #include "macroblock.h"
638
639 #endif
640