]> git.sesse.net Git - x264/blob - common/common.h
efb25be81796c3cbf9c00b9affcb53087b97cfbf
[x264] / common / common.h
1 /*****************************************************************************
2  * common.h: misc common functions
3  *****************************************************************************
4  * Copyright (C) 2003-2010 x264 project
5  *
6  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
7  *          Loren Merritt <lorenm@u.washington.edu>
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., 51 Franklin Street, Fifth Floor, Boston, MA  02111, USA.
22  *
23  * This program is also available under a commercial proprietary license.
24  * For more information, contact us at licensing@x264.com.
25  *****************************************************************************/
26
27 #ifndef X264_COMMON_H
28 #define X264_COMMON_H
29
30 /****************************************************************************
31  * Macros
32  ****************************************************************************/
33 #define X264_MIN(a,b) ( (a)<(b) ? (a) : (b) )
34 #define X264_MAX(a,b) ( (a)>(b) ? (a) : (b) )
35 #define X264_MIN3(a,b,c) X264_MIN((a),X264_MIN((b),(c)))
36 #define X264_MAX3(a,b,c) X264_MAX((a),X264_MAX((b),(c)))
37 #define X264_MIN4(a,b,c,d) X264_MIN((a),X264_MIN3((b),(c),(d)))
38 #define X264_MAX4(a,b,c,d) X264_MAX((a),X264_MAX3((b),(c),(d)))
39 #define XCHG(type,a,b) do{ type t = a; a = b; b = t; } while(0)
40 #define IS_DISPOSABLE(type) ( type == X264_TYPE_B )
41 #define FIX8(f) ((int)(f*(1<<8)+.5))
42 #define ALIGN(x,a) (((x)+((a)-1))&~((a)-1))
43
44 #define CHECKED_MALLOC( var, size )\
45 do {\
46     var = x264_malloc( size );\
47     if( !var )\
48         goto fail;\
49 } while( 0 )
50 #define CHECKED_MALLOCZERO( var, size )\
51 do {\
52     CHECKED_MALLOC( var, size );\
53     memset( var, 0, size );\
54 } while( 0 )
55
56 #define X264_BFRAME_MAX 16
57 #define X264_REF_MAX 16
58 #define X264_THREAD_MAX 128
59 #define X264_PCM_COST (384*BIT_DEPTH+16)
60 #define X264_LOOKAHEAD_MAX 250
61 #define QP_BD_OFFSET (6*(BIT_DEPTH-8))
62 #define QP_MAX (51+QP_BD_OFFSET)
63 #define QP_MAX_MAX (51+2*6)
64 #define LAMBDA_MAX (91 << (BIT_DEPTH-8))
65 #define PIXEL_MAX ((1 << BIT_DEPTH)-1)
66 // arbitrary, but low because SATD scores are 1/4 normal
67 #define X264_LOOKAHEAD_QP (12+QP_BD_OFFSET)
68
69 // number of pixels (per thread) in progress at any given time.
70 // 16 for the macroblock in progress + 3 for deblocking + 3 for motion compensation filter + 2 for extra safety
71 #define X264_THREAD_HEIGHT 24
72
73 /* WEIGHTP_FAKE is set when mb_tree & psy are enabled, but normal weightp is disabled
74  * (such as in baseline). It checks for fades in lookahead and adjusts qp accordingly
75  * to increase quality. Defined as (-1) so that if(i_weighted_pred > 0) is true only when
76  * real weights are being used. */
77
78 #define X264_WEIGHTP_FAKE (-1)
79
80 #define NALU_OVERHEAD 5 // startcode + NAL type costs 5 bytes per frame
81 #define FILLER_OVERHEAD (NALU_OVERHEAD+1)
82
83 /****************************************************************************
84  * Includes
85  ****************************************************************************/
86 #include "osdep.h"
87 #include <stdarg.h>
88 #include <stddef.h>
89 #include <stdlib.h>
90 #include <string.h>
91 #include <assert.h>
92 #include <limits.h>
93
94 /* Unions for type-punning.
95  * Mn: load or store n bits, aligned, native-endian
96  * CPn: copy n bits, aligned, native-endian
97  * we don't use memcpy for CPn because memcpy's args aren't assumed to be aligned */
98 typedef union { uint16_t i; uint8_t  c[2]; } MAY_ALIAS x264_union16_t;
99 typedef union { uint32_t i; uint16_t b[2]; uint8_t  c[4]; } MAY_ALIAS x264_union32_t;
100 typedef union { uint64_t i; uint32_t a[2]; uint16_t b[4]; uint8_t c[8]; } MAY_ALIAS x264_union64_t;
101 typedef struct { uint64_t i[2]; } x264_uint128_t;
102 typedef union { x264_uint128_t i; uint64_t a[2]; uint32_t b[4]; uint16_t c[8]; uint8_t d[16]; } MAY_ALIAS x264_union128_t;
103 #define M16(src) (((x264_union16_t*)(src))->i)
104 #define M32(src) (((x264_union32_t*)(src))->i)
105 #define M64(src) (((x264_union64_t*)(src))->i)
106 #define M128(src) (((x264_union128_t*)(src))->i)
107 #define M128_ZERO ((x264_uint128_t){{0,0}})
108 #define CP16(dst,src) M16(dst) = M16(src)
109 #define CP32(dst,src) M32(dst) = M32(src)
110 #define CP64(dst,src) M64(dst) = M64(src)
111 #define CP128(dst,src) M128(dst) = M128(src)
112
113 #if X264_HIGH_BIT_DEPTH
114     typedef uint16_t pixel;
115     typedef uint64_t pixel4;
116     typedef int32_t  dctcoef;
117
118 #   define PIXEL_SPLAT_X4(x) ((x)*0x0001000100010001ULL)
119 #   define MPIXEL_X4(src) M64(src)
120 #else
121     typedef uint8_t  pixel;
122     typedef uint32_t pixel4;
123     typedef int16_t  dctcoef;
124
125 #   define PIXEL_SPLAT_X4(x) ((x)*0x01010101U)
126 #   define MPIXEL_X4(src) M32(src)
127 #endif
128
129 #define CPPIXEL_X4(dst,src) MPIXEL_X4(dst) = MPIXEL_X4(src)
130
131 #define X264_SCAN8_SIZE (6*8)
132 #define X264_SCAN8_LUMA_SIZE (5*8)
133 #define X264_SCAN8_0 (4+1*8)
134
135 static const int x264_scan8[16+2*4+3] =
136 {
137     /* Luma */
138     4+1*8, 5+1*8, 4+2*8, 5+2*8,
139     6+1*8, 7+1*8, 6+2*8, 7+2*8,
140     4+3*8, 5+3*8, 4+4*8, 5+4*8,
141     6+3*8, 7+3*8, 6+4*8, 7+4*8,
142
143     /* Cb */
144     1+1*8, 2+1*8,
145     1+2*8, 2+2*8,
146
147     /* Cr */
148     1+4*8, 2+4*8,
149     1+5*8, 2+5*8,
150
151     /* Luma DC */
152     4+5*8,
153
154     /* Chroma DC */
155     6+5*8, 7+5*8
156 };
157 /*
158    0 1 2 3 4 5 6 7
159  0
160  1   B B   L L L L
161  2   B B   L L L L
162  3         L L L L
163  4   R R   L L L L
164  5   R R   Dy  DuDv
165 */
166
167 #include "x264.h"
168 #include "bitstream.h"
169 #include "set.h"
170 #include "predict.h"
171 #include "pixel.h"
172 #include "mc.h"
173 #include "frame.h"
174 #include "dct.h"
175 #include "cabac.h"
176 #include "quant.h"
177 #include "cpu.h"
178 #include "threadpool.h"
179
180 /****************************************************************************
181  * General functions
182  ****************************************************************************/
183 /* x264_malloc : will do or emulate a memalign
184  * you have to use x264_free for buffers allocated with x264_malloc */
185 void *x264_malloc( int );
186 void  x264_free( void * );
187
188 /* x264_slurp_file: malloc space for the whole file and read it */
189 char *x264_slurp_file( const char *filename );
190
191 /* mdate: return the current date in microsecond */
192 int64_t x264_mdate( void );
193
194 /* x264_param2string: return a (malloced) string containing most of
195  * the encoding options */
196 char *x264_param2string( x264_param_t *p, int b_res );
197
198 /* log */
199 void x264_log( x264_t *h, int i_level, const char *psz_fmt, ... );
200
201 void x264_reduce_fraction( uint32_t *n, uint32_t *d );
202 void x264_reduce_fraction64( uint64_t *n, uint64_t *d );
203 void x264_init_vlc_tables();
204
205 static ALWAYS_INLINE pixel x264_clip_pixel( int x )
206 {
207     return ( (x & ~PIXEL_MAX) ? (-x)>>31 & PIXEL_MAX : x );
208 }
209
210 static ALWAYS_INLINE int x264_clip3( int v, int i_min, int i_max )
211 {
212     return ( (v < i_min) ? i_min : (v > i_max) ? i_max : v );
213 }
214
215 static ALWAYS_INLINE double x264_clip3f( double v, double f_min, double f_max )
216 {
217     return ( (v < f_min) ? f_min : (v > f_max) ? f_max : v );
218 }
219
220 static ALWAYS_INLINE int x264_median( int a, int b, int c )
221 {
222     int t = (a-b)&((a-b)>>31);
223     a -= t;
224     b += t;
225     b -= (b-c)&((b-c)>>31);
226     b += (a-b)&((a-b)>>31);
227     return b;
228 }
229
230 static ALWAYS_INLINE void x264_median_mv( int16_t *dst, int16_t *a, int16_t *b, int16_t *c )
231 {
232     dst[0] = x264_median( a[0], b[0], c[0] );
233     dst[1] = x264_median( a[1], b[1], c[1] );
234 }
235
236 static ALWAYS_INLINE int x264_predictor_difference( int16_t (*mvc)[2], intptr_t i_mvc )
237 {
238     int sum = 0;
239     for( int i = 0; i < i_mvc-1; i++ )
240     {
241         sum += abs( mvc[i][0] - mvc[i+1][0] )
242              + abs( mvc[i][1] - mvc[i+1][1] );
243     }
244     return sum;
245 }
246
247 static ALWAYS_INLINE uint16_t x264_cabac_mvd_sum( uint8_t *mvdleft, uint8_t *mvdtop )
248 {
249     int amvd0 = abs(mvdleft[0]) + abs(mvdtop[0]);
250     int amvd1 = abs(mvdleft[1]) + abs(mvdtop[1]);
251     amvd0 = (amvd0 > 2) + (amvd0 > 32);
252     amvd1 = (amvd1 > 2) + (amvd1 > 32);
253     return amvd0 + (amvd1<<8);
254 }
255
256 static void ALWAYS_INLINE x264_predictor_roundclip( int16_t (*dst)[2], int16_t (*mvc)[2], int i_mvc, int mv_x_min, int mv_x_max, int mv_y_min, int mv_y_max )
257 {
258     for( int i = 0; i < i_mvc; i++ )
259     {
260         int mx = (mvc[i][0] + 2) >> 2;
261         int my = (mvc[i][1] + 2) >> 2;
262         dst[i][0] = x264_clip3( mx, mv_x_min, mv_x_max );
263         dst[i][1] = x264_clip3( my, mv_y_min, mv_y_max );
264     }
265 }
266
267 extern const uint8_t x264_exp2_lut[64];
268 extern const float x264_log2_lut[128];
269 extern const float x264_log2_lz_lut[32];
270
271 /* Not a general-purpose function; multiplies input by -1/6 to convert
272  * qp to qscale. */
273 static ALWAYS_INLINE int x264_exp2fix8( float x )
274 {
275     int i = x*(-64.f/6.f) + 512.5f;
276     if( i < 0 ) return 0;
277     if( i > 1023 ) return 0xffff;
278     return (x264_exp2_lut[i&63]+256) << (i>>6) >> 8;
279 }
280
281 static ALWAYS_INLINE float x264_log2( uint32_t x )
282 {
283     int lz = x264_clz( x );
284     return x264_log2_lut[(x<<lz>>24)&0x7f] + x264_log2_lz_lut[lz];
285 }
286
287 /****************************************************************************
288  *
289  ****************************************************************************/
290 enum slice_type_e
291 {
292     SLICE_TYPE_P  = 0,
293     SLICE_TYPE_B  = 1,
294     SLICE_TYPE_I  = 2,
295 };
296
297 static const char slice_type_to_char[] = { 'P', 'B', 'I' };
298
299 enum sei_payload_type_e
300 {
301     SEI_BUFFERING_PERIOD       = 0,
302     SEI_PIC_TIMING             = 1,
303     SEI_PAN_SCAN_RECT          = 2,
304     SEI_FILLER                 = 3,
305     SEI_USER_DATA_REGISTERED   = 4,
306     SEI_USER_DATA_UNREGISTERED = 5,
307     SEI_RECOVERY_POINT         = 6,
308 };
309
310 typedef struct
311 {
312     x264_sps_t *sps;
313     x264_pps_t *pps;
314
315     int i_type;
316     int i_first_mb;
317     int i_last_mb;
318
319     int i_pps_id;
320
321     int i_frame_num;
322
323     int b_mbaff;
324     int b_field_pic;
325     int b_bottom_field;
326
327     int i_idr_pic_id;   /* -1 if nal_type != 5 */
328
329     int i_poc;
330     int i_delta_poc_bottom;
331
332     int i_delta_poc[2];
333     int i_redundant_pic_cnt;
334
335     int b_direct_spatial_mv_pred;
336
337     int b_num_ref_idx_override;
338     int i_num_ref_idx_l0_active;
339     int i_num_ref_idx_l1_active;
340
341     int b_ref_pic_list_reordering_l0;
342     int b_ref_pic_list_reordering_l1;
343     struct
344     {
345         int idc;
346         int arg;
347     } ref_pic_list_order[2][X264_REF_MAX];
348
349     /* P-frame weighting */
350     x264_weight_t weight[X264_REF_MAX*2][3];
351
352     int i_mmco_remove_from_end;
353     int i_mmco_command_count;
354     struct /* struct for future expansion */
355     {
356         int i_difference_of_pic_nums;
357         int i_poc;
358     } mmco[X264_REF_MAX];
359
360     int i_cabac_init_idc;
361
362     int i_qp;
363     int i_qp_delta;
364     int b_sp_for_swidth;
365     int i_qs_delta;
366
367     /* deblocking filter */
368     int i_disable_deblocking_filter_idc;
369     int i_alpha_c0_offset;
370     int i_beta_offset;
371
372 } x264_slice_header_t;
373
374 typedef struct x264_lookahead_t
375 {
376     volatile uint8_t              b_exit_thread;
377     uint8_t                       b_thread_active;
378     uint8_t                       b_analyse_keyframe;
379     int                           i_last_keyframe;
380     int                           i_slicetype_length;
381     x264_frame_t                  *last_nonb;
382     x264_pthread_t                thread_handle;
383     x264_sync_frame_list_t        ifbuf;
384     x264_sync_frame_list_t        next;
385     x264_sync_frame_list_t        ofbuf;
386 } x264_lookahead_t;
387
388 typedef struct x264_ratecontrol_t   x264_ratecontrol_t;
389
390 struct x264_t
391 {
392     /* encoder parameters */
393     x264_param_t    param;
394
395     x264_t          *thread[X264_THREAD_MAX+1];
396     int             b_thread_active;
397     int             i_thread_phase; /* which thread to use for the next frame */
398     int             i_threadslice_start; /* first row in this thread slice */
399     int             i_threadslice_end; /* row after the end of this thread slice */
400     x264_threadpool_t *threadpool;
401
402     /* bitstream output */
403     struct
404     {
405         int         i_nal;
406         int         i_nals_allocated;
407         x264_nal_t  *nal;
408         int         i_bitstream;    /* size of p_bitstream */
409         uint8_t     *p_bitstream;   /* will hold data for all nal */
410         bs_t        bs;
411     } out;
412
413     uint8_t *nal_buffer;
414     int      nal_buffer_size;
415
416     /**** thread synchronization starts here ****/
417
418     /* frame number/poc */
419     int             i_frame;
420     int             i_frame_num;
421
422     int             i_thread_frames; /* Number of different frames being encoded by threads;
423                                       * 1 when sliced-threads is on. */
424     int             i_nal_type;
425     int             i_nal_ref_idc;
426
427     int             i_disp_fields;  /* Number of displayed fields (both coded and implied via pic_struct) */
428     int             i_disp_fields_last_frame;
429     int             i_prev_duration; /* Duration of previous frame */
430     int             i_coded_fields; /* Number of coded fields (both coded and implied via pic_struct) */
431     int             i_cpb_delay;    /* Equal to number of fields preceding this field
432                                      * since last buffering_period SEI */
433     int             i_coded_fields_lookahead; /* Use separate counters for lookahead */
434     int             i_cpb_delay_lookahead;
435
436     int             b_queued_intra_refresh;
437     int64_t         i_last_idr_pts;
438
439     /* We use only one SPS and one PPS */
440     x264_sps_t      sps_array[1];
441     x264_sps_t      *sps;
442     x264_pps_t      pps_array[1];
443     x264_pps_t      *pps;
444     int             i_idr_pic_id;
445
446     /* Timebase multiplier for DTS compression */
447     int             i_dts_compress_multiplier;
448
449     /* quantization matrix for decoding, [cqm][qp%6][coef] */
450     int             (*dequant4_mf[4])[16];   /* [4][6][16] */
451     int             (*dequant8_mf[2])[64];   /* [2][6][64] */
452     /* quantization matrix for trellis, [cqm][qp][coef] */
453     int             (*unquant4_mf[4])[16];   /* [4][52][16] */
454     int             (*unquant8_mf[2])[64];   /* [2][52][64] */
455     /* quantization matrix for deadzone */
456     uint16_t        (*quant4_mf[4])[16];     /* [4][52][16] */
457     uint16_t        (*quant8_mf[2])[64];     /* [2][52][64] */
458     uint16_t        (*quant4_bias[4])[16];   /* [4][52][16] */
459     uint16_t        (*quant8_bias[2])[64];   /* [2][52][64] */
460
461     /* mv/ref cost arrays.  Indexed by lambda instead of
462      * qp because, due to rounding, some quantizers share
463      * lambdas.  This saves memory. */
464     uint16_t *cost_mv[LAMBDA_MAX+1];
465     uint16_t *cost_mv_fpel[LAMBDA_MAX+1][4];
466
467     const uint8_t   *chroma_qp_table; /* includes both the nonlinear luma->chroma mapping and chroma_qp_offset */
468
469     /* Slice header */
470     x264_slice_header_t sh;
471
472     /* cabac context */
473     x264_cabac_t    cabac;
474
475     struct
476     {
477         /* Frames to be encoded (whose types have been decided) */
478         x264_frame_t **current;
479         /* Unused frames: 0 = fenc, 1 = fdec */
480         x264_frame_t **unused[2];
481
482         /* Unused blank frames (for duplicates) */
483         x264_frame_t **blank_unused;
484
485         /* frames used for reference + sentinels */
486         x264_frame_t *reference[X264_REF_MAX+2];
487
488         int i_last_keyframe;       /* Frame number of the last keyframe */
489         int i_last_idr;            /* Frame number of the last IDR (not RP)*/
490         int i_poc_last_open_gop;   /* Poc of the I frame of the last open-gop. The value
491                                     * is only assigned during the period between that
492                                     * I frame and the next P or I frame, else -1 */
493
494         int i_input;    /* Number of input frames already accepted */
495
496         int i_max_dpb;  /* Number of frames allocated in the decoded picture buffer */
497         int i_max_ref0;
498         int i_max_ref1;
499         int i_delay;    /* Number of frames buffered for B reordering */
500         int     i_bframe_delay;
501         int64_t i_bframe_delay_time;
502         int64_t i_init_delta;
503         int64_t i_prev_reordered_pts[2];
504         int64_t i_largest_pts;
505         int64_t i_second_largest_pts;
506         int b_have_lowres;  /* Whether 1/2 resolution luma planes are being used */
507         int b_have_sub8x8_esa;
508     } frames;
509
510     /* current frame being encoded */
511     x264_frame_t    *fenc;
512
513     /* frame being reconstructed */
514     x264_frame_t    *fdec;
515
516     /* references lists */
517     int             i_ref0;
518     x264_frame_t    *fref0[X264_REF_MAX+3];     /* ref list 0 */
519     int             i_ref1;
520     x264_frame_t    *fref1[X264_REF_MAX+3];     /* ref list 1 */
521     int             b_ref_reorder[2];
522
523     /* hrd */
524     int initial_cpb_removal_delay;
525     int initial_cpb_removal_delay_offset;
526     int64_t i_reordered_pts_delay;
527
528     /* Current MB DCT coeffs */
529     struct
530     {
531         ALIGNED_16( dctcoef luma16x16_dc[16] );
532         ALIGNED_16( dctcoef chroma_dc[2][4] );
533         // FIXME share memory?
534         ALIGNED_16( dctcoef luma8x8[4][64] );
535         ALIGNED_16( dctcoef luma4x4[16+8][16] );
536     } dct;
537
538     /* MB table and cache for current frame/mb */
539     struct
540     {
541         int     i_mb_width;
542         int     i_mb_height;
543         int     i_mb_count;                 /* number of mbs in a frame */
544
545         /* Strides */
546         int     i_mb_stride;
547         int     i_b8_stride;
548         int     i_b4_stride;
549
550         /* Current index */
551         int     i_mb_x;
552         int     i_mb_y;
553         int     i_mb_xy;
554         int     i_b8_xy;
555         int     i_b4_xy;
556
557         /* Search parameters */
558         int     i_me_method;
559         int     i_subpel_refine;
560         int     b_chroma_me;
561         int     b_trellis;
562         int     b_noise_reduction;
563         int     b_dct_decimate;
564         int     i_psy_rd; /* Psy RD strength--fixed point value*/
565         int     i_psy_trellis; /* Psy trellis strength--fixed point value*/
566
567         int     b_interlaced;
568
569         /* Allowed qpel MV range to stay within the picture + emulated edge pixels */
570         int     mv_min[2];
571         int     mv_max[2];
572         /* Subpel MV range for motion search.
573          * same mv_min/max but includes levels' i_mv_range. */
574         int     mv_min_spel[2];
575         int     mv_max_spel[2];
576         /* Fullpel MV range for motion search */
577         int     mv_min_fpel[2];
578         int     mv_max_fpel[2];
579
580         /* neighboring MBs */
581         unsigned int i_neighbour;
582         unsigned int i_neighbour8[4];       /* neighbours of each 8x8 or 4x4 block that are available */
583         unsigned int i_neighbour4[16];      /* at the time the block is coded */
584         unsigned int i_neighbour_intra;     /* for constrained intra pred */
585         unsigned int i_neighbour_frame;     /* ignoring slice boundaries */
586         int     i_mb_type_top;
587         int     i_mb_type_left;
588         int     i_mb_type_topleft;
589         int     i_mb_type_topright;
590         int     i_mb_prev_xy;
591         int     i_mb_left_xy;
592         int     i_mb_top_xy;
593         int     i_mb_topleft_xy;
594         int     i_mb_topright_xy;
595
596         /**** thread synchronization ends here ****/
597         /* subsequent variables are either thread-local or constant,
598          * and won't be copied from one thread to another */
599
600         /* mb table */
601         int8_t  *type;                      /* mb type */
602         uint8_t *partition;                 /* mb partition */
603         int8_t  *qp;                        /* mb qp */
604         int16_t *cbp;                       /* mb cbp: 0x0?: luma, 0x?0: chroma, 0x100: luma dc, 0x0200 and 0x0400: chroma dc  (all set for PCM)*/
605         int8_t  (*intra4x4_pred_mode)[8];   /* intra4x4 pred mode. for non I4x4 set to I_PRED_4x4_DC(2) */
606                                             /* actually has only 7 entries; set to 8 for write-combining optimizations */
607         uint8_t (*non_zero_count)[16+4+4];  /* nzc. for I_PCM set to 16 */
608         int8_t  *chroma_pred_mode;          /* chroma_pred_mode. cabac only. for non intra I_PRED_CHROMA_DC(0) */
609         int16_t (*mv[2])[2];                /* mb mv. set to 0 for intra mb */
610         uint8_t (*mvd[2])[8][2];            /* absolute value of mb mv difference with predict, clipped to [0,33]. set to 0 if intra. cabac only */
611         int8_t   *ref[2];                   /* mb ref. set to -1 if non used (intra or Lx only) */
612         int16_t (*mvr[2][X264_REF_MAX*2])[2];/* 16x16 mv for each possible ref */
613         int8_t  *skipbp;                    /* block pattern for SKIP or DIRECT (sub)mbs. B-frames + cabac only */
614         int8_t  *mb_transform_size;         /* transform_size_8x8_flag of each mb */
615         uint16_t *slice_table;              /* sh->first_mb of the slice that the indexed mb is part of
616                                              * NOTE: this will fail on resolutions above 2^16 MBs... */
617
618          /* buffer for weighted versions of the reference frames */
619         pixel *p_weight_buf[X264_REF_MAX];
620
621         /* current value */
622         int     i_type;
623         int     i_partition;
624         ALIGNED_4( uint8_t i_sub_partition[4] );
625         int     b_transform_8x8;
626
627         int     i_cbp_luma;
628         int     i_cbp_chroma;
629
630         int     i_intra16x16_pred_mode;
631         int     i_chroma_pred_mode;
632
633         /* skip flags for i4x4 and i8x8
634          * 0 = encode as normal.
635          * 1 (non-RD only) = the DCT is still in h->dct, restore fdec and skip reconstruction.
636          * 2 (RD only) = the DCT has since been overwritten by RD; restore that too. */
637         int i_skip_intra;
638         /* skip flag for motion compensation */
639         /* if we've already done MC, we don't need to do it again */
640         int b_skip_mc;
641         /* set to true if we are re-encoding a macroblock. */
642         int b_reencode_mb;
643         int ip_offset; /* Used by PIR to offset the quantizer of intra-refresh blocks. */
644         int b_deblock_rdo;
645
646         struct
647         {
648             /* space for p_fenc and p_fdec */
649 #define FENC_STRIDE 16
650 #define FDEC_STRIDE 32
651             ALIGNED_16( pixel fenc_buf[24*FENC_STRIDE] );
652             ALIGNED_16( pixel fdec_buf[27*FDEC_STRIDE] );
653
654             /* i4x4 and i8x8 backup data, for skipping the encode stage when possible */
655             ALIGNED_16( pixel i4x4_fdec_buf[16*16] );
656             ALIGNED_16( pixel i8x8_fdec_buf[16*16] );
657             ALIGNED_16( dctcoef i8x8_dct_buf[3][64] );
658             ALIGNED_16( dctcoef i4x4_dct_buf[15][16] );
659             uint32_t i4x4_nnz_buf[4];
660             uint32_t i8x8_nnz_buf[4];
661             int i4x4_cbp;
662             int i8x8_cbp;
663
664             /* Psy trellis DCT data */
665             ALIGNED_16( dctcoef fenc_dct8[4][64] );
666             ALIGNED_16( dctcoef fenc_dct4[16][16] );
667
668             /* Psy RD SATD/SA8D scores cache */
669             ALIGNED_16( uint64_t fenc_hadamard_cache[9] );
670             ALIGNED_16( uint32_t fenc_satd_cache[32] );
671
672             /* pointer over mb of the frame to be compressed */
673             pixel *p_fenc[3]; /* y,u,v */
674             /* pointer to the actual source frame, not a block copy */
675             pixel *p_fenc_plane[2]; /* y,uv */
676
677             /* pointer over mb of the frame to be reconstructed  */
678             pixel *p_fdec[3];
679
680             /* pointer over mb of the references */
681             int i_fref[2];
682             pixel *p_fref[2][X264_REF_MAX*2][4+1]; /* last: yN, yH, yV, yHV, uv */
683             pixel *p_fref_w[X264_REF_MAX*2];  /* weighted fullpel luma */
684             uint16_t *p_integral[2][X264_REF_MAX];
685
686             /* fref stride */
687             int     i_stride[3];
688         } pic;
689
690         /* cache */
691         struct
692         {
693             /* real intra4x4_pred_mode if I_4X4 or I_8X8, I_PRED_4x4_DC if mb available, -1 if not */
694             ALIGNED_8( int8_t intra4x4_pred_mode[X264_SCAN8_LUMA_SIZE] );
695
696             /* i_non_zero_count if available else 0x80 */
697             ALIGNED_16( uint8_t non_zero_count[X264_SCAN8_SIZE] );
698
699             /* -1 if unused, -2 if unavailable */
700             ALIGNED_4( int8_t ref[2][X264_SCAN8_LUMA_SIZE] );
701
702             /* 0 if not available */
703             ALIGNED_16( int16_t mv[2][X264_SCAN8_LUMA_SIZE][2] );
704             ALIGNED_8( uint8_t mvd[2][X264_SCAN8_LUMA_SIZE][2] );
705
706             /* 1 if SKIP or DIRECT. set only for B-frames + CABAC */
707             ALIGNED_4( int8_t skip[X264_SCAN8_LUMA_SIZE] );
708
709             ALIGNED_4( int16_t direct_mv[2][4][2] );
710             ALIGNED_4( int8_t  direct_ref[2][4] );
711             int     direct_partition;
712             ALIGNED_4( int16_t pskip_mv[2] );
713
714             /* number of neighbors (top and left) that used 8x8 dct */
715             int     i_neighbour_transform_size;
716             int     i_neighbour_interlaced;
717
718             /* neighbor CBPs */
719             int     i_cbp_top;
720             int     i_cbp_left;
721         } cache;
722
723         /* */
724         int     i_qp;       /* current qp */
725         int     i_chroma_qp;
726         int     i_last_qp;  /* last qp */
727         int     i_last_dqp; /* last delta qp */
728         int     b_variable_qp; /* whether qp is allowed to vary per macroblock */
729         int     b_lossless;
730         int     b_direct_auto_read; /* take stats for --direct auto from the 2pass log */
731         int     b_direct_auto_write; /* analyse direct modes, to use and/or save */
732
733         /* lambda values */
734         int     i_trellis_lambda2[2][2]; /* [luma,chroma][inter,intra] */
735         int     i_psy_rd_lambda;
736         int     i_chroma_lambda2_offset;
737
738         /* B_direct and weighted prediction */
739         int16_t dist_scale_factor_buf[2][X264_REF_MAX*2][4];
740         int16_t (*dist_scale_factor)[4];
741         int8_t bipred_weight_buf[2][X264_REF_MAX*2][4];
742         int8_t (*bipred_weight)[4];
743         /* maps fref1[0]'s ref indices into the current list0 */
744 #define map_col_to_list0(col) h->mb.map_col_to_list0[(col)+2]
745         int8_t  map_col_to_list0[X264_REF_MAX+2];
746         int ref_blind_dupe; /* The index of the blind reference frame duplicate. */
747         int8_t deblock_ref_table[X264_REF_MAX*2+2];
748 #define deblock_ref_table(x) h->mb.deblock_ref_table[(x)+2]
749     } mb;
750
751     /* rate control encoding only */
752     x264_ratecontrol_t *rc;
753
754     /* stats */
755     struct
756     {
757         /* Current frame stats */
758         struct
759         {
760             /* MV bits (MV+Ref+Block Type) */
761             int i_mv_bits;
762             /* Texture bits (DCT coefs) */
763             int i_tex_bits;
764             /* ? */
765             int i_misc_bits;
766             /* MB type counts */
767             int i_mb_count[19];
768             int i_mb_count_i;
769             int i_mb_count_p;
770             int i_mb_count_skip;
771             int i_mb_count_8x8dct[2];
772             int i_mb_count_ref[2][X264_REF_MAX*2];
773             int i_mb_partition[17];
774             int i_mb_cbp[6];
775             int i_mb_pred_mode[4][13];
776             /* Adaptive direct mv pred */
777             int i_direct_score[2];
778             /* Metrics */
779             int64_t i_ssd[3];
780             double f_ssim;
781         } frame;
782
783         /* Cumulated stats */
784
785         /* per slice info */
786         int     i_frame_count[5];
787         int64_t i_frame_size[5];
788         double  f_frame_qp[5];
789         int     i_consecutive_bframes[X264_BFRAME_MAX+1];
790         /* */
791         int64_t i_ssd_global[5];
792         double  f_psnr_average[5];
793         double  f_psnr_mean_y[5];
794         double  f_psnr_mean_u[5];
795         double  f_psnr_mean_v[5];
796         double  f_ssim_mean_y[5];
797         /* */
798         int64_t i_mb_count[5][19];
799         int64_t i_mb_partition[2][17];
800         int64_t i_mb_count_8x8dct[2];
801         int64_t i_mb_count_ref[2][2][X264_REF_MAX*2];
802         int64_t i_mb_cbp[6];
803         int64_t i_mb_pred_mode[4][13];
804         /* */
805         int     i_direct_score[2];
806         int     i_direct_frames[2];
807         /* num p-frames weighted */
808         int     i_wpred[3];
809
810     } stat;
811
812     ALIGNED_16( uint32_t nr_residual_sum[2][64] );
813     ALIGNED_16( uint16_t nr_offset[2][64] );
814     uint32_t        nr_count[2];
815
816     /* Buffers that are allocated per-thread even in sliced threads. */
817     void *scratch_buffer; /* for any temporary storage that doesn't want repeated malloc */
818     pixel *intra_border_backup[2][2]; /* bottom pixels of the previous mb row, used for intra prediction after the framebuffer has been deblocked */
819     uint8_t (*deblock_strength[2])[2][4][4];
820
821     /* CPU functions dependents */
822     x264_predict_t      predict_16x16[4+3];
823     x264_predict_t      predict_8x8c[4+3];
824     x264_predict8x8_t   predict_8x8[9+3];
825     x264_predict_t      predict_4x4[9+3];
826     x264_predict_8x8_filter_t predict_8x8_filter;
827
828     x264_pixel_function_t pixf;
829     x264_mc_functions_t   mc;
830     x264_dct_function_t   dctf;
831     x264_zigzag_function_t zigzagf;
832     x264_quant_function_t quantf;
833     x264_deblock_function_t loopf;
834     x264_bitstream_function_t bsf;
835
836 #if HAVE_VISUALIZE
837     struct visualize_t *visualize;
838 #endif
839     x264_lookahead_t *lookahead;
840 };
841
842 // included at the end because it needs x264_t
843 #include "macroblock.h"
844 #include "rectangle.h"
845
846 #if HAVE_MMX
847 #include "x86/util.h"
848 #endif
849
850 #endif
851