• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2016, Alliance for Open Media. All rights reserved
3  *
4  * This source code is subject to the terms of the BSD 2 Clause License and
5  * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
6  * was not distributed with this source code in the LICENSE file, you can
7  * obtain it at www.aomedia.org/license/software. If the Alliance for Open
8  * Media Patent License 1.0 was not distributed with this source code in the
9  * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
10  */
11 
12 #ifndef AOM_AV1_COMMON_AV1_COMMON_INT_H_
13 #define AOM_AV1_COMMON_AV1_COMMON_INT_H_
14 
15 #include "config/aom_config.h"
16 #include "config/av1_rtcd.h"
17 
18 #include "aom/internal/aom_codec_internal.h"
19 #include "aom_util/aom_thread.h"
20 #include "av1/common/alloccommon.h"
21 #include "av1/common/av1_loopfilter.h"
22 #include "av1/common/entropy.h"
23 #include "av1/common/entropymode.h"
24 #include "av1/common/entropymv.h"
25 #include "av1/common/enums.h"
26 #include "av1/common/frame_buffers.h"
27 #include "av1/common/mv.h"
28 #include "av1/common/quant_common.h"
29 #include "av1/common/restoration.h"
30 #include "av1/common/tile_common.h"
31 #include "av1/common/timing.h"
32 #include "aom_dsp/grain_synthesis.h"
33 #include "aom_dsp/grain_table.h"
34 #include "aom_dsp/odintrin.h"
35 #ifdef __cplusplus
36 extern "C" {
37 #endif
38 
39 #if defined(__clang__) && defined(__has_warning)
40 #if __has_feature(cxx_attributes) && __has_warning("-Wimplicit-fallthrough")
41 #define AOM_FALLTHROUGH_INTENDED [[clang::fallthrough]]  // NOLINT
42 #endif
43 #elif defined(__GNUC__) && __GNUC__ >= 7
44 #define AOM_FALLTHROUGH_INTENDED __attribute__((fallthrough))  // NOLINT
45 #endif
46 
47 #ifndef AOM_FALLTHROUGH_INTENDED
48 #define AOM_FALLTHROUGH_INTENDED \
49   do {                           \
50   } while (0)
51 #endif
52 
53 #define CDEF_MAX_STRENGTHS 16
54 
55 /* Constant values while waiting for the sequence header */
56 #define FRAME_ID_LENGTH 15
57 #define DELTA_FRAME_ID_LENGTH 14
58 
59 #define FRAME_CONTEXTS (FRAME_BUFFERS + 1)
60 // Extra frame context which is always kept at default values
61 #define FRAME_CONTEXT_DEFAULTS (FRAME_CONTEXTS - 1)
62 #define PRIMARY_REF_BITS 3
63 #define PRIMARY_REF_NONE 7
64 
65 #define NUM_PING_PONG_BUFFERS 2
66 
67 #define MAX_NUM_TEMPORAL_LAYERS 8
68 #define MAX_NUM_SPATIAL_LAYERS 4
69 /* clang-format off */
70 // clang-format seems to think this is a pointer dereference and not a
71 // multiplication.
72 #define MAX_NUM_OPERATING_POINTS \
73   (MAX_NUM_TEMPORAL_LAYERS * MAX_NUM_SPATIAL_LAYERS)
74 /* clang-format on */
75 
76 // TODO(jingning): Turning this on to set up transform coefficient
77 // processing timer.
78 #define TXCOEFF_TIMER 0
79 #define TXCOEFF_COST_TIMER 0
80 
81 /*!\cond */
82 
83 enum {
84   SINGLE_REFERENCE = 0,
85   COMPOUND_REFERENCE = 1,
86   REFERENCE_MODE_SELECT = 2,
87   REFERENCE_MODES = 3,
88 } UENUM1BYTE(REFERENCE_MODE);
89 
90 enum {
91   /**
92    * Frame context updates are disabled
93    */
94   REFRESH_FRAME_CONTEXT_DISABLED,
95   /**
96    * Update frame context to values resulting from backward probability
97    * updates based on entropy/counts in the decoded frame
98    */
99   REFRESH_FRAME_CONTEXT_BACKWARD,
100 } UENUM1BYTE(REFRESH_FRAME_CONTEXT_MODE);
101 
102 #define MFMV_STACK_SIZE 3
103 typedef struct {
104   int_mv mfmv0;
105   uint8_t ref_frame_offset;
106 } TPL_MV_REF;
107 
108 typedef struct {
109   int_mv mv;
110   MV_REFERENCE_FRAME ref_frame;
111 } MV_REF;
112 
113 typedef struct RefCntBuffer {
114   // For a RefCntBuffer, the following are reference-holding variables:
115   // - cm->ref_frame_map[]
116   // - cm->cur_frame
117   // - cm->scaled_ref_buf[] (encoder only)
118   // - pbi->output_frame_index[] (decoder only)
119   // With that definition, 'ref_count' is the number of reference-holding
120   // variables that are currently referencing this buffer.
121   // For example:
122   // - suppose this buffer is at index 'k' in the buffer pool, and
123   // - Total 'n' of the variables / array elements above have value 'k' (that
124   // is, they are pointing to buffer at index 'k').
125   // Then, pool->frame_bufs[k].ref_count = n.
126   int ref_count;
127 
128   unsigned int order_hint;
129   unsigned int ref_order_hints[INTER_REFS_PER_FRAME];
130 
131   // These variables are used only in encoder and compare the absolute
132   // display order hint to compute the relative distance and overcome
133   // the limitation of get_relative_dist() which returns incorrect
134   // distance when a very old frame is used as a reference.
135   unsigned int display_order_hint;
136   unsigned int ref_display_order_hint[INTER_REFS_PER_FRAME];
137 #if CONFIG_FRAME_PARALLEL_ENCODE
138   // Frame's level within the hierarchical structure.
139   unsigned int pyramid_level;
140 #endif  // CONFIG_FRAME_PARALLEL_ENCODE
141   MV_REF *mvs;
142   uint8_t *seg_map;
143   struct segmentation seg;
144   int mi_rows;
145   int mi_cols;
146   // Width and height give the size of the buffer (before any upscaling, unlike
147   // the sizes that can be derived from the buf structure)
148   int width;
149   int height;
150   WarpedMotionParams global_motion[REF_FRAMES];
151   int showable_frame;  // frame can be used as show existing frame in future
152   uint8_t film_grain_params_present;
153   aom_film_grain_t film_grain_params;
154   aom_codec_frame_buffer_t raw_frame_buffer;
155   YV12_BUFFER_CONFIG buf;
156   int temporal_id;  // Temporal layer ID of the frame
157   int spatial_id;   // Spatial layer ID of the frame
158   FRAME_TYPE frame_type;
159 
160   // This is only used in the encoder but needs to be indexed per ref frame
161   // so it's extremely convenient to keep it here.
162   int interp_filter_selected[SWITCHABLE];
163 
164   // Inter frame reference frame delta for loop filter
165   int8_t ref_deltas[REF_FRAMES];
166 
167   // 0 = ZERO_MV, MV
168   int8_t mode_deltas[MAX_MODE_LF_DELTAS];
169 
170   FRAME_CONTEXT frame_context;
171 } RefCntBuffer;
172 
173 typedef struct BufferPool {
174 // Protect BufferPool from being accessed by several FrameWorkers at
175 // the same time during frame parallel decode.
176 // TODO(hkuang): Try to use atomic variable instead of locking the whole pool.
177 // TODO(wtc): Remove this. See
178 // https://chromium-review.googlesource.com/c/webm/libvpx/+/560630.
179 #if CONFIG_MULTITHREAD
180   pthread_mutex_t pool_mutex;
181 #endif
182 
183   // Private data associated with the frame buffer callbacks.
184   void *cb_priv;
185 
186   aom_get_frame_buffer_cb_fn_t get_fb_cb;
187   aom_release_frame_buffer_cb_fn_t release_fb_cb;
188 
189   RefCntBuffer frame_bufs[FRAME_BUFFERS];
190 
191   // Frame buffers allocated internally by the codec.
192   InternalFrameBufferList int_frame_buffers;
193 } BufferPool;
194 
195 /*!\endcond */
196 
197 /*!\brief Parameters related to CDEF */
198 typedef struct {
199   //! CDEF column line buffer
200   uint16_t *colbuf[MAX_MB_PLANE];
201   //! CDEF top & bottom line buffer
202   uint16_t *linebuf[MAX_MB_PLANE];
203   //! CDEF intermediate buffer
204   uint16_t *srcbuf;
205   //! CDEF column line buffer sizes
206   size_t allocated_colbuf_size[MAX_MB_PLANE];
207   //! CDEF top and bottom line buffer sizes
208   size_t allocated_linebuf_size[MAX_MB_PLANE];
209   //! CDEF intermediate buffer size
210   size_t allocated_srcbuf_size;
211   //! CDEF damping factor
212   int cdef_damping;
213   //! Number of CDEF strength values
214   int nb_cdef_strengths;
215   //! CDEF strength values for luma
216   int cdef_strengths[CDEF_MAX_STRENGTHS];
217   //! CDEF strength values for chroma
218   int cdef_uv_strengths[CDEF_MAX_STRENGTHS];
219   //! Number of CDEF strength values in bits
220   int cdef_bits;
221   //! Number of rows in the frame in 4 pixel
222   int allocated_mi_rows;
223   //! Number of CDEF workers
224   int allocated_num_workers;
225 } CdefInfo;
226 
227 /*!\cond */
228 
229 typedef struct {
230   int delta_q_present_flag;
231   // Resolution of delta quant
232   int delta_q_res;
233   int delta_lf_present_flag;
234   // Resolution of delta lf level
235   int delta_lf_res;
236   // This is a flag for number of deltas of loop filter level
237   // 0: use 1 delta, for y_vertical, y_horizontal, u, and v
238   // 1: use separate deltas for each filter level
239   int delta_lf_multi;
240 } DeltaQInfo;
241 
242 typedef struct {
243   int enable_order_hint;        // 0 - disable order hint, and related tools
244   int order_hint_bits_minus_1;  // dist_wtd_comp, ref_frame_mvs,
245                                 // frame_sign_bias
246                                 // if 0, enable_dist_wtd_comp and
247                                 // enable_ref_frame_mvs must be set as 0.
248   int enable_dist_wtd_comp;     // 0 - disable dist-wtd compound modes
249                                 // 1 - enable it
250   int enable_ref_frame_mvs;     // 0 - disable ref frame mvs
251                                 // 1 - enable it
252 } OrderHintInfo;
253 
254 // Sequence header structure.
255 // Note: All syntax elements of sequence_header_obu that need to be
256 // bit-identical across multiple sequence headers must be part of this struct,
257 // so that consistency is checked by are_seq_headers_consistent() function.
258 // One exception is the last member 'op_params' that is ignored by
259 // are_seq_headers_consistent() function.
260 typedef struct SequenceHeader {
261   int num_bits_width;
262   int num_bits_height;
263   int max_frame_width;
264   int max_frame_height;
265   // Whether current and reference frame IDs are signaled in the bitstream.
266   // Frame id numbers are additional information that do not affect the
267   // decoding process, but provide decoders with a way of detecting missing
268   // reference frames so that appropriate action can be taken.
269   uint8_t frame_id_numbers_present_flag;
270   int frame_id_length;
271   int delta_frame_id_length;
272   BLOCK_SIZE sb_size;  // Size of the superblock used for this frame
273   int mib_size;        // Size of the superblock in units of MI blocks
274   int mib_size_log2;   // Log 2 of above.
275 
276   OrderHintInfo order_hint_info;
277 
278   uint8_t force_screen_content_tools;  // 0 - force off
279                                        // 1 - force on
280                                        // 2 - adaptive
281   uint8_t still_picture;               // Video is a single frame still picture
282   uint8_t reduced_still_picture_hdr;   // Use reduced header for still picture
283   uint8_t force_integer_mv;            // 0 - Don't force. MV can use subpel
284                                        // 1 - force to integer
285                                        // 2 - adaptive
286   uint8_t enable_filter_intra;         // enables/disables filterintra
287   uint8_t enable_intra_edge_filter;    // enables/disables edge upsampling
288   uint8_t enable_interintra_compound;  // enables/disables interintra_compound
289   uint8_t enable_masked_compound;      // enables/disables masked compound
290   uint8_t enable_dual_filter;          // 0 - disable dual interpolation filter
291                                        // 1 - enable vert/horz filter selection
292   uint8_t enable_warped_motion;        // 0 - disable warp for the sequence
293                                        // 1 - enable warp for the sequence
294   uint8_t enable_superres;             // 0 - Disable superres for the sequence
295                                        //     and no frame level superres flag
296                                        // 1 - Enable superres for the sequence
297                                        //     enable per-frame superres flag
298   uint8_t enable_cdef;                 // To turn on/off CDEF
299   uint8_t enable_restoration;          // To turn on/off loop restoration
300   BITSTREAM_PROFILE profile;
301 
302   // Color config.
303   aom_bit_depth_t bit_depth;  // AOM_BITS_8 in profile 0 or 1,
304                               // AOM_BITS_10 or AOM_BITS_12 in profile 2 or 3.
305   uint8_t use_highbitdepth;   // If true, we need to use 16bit frame buffers.
306   uint8_t monochrome;         // Monochorme video
307   aom_color_primaries_t color_primaries;
308   aom_transfer_characteristics_t transfer_characteristics;
309   aom_matrix_coefficients_t matrix_coefficients;
310   int color_range;
311   int subsampling_x;  // Chroma subsampling for x
312   int subsampling_y;  // Chroma subsampling for y
313   aom_chroma_sample_position_t chroma_sample_position;
314   uint8_t separate_uv_delta_q;
315   uint8_t film_grain_params_present;
316 
317   // Operating point info.
318   int operating_points_cnt_minus_1;
319   int operating_point_idc[MAX_NUM_OPERATING_POINTS];
320   int timing_info_present;
321   aom_timing_info_t timing_info;
322   uint8_t decoder_model_info_present_flag;
323   aom_dec_model_info_t decoder_model_info;
324   uint8_t display_model_info_present_flag;
325   AV1_LEVEL seq_level_idx[MAX_NUM_OPERATING_POINTS];
326   uint8_t tier[MAX_NUM_OPERATING_POINTS];  // seq_tier in spec. One bit: 0 or 1.
327 
328   // IMPORTANT: the op_params member must be at the end of the struct so that
329   // are_seq_headers_consistent() can be implemented with a memcmp() call.
330   // TODO(urvang): We probably don't need the +1 here.
331   aom_dec_model_op_parameters_t op_params[MAX_NUM_OPERATING_POINTS + 1];
332 } SequenceHeader;
333 
334 typedef struct {
335   int skip_mode_allowed;
336   int skip_mode_flag;
337   int ref_frame_idx_0;
338   int ref_frame_idx_1;
339 } SkipModeInfo;
340 
341 typedef struct {
342   FRAME_TYPE frame_type;
343   REFERENCE_MODE reference_mode;
344 
345   unsigned int order_hint;
346   unsigned int display_order_hint;
347 #if CONFIG_FRAME_PARALLEL_ENCODE
348   // Frame's level within the hierarchical structure.
349   unsigned int pyramid_level;
350 #endif  // CONFIG_FRAME_PARALLEL_ENCODE
351   unsigned int frame_number;
352   SkipModeInfo skip_mode_info;
353   int refresh_frame_flags;  // Which ref frames are overwritten by this frame
354   int frame_refs_short_signaling;
355 } CurrentFrame;
356 
357 /*!\endcond */
358 
359 /*!
360  * \brief Frame level features.
361  */
362 typedef struct {
363   /*!
364    * If true, CDF update in the symbol encoding/decoding process is disabled.
365    */
366   bool disable_cdf_update;
367   /*!
368    * If true, motion vectors are specified to eighth pel precision; and
369    * if false, motion vectors are specified to quarter pel precision.
370    */
371   bool allow_high_precision_mv;
372   /*!
373    * If true, force integer motion vectors; if false, use the default.
374    */
375   bool cur_frame_force_integer_mv;
376   /*!
377    * If true, palette tool and/or intra block copy tools may be used.
378    */
379   bool allow_screen_content_tools;
380   bool allow_intrabc;       /*!< If true, intra block copy tool may be used. */
381   bool allow_warped_motion; /*!< If true, frame may use warped motion mode. */
382   /*!
383    * If true, using previous frames' motion vectors for prediction is allowed.
384    */
385   bool allow_ref_frame_mvs;
386   /*!
387    * If true, frame is fully lossless at coded resolution.
388    * */
389   bool coded_lossless;
390   /*!
391    * If true, frame is fully lossless at upscaled resolution.
392    */
393   bool all_lossless;
394   /*!
395    * If true, the frame is restricted to a reduced subset of the full set of
396    * transform types.
397    */
398   bool reduced_tx_set_used;
399   /*!
400    * If true, error resilient mode is enabled.
401    * Note: Error resilient mode allows the syntax of a frame to be parsed
402    * independently of previously decoded frames.
403    */
404   bool error_resilient_mode;
405   /*!
406    * If false, only MOTION_MODE that may be used is SIMPLE_TRANSLATION;
407    * if true, all MOTION_MODES may be used.
408    */
409   bool switchable_motion_mode;
410   TX_MODE tx_mode;            /*!< Transform mode at frame level. */
411   InterpFilter interp_filter; /*!< Interpolation filter at frame level. */
412   /*!
413    * The reference frame that contains the CDF values and other state that
414    * should be loaded at the start of the frame.
415    */
416   int primary_ref_frame;
417   /*!
418    * Byte alignment of the planes in the reference buffers.
419    */
420   int byte_alignment;
421   /*!
422    * Flag signaling how frame contexts should be updated at the end of
423    * a frame decode.
424    */
425   REFRESH_FRAME_CONTEXT_MODE refresh_frame_context;
426 } FeatureFlags;
427 
428 /*!
429  * \brief Params related to tiles.
430  */
431 typedef struct CommonTileParams {
432   int cols;          /*!< number of tile columns that frame is divided into */
433   int rows;          /*!< number of tile rows that frame is divided into */
434   int max_width_sb;  /*!< maximum tile width in superblock units. */
435   int max_height_sb; /*!< maximum tile height in superblock units. */
436 
437   /*!
438    * Min width of non-rightmost tile in MI units. Only valid if cols > 1.
439    */
440   int min_inner_width;
441 
442   /*!
443    * If true, tiles are uniformly spaced with power-of-two number of rows and
444    * columns.
445    * If false, tiles have explicitly configured widths and heights.
446    */
447   int uniform_spacing;
448 
449   /**
450    * \name Members only valid when uniform_spacing == 1
451    */
452   /**@{*/
453   int log2_cols; /*!< log2 of 'cols'. */
454   int log2_rows; /*!< log2 of 'rows'. */
455   int width;     /*!< tile width in MI units */
456   int height;    /*!< tile height in MI units */
457   /**@}*/
458 
459   /*!
460    * Min num of tile columns possible based on 'max_width_sb' and frame width.
461    */
462   int min_log2_cols;
463   /*!
464    * Min num of tile rows possible based on 'max_height_sb' and frame height.
465    */
466   int min_log2_rows;
467   /*!
468    * Min num of tile columns possible based on frame width.
469    */
470   int max_log2_cols;
471   /*!
472    * Max num of tile columns possible based on frame width.
473    */
474   int max_log2_rows;
475   /*!
476    * log2 of min number of tiles (same as min_log2_cols + min_log2_rows).
477    */
478   int min_log2;
479   /*!
480    * col_start_sb[i] is the start position of tile column i in superblock units.
481    * valid for 0 <= i <= cols
482    */
483   int col_start_sb[MAX_TILE_COLS + 1];
484   /*!
485    * row_start_sb[i] is the start position of tile row i in superblock units.
486    * valid for 0 <= i <= rows
487    */
488   int row_start_sb[MAX_TILE_ROWS + 1];
489   /*!
490    * If true, we are using large scale tile mode.
491    */
492   unsigned int large_scale;
493   /*!
494    * Only relevant when large_scale == 1.
495    * If true, the independent decoding of a single tile or a section of a frame
496    * is allowed.
497    */
498   unsigned int single_tile_decoding;
499 } CommonTileParams;
500 
501 typedef struct CommonModeInfoParams CommonModeInfoParams;
502 /*!
503  * \brief Params related to MB_MODE_INFO arrays and related info.
504  */
505 struct CommonModeInfoParams {
506   /*!
507    * Number of rows in the frame in 16 pixel units.
508    * This is computed from frame height aligned to a multiple of 8.
509    */
510   int mb_rows;
511   /*!
512    * Number of cols in the frame in 16 pixel units.
513    * This is computed from frame width aligned to a multiple of 8.
514    */
515   int mb_cols;
516 
517   /*!
518    * Total MBs = mb_rows * mb_cols.
519    */
520   int MBs;
521 
522   /*!
523    * Number of rows in the frame in 4 pixel (MB_MODE_INFO) units.
524    * This is computed from frame height aligned to a multiple of 8.
525    */
526   int mi_rows;
527   /*!
528    * Number of cols in the frame in 4 pixel (MB_MODE_INFO) units.
529    * This is computed from frame width aligned to a multiple of 8.
530    */
531   int mi_cols;
532 
533   /*!
534    * An array of MB_MODE_INFO structs for every 'mi_alloc_bsize' sized block
535    * in the frame.
536    * Note: This array should be treated like a scratch memory, and should NOT be
537    * accessed directly, in most cases. Please use 'mi_grid_base' array instead.
538    */
539   MB_MODE_INFO *mi_alloc;
540   /*!
541    * Number of allocated elements in 'mi_alloc'.
542    */
543   int mi_alloc_size;
544   /*!
545    * Stride for 'mi_alloc' array.
546    */
547   int mi_alloc_stride;
548   /*!
549    * The minimum block size that each element in 'mi_alloc' can correspond to.
550    * For decoder, this is always BLOCK_4X4.
551    * For encoder, this is currently set to BLOCK_4X4 for resolution < 4k,
552    * and BLOCK_8X8 for resolution >= 4k.
553    */
554   BLOCK_SIZE mi_alloc_bsize;
555 
556   /*!
557    * Grid of pointers to 4x4 MB_MODE_INFO structs allocated in 'mi_alloc'.
558    * It's possible that:
559    * - Multiple pointers in the grid point to the same element in 'mi_alloc'
560    * (for example, for all 4x4 blocks that belong to the same partition block).
561    * - Some pointers can be NULL (for example, for blocks outside visible area).
562    */
563   MB_MODE_INFO **mi_grid_base;
564   /*!
565    * Number of allocated elements in 'mi_grid_base' (and 'tx_type_map' also).
566    */
567   int mi_grid_size;
568   /*!
569    * Stride for 'mi_grid_base' (and 'tx_type_map' also).
570    */
571   int mi_stride;
572 
573   /*!
574    * An array of tx types for each 4x4 block in the frame.
575    * Number of allocated elements is same as 'mi_grid_size', and stride is
576    * same as 'mi_grid_size'. So, indexing into 'tx_type_map' is same as that of
577    * 'mi_grid_base'.
578    */
579   TX_TYPE *tx_type_map;
580 
581   /**
582    * \name Function pointers to allow separate logic for encoder and decoder.
583    */
584   /**@{*/
585   /*!
586    * Free the memory allocated to arrays in 'mi_params'.
587    * \param[in,out]   mi_params   object containing common mode info parameters
588    */
589   void (*free_mi)(struct CommonModeInfoParams *mi_params);
590   /*!
591    * Initialize / reset appropriate arrays in 'mi_params'.
592    * \param[in,out]   mi_params   object containing common mode info parameters
593    */
594   void (*setup_mi)(struct CommonModeInfoParams *mi_params);
595   /*!
596    * Allocate required memory for arrays in 'mi_params'.
597    * \param[in,out]   mi_params   object containing common mode info parameters
598    * \param           width       frame width
599    * \param           height      frame height
600    */
601   void (*set_mb_mi)(struct CommonModeInfoParams *mi_params, int width,
602                     int height);
603   /**@}*/
604 };
605 
606 typedef struct CommonQuantParams CommonQuantParams;
607 /*!
608  * \brief Parameters related to quantization at the frame level.
609  */
610 struct CommonQuantParams {
611   /*!
612    * Base qindex of the frame in the range 0 to 255.
613    */
614   int base_qindex;
615 
616   /*!
617    * Delta of qindex (from base_qindex) for Y plane DC coefficient.
618    * Note: y_ac_delta_q is implicitly 0.
619    */
620   int y_dc_delta_q;
621 
622   /*!
623    * Delta of qindex (from base_qindex) for U plane DC coefficients.
624    */
625   int u_dc_delta_q;
626   /*!
627    * Delta of qindex (from base_qindex) for U plane AC coefficients.
628    */
629   int v_dc_delta_q;
630 
631   /*!
632    * Delta of qindex (from base_qindex) for V plane DC coefficients.
633    * Same as those for U plane if cm->seq_params->separate_uv_delta_q == 0.
634    */
635   int u_ac_delta_q;
636   /*!
637    * Delta of qindex (from base_qindex) for V plane AC coefficients.
638    * Same as those for U plane if cm->seq_params->separate_uv_delta_q == 0.
639    */
640   int v_ac_delta_q;
641 
642   /*
643    * Note: The qindex per superblock may have a delta from the qindex obtained
644    * at frame level from parameters above, based on 'cm->delta_q_info'.
645    */
646 
647   /**
648    * \name True dequantizers.
649    * The dequantizers below are true dequantizers used only in the
650    * dequantization process.  They have the same coefficient
651    * shift/scale as TX.
652    */
653   /**@{*/
654   int16_t y_dequant_QTX[MAX_SEGMENTS][2]; /*!< Dequant for Y plane */
655   int16_t u_dequant_QTX[MAX_SEGMENTS][2]; /*!< Dequant for U plane */
656   int16_t v_dequant_QTX[MAX_SEGMENTS][2]; /*!< Dequant for V plane */
657   /**@}*/
658 
659   /**
660    * \name Global quantization matrix tables.
661    */
662   /**@{*/
663   /*!
664    * Global dquantization matrix table.
665    */
666   const qm_val_t *giqmatrix[NUM_QM_LEVELS][3][TX_SIZES_ALL];
667   /*!
668    * Global quantization matrix table.
669    */
670   const qm_val_t *gqmatrix[NUM_QM_LEVELS][3][TX_SIZES_ALL];
671   /**@}*/
672 
673   /**
674    * \name Local dequantization matrix tables for each frame.
675    */
676   /**@{*/
677   /*!
678    * Local dequant matrix for Y plane.
679    */
680   const qm_val_t *y_iqmatrix[MAX_SEGMENTS][TX_SIZES_ALL];
681   /*!
682    * Local dequant matrix for U plane.
683    */
684   const qm_val_t *u_iqmatrix[MAX_SEGMENTS][TX_SIZES_ALL];
685   /*!
686    * Local dequant matrix for V plane.
687    */
688   const qm_val_t *v_iqmatrix[MAX_SEGMENTS][TX_SIZES_ALL];
689   /**@}*/
690 
691   /*!
692    * Flag indicating whether quantization matrices are being used:
693    *  - If true, qm_level_y, qm_level_u and qm_level_v indicate the level
694    *    indices to be used to access appropriate global quant matrix tables.
695    *  - If false, we implicitly use level index 'NUM_QM_LEVELS - 1'.
696    */
697   bool using_qmatrix;
698   /**
699    * \name Valid only when using_qmatrix == true
700    * Indicate the level indices to be used to access appropriate global quant
701    * matrix tables.
702    */
703   /**@{*/
704   int qmatrix_level_y; /*!< Level index for Y plane */
705   int qmatrix_level_u; /*!< Level index for U plane */
706   int qmatrix_level_v; /*!< Level index for V plane */
707   /**@}*/
708 };
709 
710 typedef struct CommonContexts CommonContexts;
711 /*!
712  * \brief Contexts used for transmitting various symbols in the bitstream.
713  */
714 struct CommonContexts {
715   /*!
716    * Context used by 'FRAME_CONTEXT.partition_cdf' to transmit partition type.
717    * partition[i][j] is the context for ith tile row, jth mi_col.
718    */
719   PARTITION_CONTEXT **partition;
720 
721   /*!
722    * Context used to derive context for multiple symbols:
723    * - 'TXB_CTX.txb_skip_ctx' used by 'FRAME_CONTEXT.txb_skip_cdf' to transmit
724    * to transmit skip_txfm flag.
725    * - 'TXB_CTX.dc_sign_ctx' used by 'FRAME_CONTEXT.dc_sign_cdf' to transmit
726    * sign.
727    * entropy[i][j][k] is the context for ith plane, jth tile row, kth mi_col.
728    */
729   ENTROPY_CONTEXT **entropy[MAX_MB_PLANE];
730 
731   /*!
732    * Context used to derive context for 'FRAME_CONTEXT.txfm_partition_cdf' to
733    * transmit 'is_split' flag to indicate if this transform block should be
734    * split into smaller sub-blocks.
735    * txfm[i][j] is the context for ith tile row, jth mi_col.
736    */
737   TXFM_CONTEXT **txfm;
738 
739   /*!
740    * Dimensions that were used to allocate the arrays above.
741    * If these dimensions change, the arrays may have to be re-allocated.
742    */
743   int num_planes;    /*!< Corresponds to av1_num_planes(cm) */
744   int num_tile_rows; /*!< Corresponds to cm->tiles.row */
745   int num_mi_cols;   /*!< Corresponds to cm->mi_params.mi_cols */
746 };
747 
748 /*!
749  * \brief Top level common structure used by both encoder and decoder.
750  */
751 typedef struct AV1Common {
752   /*!
753    * Information about the current frame that is being coded.
754    */
755   CurrentFrame current_frame;
756   /*!
757    * Code and details about current error status.
758    */
759   struct aom_internal_error_info *error;
760 
761   /*!
762    * AV1 allows two types of frame scaling operations:
763    * 1. Frame super-resolution: that allows coding a frame at lower resolution
764    * and after decoding the frame, normatively uscales and restores the frame --
765    * inside the coding loop.
766    * 2. Frame resize: that allows coding frame at lower/higher resolution, and
767    * then non-normatively upscale the frame at the time of rendering -- outside
768    * the coding loop.
769    * Hence, the need for 3 types of dimensions.
770    */
771 
772   /**
773    * \name Coded frame dimensions.
774    */
775   /**@{*/
776   int width;  /*!< Coded frame width */
777   int height; /*!< Coded frame height */
778   /**@}*/
779 
780   /**
781    * \name Rendered frame dimensions.
782    * Dimensions after applying both super-resolution and resize to the coded
783    * frame. Different from coded dimensions if super-resolution and/or resize
784    * are being used for this frame.
785    */
786   /**@{*/
787   int render_width;  /*!< Rendered frame width */
788   int render_height; /*!< Rendered frame height */
789   /**@}*/
790 
791   /**
792    * \name Super-resolved frame dimensions.
793    * Frame dimensions after applying super-resolution to the coded frame (if
794    * present), but before applying resize.
795    * Larger than the coded dimensions if super-resolution is being used for
796    * this frame.
797    * Different from rendered dimensions if resize is being used for this frame.
798    */
799   /**@{*/
800   int superres_upscaled_width;  /*!< Super-resolved frame width */
801   int superres_upscaled_height; /*!< Super-resolved frame height */
802   /**@}*/
803 
804   /*!
805    * The denominator of the superres scale used by this frame.
806    * Note: The numerator is fixed to be SCALE_NUMERATOR.
807    */
808   uint8_t superres_scale_denominator;
809 
810   /*!
811    * buffer_removal_times[op_num] specifies the frame removal time in units of
812    * DecCT clock ticks counted from the removal time of the last random access
813    * point for operating point op_num.
814    * TODO(urvang): We probably don't need the +1 here.
815    */
816   uint32_t buffer_removal_times[MAX_NUM_OPERATING_POINTS + 1];
817   /*!
818    * Presentation time of the frame in clock ticks DispCT counted from the
819    * removal time of the last random access point for the operating point that
820    * is being decoded.
821    */
822   uint32_t frame_presentation_time;
823 
824   /*!
825    * Buffer where previous frame is stored.
826    */
827   RefCntBuffer *prev_frame;
828 
829   /*!
830    * Buffer into which the current frame will be stored and other related info.
831    * TODO(hkuang): Combine this with cur_buf in macroblockd.
832    */
833   RefCntBuffer *cur_frame;
834 
835   /*!
836    * For encoder, we have a two-level mapping from reference frame type to the
837    * corresponding buffer in the buffer pool:
838    * * 'remapped_ref_idx[i - 1]' maps reference type 'i' (range: LAST_FRAME ...
839    * EXTREF_FRAME) to a remapped index 'j' (in range: 0 ... REF_FRAMES - 1)
840    * * Later, 'cm->ref_frame_map[j]' maps the remapped index 'j' to a pointer to
841    * the reference counted buffer structure RefCntBuffer, taken from the buffer
842    * pool cm->buffer_pool->frame_bufs.
843    *
844    * LAST_FRAME,                        ...,      EXTREF_FRAME
845    *      |                                           |
846    *      v                                           v
847    * remapped_ref_idx[LAST_FRAME - 1],  ...,  remapped_ref_idx[EXTREF_FRAME - 1]
848    *      |                                           |
849    *      v                                           v
850    * ref_frame_map[],                   ...,     ref_frame_map[]
851    *
852    * Note: INTRA_FRAME always refers to the current frame, so there's no need to
853    * have a remapped index for the same.
854    */
855   int remapped_ref_idx[REF_FRAMES];
856 
857   /*!
858    * Scale of the current frame with respect to itself.
859    * This is currently used for intra block copy, which behaves like an inter
860    * prediction mode, where the reference frame is the current frame itself.
861    */
862   struct scale_factors sf_identity;
863 
864   /*!
865    * Scale factors of the reference frame with respect to the current frame.
866    * This is required for generating inter prediction and will be non-identity
867    * for a reference frame, if it has different dimensions than the coded
868    * dimensions of the current frame.
869    */
870   struct scale_factors ref_scale_factors[REF_FRAMES];
871 
872   /*!
873    * For decoder, ref_frame_map[i] maps reference type 'i' to a pointer to
874    * the buffer in the buffer pool 'cm->buffer_pool.frame_bufs'.
875    * For encoder, ref_frame_map[j] (where j = remapped_ref_idx[i]) maps
876    * remapped reference index 'j' (that is, original reference type 'i') to
877    * a pointer to the buffer in the buffer pool 'cm->buffer_pool.frame_bufs'.
878    */
879   RefCntBuffer *ref_frame_map[REF_FRAMES];
880 
881   /*!
882    * If true, this frame is actually shown after decoding.
883    * If false, this frame is coded in the bitstream, but not shown. It is only
884    * used as a reference for other frames coded later.
885    */
886   int show_frame;
887 
888   /*!
889    * If true, this frame can be used as a show-existing frame for other frames
890    * coded later.
891    * When 'show_frame' is true, this is always true for all non-keyframes.
892    * When 'show_frame' is false, this value is transmitted in the bitstream.
893    */
894   int showable_frame;
895 
896   /*!
897    * If true, show an existing frame coded before, instead of actually coding a
898    * frame. The existing frame comes from one of the existing reference buffers,
899    * as signaled in the bitstream.
900    */
901   int show_existing_frame;
902 
903   /*!
904    * Whether some features are allowed or not.
905    */
906   FeatureFlags features;
907 
908   /*!
909    * Params related to MB_MODE_INFO arrays and related info.
910    */
911   CommonModeInfoParams mi_params;
912 
913 #if CONFIG_ENTROPY_STATS
914   /*!
915    * Context type used by token CDFs, in the range 0 .. (TOKEN_CDF_Q_CTXS - 1).
916    */
917   int coef_cdf_category;
918 #endif  // CONFIG_ENTROPY_STATS
919 
920   /*!
921    * Quantization params.
922    */
923   CommonQuantParams quant_params;
924 
925   /*!
926    * Segmentation info for current frame.
927    */
928   struct segmentation seg;
929 
930   /*!
931    * Segmentation map for previous frame.
932    */
933   uint8_t *last_frame_seg_map;
934 
935   /**
936    * \name Deblocking filter parameters.
937    */
938   /**@{*/
939   loop_filter_info_n lf_info; /*!< Loop filter info */
940   struct loopfilter lf;       /*!< Loop filter parameters */
941   /**@}*/
942 
943   /**
944    * \name Loop Restoration filter parameters.
945    */
946   /**@{*/
947   RestorationInfo rst_info[MAX_MB_PLANE]; /*!< Loop Restoration filter info */
948   int32_t *rst_tmpbuf; /*!< Scratch buffer for self-guided restoration */
949   RestorationLineBuffers *rlbs; /*!< Line buffers needed by loop restoration */
950   YV12_BUFFER_CONFIG rst_frame; /*!< Stores the output of loop restoration */
951   /**@}*/
952 
953   /*!
954    * CDEF (Constrained Directional Enhancement Filter) parameters.
955    */
956   CdefInfo cdef_info;
957 
958   /*!
959    * Parameters for film grain synthesis.
960    */
961   aom_film_grain_t film_grain_params;
962 
963   /*!
964    * Parameters for delta quantization and delta loop filter level.
965    */
966   DeltaQInfo delta_q_info;
967 
968   /*!
969    * Global motion parameters for each reference frame.
970    */
971   WarpedMotionParams global_motion[REF_FRAMES];
972 
973   /*!
974    * Elements part of the sequence header, that are applicable for all the
975    * frames in the video.
976    */
977   SequenceHeader *seq_params;
978 
979   /*!
980    * Current CDFs of all the symbols for the current frame.
981    */
982   FRAME_CONTEXT *fc;
983   /*!
984    * Default CDFs used when features.primary_ref_frame = PRIMARY_REF_NONE
985    * (e.g. for a keyframe). These default CDFs are defined by the bitstream and
986    * copied from default CDF tables for each symbol.
987    */
988   FRAME_CONTEXT *default_frame_context;
989 
990   /*!
991    * Parameters related to tiling.
992    */
993   CommonTileParams tiles;
994 
995   /*!
996    * External BufferPool passed from outside.
997    */
998   BufferPool *buffer_pool;
999 
1000   /*!
1001    * Above context buffers and their sizes.
1002    * Note: above contexts are allocated in this struct, as their size is
1003    * dependent on frame width, while left contexts are declared and allocated in
1004    * MACROBLOCKD struct, as they have a fixed size.
1005    */
1006   CommonContexts above_contexts;
1007 
1008   /**
1009    * \name Signaled when cm->seq_params->frame_id_numbers_present_flag == 1
1010    */
1011   /**@{*/
1012   int current_frame_id;         /*!< frame ID for the current frame. */
1013   int ref_frame_id[REF_FRAMES]; /*!< frame IDs for the reference frames. */
1014   /**@}*/
1015 
1016   /*!
1017    * Motion vectors provided by motion field estimation.
1018    * tpl_mvs[row * stride + col] stores MV for block at [mi_row, mi_col] where:
1019    * mi_row = 2 * row,
1020    * mi_col = 2 * col, and
1021    * stride = cm->mi_params.mi_stride / 2
1022    */
1023   TPL_MV_REF *tpl_mvs;
1024   /*!
1025    * Allocated size of 'tpl_mvs' array. Refer to 'ensure_mv_buffer()' function.
1026    */
1027   int tpl_mvs_mem_size;
1028   /*!
1029    * ref_frame_sign_bias[k] is 1 if relative distance between reference 'k' and
1030    * current frame is positive; and 0 otherwise.
1031    */
1032   int ref_frame_sign_bias[REF_FRAMES];
1033   /*!
1034    * ref_frame_side[k] is 1 if relative distance between reference 'k' and
1035    * current frame is positive, -1 if relative distance is 0; and 0 otherwise.
1036    * TODO(jingning): This can be combined with sign_bias later.
1037    */
1038   int8_t ref_frame_side[REF_FRAMES];
1039 
1040   /*!
1041    * Temporal layer ID of this frame
1042    * (in the range 0 ... (number_temporal_layers - 1)).
1043    */
1044   int temporal_layer_id;
1045 
1046   /*!
1047    * Spatial layer ID of this frame
1048    * (in the range 0 ... (number_spatial_layers - 1)).
1049    */
1050   int spatial_layer_id;
1051 
1052 #if TXCOEFF_TIMER
1053   int64_t cum_txcoeff_timer;
1054   int64_t txcoeff_timer;
1055   int txb_count;
1056 #endif  // TXCOEFF_TIMER
1057 
1058 #if TXCOEFF_COST_TIMER
1059   int64_t cum_txcoeff_cost_timer;
1060   int64_t txcoeff_cost_timer;
1061   int64_t txcoeff_cost_count;
1062 #endif  // TXCOEFF_COST_TIMER
1063 } AV1_COMMON;
1064 
1065 /*!\cond */
1066 
1067 // TODO(hkuang): Don't need to lock the whole pool after implementing atomic
1068 // frame reference count.
lock_buffer_pool(BufferPool * const pool)1069 static void lock_buffer_pool(BufferPool *const pool) {
1070 #if CONFIG_MULTITHREAD
1071   pthread_mutex_lock(&pool->pool_mutex);
1072 #else
1073   (void)pool;
1074 #endif
1075 }
1076 
unlock_buffer_pool(BufferPool * const pool)1077 static void unlock_buffer_pool(BufferPool *const pool) {
1078 #if CONFIG_MULTITHREAD
1079   pthread_mutex_unlock(&pool->pool_mutex);
1080 #else
1081   (void)pool;
1082 #endif
1083 }
1084 
get_ref_frame(AV1_COMMON * cm,int index)1085 static INLINE YV12_BUFFER_CONFIG *get_ref_frame(AV1_COMMON *cm, int index) {
1086   if (index < 0 || index >= REF_FRAMES) return NULL;
1087   if (cm->ref_frame_map[index] == NULL) return NULL;
1088   return &cm->ref_frame_map[index]->buf;
1089 }
1090 
get_free_fb(AV1_COMMON * cm)1091 static INLINE int get_free_fb(AV1_COMMON *cm) {
1092   RefCntBuffer *const frame_bufs = cm->buffer_pool->frame_bufs;
1093   int i;
1094 
1095   lock_buffer_pool(cm->buffer_pool);
1096   for (i = 0; i < FRAME_BUFFERS; ++i)
1097     if (frame_bufs[i].ref_count == 0) break;
1098 
1099   if (i != FRAME_BUFFERS) {
1100     if (frame_bufs[i].buf.use_external_reference_buffers) {
1101       // If this frame buffer's y_buffer, u_buffer, and v_buffer point to the
1102       // external reference buffers. Restore the buffer pointers to point to the
1103       // internally allocated memory.
1104       YV12_BUFFER_CONFIG *ybf = &frame_bufs[i].buf;
1105       ybf->y_buffer = ybf->store_buf_adr[0];
1106       ybf->u_buffer = ybf->store_buf_adr[1];
1107       ybf->v_buffer = ybf->store_buf_adr[2];
1108       ybf->use_external_reference_buffers = 0;
1109     }
1110 
1111     frame_bufs[i].ref_count = 1;
1112   } else {
1113     // We should never run out of free buffers. If this assertion fails, there
1114     // is a reference leak.
1115     assert(0 && "Ran out of free frame buffers. Likely a reference leak.");
1116     // Reset i to be INVALID_IDX to indicate no free buffer found.
1117     i = INVALID_IDX;
1118   }
1119 
1120   unlock_buffer_pool(cm->buffer_pool);
1121   return i;
1122 }
1123 
assign_cur_frame_new_fb(AV1_COMMON * const cm)1124 static INLINE RefCntBuffer *assign_cur_frame_new_fb(AV1_COMMON *const cm) {
1125   // Release the previously-used frame-buffer
1126   if (cm->cur_frame != NULL) {
1127     --cm->cur_frame->ref_count;
1128     cm->cur_frame = NULL;
1129   }
1130 
1131   // Assign a new framebuffer
1132   const int new_fb_idx = get_free_fb(cm);
1133   if (new_fb_idx == INVALID_IDX) return NULL;
1134 
1135   cm->cur_frame = &cm->buffer_pool->frame_bufs[new_fb_idx];
1136   cm->cur_frame->buf.buf_8bit_valid = 0;
1137   av1_zero(cm->cur_frame->interp_filter_selected);
1138   return cm->cur_frame;
1139 }
1140 
1141 // Modify 'lhs_ptr' to reference the buffer at 'rhs_ptr', and update the ref
1142 // counts accordingly.
assign_frame_buffer_p(RefCntBuffer ** lhs_ptr,RefCntBuffer * rhs_ptr)1143 static INLINE void assign_frame_buffer_p(RefCntBuffer **lhs_ptr,
1144                                          RefCntBuffer *rhs_ptr) {
1145   RefCntBuffer *const old_ptr = *lhs_ptr;
1146   if (old_ptr != NULL) {
1147     assert(old_ptr->ref_count > 0);
1148     // One less reference to the buffer at 'old_ptr', so decrease ref count.
1149     --old_ptr->ref_count;
1150   }
1151 
1152   *lhs_ptr = rhs_ptr;
1153   // One more reference to the buffer at 'rhs_ptr', so increase ref count.
1154   ++rhs_ptr->ref_count;
1155 }
1156 
frame_is_intra_only(const AV1_COMMON * const cm)1157 static INLINE int frame_is_intra_only(const AV1_COMMON *const cm) {
1158   return cm->current_frame.frame_type == KEY_FRAME ||
1159          cm->current_frame.frame_type == INTRA_ONLY_FRAME;
1160 }
1161 
frame_is_sframe(const AV1_COMMON * cm)1162 static INLINE int frame_is_sframe(const AV1_COMMON *cm) {
1163   return cm->current_frame.frame_type == S_FRAME;
1164 }
1165 
1166 // These functions take a reference frame label between LAST_FRAME and
1167 // EXTREF_FRAME inclusive.  Note that this is different to the indexing
1168 // previously used by the frame_refs[] array.
get_ref_frame_map_idx(const AV1_COMMON * const cm,const MV_REFERENCE_FRAME ref_frame)1169 static INLINE int get_ref_frame_map_idx(const AV1_COMMON *const cm,
1170                                         const MV_REFERENCE_FRAME ref_frame) {
1171   return (ref_frame >= LAST_FRAME && ref_frame <= EXTREF_FRAME)
1172              ? cm->remapped_ref_idx[ref_frame - LAST_FRAME]
1173              : INVALID_IDX;
1174 }
1175 
get_ref_frame_buf(const AV1_COMMON * const cm,const MV_REFERENCE_FRAME ref_frame)1176 static INLINE RefCntBuffer *get_ref_frame_buf(
1177     const AV1_COMMON *const cm, const MV_REFERENCE_FRAME ref_frame) {
1178   const int map_idx = get_ref_frame_map_idx(cm, ref_frame);
1179   return (map_idx != INVALID_IDX) ? cm->ref_frame_map[map_idx] : NULL;
1180 }
1181 
1182 // Both const and non-const versions of this function are provided so that it
1183 // can be used with a const AV1_COMMON if needed.
get_ref_scale_factors_const(const AV1_COMMON * const cm,const MV_REFERENCE_FRAME ref_frame)1184 static INLINE const struct scale_factors *get_ref_scale_factors_const(
1185     const AV1_COMMON *const cm, const MV_REFERENCE_FRAME ref_frame) {
1186   const int map_idx = get_ref_frame_map_idx(cm, ref_frame);
1187   return (map_idx != INVALID_IDX) ? &cm->ref_scale_factors[map_idx] : NULL;
1188 }
1189 
get_ref_scale_factors(AV1_COMMON * const cm,const MV_REFERENCE_FRAME ref_frame)1190 static INLINE struct scale_factors *get_ref_scale_factors(
1191     AV1_COMMON *const cm, const MV_REFERENCE_FRAME ref_frame) {
1192   const int map_idx = get_ref_frame_map_idx(cm, ref_frame);
1193   return (map_idx != INVALID_IDX) ? &cm->ref_scale_factors[map_idx] : NULL;
1194 }
1195 
get_primary_ref_frame_buf(const AV1_COMMON * const cm)1196 static INLINE RefCntBuffer *get_primary_ref_frame_buf(
1197     const AV1_COMMON *const cm) {
1198   const int primary_ref_frame = cm->features.primary_ref_frame;
1199   if (primary_ref_frame == PRIMARY_REF_NONE) return NULL;
1200   const int map_idx = get_ref_frame_map_idx(cm, primary_ref_frame + 1);
1201   return (map_idx != INVALID_IDX) ? cm->ref_frame_map[map_idx] : NULL;
1202 }
1203 
1204 // Returns 1 if this frame might allow mvs from some reference frame.
frame_might_allow_ref_frame_mvs(const AV1_COMMON * cm)1205 static INLINE int frame_might_allow_ref_frame_mvs(const AV1_COMMON *cm) {
1206   return !cm->features.error_resilient_mode &&
1207          cm->seq_params->order_hint_info.enable_ref_frame_mvs &&
1208          cm->seq_params->order_hint_info.enable_order_hint &&
1209          !frame_is_intra_only(cm);
1210 }
1211 
1212 // Returns 1 if this frame might use warped_motion
frame_might_allow_warped_motion(const AV1_COMMON * cm)1213 static INLINE int frame_might_allow_warped_motion(const AV1_COMMON *cm) {
1214   return !cm->features.error_resilient_mode && !frame_is_intra_only(cm) &&
1215          cm->seq_params->enable_warped_motion;
1216 }
1217 
ensure_mv_buffer(RefCntBuffer * buf,AV1_COMMON * cm)1218 static INLINE void ensure_mv_buffer(RefCntBuffer *buf, AV1_COMMON *cm) {
1219   const int buf_rows = buf->mi_rows;
1220   const int buf_cols = buf->mi_cols;
1221   const CommonModeInfoParams *const mi_params = &cm->mi_params;
1222 
1223   if (buf->mvs == NULL || buf_rows != mi_params->mi_rows ||
1224       buf_cols != mi_params->mi_cols) {
1225     aom_free(buf->mvs);
1226     buf->mi_rows = mi_params->mi_rows;
1227     buf->mi_cols = mi_params->mi_cols;
1228     CHECK_MEM_ERROR(cm, buf->mvs,
1229                     (MV_REF *)aom_calloc(((mi_params->mi_rows + 1) >> 1) *
1230                                              ((mi_params->mi_cols + 1) >> 1),
1231                                          sizeof(*buf->mvs)));
1232     aom_free(buf->seg_map);
1233     CHECK_MEM_ERROR(
1234         cm, buf->seg_map,
1235         (uint8_t *)aom_calloc(mi_params->mi_rows * mi_params->mi_cols,
1236                               sizeof(*buf->seg_map)));
1237   }
1238 
1239   const int mem_size =
1240       ((mi_params->mi_rows + MAX_MIB_SIZE) >> 1) * (mi_params->mi_stride >> 1);
1241   int realloc = cm->tpl_mvs == NULL;
1242   if (cm->tpl_mvs) realloc |= cm->tpl_mvs_mem_size < mem_size;
1243 
1244   if (realloc) {
1245     aom_free(cm->tpl_mvs);
1246     CHECK_MEM_ERROR(cm, cm->tpl_mvs,
1247                     (TPL_MV_REF *)aom_calloc(mem_size, sizeof(*cm->tpl_mvs)));
1248     cm->tpl_mvs_mem_size = mem_size;
1249   }
1250 }
1251 
1252 void cfl_init(CFL_CTX *cfl, const SequenceHeader *seq_params);
1253 
av1_num_planes(const AV1_COMMON * cm)1254 static INLINE int av1_num_planes(const AV1_COMMON *cm) {
1255   return cm->seq_params->monochrome ? 1 : MAX_MB_PLANE;
1256 }
1257 
av1_init_above_context(CommonContexts * above_contexts,int num_planes,int tile_row,MACROBLOCKD * xd)1258 static INLINE void av1_init_above_context(CommonContexts *above_contexts,
1259                                           int num_planes, int tile_row,
1260                                           MACROBLOCKD *xd) {
1261   for (int i = 0; i < num_planes; ++i) {
1262     xd->above_entropy_context[i] = above_contexts->entropy[i][tile_row];
1263   }
1264   xd->above_partition_context = above_contexts->partition[tile_row];
1265   xd->above_txfm_context = above_contexts->txfm[tile_row];
1266 }
1267 
av1_init_macroblockd(AV1_COMMON * cm,MACROBLOCKD * xd)1268 static INLINE void av1_init_macroblockd(AV1_COMMON *cm, MACROBLOCKD *xd) {
1269   const int num_planes = av1_num_planes(cm);
1270   const CommonQuantParams *const quant_params = &cm->quant_params;
1271 
1272   for (int i = 0; i < num_planes; ++i) {
1273     if (xd->plane[i].plane_type == PLANE_TYPE_Y) {
1274       memcpy(xd->plane[i].seg_dequant_QTX, quant_params->y_dequant_QTX,
1275              sizeof(quant_params->y_dequant_QTX));
1276       memcpy(xd->plane[i].seg_iqmatrix, quant_params->y_iqmatrix,
1277              sizeof(quant_params->y_iqmatrix));
1278 
1279     } else {
1280       if (i == AOM_PLANE_U) {
1281         memcpy(xd->plane[i].seg_dequant_QTX, quant_params->u_dequant_QTX,
1282                sizeof(quant_params->u_dequant_QTX));
1283         memcpy(xd->plane[i].seg_iqmatrix, quant_params->u_iqmatrix,
1284                sizeof(quant_params->u_iqmatrix));
1285       } else {
1286         memcpy(xd->plane[i].seg_dequant_QTX, quant_params->v_dequant_QTX,
1287                sizeof(quant_params->v_dequant_QTX));
1288         memcpy(xd->plane[i].seg_iqmatrix, quant_params->v_iqmatrix,
1289                sizeof(quant_params->v_iqmatrix));
1290       }
1291     }
1292   }
1293   xd->mi_stride = cm->mi_params.mi_stride;
1294   xd->error_info = cm->error;
1295   cfl_init(&xd->cfl, cm->seq_params);
1296 }
1297 
set_entropy_context(MACROBLOCKD * xd,int mi_row,int mi_col,const int num_planes)1298 static INLINE void set_entropy_context(MACROBLOCKD *xd, int mi_row, int mi_col,
1299                                        const int num_planes) {
1300   int i;
1301   int row_offset = mi_row;
1302   int col_offset = mi_col;
1303   for (i = 0; i < num_planes; ++i) {
1304     struct macroblockd_plane *const pd = &xd->plane[i];
1305     // Offset the buffer pointer
1306     const BLOCK_SIZE bsize = xd->mi[0]->bsize;
1307     if (pd->subsampling_y && (mi_row & 0x01) && (mi_size_high[bsize] == 1))
1308       row_offset = mi_row - 1;
1309     if (pd->subsampling_x && (mi_col & 0x01) && (mi_size_wide[bsize] == 1))
1310       col_offset = mi_col - 1;
1311     int above_idx = col_offset;
1312     int left_idx = row_offset & MAX_MIB_MASK;
1313     pd->above_entropy_context =
1314         &xd->above_entropy_context[i][above_idx >> pd->subsampling_x];
1315     pd->left_entropy_context =
1316         &xd->left_entropy_context[i][left_idx >> pd->subsampling_y];
1317   }
1318 }
1319 
calc_mi_size(int len)1320 static INLINE int calc_mi_size(int len) {
1321   // len is in mi units. Align to a multiple of SBs.
1322   return ALIGN_POWER_OF_TWO(len, MAX_MIB_SIZE_LOG2);
1323 }
1324 
set_plane_n4(MACROBLOCKD * const xd,int bw,int bh,const int num_planes)1325 static INLINE void set_plane_n4(MACROBLOCKD *const xd, int bw, int bh,
1326                                 const int num_planes) {
1327   int i;
1328   for (i = 0; i < num_planes; i++) {
1329     xd->plane[i].width = (bw * MI_SIZE) >> xd->plane[i].subsampling_x;
1330     xd->plane[i].height = (bh * MI_SIZE) >> xd->plane[i].subsampling_y;
1331 
1332     xd->plane[i].width = AOMMAX(xd->plane[i].width, 4);
1333     xd->plane[i].height = AOMMAX(xd->plane[i].height, 4);
1334   }
1335 }
1336 
set_mi_row_col(MACROBLOCKD * xd,const TileInfo * const tile,int mi_row,int bh,int mi_col,int bw,int mi_rows,int mi_cols)1337 static INLINE void set_mi_row_col(MACROBLOCKD *xd, const TileInfo *const tile,
1338                                   int mi_row, int bh, int mi_col, int bw,
1339                                   int mi_rows, int mi_cols) {
1340   xd->mb_to_top_edge = -GET_MV_SUBPEL(mi_row * MI_SIZE);
1341   xd->mb_to_bottom_edge = GET_MV_SUBPEL((mi_rows - bh - mi_row) * MI_SIZE);
1342   xd->mb_to_left_edge = -GET_MV_SUBPEL((mi_col * MI_SIZE));
1343   xd->mb_to_right_edge = GET_MV_SUBPEL((mi_cols - bw - mi_col) * MI_SIZE);
1344 
1345   xd->mi_row = mi_row;
1346   xd->mi_col = mi_col;
1347 
1348   // Are edges available for intra prediction?
1349   xd->up_available = (mi_row > tile->mi_row_start);
1350 
1351   const int ss_x = xd->plane[1].subsampling_x;
1352   const int ss_y = xd->plane[1].subsampling_y;
1353 
1354   xd->left_available = (mi_col > tile->mi_col_start);
1355   xd->chroma_up_available = xd->up_available;
1356   xd->chroma_left_available = xd->left_available;
1357   if (ss_x && bw < mi_size_wide[BLOCK_8X8])
1358     xd->chroma_left_available = (mi_col - 1) > tile->mi_col_start;
1359   if (ss_y && bh < mi_size_high[BLOCK_8X8])
1360     xd->chroma_up_available = (mi_row - 1) > tile->mi_row_start;
1361   if (xd->up_available) {
1362     xd->above_mbmi = xd->mi[-xd->mi_stride];
1363   } else {
1364     xd->above_mbmi = NULL;
1365   }
1366 
1367   if (xd->left_available) {
1368     xd->left_mbmi = xd->mi[-1];
1369   } else {
1370     xd->left_mbmi = NULL;
1371   }
1372 
1373   const int chroma_ref = ((mi_row & 0x01) || !(bh & 0x01) || !ss_y) &&
1374                          ((mi_col & 0x01) || !(bw & 0x01) || !ss_x);
1375   xd->is_chroma_ref = chroma_ref;
1376   if (chroma_ref) {
1377     // To help calculate the "above" and "left" chroma blocks, note that the
1378     // current block may cover multiple luma blocks (eg, if partitioned into
1379     // 4x4 luma blocks).
1380     // First, find the top-left-most luma block covered by this chroma block
1381     MB_MODE_INFO **base_mi =
1382         &xd->mi[-(mi_row & ss_y) * xd->mi_stride - (mi_col & ss_x)];
1383 
1384     // Then, we consider the luma region covered by the left or above 4x4 chroma
1385     // prediction. We want to point to the chroma reference block in that
1386     // region, which is the bottom-right-most mi unit.
1387     // This leads to the following offsets:
1388     MB_MODE_INFO *chroma_above_mi =
1389         xd->chroma_up_available ? base_mi[-xd->mi_stride + ss_x] : NULL;
1390     xd->chroma_above_mbmi = chroma_above_mi;
1391 
1392     MB_MODE_INFO *chroma_left_mi =
1393         xd->chroma_left_available ? base_mi[ss_y * xd->mi_stride - 1] : NULL;
1394     xd->chroma_left_mbmi = chroma_left_mi;
1395   }
1396 
1397   xd->height = bh;
1398   xd->width = bw;
1399 
1400   xd->is_last_vertical_rect = 0;
1401   if (xd->width < xd->height) {
1402     if (!((mi_col + xd->width) & (xd->height - 1))) {
1403       xd->is_last_vertical_rect = 1;
1404     }
1405   }
1406 
1407   xd->is_first_horizontal_rect = 0;
1408   if (xd->width > xd->height)
1409     if (!(mi_row & (xd->width - 1))) xd->is_first_horizontal_rect = 1;
1410 }
1411 
get_y_mode_cdf(FRAME_CONTEXT * tile_ctx,const MB_MODE_INFO * above_mi,const MB_MODE_INFO * left_mi)1412 static INLINE aom_cdf_prob *get_y_mode_cdf(FRAME_CONTEXT *tile_ctx,
1413                                            const MB_MODE_INFO *above_mi,
1414                                            const MB_MODE_INFO *left_mi) {
1415   const PREDICTION_MODE above = av1_above_block_mode(above_mi);
1416   const PREDICTION_MODE left = av1_left_block_mode(left_mi);
1417   const int above_ctx = intra_mode_context[above];
1418   const int left_ctx = intra_mode_context[left];
1419   return tile_ctx->kf_y_cdf[above_ctx][left_ctx];
1420 }
1421 
update_partition_context(MACROBLOCKD * xd,int mi_row,int mi_col,BLOCK_SIZE subsize,BLOCK_SIZE bsize)1422 static INLINE void update_partition_context(MACROBLOCKD *xd, int mi_row,
1423                                             int mi_col, BLOCK_SIZE subsize,
1424                                             BLOCK_SIZE bsize) {
1425   PARTITION_CONTEXT *const above_ctx = xd->above_partition_context + mi_col;
1426   PARTITION_CONTEXT *const left_ctx =
1427       xd->left_partition_context + (mi_row & MAX_MIB_MASK);
1428 
1429   const int bw = mi_size_wide[bsize];
1430   const int bh = mi_size_high[bsize];
1431   memset(above_ctx, partition_context_lookup[subsize].above, bw);
1432   memset(left_ctx, partition_context_lookup[subsize].left, bh);
1433 }
1434 
is_chroma_reference(int mi_row,int mi_col,BLOCK_SIZE bsize,int subsampling_x,int subsampling_y)1435 static INLINE int is_chroma_reference(int mi_row, int mi_col, BLOCK_SIZE bsize,
1436                                       int subsampling_x, int subsampling_y) {
1437   assert(bsize < BLOCK_SIZES_ALL);
1438   const int bw = mi_size_wide[bsize];
1439   const int bh = mi_size_high[bsize];
1440   int ref_pos = ((mi_row & 0x01) || !(bh & 0x01) || !subsampling_y) &&
1441                 ((mi_col & 0x01) || !(bw & 0x01) || !subsampling_x);
1442   return ref_pos;
1443 }
1444 
cdf_element_prob(const aom_cdf_prob * cdf,size_t element)1445 static INLINE aom_cdf_prob cdf_element_prob(const aom_cdf_prob *cdf,
1446                                             size_t element) {
1447   assert(cdf != NULL);
1448   return (element > 0 ? cdf[element - 1] : CDF_PROB_TOP) - cdf[element];
1449 }
1450 
partition_gather_horz_alike(aom_cdf_prob * out,const aom_cdf_prob * const in,BLOCK_SIZE bsize)1451 static INLINE void partition_gather_horz_alike(aom_cdf_prob *out,
1452                                                const aom_cdf_prob *const in,
1453                                                BLOCK_SIZE bsize) {
1454   (void)bsize;
1455   out[0] = CDF_PROB_TOP;
1456   out[0] -= cdf_element_prob(in, PARTITION_HORZ);
1457   out[0] -= cdf_element_prob(in, PARTITION_SPLIT);
1458   out[0] -= cdf_element_prob(in, PARTITION_HORZ_A);
1459   out[0] -= cdf_element_prob(in, PARTITION_HORZ_B);
1460   out[0] -= cdf_element_prob(in, PARTITION_VERT_A);
1461   if (bsize != BLOCK_128X128) out[0] -= cdf_element_prob(in, PARTITION_HORZ_4);
1462   out[0] = AOM_ICDF(out[0]);
1463   out[1] = AOM_ICDF(CDF_PROB_TOP);
1464 }
1465 
partition_gather_vert_alike(aom_cdf_prob * out,const aom_cdf_prob * const in,BLOCK_SIZE bsize)1466 static INLINE void partition_gather_vert_alike(aom_cdf_prob *out,
1467                                                const aom_cdf_prob *const in,
1468                                                BLOCK_SIZE bsize) {
1469   (void)bsize;
1470   out[0] = CDF_PROB_TOP;
1471   out[0] -= cdf_element_prob(in, PARTITION_VERT);
1472   out[0] -= cdf_element_prob(in, PARTITION_SPLIT);
1473   out[0] -= cdf_element_prob(in, PARTITION_HORZ_A);
1474   out[0] -= cdf_element_prob(in, PARTITION_VERT_A);
1475   out[0] -= cdf_element_prob(in, PARTITION_VERT_B);
1476   if (bsize != BLOCK_128X128) out[0] -= cdf_element_prob(in, PARTITION_VERT_4);
1477   out[0] = AOM_ICDF(out[0]);
1478   out[1] = AOM_ICDF(CDF_PROB_TOP);
1479 }
1480 
update_ext_partition_context(MACROBLOCKD * xd,int mi_row,int mi_col,BLOCK_SIZE subsize,BLOCK_SIZE bsize,PARTITION_TYPE partition)1481 static INLINE void update_ext_partition_context(MACROBLOCKD *xd, int mi_row,
1482                                                 int mi_col, BLOCK_SIZE subsize,
1483                                                 BLOCK_SIZE bsize,
1484                                                 PARTITION_TYPE partition) {
1485   if (bsize >= BLOCK_8X8) {
1486     const int hbs = mi_size_wide[bsize] / 2;
1487     BLOCK_SIZE bsize2 = get_partition_subsize(bsize, PARTITION_SPLIT);
1488     switch (partition) {
1489       case PARTITION_SPLIT:
1490         if (bsize != BLOCK_8X8) break;
1491         AOM_FALLTHROUGH_INTENDED;
1492       case PARTITION_NONE:
1493       case PARTITION_HORZ:
1494       case PARTITION_VERT:
1495       case PARTITION_HORZ_4:
1496       case PARTITION_VERT_4:
1497         update_partition_context(xd, mi_row, mi_col, subsize, bsize);
1498         break;
1499       case PARTITION_HORZ_A:
1500         update_partition_context(xd, mi_row, mi_col, bsize2, subsize);
1501         update_partition_context(xd, mi_row + hbs, mi_col, subsize, subsize);
1502         break;
1503       case PARTITION_HORZ_B:
1504         update_partition_context(xd, mi_row, mi_col, subsize, subsize);
1505         update_partition_context(xd, mi_row + hbs, mi_col, bsize2, subsize);
1506         break;
1507       case PARTITION_VERT_A:
1508         update_partition_context(xd, mi_row, mi_col, bsize2, subsize);
1509         update_partition_context(xd, mi_row, mi_col + hbs, subsize, subsize);
1510         break;
1511       case PARTITION_VERT_B:
1512         update_partition_context(xd, mi_row, mi_col, subsize, subsize);
1513         update_partition_context(xd, mi_row, mi_col + hbs, bsize2, subsize);
1514         break;
1515       default: assert(0 && "Invalid partition type");
1516     }
1517   }
1518 }
1519 
partition_plane_context(const MACROBLOCKD * xd,int mi_row,int mi_col,BLOCK_SIZE bsize)1520 static INLINE int partition_plane_context(const MACROBLOCKD *xd, int mi_row,
1521                                           int mi_col, BLOCK_SIZE bsize) {
1522   const PARTITION_CONTEXT *above_ctx = xd->above_partition_context + mi_col;
1523   const PARTITION_CONTEXT *left_ctx =
1524       xd->left_partition_context + (mi_row & MAX_MIB_MASK);
1525   // Minimum partition point is 8x8. Offset the bsl accordingly.
1526   const int bsl = mi_size_wide_log2[bsize] - mi_size_wide_log2[BLOCK_8X8];
1527   int above = (*above_ctx >> bsl) & 1, left = (*left_ctx >> bsl) & 1;
1528 
1529   assert(mi_size_wide_log2[bsize] == mi_size_high_log2[bsize]);
1530   assert(bsl >= 0);
1531 
1532   return (left * 2 + above) + bsl * PARTITION_PLOFFSET;
1533 }
1534 
1535 // Return the number of elements in the partition CDF when
1536 // partitioning the (square) block with luma block size of bsize.
partition_cdf_length(BLOCK_SIZE bsize)1537 static INLINE int partition_cdf_length(BLOCK_SIZE bsize) {
1538   if (bsize <= BLOCK_8X8)
1539     return PARTITION_TYPES;
1540   else if (bsize == BLOCK_128X128)
1541     return EXT_PARTITION_TYPES - 2;
1542   else
1543     return EXT_PARTITION_TYPES;
1544 }
1545 
max_block_wide(const MACROBLOCKD * xd,BLOCK_SIZE bsize,int plane)1546 static INLINE int max_block_wide(const MACROBLOCKD *xd, BLOCK_SIZE bsize,
1547                                  int plane) {
1548   assert(bsize < BLOCK_SIZES_ALL);
1549   int max_blocks_wide = block_size_wide[bsize];
1550 
1551   if (xd->mb_to_right_edge < 0) {
1552     const struct macroblockd_plane *const pd = &xd->plane[plane];
1553     max_blocks_wide += xd->mb_to_right_edge >> (3 + pd->subsampling_x);
1554   }
1555 
1556   // Scale the width in the transform block unit.
1557   return max_blocks_wide >> MI_SIZE_LOG2;
1558 }
1559 
max_block_high(const MACROBLOCKD * xd,BLOCK_SIZE bsize,int plane)1560 static INLINE int max_block_high(const MACROBLOCKD *xd, BLOCK_SIZE bsize,
1561                                  int plane) {
1562   int max_blocks_high = block_size_high[bsize];
1563 
1564   if (xd->mb_to_bottom_edge < 0) {
1565     const struct macroblockd_plane *const pd = &xd->plane[plane];
1566     max_blocks_high += xd->mb_to_bottom_edge >> (3 + pd->subsampling_y);
1567   }
1568 
1569   // Scale the height in the transform block unit.
1570   return max_blocks_high >> MI_SIZE_LOG2;
1571 }
1572 
av1_zero_above_context(AV1_COMMON * const cm,const MACROBLOCKD * xd,int mi_col_start,int mi_col_end,const int tile_row)1573 static INLINE void av1_zero_above_context(AV1_COMMON *const cm,
1574                                           const MACROBLOCKD *xd,
1575                                           int mi_col_start, int mi_col_end,
1576                                           const int tile_row) {
1577   const SequenceHeader *const seq_params = cm->seq_params;
1578   const int num_planes = av1_num_planes(cm);
1579   const int width = mi_col_end - mi_col_start;
1580   const int aligned_width =
1581       ALIGN_POWER_OF_TWO(width, seq_params->mib_size_log2);
1582   const int offset_y = mi_col_start;
1583   const int width_y = aligned_width;
1584   const int offset_uv = offset_y >> seq_params->subsampling_x;
1585   const int width_uv = width_y >> seq_params->subsampling_x;
1586   CommonContexts *const above_contexts = &cm->above_contexts;
1587 
1588   av1_zero_array(above_contexts->entropy[0][tile_row] + offset_y, width_y);
1589   if (num_planes > 1) {
1590     if (above_contexts->entropy[1][tile_row] &&
1591         above_contexts->entropy[2][tile_row]) {
1592       av1_zero_array(above_contexts->entropy[1][tile_row] + offset_uv,
1593                      width_uv);
1594       av1_zero_array(above_contexts->entropy[2][tile_row] + offset_uv,
1595                      width_uv);
1596     } else {
1597       aom_internal_error(xd->error_info, AOM_CODEC_CORRUPT_FRAME,
1598                          "Invalid value of planes");
1599     }
1600   }
1601 
1602   av1_zero_array(above_contexts->partition[tile_row] + mi_col_start,
1603                  aligned_width);
1604 
1605   memset(above_contexts->txfm[tile_row] + mi_col_start,
1606          tx_size_wide[TX_SIZES_LARGEST], aligned_width * sizeof(TXFM_CONTEXT));
1607 }
1608 
av1_zero_left_context(MACROBLOCKD * const xd)1609 static INLINE void av1_zero_left_context(MACROBLOCKD *const xd) {
1610   av1_zero(xd->left_entropy_context);
1611   av1_zero(xd->left_partition_context);
1612 
1613   memset(xd->left_txfm_context_buffer, tx_size_high[TX_SIZES_LARGEST],
1614          sizeof(xd->left_txfm_context_buffer));
1615 }
1616 
1617 // Disable array-bounds checks as the TX_SIZE enum contains values larger than
1618 // TX_SIZES_ALL (TX_INVALID) which make extending the array as a workaround
1619 // infeasible. The assert is enough for static analysis and this or other tools
1620 // asan, valgrind would catch oob access at runtime.
1621 #if defined(__GNUC__) && __GNUC__ >= 4
1622 #pragma GCC diagnostic ignored "-Warray-bounds"
1623 #endif
1624 
1625 #if defined(__GNUC__) && __GNUC__ >= 4
1626 #pragma GCC diagnostic warning "-Warray-bounds"
1627 #endif
1628 
set_txfm_ctx(TXFM_CONTEXT * txfm_ctx,uint8_t txs,int len)1629 static INLINE void set_txfm_ctx(TXFM_CONTEXT *txfm_ctx, uint8_t txs, int len) {
1630   int i;
1631   for (i = 0; i < len; ++i) txfm_ctx[i] = txs;
1632 }
1633 
set_txfm_ctxs(TX_SIZE tx_size,int n4_w,int n4_h,int skip,const MACROBLOCKD * xd)1634 static INLINE void set_txfm_ctxs(TX_SIZE tx_size, int n4_w, int n4_h, int skip,
1635                                  const MACROBLOCKD *xd) {
1636   uint8_t bw = tx_size_wide[tx_size];
1637   uint8_t bh = tx_size_high[tx_size];
1638 
1639   if (skip) {
1640     bw = n4_w * MI_SIZE;
1641     bh = n4_h * MI_SIZE;
1642   }
1643 
1644   set_txfm_ctx(xd->above_txfm_context, bw, n4_w);
1645   set_txfm_ctx(xd->left_txfm_context, bh, n4_h);
1646 }
1647 
get_mi_grid_idx(const CommonModeInfoParams * const mi_params,int mi_row,int mi_col)1648 static INLINE int get_mi_grid_idx(const CommonModeInfoParams *const mi_params,
1649                                   int mi_row, int mi_col) {
1650   return mi_row * mi_params->mi_stride + mi_col;
1651 }
1652 
get_alloc_mi_idx(const CommonModeInfoParams * const mi_params,int mi_row,int mi_col)1653 static INLINE int get_alloc_mi_idx(const CommonModeInfoParams *const mi_params,
1654                                    int mi_row, int mi_col) {
1655   const int mi_alloc_size_1d = mi_size_wide[mi_params->mi_alloc_bsize];
1656   const int mi_alloc_row = mi_row / mi_alloc_size_1d;
1657   const int mi_alloc_col = mi_col / mi_alloc_size_1d;
1658 
1659   return mi_alloc_row * mi_params->mi_alloc_stride + mi_alloc_col;
1660 }
1661 
1662 // For this partition block, set pointers in mi_params->mi_grid_base and xd->mi.
set_mi_offsets(const CommonModeInfoParams * const mi_params,MACROBLOCKD * const xd,int mi_row,int mi_col)1663 static INLINE void set_mi_offsets(const CommonModeInfoParams *const mi_params,
1664                                   MACROBLOCKD *const xd, int mi_row,
1665                                   int mi_col) {
1666   // 'mi_grid_base' should point to appropriate memory in 'mi'.
1667   const int mi_grid_idx = get_mi_grid_idx(mi_params, mi_row, mi_col);
1668   const int mi_alloc_idx = get_alloc_mi_idx(mi_params, mi_row, mi_col);
1669   mi_params->mi_grid_base[mi_grid_idx] = &mi_params->mi_alloc[mi_alloc_idx];
1670   // 'xd->mi' should point to an offset in 'mi_grid_base';
1671   xd->mi = mi_params->mi_grid_base + mi_grid_idx;
1672   // 'xd->tx_type_map' should point to an offset in 'mi_params->tx_type_map'.
1673   xd->tx_type_map = mi_params->tx_type_map + mi_grid_idx;
1674   xd->tx_type_map_stride = mi_params->mi_stride;
1675 }
1676 
txfm_partition_update(TXFM_CONTEXT * above_ctx,TXFM_CONTEXT * left_ctx,TX_SIZE tx_size,TX_SIZE txb_size)1677 static INLINE void txfm_partition_update(TXFM_CONTEXT *above_ctx,
1678                                          TXFM_CONTEXT *left_ctx,
1679                                          TX_SIZE tx_size, TX_SIZE txb_size) {
1680   BLOCK_SIZE bsize = txsize_to_bsize[txb_size];
1681   int bh = mi_size_high[bsize];
1682   int bw = mi_size_wide[bsize];
1683   uint8_t txw = tx_size_wide[tx_size];
1684   uint8_t txh = tx_size_high[tx_size];
1685   int i;
1686   for (i = 0; i < bh; ++i) left_ctx[i] = txh;
1687   for (i = 0; i < bw; ++i) above_ctx[i] = txw;
1688 }
1689 
get_sqr_tx_size(int tx_dim)1690 static INLINE TX_SIZE get_sqr_tx_size(int tx_dim) {
1691   switch (tx_dim) {
1692     case 128:
1693     case 64: return TX_64X64; break;
1694     case 32: return TX_32X32; break;
1695     case 16: return TX_16X16; break;
1696     case 8: return TX_8X8; break;
1697     default: return TX_4X4;
1698   }
1699 }
1700 
get_tx_size(int width,int height)1701 static INLINE TX_SIZE get_tx_size(int width, int height) {
1702   if (width == height) {
1703     return get_sqr_tx_size(width);
1704   }
1705   if (width < height) {
1706     if (width + width == height) {
1707       switch (width) {
1708         case 4: return TX_4X8; break;
1709         case 8: return TX_8X16; break;
1710         case 16: return TX_16X32; break;
1711         case 32: return TX_32X64; break;
1712       }
1713     } else {
1714       switch (width) {
1715         case 4: return TX_4X16; break;
1716         case 8: return TX_8X32; break;
1717         case 16: return TX_16X64; break;
1718       }
1719     }
1720   } else {
1721     if (height + height == width) {
1722       switch (height) {
1723         case 4: return TX_8X4; break;
1724         case 8: return TX_16X8; break;
1725         case 16: return TX_32X16; break;
1726         case 32: return TX_64X32; break;
1727       }
1728     } else {
1729       switch (height) {
1730         case 4: return TX_16X4; break;
1731         case 8: return TX_32X8; break;
1732         case 16: return TX_64X16; break;
1733       }
1734     }
1735   }
1736   assert(0);
1737   return TX_4X4;
1738 }
1739 
txfm_partition_context(const TXFM_CONTEXT * const above_ctx,const TXFM_CONTEXT * const left_ctx,BLOCK_SIZE bsize,TX_SIZE tx_size)1740 static INLINE int txfm_partition_context(const TXFM_CONTEXT *const above_ctx,
1741                                          const TXFM_CONTEXT *const left_ctx,
1742                                          BLOCK_SIZE bsize, TX_SIZE tx_size) {
1743   const uint8_t txw = tx_size_wide[tx_size];
1744   const uint8_t txh = tx_size_high[tx_size];
1745   const int above = *above_ctx < txw;
1746   const int left = *left_ctx < txh;
1747   int category = TXFM_PARTITION_CONTEXTS;
1748 
1749   // dummy return, not used by others.
1750   if (tx_size <= TX_4X4) return 0;
1751 
1752   TX_SIZE max_tx_size =
1753       get_sqr_tx_size(AOMMAX(block_size_wide[bsize], block_size_high[bsize]));
1754 
1755   if (max_tx_size >= TX_8X8) {
1756     category =
1757         (txsize_sqr_up_map[tx_size] != max_tx_size && max_tx_size > TX_8X8) +
1758         (TX_SIZES - 1 - max_tx_size) * 2;
1759   }
1760   assert(category != TXFM_PARTITION_CONTEXTS);
1761   return category * 3 + above + left;
1762 }
1763 
1764 // Compute the next partition in the direction of the sb_type stored in the mi
1765 // array, starting with bsize.
get_partition(const AV1_COMMON * const cm,int mi_row,int mi_col,BLOCK_SIZE bsize)1766 static INLINE PARTITION_TYPE get_partition(const AV1_COMMON *const cm,
1767                                            int mi_row, int mi_col,
1768                                            BLOCK_SIZE bsize) {
1769   const CommonModeInfoParams *const mi_params = &cm->mi_params;
1770   if (mi_row >= mi_params->mi_rows || mi_col >= mi_params->mi_cols)
1771     return PARTITION_INVALID;
1772 
1773   const int offset = mi_row * mi_params->mi_stride + mi_col;
1774   MB_MODE_INFO **mi = mi_params->mi_grid_base + offset;
1775   const BLOCK_SIZE subsize = mi[0]->bsize;
1776 
1777   assert(bsize < BLOCK_SIZES_ALL);
1778 
1779   if (subsize == bsize) return PARTITION_NONE;
1780 
1781   const int bhigh = mi_size_high[bsize];
1782   const int bwide = mi_size_wide[bsize];
1783   const int sshigh = mi_size_high[subsize];
1784   const int sswide = mi_size_wide[subsize];
1785 
1786   if (bsize > BLOCK_8X8 && mi_row + bwide / 2 < mi_params->mi_rows &&
1787       mi_col + bhigh / 2 < mi_params->mi_cols) {
1788     // In this case, the block might be using an extended partition
1789     // type.
1790     const MB_MODE_INFO *const mbmi_right = mi[bwide / 2];
1791     const MB_MODE_INFO *const mbmi_below = mi[bhigh / 2 * mi_params->mi_stride];
1792 
1793     if (sswide == bwide) {
1794       // Smaller height but same width. Is PARTITION_HORZ_4, PARTITION_HORZ or
1795       // PARTITION_HORZ_B. To distinguish the latter two, check if the lower
1796       // half was split.
1797       if (sshigh * 4 == bhigh) return PARTITION_HORZ_4;
1798       assert(sshigh * 2 == bhigh);
1799 
1800       if (mbmi_below->bsize == subsize)
1801         return PARTITION_HORZ;
1802       else
1803         return PARTITION_HORZ_B;
1804     } else if (sshigh == bhigh) {
1805       // Smaller width but same height. Is PARTITION_VERT_4, PARTITION_VERT or
1806       // PARTITION_VERT_B. To distinguish the latter two, check if the right
1807       // half was split.
1808       if (sswide * 4 == bwide) return PARTITION_VERT_4;
1809       assert(sswide * 2 == bhigh);
1810 
1811       if (mbmi_right->bsize == subsize)
1812         return PARTITION_VERT;
1813       else
1814         return PARTITION_VERT_B;
1815     } else {
1816       // Smaller width and smaller height. Might be PARTITION_SPLIT or could be
1817       // PARTITION_HORZ_A or PARTITION_VERT_A. If subsize isn't halved in both
1818       // dimensions, we immediately know this is a split (which will recurse to
1819       // get to subsize). Otherwise look down and to the right. With
1820       // PARTITION_VERT_A, the right block will have height bhigh; with
1821       // PARTITION_HORZ_A, the lower block with have width bwide. Otherwise
1822       // it's PARTITION_SPLIT.
1823       if (sswide * 2 != bwide || sshigh * 2 != bhigh) return PARTITION_SPLIT;
1824 
1825       if (mi_size_wide[mbmi_below->bsize] == bwide) return PARTITION_HORZ_A;
1826       if (mi_size_high[mbmi_right->bsize] == bhigh) return PARTITION_VERT_A;
1827 
1828       return PARTITION_SPLIT;
1829     }
1830   }
1831   const int vert_split = sswide < bwide;
1832   const int horz_split = sshigh < bhigh;
1833   const int split_idx = (vert_split << 1) | horz_split;
1834   assert(split_idx != 0);
1835 
1836   static const PARTITION_TYPE base_partitions[4] = {
1837     PARTITION_INVALID, PARTITION_HORZ, PARTITION_VERT, PARTITION_SPLIT
1838   };
1839 
1840   return base_partitions[split_idx];
1841 }
1842 
set_sb_size(SequenceHeader * const seq_params,BLOCK_SIZE sb_size)1843 static INLINE void set_sb_size(SequenceHeader *const seq_params,
1844                                BLOCK_SIZE sb_size) {
1845   seq_params->sb_size = sb_size;
1846   seq_params->mib_size = mi_size_wide[seq_params->sb_size];
1847   seq_params->mib_size_log2 = mi_size_wide_log2[seq_params->sb_size];
1848 }
1849 
1850 // Returns true if the frame is fully lossless at the coded resolution.
1851 // Note: If super-resolution is used, such a frame will still NOT be lossless at
1852 // the upscaled resolution.
is_coded_lossless(const AV1_COMMON * cm,const MACROBLOCKD * xd)1853 static INLINE int is_coded_lossless(const AV1_COMMON *cm,
1854                                     const MACROBLOCKD *xd) {
1855   int coded_lossless = 1;
1856   if (cm->seg.enabled) {
1857     for (int i = 0; i < MAX_SEGMENTS; ++i) {
1858       if (!xd->lossless[i]) {
1859         coded_lossless = 0;
1860         break;
1861       }
1862     }
1863   } else {
1864     coded_lossless = xd->lossless[0];
1865   }
1866   return coded_lossless;
1867 }
1868 
is_valid_seq_level_idx(AV1_LEVEL seq_level_idx)1869 static INLINE int is_valid_seq_level_idx(AV1_LEVEL seq_level_idx) {
1870   return seq_level_idx == SEQ_LEVEL_MAX ||
1871          (seq_level_idx < SEQ_LEVELS &&
1872           // The following levels are currently undefined.
1873           seq_level_idx != SEQ_LEVEL_2_2 && seq_level_idx != SEQ_LEVEL_2_3 &&
1874           seq_level_idx != SEQ_LEVEL_3_2 && seq_level_idx != SEQ_LEVEL_3_3 &&
1875           seq_level_idx != SEQ_LEVEL_4_2 && seq_level_idx != SEQ_LEVEL_4_3 &&
1876           seq_level_idx != SEQ_LEVEL_7_0 && seq_level_idx != SEQ_LEVEL_7_1 &&
1877           seq_level_idx != SEQ_LEVEL_7_2 && seq_level_idx != SEQ_LEVEL_7_3);
1878 }
1879 
1880 /*!\endcond */
1881 
1882 #ifdef __cplusplus
1883 }  // extern "C"
1884 #endif
1885 
1886 #endif  // AOM_AV1_COMMON_AV1_COMMON_INT_H_
1887