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