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