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