summaryrefslogtreecommitdiffstats
path: root/third_party/aom/av1/decoder
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-19 00:47:55 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-19 00:47:55 +0000
commit26a029d407be480d791972afb5975cf62c9360a6 (patch)
treef435a8308119effd964b339f76abb83a57c29483 /third_party/aom/av1/decoder
parentInitial commit. (diff)
downloadfirefox-26a029d407be480d791972afb5975cf62c9360a6.tar.xz
firefox-26a029d407be480d791972afb5975cf62c9360a6.zip
Adding upstream version 124.0.1.upstream/124.0.1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to '')
-rw-r--r--third_party/aom/av1/decoder/accounting.c140
-rw-r--r--third_party/aom/av1/decoder/accounting.h82
-rw-r--r--third_party/aom/av1/decoder/decodeframe.c5369
-rw-r--r--third_party/aom/av1/decoder/decodeframe.h84
-rw-r--r--third_party/aom/av1/decoder/decodemv.c1586
-rw-r--r--third_party/aom/av1/decoder/decodemv.h33
-rw-r--r--third_party/aom/av1/decoder/decoder.c538
-rw-r--r--third_party/aom/av1/decoder/decoder.h452
-rw-r--r--third_party/aom/av1/decoder/decodetxb.c381
-rw-r--r--third_party/aom/av1/decoder/decodetxb.h34
-rw-r--r--third_party/aom/av1/decoder/detokenize.c78
-rw-r--r--third_party/aom/av1/decoder/detokenize.h29
-rw-r--r--third_party/aom/av1/decoder/dthread.h51
-rw-r--r--third_party/aom/av1/decoder/grain_synthesis.c1461
-rw-r--r--third_party/aom/av1/decoder/grain_synthesis.h66
-rw-r--r--third_party/aom/av1/decoder/inspection.c162
-rw-r--r--third_party/aom/av1/decoder/inspection.h91
-rw-r--r--third_party/aom/av1/decoder/obu.c1101
-rw-r--r--third_party/aom/av1/decoder/obu.h31
19 files changed, 11769 insertions, 0 deletions
diff --git a/third_party/aom/av1/decoder/accounting.c b/third_party/aom/av1/decoder/accounting.c
new file mode 100644
index 0000000000..1ded380ec3
--- /dev/null
+++ b/third_party/aom/av1/decoder/accounting.c
@@ -0,0 +1,140 @@
+/*
+ * Copyright (c) 2016, Alliance for Open Media. All rights reserved
+ *
+ * This source code is subject to the terms of the BSD 2 Clause License and
+ * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
+ * was not distributed with this source code in the LICENSE file, you can
+ * obtain it at www.aomedia.org/license/software. If the Alliance for Open
+ * Media Patent License 1.0 was not distributed with this source code in the
+ * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
+ */
+
+#include <assert.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "aom/aom_integer.h"
+#include "av1/decoder/accounting.h"
+
+static int accounting_hash(const char *str) {
+ uint32_t val;
+ const unsigned char *ustr;
+ val = 0;
+ ustr = (const unsigned char *)str;
+ /* This is about the worst hash one can design, but it should be good enough
+ here. */
+ while (*ustr) val += *ustr++;
+ return val % AOM_ACCOUNTING_HASH_SIZE;
+}
+
+/* Dictionary lookup based on an open-addressing hash table. */
+int aom_accounting_dictionary_lookup(Accounting *accounting, const char *str) {
+ int hash;
+ size_t len;
+ AccountingDictionary *dictionary;
+ dictionary = &accounting->syms.dictionary;
+ hash = accounting_hash(str);
+ while (accounting->hash_dictionary[hash] != -1) {
+ if (strcmp(dictionary->strs[accounting->hash_dictionary[hash]], str) == 0) {
+ return accounting->hash_dictionary[hash];
+ }
+ hash++;
+ if (hash == AOM_ACCOUNTING_HASH_SIZE) hash = 0;
+ }
+ /* No match found. */
+ assert(dictionary->num_strs + 1 < MAX_SYMBOL_TYPES);
+ accounting->hash_dictionary[hash] = dictionary->num_strs;
+ len = strlen(str);
+ dictionary->strs[dictionary->num_strs] = malloc(len + 1);
+ if (!dictionary->strs[dictionary->num_strs]) abort();
+ snprintf(dictionary->strs[dictionary->num_strs], len + 1, "%s", str);
+ dictionary->num_strs++;
+ return dictionary->num_strs - 1;
+}
+
+void aom_accounting_init(Accounting *accounting) {
+ int i;
+ accounting->num_syms_allocated = 1000;
+ accounting->syms.syms =
+ malloc(sizeof(AccountingSymbol) * accounting->num_syms_allocated);
+ if (!accounting->syms.syms) abort();
+ accounting->syms.dictionary.num_strs = 0;
+ assert(AOM_ACCOUNTING_HASH_SIZE > 2 * MAX_SYMBOL_TYPES);
+ for (i = 0; i < AOM_ACCOUNTING_HASH_SIZE; i++)
+ accounting->hash_dictionary[i] = -1;
+ aom_accounting_reset(accounting);
+}
+
+void aom_accounting_reset(Accounting *accounting) {
+ accounting->syms.num_syms = 0;
+ accounting->syms.num_binary_syms = 0;
+ accounting->syms.num_multi_syms = 0;
+ accounting->context.x = -1;
+ accounting->context.y = -1;
+ accounting->last_tell_frac = 0;
+}
+
+void aom_accounting_clear(Accounting *accounting) {
+ int i;
+ AccountingDictionary *dictionary;
+ free(accounting->syms.syms);
+ dictionary = &accounting->syms.dictionary;
+ for (i = 0; i < dictionary->num_strs; i++) {
+ free(dictionary->strs[i]);
+ }
+}
+
+void aom_accounting_set_context(Accounting *accounting, int16_t x, int16_t y) {
+ accounting->context.x = x;
+ accounting->context.y = y;
+}
+
+void aom_accounting_record(Accounting *accounting, const char *str,
+ uint32_t bits) {
+ AccountingSymbol sym;
+ // Reuse previous symbol if it has the same context and symbol id.
+ if (accounting->syms.num_syms) {
+ AccountingSymbol *last_sym;
+ last_sym = &accounting->syms.syms[accounting->syms.num_syms - 1];
+ if (memcmp(&last_sym->context, &accounting->context,
+ sizeof(AccountingSymbolContext)) == 0) {
+ uint32_t id;
+ id = aom_accounting_dictionary_lookup(accounting, str);
+ if (id == last_sym->id) {
+ last_sym->bits += bits;
+ last_sym->samples++;
+ return;
+ }
+ }
+ }
+ sym.context = accounting->context;
+ sym.samples = 1;
+ sym.bits = bits;
+ sym.id = aom_accounting_dictionary_lookup(accounting, str);
+ assert(sym.id <= 255);
+ if (accounting->syms.num_syms == accounting->num_syms_allocated) {
+ accounting->num_syms_allocated *= 2;
+ accounting->syms.syms =
+ realloc(accounting->syms.syms,
+ sizeof(AccountingSymbol) * accounting->num_syms_allocated);
+ if (!accounting->syms.syms) abort();
+ }
+ accounting->syms.syms[accounting->syms.num_syms++] = sym;
+}
+
+void aom_accounting_dump(Accounting *accounting) {
+ int i;
+ AccountingSymbol *sym;
+ printf("\n----- Number of recorded syntax elements = %d -----\n",
+ accounting->syms.num_syms);
+ printf("----- Total number of symbol calls = %d (%d binary) -----\n",
+ accounting->syms.num_multi_syms + accounting->syms.num_binary_syms,
+ accounting->syms.num_binary_syms);
+ for (i = 0; i < accounting->syms.num_syms; i++) {
+ sym = &accounting->syms.syms[i];
+ printf("%s x: %d, y: %d bits: %f samples: %d\n",
+ accounting->syms.dictionary.strs[sym->id], sym->context.x,
+ sym->context.y, (float)sym->bits / 8.0, sym->samples);
+ }
+}
diff --git a/third_party/aom/av1/decoder/accounting.h b/third_party/aom/av1/decoder/accounting.h
new file mode 100644
index 0000000000..ad2e8b6cfe
--- /dev/null
+++ b/third_party/aom/av1/decoder/accounting.h
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 2016, Alliance for Open Media. All rights reserved
+ *
+ * This source code is subject to the terms of the BSD 2 Clause License and
+ * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
+ * was not distributed with this source code in the LICENSE file, you can
+ * obtain it at www.aomedia.org/license/software. If the Alliance for Open
+ * Media Patent License 1.0 was not distributed with this source code in the
+ * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
+ */
+#ifndef AOM_AV1_DECODER_ACCOUNTING_H_
+#define AOM_AV1_DECODER_ACCOUNTING_H_
+#include <stdlib.h>
+#include "aom/aomdx.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+#define AOM_ACCOUNTING_HASH_SIZE (1021)
+
+/* Max number of entries for symbol types in the dictionary (increase as
+ necessary). */
+#define MAX_SYMBOL_TYPES (256)
+
+/*The resolution of fractional-precision bit usage measurements, i.e.,
+ 3 => 1/8th bits.*/
+#define AOM_ACCT_BITRES (3)
+
+typedef struct {
+ int16_t x;
+ int16_t y;
+} AccountingSymbolContext;
+
+typedef struct {
+ AccountingSymbolContext context;
+ uint32_t id;
+ /** Number of bits in units of 1/8 bit. */
+ uint32_t bits;
+ uint32_t samples;
+} AccountingSymbol;
+
+/** Dictionary for translating strings into id. */
+typedef struct {
+ char *strs[MAX_SYMBOL_TYPES];
+ int num_strs;
+} AccountingDictionary;
+
+typedef struct {
+ /** All recorded symbols decoded. */
+ AccountingSymbol *syms;
+ /** Number of syntax actually recorded. */
+ int num_syms;
+ /** Raw symbol decoding calls for non-binary values. */
+ int num_multi_syms;
+ /** Raw binary symbol decoding calls. */
+ int num_binary_syms;
+ /** Dictionary for translating strings into id. */
+ AccountingDictionary dictionary;
+} AccountingSymbols;
+
+struct Accounting {
+ AccountingSymbols syms;
+ /** Size allocated for symbols (not all may be used). */
+ int num_syms_allocated;
+ int16_t hash_dictionary[AOM_ACCOUNTING_HASH_SIZE];
+ AccountingSymbolContext context;
+ uint32_t last_tell_frac;
+};
+
+void aom_accounting_init(Accounting *accounting);
+void aom_accounting_reset(Accounting *accounting);
+void aom_accounting_clear(Accounting *accounting);
+void aom_accounting_set_context(Accounting *accounting, int16_t x, int16_t y);
+int aom_accounting_dictionary_lookup(Accounting *accounting, const char *str);
+void aom_accounting_record(Accounting *accounting, const char *str,
+ uint32_t bits);
+void aom_accounting_dump(Accounting *accounting);
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
+#endif // AOM_AV1_DECODER_ACCOUNTING_H_
diff --git a/third_party/aom/av1/decoder/decodeframe.c b/third_party/aom/av1/decoder/decodeframe.c
new file mode 100644
index 0000000000..bb09347e1c
--- /dev/null
+++ b/third_party/aom/av1/decoder/decodeframe.c
@@ -0,0 +1,5369 @@
+/*
+ * Copyright (c) 2016, Alliance for Open Media. All rights reserved
+ *
+ * This source code is subject to the terms of the BSD 2 Clause License and
+ * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
+ * was not distributed with this source code in the LICENSE file, you can
+ * obtain it at www.aomedia.org/license/software. If the Alliance for Open
+ * Media Patent License 1.0 was not distributed with this source code in the
+ * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
+ */
+
+#include <assert.h>
+#include <stdbool.h>
+#include <stddef.h>
+
+#include "config/aom_config.h"
+#include "config/aom_dsp_rtcd.h"
+#include "config/aom_scale_rtcd.h"
+#include "config/av1_rtcd.h"
+
+#include "aom/aom_codec.h"
+#include "aom_dsp/aom_dsp_common.h"
+#include "aom_dsp/binary_codes_reader.h"
+#include "aom_dsp/bitreader.h"
+#include "aom_dsp/bitreader_buffer.h"
+#include "aom_mem/aom_mem.h"
+#include "aom_ports/aom_timer.h"
+#include "aom_ports/mem.h"
+#include "aom_ports/mem_ops.h"
+#include "aom_scale/aom_scale.h"
+#include "aom_util/aom_thread.h"
+
+#if CONFIG_BITSTREAM_DEBUG || CONFIG_MISMATCH_DEBUG
+#include "aom_util/debug_util.h"
+#endif // CONFIG_BITSTREAM_DEBUG || CONFIG_MISMATCH_DEBUG
+
+#include "av1/common/alloccommon.h"
+#include "av1/common/cdef.h"
+#include "av1/common/cfl.h"
+#if CONFIG_INSPECTION
+#include "av1/decoder/inspection.h"
+#endif
+#include "av1/common/common.h"
+#include "av1/common/entropy.h"
+#include "av1/common/entropymode.h"
+#include "av1/common/entropymv.h"
+#include "av1/common/frame_buffers.h"
+#include "av1/common/idct.h"
+#include "av1/common/mvref_common.h"
+#include "av1/common/pred_common.h"
+#include "av1/common/quant_common.h"
+#include "av1/common/reconinter.h"
+#include "av1/common/reconintra.h"
+#include "av1/common/resize.h"
+#include "av1/common/seg_common.h"
+#include "av1/common/thread_common.h"
+#include "av1/common/tile_common.h"
+#include "av1/common/warped_motion.h"
+#include "av1/common/obmc.h"
+#include "av1/decoder/decodeframe.h"
+#include "av1/decoder/decodemv.h"
+#include "av1/decoder/decoder.h"
+#include "av1/decoder/decodetxb.h"
+#include "av1/decoder/detokenize.h"
+
+#define ACCT_STR __func__
+
+#define AOM_MIN_THREADS_PER_TILE 1
+#define AOM_MAX_THREADS_PER_TILE 2
+
+// This is needed by ext_tile related unit tests.
+#define EXT_TILE_DEBUG 1
+#define MC_TEMP_BUF_PELS \
+ (((MAX_SB_SIZE)*2 + (AOM_INTERP_EXTEND)*2) * \
+ ((MAX_SB_SIZE)*2 + (AOM_INTERP_EXTEND)*2))
+
+// Checks that the remaining bits start with a 1 and ends with 0s.
+// It consumes an additional byte, if already byte aligned before the check.
+int av1_check_trailing_bits(AV1Decoder *pbi, struct aom_read_bit_buffer *rb) {
+ // bit_offset is set to 0 (mod 8) when the reader is already byte aligned
+ int bits_before_alignment = 8 - rb->bit_offset % 8;
+ int trailing = aom_rb_read_literal(rb, bits_before_alignment);
+ if (trailing != (1 << (bits_before_alignment - 1))) {
+ pbi->error.error_code = AOM_CODEC_CORRUPT_FRAME;
+ return -1;
+ }
+ return 0;
+}
+
+// Use only_chroma = 1 to only set the chroma planes
+static AOM_INLINE void set_planes_to_neutral_grey(
+ const SequenceHeader *const seq_params, const YV12_BUFFER_CONFIG *const buf,
+ int only_chroma) {
+ if (seq_params->use_highbitdepth) {
+ const int val = 1 << (seq_params->bit_depth - 1);
+ for (int plane = only_chroma; plane < MAX_MB_PLANE; plane++) {
+ const int is_uv = plane > 0;
+ uint16_t *const base = CONVERT_TO_SHORTPTR(buf->buffers[plane]);
+ // Set the first row to neutral grey. Then copy the first row to all
+ // subsequent rows.
+ if (buf->crop_heights[is_uv] > 0) {
+ aom_memset16(base, val, buf->crop_widths[is_uv]);
+ for (int row_idx = 1; row_idx < buf->crop_heights[is_uv]; row_idx++) {
+ memcpy(&base[row_idx * buf->strides[is_uv]], base,
+ sizeof(*base) * buf->crop_widths[is_uv]);
+ }
+ }
+ }
+ } else {
+ for (int plane = only_chroma; plane < MAX_MB_PLANE; plane++) {
+ const int is_uv = plane > 0;
+ for (int row_idx = 0; row_idx < buf->crop_heights[is_uv]; row_idx++) {
+ memset(&buf->buffers[plane][row_idx * buf->strides[is_uv]], 1 << 7,
+ buf->crop_widths[is_uv]);
+ }
+ }
+ }
+}
+
+static AOM_INLINE void loop_restoration_read_sb_coeffs(
+ const AV1_COMMON *const cm, MACROBLOCKD *xd, aom_reader *const r, int plane,
+ int runit_idx);
+
+static int read_is_valid(const uint8_t *start, size_t len, const uint8_t *end) {
+ return len != 0 && len <= (size_t)(end - start);
+}
+
+static TX_MODE read_tx_mode(struct aom_read_bit_buffer *rb,
+ int coded_lossless) {
+ if (coded_lossless) return ONLY_4X4;
+ return aom_rb_read_bit(rb) ? TX_MODE_SELECT : TX_MODE_LARGEST;
+}
+
+static REFERENCE_MODE read_frame_reference_mode(
+ const AV1_COMMON *cm, struct aom_read_bit_buffer *rb) {
+ if (frame_is_intra_only(cm)) {
+ return SINGLE_REFERENCE;
+ } else {
+ return aom_rb_read_bit(rb) ? REFERENCE_MODE_SELECT : SINGLE_REFERENCE;
+ }
+}
+
+static AOM_INLINE void inverse_transform_block(DecoderCodingBlock *dcb,
+ int plane, const TX_TYPE tx_type,
+ const TX_SIZE tx_size,
+ uint8_t *dst, int stride,
+ int reduced_tx_set) {
+ tran_low_t *const dqcoeff = dcb->dqcoeff_block[plane] + dcb->cb_offset[plane];
+ eob_info *eob_data = dcb->eob_data[plane] + dcb->txb_offset[plane];
+ uint16_t scan_line = eob_data->max_scan_line;
+ uint16_t eob = eob_data->eob;
+ av1_inverse_transform_block(&dcb->xd, dqcoeff, plane, tx_type, tx_size, dst,
+ stride, eob, reduced_tx_set);
+ memset(dqcoeff, 0, (scan_line + 1) * sizeof(dqcoeff[0]));
+}
+
+static AOM_INLINE void read_coeffs_tx_intra_block(
+ const AV1_COMMON *const cm, DecoderCodingBlock *dcb, aom_reader *const r,
+ const int plane, const int row, const int col, const TX_SIZE tx_size) {
+ MB_MODE_INFO *mbmi = dcb->xd.mi[0];
+ if (!mbmi->skip_txfm) {
+#if TXCOEFF_TIMER
+ struct aom_usec_timer timer;
+ aom_usec_timer_start(&timer);
+#endif
+ av1_read_coeffs_txb_facade(cm, dcb, r, plane, row, col, tx_size);
+#if TXCOEFF_TIMER
+ aom_usec_timer_mark(&timer);
+ const int64_t elapsed_time = aom_usec_timer_elapsed(&timer);
+ cm->txcoeff_timer += elapsed_time;
+ ++cm->txb_count;
+#endif
+ }
+}
+
+static AOM_INLINE void decode_block_void(const AV1_COMMON *const cm,
+ DecoderCodingBlock *dcb,
+ aom_reader *const r, const int plane,
+ const int row, const int col,
+ const TX_SIZE tx_size) {
+ (void)cm;
+ (void)dcb;
+ (void)r;
+ (void)plane;
+ (void)row;
+ (void)col;
+ (void)tx_size;
+}
+
+static AOM_INLINE void predict_inter_block_void(AV1_COMMON *const cm,
+ DecoderCodingBlock *dcb,
+ BLOCK_SIZE bsize) {
+ (void)cm;
+ (void)dcb;
+ (void)bsize;
+}
+
+static AOM_INLINE void cfl_store_inter_block_void(AV1_COMMON *const cm,
+ MACROBLOCKD *const xd) {
+ (void)cm;
+ (void)xd;
+}
+
+static AOM_INLINE void predict_and_reconstruct_intra_block(
+ const AV1_COMMON *const cm, DecoderCodingBlock *dcb, aom_reader *const r,
+ const int plane, const int row, const int col, const TX_SIZE tx_size) {
+ (void)r;
+ MACROBLOCKD *const xd = &dcb->xd;
+ MB_MODE_INFO *mbmi = xd->mi[0];
+ PLANE_TYPE plane_type = get_plane_type(plane);
+
+ av1_predict_intra_block_facade(cm, xd, plane, col, row, tx_size);
+
+ if (!mbmi->skip_txfm) {
+ eob_info *eob_data = dcb->eob_data[plane] + dcb->txb_offset[plane];
+ if (eob_data->eob) {
+ const bool reduced_tx_set_used = cm->features.reduced_tx_set_used;
+ // tx_type was read out in av1_read_coeffs_txb.
+ const TX_TYPE tx_type = av1_get_tx_type(xd, plane_type, row, col, tx_size,
+ reduced_tx_set_used);
+ struct macroblockd_plane *const pd = &xd->plane[plane];
+ uint8_t *dst = &pd->dst.buf[(row * pd->dst.stride + col) << MI_SIZE_LOG2];
+ inverse_transform_block(dcb, plane, tx_type, tx_size, dst, pd->dst.stride,
+ reduced_tx_set_used);
+ }
+ }
+ if (plane == AOM_PLANE_Y && store_cfl_required(cm, xd)) {
+ cfl_store_tx(xd, row, col, tx_size, mbmi->bsize);
+ }
+}
+
+static AOM_INLINE void inverse_transform_inter_block(
+ const AV1_COMMON *const cm, DecoderCodingBlock *dcb, aom_reader *const r,
+ const int plane, const int blk_row, const int blk_col,
+ const TX_SIZE tx_size) {
+ (void)r;
+ MACROBLOCKD *const xd = &dcb->xd;
+ PLANE_TYPE plane_type = get_plane_type(plane);
+ const struct macroblockd_plane *const pd = &xd->plane[plane];
+ const bool reduced_tx_set_used = cm->features.reduced_tx_set_used;
+ // tx_type was read out in av1_read_coeffs_txb.
+ const TX_TYPE tx_type = av1_get_tx_type(xd, plane_type, blk_row, blk_col,
+ tx_size, reduced_tx_set_used);
+
+ uint8_t *dst =
+ &pd->dst.buf[(blk_row * pd->dst.stride + blk_col) << MI_SIZE_LOG2];
+ inverse_transform_block(dcb, plane, tx_type, tx_size, dst, pd->dst.stride,
+ reduced_tx_set_used);
+#if CONFIG_MISMATCH_DEBUG
+ int pixel_c, pixel_r;
+ BLOCK_SIZE bsize = txsize_to_bsize[tx_size];
+ int blk_w = block_size_wide[bsize];
+ int blk_h = block_size_high[bsize];
+ const int mi_row = -xd->mb_to_top_edge >> (3 + MI_SIZE_LOG2);
+ const int mi_col = -xd->mb_to_left_edge >> (3 + MI_SIZE_LOG2);
+ mi_to_pixel_loc(&pixel_c, &pixel_r, mi_col, mi_row, blk_col, blk_row,
+ pd->subsampling_x, pd->subsampling_y);
+ mismatch_check_block_tx(dst, pd->dst.stride, cm->current_frame.order_hint,
+ plane, pixel_c, pixel_r, blk_w, blk_h,
+ xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH);
+#endif
+}
+
+static AOM_INLINE void set_cb_buffer_offsets(DecoderCodingBlock *dcb,
+ TX_SIZE tx_size, int plane) {
+ dcb->cb_offset[plane] += tx_size_wide[tx_size] * tx_size_high[tx_size];
+ dcb->txb_offset[plane] =
+ dcb->cb_offset[plane] / (TX_SIZE_W_MIN * TX_SIZE_H_MIN);
+}
+
+static AOM_INLINE void decode_reconstruct_tx(
+ AV1_COMMON *cm, ThreadData *const td, aom_reader *r,
+ MB_MODE_INFO *const mbmi, int plane, BLOCK_SIZE plane_bsize, int blk_row,
+ int blk_col, int block, TX_SIZE tx_size, int *eob_total) {
+ DecoderCodingBlock *const dcb = &td->dcb;
+ MACROBLOCKD *const xd = &dcb->xd;
+ const struct macroblockd_plane *const pd = &xd->plane[plane];
+ const TX_SIZE plane_tx_size =
+ plane ? av1_get_max_uv_txsize(mbmi->bsize, pd->subsampling_x,
+ pd->subsampling_y)
+ : mbmi->inter_tx_size[av1_get_txb_size_index(plane_bsize, blk_row,
+ blk_col)];
+ // Scale to match transform block unit.
+ const int max_blocks_high = max_block_high(xd, plane_bsize, plane);
+ const int max_blocks_wide = max_block_wide(xd, plane_bsize, plane);
+
+ if (blk_row >= max_blocks_high || blk_col >= max_blocks_wide) return;
+
+ if (tx_size == plane_tx_size || plane) {
+ td->read_coeffs_tx_inter_block_visit(cm, dcb, r, plane, blk_row, blk_col,
+ tx_size);
+
+ td->inverse_tx_inter_block_visit(cm, dcb, r, plane, blk_row, blk_col,
+ tx_size);
+ eob_info *eob_data = dcb->eob_data[plane] + dcb->txb_offset[plane];
+ *eob_total += eob_data->eob;
+ set_cb_buffer_offsets(dcb, tx_size, plane);
+ } else {
+ const TX_SIZE sub_txs = sub_tx_size_map[tx_size];
+ assert(IMPLIES(tx_size <= TX_4X4, sub_txs == tx_size));
+ assert(IMPLIES(tx_size > TX_4X4, sub_txs < tx_size));
+ const int bsw = tx_size_wide_unit[sub_txs];
+ const int bsh = tx_size_high_unit[sub_txs];
+ const int sub_step = bsw * bsh;
+ const int row_end =
+ AOMMIN(tx_size_high_unit[tx_size], max_blocks_high - blk_row);
+ const int col_end =
+ AOMMIN(tx_size_wide_unit[tx_size], max_blocks_wide - blk_col);
+
+ assert(bsw > 0 && bsh > 0);
+
+ for (int row = 0; row < row_end; row += bsh) {
+ const int offsetr = blk_row + row;
+ for (int col = 0; col < col_end; col += bsw) {
+ const int offsetc = blk_col + col;
+
+ decode_reconstruct_tx(cm, td, r, mbmi, plane, plane_bsize, offsetr,
+ offsetc, block, sub_txs, eob_total);
+ block += sub_step;
+ }
+ }
+ }
+}
+
+static AOM_INLINE void set_offsets(AV1_COMMON *const cm, MACROBLOCKD *const xd,
+ BLOCK_SIZE bsize, int mi_row, int mi_col,
+ int bw, int bh, int x_mis, int y_mis) {
+ const int num_planes = av1_num_planes(cm);
+ const CommonModeInfoParams *const mi_params = &cm->mi_params;
+ const TileInfo *const tile = &xd->tile;
+
+ set_mi_offsets(mi_params, xd, mi_row, mi_col);
+ xd->mi[0]->bsize = bsize;
+#if CONFIG_RD_DEBUG
+ xd->mi[0]->mi_row = mi_row;
+ xd->mi[0]->mi_col = mi_col;
+#endif
+
+ assert(x_mis && y_mis);
+ for (int x = 1; x < x_mis; ++x) xd->mi[x] = xd->mi[0];
+ int idx = mi_params->mi_stride;
+ for (int y = 1; y < y_mis; ++y) {
+ memcpy(&xd->mi[idx], &xd->mi[0], x_mis * sizeof(xd->mi[0]));
+ idx += mi_params->mi_stride;
+ }
+
+ set_plane_n4(xd, bw, bh, num_planes);
+ set_entropy_context(xd, mi_row, mi_col, num_planes);
+
+ // Distance of Mb to the various image edges. These are specified to 8th pel
+ // as they are always compared to values that are in 1/8th pel units
+ set_mi_row_col(xd, tile, mi_row, bh, mi_col, bw, mi_params->mi_rows,
+ mi_params->mi_cols);
+
+ av1_setup_dst_planes(xd->plane, bsize, &cm->cur_frame->buf, mi_row, mi_col, 0,
+ num_planes);
+}
+
+static AOM_INLINE void decode_mbmi_block(AV1Decoder *const pbi,
+ DecoderCodingBlock *dcb, int mi_row,
+ int mi_col, aom_reader *r,
+ PARTITION_TYPE partition,
+ BLOCK_SIZE bsize) {
+ AV1_COMMON *const cm = &pbi->common;
+ const SequenceHeader *const seq_params = cm->seq_params;
+ const int bw = mi_size_wide[bsize];
+ const int bh = mi_size_high[bsize];
+ const int x_mis = AOMMIN(bw, cm->mi_params.mi_cols - mi_col);
+ const int y_mis = AOMMIN(bh, cm->mi_params.mi_rows - mi_row);
+ MACROBLOCKD *const xd = &dcb->xd;
+
+#if CONFIG_ACCOUNTING
+ aom_accounting_set_context(&pbi->accounting, mi_col, mi_row);
+#endif
+ set_offsets(cm, xd, bsize, mi_row, mi_col, bw, bh, x_mis, y_mis);
+ xd->mi[0]->partition = partition;
+ av1_read_mode_info(pbi, dcb, r, x_mis, y_mis);
+ if (bsize >= BLOCK_8X8 &&
+ (seq_params->subsampling_x || seq_params->subsampling_y)) {
+ const BLOCK_SIZE uv_subsize =
+ av1_ss_size_lookup[bsize][seq_params->subsampling_x]
+ [seq_params->subsampling_y];
+ if (uv_subsize == BLOCK_INVALID)
+ aom_internal_error(xd->error_info, AOM_CODEC_CORRUPT_FRAME,
+ "Invalid block size.");
+ }
+}
+
+typedef struct PadBlock {
+ int x0;
+ int x1;
+ int y0;
+ int y1;
+} PadBlock;
+
+#if CONFIG_AV1_HIGHBITDEPTH
+static AOM_INLINE void highbd_build_mc_border(const uint8_t *src8,
+ int src_stride, uint8_t *dst8,
+ int dst_stride, int x, int y,
+ int b_w, int b_h, int w, int h) {
+ // Get a pointer to the start of the real data for this row.
+ const uint16_t *src = CONVERT_TO_SHORTPTR(src8);
+ uint16_t *dst = CONVERT_TO_SHORTPTR(dst8);
+ const uint16_t *ref_row = src - x - y * src_stride;
+
+ if (y >= h)
+ ref_row += (h - 1) * src_stride;
+ else if (y > 0)
+ ref_row += y * src_stride;
+
+ do {
+ int right = 0, copy;
+ int left = x < 0 ? -x : 0;
+
+ if (left > b_w) left = b_w;
+
+ if (x + b_w > w) right = x + b_w - w;
+
+ if (right > b_w) right = b_w;
+
+ copy = b_w - left - right;
+
+ if (left) aom_memset16(dst, ref_row[0], left);
+
+ if (copy) memcpy(dst + left, ref_row + x + left, copy * sizeof(uint16_t));
+
+ if (right) aom_memset16(dst + left + copy, ref_row[w - 1], right);
+
+ dst += dst_stride;
+ ++y;
+
+ if (y > 0 && y < h) ref_row += src_stride;
+ } while (--b_h);
+}
+#endif // CONFIG_AV1_HIGHBITDEPTH
+
+static AOM_INLINE void build_mc_border(const uint8_t *src, int src_stride,
+ uint8_t *dst, int dst_stride, int x,
+ int y, int b_w, int b_h, int w, int h) {
+ // Get a pointer to the start of the real data for this row.
+ const uint8_t *ref_row = src - x - y * src_stride;
+
+ if (y >= h)
+ ref_row += (h - 1) * src_stride;
+ else if (y > 0)
+ ref_row += y * src_stride;
+
+ do {
+ int right = 0, copy;
+ int left = x < 0 ? -x : 0;
+
+ if (left > b_w) left = b_w;
+
+ if (x + b_w > w) right = x + b_w - w;
+
+ if (right > b_w) right = b_w;
+
+ copy = b_w - left - right;
+
+ if (left) memset(dst, ref_row[0], left);
+
+ if (copy) memcpy(dst + left, ref_row + x + left, copy);
+
+ if (right) memset(dst + left + copy, ref_row[w - 1], right);
+
+ dst += dst_stride;
+ ++y;
+
+ if (y > 0 && y < h) ref_row += src_stride;
+ } while (--b_h);
+}
+
+static INLINE int update_extend_mc_border_params(
+ const struct scale_factors *const sf, struct buf_2d *const pre_buf,
+ MV32 scaled_mv, PadBlock *block, int subpel_x_mv, int subpel_y_mv,
+ int do_warp, int is_intrabc, int *x_pad, int *y_pad) {
+ const int is_scaled = av1_is_scaled(sf);
+ // Get reference width and height.
+ int frame_width = pre_buf->width;
+ int frame_height = pre_buf->height;
+
+ // Do border extension if there is motion or
+ // width/height is not a multiple of 8 pixels.
+ if ((!is_intrabc) && (!do_warp) &&
+ (is_scaled || scaled_mv.col || scaled_mv.row || (frame_width & 0x7) ||
+ (frame_height & 0x7))) {
+ if (subpel_x_mv || (sf->x_step_q4 != SUBPEL_SHIFTS)) {
+ block->x0 -= AOM_INTERP_EXTEND - 1;
+ block->x1 += AOM_INTERP_EXTEND;
+ *x_pad = 1;
+ }
+
+ if (subpel_y_mv || (sf->y_step_q4 != SUBPEL_SHIFTS)) {
+ block->y0 -= AOM_INTERP_EXTEND - 1;
+ block->y1 += AOM_INTERP_EXTEND;
+ *y_pad = 1;
+ }
+
+ // Skip border extension if block is inside the frame.
+ if (block->x0 < 0 || block->x1 > frame_width - 1 || block->y0 < 0 ||
+ block->y1 > frame_height - 1) {
+ return 1;
+ }
+ }
+ return 0;
+}
+
+static INLINE void extend_mc_border(const struct scale_factors *const sf,
+ struct buf_2d *const pre_buf,
+ MV32 scaled_mv, PadBlock block,
+ int subpel_x_mv, int subpel_y_mv,
+ int do_warp, int is_intrabc, int highbd,
+ uint8_t *mc_buf, uint8_t **pre,
+ int *src_stride) {
+ int x_pad = 0, y_pad = 0;
+ if (update_extend_mc_border_params(sf, pre_buf, scaled_mv, &block,
+ subpel_x_mv, subpel_y_mv, do_warp,
+ is_intrabc, &x_pad, &y_pad)) {
+ // Get reference block pointer.
+ const uint8_t *const buf_ptr =
+ pre_buf->buf0 + block.y0 * pre_buf->stride + block.x0;
+ int buf_stride = pre_buf->stride;
+ const int b_w = block.x1 - block.x0;
+ const int b_h = block.y1 - block.y0;
+
+#if CONFIG_AV1_HIGHBITDEPTH
+ // Extend the border.
+ if (highbd) {
+ highbd_build_mc_border(buf_ptr, buf_stride, mc_buf, b_w, block.x0,
+ block.y0, b_w, b_h, pre_buf->width,
+ pre_buf->height);
+ } else {
+ build_mc_border(buf_ptr, buf_stride, mc_buf, b_w, block.x0, block.y0, b_w,
+ b_h, pre_buf->width, pre_buf->height);
+ }
+#else
+ (void)highbd;
+ build_mc_border(buf_ptr, buf_stride, mc_buf, b_w, block.x0, block.y0, b_w,
+ b_h, pre_buf->width, pre_buf->height);
+#endif
+ *src_stride = b_w;
+ *pre = mc_buf + y_pad * (AOM_INTERP_EXTEND - 1) * b_w +
+ x_pad * (AOM_INTERP_EXTEND - 1);
+ }
+}
+
+static AOM_INLINE void dec_calc_subpel_params(
+ const MV *const src_mv, InterPredParams *const inter_pred_params,
+ const MACROBLOCKD *const xd, int mi_x, int mi_y, uint8_t **pre,
+ SubpelParams *subpel_params, int *src_stride, PadBlock *block,
+ MV32 *scaled_mv, int *subpel_x_mv, int *subpel_y_mv) {
+ const struct scale_factors *sf = inter_pred_params->scale_factors;
+ struct buf_2d *pre_buf = &inter_pred_params->ref_frame_buf;
+ const int bw = inter_pred_params->block_width;
+ const int bh = inter_pred_params->block_height;
+ const int is_scaled = av1_is_scaled(sf);
+ if (is_scaled) {
+ int ssx = inter_pred_params->subsampling_x;
+ int ssy = inter_pred_params->subsampling_y;
+ int orig_pos_y = inter_pred_params->pix_row << SUBPEL_BITS;
+ orig_pos_y += src_mv->row * (1 << (1 - ssy));
+ int orig_pos_x = inter_pred_params->pix_col << SUBPEL_BITS;
+ orig_pos_x += src_mv->col * (1 << (1 - ssx));
+ int pos_y = av1_scaled_y(orig_pos_y, sf);
+ int pos_x = av1_scaled_x(orig_pos_x, sf);
+ pos_x += SCALE_EXTRA_OFF;
+ pos_y += SCALE_EXTRA_OFF;
+
+ const int top = -AOM_LEFT_TOP_MARGIN_SCALED(ssy);
+ const int left = -AOM_LEFT_TOP_MARGIN_SCALED(ssx);
+ const int bottom = (pre_buf->height + AOM_INTERP_EXTEND)
+ << SCALE_SUBPEL_BITS;
+ const int right = (pre_buf->width + AOM_INTERP_EXTEND) << SCALE_SUBPEL_BITS;
+ pos_y = clamp(pos_y, top, bottom);
+ pos_x = clamp(pos_x, left, right);
+
+ subpel_params->subpel_x = pos_x & SCALE_SUBPEL_MASK;
+ subpel_params->subpel_y = pos_y & SCALE_SUBPEL_MASK;
+ subpel_params->xs = sf->x_step_q4;
+ subpel_params->ys = sf->y_step_q4;
+
+ // Get reference block top left coordinate.
+ block->x0 = pos_x >> SCALE_SUBPEL_BITS;
+ block->y0 = pos_y >> SCALE_SUBPEL_BITS;
+
+ // Get reference block bottom right coordinate.
+ block->x1 =
+ ((pos_x + (bw - 1) * subpel_params->xs) >> SCALE_SUBPEL_BITS) + 1;
+ block->y1 =
+ ((pos_y + (bh - 1) * subpel_params->ys) >> SCALE_SUBPEL_BITS) + 1;
+
+ MV temp_mv;
+ temp_mv = clamp_mv_to_umv_border_sb(xd, src_mv, bw, bh,
+ inter_pred_params->subsampling_x,
+ inter_pred_params->subsampling_y);
+ *scaled_mv = av1_scale_mv(&temp_mv, mi_x, mi_y, sf);
+ scaled_mv->row += SCALE_EXTRA_OFF;
+ scaled_mv->col += SCALE_EXTRA_OFF;
+
+ *subpel_x_mv = scaled_mv->col & SCALE_SUBPEL_MASK;
+ *subpel_y_mv = scaled_mv->row & SCALE_SUBPEL_MASK;
+ } else {
+ // Get block position in current frame.
+ int pos_x = inter_pred_params->pix_col << SUBPEL_BITS;
+ int pos_y = inter_pred_params->pix_row << SUBPEL_BITS;
+
+ const MV mv_q4 = clamp_mv_to_umv_border_sb(
+ xd, src_mv, bw, bh, inter_pred_params->subsampling_x,
+ inter_pred_params->subsampling_y);
+ subpel_params->xs = subpel_params->ys = SCALE_SUBPEL_SHIFTS;
+ subpel_params->subpel_x = (mv_q4.col & SUBPEL_MASK) << SCALE_EXTRA_BITS;
+ subpel_params->subpel_y = (mv_q4.row & SUBPEL_MASK) << SCALE_EXTRA_BITS;
+
+ // Get reference block top left coordinate.
+ pos_x += mv_q4.col;
+ pos_y += mv_q4.row;
+ block->x0 = pos_x >> SUBPEL_BITS;
+ block->y0 = pos_y >> SUBPEL_BITS;
+
+ // Get reference block bottom right coordinate.
+ block->x1 = (pos_x >> SUBPEL_BITS) + (bw - 1) + 1;
+ block->y1 = (pos_y >> SUBPEL_BITS) + (bh - 1) + 1;
+
+ scaled_mv->row = mv_q4.row;
+ scaled_mv->col = mv_q4.col;
+ *subpel_x_mv = scaled_mv->col & SUBPEL_MASK;
+ *subpel_y_mv = scaled_mv->row & SUBPEL_MASK;
+ }
+ *pre = pre_buf->buf0 + block->y0 * pre_buf->stride + block->x0;
+ *src_stride = pre_buf->stride;
+}
+
+static AOM_INLINE void dec_calc_subpel_params_and_extend(
+ const MV *const src_mv, InterPredParams *const inter_pred_params,
+ MACROBLOCKD *const xd, int mi_x, int mi_y, int ref, uint8_t **mc_buf,
+ uint8_t **pre, SubpelParams *subpel_params, int *src_stride) {
+ PadBlock block;
+ MV32 scaled_mv;
+ int subpel_x_mv, subpel_y_mv;
+ dec_calc_subpel_params(src_mv, inter_pred_params, xd, mi_x, mi_y, pre,
+ subpel_params, src_stride, &block, &scaled_mv,
+ &subpel_x_mv, &subpel_y_mv);
+ extend_mc_border(
+ inter_pred_params->scale_factors, &inter_pred_params->ref_frame_buf,
+ scaled_mv, block, subpel_x_mv, subpel_y_mv,
+ inter_pred_params->mode == WARP_PRED, inter_pred_params->is_intrabc,
+ inter_pred_params->use_hbd_buf, mc_buf[ref], pre, src_stride);
+}
+
+#define IS_DEC 1
+#include "av1/common/reconinter_template.inc"
+#undef IS_DEC
+
+static void dec_build_inter_predictors(const AV1_COMMON *cm,
+ DecoderCodingBlock *dcb, int plane,
+ const MB_MODE_INFO *mi,
+ int build_for_obmc, int bw, int bh,
+ int mi_x, int mi_y) {
+ build_inter_predictors(cm, &dcb->xd, plane, mi, build_for_obmc, bw, bh, mi_x,
+ mi_y, dcb->mc_buf);
+}
+
+static AOM_INLINE void dec_build_inter_predictor(const AV1_COMMON *cm,
+ DecoderCodingBlock *dcb,
+ int mi_row, int mi_col,
+ BLOCK_SIZE bsize) {
+ MACROBLOCKD *const xd = &dcb->xd;
+ const int num_planes = av1_num_planes(cm);
+ for (int plane = 0; plane < num_planes; ++plane) {
+ if (plane && !xd->is_chroma_ref) break;
+ const int mi_x = mi_col * MI_SIZE;
+ const int mi_y = mi_row * MI_SIZE;
+ dec_build_inter_predictors(cm, dcb, plane, xd->mi[0], 0,
+ xd->plane[plane].width, xd->plane[plane].height,
+ mi_x, mi_y);
+ if (is_interintra_pred(xd->mi[0])) {
+ BUFFER_SET ctx = { { xd->plane[0].dst.buf, xd->plane[1].dst.buf,
+ xd->plane[2].dst.buf },
+ { xd->plane[0].dst.stride, xd->plane[1].dst.stride,
+ xd->plane[2].dst.stride } };
+ av1_build_interintra_predictor(cm, xd, xd->plane[plane].dst.buf,
+ xd->plane[plane].dst.stride, &ctx, plane,
+ bsize);
+ }
+ }
+}
+
+static INLINE void dec_build_prediction_by_above_pred(
+ MACROBLOCKD *const xd, int rel_mi_row, int rel_mi_col, uint8_t op_mi_size,
+ int dir, MB_MODE_INFO *above_mbmi, void *fun_ctxt, const int num_planes) {
+ struct build_prediction_ctxt *ctxt = (struct build_prediction_ctxt *)fun_ctxt;
+ const int above_mi_col = xd->mi_col + rel_mi_col;
+ int mi_x, mi_y;
+ MB_MODE_INFO backup_mbmi = *above_mbmi;
+
+ (void)rel_mi_row;
+ (void)dir;
+
+ av1_setup_build_prediction_by_above_pred(xd, rel_mi_col, op_mi_size,
+ &backup_mbmi, ctxt, num_planes);
+ mi_x = above_mi_col << MI_SIZE_LOG2;
+ mi_y = xd->mi_row << MI_SIZE_LOG2;
+
+ const BLOCK_SIZE bsize = xd->mi[0]->bsize;
+
+ for (int j = 0; j < num_planes; ++j) {
+ const struct macroblockd_plane *pd = &xd->plane[j];
+ int bw = (op_mi_size * MI_SIZE) >> pd->subsampling_x;
+ int bh = clamp(block_size_high[bsize] >> (pd->subsampling_y + 1), 4,
+ block_size_high[BLOCK_64X64] >> (pd->subsampling_y + 1));
+
+ if (av1_skip_u4x4_pred_in_obmc(bsize, pd, 0)) continue;
+ dec_build_inter_predictors(ctxt->cm, (DecoderCodingBlock *)ctxt->dcb, j,
+ &backup_mbmi, 1, bw, bh, mi_x, mi_y);
+ }
+}
+
+static AOM_INLINE void dec_build_prediction_by_above_preds(
+ const AV1_COMMON *cm, DecoderCodingBlock *dcb,
+ uint8_t *tmp_buf[MAX_MB_PLANE], int tmp_width[MAX_MB_PLANE],
+ int tmp_height[MAX_MB_PLANE], int tmp_stride[MAX_MB_PLANE]) {
+ MACROBLOCKD *const xd = &dcb->xd;
+ if (!xd->up_available) return;
+
+ // Adjust mb_to_bottom_edge to have the correct value for the OBMC
+ // prediction block. This is half the height of the original block,
+ // except for 128-wide blocks, where we only use a height of 32.
+ const int this_height = xd->height * MI_SIZE;
+ const int pred_height = AOMMIN(this_height / 2, 32);
+ xd->mb_to_bottom_edge += GET_MV_SUBPEL(this_height - pred_height);
+ struct build_prediction_ctxt ctxt = {
+ cm, tmp_buf, tmp_width, tmp_height, tmp_stride, xd->mb_to_right_edge, dcb
+ };
+ const BLOCK_SIZE bsize = xd->mi[0]->bsize;
+ foreach_overlappable_nb_above(cm, xd,
+ max_neighbor_obmc[mi_size_wide_log2[bsize]],
+ dec_build_prediction_by_above_pred, &ctxt);
+
+ xd->mb_to_left_edge = -GET_MV_SUBPEL(xd->mi_col * MI_SIZE);
+ xd->mb_to_right_edge = ctxt.mb_to_far_edge;
+ xd->mb_to_bottom_edge -= GET_MV_SUBPEL(this_height - pred_height);
+}
+
+static INLINE void dec_build_prediction_by_left_pred(
+ MACROBLOCKD *const xd, int rel_mi_row, int rel_mi_col, uint8_t op_mi_size,
+ int dir, MB_MODE_INFO *left_mbmi, void *fun_ctxt, const int num_planes) {
+ struct build_prediction_ctxt *ctxt = (struct build_prediction_ctxt *)fun_ctxt;
+ const int left_mi_row = xd->mi_row + rel_mi_row;
+ int mi_x, mi_y;
+ MB_MODE_INFO backup_mbmi = *left_mbmi;
+
+ (void)rel_mi_col;
+ (void)dir;
+
+ av1_setup_build_prediction_by_left_pred(xd, rel_mi_row, op_mi_size,
+ &backup_mbmi, ctxt, num_planes);
+ mi_x = xd->mi_col << MI_SIZE_LOG2;
+ mi_y = left_mi_row << MI_SIZE_LOG2;
+ const BLOCK_SIZE bsize = xd->mi[0]->bsize;
+
+ for (int j = 0; j < num_planes; ++j) {
+ const struct macroblockd_plane *pd = &xd->plane[j];
+ int bw = clamp(block_size_wide[bsize] >> (pd->subsampling_x + 1), 4,
+ block_size_wide[BLOCK_64X64] >> (pd->subsampling_x + 1));
+ int bh = (op_mi_size << MI_SIZE_LOG2) >> pd->subsampling_y;
+
+ if (av1_skip_u4x4_pred_in_obmc(bsize, pd, 1)) continue;
+ dec_build_inter_predictors(ctxt->cm, (DecoderCodingBlock *)ctxt->dcb, j,
+ &backup_mbmi, 1, bw, bh, mi_x, mi_y);
+ }
+}
+
+static AOM_INLINE void dec_build_prediction_by_left_preds(
+ const AV1_COMMON *cm, DecoderCodingBlock *dcb,
+ uint8_t *tmp_buf[MAX_MB_PLANE], int tmp_width[MAX_MB_PLANE],
+ int tmp_height[MAX_MB_PLANE], int tmp_stride[MAX_MB_PLANE]) {
+ MACROBLOCKD *const xd = &dcb->xd;
+ if (!xd->left_available) return;
+
+ // Adjust mb_to_right_edge to have the correct value for the OBMC
+ // prediction block. This is half the width of the original block,
+ // except for 128-wide blocks, where we only use a width of 32.
+ const int this_width = xd->width * MI_SIZE;
+ const int pred_width = AOMMIN(this_width / 2, 32);
+ xd->mb_to_right_edge += GET_MV_SUBPEL(this_width - pred_width);
+
+ struct build_prediction_ctxt ctxt = {
+ cm, tmp_buf, tmp_width, tmp_height, tmp_stride, xd->mb_to_bottom_edge, dcb
+ };
+ const BLOCK_SIZE bsize = xd->mi[0]->bsize;
+ foreach_overlappable_nb_left(cm, xd,
+ max_neighbor_obmc[mi_size_high_log2[bsize]],
+ dec_build_prediction_by_left_pred, &ctxt);
+
+ xd->mb_to_top_edge = -GET_MV_SUBPEL(xd->mi_row * MI_SIZE);
+ xd->mb_to_right_edge -= GET_MV_SUBPEL(this_width - pred_width);
+ xd->mb_to_bottom_edge = ctxt.mb_to_far_edge;
+}
+
+static AOM_INLINE void dec_build_obmc_inter_predictors_sb(
+ const AV1_COMMON *cm, DecoderCodingBlock *dcb) {
+ const int num_planes = av1_num_planes(cm);
+ uint8_t *dst_buf1[MAX_MB_PLANE], *dst_buf2[MAX_MB_PLANE];
+ int dst_stride1[MAX_MB_PLANE] = { MAX_SB_SIZE, MAX_SB_SIZE, MAX_SB_SIZE };
+ int dst_stride2[MAX_MB_PLANE] = { MAX_SB_SIZE, MAX_SB_SIZE, MAX_SB_SIZE };
+ int dst_width1[MAX_MB_PLANE] = { MAX_SB_SIZE, MAX_SB_SIZE, MAX_SB_SIZE };
+ int dst_width2[MAX_MB_PLANE] = { MAX_SB_SIZE, MAX_SB_SIZE, MAX_SB_SIZE };
+ int dst_height1[MAX_MB_PLANE] = { MAX_SB_SIZE, MAX_SB_SIZE, MAX_SB_SIZE };
+ int dst_height2[MAX_MB_PLANE] = { MAX_SB_SIZE, MAX_SB_SIZE, MAX_SB_SIZE };
+
+ MACROBLOCKD *const xd = &dcb->xd;
+ av1_setup_obmc_dst_bufs(xd, dst_buf1, dst_buf2);
+
+ dec_build_prediction_by_above_preds(cm, dcb, dst_buf1, dst_width1,
+ dst_height1, dst_stride1);
+ dec_build_prediction_by_left_preds(cm, dcb, dst_buf2, dst_width2, dst_height2,
+ dst_stride2);
+ const int mi_row = xd->mi_row;
+ const int mi_col = xd->mi_col;
+ av1_setup_dst_planes(xd->plane, xd->mi[0]->bsize, &cm->cur_frame->buf, mi_row,
+ mi_col, 0, num_planes);
+ av1_build_obmc_inter_prediction(cm, xd, dst_buf1, dst_stride1, dst_buf2,
+ dst_stride2);
+}
+
+static AOM_INLINE void cfl_store_inter_block(AV1_COMMON *const cm,
+ MACROBLOCKD *const xd) {
+ MB_MODE_INFO *mbmi = xd->mi[0];
+ if (store_cfl_required(cm, xd)) {
+ cfl_store_block(xd, mbmi->bsize, mbmi->tx_size);
+ }
+}
+
+static AOM_INLINE void predict_inter_block(AV1_COMMON *const cm,
+ DecoderCodingBlock *dcb,
+ BLOCK_SIZE bsize) {
+ MACROBLOCKD *const xd = &dcb->xd;
+ MB_MODE_INFO *mbmi = xd->mi[0];
+ const int num_planes = av1_num_planes(cm);
+ const int mi_row = xd->mi_row;
+ const int mi_col = xd->mi_col;
+ for (int ref = 0; ref < 1 + has_second_ref(mbmi); ++ref) {
+ const MV_REFERENCE_FRAME frame = mbmi->ref_frame[ref];
+ if (frame < LAST_FRAME) {
+ assert(is_intrabc_block(mbmi));
+ assert(frame == INTRA_FRAME);
+ assert(ref == 0);
+ } else {
+ const RefCntBuffer *ref_buf = get_ref_frame_buf(cm, frame);
+ const struct scale_factors *ref_scale_factors =
+ get_ref_scale_factors_const(cm, frame);
+
+ xd->block_ref_scale_factors[ref] = ref_scale_factors;
+ av1_setup_pre_planes(xd, ref, &ref_buf->buf, mi_row, mi_col,
+ ref_scale_factors, num_planes);
+ }
+ }
+
+ dec_build_inter_predictor(cm, dcb, mi_row, mi_col, bsize);
+ if (mbmi->motion_mode == OBMC_CAUSAL) {
+ dec_build_obmc_inter_predictors_sb(cm, dcb);
+ }
+#if CONFIG_MISMATCH_DEBUG
+ for (int plane = 0; plane < num_planes; ++plane) {
+ const struct macroblockd_plane *pd = &xd->plane[plane];
+ int pixel_c, pixel_r;
+ mi_to_pixel_loc(&pixel_c, &pixel_r, mi_col, mi_row, 0, 0, pd->subsampling_x,
+ pd->subsampling_y);
+ if (!is_chroma_reference(mi_row, mi_col, bsize, pd->subsampling_x,
+ pd->subsampling_y))
+ continue;
+ mismatch_check_block_pre(pd->dst.buf, pd->dst.stride,
+ cm->current_frame.order_hint, plane, pixel_c,
+ pixel_r, pd->width, pd->height,
+ xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH);
+ }
+#endif
+}
+
+static AOM_INLINE void set_color_index_map_offset(MACROBLOCKD *const xd,
+ int plane, aom_reader *r) {
+ (void)r;
+ Av1ColorMapParam params;
+ const MB_MODE_INFO *const mbmi = xd->mi[0];
+ av1_get_block_dimensions(mbmi->bsize, plane, xd, &params.plane_width,
+ &params.plane_height, NULL, NULL);
+ xd->color_index_map_offset[plane] += params.plane_width * params.plane_height;
+}
+
+static AOM_INLINE void decode_token_recon_block(AV1Decoder *const pbi,
+ ThreadData *const td,
+ aom_reader *r,
+ BLOCK_SIZE bsize) {
+ AV1_COMMON *const cm = &pbi->common;
+ DecoderCodingBlock *const dcb = &td->dcb;
+ MACROBLOCKD *const xd = &dcb->xd;
+ const int num_planes = av1_num_planes(cm);
+ MB_MODE_INFO *mbmi = xd->mi[0];
+
+ if (!is_inter_block(mbmi)) {
+ int row, col;
+ assert(bsize == get_plane_block_size(bsize, xd->plane[0].subsampling_x,
+ xd->plane[0].subsampling_y));
+ const int max_blocks_wide = max_block_wide(xd, bsize, 0);
+ const int max_blocks_high = max_block_high(xd, bsize, 0);
+ const BLOCK_SIZE max_unit_bsize = BLOCK_64X64;
+ int mu_blocks_wide = mi_size_wide[max_unit_bsize];
+ int mu_blocks_high = mi_size_high[max_unit_bsize];
+ mu_blocks_wide = AOMMIN(max_blocks_wide, mu_blocks_wide);
+ mu_blocks_high = AOMMIN(max_blocks_high, mu_blocks_high);
+
+ for (row = 0; row < max_blocks_high; row += mu_blocks_high) {
+ for (col = 0; col < max_blocks_wide; col += mu_blocks_wide) {
+ for (int plane = 0; plane < num_planes; ++plane) {
+ if (plane && !xd->is_chroma_ref) break;
+ const struct macroblockd_plane *const pd = &xd->plane[plane];
+ const TX_SIZE tx_size = av1_get_tx_size(plane, xd);
+ const int stepr = tx_size_high_unit[tx_size];
+ const int stepc = tx_size_wide_unit[tx_size];
+
+ const int unit_height = ROUND_POWER_OF_TWO(
+ AOMMIN(mu_blocks_high + row, max_blocks_high), pd->subsampling_y);
+ const int unit_width = ROUND_POWER_OF_TWO(
+ AOMMIN(mu_blocks_wide + col, max_blocks_wide), pd->subsampling_x);
+
+ for (int blk_row = row >> pd->subsampling_y; blk_row < unit_height;
+ blk_row += stepr) {
+ for (int blk_col = col >> pd->subsampling_x; blk_col < unit_width;
+ blk_col += stepc) {
+ td->read_coeffs_tx_intra_block_visit(cm, dcb, r, plane, blk_row,
+ blk_col, tx_size);
+ td->predict_and_recon_intra_block_visit(
+ cm, dcb, r, plane, blk_row, blk_col, tx_size);
+ set_cb_buffer_offsets(dcb, tx_size, plane);
+ }
+ }
+ }
+ }
+ }
+ } else {
+ td->predict_inter_block_visit(cm, dcb, bsize);
+ // Reconstruction
+ if (!mbmi->skip_txfm) {
+ int eobtotal = 0;
+
+ const int max_blocks_wide = max_block_wide(xd, bsize, 0);
+ const int max_blocks_high = max_block_high(xd, bsize, 0);
+ int row, col;
+
+ const BLOCK_SIZE max_unit_bsize = BLOCK_64X64;
+ assert(max_unit_bsize ==
+ get_plane_block_size(BLOCK_64X64, xd->plane[0].subsampling_x,
+ xd->plane[0].subsampling_y));
+ int mu_blocks_wide = mi_size_wide[max_unit_bsize];
+ int mu_blocks_high = mi_size_high[max_unit_bsize];
+
+ mu_blocks_wide = AOMMIN(max_blocks_wide, mu_blocks_wide);
+ mu_blocks_high = AOMMIN(max_blocks_high, mu_blocks_high);
+
+ for (row = 0; row < max_blocks_high; row += mu_blocks_high) {
+ for (col = 0; col < max_blocks_wide; col += mu_blocks_wide) {
+ for (int plane = 0; plane < num_planes; ++plane) {
+ if (plane && !xd->is_chroma_ref) break;
+ const struct macroblockd_plane *const pd = &xd->plane[plane];
+ const int ss_x = pd->subsampling_x;
+ const int ss_y = pd->subsampling_y;
+ const BLOCK_SIZE plane_bsize =
+ get_plane_block_size(bsize, ss_x, ss_y);
+ const TX_SIZE max_tx_size =
+ get_vartx_max_txsize(xd, plane_bsize, plane);
+ const int bh_var_tx = tx_size_high_unit[max_tx_size];
+ const int bw_var_tx = tx_size_wide_unit[max_tx_size];
+ int block = 0;
+ int step =
+ tx_size_wide_unit[max_tx_size] * tx_size_high_unit[max_tx_size];
+ int blk_row, blk_col;
+ const int unit_height = ROUND_POWER_OF_TWO(
+ AOMMIN(mu_blocks_high + row, max_blocks_high), ss_y);
+ const int unit_width = ROUND_POWER_OF_TWO(
+ AOMMIN(mu_blocks_wide + col, max_blocks_wide), ss_x);
+
+ for (blk_row = row >> ss_y; blk_row < unit_height;
+ blk_row += bh_var_tx) {
+ for (blk_col = col >> ss_x; blk_col < unit_width;
+ blk_col += bw_var_tx) {
+ decode_reconstruct_tx(cm, td, r, mbmi, plane, plane_bsize,
+ blk_row, blk_col, block, max_tx_size,
+ &eobtotal);
+ block += step;
+ }
+ }
+ }
+ }
+ }
+ }
+ td->cfl_store_inter_block_visit(cm, xd);
+ }
+
+ av1_visit_palette(pbi, xd, r, set_color_index_map_offset);
+}
+
+static AOM_INLINE void set_inter_tx_size(MB_MODE_INFO *mbmi, int stride_log2,
+ int tx_w_log2, int tx_h_log2,
+ int min_txs, int split_size, int txs,
+ int blk_row, int blk_col) {
+ for (int idy = 0; idy < tx_size_high_unit[split_size];
+ idy += tx_size_high_unit[min_txs]) {
+ for (int idx = 0; idx < tx_size_wide_unit[split_size];
+ idx += tx_size_wide_unit[min_txs]) {
+ const int index = (((blk_row + idy) >> tx_h_log2) << stride_log2) +
+ ((blk_col + idx) >> tx_w_log2);
+ mbmi->inter_tx_size[index] = txs;
+ }
+ }
+}
+
+static AOM_INLINE void read_tx_size_vartx(MACROBLOCKD *xd, MB_MODE_INFO *mbmi,
+ TX_SIZE tx_size, int depth,
+ int blk_row, int blk_col,
+ aom_reader *r) {
+ FRAME_CONTEXT *ec_ctx = xd->tile_ctx;
+ int is_split = 0;
+ const BLOCK_SIZE bsize = mbmi->bsize;
+ const int max_blocks_high = max_block_high(xd, bsize, 0);
+ const int max_blocks_wide = max_block_wide(xd, bsize, 0);
+ if (blk_row >= max_blocks_high || blk_col >= max_blocks_wide) return;
+ assert(tx_size > TX_4X4);
+ TX_SIZE txs = max_txsize_rect_lookup[bsize];
+ for (int level = 0; level < MAX_VARTX_DEPTH - 1; ++level)
+ txs = sub_tx_size_map[txs];
+ const int tx_w_log2 = tx_size_wide_log2[txs] - MI_SIZE_LOG2;
+ const int tx_h_log2 = tx_size_high_log2[txs] - MI_SIZE_LOG2;
+ const int bw_log2 = mi_size_wide_log2[bsize];
+ const int stride_log2 = bw_log2 - tx_w_log2;
+
+ if (depth == MAX_VARTX_DEPTH) {
+ set_inter_tx_size(mbmi, stride_log2, tx_w_log2, tx_h_log2, txs, tx_size,
+ tx_size, blk_row, blk_col);
+ mbmi->tx_size = tx_size;
+ txfm_partition_update(xd->above_txfm_context + blk_col,
+ xd->left_txfm_context + blk_row, tx_size, tx_size);
+ return;
+ }
+
+ const int ctx = txfm_partition_context(xd->above_txfm_context + blk_col,
+ xd->left_txfm_context + blk_row,
+ mbmi->bsize, tx_size);
+ is_split = aom_read_symbol(r, ec_ctx->txfm_partition_cdf[ctx], 2, ACCT_STR);
+
+ if (is_split) {
+ const TX_SIZE sub_txs = sub_tx_size_map[tx_size];
+ const int bsw = tx_size_wide_unit[sub_txs];
+ const int bsh = tx_size_high_unit[sub_txs];
+
+ if (sub_txs == TX_4X4) {
+ set_inter_tx_size(mbmi, stride_log2, tx_w_log2, tx_h_log2, txs, tx_size,
+ sub_txs, blk_row, blk_col);
+ mbmi->tx_size = sub_txs;
+ txfm_partition_update(xd->above_txfm_context + blk_col,
+ xd->left_txfm_context + blk_row, sub_txs, tx_size);
+ return;
+ }
+
+ assert(bsw > 0 && bsh > 0);
+ for (int row = 0; row < tx_size_high_unit[tx_size]; row += bsh) {
+ for (int col = 0; col < tx_size_wide_unit[tx_size]; col += bsw) {
+ int offsetr = blk_row + row;
+ int offsetc = blk_col + col;
+ read_tx_size_vartx(xd, mbmi, sub_txs, depth + 1, offsetr, offsetc, r);
+ }
+ }
+ } else {
+ set_inter_tx_size(mbmi, stride_log2, tx_w_log2, tx_h_log2, txs, tx_size,
+ tx_size, blk_row, blk_col);
+ mbmi->tx_size = tx_size;
+ txfm_partition_update(xd->above_txfm_context + blk_col,
+ xd->left_txfm_context + blk_row, tx_size, tx_size);
+ }
+}
+
+static TX_SIZE read_selected_tx_size(const MACROBLOCKD *const xd,
+ aom_reader *r) {
+ // TODO(debargha): Clean up the logic here. This function should only
+ // be called for intra.
+ const BLOCK_SIZE bsize = xd->mi[0]->bsize;
+ const int32_t tx_size_cat = bsize_to_tx_size_cat(bsize);
+ const int max_depths = bsize_to_max_depth(bsize);
+ const int ctx = get_tx_size_context(xd);
+ FRAME_CONTEXT *ec_ctx = xd->tile_ctx;
+ const int depth = aom_read_symbol(r, ec_ctx->tx_size_cdf[tx_size_cat][ctx],
+ max_depths + 1, ACCT_STR);
+ assert(depth >= 0 && depth <= max_depths);
+ const TX_SIZE tx_size = depth_to_tx_size(depth, bsize);
+ return tx_size;
+}
+
+static TX_SIZE read_tx_size(const MACROBLOCKD *const xd, TX_MODE tx_mode,
+ int is_inter, int allow_select_inter,
+ aom_reader *r) {
+ const BLOCK_SIZE bsize = xd->mi[0]->bsize;
+ if (xd->lossless[xd->mi[0]->segment_id]) return TX_4X4;
+
+ if (block_signals_txsize(bsize)) {
+ if ((!is_inter || allow_select_inter) && tx_mode == TX_MODE_SELECT) {
+ const TX_SIZE coded_tx_size = read_selected_tx_size(xd, r);
+ return coded_tx_size;
+ } else {
+ return tx_size_from_tx_mode(bsize, tx_mode);
+ }
+ } else {
+ assert(IMPLIES(tx_mode == ONLY_4X4, bsize == BLOCK_4X4));
+ return max_txsize_rect_lookup[bsize];
+ }
+}
+
+static AOM_INLINE void parse_decode_block(AV1Decoder *const pbi,
+ ThreadData *const td, int mi_row,
+ int mi_col, aom_reader *r,
+ PARTITION_TYPE partition,
+ BLOCK_SIZE bsize) {
+ DecoderCodingBlock *const dcb = &td->dcb;
+ MACROBLOCKD *const xd = &dcb->xd;
+ decode_mbmi_block(pbi, dcb, mi_row, mi_col, r, partition, bsize);
+
+ av1_visit_palette(pbi, xd, r, av1_decode_palette_tokens);
+
+ AV1_COMMON *cm = &pbi->common;
+ const int num_planes = av1_num_planes(cm);
+ MB_MODE_INFO *mbmi = xd->mi[0];
+ int inter_block_tx = is_inter_block(mbmi) || is_intrabc_block(mbmi);
+ if (cm->features.tx_mode == TX_MODE_SELECT && block_signals_txsize(bsize) &&
+ !mbmi->skip_txfm && inter_block_tx && !xd->lossless[mbmi->segment_id]) {
+ const TX_SIZE max_tx_size = max_txsize_rect_lookup[bsize];
+ const int bh = tx_size_high_unit[max_tx_size];
+ const int bw = tx_size_wide_unit[max_tx_size];
+ const int width = mi_size_wide[bsize];
+ const int height = mi_size_high[bsize];
+
+ for (int idy = 0; idy < height; idy += bh)
+ for (int idx = 0; idx < width; idx += bw)
+ read_tx_size_vartx(xd, mbmi, max_tx_size, 0, idy, idx, r);
+ } else {
+ mbmi->tx_size = read_tx_size(xd, cm->features.tx_mode, inter_block_tx,
+ !mbmi->skip_txfm, r);
+ if (inter_block_tx)
+ memset(mbmi->inter_tx_size, mbmi->tx_size, sizeof(mbmi->inter_tx_size));
+ set_txfm_ctxs(mbmi->tx_size, xd->width, xd->height,
+ mbmi->skip_txfm && is_inter_block(mbmi), xd);
+ }
+
+ if (cm->delta_q_info.delta_q_present_flag) {
+ for (int i = 0; i < MAX_SEGMENTS; i++) {
+ const int current_qindex =
+ av1_get_qindex(&cm->seg, i, xd->current_base_qindex);
+ const CommonQuantParams *const quant_params = &cm->quant_params;
+ for (int j = 0; j < num_planes; ++j) {
+ const int dc_delta_q = j == 0 ? quant_params->y_dc_delta_q
+ : (j == 1 ? quant_params->u_dc_delta_q
+ : quant_params->v_dc_delta_q);
+ const int ac_delta_q = j == 0 ? 0
+ : (j == 1 ? quant_params->u_ac_delta_q
+ : quant_params->v_ac_delta_q);
+ xd->plane[j].seg_dequant_QTX[i][0] = av1_dc_quant_QTX(
+ current_qindex, dc_delta_q, cm->seq_params->bit_depth);
+ xd->plane[j].seg_dequant_QTX[i][1] = av1_ac_quant_QTX(
+ current_qindex, ac_delta_q, cm->seq_params->bit_depth);
+ }
+ }
+ }
+ if (mbmi->skip_txfm) av1_reset_entropy_context(xd, bsize, num_planes);
+
+ decode_token_recon_block(pbi, td, r, bsize);
+}
+
+static AOM_INLINE void set_offsets_for_pred_and_recon(AV1Decoder *const pbi,
+ ThreadData *const td,
+ int mi_row, int mi_col,
+ BLOCK_SIZE bsize) {
+ AV1_COMMON *const cm = &pbi->common;
+ const CommonModeInfoParams *const mi_params = &cm->mi_params;
+ DecoderCodingBlock *const dcb = &td->dcb;
+ MACROBLOCKD *const xd = &dcb->xd;
+ const int bw = mi_size_wide[bsize];
+ const int bh = mi_size_high[bsize];
+ const int num_planes = av1_num_planes(cm);
+
+ const int offset = mi_row * mi_params->mi_stride + mi_col;
+ const TileInfo *const tile = &xd->tile;
+
+ xd->mi = mi_params->mi_grid_base + offset;
+ xd->tx_type_map =
+ &mi_params->tx_type_map[mi_row * mi_params->mi_stride + mi_col];
+ xd->tx_type_map_stride = mi_params->mi_stride;
+
+ set_plane_n4(xd, bw, bh, num_planes);
+
+ // Distance of Mb to the various image edges. These are specified to 8th pel
+ // as they are always compared to values that are in 1/8th pel units
+ set_mi_row_col(xd, tile, mi_row, bh, mi_col, bw, mi_params->mi_rows,
+ mi_params->mi_cols);
+
+ av1_setup_dst_planes(xd->plane, bsize, &cm->cur_frame->buf, mi_row, mi_col, 0,
+ num_planes);
+}
+
+static AOM_INLINE void decode_block(AV1Decoder *const pbi, ThreadData *const td,
+ int mi_row, int mi_col, aom_reader *r,
+ PARTITION_TYPE partition,
+ BLOCK_SIZE bsize) {
+ (void)partition;
+ set_offsets_for_pred_and_recon(pbi, td, mi_row, mi_col, bsize);
+ decode_token_recon_block(pbi, td, r, bsize);
+}
+
+static PARTITION_TYPE read_partition(MACROBLOCKD *xd, int mi_row, int mi_col,
+ aom_reader *r, int has_rows, int has_cols,
+ BLOCK_SIZE bsize) {
+ const int ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
+ FRAME_CONTEXT *ec_ctx = xd->tile_ctx;
+
+ if (!has_rows && !has_cols) return PARTITION_SPLIT;
+
+ assert(ctx >= 0);
+ aom_cdf_prob *partition_cdf = ec_ctx->partition_cdf[ctx];
+ if (has_rows && has_cols) {
+ return (PARTITION_TYPE)aom_read_symbol(
+ r, partition_cdf, partition_cdf_length(bsize), ACCT_STR);
+ } else if (!has_rows && has_cols) {
+ assert(bsize > BLOCK_8X8);
+ aom_cdf_prob cdf[2];
+ partition_gather_vert_alike(cdf, partition_cdf, bsize);
+ assert(cdf[1] == AOM_ICDF(CDF_PROB_TOP));
+ return aom_read_cdf(r, cdf, 2, ACCT_STR) ? PARTITION_SPLIT : PARTITION_HORZ;
+ } else {
+ assert(has_rows && !has_cols);
+ assert(bsize > BLOCK_8X8);
+ aom_cdf_prob cdf[2];
+ partition_gather_horz_alike(cdf, partition_cdf, bsize);
+ assert(cdf[1] == AOM_ICDF(CDF_PROB_TOP));
+ return aom_read_cdf(r, cdf, 2, ACCT_STR) ? PARTITION_SPLIT : PARTITION_VERT;
+ }
+}
+
+// TODO(slavarnway): eliminate bsize and subsize in future commits
+static AOM_INLINE void decode_partition(AV1Decoder *const pbi,
+ ThreadData *const td, int mi_row,
+ int mi_col, aom_reader *reader,
+ BLOCK_SIZE bsize,
+ int parse_decode_flag) {
+ assert(bsize < BLOCK_SIZES_ALL);
+ AV1_COMMON *const cm = &pbi->common;
+ DecoderCodingBlock *const dcb = &td->dcb;
+ MACROBLOCKD *const xd = &dcb->xd;
+ const int bw = mi_size_wide[bsize];
+ const int hbs = bw >> 1;
+ PARTITION_TYPE partition;
+ BLOCK_SIZE subsize;
+ const int quarter_step = bw / 4;
+ BLOCK_SIZE bsize2 = get_partition_subsize(bsize, PARTITION_SPLIT);
+ const int has_rows = (mi_row + hbs) < cm->mi_params.mi_rows;
+ const int has_cols = (mi_col + hbs) < cm->mi_params.mi_cols;
+
+ if (mi_row >= cm->mi_params.mi_rows || mi_col >= cm->mi_params.mi_cols)
+ return;
+
+ // parse_decode_flag takes the following values :
+ // 01 - do parse only
+ // 10 - do decode only
+ // 11 - do parse and decode
+ static const block_visitor_fn_t block_visit[4] = { NULL, parse_decode_block,
+ decode_block,
+ parse_decode_block };
+
+ if (parse_decode_flag & 1) {
+ const int num_planes = av1_num_planes(cm);
+ for (int plane = 0; plane < num_planes; ++plane) {
+ int rcol0, rcol1, rrow0, rrow1;
+
+ // Skip some unnecessary work if loop restoration is disabled
+ if (cm->rst_info[plane].frame_restoration_type == RESTORE_NONE) continue;
+
+ if (av1_loop_restoration_corners_in_sb(cm, plane, mi_row, mi_col, bsize,
+ &rcol0, &rcol1, &rrow0, &rrow1)) {
+ const int rstride = cm->rst_info[plane].horz_units;
+ for (int rrow = rrow0; rrow < rrow1; ++rrow) {
+ for (int rcol = rcol0; rcol < rcol1; ++rcol) {
+ const int runit_idx = rcol + rrow * rstride;
+ loop_restoration_read_sb_coeffs(cm, xd, reader, plane, runit_idx);
+ }
+ }
+ }
+ }
+
+ partition = (bsize < BLOCK_8X8) ? PARTITION_NONE
+ : read_partition(xd, mi_row, mi_col, reader,
+ has_rows, has_cols, bsize);
+ } else {
+ partition = get_partition(cm, mi_row, mi_col, bsize);
+ }
+ subsize = get_partition_subsize(bsize, partition);
+ if (subsize == BLOCK_INVALID) {
+ // When an internal error occurs ensure that xd->mi_row is set appropriately
+ // w.r.t. current tile, which is used to signal processing of current row is
+ // done.
+ xd->mi_row = mi_row;
+ aom_internal_error(xd->error_info, AOM_CODEC_CORRUPT_FRAME,
+ "Partition is invalid for block size %dx%d",
+ block_size_wide[bsize], block_size_high[bsize]);
+ }
+ // Check the bitstream is conformant: if there is subsampling on the
+ // chroma planes, subsize must subsample to a valid block size.
+ const struct macroblockd_plane *const pd_u = &xd->plane[1];
+ if (get_plane_block_size(subsize, pd_u->subsampling_x, pd_u->subsampling_y) ==
+ BLOCK_INVALID) {
+ // When an internal error occurs ensure that xd->mi_row is set appropriately
+ // w.r.t. current tile, which is used to signal processing of current row is
+ // done.
+ xd->mi_row = mi_row;
+ aom_internal_error(xd->error_info, AOM_CODEC_CORRUPT_FRAME,
+ "Block size %dx%d invalid with this subsampling mode",
+ block_size_wide[subsize], block_size_high[subsize]);
+ }
+
+#define DEC_BLOCK_STX_ARG
+#define DEC_BLOCK_EPT_ARG partition,
+#define DEC_BLOCK(db_r, db_c, db_subsize) \
+ block_visit[parse_decode_flag](pbi, td, DEC_BLOCK_STX_ARG(db_r), (db_c), \
+ reader, DEC_BLOCK_EPT_ARG(db_subsize))
+#define DEC_PARTITION(db_r, db_c, db_subsize) \
+ decode_partition(pbi, td, DEC_BLOCK_STX_ARG(db_r), (db_c), reader, \
+ (db_subsize), parse_decode_flag)
+
+ switch (partition) {
+ case PARTITION_NONE: DEC_BLOCK(mi_row, mi_col, subsize); break;
+ case PARTITION_HORZ:
+ DEC_BLOCK(mi_row, mi_col, subsize);
+ if (has_rows) DEC_BLOCK(mi_row + hbs, mi_col, subsize);
+ break;
+ case PARTITION_VERT:
+ DEC_BLOCK(mi_row, mi_col, subsize);
+ if (has_cols) DEC_BLOCK(mi_row, mi_col + hbs, subsize);
+ break;
+ case PARTITION_SPLIT:
+ DEC_PARTITION(mi_row, mi_col, subsize);
+ DEC_PARTITION(mi_row, mi_col + hbs, subsize);
+ DEC_PARTITION(mi_row + hbs, mi_col, subsize);
+ DEC_PARTITION(mi_row + hbs, mi_col + hbs, subsize);
+ break;
+ case PARTITION_HORZ_A:
+ DEC_BLOCK(mi_row, mi_col, bsize2);
+ DEC_BLOCK(mi_row, mi_col + hbs, bsize2);
+ DEC_BLOCK(mi_row + hbs, mi_col, subsize);
+ break;
+ case PARTITION_HORZ_B:
+ DEC_BLOCK(mi_row, mi_col, subsize);
+ DEC_BLOCK(mi_row + hbs, mi_col, bsize2);
+ DEC_BLOCK(mi_row + hbs, mi_col + hbs, bsize2);
+ break;
+ case PARTITION_VERT_A:
+ DEC_BLOCK(mi_row, mi_col, bsize2);
+ DEC_BLOCK(mi_row + hbs, mi_col, bsize2);
+ DEC_BLOCK(mi_row, mi_col + hbs, subsize);
+ break;
+ case PARTITION_VERT_B:
+ DEC_BLOCK(mi_row, mi_col, subsize);
+ DEC_BLOCK(mi_row, mi_col + hbs, bsize2);
+ DEC_BLOCK(mi_row + hbs, mi_col + hbs, bsize2);
+ break;
+ case PARTITION_HORZ_4:
+ for (int i = 0; i < 4; ++i) {
+ int this_mi_row = mi_row + i * quarter_step;
+ if (i > 0 && this_mi_row >= cm->mi_params.mi_rows) break;
+ DEC_BLOCK(this_mi_row, mi_col, subsize);
+ }
+ break;
+ case PARTITION_VERT_4:
+ for (int i = 0; i < 4; ++i) {
+ int this_mi_col = mi_col + i * quarter_step;
+ if (i > 0 && this_mi_col >= cm->mi_params.mi_cols) break;
+ DEC_BLOCK(mi_row, this_mi_col, subsize);
+ }
+ break;
+ default: assert(0 && "Invalid partition type");
+ }
+
+#undef DEC_PARTITION
+#undef DEC_BLOCK
+#undef DEC_BLOCK_EPT_ARG
+#undef DEC_BLOCK_STX_ARG
+
+ if (parse_decode_flag & 1)
+ update_ext_partition_context(xd, mi_row, mi_col, subsize, bsize, partition);
+}
+
+static AOM_INLINE void setup_bool_decoder(
+ MACROBLOCKD *const xd, const uint8_t *data, const uint8_t *data_end,
+ const size_t read_size, struct aom_internal_error_info *error_info,
+ aom_reader *r, uint8_t allow_update_cdf) {
+ // Validate the calculated partition length. If the buffer
+ // described by the partition can't be fully read, then restrict
+ // it to the portion that can be (for EC mode) or throw an error.
+ if (!read_is_valid(data, read_size, data_end)) {
+ // When internal error occurs ensure that xd->mi_row is set appropriately
+ // w.r.t. current tile, which is used to signal processing of current row is
+ // done in row-mt decoding.
+ xd->mi_row = xd->tile.mi_row_start;
+
+ aom_internal_error(error_info, AOM_CODEC_CORRUPT_FRAME,
+ "Truncated packet or corrupt tile length");
+ }
+ if (aom_reader_init(r, data, read_size)) {
+ // When internal error occurs ensure that xd->mi_row is set appropriately
+ // w.r.t. current tile, which is used to signal processing of current row is
+ // done in row-mt decoding.
+ xd->mi_row = xd->tile.mi_row_start;
+
+ aom_internal_error(error_info, AOM_CODEC_MEM_ERROR,
+ "Failed to allocate bool decoder %d", 1);
+ }
+
+ r->allow_update_cdf = allow_update_cdf;
+}
+
+static AOM_INLINE void setup_segmentation(AV1_COMMON *const cm,
+ struct aom_read_bit_buffer *rb) {
+ struct segmentation *const seg = &cm->seg;
+
+ seg->update_map = 0;
+ seg->update_data = 0;
+ seg->temporal_update = 0;
+
+ seg->enabled = aom_rb_read_bit(rb);
+ if (!seg->enabled) {
+ if (cm->cur_frame->seg_map) {
+ memset(cm->cur_frame->seg_map, 0,
+ (cm->cur_frame->mi_rows * cm->cur_frame->mi_cols));
+ }
+
+ memset(seg, 0, sizeof(*seg));
+ segfeatures_copy(&cm->cur_frame->seg, seg);
+ return;
+ }
+ if (cm->seg.enabled && cm->prev_frame &&
+ (cm->mi_params.mi_rows == cm->prev_frame->mi_rows) &&
+ (cm->mi_params.mi_cols == cm->prev_frame->mi_cols)) {
+ cm->last_frame_seg_map = cm->prev_frame->seg_map;
+ } else {
+ cm->last_frame_seg_map = NULL;
+ }
+ // Read update flags
+ if (cm->features.primary_ref_frame == PRIMARY_REF_NONE) {
+ // These frames can't use previous frames, so must signal map + features
+ seg->update_map = 1;
+ seg->temporal_update = 0;
+ seg->update_data = 1;
+ } else {
+ seg->update_map = aom_rb_read_bit(rb);
+ if (seg->update_map) {
+ seg->temporal_update = aom_rb_read_bit(rb);
+ } else {
+ seg->temporal_update = 0;
+ }
+ seg->update_data = aom_rb_read_bit(rb);
+ }
+
+ // Segmentation data update
+ if (seg->update_data) {
+ av1_clearall_segfeatures(seg);
+
+ for (int i = 0; i < MAX_SEGMENTS; i++) {
+ for (int j = 0; j < SEG_LVL_MAX; j++) {
+ int data = 0;
+ const int feature_enabled = aom_rb_read_bit(rb);
+ if (feature_enabled) {
+ av1_enable_segfeature(seg, i, j);
+
+ const int data_max = av1_seg_feature_data_max(j);
+ const int data_min = -data_max;
+ const int ubits = get_unsigned_bits(data_max);
+
+ if (av1_is_segfeature_signed(j)) {
+ data = aom_rb_read_inv_signed_literal(rb, ubits);
+ } else {
+ data = aom_rb_read_literal(rb, ubits);
+ }
+
+ data = clamp(data, data_min, data_max);
+ }
+ av1_set_segdata(seg, i, j, data);
+ }
+ }
+ av1_calculate_segdata(seg);
+ } else if (cm->prev_frame) {
+ segfeatures_copy(seg, &cm->prev_frame->seg);
+ }
+ segfeatures_copy(&cm->cur_frame->seg, seg);
+}
+
+static AOM_INLINE void decode_restoration_mode(AV1_COMMON *cm,
+ struct aom_read_bit_buffer *rb) {
+ assert(!cm->features.all_lossless);
+ const int num_planes = av1_num_planes(cm);
+ if (cm->features.allow_intrabc) return;
+ int all_none = 1, chroma_none = 1;
+ for (int p = 0; p < num_planes; ++p) {
+ RestorationInfo *rsi = &cm->rst_info[p];
+ if (aom_rb_read_bit(rb)) {
+ rsi->frame_restoration_type =
+ aom_rb_read_bit(rb) ? RESTORE_SGRPROJ : RESTORE_WIENER;
+ } else {
+ rsi->frame_restoration_type =
+ aom_rb_read_bit(rb) ? RESTORE_SWITCHABLE : RESTORE_NONE;
+ }
+ if (rsi->frame_restoration_type != RESTORE_NONE) {
+ all_none = 0;
+ chroma_none &= p == 0;
+ }
+ }
+ if (!all_none) {
+ assert(cm->seq_params->sb_size == BLOCK_64X64 ||
+ cm->seq_params->sb_size == BLOCK_128X128);
+ const int sb_size = cm->seq_params->sb_size == BLOCK_128X128 ? 128 : 64;
+
+ for (int p = 0; p < num_planes; ++p)
+ cm->rst_info[p].restoration_unit_size = sb_size;
+
+ RestorationInfo *rsi = &cm->rst_info[0];
+
+ if (sb_size == 64) {
+ rsi->restoration_unit_size <<= aom_rb_read_bit(rb);
+ }
+ if (rsi->restoration_unit_size > 64) {
+ rsi->restoration_unit_size <<= aom_rb_read_bit(rb);
+ }
+ } else {
+ const int size = RESTORATION_UNITSIZE_MAX;
+ for (int p = 0; p < num_planes; ++p)
+ cm->rst_info[p].restoration_unit_size = size;
+ }
+
+ if (num_planes > 1) {
+ int s =
+ AOMMIN(cm->seq_params->subsampling_x, cm->seq_params->subsampling_y);
+ if (s && !chroma_none) {
+ cm->rst_info[1].restoration_unit_size =
+ cm->rst_info[0].restoration_unit_size >> (aom_rb_read_bit(rb) * s);
+ } else {
+ cm->rst_info[1].restoration_unit_size =
+ cm->rst_info[0].restoration_unit_size;
+ }
+ cm->rst_info[2].restoration_unit_size =
+ cm->rst_info[1].restoration_unit_size;
+ }
+}
+
+static AOM_INLINE void read_wiener_filter(int wiener_win,
+ WienerInfo *wiener_info,
+ WienerInfo *ref_wiener_info,
+ aom_reader *rb) {
+ memset(wiener_info->vfilter, 0, sizeof(wiener_info->vfilter));
+ memset(wiener_info->hfilter, 0, sizeof(wiener_info->hfilter));
+
+ if (wiener_win == WIENER_WIN)
+ wiener_info->vfilter[0] = wiener_info->vfilter[WIENER_WIN - 1] =
+ aom_read_primitive_refsubexpfin(
+ rb, WIENER_FILT_TAP0_MAXV - WIENER_FILT_TAP0_MINV + 1,
+ WIENER_FILT_TAP0_SUBEXP_K,
+ ref_wiener_info->vfilter[0] - WIENER_FILT_TAP0_MINV, ACCT_STR) +
+ WIENER_FILT_TAP0_MINV;
+ else
+ wiener_info->vfilter[0] = wiener_info->vfilter[WIENER_WIN - 1] = 0;
+ wiener_info->vfilter[1] = wiener_info->vfilter[WIENER_WIN - 2] =
+ aom_read_primitive_refsubexpfin(
+ rb, WIENER_FILT_TAP1_MAXV - WIENER_FILT_TAP1_MINV + 1,
+ WIENER_FILT_TAP1_SUBEXP_K,
+ ref_wiener_info->vfilter[1] - WIENER_FILT_TAP1_MINV, ACCT_STR) +
+ WIENER_FILT_TAP1_MINV;
+ wiener_info->vfilter[2] = wiener_info->vfilter[WIENER_WIN - 3] =
+ aom_read_primitive_refsubexpfin(
+ rb, WIENER_FILT_TAP2_MAXV - WIENER_FILT_TAP2_MINV + 1,
+ WIENER_FILT_TAP2_SUBEXP_K,
+ ref_wiener_info->vfilter[2] - WIENER_FILT_TAP2_MINV, ACCT_STR) +
+ WIENER_FILT_TAP2_MINV;
+ // The central element has an implicit +WIENER_FILT_STEP
+ wiener_info->vfilter[WIENER_HALFWIN] =
+ -2 * (wiener_info->vfilter[0] + wiener_info->vfilter[1] +
+ wiener_info->vfilter[2]);
+
+ if (wiener_win == WIENER_WIN)
+ wiener_info->hfilter[0] = wiener_info->hfilter[WIENER_WIN - 1] =
+ aom_read_primitive_refsubexpfin(
+ rb, WIENER_FILT_TAP0_MAXV - WIENER_FILT_TAP0_MINV + 1,
+ WIENER_FILT_TAP0_SUBEXP_K,
+ ref_wiener_info->hfilter[0] - WIENER_FILT_TAP0_MINV, ACCT_STR) +
+ WIENER_FILT_TAP0_MINV;
+ else
+ wiener_info->hfilter[0] = wiener_info->hfilter[WIENER_WIN - 1] = 0;
+ wiener_info->hfilter[1] = wiener_info->hfilter[WIENER_WIN - 2] =
+ aom_read_primitive_refsubexpfin(
+ rb, WIENER_FILT_TAP1_MAXV - WIENER_FILT_TAP1_MINV + 1,
+ WIENER_FILT_TAP1_SUBEXP_K,
+ ref_wiener_info->hfilter[1] - WIENER_FILT_TAP1_MINV, ACCT_STR) +
+ WIENER_FILT_TAP1_MINV;
+ wiener_info->hfilter[2] = wiener_info->hfilter[WIENER_WIN - 3] =
+ aom_read_primitive_refsubexpfin(
+ rb, WIENER_FILT_TAP2_MAXV - WIENER_FILT_TAP2_MINV + 1,
+ WIENER_FILT_TAP2_SUBEXP_K,
+ ref_wiener_info->hfilter[2] - WIENER_FILT_TAP2_MINV, ACCT_STR) +
+ WIENER_FILT_TAP2_MINV;
+ // The central element has an implicit +WIENER_FILT_STEP
+ wiener_info->hfilter[WIENER_HALFWIN] =
+ -2 * (wiener_info->hfilter[0] + wiener_info->hfilter[1] +
+ wiener_info->hfilter[2]);
+ memcpy(ref_wiener_info, wiener_info, sizeof(*wiener_info));
+}
+
+static AOM_INLINE void read_sgrproj_filter(SgrprojInfo *sgrproj_info,
+ SgrprojInfo *ref_sgrproj_info,
+ aom_reader *rb) {
+ sgrproj_info->ep = aom_read_literal(rb, SGRPROJ_PARAMS_BITS, ACCT_STR);
+ const sgr_params_type *params = &av1_sgr_params[sgrproj_info->ep];
+
+ if (params->r[0] == 0) {
+ sgrproj_info->xqd[0] = 0;
+ sgrproj_info->xqd[1] =
+ aom_read_primitive_refsubexpfin(
+ rb, SGRPROJ_PRJ_MAX1 - SGRPROJ_PRJ_MIN1 + 1, SGRPROJ_PRJ_SUBEXP_K,
+ ref_sgrproj_info->xqd[1] - SGRPROJ_PRJ_MIN1, ACCT_STR) +
+ SGRPROJ_PRJ_MIN1;
+ } else if (params->r[1] == 0) {
+ sgrproj_info->xqd[0] =
+ aom_read_primitive_refsubexpfin(
+ rb, SGRPROJ_PRJ_MAX0 - SGRPROJ_PRJ_MIN0 + 1, SGRPROJ_PRJ_SUBEXP_K,
+ ref_sgrproj_info->xqd[0] - SGRPROJ_PRJ_MIN0, ACCT_STR) +
+ SGRPROJ_PRJ_MIN0;
+ sgrproj_info->xqd[1] = clamp((1 << SGRPROJ_PRJ_BITS) - sgrproj_info->xqd[0],
+ SGRPROJ_PRJ_MIN1, SGRPROJ_PRJ_MAX1);
+ } else {
+ sgrproj_info->xqd[0] =
+ aom_read_primitive_refsubexpfin(
+ rb, SGRPROJ_PRJ_MAX0 - SGRPROJ_PRJ_MIN0 + 1, SGRPROJ_PRJ_SUBEXP_K,
+ ref_sgrproj_info->xqd[0] - SGRPROJ_PRJ_MIN0, ACCT_STR) +
+ SGRPROJ_PRJ_MIN0;
+ sgrproj_info->xqd[1] =
+ aom_read_primitive_refsubexpfin(
+ rb, SGRPROJ_PRJ_MAX1 - SGRPROJ_PRJ_MIN1 + 1, SGRPROJ_PRJ_SUBEXP_K,
+ ref_sgrproj_info->xqd[1] - SGRPROJ_PRJ_MIN1, ACCT_STR) +
+ SGRPROJ_PRJ_MIN1;
+ }
+
+ memcpy(ref_sgrproj_info, sgrproj_info, sizeof(*sgrproj_info));
+}
+
+static AOM_INLINE void loop_restoration_read_sb_coeffs(
+ const AV1_COMMON *const cm, MACROBLOCKD *xd, aom_reader *const r, int plane,
+ int runit_idx) {
+ const RestorationInfo *rsi = &cm->rst_info[plane];
+ RestorationUnitInfo *rui = &rsi->unit_info[runit_idx];
+ assert(rsi->frame_restoration_type != RESTORE_NONE);
+
+ assert(!cm->features.all_lossless);
+
+ const int wiener_win = (plane > 0) ? WIENER_WIN_CHROMA : WIENER_WIN;
+ WienerInfo *wiener_info = xd->wiener_info + plane;
+ SgrprojInfo *sgrproj_info = xd->sgrproj_info + plane;
+
+ if (rsi->frame_restoration_type == RESTORE_SWITCHABLE) {
+ rui->restoration_type =
+ aom_read_symbol(r, xd->tile_ctx->switchable_restore_cdf,
+ RESTORE_SWITCHABLE_TYPES, ACCT_STR);
+ switch (rui->restoration_type) {
+ case RESTORE_WIENER:
+ read_wiener_filter(wiener_win, &rui->wiener_info, wiener_info, r);
+ break;
+ case RESTORE_SGRPROJ:
+ read_sgrproj_filter(&rui->sgrproj_info, sgrproj_info, r);
+ break;
+ default: assert(rui->restoration_type == RESTORE_NONE); break;
+ }
+ } else if (rsi->frame_restoration_type == RESTORE_WIENER) {
+ if (aom_read_symbol(r, xd->tile_ctx->wiener_restore_cdf, 2, ACCT_STR)) {
+ rui->restoration_type = RESTORE_WIENER;
+ read_wiener_filter(wiener_win, &rui->wiener_info, wiener_info, r);
+ } else {
+ rui->restoration_type = RESTORE_NONE;
+ }
+ } else if (rsi->frame_restoration_type == RESTORE_SGRPROJ) {
+ if (aom_read_symbol(r, xd->tile_ctx->sgrproj_restore_cdf, 2, ACCT_STR)) {
+ rui->restoration_type = RESTORE_SGRPROJ;
+ read_sgrproj_filter(&rui->sgrproj_info, sgrproj_info, r);
+ } else {
+ rui->restoration_type = RESTORE_NONE;
+ }
+ }
+}
+
+static AOM_INLINE void setup_loopfilter(AV1_COMMON *cm,
+ struct aom_read_bit_buffer *rb) {
+ const int num_planes = av1_num_planes(cm);
+ struct loopfilter *lf = &cm->lf;
+
+ if (cm->features.allow_intrabc || cm->features.coded_lossless) {
+ // write default deltas to frame buffer
+ av1_set_default_ref_deltas(cm->cur_frame->ref_deltas);
+ av1_set_default_mode_deltas(cm->cur_frame->mode_deltas);
+ return;
+ }
+ assert(!cm->features.coded_lossless);
+ if (cm->prev_frame) {
+ // write deltas to frame buffer
+ memcpy(lf->ref_deltas, cm->prev_frame->ref_deltas, REF_FRAMES);
+ memcpy(lf->mode_deltas, cm->prev_frame->mode_deltas, MAX_MODE_LF_DELTAS);
+ } else {
+ av1_set_default_ref_deltas(lf->ref_deltas);
+ av1_set_default_mode_deltas(lf->mode_deltas);
+ }
+ lf->filter_level[0] = aom_rb_read_literal(rb, 6);
+ lf->filter_level[1] = aom_rb_read_literal(rb, 6);
+ if (num_planes > 1) {
+ if (lf->filter_level[0] || lf->filter_level[1]) {
+ lf->filter_level_u = aom_rb_read_literal(rb, 6);
+ lf->filter_level_v = aom_rb_read_literal(rb, 6);
+ }
+ }
+ lf->sharpness_level = aom_rb_read_literal(rb, 3);
+
+ // Read in loop filter deltas applied at the MB level based on mode or ref
+ // frame.
+ lf->mode_ref_delta_update = 0;
+
+ lf->mode_ref_delta_enabled = aom_rb_read_bit(rb);
+ if (lf->mode_ref_delta_enabled) {
+ lf->mode_ref_delta_update = aom_rb_read_bit(rb);
+ if (lf->mode_ref_delta_update) {
+ for (int i = 0; i < REF_FRAMES; i++)
+ if (aom_rb_read_bit(rb))
+ lf->ref_deltas[i] = aom_rb_read_inv_signed_literal(rb, 6);
+
+ for (int i = 0; i < MAX_MODE_LF_DELTAS; i++)
+ if (aom_rb_read_bit(rb))
+ lf->mode_deltas[i] = aom_rb_read_inv_signed_literal(rb, 6);
+ }
+ }
+
+ // write deltas to frame buffer
+ memcpy(cm->cur_frame->ref_deltas, lf->ref_deltas, REF_FRAMES);
+ memcpy(cm->cur_frame->mode_deltas, lf->mode_deltas, MAX_MODE_LF_DELTAS);
+}
+
+static AOM_INLINE void setup_cdef(AV1_COMMON *cm,
+ struct aom_read_bit_buffer *rb) {
+ const int num_planes = av1_num_planes(cm);
+ CdefInfo *const cdef_info = &cm->cdef_info;
+
+ if (cm->features.allow_intrabc) return;
+ cdef_info->cdef_damping = aom_rb_read_literal(rb, 2) + 3;
+ cdef_info->cdef_bits = aom_rb_read_literal(rb, 2);
+ cdef_info->nb_cdef_strengths = 1 << cdef_info->cdef_bits;
+ for (int i = 0; i < cdef_info->nb_cdef_strengths; i++) {
+ cdef_info->cdef_strengths[i] = aom_rb_read_literal(rb, CDEF_STRENGTH_BITS);
+ cdef_info->cdef_uv_strengths[i] =
+ num_planes > 1 ? aom_rb_read_literal(rb, CDEF_STRENGTH_BITS) : 0;
+ }
+}
+
+static INLINE int read_delta_q(struct aom_read_bit_buffer *rb) {
+ return aom_rb_read_bit(rb) ? aom_rb_read_inv_signed_literal(rb, 6) : 0;
+}
+
+static AOM_INLINE void setup_quantization(CommonQuantParams *quant_params,
+ int num_planes,
+ bool separate_uv_delta_q,
+ struct aom_read_bit_buffer *rb) {
+ quant_params->base_qindex = aom_rb_read_literal(rb, QINDEX_BITS);
+ quant_params->y_dc_delta_q = read_delta_q(rb);
+ if (num_planes > 1) {
+ int diff_uv_delta = 0;
+ if (separate_uv_delta_q) diff_uv_delta = aom_rb_read_bit(rb);
+ quant_params->u_dc_delta_q = read_delta_q(rb);
+ quant_params->u_ac_delta_q = read_delta_q(rb);
+ if (diff_uv_delta) {
+ quant_params->v_dc_delta_q = read_delta_q(rb);
+ quant_params->v_ac_delta_q = read_delta_q(rb);
+ } else {
+ quant_params->v_dc_delta_q = quant_params->u_dc_delta_q;
+ quant_params->v_ac_delta_q = quant_params->u_ac_delta_q;
+ }
+ } else {
+ quant_params->u_dc_delta_q = 0;
+ quant_params->u_ac_delta_q = 0;
+ quant_params->v_dc_delta_q = 0;
+ quant_params->v_ac_delta_q = 0;
+ }
+ quant_params->using_qmatrix = aom_rb_read_bit(rb);
+ if (quant_params->using_qmatrix) {
+ quant_params->qmatrix_level_y = aom_rb_read_literal(rb, QM_LEVEL_BITS);
+ quant_params->qmatrix_level_u = aom_rb_read_literal(rb, QM_LEVEL_BITS);
+ if (!separate_uv_delta_q)
+ quant_params->qmatrix_level_v = quant_params->qmatrix_level_u;
+ else
+ quant_params->qmatrix_level_v = aom_rb_read_literal(rb, QM_LEVEL_BITS);
+ } else {
+ quant_params->qmatrix_level_y = 0;
+ quant_params->qmatrix_level_u = 0;
+ quant_params->qmatrix_level_v = 0;
+ }
+}
+
+// Build y/uv dequant values based on segmentation.
+static AOM_INLINE void setup_segmentation_dequant(AV1_COMMON *const cm,
+ MACROBLOCKD *const xd) {
+ const int bit_depth = cm->seq_params->bit_depth;
+ // When segmentation is disabled, only the first value is used. The
+ // remaining are don't cares.
+ const int max_segments = cm->seg.enabled ? MAX_SEGMENTS : 1;
+ CommonQuantParams *const quant_params = &cm->quant_params;
+ for (int i = 0; i < max_segments; ++i) {
+ const int qindex = xd->qindex[i];
+ quant_params->y_dequant_QTX[i][0] =
+ av1_dc_quant_QTX(qindex, quant_params->y_dc_delta_q, bit_depth);
+ quant_params->y_dequant_QTX[i][1] = av1_ac_quant_QTX(qindex, 0, bit_depth);
+ quant_params->u_dequant_QTX[i][0] =
+ av1_dc_quant_QTX(qindex, quant_params->u_dc_delta_q, bit_depth);
+ quant_params->u_dequant_QTX[i][1] =
+ av1_ac_quant_QTX(qindex, quant_params->u_ac_delta_q, bit_depth);
+ quant_params->v_dequant_QTX[i][0] =
+ av1_dc_quant_QTX(qindex, quant_params->v_dc_delta_q, bit_depth);
+ quant_params->v_dequant_QTX[i][1] =
+ av1_ac_quant_QTX(qindex, quant_params->v_ac_delta_q, bit_depth);
+ const int use_qmatrix = av1_use_qmatrix(quant_params, xd, i);
+ // NB: depends on base index so there is only 1 set per frame
+ // No quant weighting when lossless or signalled not using QM
+ const int qmlevel_y =
+ use_qmatrix ? quant_params->qmatrix_level_y : NUM_QM_LEVELS - 1;
+ for (int j = 0; j < TX_SIZES_ALL; ++j) {
+ quant_params->y_iqmatrix[i][j] =
+ av1_iqmatrix(quant_params, qmlevel_y, AOM_PLANE_Y, j);
+ }
+ const int qmlevel_u =
+ use_qmatrix ? quant_params->qmatrix_level_u : NUM_QM_LEVELS - 1;
+ for (int j = 0; j < TX_SIZES_ALL; ++j) {
+ quant_params->u_iqmatrix[i][j] =
+ av1_iqmatrix(quant_params, qmlevel_u, AOM_PLANE_U, j);
+ }
+ const int qmlevel_v =
+ use_qmatrix ? quant_params->qmatrix_level_v : NUM_QM_LEVELS - 1;
+ for (int j = 0; j < TX_SIZES_ALL; ++j) {
+ quant_params->v_iqmatrix[i][j] =
+ av1_iqmatrix(quant_params, qmlevel_v, AOM_PLANE_V, j);
+ }
+ }
+}
+
+static InterpFilter read_frame_interp_filter(struct aom_read_bit_buffer *rb) {
+ return aom_rb_read_bit(rb) ? SWITCHABLE
+ : aom_rb_read_literal(rb, LOG_SWITCHABLE_FILTERS);
+}
+
+static AOM_INLINE void setup_render_size(AV1_COMMON *cm,
+ struct aom_read_bit_buffer *rb) {
+ cm->render_width = cm->superres_upscaled_width;
+ cm->render_height = cm->superres_upscaled_height;
+ if (aom_rb_read_bit(rb))
+ av1_read_frame_size(rb, 16, 16, &cm->render_width, &cm->render_height);
+}
+
+// TODO(afergs): make "struct aom_read_bit_buffer *const rb"?
+static AOM_INLINE void setup_superres(AV1_COMMON *const cm,
+ struct aom_read_bit_buffer *rb,
+ int *width, int *height) {
+ cm->superres_upscaled_width = *width;
+ cm->superres_upscaled_height = *height;
+
+ const SequenceHeader *const seq_params = cm->seq_params;
+ if (!seq_params->enable_superres) return;
+
+ if (aom_rb_read_bit(rb)) {
+ cm->superres_scale_denominator =
+ (uint8_t)aom_rb_read_literal(rb, SUPERRES_SCALE_BITS);
+ cm->superres_scale_denominator += SUPERRES_SCALE_DENOMINATOR_MIN;
+ // Don't edit cm->width or cm->height directly, or the buffers won't get
+ // resized correctly
+ av1_calculate_scaled_superres_size(width, height,
+ cm->superres_scale_denominator);
+ } else {
+ // 1:1 scaling - ie. no scaling, scale not provided
+ cm->superres_scale_denominator = SCALE_NUMERATOR;
+ }
+}
+
+static AOM_INLINE void resize_context_buffers(AV1_COMMON *cm, int width,
+ int height) {
+#if CONFIG_SIZE_LIMIT
+ if (width > DECODE_WIDTH_LIMIT || height > DECODE_HEIGHT_LIMIT)
+ aom_internal_error(cm->error, AOM_CODEC_CORRUPT_FRAME,
+ "Dimensions of %dx%d beyond allowed size of %dx%d.",
+ width, height, DECODE_WIDTH_LIMIT, DECODE_HEIGHT_LIMIT);
+#endif
+ if (cm->width != width || cm->height != height) {
+ const int new_mi_rows = CEIL_POWER_OF_TWO(height, MI_SIZE_LOG2);
+ const int new_mi_cols = CEIL_POWER_OF_TWO(width, MI_SIZE_LOG2);
+
+ // Allocations in av1_alloc_context_buffers() depend on individual
+ // dimensions as well as the overall size.
+ if (new_mi_cols > cm->mi_params.mi_cols ||
+ new_mi_rows > cm->mi_params.mi_rows) {
+ if (av1_alloc_context_buffers(cm, width, height, BLOCK_4X4)) {
+ // The cm->mi_* values have been cleared and any existing context
+ // buffers have been freed. Clear cm->width and cm->height to be
+ // consistent and to force a realloc next time.
+ cm->width = 0;
+ cm->height = 0;
+ aom_internal_error(cm->error, AOM_CODEC_MEM_ERROR,
+ "Failed to allocate context buffers");
+ }
+ } else {
+ cm->mi_params.set_mb_mi(&cm->mi_params, width, height, BLOCK_4X4);
+ }
+ av1_init_mi_buffers(&cm->mi_params);
+ cm->width = width;
+ cm->height = height;
+ }
+
+ ensure_mv_buffer(cm->cur_frame, cm);
+ cm->cur_frame->width = cm->width;
+ cm->cur_frame->height = cm->height;
+}
+
+static AOM_INLINE void setup_buffer_pool(AV1_COMMON *cm) {
+ BufferPool *const pool = cm->buffer_pool;
+ const SequenceHeader *const seq_params = cm->seq_params;
+
+ lock_buffer_pool(pool);
+ if (aom_realloc_frame_buffer(
+ &cm->cur_frame->buf, cm->width, cm->height, seq_params->subsampling_x,
+ seq_params->subsampling_y, seq_params->use_highbitdepth,
+ AOM_DEC_BORDER_IN_PIXELS, cm->features.byte_alignment,
+ &cm->cur_frame->raw_frame_buffer, pool->get_fb_cb, pool->cb_priv, 0,
+ 0)) {
+ unlock_buffer_pool(pool);
+ aom_internal_error(cm->error, AOM_CODEC_MEM_ERROR,
+ "Failed to allocate frame buffer");
+ }
+ unlock_buffer_pool(pool);
+
+ cm->cur_frame->buf.bit_depth = (unsigned int)seq_params->bit_depth;
+ cm->cur_frame->buf.color_primaries = seq_params->color_primaries;
+ cm->cur_frame->buf.transfer_characteristics =
+ seq_params->transfer_characteristics;
+ cm->cur_frame->buf.matrix_coefficients = seq_params->matrix_coefficients;
+ cm->cur_frame->buf.monochrome = seq_params->monochrome;
+ cm->cur_frame->buf.chroma_sample_position =
+ seq_params->chroma_sample_position;
+ cm->cur_frame->buf.color_range = seq_params->color_range;
+ cm->cur_frame->buf.render_width = cm->render_width;
+ cm->cur_frame->buf.render_height = cm->render_height;
+}
+
+static AOM_INLINE void setup_frame_size(AV1_COMMON *cm,
+ int frame_size_override_flag,
+ struct aom_read_bit_buffer *rb) {
+ const SequenceHeader *const seq_params = cm->seq_params;
+ int width, height;
+
+ if (frame_size_override_flag) {
+ int num_bits_width = seq_params->num_bits_width;
+ int num_bits_height = seq_params->num_bits_height;
+ av1_read_frame_size(rb, num_bits_width, num_bits_height, &width, &height);
+ if (width > seq_params->max_frame_width ||
+ height > seq_params->max_frame_height) {
+ aom_internal_error(cm->error, AOM_CODEC_CORRUPT_FRAME,
+ "Frame dimensions are larger than the maximum values");
+ }
+ } else {
+ width = seq_params->max_frame_width;
+ height = seq_params->max_frame_height;
+ }
+
+ setup_superres(cm, rb, &width, &height);
+ resize_context_buffers(cm, width, height);
+ setup_render_size(cm, rb);
+ setup_buffer_pool(cm);
+}
+
+static AOM_INLINE void setup_sb_size(SequenceHeader *seq_params,
+ struct aom_read_bit_buffer *rb) {
+ set_sb_size(seq_params, aom_rb_read_bit(rb) ? BLOCK_128X128 : BLOCK_64X64);
+}
+
+static INLINE int valid_ref_frame_img_fmt(aom_bit_depth_t ref_bit_depth,
+ int ref_xss, int ref_yss,
+ aom_bit_depth_t this_bit_depth,
+ int this_xss, int this_yss) {
+ return ref_bit_depth == this_bit_depth && ref_xss == this_xss &&
+ ref_yss == this_yss;
+}
+
+static AOM_INLINE void setup_frame_size_with_refs(
+ AV1_COMMON *cm, struct aom_read_bit_buffer *rb) {
+ int width, height;
+ int found = 0;
+ int has_valid_ref_frame = 0;
+ for (int i = LAST_FRAME; i <= ALTREF_FRAME; ++i) {
+ if (aom_rb_read_bit(rb)) {
+ const RefCntBuffer *const ref_buf = get_ref_frame_buf(cm, i);
+ // This will never be NULL in a normal stream, as streams are required to
+ // have a shown keyframe before any inter frames, which would refresh all
+ // the reference buffers. However, it might be null if we're starting in
+ // the middle of a stream, and static analysis will error if we don't do
+ // a null check here.
+ if (ref_buf == NULL) {
+ aom_internal_error(cm->error, AOM_CODEC_CORRUPT_FRAME,
+ "Invalid condition: invalid reference buffer");
+ } else {
+ const YV12_BUFFER_CONFIG *const buf = &ref_buf->buf;
+ width = buf->y_crop_width;
+ height = buf->y_crop_height;
+ cm->render_width = buf->render_width;
+ cm->render_height = buf->render_height;
+ setup_superres(cm, rb, &width, &height);
+ resize_context_buffers(cm, width, height);
+ found = 1;
+ break;
+ }
+ }
+ }
+
+ const SequenceHeader *const seq_params = cm->seq_params;
+ if (!found) {
+ int num_bits_width = seq_params->num_bits_width;
+ int num_bits_height = seq_params->num_bits_height;
+
+ av1_read_frame_size(rb, num_bits_width, num_bits_height, &width, &height);
+ setup_superres(cm, rb, &width, &height);
+ resize_context_buffers(cm, width, height);
+ setup_render_size(cm, rb);
+ }
+
+ if (width <= 0 || height <= 0)
+ aom_internal_error(cm->error, AOM_CODEC_CORRUPT_FRAME,
+ "Invalid frame size");
+
+ // Check to make sure at least one of frames that this frame references
+ // has valid dimensions.
+ for (int i = LAST_FRAME; i <= ALTREF_FRAME; ++i) {
+ const RefCntBuffer *const ref_frame = get_ref_frame_buf(cm, i);
+ has_valid_ref_frame |=
+ valid_ref_frame_size(ref_frame->buf.y_crop_width,
+ ref_frame->buf.y_crop_height, width, height);
+ }
+ if (!has_valid_ref_frame)
+ aom_internal_error(cm->error, AOM_CODEC_CORRUPT_FRAME,
+ "Referenced frame has invalid size");
+ for (int i = LAST_FRAME; i <= ALTREF_FRAME; ++i) {
+ const RefCntBuffer *const ref_frame = get_ref_frame_buf(cm, i);
+ if (!valid_ref_frame_img_fmt(
+ ref_frame->buf.bit_depth, ref_frame->buf.subsampling_x,
+ ref_frame->buf.subsampling_y, seq_params->bit_depth,
+ seq_params->subsampling_x, seq_params->subsampling_y))
+ aom_internal_error(cm->error, AOM_CODEC_CORRUPT_FRAME,
+ "Referenced frame has incompatible color format");
+ }
+ setup_buffer_pool(cm);
+}
+
+// Same function as av1_read_uniform but reading from uncompresses header wb
+static int rb_read_uniform(struct aom_read_bit_buffer *const rb, int n) {
+ const int l = get_unsigned_bits(n);
+ const int m = (1 << l) - n;
+ const int v = aom_rb_read_literal(rb, l - 1);
+ assert(l != 0);
+ if (v < m)
+ return v;
+ else
+ return (v << 1) - m + aom_rb_read_bit(rb);
+}
+
+static AOM_INLINE void read_tile_info_max_tile(
+ AV1_COMMON *const cm, struct aom_read_bit_buffer *const rb) {
+ const SequenceHeader *const seq_params = cm->seq_params;
+ CommonTileParams *const tiles = &cm->tiles;
+ int width_sb =
+ CEIL_POWER_OF_TWO(cm->mi_params.mi_cols, seq_params->mib_size_log2);
+ int height_sb =
+ CEIL_POWER_OF_TWO(cm->mi_params.mi_rows, seq_params->mib_size_log2);
+
+ av1_get_tile_limits(cm);
+ tiles->uniform_spacing = aom_rb_read_bit(rb);
+
+ // Read tile columns
+ if (tiles->uniform_spacing) {
+ tiles->log2_cols = tiles->min_log2_cols;
+ while (tiles->log2_cols < tiles->max_log2_cols) {
+ if (!aom_rb_read_bit(rb)) {
+ break;
+ }
+ tiles->log2_cols++;
+ }
+ } else {
+ int i;
+ int start_sb;
+ for (i = 0, start_sb = 0; width_sb > 0 && i < MAX_TILE_COLS; i++) {
+ const int size_sb =
+ 1 + rb_read_uniform(rb, AOMMIN(width_sb, tiles->max_width_sb));
+ tiles->col_start_sb[i] = start_sb;
+ start_sb += size_sb;
+ width_sb -= size_sb;
+ }
+ tiles->cols = i;
+ tiles->col_start_sb[i] = start_sb + width_sb;
+ }
+ av1_calculate_tile_cols(seq_params, cm->mi_params.mi_rows,
+ cm->mi_params.mi_cols, tiles);
+
+ // Read tile rows
+ if (tiles->uniform_spacing) {
+ tiles->log2_rows = tiles->min_log2_rows;
+ while (tiles->log2_rows < tiles->max_log2_rows) {
+ if (!aom_rb_read_bit(rb)) {
+ break;
+ }
+ tiles->log2_rows++;
+ }
+ } else {
+ int i;
+ int start_sb;
+ for (i = 0, start_sb = 0; height_sb > 0 && i < MAX_TILE_ROWS; i++) {
+ const int size_sb =
+ 1 + rb_read_uniform(rb, AOMMIN(height_sb, tiles->max_height_sb));
+ tiles->row_start_sb[i] = start_sb;
+ start_sb += size_sb;
+ height_sb -= size_sb;
+ }
+ tiles->rows = i;
+ tiles->row_start_sb[i] = start_sb + height_sb;
+ }
+ av1_calculate_tile_rows(seq_params, cm->mi_params.mi_rows, tiles);
+}
+
+void av1_set_single_tile_decoding_mode(AV1_COMMON *const cm) {
+ cm->tiles.single_tile_decoding = 0;
+ if (cm->tiles.large_scale) {
+ struct loopfilter *lf = &cm->lf;
+ RestorationInfo *const rst_info = cm->rst_info;
+ const CdefInfo *const cdef_info = &cm->cdef_info;
+
+ // Figure out single_tile_decoding by loopfilter_level.
+ const int no_loopfilter = !(lf->filter_level[0] || lf->filter_level[1]);
+ const int no_cdef = cdef_info->cdef_bits == 0 &&
+ cdef_info->cdef_strengths[0] == 0 &&
+ cdef_info->cdef_uv_strengths[0] == 0;
+ const int no_restoration =
+ rst_info[0].frame_restoration_type == RESTORE_NONE &&
+ rst_info[1].frame_restoration_type == RESTORE_NONE &&
+ rst_info[2].frame_restoration_type == RESTORE_NONE;
+ assert(IMPLIES(cm->features.coded_lossless, no_loopfilter && no_cdef));
+ assert(IMPLIES(cm->features.all_lossless, no_restoration));
+ cm->tiles.single_tile_decoding = no_loopfilter && no_cdef && no_restoration;
+ }
+}
+
+static AOM_INLINE void read_tile_info(AV1Decoder *const pbi,
+ struct aom_read_bit_buffer *const rb) {
+ AV1_COMMON *const cm = &pbi->common;
+
+ read_tile_info_max_tile(cm, rb);
+
+ pbi->context_update_tile_id = 0;
+ if (cm->tiles.rows * cm->tiles.cols > 1) {
+ // tile to use for cdf update
+ pbi->context_update_tile_id =
+ aom_rb_read_literal(rb, cm->tiles.log2_rows + cm->tiles.log2_cols);
+ if (pbi->context_update_tile_id >= cm->tiles.rows * cm->tiles.cols) {
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "Invalid context_update_tile_id");
+ }
+ // tile size magnitude
+ pbi->tile_size_bytes = aom_rb_read_literal(rb, 2) + 1;
+ }
+}
+
+#if EXT_TILE_DEBUG
+static AOM_INLINE void read_ext_tile_info(
+ AV1Decoder *const pbi, struct aom_read_bit_buffer *const rb) {
+ AV1_COMMON *const cm = &pbi->common;
+
+ // This information is stored as a separate byte.
+ int mod = rb->bit_offset % CHAR_BIT;
+ if (mod > 0) aom_rb_read_literal(rb, CHAR_BIT - mod);
+ assert(rb->bit_offset % CHAR_BIT == 0);
+
+ if (cm->tiles.cols * cm->tiles.rows > 1) {
+ // Read the number of bytes used to store tile size
+ pbi->tile_col_size_bytes = aom_rb_read_literal(rb, 2) + 1;
+ pbi->tile_size_bytes = aom_rb_read_literal(rb, 2) + 1;
+ }
+}
+#endif // EXT_TILE_DEBUG
+
+static size_t mem_get_varsize(const uint8_t *src, int sz) {
+ switch (sz) {
+ case 1: return src[0];
+ case 2: return mem_get_le16(src);
+ case 3: return mem_get_le24(src);
+ case 4: return mem_get_le32(src);
+ default: assert(0 && "Invalid size"); return -1;
+ }
+}
+
+#if EXT_TILE_DEBUG
+// Reads the next tile returning its size and adjusting '*data' accordingly
+// based on 'is_last'. On return, '*data' is updated to point to the end of the
+// raw tile buffer in the bit stream.
+static AOM_INLINE void get_ls_tile_buffer(
+ const uint8_t *const data_end, struct aom_internal_error_info *error_info,
+ const uint8_t **data, TileBufferDec (*const tile_buffers)[MAX_TILE_COLS],
+ int tile_size_bytes, int col, int row, int tile_copy_mode) {
+ size_t size;
+
+ size_t copy_size = 0;
+ const uint8_t *copy_data = NULL;
+
+ if (!read_is_valid(*data, tile_size_bytes, data_end))
+ aom_internal_error(error_info, AOM_CODEC_CORRUPT_FRAME,
+ "Truncated packet or corrupt tile length");
+ size = mem_get_varsize(*data, tile_size_bytes);
+
+ // If tile_copy_mode = 1, then the top bit of the tile header indicates copy
+ // mode.
+ if (tile_copy_mode && (size >> (tile_size_bytes * 8 - 1)) == 1) {
+ // The remaining bits in the top byte signal the row offset
+ int offset = (size >> (tile_size_bytes - 1) * 8) & 0x7f;
+
+ // Currently, only use tiles in same column as reference tiles.
+ copy_data = tile_buffers[row - offset][col].data;
+ copy_size = tile_buffers[row - offset][col].size;
+ size = 0;
+ } else {
+ size += AV1_MIN_TILE_SIZE_BYTES;
+ }
+
+ *data += tile_size_bytes;
+
+ if (size > (size_t)(data_end - *data))
+ aom_internal_error(error_info, AOM_CODEC_CORRUPT_FRAME,
+ "Truncated packet or corrupt tile size");
+
+ if (size > 0) {
+ tile_buffers[row][col].data = *data;
+ tile_buffers[row][col].size = size;
+ } else {
+ tile_buffers[row][col].data = copy_data;
+ tile_buffers[row][col].size = copy_size;
+ }
+
+ *data += size;
+}
+
+// Returns the end of the last tile buffer
+// (tile_buffers[cm->tiles.rows - 1][cm->tiles.cols - 1]).
+static const uint8_t *get_ls_tile_buffers(
+ AV1Decoder *pbi, const uint8_t *data, const uint8_t *data_end,
+ TileBufferDec (*const tile_buffers)[MAX_TILE_COLS]) {
+ AV1_COMMON *const cm = &pbi->common;
+ const int tile_cols = cm->tiles.cols;
+ const int tile_rows = cm->tiles.rows;
+ const int have_tiles = tile_cols * tile_rows > 1;
+ const uint8_t *raw_data_end; // The end of the last tile buffer
+
+ if (!have_tiles) {
+ const size_t tile_size = data_end - data;
+ tile_buffers[0][0].data = data;
+ tile_buffers[0][0].size = tile_size;
+ raw_data_end = NULL;
+ } else {
+ // We locate only the tile buffers that are required, which are the ones
+ // specified by pbi->dec_tile_col and pbi->dec_tile_row. Also, we always
+ // need the last (bottom right) tile buffer, as we need to know where the
+ // end of the compressed frame buffer is for proper superframe decoding.
+
+ const uint8_t *tile_col_data_end[MAX_TILE_COLS] = { NULL };
+ const uint8_t *const data_start = data;
+
+ const int dec_tile_row = AOMMIN(pbi->dec_tile_row, tile_rows);
+ const int single_row = pbi->dec_tile_row >= 0;
+ const int tile_rows_start = single_row ? dec_tile_row : 0;
+ const int tile_rows_end = single_row ? tile_rows_start + 1 : tile_rows;
+ const int dec_tile_col = AOMMIN(pbi->dec_tile_col, tile_cols);
+ const int single_col = pbi->dec_tile_col >= 0;
+ const int tile_cols_start = single_col ? dec_tile_col : 0;
+ const int tile_cols_end = single_col ? tile_cols_start + 1 : tile_cols;
+
+ const int tile_col_size_bytes = pbi->tile_col_size_bytes;
+ const int tile_size_bytes = pbi->tile_size_bytes;
+ int tile_width, tile_height;
+ av1_get_uniform_tile_size(cm, &tile_width, &tile_height);
+ const int tile_copy_mode =
+ ((AOMMAX(tile_width, tile_height) << MI_SIZE_LOG2) <= 256) ? 1 : 0;
+ // Read tile column sizes for all columns (we need the last tile buffer)
+ for (int c = 0; c < tile_cols; ++c) {
+ const int is_last = c == tile_cols - 1;
+ size_t tile_col_size;
+
+ if (!is_last) {
+ tile_col_size = mem_get_varsize(data, tile_col_size_bytes);
+ data += tile_col_size_bytes;
+ tile_col_data_end[c] = data + tile_col_size;
+ } else {
+ tile_col_size = data_end - data;
+ tile_col_data_end[c] = data_end;
+ }
+ data += tile_col_size;
+ }
+
+ data = data_start;
+
+ // Read the required tile sizes.
+ for (int c = tile_cols_start; c < tile_cols_end; ++c) {
+ const int is_last = c == tile_cols - 1;
+
+ if (c > 0) data = tile_col_data_end[c - 1];
+
+ if (!is_last) data += tile_col_size_bytes;
+
+ // Get the whole of the last column, otherwise stop at the required tile.
+ for (int r = 0; r < (is_last ? tile_rows : tile_rows_end); ++r) {
+ get_ls_tile_buffer(tile_col_data_end[c], &pbi->error, &data,
+ tile_buffers, tile_size_bytes, c, r, tile_copy_mode);
+ }
+ }
+
+ // If we have not read the last column, then read it to get the last tile.
+ if (tile_cols_end != tile_cols) {
+ const int c = tile_cols - 1;
+
+ data = tile_col_data_end[c - 1];
+
+ for (int r = 0; r < tile_rows; ++r) {
+ get_ls_tile_buffer(tile_col_data_end[c], &pbi->error, &data,
+ tile_buffers, tile_size_bytes, c, r, tile_copy_mode);
+ }
+ }
+ raw_data_end = data;
+ }
+ return raw_data_end;
+}
+#endif // EXT_TILE_DEBUG
+
+static const uint8_t *get_ls_single_tile_buffer(
+ AV1Decoder *pbi, const uint8_t *data,
+ TileBufferDec (*const tile_buffers)[MAX_TILE_COLS]) {
+ assert(pbi->dec_tile_row >= 0 && pbi->dec_tile_col >= 0);
+ tile_buffers[pbi->dec_tile_row][pbi->dec_tile_col].data = data;
+ tile_buffers[pbi->dec_tile_row][pbi->dec_tile_col].size =
+ (size_t)pbi->coded_tile_data_size;
+ return data + pbi->coded_tile_data_size;
+}
+
+// Reads the next tile returning its size and adjusting '*data' accordingly
+// based on 'is_last'.
+static AOM_INLINE void get_tile_buffer(
+ const uint8_t *const data_end, const int tile_size_bytes, int is_last,
+ struct aom_internal_error_info *error_info, const uint8_t **data,
+ TileBufferDec *const buf) {
+ size_t size;
+
+ if (!is_last) {
+ if (!read_is_valid(*data, tile_size_bytes, data_end))
+ aom_internal_error(error_info, AOM_CODEC_CORRUPT_FRAME,
+ "Not enough data to read tile size");
+
+ size = mem_get_varsize(*data, tile_size_bytes) + AV1_MIN_TILE_SIZE_BYTES;
+ *data += tile_size_bytes;
+
+ if (size > (size_t)(data_end - *data))
+ aom_internal_error(error_info, AOM_CODEC_CORRUPT_FRAME,
+ "Truncated packet or corrupt tile size");
+ } else {
+ size = data_end - *data;
+ }
+
+ buf->data = *data;
+ buf->size = size;
+
+ *data += size;
+}
+
+static AOM_INLINE void get_tile_buffers(
+ AV1Decoder *pbi, const uint8_t *data, const uint8_t *data_end,
+ TileBufferDec (*const tile_buffers)[MAX_TILE_COLS], int start_tile,
+ int end_tile) {
+ AV1_COMMON *const cm = &pbi->common;
+ const int tile_cols = cm->tiles.cols;
+ const int tile_rows = cm->tiles.rows;
+ int tc = 0;
+
+ for (int r = 0; r < tile_rows; ++r) {
+ for (int c = 0; c < tile_cols; ++c, ++tc) {
+ TileBufferDec *const buf = &tile_buffers[r][c];
+
+ const int is_last = (tc == end_tile);
+ const size_t hdr_offset = 0;
+
+ if (tc < start_tile || tc > end_tile) continue;
+
+ if (data + hdr_offset >= data_end)
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "Data ended before all tiles were read.");
+ data += hdr_offset;
+ get_tile_buffer(data_end, pbi->tile_size_bytes, is_last, &pbi->error,
+ &data, buf);
+ }
+ }
+}
+
+static AOM_INLINE void set_cb_buffer(AV1Decoder *pbi, DecoderCodingBlock *dcb,
+ CB_BUFFER *cb_buffer_base,
+ const int num_planes, int mi_row,
+ int mi_col) {
+ AV1_COMMON *const cm = &pbi->common;
+ int mib_size_log2 = cm->seq_params->mib_size_log2;
+ int stride = (cm->mi_params.mi_cols >> mib_size_log2) + 1;
+ int offset = (mi_row >> mib_size_log2) * stride + (mi_col >> mib_size_log2);
+ CB_BUFFER *cb_buffer = cb_buffer_base + offset;
+
+ for (int plane = 0; plane < num_planes; ++plane) {
+ dcb->dqcoeff_block[plane] = cb_buffer->dqcoeff[plane];
+ dcb->eob_data[plane] = cb_buffer->eob_data[plane];
+ dcb->cb_offset[plane] = 0;
+ dcb->txb_offset[plane] = 0;
+ }
+ MACROBLOCKD *const xd = &dcb->xd;
+ xd->plane[0].color_index_map = cb_buffer->color_index_map[0];
+ xd->plane[1].color_index_map = cb_buffer->color_index_map[1];
+ xd->color_index_map_offset[0] = 0;
+ xd->color_index_map_offset[1] = 0;
+}
+
+static AOM_INLINE void decoder_alloc_tile_data(AV1Decoder *pbi,
+ const int n_tiles) {
+ AV1_COMMON *const cm = &pbi->common;
+ aom_free(pbi->tile_data);
+ pbi->allocated_tiles = 0;
+ CHECK_MEM_ERROR(cm, pbi->tile_data,
+ aom_memalign(32, n_tiles * sizeof(*pbi->tile_data)));
+ pbi->allocated_tiles = n_tiles;
+ for (int i = 0; i < n_tiles; i++) {
+ TileDataDec *const tile_data = pbi->tile_data + i;
+ av1_zero(tile_data->dec_row_mt_sync);
+ }
+ pbi->allocated_row_mt_sync_rows = 0;
+}
+
+// Set up nsync by width.
+static INLINE int get_sync_range(int width) {
+// nsync numbers are picked by testing.
+#if 0
+ if (width < 640)
+ return 1;
+ else if (width <= 1280)
+ return 2;
+ else if (width <= 4096)
+ return 4;
+ else
+ return 8;
+#else
+ (void)width;
+#endif
+ return 1;
+}
+
+// Allocate memory for decoder row synchronization
+static AOM_INLINE void dec_row_mt_alloc(AV1DecRowMTSync *dec_row_mt_sync,
+ AV1_COMMON *cm, int rows) {
+ dec_row_mt_sync->allocated_sb_rows = rows;
+#if CONFIG_MULTITHREAD
+ {
+ int i;
+
+ CHECK_MEM_ERROR(cm, dec_row_mt_sync->mutex_,
+ aom_malloc(sizeof(*(dec_row_mt_sync->mutex_)) * rows));
+ if (dec_row_mt_sync->mutex_) {
+ for (i = 0; i < rows; ++i) {
+ pthread_mutex_init(&dec_row_mt_sync->mutex_[i], NULL);
+ }
+ }
+
+ CHECK_MEM_ERROR(cm, dec_row_mt_sync->cond_,
+ aom_malloc(sizeof(*(dec_row_mt_sync->cond_)) * rows));
+ if (dec_row_mt_sync->cond_) {
+ for (i = 0; i < rows; ++i) {
+ pthread_cond_init(&dec_row_mt_sync->cond_[i], NULL);
+ }
+ }
+ }
+#endif // CONFIG_MULTITHREAD
+
+ CHECK_MEM_ERROR(cm, dec_row_mt_sync->cur_sb_col,
+ aom_malloc(sizeof(*(dec_row_mt_sync->cur_sb_col)) * rows));
+
+ // Set up nsync.
+ dec_row_mt_sync->sync_range = get_sync_range(cm->width);
+}
+
+// Deallocate decoder row synchronization related mutex and data
+void av1_dec_row_mt_dealloc(AV1DecRowMTSync *dec_row_mt_sync) {
+ if (dec_row_mt_sync != NULL) {
+#if CONFIG_MULTITHREAD
+ int i;
+ if (dec_row_mt_sync->mutex_ != NULL) {
+ for (i = 0; i < dec_row_mt_sync->allocated_sb_rows; ++i) {
+ pthread_mutex_destroy(&dec_row_mt_sync->mutex_[i]);
+ }
+ aom_free(dec_row_mt_sync->mutex_);
+ }
+ if (dec_row_mt_sync->cond_ != NULL) {
+ for (i = 0; i < dec_row_mt_sync->allocated_sb_rows; ++i) {
+ pthread_cond_destroy(&dec_row_mt_sync->cond_[i]);
+ }
+ aom_free(dec_row_mt_sync->cond_);
+ }
+#endif // CONFIG_MULTITHREAD
+ aom_free(dec_row_mt_sync->cur_sb_col);
+
+ // clear the structure as the source of this call may be a resize in which
+ // case this call will be followed by an _alloc() which may fail.
+ av1_zero(*dec_row_mt_sync);
+ }
+}
+
+static INLINE void sync_read(AV1DecRowMTSync *const dec_row_mt_sync, int r,
+ int c) {
+#if CONFIG_MULTITHREAD
+ const int nsync = dec_row_mt_sync->sync_range;
+
+ if (r && !(c & (nsync - 1))) {
+ pthread_mutex_t *const mutex = &dec_row_mt_sync->mutex_[r - 1];
+ pthread_mutex_lock(mutex);
+
+ while (c > dec_row_mt_sync->cur_sb_col[r - 1] - nsync -
+ dec_row_mt_sync->intrabc_extra_top_right_sb_delay) {
+ pthread_cond_wait(&dec_row_mt_sync->cond_[r - 1], mutex);
+ }
+ pthread_mutex_unlock(mutex);
+ }
+#else
+ (void)dec_row_mt_sync;
+ (void)r;
+ (void)c;
+#endif // CONFIG_MULTITHREAD
+}
+
+static INLINE void sync_write(AV1DecRowMTSync *const dec_row_mt_sync, int r,
+ int c, const int sb_cols) {
+#if CONFIG_MULTITHREAD
+ const int nsync = dec_row_mt_sync->sync_range;
+ int cur;
+ int sig = 1;
+
+ if (c < sb_cols - 1) {
+ cur = c;
+ if (c % nsync) sig = 0;
+ } else {
+ cur = sb_cols + nsync + dec_row_mt_sync->intrabc_extra_top_right_sb_delay;
+ }
+
+ if (sig) {
+ pthread_mutex_lock(&dec_row_mt_sync->mutex_[r]);
+
+ dec_row_mt_sync->cur_sb_col[r] = cur;
+
+ pthread_cond_signal(&dec_row_mt_sync->cond_[r]);
+ pthread_mutex_unlock(&dec_row_mt_sync->mutex_[r]);
+ }
+#else
+ (void)dec_row_mt_sync;
+ (void)r;
+ (void)c;
+ (void)sb_cols;
+#endif // CONFIG_MULTITHREAD
+}
+
+static INLINE void signal_decoding_done_for_erroneous_row(
+ AV1Decoder *const pbi, const MACROBLOCKD *const xd) {
+ AV1_COMMON *const cm = &pbi->common;
+ const TileInfo *const tile = &xd->tile;
+ const int sb_row_in_tile =
+ ((xd->mi_row - tile->mi_row_start) >> cm->seq_params->mib_size_log2);
+ const int sb_cols_in_tile = av1_get_sb_cols_in_tile(cm, tile);
+ TileDataDec *const tile_data =
+ pbi->tile_data + tile->tile_row * cm->tiles.cols + tile->tile_col;
+ AV1DecRowMTSync *dec_row_mt_sync = &tile_data->dec_row_mt_sync;
+
+ sync_write(dec_row_mt_sync, sb_row_in_tile, sb_cols_in_tile - 1,
+ sb_cols_in_tile);
+}
+
+static AOM_INLINE void decode_tile_sb_row(AV1Decoder *pbi, ThreadData *const td,
+ const TileInfo *tile_info,
+ const int mi_row) {
+ AV1_COMMON *const cm = &pbi->common;
+ const int num_planes = av1_num_planes(cm);
+ TileDataDec *const tile_data = pbi->tile_data +
+ tile_info->tile_row * cm->tiles.cols +
+ tile_info->tile_col;
+ const int sb_cols_in_tile = av1_get_sb_cols_in_tile(cm, tile_info);
+ const int sb_row_in_tile =
+ (mi_row - tile_info->mi_row_start) >> cm->seq_params->mib_size_log2;
+ int sb_col_in_tile = 0;
+ int row_mt_exit = 0;
+
+ for (int mi_col = tile_info->mi_col_start; mi_col < tile_info->mi_col_end;
+ mi_col += cm->seq_params->mib_size, sb_col_in_tile++) {
+ set_cb_buffer(pbi, &td->dcb, pbi->cb_buffer_base, num_planes, mi_row,
+ mi_col);
+
+ sync_read(&tile_data->dec_row_mt_sync, sb_row_in_tile, sb_col_in_tile);
+
+#if CONFIG_MULTITHREAD
+ pthread_mutex_lock(pbi->row_mt_mutex_);
+#endif
+ row_mt_exit = pbi->frame_row_mt_info.row_mt_exit;
+#if CONFIG_MULTITHREAD
+ pthread_mutex_unlock(pbi->row_mt_mutex_);
+#endif
+
+ if (!row_mt_exit) {
+ // Decoding of the super-block
+ decode_partition(pbi, td, mi_row, mi_col, td->bit_reader,
+ cm->seq_params->sb_size, 0x2);
+ }
+
+ sync_write(&tile_data->dec_row_mt_sync, sb_row_in_tile, sb_col_in_tile,
+ sb_cols_in_tile);
+ }
+}
+
+static int check_trailing_bits_after_symbol_coder(aom_reader *r) {
+ if (aom_reader_has_overflowed(r)) return -1;
+
+ uint32_t nb_bits = aom_reader_tell(r);
+ uint32_t nb_bytes = (nb_bits + 7) >> 3;
+ const uint8_t *p = aom_reader_find_begin(r) + nb_bytes;
+
+ // aom_reader_tell() returns 1 for a newly initialized decoder, and the
+ // return value only increases as values are decoded. So nb_bits > 0, and
+ // thus p > p_begin. Therefore accessing p[-1] is safe.
+ uint8_t last_byte = p[-1];
+ uint8_t pattern = 128 >> ((nb_bits - 1) & 7);
+ if ((last_byte & (2 * pattern - 1)) != pattern) return -1;
+
+ // Make sure that all padding bytes are zero as required by the spec.
+ const uint8_t *p_end = aom_reader_find_end(r);
+ while (p < p_end) {
+ if (*p != 0) return -1;
+ p++;
+ }
+ return 0;
+}
+
+static AOM_INLINE void set_decode_func_pointers(ThreadData *td,
+ int parse_decode_flag) {
+ td->read_coeffs_tx_intra_block_visit = decode_block_void;
+ td->predict_and_recon_intra_block_visit = decode_block_void;
+ td->read_coeffs_tx_inter_block_visit = decode_block_void;
+ td->inverse_tx_inter_block_visit = decode_block_void;
+ td->predict_inter_block_visit = predict_inter_block_void;
+ td->cfl_store_inter_block_visit = cfl_store_inter_block_void;
+
+ if (parse_decode_flag & 0x1) {
+ td->read_coeffs_tx_intra_block_visit = read_coeffs_tx_intra_block;
+ td->read_coeffs_tx_inter_block_visit = av1_read_coeffs_txb_facade;
+ }
+ if (parse_decode_flag & 0x2) {
+ td->predict_and_recon_intra_block_visit =
+ predict_and_reconstruct_intra_block;
+ td->inverse_tx_inter_block_visit = inverse_transform_inter_block;
+ td->predict_inter_block_visit = predict_inter_block;
+ td->cfl_store_inter_block_visit = cfl_store_inter_block;
+ }
+}
+
+static AOM_INLINE void decode_tile(AV1Decoder *pbi, ThreadData *const td,
+ int tile_row, int tile_col) {
+ TileInfo tile_info;
+
+ AV1_COMMON *const cm = &pbi->common;
+ const int num_planes = av1_num_planes(cm);
+
+ av1_tile_set_row(&tile_info, cm, tile_row);
+ av1_tile_set_col(&tile_info, cm, tile_col);
+ DecoderCodingBlock *const dcb = &td->dcb;
+ MACROBLOCKD *const xd = &dcb->xd;
+
+ av1_zero_above_context(cm, xd, tile_info.mi_col_start, tile_info.mi_col_end,
+ tile_row);
+ av1_reset_loop_filter_delta(xd, num_planes);
+ av1_reset_loop_restoration(xd, num_planes);
+
+ for (int mi_row = tile_info.mi_row_start; mi_row < tile_info.mi_row_end;
+ mi_row += cm->seq_params->mib_size) {
+ av1_zero_left_context(xd);
+
+ for (int mi_col = tile_info.mi_col_start; mi_col < tile_info.mi_col_end;
+ mi_col += cm->seq_params->mib_size) {
+ set_cb_buffer(pbi, dcb, &td->cb_buffer_base, num_planes, 0, 0);
+
+ // Bit-stream parsing and decoding of the superblock
+ decode_partition(pbi, td, mi_row, mi_col, td->bit_reader,
+ cm->seq_params->sb_size, 0x3);
+
+ if (aom_reader_has_overflowed(td->bit_reader)) {
+ aom_merge_corrupted_flag(&dcb->corrupted, 1);
+ return;
+ }
+ }
+ }
+
+ int corrupted =
+ (check_trailing_bits_after_symbol_coder(td->bit_reader)) ? 1 : 0;
+ aom_merge_corrupted_flag(&dcb->corrupted, corrupted);
+}
+
+static const uint8_t *decode_tiles(AV1Decoder *pbi, const uint8_t *data,
+ const uint8_t *data_end, int start_tile,
+ int end_tile) {
+ AV1_COMMON *const cm = &pbi->common;
+ ThreadData *const td = &pbi->td;
+ CommonTileParams *const tiles = &cm->tiles;
+ const int tile_cols = tiles->cols;
+ const int tile_rows = tiles->rows;
+ const int n_tiles = tile_cols * tile_rows;
+ TileBufferDec(*const tile_buffers)[MAX_TILE_COLS] = pbi->tile_buffers;
+ const int dec_tile_row = AOMMIN(pbi->dec_tile_row, tile_rows);
+ const int single_row = pbi->dec_tile_row >= 0;
+ const int dec_tile_col = AOMMIN(pbi->dec_tile_col, tile_cols);
+ const int single_col = pbi->dec_tile_col >= 0;
+ int tile_rows_start;
+ int tile_rows_end;
+ int tile_cols_start;
+ int tile_cols_end;
+ int inv_col_order;
+ int inv_row_order;
+ int tile_row, tile_col;
+ uint8_t allow_update_cdf;
+ const uint8_t *raw_data_end = NULL;
+
+ if (tiles->large_scale) {
+ tile_rows_start = single_row ? dec_tile_row : 0;
+ tile_rows_end = single_row ? dec_tile_row + 1 : tile_rows;
+ tile_cols_start = single_col ? dec_tile_col : 0;
+ tile_cols_end = single_col ? tile_cols_start + 1 : tile_cols;
+ inv_col_order = pbi->inv_tile_order && !single_col;
+ inv_row_order = pbi->inv_tile_order && !single_row;
+ allow_update_cdf = 0;
+ } else {
+ tile_rows_start = 0;
+ tile_rows_end = tile_rows;
+ tile_cols_start = 0;
+ tile_cols_end = tile_cols;
+ inv_col_order = pbi->inv_tile_order;
+ inv_row_order = pbi->inv_tile_order;
+ allow_update_cdf = 1;
+ }
+
+ // No tiles to decode.
+ if (tile_rows_end <= tile_rows_start || tile_cols_end <= tile_cols_start ||
+ // First tile is larger than end_tile.
+ tile_rows_start * tiles->cols + tile_cols_start > end_tile ||
+ // Last tile is smaller than start_tile.
+ (tile_rows_end - 1) * tiles->cols + tile_cols_end - 1 < start_tile)
+ return data;
+
+ allow_update_cdf = allow_update_cdf && !cm->features.disable_cdf_update;
+
+ assert(tile_rows <= MAX_TILE_ROWS);
+ assert(tile_cols <= MAX_TILE_COLS);
+
+#if EXT_TILE_DEBUG
+ if (tiles->large_scale && !pbi->ext_tile_debug)
+ raw_data_end = get_ls_single_tile_buffer(pbi, data, tile_buffers);
+ else if (tiles->large_scale && pbi->ext_tile_debug)
+ raw_data_end = get_ls_tile_buffers(pbi, data, data_end, tile_buffers);
+ else
+#endif // EXT_TILE_DEBUG
+ get_tile_buffers(pbi, data, data_end, tile_buffers, start_tile, end_tile);
+
+ if (pbi->tile_data == NULL || n_tiles != pbi->allocated_tiles) {
+ decoder_alloc_tile_data(pbi, n_tiles);
+ }
+ if (pbi->dcb.xd.seg_mask == NULL)
+ CHECK_MEM_ERROR(cm, pbi->dcb.xd.seg_mask,
+ (uint8_t *)aom_memalign(
+ 16, 2 * MAX_SB_SQUARE * sizeof(*pbi->dcb.xd.seg_mask)));
+#if CONFIG_ACCOUNTING
+ if (pbi->acct_enabled) {
+ aom_accounting_reset(&pbi->accounting);
+ }
+#endif
+
+ set_decode_func_pointers(&pbi->td, 0x3);
+
+ // Load all tile information into thread_data.
+ td->dcb = pbi->dcb;
+
+ td->dcb.corrupted = 0;
+ td->dcb.mc_buf[0] = td->mc_buf[0];
+ td->dcb.mc_buf[1] = td->mc_buf[1];
+ td->dcb.xd.tmp_conv_dst = td->tmp_conv_dst;
+ for (int j = 0; j < 2; ++j) {
+ td->dcb.xd.tmp_obmc_bufs[j] = td->tmp_obmc_bufs[j];
+ }
+
+ for (tile_row = tile_rows_start; tile_row < tile_rows_end; ++tile_row) {
+ const int row = inv_row_order ? tile_rows - 1 - tile_row : tile_row;
+
+ for (tile_col = tile_cols_start; tile_col < tile_cols_end; ++tile_col) {
+ const int col = inv_col_order ? tile_cols - 1 - tile_col : tile_col;
+ TileDataDec *const tile_data = pbi->tile_data + row * tiles->cols + col;
+ const TileBufferDec *const tile_bs_buf = &tile_buffers[row][col];
+
+ if (row * tiles->cols + col < start_tile ||
+ row * tiles->cols + col > end_tile)
+ continue;
+
+ td->bit_reader = &tile_data->bit_reader;
+ av1_zero(td->cb_buffer_base.dqcoeff);
+ av1_tile_init(&td->dcb.xd.tile, cm, row, col);
+ td->dcb.xd.current_base_qindex = cm->quant_params.base_qindex;
+ setup_bool_decoder(&td->dcb.xd, tile_bs_buf->data, data_end,
+ tile_bs_buf->size, &pbi->error, td->bit_reader,
+ allow_update_cdf);
+#if CONFIG_ACCOUNTING
+ if (pbi->acct_enabled) {
+ td->bit_reader->accounting = &pbi->accounting;
+ td->bit_reader->accounting->last_tell_frac =
+ aom_reader_tell_frac(td->bit_reader);
+ } else {
+ td->bit_reader->accounting = NULL;
+ }
+#endif
+ av1_init_macroblockd(cm, &td->dcb.xd);
+ av1_init_above_context(&cm->above_contexts, av1_num_planes(cm), row,
+ &td->dcb.xd);
+
+ // Initialise the tile context from the frame context
+ tile_data->tctx = *cm->fc;
+ td->dcb.xd.tile_ctx = &tile_data->tctx;
+
+ // decode tile
+ decode_tile(pbi, td, row, col);
+ aom_merge_corrupted_flag(&pbi->dcb.corrupted, td->dcb.corrupted);
+ if (pbi->dcb.corrupted)
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "Failed to decode tile data");
+ }
+ }
+
+ if (tiles->large_scale) {
+ if (n_tiles == 1) {
+ // Find the end of the single tile buffer
+ return aom_reader_find_end(&pbi->tile_data->bit_reader);
+ }
+ // Return the end of the last tile buffer
+ return raw_data_end;
+ }
+ TileDataDec *const tile_data = pbi->tile_data + end_tile;
+
+ return aom_reader_find_end(&tile_data->bit_reader);
+}
+
+static TileJobsDec *get_dec_job_info(AV1DecTileMT *tile_mt_info) {
+ TileJobsDec *cur_job_info = NULL;
+#if CONFIG_MULTITHREAD
+ pthread_mutex_lock(tile_mt_info->job_mutex);
+
+ if (tile_mt_info->jobs_dequeued < tile_mt_info->jobs_enqueued) {
+ cur_job_info = tile_mt_info->job_queue + tile_mt_info->jobs_dequeued;
+ tile_mt_info->jobs_dequeued++;
+ }
+
+ pthread_mutex_unlock(tile_mt_info->job_mutex);
+#else
+ (void)tile_mt_info;
+#endif
+ return cur_job_info;
+}
+
+static AOM_INLINE void tile_worker_hook_init(
+ AV1Decoder *const pbi, DecWorkerData *const thread_data,
+ const TileBufferDec *const tile_buffer, TileDataDec *const tile_data,
+ uint8_t allow_update_cdf) {
+ AV1_COMMON *cm = &pbi->common;
+ ThreadData *const td = thread_data->td;
+ int tile_row = tile_data->tile_info.tile_row;
+ int tile_col = tile_data->tile_info.tile_col;
+
+ td->bit_reader = &tile_data->bit_reader;
+ av1_zero(td->cb_buffer_base.dqcoeff);
+
+ MACROBLOCKD *const xd = &td->dcb.xd;
+ av1_tile_init(&xd->tile, cm, tile_row, tile_col);
+ xd->current_base_qindex = cm->quant_params.base_qindex;
+
+ setup_bool_decoder(xd, tile_buffer->data, thread_data->data_end,
+ tile_buffer->size, &thread_data->error_info,
+ td->bit_reader, allow_update_cdf);
+#if CONFIG_ACCOUNTING
+ if (pbi->acct_enabled) {
+ td->bit_reader->accounting = &pbi->accounting;
+ td->bit_reader->accounting->last_tell_frac =
+ aom_reader_tell_frac(td->bit_reader);
+ } else {
+ td->bit_reader->accounting = NULL;
+ }
+#endif
+ av1_init_macroblockd(cm, xd);
+ xd->error_info = &thread_data->error_info;
+ av1_init_above_context(&cm->above_contexts, av1_num_planes(cm), tile_row, xd);
+
+ // Initialise the tile context from the frame context
+ tile_data->tctx = *cm->fc;
+ xd->tile_ctx = &tile_data->tctx;
+#if CONFIG_ACCOUNTING
+ if (pbi->acct_enabled) {
+ tile_data->bit_reader.accounting->last_tell_frac =
+ aom_reader_tell_frac(&tile_data->bit_reader);
+ }
+#endif
+}
+
+static int tile_worker_hook(void *arg1, void *arg2) {
+ DecWorkerData *const thread_data = (DecWorkerData *)arg1;
+ AV1Decoder *const pbi = (AV1Decoder *)arg2;
+ AV1_COMMON *cm = &pbi->common;
+ ThreadData *const td = thread_data->td;
+ uint8_t allow_update_cdf;
+
+ // The jmp_buf is valid only for the duration of the function that calls
+ // setjmp(). Therefore, this function must reset the 'setjmp' field to 0
+ // before it returns.
+ if (setjmp(thread_data->error_info.jmp)) {
+ thread_data->error_info.setjmp = 0;
+ thread_data->td->dcb.corrupted = 1;
+ return 0;
+ }
+ thread_data->error_info.setjmp = 1;
+
+ allow_update_cdf = cm->tiles.large_scale ? 0 : 1;
+ allow_update_cdf = allow_update_cdf && !cm->features.disable_cdf_update;
+
+ set_decode_func_pointers(td, 0x3);
+
+ assert(cm->tiles.cols > 0);
+ while (!td->dcb.corrupted) {
+ TileJobsDec *cur_job_info = get_dec_job_info(&pbi->tile_mt_info);
+
+ if (cur_job_info != NULL) {
+ const TileBufferDec *const tile_buffer = cur_job_info->tile_buffer;
+ TileDataDec *const tile_data = cur_job_info->tile_data;
+ tile_worker_hook_init(pbi, thread_data, tile_buffer, tile_data,
+ allow_update_cdf);
+ // decode tile
+ int tile_row = tile_data->tile_info.tile_row;
+ int tile_col = tile_data->tile_info.tile_col;
+ decode_tile(pbi, td, tile_row, tile_col);
+ } else {
+ break;
+ }
+ }
+ thread_data->error_info.setjmp = 0;
+ return !td->dcb.corrupted;
+}
+
+static INLINE int get_max_row_mt_workers_per_tile(AV1_COMMON *cm,
+ const TileInfo *tile) {
+ // NOTE: Currently value of max workers is calculated based
+ // on the parse and decode time. As per the theoretical estimate
+ // when percentage of parse time is equal to percentage of decode
+ // time, number of workers needed to parse + decode a tile can not
+ // exceed more than 2.
+ // TODO(any): Modify this value if parsing is optimized in future.
+ int sb_rows = av1_get_sb_rows_in_tile(cm, tile);
+ int max_workers =
+ sb_rows == 1 ? AOM_MIN_THREADS_PER_TILE : AOM_MAX_THREADS_PER_TILE;
+ return max_workers;
+}
+
+// The caller must hold pbi->row_mt_mutex_ when calling this function.
+// Returns 1 if either the next job is stored in *next_job_info or 1 is stored
+// in *end_of_frame.
+// NOTE: The caller waits on pbi->row_mt_cond_ if this function returns 0.
+// The return value of this function depends on the following variables:
+// - frame_row_mt_info->mi_rows_parse_done
+// - frame_row_mt_info->mi_rows_decode_started
+// - frame_row_mt_info->row_mt_exit
+// Therefore we may need to signal or broadcast pbi->row_mt_cond_ if any of
+// these variables is modified.
+static int get_next_job_info(AV1Decoder *const pbi,
+ AV1DecRowMTJobInfo *next_job_info,
+ int *end_of_frame) {
+ AV1_COMMON *cm = &pbi->common;
+ TileDataDec *tile_data;
+ AV1DecRowMTSync *dec_row_mt_sync;
+ AV1DecRowMTInfo *frame_row_mt_info = &pbi->frame_row_mt_info;
+ const int tile_rows_start = frame_row_mt_info->tile_rows_start;
+ const int tile_rows_end = frame_row_mt_info->tile_rows_end;
+ const int tile_cols_start = frame_row_mt_info->tile_cols_start;
+ const int tile_cols_end = frame_row_mt_info->tile_cols_end;
+ const int start_tile = frame_row_mt_info->start_tile;
+ const int end_tile = frame_row_mt_info->end_tile;
+ const int sb_mi_size = mi_size_wide[cm->seq_params->sb_size];
+ int num_mis_to_decode, num_threads_working;
+ int num_mis_waiting_for_decode;
+ int min_threads_working = INT_MAX;
+ int max_mis_to_decode = 0;
+ int tile_row_idx, tile_col_idx;
+ int tile_row = -1;
+ int tile_col = -1;
+
+ memset(next_job_info, 0, sizeof(*next_job_info));
+
+ // Frame decode is completed or error is encountered.
+ *end_of_frame = (frame_row_mt_info->mi_rows_decode_started ==
+ frame_row_mt_info->mi_rows_to_decode) ||
+ (frame_row_mt_info->row_mt_exit == 1);
+ if (*end_of_frame) {
+ return 1;
+ }
+
+ // Decoding cannot start as bit-stream parsing is not complete.
+ assert(frame_row_mt_info->mi_rows_parse_done >=
+ frame_row_mt_info->mi_rows_decode_started);
+ if (frame_row_mt_info->mi_rows_parse_done ==
+ frame_row_mt_info->mi_rows_decode_started)
+ return 0;
+
+ // Choose the tile to decode.
+ for (tile_row_idx = tile_rows_start; tile_row_idx < tile_rows_end;
+ ++tile_row_idx) {
+ for (tile_col_idx = tile_cols_start; tile_col_idx < tile_cols_end;
+ ++tile_col_idx) {
+ if (tile_row_idx * cm->tiles.cols + tile_col_idx < start_tile ||
+ tile_row_idx * cm->tiles.cols + tile_col_idx > end_tile)
+ continue;
+
+ tile_data = pbi->tile_data + tile_row_idx * cm->tiles.cols + tile_col_idx;
+ dec_row_mt_sync = &tile_data->dec_row_mt_sync;
+
+ num_threads_working = dec_row_mt_sync->num_threads_working;
+ num_mis_waiting_for_decode = (dec_row_mt_sync->mi_rows_parse_done -
+ dec_row_mt_sync->mi_rows_decode_started) *
+ dec_row_mt_sync->mi_cols;
+ num_mis_to_decode =
+ (dec_row_mt_sync->mi_rows - dec_row_mt_sync->mi_rows_decode_started) *
+ dec_row_mt_sync->mi_cols;
+
+ assert(num_mis_to_decode >= num_mis_waiting_for_decode);
+
+ // Pick the tile which has minimum number of threads working on it.
+ if (num_mis_waiting_for_decode > 0) {
+ if (num_threads_working < min_threads_working) {
+ min_threads_working = num_threads_working;
+ max_mis_to_decode = 0;
+ }
+ if (num_threads_working == min_threads_working &&
+ num_mis_to_decode > max_mis_to_decode &&
+ num_threads_working <
+ get_max_row_mt_workers_per_tile(cm, &tile_data->tile_info)) {
+ max_mis_to_decode = num_mis_to_decode;
+ tile_row = tile_row_idx;
+ tile_col = tile_col_idx;
+ }
+ }
+ }
+ }
+ // No job found to process
+ if (tile_row == -1 || tile_col == -1) return 0;
+
+ tile_data = pbi->tile_data + tile_row * cm->tiles.cols + tile_col;
+ dec_row_mt_sync = &tile_data->dec_row_mt_sync;
+
+ next_job_info->tile_row = tile_row;
+ next_job_info->tile_col = tile_col;
+ next_job_info->mi_row = dec_row_mt_sync->mi_rows_decode_started +
+ tile_data->tile_info.mi_row_start;
+
+ dec_row_mt_sync->num_threads_working++;
+ dec_row_mt_sync->mi_rows_decode_started += sb_mi_size;
+ frame_row_mt_info->mi_rows_decode_started += sb_mi_size;
+ assert(frame_row_mt_info->mi_rows_parse_done >=
+ frame_row_mt_info->mi_rows_decode_started);
+#if CONFIG_MULTITHREAD
+ if (frame_row_mt_info->mi_rows_decode_started ==
+ frame_row_mt_info->mi_rows_to_decode) {
+ pthread_cond_broadcast(pbi->row_mt_cond_);
+ }
+#endif
+
+ return 1;
+}
+
+static INLINE void signal_parse_sb_row_done(AV1Decoder *const pbi,
+ TileDataDec *const tile_data,
+ const int sb_mi_size) {
+ AV1DecRowMTInfo *frame_row_mt_info = &pbi->frame_row_mt_info;
+#if CONFIG_MULTITHREAD
+ pthread_mutex_lock(pbi->row_mt_mutex_);
+#endif
+ assert(frame_row_mt_info->mi_rows_parse_done >=
+ frame_row_mt_info->mi_rows_decode_started);
+ tile_data->dec_row_mt_sync.mi_rows_parse_done += sb_mi_size;
+ frame_row_mt_info->mi_rows_parse_done += sb_mi_size;
+#if CONFIG_MULTITHREAD
+ // A new decode job is available. Wake up one worker thread to handle the
+ // new decode job.
+ // NOTE: This assumes we bump mi_rows_parse_done and mi_rows_decode_started
+ // by the same increment (sb_mi_size).
+ pthread_cond_signal(pbi->row_mt_cond_);
+ pthread_mutex_unlock(pbi->row_mt_mutex_);
+#endif
+}
+
+// This function is very similar to decode_tile(). It would be good to figure
+// out how to share code.
+static AOM_INLINE void parse_tile_row_mt(AV1Decoder *pbi, ThreadData *const td,
+ TileDataDec *const tile_data) {
+ AV1_COMMON *const cm = &pbi->common;
+ const int sb_mi_size = mi_size_wide[cm->seq_params->sb_size];
+ const int num_planes = av1_num_planes(cm);
+ const TileInfo *const tile_info = &tile_data->tile_info;
+ int tile_row = tile_info->tile_row;
+ DecoderCodingBlock *const dcb = &td->dcb;
+ MACROBLOCKD *const xd = &dcb->xd;
+
+ av1_zero_above_context(cm, xd, tile_info->mi_col_start, tile_info->mi_col_end,
+ tile_row);
+ av1_reset_loop_filter_delta(xd, num_planes);
+ av1_reset_loop_restoration(xd, num_planes);
+
+ for (int mi_row = tile_info->mi_row_start; mi_row < tile_info->mi_row_end;
+ mi_row += cm->seq_params->mib_size) {
+ av1_zero_left_context(xd);
+
+ for (int mi_col = tile_info->mi_col_start; mi_col < tile_info->mi_col_end;
+ mi_col += cm->seq_params->mib_size) {
+ set_cb_buffer(pbi, dcb, pbi->cb_buffer_base, num_planes, mi_row, mi_col);
+
+ // Bit-stream parsing of the superblock
+ decode_partition(pbi, td, mi_row, mi_col, td->bit_reader,
+ cm->seq_params->sb_size, 0x1);
+
+ if (aom_reader_has_overflowed(td->bit_reader)) {
+ aom_merge_corrupted_flag(&dcb->corrupted, 1);
+ return;
+ }
+ }
+ signal_parse_sb_row_done(pbi, tile_data, sb_mi_size);
+ }
+
+ int corrupted =
+ (check_trailing_bits_after_symbol_coder(td->bit_reader)) ? 1 : 0;
+ aom_merge_corrupted_flag(&dcb->corrupted, corrupted);
+}
+
+static int row_mt_worker_hook(void *arg1, void *arg2) {
+ DecWorkerData *const thread_data = (DecWorkerData *)arg1;
+ AV1Decoder *const pbi = (AV1Decoder *)arg2;
+ ThreadData *const td = thread_data->td;
+ uint8_t allow_update_cdf;
+ AV1DecRowMTInfo *frame_row_mt_info = &pbi->frame_row_mt_info;
+ td->dcb.corrupted = 0;
+
+ // The jmp_buf is valid only for the duration of the function that calls
+ // setjmp(). Therefore, this function must reset the 'setjmp' field to 0
+ // before it returns.
+ if (setjmp(thread_data->error_info.jmp)) {
+ thread_data->error_info.setjmp = 0;
+ thread_data->td->dcb.corrupted = 1;
+#if CONFIG_MULTITHREAD
+ pthread_mutex_lock(pbi->row_mt_mutex_);
+#endif
+ frame_row_mt_info->row_mt_exit = 1;
+#if CONFIG_MULTITHREAD
+ pthread_cond_broadcast(pbi->row_mt_cond_);
+ pthread_mutex_unlock(pbi->row_mt_mutex_);
+#endif
+ // If any SB row (erroneous row) processed by a thread encounters an
+ // internal error, there is a need to indicate other threads that decoding
+ // of the erroneous row is complete. This ensures that other threads which
+ // wait upon the completion of SB's present in erroneous row are not waiting
+ // indefinitely.
+ signal_decoding_done_for_erroneous_row(pbi, &thread_data->td->dcb.xd);
+ return 0;
+ }
+ thread_data->error_info.setjmp = 1;
+
+ AV1_COMMON *cm = &pbi->common;
+ allow_update_cdf = cm->tiles.large_scale ? 0 : 1;
+ allow_update_cdf = allow_update_cdf && !cm->features.disable_cdf_update;
+
+ set_decode_func_pointers(td, 0x1);
+
+ assert(cm->tiles.cols > 0);
+ while (!td->dcb.corrupted) {
+ TileJobsDec *cur_job_info = get_dec_job_info(&pbi->tile_mt_info);
+
+ if (cur_job_info != NULL) {
+ const TileBufferDec *const tile_buffer = cur_job_info->tile_buffer;
+ TileDataDec *const tile_data = cur_job_info->tile_data;
+ tile_worker_hook_init(pbi, thread_data, tile_buffer, tile_data,
+ allow_update_cdf);
+#if CONFIG_MULTITHREAD
+ pthread_mutex_lock(pbi->row_mt_mutex_);
+#endif
+ tile_data->dec_row_mt_sync.num_threads_working++;
+#if CONFIG_MULTITHREAD
+ pthread_mutex_unlock(pbi->row_mt_mutex_);
+#endif
+ // decode tile
+ parse_tile_row_mt(pbi, td, tile_data);
+#if CONFIG_MULTITHREAD
+ pthread_mutex_lock(pbi->row_mt_mutex_);
+#endif
+ tile_data->dec_row_mt_sync.num_threads_working--;
+#if CONFIG_MULTITHREAD
+ pthread_mutex_unlock(pbi->row_mt_mutex_);
+#endif
+ } else {
+ break;
+ }
+ }
+
+ if (td->dcb.corrupted) {
+ thread_data->error_info.setjmp = 0;
+#if CONFIG_MULTITHREAD
+ pthread_mutex_lock(pbi->row_mt_mutex_);
+#endif
+ frame_row_mt_info->row_mt_exit = 1;
+#if CONFIG_MULTITHREAD
+ pthread_cond_broadcast(pbi->row_mt_cond_);
+ pthread_mutex_unlock(pbi->row_mt_mutex_);
+#endif
+ return 0;
+ }
+
+ set_decode_func_pointers(td, 0x2);
+
+ while (1) {
+ AV1DecRowMTJobInfo next_job_info;
+ int end_of_frame = 0;
+
+#if CONFIG_MULTITHREAD
+ pthread_mutex_lock(pbi->row_mt_mutex_);
+#endif
+ while (!get_next_job_info(pbi, &next_job_info, &end_of_frame)) {
+#if CONFIG_MULTITHREAD
+ pthread_cond_wait(pbi->row_mt_cond_, pbi->row_mt_mutex_);
+#endif
+ }
+#if CONFIG_MULTITHREAD
+ pthread_mutex_unlock(pbi->row_mt_mutex_);
+#endif
+
+ if (end_of_frame) break;
+
+ int tile_row = next_job_info.tile_row;
+ int tile_col = next_job_info.tile_col;
+ int mi_row = next_job_info.mi_row;
+
+ TileDataDec *tile_data =
+ pbi->tile_data + tile_row * cm->tiles.cols + tile_col;
+ AV1DecRowMTSync *dec_row_mt_sync = &tile_data->dec_row_mt_sync;
+
+ av1_tile_init(&td->dcb.xd.tile, cm, tile_row, tile_col);
+ av1_init_macroblockd(cm, &td->dcb.xd);
+ td->dcb.xd.error_info = &thread_data->error_info;
+
+ decode_tile_sb_row(pbi, td, &tile_data->tile_info, mi_row);
+
+#if CONFIG_MULTITHREAD
+ pthread_mutex_lock(pbi->row_mt_mutex_);
+#endif
+ dec_row_mt_sync->num_threads_working--;
+#if CONFIG_MULTITHREAD
+ pthread_mutex_unlock(pbi->row_mt_mutex_);
+#endif
+ }
+ thread_data->error_info.setjmp = 0;
+ return !td->dcb.corrupted;
+}
+
+// sorts in descending order
+static int compare_tile_buffers(const void *a, const void *b) {
+ const TileJobsDec *const buf1 = (const TileJobsDec *)a;
+ const TileJobsDec *const buf2 = (const TileJobsDec *)b;
+ return (((int)buf2->tile_buffer->size) - ((int)buf1->tile_buffer->size));
+}
+
+static AOM_INLINE void enqueue_tile_jobs(AV1Decoder *pbi, AV1_COMMON *cm,
+ int tile_rows_start, int tile_rows_end,
+ int tile_cols_start, int tile_cols_end,
+ int start_tile, int end_tile) {
+ AV1DecTileMT *tile_mt_info = &pbi->tile_mt_info;
+ TileJobsDec *tile_job_queue = tile_mt_info->job_queue;
+ tile_mt_info->jobs_enqueued = 0;
+ tile_mt_info->jobs_dequeued = 0;
+
+ for (int row = tile_rows_start; row < tile_rows_end; row++) {
+ for (int col = tile_cols_start; col < tile_cols_end; col++) {
+ if (row * cm->tiles.cols + col < start_tile ||
+ row * cm->tiles.cols + col > end_tile)
+ continue;
+ tile_job_queue->tile_buffer = &pbi->tile_buffers[row][col];
+ tile_job_queue->tile_data = pbi->tile_data + row * cm->tiles.cols + col;
+ tile_job_queue++;
+ tile_mt_info->jobs_enqueued++;
+ }
+ }
+}
+
+static AOM_INLINE void alloc_dec_jobs(AV1DecTileMT *tile_mt_info,
+ AV1_COMMON *cm, int tile_rows,
+ int tile_cols) {
+ tile_mt_info->alloc_tile_rows = tile_rows;
+ tile_mt_info->alloc_tile_cols = tile_cols;
+ int num_tiles = tile_rows * tile_cols;
+#if CONFIG_MULTITHREAD
+ {
+ CHECK_MEM_ERROR(cm, tile_mt_info->job_mutex,
+ aom_malloc(sizeof(*tile_mt_info->job_mutex) * num_tiles));
+
+ for (int i = 0; i < num_tiles; i++) {
+ pthread_mutex_init(&tile_mt_info->job_mutex[i], NULL);
+ }
+ }
+#endif
+ CHECK_MEM_ERROR(cm, tile_mt_info->job_queue,
+ aom_malloc(sizeof(*tile_mt_info->job_queue) * num_tiles));
+}
+
+void av1_free_mc_tmp_buf(ThreadData *thread_data) {
+ int ref;
+ for (ref = 0; ref < 2; ref++) {
+ if (thread_data->mc_buf_use_highbd)
+ aom_free(CONVERT_TO_SHORTPTR(thread_data->mc_buf[ref]));
+ else
+ aom_free(thread_data->mc_buf[ref]);
+ thread_data->mc_buf[ref] = NULL;
+ }
+ thread_data->mc_buf_size = 0;
+ thread_data->mc_buf_use_highbd = 0;
+
+ aom_free(thread_data->tmp_conv_dst);
+ thread_data->tmp_conv_dst = NULL;
+ aom_free(thread_data->seg_mask);
+ thread_data->seg_mask = NULL;
+ for (int i = 0; i < 2; ++i) {
+ aom_free(thread_data->tmp_obmc_bufs[i]);
+ thread_data->tmp_obmc_bufs[i] = NULL;
+ }
+}
+
+static AOM_INLINE void allocate_mc_tmp_buf(AV1_COMMON *const cm,
+ ThreadData *thread_data,
+ int buf_size, int use_highbd) {
+ for (int ref = 0; ref < 2; ref++) {
+ // The mc_buf/hbd_mc_buf must be zeroed to fix a intermittent valgrind error
+ // 'Conditional jump or move depends on uninitialised value' from the loop
+ // filter. Uninitialized reads in convolve function (e.g. horiz_4tap path in
+ // av1_convolve_2d_sr_avx2()) from mc_buf/hbd_mc_buf are seen to be the
+ // potential reason for this issue.
+ if (use_highbd) {
+ uint16_t *hbd_mc_buf;
+ CHECK_MEM_ERROR(cm, hbd_mc_buf, (uint16_t *)aom_memalign(16, buf_size));
+ memset(hbd_mc_buf, 0, buf_size);
+ thread_data->mc_buf[ref] = CONVERT_TO_BYTEPTR(hbd_mc_buf);
+ } else {
+ CHECK_MEM_ERROR(cm, thread_data->mc_buf[ref],
+ (uint8_t *)aom_memalign(16, buf_size));
+ memset(thread_data->mc_buf[ref], 0, buf_size);
+ }
+ }
+ thread_data->mc_buf_size = buf_size;
+ thread_data->mc_buf_use_highbd = use_highbd;
+
+ CHECK_MEM_ERROR(cm, thread_data->tmp_conv_dst,
+ aom_memalign(32, MAX_SB_SIZE * MAX_SB_SIZE *
+ sizeof(*thread_data->tmp_conv_dst)));
+ CHECK_MEM_ERROR(cm, thread_data->seg_mask,
+ (uint8_t *)aom_memalign(
+ 16, 2 * MAX_SB_SQUARE * sizeof(*thread_data->seg_mask)));
+
+ for (int i = 0; i < 2; ++i) {
+ CHECK_MEM_ERROR(
+ cm, thread_data->tmp_obmc_bufs[i],
+ aom_memalign(16, 2 * MAX_MB_PLANE * MAX_SB_SQUARE *
+ sizeof(*thread_data->tmp_obmc_bufs[i])));
+ }
+}
+
+static AOM_INLINE void reset_dec_workers(AV1Decoder *pbi,
+ AVxWorkerHook worker_hook,
+ int num_workers) {
+ const AVxWorkerInterface *const winterface = aom_get_worker_interface();
+
+ // Reset tile decoding hook
+ for (int worker_idx = 0; worker_idx < num_workers; ++worker_idx) {
+ AVxWorker *const worker = &pbi->tile_workers[worker_idx];
+ DecWorkerData *const thread_data = pbi->thread_data + worker_idx;
+ thread_data->td->dcb = pbi->dcb;
+ thread_data->td->dcb.corrupted = 0;
+ thread_data->td->dcb.mc_buf[0] = thread_data->td->mc_buf[0];
+ thread_data->td->dcb.mc_buf[1] = thread_data->td->mc_buf[1];
+ thread_data->td->dcb.xd.tmp_conv_dst = thread_data->td->tmp_conv_dst;
+ if (worker_idx)
+ thread_data->td->dcb.xd.seg_mask = thread_data->td->seg_mask;
+ for (int j = 0; j < 2; ++j) {
+ thread_data->td->dcb.xd.tmp_obmc_bufs[j] =
+ thread_data->td->tmp_obmc_bufs[j];
+ }
+ winterface->sync(worker);
+
+ worker->hook = worker_hook;
+ worker->data1 = thread_data;
+ worker->data2 = pbi;
+ }
+#if CONFIG_ACCOUNTING
+ if (pbi->acct_enabled) {
+ aom_accounting_reset(&pbi->accounting);
+ }
+#endif
+}
+
+static AOM_INLINE void launch_dec_workers(AV1Decoder *pbi,
+ const uint8_t *data_end,
+ int num_workers) {
+ const AVxWorkerInterface *const winterface = aom_get_worker_interface();
+
+ for (int worker_idx = num_workers - 1; worker_idx >= 0; --worker_idx) {
+ AVxWorker *const worker = &pbi->tile_workers[worker_idx];
+ DecWorkerData *const thread_data = (DecWorkerData *)worker->data1;
+
+ thread_data->data_end = data_end;
+
+ worker->had_error = 0;
+ if (worker_idx == 0) {
+ winterface->execute(worker);
+ } else {
+ winterface->launch(worker);
+ }
+ }
+}
+
+static AOM_INLINE void sync_dec_workers(AV1Decoder *pbi, int num_workers) {
+ const AVxWorkerInterface *const winterface = aom_get_worker_interface();
+ int corrupted = 0;
+
+ for (int worker_idx = num_workers; worker_idx > 0; --worker_idx) {
+ AVxWorker *const worker = &pbi->tile_workers[worker_idx - 1];
+ aom_merge_corrupted_flag(&corrupted, !winterface->sync(worker));
+ }
+
+ pbi->dcb.corrupted = corrupted;
+}
+
+static AOM_INLINE void decode_mt_init(AV1Decoder *pbi) {
+ AV1_COMMON *const cm = &pbi->common;
+ const AVxWorkerInterface *const winterface = aom_get_worker_interface();
+ int worker_idx;
+
+ // Create workers and thread_data
+ if (pbi->num_workers == 0) {
+ const int num_threads = pbi->max_threads;
+ CHECK_MEM_ERROR(cm, pbi->tile_workers,
+ aom_malloc(num_threads * sizeof(*pbi->tile_workers)));
+ CHECK_MEM_ERROR(cm, pbi->thread_data,
+ aom_calloc(num_threads, sizeof(*pbi->thread_data)));
+
+ for (worker_idx = 0; worker_idx < num_threads; ++worker_idx) {
+ AVxWorker *const worker = &pbi->tile_workers[worker_idx];
+ DecWorkerData *const thread_data = pbi->thread_data + worker_idx;
+
+ winterface->init(worker);
+ worker->thread_name = "aom tile worker";
+ if (worker_idx != 0 && !winterface->reset(worker)) {
+ aom_internal_error(&pbi->error, AOM_CODEC_ERROR,
+ "Tile decoder thread creation failed");
+ }
+ ++pbi->num_workers;
+
+ if (worker_idx != 0) {
+ // Allocate thread data.
+ CHECK_MEM_ERROR(cm, thread_data->td,
+ aom_memalign(32, sizeof(*thread_data->td)));
+ av1_zero(*thread_data->td);
+ } else {
+ // Main thread acts as a worker and uses the thread data in pbi
+ thread_data->td = &pbi->td;
+ }
+ thread_data->error_info.error_code = AOM_CODEC_OK;
+ thread_data->error_info.setjmp = 0;
+ }
+ }
+ const int use_highbd = cm->seq_params->use_highbitdepth;
+ const int buf_size = MC_TEMP_BUF_PELS << use_highbd;
+ for (worker_idx = 1; worker_idx < pbi->max_threads; ++worker_idx) {
+ DecWorkerData *const thread_data = pbi->thread_data + worker_idx;
+ if (thread_data->td->mc_buf_size != buf_size) {
+ av1_free_mc_tmp_buf(thread_data->td);
+ allocate_mc_tmp_buf(cm, thread_data->td, buf_size, use_highbd);
+ }
+ }
+}
+
+static AOM_INLINE void tile_mt_queue(AV1Decoder *pbi, int tile_cols,
+ int tile_rows, int tile_rows_start,
+ int tile_rows_end, int tile_cols_start,
+ int tile_cols_end, int start_tile,
+ int end_tile) {
+ AV1_COMMON *const cm = &pbi->common;
+ if (pbi->tile_mt_info.alloc_tile_cols != tile_cols ||
+ pbi->tile_mt_info.alloc_tile_rows != tile_rows) {
+ av1_dealloc_dec_jobs(&pbi->tile_mt_info);
+ alloc_dec_jobs(&pbi->tile_mt_info, cm, tile_rows, tile_cols);
+ }
+ enqueue_tile_jobs(pbi, cm, tile_rows_start, tile_rows_end, tile_cols_start,
+ tile_cols_end, start_tile, end_tile);
+ qsort(pbi->tile_mt_info.job_queue, pbi->tile_mt_info.jobs_enqueued,
+ sizeof(pbi->tile_mt_info.job_queue[0]), compare_tile_buffers);
+}
+
+static const uint8_t *decode_tiles_mt(AV1Decoder *pbi, const uint8_t *data,
+ const uint8_t *data_end, int start_tile,
+ int end_tile) {
+ AV1_COMMON *const cm = &pbi->common;
+ CommonTileParams *const tiles = &cm->tiles;
+ const int tile_cols = tiles->cols;
+ const int tile_rows = tiles->rows;
+ const int n_tiles = tile_cols * tile_rows;
+ TileBufferDec(*const tile_buffers)[MAX_TILE_COLS] = pbi->tile_buffers;
+ const int dec_tile_row = AOMMIN(pbi->dec_tile_row, tile_rows);
+ const int single_row = pbi->dec_tile_row >= 0;
+ const int dec_tile_col = AOMMIN(pbi->dec_tile_col, tile_cols);
+ const int single_col = pbi->dec_tile_col >= 0;
+ int tile_rows_start;
+ int tile_rows_end;
+ int tile_cols_start;
+ int tile_cols_end;
+ int tile_count_tg;
+ int num_workers;
+ const uint8_t *raw_data_end = NULL;
+
+ if (tiles->large_scale) {
+ tile_rows_start = single_row ? dec_tile_row : 0;
+ tile_rows_end = single_row ? dec_tile_row + 1 : tile_rows;
+ tile_cols_start = single_col ? dec_tile_col : 0;
+ tile_cols_end = single_col ? tile_cols_start + 1 : tile_cols;
+ } else {
+ tile_rows_start = 0;
+ tile_rows_end = tile_rows;
+ tile_cols_start = 0;
+ tile_cols_end = tile_cols;
+ }
+ tile_count_tg = end_tile - start_tile + 1;
+ num_workers = AOMMIN(pbi->max_threads, tile_count_tg);
+
+ // No tiles to decode.
+ if (tile_rows_end <= tile_rows_start || tile_cols_end <= tile_cols_start ||
+ // First tile is larger than end_tile.
+ tile_rows_start * tile_cols + tile_cols_start > end_tile ||
+ // Last tile is smaller than start_tile.
+ (tile_rows_end - 1) * tile_cols + tile_cols_end - 1 < start_tile)
+ return data;
+
+ assert(tile_rows <= MAX_TILE_ROWS);
+ assert(tile_cols <= MAX_TILE_COLS);
+ assert(tile_count_tg > 0);
+ assert(num_workers > 0);
+ assert(start_tile <= end_tile);
+ assert(start_tile >= 0 && end_tile < n_tiles);
+
+ decode_mt_init(pbi);
+
+ // get tile size in tile group
+#if EXT_TILE_DEBUG
+ if (tiles->large_scale) assert(pbi->ext_tile_debug == 1);
+ if (tiles->large_scale)
+ raw_data_end = get_ls_tile_buffers(pbi, data, data_end, tile_buffers);
+ else
+#endif // EXT_TILE_DEBUG
+ get_tile_buffers(pbi, data, data_end, tile_buffers, start_tile, end_tile);
+
+ if (pbi->tile_data == NULL || n_tiles != pbi->allocated_tiles) {
+ decoder_alloc_tile_data(pbi, n_tiles);
+ }
+ if (pbi->dcb.xd.seg_mask == NULL)
+ CHECK_MEM_ERROR(cm, pbi->dcb.xd.seg_mask,
+ (uint8_t *)aom_memalign(
+ 16, 2 * MAX_SB_SQUARE * sizeof(*pbi->dcb.xd.seg_mask)));
+
+ for (int row = 0; row < tile_rows; row++) {
+ for (int col = 0; col < tile_cols; col++) {
+ TileDataDec *tile_data = pbi->tile_data + row * tiles->cols + col;
+ av1_tile_init(&tile_data->tile_info, cm, row, col);
+ }
+ }
+
+ tile_mt_queue(pbi, tile_cols, tile_rows, tile_rows_start, tile_rows_end,
+ tile_cols_start, tile_cols_end, start_tile, end_tile);
+
+ reset_dec_workers(pbi, tile_worker_hook, num_workers);
+ launch_dec_workers(pbi, data_end, num_workers);
+ sync_dec_workers(pbi, num_workers);
+
+ if (pbi->dcb.corrupted)
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "Failed to decode tile data");
+
+ if (tiles->large_scale) {
+ if (n_tiles == 1) {
+ // Find the end of the single tile buffer
+ return aom_reader_find_end(&pbi->tile_data->bit_reader);
+ }
+ // Return the end of the last tile buffer
+ return raw_data_end;
+ }
+ TileDataDec *const tile_data = pbi->tile_data + end_tile;
+
+ return aom_reader_find_end(&tile_data->bit_reader);
+}
+
+static AOM_INLINE void dec_alloc_cb_buf(AV1Decoder *pbi) {
+ AV1_COMMON *const cm = &pbi->common;
+ int size = ((cm->mi_params.mi_rows >> cm->seq_params->mib_size_log2) + 1) *
+ ((cm->mi_params.mi_cols >> cm->seq_params->mib_size_log2) + 1);
+
+ if (pbi->cb_buffer_alloc_size < size) {
+ av1_dec_free_cb_buf(pbi);
+ CHECK_MEM_ERROR(cm, pbi->cb_buffer_base,
+ aom_memalign(32, sizeof(*pbi->cb_buffer_base) * size));
+ memset(pbi->cb_buffer_base, 0, sizeof(*pbi->cb_buffer_base) * size);
+ pbi->cb_buffer_alloc_size = size;
+ }
+}
+
+static AOM_INLINE void row_mt_frame_init(AV1Decoder *pbi, int tile_rows_start,
+ int tile_rows_end, int tile_cols_start,
+ int tile_cols_end, int start_tile,
+ int end_tile, int max_sb_rows) {
+ AV1_COMMON *const cm = &pbi->common;
+ AV1DecRowMTInfo *frame_row_mt_info = &pbi->frame_row_mt_info;
+
+ frame_row_mt_info->tile_rows_start = tile_rows_start;
+ frame_row_mt_info->tile_rows_end = tile_rows_end;
+ frame_row_mt_info->tile_cols_start = tile_cols_start;
+ frame_row_mt_info->tile_cols_end = tile_cols_end;
+ frame_row_mt_info->start_tile = start_tile;
+ frame_row_mt_info->end_tile = end_tile;
+ frame_row_mt_info->mi_rows_to_decode = 0;
+ frame_row_mt_info->mi_rows_parse_done = 0;
+ frame_row_mt_info->mi_rows_decode_started = 0;
+ frame_row_mt_info->row_mt_exit = 0;
+
+ for (int tile_row = tile_rows_start; tile_row < tile_rows_end; ++tile_row) {
+ for (int tile_col = tile_cols_start; tile_col < tile_cols_end; ++tile_col) {
+ if (tile_row * cm->tiles.cols + tile_col < start_tile ||
+ tile_row * cm->tiles.cols + tile_col > end_tile)
+ continue;
+
+ TileDataDec *const tile_data =
+ pbi->tile_data + tile_row * cm->tiles.cols + tile_col;
+ const TileInfo *const tile_info = &tile_data->tile_info;
+
+ tile_data->dec_row_mt_sync.mi_rows_parse_done = 0;
+ tile_data->dec_row_mt_sync.mi_rows_decode_started = 0;
+ tile_data->dec_row_mt_sync.num_threads_working = 0;
+ tile_data->dec_row_mt_sync.mi_rows =
+ ALIGN_POWER_OF_TWO(tile_info->mi_row_end - tile_info->mi_row_start,
+ cm->seq_params->mib_size_log2);
+ tile_data->dec_row_mt_sync.mi_cols =
+ ALIGN_POWER_OF_TWO(tile_info->mi_col_end - tile_info->mi_col_start,
+ cm->seq_params->mib_size_log2);
+ tile_data->dec_row_mt_sync.intrabc_extra_top_right_sb_delay =
+ av1_get_intrabc_extra_top_right_sb_delay(cm);
+
+ frame_row_mt_info->mi_rows_to_decode +=
+ tile_data->dec_row_mt_sync.mi_rows;
+
+ // Initialize cur_sb_col to -1 for all SB rows.
+ memset(tile_data->dec_row_mt_sync.cur_sb_col, -1,
+ sizeof(*tile_data->dec_row_mt_sync.cur_sb_col) * max_sb_rows);
+ }
+ }
+
+#if CONFIG_MULTITHREAD
+ if (pbi->row_mt_mutex_ == NULL) {
+ CHECK_MEM_ERROR(cm, pbi->row_mt_mutex_,
+ aom_malloc(sizeof(*(pbi->row_mt_mutex_))));
+ if (pbi->row_mt_mutex_) {
+ pthread_mutex_init(pbi->row_mt_mutex_, NULL);
+ }
+ }
+
+ if (pbi->row_mt_cond_ == NULL) {
+ CHECK_MEM_ERROR(cm, pbi->row_mt_cond_,
+ aom_malloc(sizeof(*(pbi->row_mt_cond_))));
+ if (pbi->row_mt_cond_) {
+ pthread_cond_init(pbi->row_mt_cond_, NULL);
+ }
+ }
+#endif
+}
+
+static const uint8_t *decode_tiles_row_mt(AV1Decoder *pbi, const uint8_t *data,
+ const uint8_t *data_end,
+ int start_tile, int end_tile) {
+ AV1_COMMON *const cm = &pbi->common;
+ CommonTileParams *const tiles = &cm->tiles;
+ const int tile_cols = tiles->cols;
+ const int tile_rows = tiles->rows;
+ const int n_tiles = tile_cols * tile_rows;
+ TileBufferDec(*const tile_buffers)[MAX_TILE_COLS] = pbi->tile_buffers;
+ const int dec_tile_row = AOMMIN(pbi->dec_tile_row, tile_rows);
+ const int single_row = pbi->dec_tile_row >= 0;
+ const int dec_tile_col = AOMMIN(pbi->dec_tile_col, tile_cols);
+ const int single_col = pbi->dec_tile_col >= 0;
+ int tile_rows_start;
+ int tile_rows_end;
+ int tile_cols_start;
+ int tile_cols_end;
+ int tile_count_tg;
+ int num_workers = 0;
+ int max_threads;
+ const uint8_t *raw_data_end = NULL;
+ int max_sb_rows = 0;
+
+ if (tiles->large_scale) {
+ tile_rows_start = single_row ? dec_tile_row : 0;
+ tile_rows_end = single_row ? dec_tile_row + 1 : tile_rows;
+ tile_cols_start = single_col ? dec_tile_col : 0;
+ tile_cols_end = single_col ? tile_cols_start + 1 : tile_cols;
+ } else {
+ tile_rows_start = 0;
+ tile_rows_end = tile_rows;
+ tile_cols_start = 0;
+ tile_cols_end = tile_cols;
+ }
+ tile_count_tg = end_tile - start_tile + 1;
+ max_threads = pbi->max_threads;
+
+ // No tiles to decode.
+ if (tile_rows_end <= tile_rows_start || tile_cols_end <= tile_cols_start ||
+ // First tile is larger than end_tile.
+ tile_rows_start * tile_cols + tile_cols_start > end_tile ||
+ // Last tile is smaller than start_tile.
+ (tile_rows_end - 1) * tile_cols + tile_cols_end - 1 < start_tile)
+ return data;
+
+ assert(tile_rows <= MAX_TILE_ROWS);
+ assert(tile_cols <= MAX_TILE_COLS);
+ assert(tile_count_tg > 0);
+ assert(max_threads > 0);
+ assert(start_tile <= end_tile);
+ assert(start_tile >= 0 && end_tile < n_tiles);
+
+ (void)tile_count_tg;
+
+ decode_mt_init(pbi);
+
+ // get tile size in tile group
+#if EXT_TILE_DEBUG
+ if (tiles->large_scale) assert(pbi->ext_tile_debug == 1);
+ if (tiles->large_scale)
+ raw_data_end = get_ls_tile_buffers(pbi, data, data_end, tile_buffers);
+ else
+#endif // EXT_TILE_DEBUG
+ get_tile_buffers(pbi, data, data_end, tile_buffers, start_tile, end_tile);
+
+ if (pbi->tile_data == NULL || n_tiles != pbi->allocated_tiles) {
+ if (pbi->tile_data != NULL) {
+ for (int i = 0; i < pbi->allocated_tiles; i++) {
+ TileDataDec *const tile_data = pbi->tile_data + i;
+ av1_dec_row_mt_dealloc(&tile_data->dec_row_mt_sync);
+ }
+ }
+ decoder_alloc_tile_data(pbi, n_tiles);
+ }
+ if (pbi->dcb.xd.seg_mask == NULL)
+ CHECK_MEM_ERROR(cm, pbi->dcb.xd.seg_mask,
+ (uint8_t *)aom_memalign(
+ 16, 2 * MAX_SB_SQUARE * sizeof(*pbi->dcb.xd.seg_mask)));
+
+ for (int row = 0; row < tile_rows; row++) {
+ for (int col = 0; col < tile_cols; col++) {
+ TileDataDec *tile_data = pbi->tile_data + row * tiles->cols + col;
+ av1_tile_init(&tile_data->tile_info, cm, row, col);
+
+ max_sb_rows = AOMMAX(max_sb_rows,
+ av1_get_sb_rows_in_tile(cm, &tile_data->tile_info));
+ num_workers += get_max_row_mt_workers_per_tile(cm, &tile_data->tile_info);
+ }
+ }
+ num_workers = AOMMIN(num_workers, max_threads);
+
+ if (pbi->allocated_row_mt_sync_rows != max_sb_rows) {
+ for (int i = 0; i < n_tiles; ++i) {
+ TileDataDec *const tile_data = pbi->tile_data + i;
+ av1_dec_row_mt_dealloc(&tile_data->dec_row_mt_sync);
+ dec_row_mt_alloc(&tile_data->dec_row_mt_sync, cm, max_sb_rows);
+ }
+ pbi->allocated_row_mt_sync_rows = max_sb_rows;
+ }
+
+ tile_mt_queue(pbi, tile_cols, tile_rows, tile_rows_start, tile_rows_end,
+ tile_cols_start, tile_cols_end, start_tile, end_tile);
+
+ dec_alloc_cb_buf(pbi);
+
+ row_mt_frame_init(pbi, tile_rows_start, tile_rows_end, tile_cols_start,
+ tile_cols_end, start_tile, end_tile, max_sb_rows);
+
+ reset_dec_workers(pbi, row_mt_worker_hook, num_workers);
+ launch_dec_workers(pbi, data_end, num_workers);
+ sync_dec_workers(pbi, num_workers);
+
+ if (pbi->dcb.corrupted)
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "Failed to decode tile data");
+
+ if (tiles->large_scale) {
+ if (n_tiles == 1) {
+ // Find the end of the single tile buffer
+ return aom_reader_find_end(&pbi->tile_data->bit_reader);
+ }
+ // Return the end of the last tile buffer
+ return raw_data_end;
+ }
+ TileDataDec *const tile_data = pbi->tile_data + end_tile;
+
+ return aom_reader_find_end(&tile_data->bit_reader);
+}
+
+static AOM_INLINE void error_handler(void *data) {
+ AV1_COMMON *const cm = (AV1_COMMON *)data;
+ aom_internal_error(cm->error, AOM_CODEC_CORRUPT_FRAME, "Truncated packet");
+}
+
+// Reads the high_bitdepth and twelve_bit fields in color_config() and sets
+// seq_params->bit_depth based on the values of those fields and
+// seq_params->profile. Reports errors by calling rb->error_handler() or
+// aom_internal_error().
+static AOM_INLINE void read_bitdepth(
+ struct aom_read_bit_buffer *rb, SequenceHeader *seq_params,
+ struct aom_internal_error_info *error_info) {
+ const int high_bitdepth = aom_rb_read_bit(rb);
+ if (seq_params->profile == PROFILE_2 && high_bitdepth) {
+ const int twelve_bit = aom_rb_read_bit(rb);
+ seq_params->bit_depth = twelve_bit ? AOM_BITS_12 : AOM_BITS_10;
+ } else if (seq_params->profile <= PROFILE_2) {
+ seq_params->bit_depth = high_bitdepth ? AOM_BITS_10 : AOM_BITS_8;
+ } else {
+ aom_internal_error(error_info, AOM_CODEC_UNSUP_BITSTREAM,
+ "Unsupported profile/bit-depth combination");
+ }
+#if !CONFIG_AV1_HIGHBITDEPTH
+ if (seq_params->bit_depth > AOM_BITS_8) {
+ aom_internal_error(error_info, AOM_CODEC_UNSUP_BITSTREAM,
+ "Bit-depth %d not supported", seq_params->bit_depth);
+ }
+#endif
+}
+
+void av1_read_film_grain_params(AV1_COMMON *cm,
+ struct aom_read_bit_buffer *rb) {
+ aom_film_grain_t *pars = &cm->film_grain_params;
+ const SequenceHeader *const seq_params = cm->seq_params;
+
+ pars->apply_grain = aom_rb_read_bit(rb);
+ if (!pars->apply_grain) {
+ memset(pars, 0, sizeof(*pars));
+ return;
+ }
+
+ pars->random_seed = aom_rb_read_literal(rb, 16);
+ if (cm->current_frame.frame_type == INTER_FRAME)
+ pars->update_parameters = aom_rb_read_bit(rb);
+ else
+ pars->update_parameters = 1;
+
+ pars->bit_depth = seq_params->bit_depth;
+
+ if (!pars->update_parameters) {
+ // inherit parameters from a previous reference frame
+ int film_grain_params_ref_idx = aom_rb_read_literal(rb, 3);
+ // Section 6.8.20: It is a requirement of bitstream conformance that
+ // film_grain_params_ref_idx is equal to ref_frame_idx[ j ] for some value
+ // of j in the range 0 to REFS_PER_FRAME - 1.
+ int found = 0;
+ for (int i = 0; i < INTER_REFS_PER_FRAME; ++i) {
+ if (film_grain_params_ref_idx == cm->remapped_ref_idx[i]) {
+ found = 1;
+ break;
+ }
+ }
+ if (!found) {
+ aom_internal_error(cm->error, AOM_CODEC_UNSUP_BITSTREAM,
+ "Invalid film grain reference idx %d. ref_frame_idx = "
+ "{%d, %d, %d, %d, %d, %d, %d}",
+ film_grain_params_ref_idx, cm->remapped_ref_idx[0],
+ cm->remapped_ref_idx[1], cm->remapped_ref_idx[2],
+ cm->remapped_ref_idx[3], cm->remapped_ref_idx[4],
+ cm->remapped_ref_idx[5], cm->remapped_ref_idx[6]);
+ }
+ RefCntBuffer *const buf = cm->ref_frame_map[film_grain_params_ref_idx];
+ if (buf == NULL) {
+ aom_internal_error(cm->error, AOM_CODEC_UNSUP_BITSTREAM,
+ "Invalid Film grain reference idx");
+ }
+ if (!buf->film_grain_params_present) {
+ aom_internal_error(cm->error, AOM_CODEC_UNSUP_BITSTREAM,
+ "Film grain reference parameters not available");
+ }
+ uint16_t random_seed = pars->random_seed;
+ *pars = buf->film_grain_params; // inherit paramaters
+ pars->random_seed = random_seed; // with new random seed
+ return;
+ }
+
+ // Scaling functions parameters
+ pars->num_y_points = aom_rb_read_literal(rb, 4); // max 14
+ if (pars->num_y_points > 14)
+ aom_internal_error(cm->error, AOM_CODEC_UNSUP_BITSTREAM,
+ "Number of points for film grain luma scaling function "
+ "exceeds the maximum value.");
+ for (int i = 0; i < pars->num_y_points; i++) {
+ pars->scaling_points_y[i][0] = aom_rb_read_literal(rb, 8);
+ if (i && pars->scaling_points_y[i - 1][0] >= pars->scaling_points_y[i][0])
+ aom_internal_error(cm->error, AOM_CODEC_UNSUP_BITSTREAM,
+ "First coordinate of the scaling function points "
+ "shall be increasing.");
+ pars->scaling_points_y[i][1] = aom_rb_read_literal(rb, 8);
+ }
+
+ if (!seq_params->monochrome)
+ pars->chroma_scaling_from_luma = aom_rb_read_bit(rb);
+ else
+ pars->chroma_scaling_from_luma = 0;
+
+ if (seq_params->monochrome || pars->chroma_scaling_from_luma ||
+ ((seq_params->subsampling_x == 1) && (seq_params->subsampling_y == 1) &&
+ (pars->num_y_points == 0))) {
+ pars->num_cb_points = 0;
+ pars->num_cr_points = 0;
+ } else {
+ pars->num_cb_points = aom_rb_read_literal(rb, 4); // max 10
+ if (pars->num_cb_points > 10)
+ aom_internal_error(cm->error, AOM_CODEC_UNSUP_BITSTREAM,
+ "Number of points for film grain cb scaling function "
+ "exceeds the maximum value.");
+ for (int i = 0; i < pars->num_cb_points; i++) {
+ pars->scaling_points_cb[i][0] = aom_rb_read_literal(rb, 8);
+ if (i &&
+ pars->scaling_points_cb[i - 1][0] >= pars->scaling_points_cb[i][0])
+ aom_internal_error(cm->error, AOM_CODEC_UNSUP_BITSTREAM,
+ "First coordinate of the scaling function points "
+ "shall be increasing.");
+ pars->scaling_points_cb[i][1] = aom_rb_read_literal(rb, 8);
+ }
+
+ pars->num_cr_points = aom_rb_read_literal(rb, 4); // max 10
+ if (pars->num_cr_points > 10)
+ aom_internal_error(cm->error, AOM_CODEC_UNSUP_BITSTREAM,
+ "Number of points for film grain cr scaling function "
+ "exceeds the maximum value.");
+ for (int i = 0; i < pars->num_cr_points; i++) {
+ pars->scaling_points_cr[i][0] = aom_rb_read_literal(rb, 8);
+ if (i &&
+ pars->scaling_points_cr[i - 1][0] >= pars->scaling_points_cr[i][0])
+ aom_internal_error(cm->error, AOM_CODEC_UNSUP_BITSTREAM,
+ "First coordinate of the scaling function points "
+ "shall be increasing.");
+ pars->scaling_points_cr[i][1] = aom_rb_read_literal(rb, 8);
+ }
+
+ if ((seq_params->subsampling_x == 1) && (seq_params->subsampling_y == 1) &&
+ (((pars->num_cb_points == 0) && (pars->num_cr_points != 0)) ||
+ ((pars->num_cb_points != 0) && (pars->num_cr_points == 0))))
+ aom_internal_error(cm->error, AOM_CODEC_UNSUP_BITSTREAM,
+ "In YCbCr 4:2:0, film grain shall be applied "
+ "to both chroma components or neither.");
+ }
+
+ pars->scaling_shift = aom_rb_read_literal(rb, 2) + 8; // 8 + value
+
+ // AR coefficients
+ // Only sent if the corresponsing scaling function has
+ // more than 0 points
+
+ pars->ar_coeff_lag = aom_rb_read_literal(rb, 2);
+
+ int num_pos_luma = 2 * pars->ar_coeff_lag * (pars->ar_coeff_lag + 1);
+ int num_pos_chroma = num_pos_luma;
+ if (pars->num_y_points > 0) ++num_pos_chroma;
+
+ if (pars->num_y_points)
+ for (int i = 0; i < num_pos_luma; i++)
+ pars->ar_coeffs_y[i] = aom_rb_read_literal(rb, 8) - 128;
+
+ if (pars->num_cb_points || pars->chroma_scaling_from_luma)
+ for (int i = 0; i < num_pos_chroma; i++)
+ pars->ar_coeffs_cb[i] = aom_rb_read_literal(rb, 8) - 128;
+
+ if (pars->num_cr_points || pars->chroma_scaling_from_luma)
+ for (int i = 0; i < num_pos_chroma; i++)
+ pars->ar_coeffs_cr[i] = aom_rb_read_literal(rb, 8) - 128;
+
+ pars->ar_coeff_shift = aom_rb_read_literal(rb, 2) + 6; // 6 + value
+
+ pars->grain_scale_shift = aom_rb_read_literal(rb, 2);
+
+ if (pars->num_cb_points) {
+ pars->cb_mult = aom_rb_read_literal(rb, 8);
+ pars->cb_luma_mult = aom_rb_read_literal(rb, 8);
+ pars->cb_offset = aom_rb_read_literal(rb, 9);
+ }
+
+ if (pars->num_cr_points) {
+ pars->cr_mult = aom_rb_read_literal(rb, 8);
+ pars->cr_luma_mult = aom_rb_read_literal(rb, 8);
+ pars->cr_offset = aom_rb_read_literal(rb, 9);
+ }
+
+ pars->overlap_flag = aom_rb_read_bit(rb);
+
+ pars->clip_to_restricted_range = aom_rb_read_bit(rb);
+}
+
+static AOM_INLINE void read_film_grain(AV1_COMMON *cm,
+ struct aom_read_bit_buffer *rb) {
+ if (cm->seq_params->film_grain_params_present &&
+ (cm->show_frame || cm->showable_frame)) {
+ av1_read_film_grain_params(cm, rb);
+ } else {
+ memset(&cm->film_grain_params, 0, sizeof(cm->film_grain_params));
+ }
+ cm->film_grain_params.bit_depth = cm->seq_params->bit_depth;
+ memcpy(&cm->cur_frame->film_grain_params, &cm->film_grain_params,
+ sizeof(aom_film_grain_t));
+}
+
+void av1_read_color_config(struct aom_read_bit_buffer *rb,
+ int allow_lowbitdepth, SequenceHeader *seq_params,
+ struct aom_internal_error_info *error_info) {
+ read_bitdepth(rb, seq_params, error_info);
+
+ seq_params->use_highbitdepth =
+ seq_params->bit_depth > AOM_BITS_8 || !allow_lowbitdepth;
+ // monochrome bit (not needed for PROFILE_1)
+ const int is_monochrome =
+ seq_params->profile != PROFILE_1 ? aom_rb_read_bit(rb) : 0;
+ seq_params->monochrome = is_monochrome;
+ int color_description_present_flag = aom_rb_read_bit(rb);
+ if (color_description_present_flag) {
+ seq_params->color_primaries = aom_rb_read_literal(rb, 8);
+ seq_params->transfer_characteristics = aom_rb_read_literal(rb, 8);
+ seq_params->matrix_coefficients = aom_rb_read_literal(rb, 8);
+ } else {
+ seq_params->color_primaries = AOM_CICP_CP_UNSPECIFIED;
+ seq_params->transfer_characteristics = AOM_CICP_TC_UNSPECIFIED;
+ seq_params->matrix_coefficients = AOM_CICP_MC_UNSPECIFIED;
+ }
+ if (is_monochrome) {
+ // [16,235] (including xvycc) vs [0,255] range
+ seq_params->color_range = aom_rb_read_bit(rb);
+ seq_params->subsampling_y = seq_params->subsampling_x = 1;
+ seq_params->chroma_sample_position = AOM_CSP_UNKNOWN;
+ seq_params->separate_uv_delta_q = 0;
+ return;
+ }
+ if (seq_params->color_primaries == AOM_CICP_CP_BT_709 &&
+ seq_params->transfer_characteristics == AOM_CICP_TC_SRGB &&
+ seq_params->matrix_coefficients == AOM_CICP_MC_IDENTITY) {
+ seq_params->subsampling_y = seq_params->subsampling_x = 0;
+ seq_params->color_range = 1; // assume full color-range
+ if (!(seq_params->profile == PROFILE_1 ||
+ (seq_params->profile == PROFILE_2 &&
+ seq_params->bit_depth == AOM_BITS_12))) {
+ aom_internal_error(
+ error_info, AOM_CODEC_UNSUP_BITSTREAM,
+ "sRGB colorspace not compatible with specified profile");
+ }
+ } else {
+ // [16,235] (including xvycc) vs [0,255] range
+ seq_params->color_range = aom_rb_read_bit(rb);
+ if (seq_params->profile == PROFILE_0) {
+ // 420 only
+ seq_params->subsampling_x = seq_params->subsampling_y = 1;
+ } else if (seq_params->profile == PROFILE_1) {
+ // 444 only
+ seq_params->subsampling_x = seq_params->subsampling_y = 0;
+ } else {
+ assert(seq_params->profile == PROFILE_2);
+ if (seq_params->bit_depth == AOM_BITS_12) {
+ seq_params->subsampling_x = aom_rb_read_bit(rb);
+ if (seq_params->subsampling_x)
+ seq_params->subsampling_y = aom_rb_read_bit(rb); // 422 or 420
+ else
+ seq_params->subsampling_y = 0; // 444
+ } else {
+ // 422
+ seq_params->subsampling_x = 1;
+ seq_params->subsampling_y = 0;
+ }
+ }
+ if (seq_params->matrix_coefficients == AOM_CICP_MC_IDENTITY &&
+ (seq_params->subsampling_x || seq_params->subsampling_y)) {
+ aom_internal_error(
+ error_info, AOM_CODEC_UNSUP_BITSTREAM,
+ "Identity CICP Matrix incompatible with non 4:4:4 color sampling");
+ }
+ if (seq_params->subsampling_x && seq_params->subsampling_y) {
+ seq_params->chroma_sample_position = aom_rb_read_literal(rb, 2);
+ }
+ }
+ seq_params->separate_uv_delta_q = aom_rb_read_bit(rb);
+}
+
+void av1_read_timing_info_header(aom_timing_info_t *timing_info,
+ struct aom_internal_error_info *error,
+ struct aom_read_bit_buffer *rb) {
+ timing_info->num_units_in_display_tick =
+ aom_rb_read_unsigned_literal(rb,
+ 32); // Number of units in a display tick
+ timing_info->time_scale = aom_rb_read_unsigned_literal(rb, 32); // Time scale
+ if (timing_info->num_units_in_display_tick == 0 ||
+ timing_info->time_scale == 0) {
+ aom_internal_error(
+ error, AOM_CODEC_UNSUP_BITSTREAM,
+ "num_units_in_display_tick and time_scale must be greater than 0.");
+ }
+ timing_info->equal_picture_interval =
+ aom_rb_read_bit(rb); // Equal picture interval bit
+ if (timing_info->equal_picture_interval) {
+ const uint32_t num_ticks_per_picture_minus_1 = aom_rb_read_uvlc(rb);
+ if (num_ticks_per_picture_minus_1 == UINT32_MAX) {
+ aom_internal_error(
+ error, AOM_CODEC_UNSUP_BITSTREAM,
+ "num_ticks_per_picture_minus_1 cannot be (1 << 32) - 1.");
+ }
+ timing_info->num_ticks_per_picture = num_ticks_per_picture_minus_1 + 1;
+ }
+}
+
+void av1_read_decoder_model_info(aom_dec_model_info_t *decoder_model_info,
+ struct aom_read_bit_buffer *rb) {
+ decoder_model_info->encoder_decoder_buffer_delay_length =
+ aom_rb_read_literal(rb, 5) + 1;
+ decoder_model_info->num_units_in_decoding_tick =
+ aom_rb_read_unsigned_literal(rb,
+ 32); // Number of units in a decoding tick
+ decoder_model_info->buffer_removal_time_length =
+ aom_rb_read_literal(rb, 5) + 1;
+ decoder_model_info->frame_presentation_time_length =
+ aom_rb_read_literal(rb, 5) + 1;
+}
+
+void av1_read_op_parameters_info(aom_dec_model_op_parameters_t *op_params,
+ int buffer_delay_length,
+ struct aom_read_bit_buffer *rb) {
+ op_params->decoder_buffer_delay =
+ aom_rb_read_unsigned_literal(rb, buffer_delay_length);
+ op_params->encoder_buffer_delay =
+ aom_rb_read_unsigned_literal(rb, buffer_delay_length);
+ op_params->low_delay_mode_flag = aom_rb_read_bit(rb);
+}
+
+static AOM_INLINE void read_temporal_point_info(
+ AV1_COMMON *const cm, struct aom_read_bit_buffer *rb) {
+ cm->frame_presentation_time = aom_rb_read_unsigned_literal(
+ rb, cm->seq_params->decoder_model_info.frame_presentation_time_length);
+}
+
+void av1_read_sequence_header(AV1_COMMON *cm, struct aom_read_bit_buffer *rb,
+ SequenceHeader *seq_params) {
+ const int num_bits_width = aom_rb_read_literal(rb, 4) + 1;
+ const int num_bits_height = aom_rb_read_literal(rb, 4) + 1;
+ const int max_frame_width = aom_rb_read_literal(rb, num_bits_width) + 1;
+ const int max_frame_height = aom_rb_read_literal(rb, num_bits_height) + 1;
+
+ seq_params->num_bits_width = num_bits_width;
+ seq_params->num_bits_height = num_bits_height;
+ seq_params->max_frame_width = max_frame_width;
+ seq_params->max_frame_height = max_frame_height;
+
+ if (seq_params->reduced_still_picture_hdr) {
+ seq_params->frame_id_numbers_present_flag = 0;
+ } else {
+ seq_params->frame_id_numbers_present_flag = aom_rb_read_bit(rb);
+ }
+ if (seq_params->frame_id_numbers_present_flag) {
+ // We must always have delta_frame_id_length < frame_id_length,
+ // in order for a frame to be referenced with a unique delta.
+ // Avoid wasting bits by using a coding that enforces this restriction.
+ seq_params->delta_frame_id_length = aom_rb_read_literal(rb, 4) + 2;
+ seq_params->frame_id_length =
+ aom_rb_read_literal(rb, 3) + seq_params->delta_frame_id_length + 1;
+ if (seq_params->frame_id_length > 16)
+ aom_internal_error(cm->error, AOM_CODEC_CORRUPT_FRAME,
+ "Invalid frame_id_length");
+ }
+
+ setup_sb_size(seq_params, rb);
+
+ seq_params->enable_filter_intra = aom_rb_read_bit(rb);
+ seq_params->enable_intra_edge_filter = aom_rb_read_bit(rb);
+
+ if (seq_params->reduced_still_picture_hdr) {
+ seq_params->enable_interintra_compound = 0;
+ seq_params->enable_masked_compound = 0;
+ seq_params->enable_warped_motion = 0;
+ seq_params->enable_dual_filter = 0;
+ seq_params->order_hint_info.enable_order_hint = 0;
+ seq_params->order_hint_info.enable_dist_wtd_comp = 0;
+ seq_params->order_hint_info.enable_ref_frame_mvs = 0;
+ seq_params->force_screen_content_tools = 2; // SELECT_SCREEN_CONTENT_TOOLS
+ seq_params->force_integer_mv = 2; // SELECT_INTEGER_MV
+ seq_params->order_hint_info.order_hint_bits_minus_1 = -1;
+ } else {
+ seq_params->enable_interintra_compound = aom_rb_read_bit(rb);
+ seq_params->enable_masked_compound = aom_rb_read_bit(rb);
+ seq_params->enable_warped_motion = aom_rb_read_bit(rb);
+ seq_params->enable_dual_filter = aom_rb_read_bit(rb);
+
+ seq_params->order_hint_info.enable_order_hint = aom_rb_read_bit(rb);
+ seq_params->order_hint_info.enable_dist_wtd_comp =
+ seq_params->order_hint_info.enable_order_hint ? aom_rb_read_bit(rb) : 0;
+ seq_params->order_hint_info.enable_ref_frame_mvs =
+ seq_params->order_hint_info.enable_order_hint ? aom_rb_read_bit(rb) : 0;
+
+ if (aom_rb_read_bit(rb)) {
+ seq_params->force_screen_content_tools =
+ 2; // SELECT_SCREEN_CONTENT_TOOLS
+ } else {
+ seq_params->force_screen_content_tools = aom_rb_read_bit(rb);
+ }
+
+ if (seq_params->force_screen_content_tools > 0) {
+ if (aom_rb_read_bit(rb)) {
+ seq_params->force_integer_mv = 2; // SELECT_INTEGER_MV
+ } else {
+ seq_params->force_integer_mv = aom_rb_read_bit(rb);
+ }
+ } else {
+ seq_params->force_integer_mv = 2; // SELECT_INTEGER_MV
+ }
+ seq_params->order_hint_info.order_hint_bits_minus_1 =
+ seq_params->order_hint_info.enable_order_hint
+ ? aom_rb_read_literal(rb, 3)
+ : -1;
+ }
+
+ seq_params->enable_superres = aom_rb_read_bit(rb);
+ seq_params->enable_cdef = aom_rb_read_bit(rb);
+ seq_params->enable_restoration = aom_rb_read_bit(rb);
+}
+
+static int read_global_motion_params(WarpedMotionParams *params,
+ const WarpedMotionParams *ref_params,
+ struct aom_read_bit_buffer *rb,
+ int allow_hp) {
+ TransformationType type = aom_rb_read_bit(rb);
+ if (type != IDENTITY) {
+ if (aom_rb_read_bit(rb))
+ type = ROTZOOM;
+ else
+ type = aom_rb_read_bit(rb) ? TRANSLATION : AFFINE;
+ }
+
+ *params = default_warp_params;
+ params->wmtype = type;
+
+ if (type >= ROTZOOM) {
+ params->wmmat[2] = aom_rb_read_signed_primitive_refsubexpfin(
+ rb, GM_ALPHA_MAX + 1, SUBEXPFIN_K,
+ (ref_params->wmmat[2] >> GM_ALPHA_PREC_DIFF) -
+ (1 << GM_ALPHA_PREC_BITS)) *
+ GM_ALPHA_DECODE_FACTOR +
+ (1 << WARPEDMODEL_PREC_BITS);
+ params->wmmat[3] = aom_rb_read_signed_primitive_refsubexpfin(
+ rb, GM_ALPHA_MAX + 1, SUBEXPFIN_K,
+ (ref_params->wmmat[3] >> GM_ALPHA_PREC_DIFF)) *
+ GM_ALPHA_DECODE_FACTOR;
+ }
+
+ if (type >= AFFINE) {
+ params->wmmat[4] = aom_rb_read_signed_primitive_refsubexpfin(
+ rb, GM_ALPHA_MAX + 1, SUBEXPFIN_K,
+ (ref_params->wmmat[4] >> GM_ALPHA_PREC_DIFF)) *
+ GM_ALPHA_DECODE_FACTOR;
+ params->wmmat[5] = aom_rb_read_signed_primitive_refsubexpfin(
+ rb, GM_ALPHA_MAX + 1, SUBEXPFIN_K,
+ (ref_params->wmmat[5] >> GM_ALPHA_PREC_DIFF) -
+ (1 << GM_ALPHA_PREC_BITS)) *
+ GM_ALPHA_DECODE_FACTOR +
+ (1 << WARPEDMODEL_PREC_BITS);
+ } else {
+ params->wmmat[4] = -params->wmmat[3];
+ params->wmmat[5] = params->wmmat[2];
+ }
+
+ if (type >= TRANSLATION) {
+ const int trans_bits = (type == TRANSLATION)
+ ? GM_ABS_TRANS_ONLY_BITS - !allow_hp
+ : GM_ABS_TRANS_BITS;
+ const int trans_dec_factor =
+ (type == TRANSLATION) ? GM_TRANS_ONLY_DECODE_FACTOR * (1 << !allow_hp)
+ : GM_TRANS_DECODE_FACTOR;
+ const int trans_prec_diff = (type == TRANSLATION)
+ ? GM_TRANS_ONLY_PREC_DIFF + !allow_hp
+ : GM_TRANS_PREC_DIFF;
+ params->wmmat[0] = aom_rb_read_signed_primitive_refsubexpfin(
+ rb, (1 << trans_bits) + 1, SUBEXPFIN_K,
+ (ref_params->wmmat[0] >> trans_prec_diff)) *
+ trans_dec_factor;
+ params->wmmat[1] = aom_rb_read_signed_primitive_refsubexpfin(
+ rb, (1 << trans_bits) + 1, SUBEXPFIN_K,
+ (ref_params->wmmat[1] >> trans_prec_diff)) *
+ trans_dec_factor;
+ }
+
+ int good_shear_params = av1_get_shear_params(params);
+ if (!good_shear_params) return 0;
+
+ return 1;
+}
+
+static AOM_INLINE void read_global_motion(AV1_COMMON *cm,
+ struct aom_read_bit_buffer *rb) {
+ for (int frame = LAST_FRAME; frame <= ALTREF_FRAME; ++frame) {
+ const WarpedMotionParams *ref_params =
+ cm->prev_frame ? &cm->prev_frame->global_motion[frame]
+ : &default_warp_params;
+ int good_params =
+ read_global_motion_params(&cm->global_motion[frame], ref_params, rb,
+ cm->features.allow_high_precision_mv);
+ if (!good_params) {
+#if WARPED_MOTION_DEBUG
+ printf("Warning: unexpected global motion shear params from aomenc\n");
+#endif
+ cm->global_motion[frame].invalid = 1;
+ }
+
+ // TODO(sarahparker, debargha): The logic in the commented out code below
+ // does not work currently and causes mismatches when resize is on. Fix it
+ // before turning the optimization back on.
+ /*
+ YV12_BUFFER_CONFIG *ref_buf = get_ref_frame(cm, frame);
+ if (cm->width == ref_buf->y_crop_width &&
+ cm->height == ref_buf->y_crop_height) {
+ read_global_motion_params(&cm->global_motion[frame],
+ &cm->prev_frame->global_motion[frame], rb,
+ cm->features.allow_high_precision_mv);
+ } else {
+ cm->global_motion[frame] = default_warp_params;
+ }
+ */
+ /*
+ printf("Dec Ref %d [%d/%d]: %d %d %d %d\n",
+ frame, cm->current_frame.frame_number, cm->show_frame,
+ cm->global_motion[frame].wmmat[0],
+ cm->global_motion[frame].wmmat[1],
+ cm->global_motion[frame].wmmat[2],
+ cm->global_motion[frame].wmmat[3]);
+ */
+ }
+ memcpy(cm->cur_frame->global_motion, cm->global_motion,
+ REF_FRAMES * sizeof(WarpedMotionParams));
+}
+
+// Release the references to the frame buffers in cm->ref_frame_map and reset
+// all elements of cm->ref_frame_map to NULL.
+static AOM_INLINE void reset_ref_frame_map(AV1_COMMON *const cm) {
+ BufferPool *const pool = cm->buffer_pool;
+
+ for (int i = 0; i < REF_FRAMES; i++) {
+ decrease_ref_count(cm->ref_frame_map[i], pool);
+ cm->ref_frame_map[i] = NULL;
+ }
+}
+
+// If the refresh_frame_flags bitmask is set, update reference frame id values
+// and mark frames as valid for reference.
+static AOM_INLINE void update_ref_frame_id(AV1Decoder *const pbi) {
+ AV1_COMMON *const cm = &pbi->common;
+ int refresh_frame_flags = cm->current_frame.refresh_frame_flags;
+ for (int i = 0; i < REF_FRAMES; i++) {
+ if ((refresh_frame_flags >> i) & 1) {
+ cm->ref_frame_id[i] = cm->current_frame_id;
+ pbi->valid_for_referencing[i] = 1;
+ }
+ }
+}
+
+static AOM_INLINE void show_existing_frame_reset(AV1Decoder *const pbi,
+ int existing_frame_idx) {
+ AV1_COMMON *const cm = &pbi->common;
+
+ assert(cm->show_existing_frame);
+
+ cm->current_frame.frame_type = KEY_FRAME;
+
+ cm->current_frame.refresh_frame_flags = (1 << REF_FRAMES) - 1;
+
+ for (int i = 0; i < INTER_REFS_PER_FRAME; ++i) {
+ cm->remapped_ref_idx[i] = INVALID_IDX;
+ }
+
+ if (pbi->need_resync) {
+ reset_ref_frame_map(cm);
+ pbi->need_resync = 0;
+ }
+
+ // Note that the displayed frame must be valid for referencing in order to
+ // have been selected.
+ cm->current_frame_id = cm->ref_frame_id[existing_frame_idx];
+ update_ref_frame_id(pbi);
+
+ cm->features.refresh_frame_context = REFRESH_FRAME_CONTEXT_DISABLED;
+}
+
+static INLINE void reset_frame_buffers(AV1_COMMON *cm) {
+ RefCntBuffer *const frame_bufs = cm->buffer_pool->frame_bufs;
+ int i;
+
+ lock_buffer_pool(cm->buffer_pool);
+ reset_ref_frame_map(cm);
+ assert(cm->cur_frame->ref_count == 1);
+ for (i = 0; i < cm->buffer_pool->num_frame_bufs; ++i) {
+ // Reset all unreferenced frame buffers. We can also reset cm->cur_frame
+ // because we are the sole owner of cm->cur_frame.
+ if (frame_bufs[i].ref_count > 0 && &frame_bufs[i] != cm->cur_frame) {
+ continue;
+ }
+ frame_bufs[i].order_hint = 0;
+ av1_zero(frame_bufs[i].ref_order_hints);
+ }
+ av1_zero_unused_internal_frame_buffers(&cm->buffer_pool->int_frame_buffers);
+ unlock_buffer_pool(cm->buffer_pool);
+}
+
+// On success, returns 0. On failure, calls aom_internal_error and does not
+// return.
+static int read_uncompressed_header(AV1Decoder *pbi,
+ struct aom_read_bit_buffer *rb) {
+ AV1_COMMON *const cm = &pbi->common;
+ const SequenceHeader *const seq_params = cm->seq_params;
+ CurrentFrame *const current_frame = &cm->current_frame;
+ FeatureFlags *const features = &cm->features;
+ MACROBLOCKD *const xd = &pbi->dcb.xd;
+ BufferPool *const pool = cm->buffer_pool;
+ RefCntBuffer *const frame_bufs = pool->frame_bufs;
+ aom_s_frame_info *sframe_info = &pbi->sframe_info;
+ sframe_info->is_s_frame = 0;
+ sframe_info->is_s_frame_at_altref = 0;
+
+ if (!pbi->sequence_header_ready) {
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "No sequence header");
+ }
+
+ if (seq_params->reduced_still_picture_hdr) {
+ cm->show_existing_frame = 0;
+ cm->show_frame = 1;
+ current_frame->frame_type = KEY_FRAME;
+ if (pbi->sequence_header_changed) {
+ // This is the start of a new coded video sequence.
+ pbi->sequence_header_changed = 0;
+ pbi->decoding_first_frame = 1;
+ reset_frame_buffers(cm);
+ }
+ features->error_resilient_mode = 1;
+ } else {
+ cm->show_existing_frame = aom_rb_read_bit(rb);
+ pbi->reset_decoder_state = 0;
+
+ if (cm->show_existing_frame) {
+ if (pbi->sequence_header_changed) {
+ aom_internal_error(
+ &pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "New sequence header starts with a show_existing_frame.");
+ }
+ // Show an existing frame directly.
+ const int existing_frame_idx = aom_rb_read_literal(rb, 3);
+ RefCntBuffer *const frame_to_show = cm->ref_frame_map[existing_frame_idx];
+ if (frame_to_show == NULL) {
+ aom_internal_error(&pbi->error, AOM_CODEC_UNSUP_BITSTREAM,
+ "Buffer does not contain a decoded frame");
+ }
+ if (seq_params->decoder_model_info_present_flag &&
+ seq_params->timing_info.equal_picture_interval == 0) {
+ read_temporal_point_info(cm, rb);
+ }
+ if (seq_params->frame_id_numbers_present_flag) {
+ int frame_id_length = seq_params->frame_id_length;
+ int display_frame_id = aom_rb_read_literal(rb, frame_id_length);
+ /* Compare display_frame_id with ref_frame_id and check valid for
+ * referencing */
+ if (display_frame_id != cm->ref_frame_id[existing_frame_idx] ||
+ pbi->valid_for_referencing[existing_frame_idx] == 0)
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "Reference buffer frame ID mismatch");
+ }
+ lock_buffer_pool(pool);
+ assert(frame_to_show->ref_count > 0);
+ // cm->cur_frame should be the buffer referenced by the return value
+ // of the get_free_fb() call in assign_cur_frame_new_fb() (called by
+ // av1_receive_compressed_data()), so the ref_count should be 1.
+ assert(cm->cur_frame->ref_count == 1);
+ // assign_frame_buffer_p() decrements ref_count directly rather than
+ // call decrease_ref_count(). If cm->cur_frame->raw_frame_buffer has
+ // already been allocated, it will not be released by
+ // assign_frame_buffer_p()!
+ assert(!cm->cur_frame->raw_frame_buffer.data);
+ assign_frame_buffer_p(&cm->cur_frame, frame_to_show);
+ pbi->reset_decoder_state = frame_to_show->frame_type == KEY_FRAME;
+ unlock_buffer_pool(pool);
+
+ cm->lf.filter_level[0] = 0;
+ cm->lf.filter_level[1] = 0;
+ cm->show_frame = 1;
+ current_frame->order_hint = frame_to_show->order_hint;
+
+ // Section 6.8.2: It is a requirement of bitstream conformance that when
+ // show_existing_frame is used to show a previous frame, that the value
+ // of showable_frame for the previous frame was equal to 1.
+ if (!frame_to_show->showable_frame) {
+ aom_internal_error(&pbi->error, AOM_CODEC_UNSUP_BITSTREAM,
+ "Buffer does not contain a showable frame");
+ }
+ // Section 6.8.2: It is a requirement of bitstream conformance that when
+ // show_existing_frame is used to show a previous frame with
+ // RefFrameType[ frame_to_show_map_idx ] equal to KEY_FRAME, that the
+ // frame is output via the show_existing_frame mechanism at most once.
+ if (pbi->reset_decoder_state) frame_to_show->showable_frame = 0;
+
+ cm->film_grain_params = frame_to_show->film_grain_params;
+
+ if (pbi->reset_decoder_state) {
+ show_existing_frame_reset(pbi, existing_frame_idx);
+ } else {
+ current_frame->refresh_frame_flags = 0;
+ }
+
+ return 0;
+ }
+
+ current_frame->frame_type = (FRAME_TYPE)aom_rb_read_literal(rb, 2);
+ if (pbi->sequence_header_changed) {
+ if (current_frame->frame_type == KEY_FRAME) {
+ // This is the start of a new coded video sequence.
+ pbi->sequence_header_changed = 0;
+ pbi->decoding_first_frame = 1;
+ reset_frame_buffers(cm);
+ } else {
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "Sequence header has changed without a keyframe.");
+ }
+ }
+
+ cm->show_frame = aom_rb_read_bit(rb);
+ if (cm->show_frame == 0) pbi->is_arf_frame_present = 1;
+ if (cm->show_frame == 0 && cm->current_frame.frame_type == KEY_FRAME)
+ pbi->is_fwd_kf_present = 1;
+ if (cm->current_frame.frame_type == S_FRAME) {
+ sframe_info->is_s_frame = 1;
+ sframe_info->is_s_frame_at_altref = cm->show_frame ? 0 : 1;
+ }
+ if (seq_params->still_picture &&
+ (current_frame->frame_type != KEY_FRAME || !cm->show_frame)) {
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "Still pictures must be coded as shown keyframes");
+ }
+ cm->showable_frame = current_frame->frame_type != KEY_FRAME;
+ if (cm->show_frame) {
+ if (seq_params->decoder_model_info_present_flag &&
+ seq_params->timing_info.equal_picture_interval == 0)
+ read_temporal_point_info(cm, rb);
+ } else {
+ // See if this frame can be used as show_existing_frame in future
+ cm->showable_frame = aom_rb_read_bit(rb);
+ }
+ cm->cur_frame->showable_frame = cm->showable_frame;
+ features->error_resilient_mode =
+ frame_is_sframe(cm) ||
+ (current_frame->frame_type == KEY_FRAME && cm->show_frame)
+ ? 1
+ : aom_rb_read_bit(rb);
+ }
+
+ if (current_frame->frame_type == KEY_FRAME && cm->show_frame) {
+ /* All frames need to be marked as not valid for referencing */
+ for (int i = 0; i < REF_FRAMES; i++) {
+ pbi->valid_for_referencing[i] = 0;
+ }
+ }
+ features->disable_cdf_update = aom_rb_read_bit(rb);
+ if (seq_params->force_screen_content_tools == 2) {
+ features->allow_screen_content_tools = aom_rb_read_bit(rb);
+ } else {
+ features->allow_screen_content_tools =
+ seq_params->force_screen_content_tools;
+ }
+
+ if (features->allow_screen_content_tools) {
+ if (seq_params->force_integer_mv == 2) {
+ features->cur_frame_force_integer_mv = aom_rb_read_bit(rb);
+ } else {
+ features->cur_frame_force_integer_mv = seq_params->force_integer_mv;
+ }
+ } else {
+ features->cur_frame_force_integer_mv = 0;
+ }
+
+ int frame_size_override_flag = 0;
+ features->allow_intrabc = 0;
+ features->primary_ref_frame = PRIMARY_REF_NONE;
+
+ if (!seq_params->reduced_still_picture_hdr) {
+ if (seq_params->frame_id_numbers_present_flag) {
+ int frame_id_length = seq_params->frame_id_length;
+ int diff_len = seq_params->delta_frame_id_length;
+ int prev_frame_id = 0;
+ int have_prev_frame_id =
+ !pbi->decoding_first_frame &&
+ !(current_frame->frame_type == KEY_FRAME && cm->show_frame);
+ if (have_prev_frame_id) {
+ prev_frame_id = cm->current_frame_id;
+ }
+ cm->current_frame_id = aom_rb_read_literal(rb, frame_id_length);
+
+ if (have_prev_frame_id) {
+ int diff_frame_id;
+ if (cm->current_frame_id > prev_frame_id) {
+ diff_frame_id = cm->current_frame_id - prev_frame_id;
+ } else {
+ diff_frame_id =
+ (1 << frame_id_length) + cm->current_frame_id - prev_frame_id;
+ }
+ /* Check current_frame_id for conformance */
+ if (prev_frame_id == cm->current_frame_id ||
+ diff_frame_id >= (1 << (frame_id_length - 1))) {
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "Invalid value of current_frame_id");
+ }
+ }
+ /* Check if some frames need to be marked as not valid for referencing */
+ for (int i = 0; i < REF_FRAMES; i++) {
+ if (cm->current_frame_id - (1 << diff_len) > 0) {
+ if (cm->ref_frame_id[i] > cm->current_frame_id ||
+ cm->ref_frame_id[i] < cm->current_frame_id - (1 << diff_len))
+ pbi->valid_for_referencing[i] = 0;
+ } else {
+ if (cm->ref_frame_id[i] > cm->current_frame_id &&
+ cm->ref_frame_id[i] < (1 << frame_id_length) +
+ cm->current_frame_id - (1 << diff_len))
+ pbi->valid_for_referencing[i] = 0;
+ }
+ }
+ }
+
+ frame_size_override_flag = frame_is_sframe(cm) ? 1 : aom_rb_read_bit(rb);
+
+ current_frame->order_hint = aom_rb_read_literal(
+ rb, seq_params->order_hint_info.order_hint_bits_minus_1 + 1);
+
+ if (seq_params->order_hint_info.enable_order_hint)
+ current_frame->frame_number = current_frame->order_hint;
+
+ if (!features->error_resilient_mode && !frame_is_intra_only(cm)) {
+ features->primary_ref_frame = aom_rb_read_literal(rb, PRIMARY_REF_BITS);
+ }
+ }
+
+ if (seq_params->decoder_model_info_present_flag) {
+ pbi->buffer_removal_time_present = aom_rb_read_bit(rb);
+ if (pbi->buffer_removal_time_present) {
+ for (int op_num = 0;
+ op_num < seq_params->operating_points_cnt_minus_1 + 1; op_num++) {
+ if (seq_params->op_params[op_num].decoder_model_param_present_flag) {
+ if (seq_params->operating_point_idc[op_num] == 0 ||
+ (((seq_params->operating_point_idc[op_num] >>
+ cm->temporal_layer_id) &
+ 0x1) &&
+ ((seq_params->operating_point_idc[op_num] >>
+ (cm->spatial_layer_id + 8)) &
+ 0x1))) {
+ cm->buffer_removal_times[op_num] = aom_rb_read_unsigned_literal(
+ rb, seq_params->decoder_model_info.buffer_removal_time_length);
+ } else {
+ cm->buffer_removal_times[op_num] = 0;
+ }
+ } else {
+ cm->buffer_removal_times[op_num] = 0;
+ }
+ }
+ }
+ }
+ if (current_frame->frame_type == KEY_FRAME) {
+ if (!cm->show_frame) { // unshown keyframe (forward keyframe)
+ current_frame->refresh_frame_flags = aom_rb_read_literal(rb, REF_FRAMES);
+ } else { // shown keyframe
+ current_frame->refresh_frame_flags = (1 << REF_FRAMES) - 1;
+ }
+
+ for (int i = 0; i < INTER_REFS_PER_FRAME; ++i) {
+ cm->remapped_ref_idx[i] = INVALID_IDX;
+ }
+ if (pbi->need_resync) {
+ reset_ref_frame_map(cm);
+ pbi->need_resync = 0;
+ }
+ } else {
+ if (current_frame->frame_type == INTRA_ONLY_FRAME) {
+ current_frame->refresh_frame_flags = aom_rb_read_literal(rb, REF_FRAMES);
+ if (current_frame->refresh_frame_flags == 0xFF) {
+ aom_internal_error(&pbi->error, AOM_CODEC_UNSUP_BITSTREAM,
+ "Intra only frames cannot have refresh flags 0xFF");
+ }
+ if (pbi->need_resync) {
+ reset_ref_frame_map(cm);
+ pbi->need_resync = 0;
+ }
+ } else if (pbi->need_resync != 1) { /* Skip if need resync */
+ current_frame->refresh_frame_flags =
+ frame_is_sframe(cm) ? 0xFF : aom_rb_read_literal(rb, REF_FRAMES);
+ }
+ }
+
+ if (!frame_is_intra_only(cm) || current_frame->refresh_frame_flags != 0xFF) {
+ // Read all ref frame order hints if error_resilient_mode == 1
+ if (features->error_resilient_mode &&
+ seq_params->order_hint_info.enable_order_hint) {
+ for (int ref_idx = 0; ref_idx < REF_FRAMES; ref_idx++) {
+ // Read order hint from bit stream
+ unsigned int order_hint = aom_rb_read_literal(
+ rb, seq_params->order_hint_info.order_hint_bits_minus_1 + 1);
+ // Get buffer
+ RefCntBuffer *buf = cm->ref_frame_map[ref_idx];
+ if (buf == NULL || order_hint != buf->order_hint) {
+ if (buf != NULL) {
+ lock_buffer_pool(pool);
+ decrease_ref_count(buf, pool);
+ unlock_buffer_pool(pool);
+ cm->ref_frame_map[ref_idx] = NULL;
+ }
+ // If no corresponding buffer exists, allocate a new buffer with all
+ // pixels set to neutral grey.
+ int buf_idx = get_free_fb(cm);
+ if (buf_idx == INVALID_IDX) {
+ aom_internal_error(&pbi->error, AOM_CODEC_MEM_ERROR,
+ "Unable to find free frame buffer");
+ }
+ buf = &frame_bufs[buf_idx];
+ lock_buffer_pool(pool);
+ if (aom_realloc_frame_buffer(
+ &buf->buf, seq_params->max_frame_width,
+ seq_params->max_frame_height, seq_params->subsampling_x,
+ seq_params->subsampling_y, seq_params->use_highbitdepth,
+ AOM_BORDER_IN_PIXELS, features->byte_alignment,
+ &buf->raw_frame_buffer, pool->get_fb_cb, pool->cb_priv, 0,
+ 0)) {
+ decrease_ref_count(buf, pool);
+ unlock_buffer_pool(pool);
+ aom_internal_error(&pbi->error, AOM_CODEC_MEM_ERROR,
+ "Failed to allocate frame buffer");
+ }
+ unlock_buffer_pool(pool);
+ // According to the specification, valid bitstreams are required to
+ // never use missing reference frames so the filling process for
+ // missing frames is not normatively defined and RefValid for missing
+ // frames is set to 0.
+
+ // To make libaom more robust when the bitstream has been corrupted
+ // by the loss of some frames of data, this code adds a neutral grey
+ // buffer in place of missing frames, i.e.
+ //
+ set_planes_to_neutral_grey(seq_params, &buf->buf, 0);
+ //
+ // and allows the frames to be used for referencing, i.e.
+ //
+ pbi->valid_for_referencing[ref_idx] = 1;
+ //
+ // Please note such behavior is not normative and other decoders may
+ // use a different approach.
+ cm->ref_frame_map[ref_idx] = buf;
+ buf->order_hint = order_hint;
+ }
+ }
+ }
+ }
+
+ if (current_frame->frame_type == KEY_FRAME) {
+ setup_frame_size(cm, frame_size_override_flag, rb);
+
+ if (features->allow_screen_content_tools && !av1_superres_scaled(cm))
+ features->allow_intrabc = aom_rb_read_bit(rb);
+ features->allow_ref_frame_mvs = 0;
+ cm->prev_frame = NULL;
+ } else {
+ features->allow_ref_frame_mvs = 0;
+
+ if (current_frame->frame_type == INTRA_ONLY_FRAME) {
+ cm->cur_frame->film_grain_params_present =
+ seq_params->film_grain_params_present;
+ setup_frame_size(cm, frame_size_override_flag, rb);
+ if (features->allow_screen_content_tools && !av1_superres_scaled(cm))
+ features->allow_intrabc = aom_rb_read_bit(rb);
+
+ } else if (pbi->need_resync != 1) { /* Skip if need resync */
+ int frame_refs_short_signaling = 0;
+ // Frame refs short signaling is off when error resilient mode is on.
+ if (seq_params->order_hint_info.enable_order_hint)
+ frame_refs_short_signaling = aom_rb_read_bit(rb);
+
+ if (frame_refs_short_signaling) {
+ // == LAST_FRAME ==
+ const int lst_ref = aom_rb_read_literal(rb, REF_FRAMES_LOG2);
+ const RefCntBuffer *const lst_buf = cm->ref_frame_map[lst_ref];
+
+ // == GOLDEN_FRAME ==
+ const int gld_ref = aom_rb_read_literal(rb, REF_FRAMES_LOG2);
+ const RefCntBuffer *const gld_buf = cm->ref_frame_map[gld_ref];
+
+ // Most of the time, streams start with a keyframe. In that case,
+ // ref_frame_map will have been filled in at that point and will not
+ // contain any NULLs. However, streams are explicitly allowed to start
+ // with an intra-only frame, so long as they don't then signal a
+ // reference to a slot that hasn't been set yet. That's what we are
+ // checking here.
+ if (lst_buf == NULL)
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "Inter frame requests nonexistent reference");
+ if (gld_buf == NULL)
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "Inter frame requests nonexistent reference");
+
+ av1_set_frame_refs(cm, cm->remapped_ref_idx, lst_ref, gld_ref);
+ }
+
+ for (int i = 0; i < INTER_REFS_PER_FRAME; ++i) {
+ int ref = 0;
+ if (!frame_refs_short_signaling) {
+ ref = aom_rb_read_literal(rb, REF_FRAMES_LOG2);
+
+ // Most of the time, streams start with a keyframe. In that case,
+ // ref_frame_map will have been filled in at that point and will not
+ // contain any NULLs. However, streams are explicitly allowed to start
+ // with an intra-only frame, so long as they don't then signal a
+ // reference to a slot that hasn't been set yet. That's what we are
+ // checking here.
+ if (cm->ref_frame_map[ref] == NULL)
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "Inter frame requests nonexistent reference");
+ cm->remapped_ref_idx[i] = ref;
+ } else {
+ ref = cm->remapped_ref_idx[i];
+ }
+ // Check valid for referencing
+ if (pbi->valid_for_referencing[ref] == 0)
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "Reference frame not valid for referencing");
+
+ cm->ref_frame_sign_bias[LAST_FRAME + i] = 0;
+
+ if (seq_params->frame_id_numbers_present_flag) {
+ int frame_id_length = seq_params->frame_id_length;
+ int diff_len = seq_params->delta_frame_id_length;
+ int delta_frame_id_minus_1 = aom_rb_read_literal(rb, diff_len);
+ int ref_frame_id =
+ ((cm->current_frame_id - (delta_frame_id_minus_1 + 1) +
+ (1 << frame_id_length)) %
+ (1 << frame_id_length));
+ // Compare values derived from delta_frame_id_minus_1 and
+ // refresh_frame_flags.
+ if (ref_frame_id != cm->ref_frame_id[ref])
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "Reference buffer frame ID mismatch");
+ }
+ }
+
+ if (!features->error_resilient_mode && frame_size_override_flag) {
+ setup_frame_size_with_refs(cm, rb);
+ } else {
+ setup_frame_size(cm, frame_size_override_flag, rb);
+ }
+
+ if (features->cur_frame_force_integer_mv) {
+ features->allow_high_precision_mv = 0;
+ } else {
+ features->allow_high_precision_mv = aom_rb_read_bit(rb);
+ }
+ features->interp_filter = read_frame_interp_filter(rb);
+ features->switchable_motion_mode = aom_rb_read_bit(rb);
+ }
+
+ cm->prev_frame = get_primary_ref_frame_buf(cm);
+ if (features->primary_ref_frame != PRIMARY_REF_NONE &&
+ get_primary_ref_frame_buf(cm) == NULL) {
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "Reference frame containing this frame's initial "
+ "frame context is unavailable.");
+ }
+
+ if (!(current_frame->frame_type == INTRA_ONLY_FRAME) &&
+ pbi->need_resync != 1) {
+ if (frame_might_allow_ref_frame_mvs(cm))
+ features->allow_ref_frame_mvs = aom_rb_read_bit(rb);
+ else
+ features->allow_ref_frame_mvs = 0;
+
+ for (int i = LAST_FRAME; i <= ALTREF_FRAME; ++i) {
+ const RefCntBuffer *const ref_buf = get_ref_frame_buf(cm, i);
+ struct scale_factors *const ref_scale_factors =
+ get_ref_scale_factors(cm, i);
+ av1_setup_scale_factors_for_frame(
+ ref_scale_factors, ref_buf->buf.y_crop_width,
+ ref_buf->buf.y_crop_height, cm->width, cm->height);
+ if ((!av1_is_valid_scale(ref_scale_factors)))
+ aom_internal_error(&pbi->error, AOM_CODEC_UNSUP_BITSTREAM,
+ "Reference frame has invalid dimensions");
+ }
+ }
+ }
+
+ av1_setup_frame_buf_refs(cm);
+
+ av1_setup_frame_sign_bias(cm);
+
+ cm->cur_frame->frame_type = current_frame->frame_type;
+
+ update_ref_frame_id(pbi);
+
+ const int might_bwd_adapt = !(seq_params->reduced_still_picture_hdr) &&
+ !(features->disable_cdf_update);
+ if (might_bwd_adapt) {
+ features->refresh_frame_context = aom_rb_read_bit(rb)
+ ? REFRESH_FRAME_CONTEXT_DISABLED
+ : REFRESH_FRAME_CONTEXT_BACKWARD;
+ } else {
+ features->refresh_frame_context = REFRESH_FRAME_CONTEXT_DISABLED;
+ }
+
+ cm->cur_frame->buf.bit_depth = seq_params->bit_depth;
+ cm->cur_frame->buf.color_primaries = seq_params->color_primaries;
+ cm->cur_frame->buf.transfer_characteristics =
+ seq_params->transfer_characteristics;
+ cm->cur_frame->buf.matrix_coefficients = seq_params->matrix_coefficients;
+ cm->cur_frame->buf.monochrome = seq_params->monochrome;
+ cm->cur_frame->buf.chroma_sample_position =
+ seq_params->chroma_sample_position;
+ cm->cur_frame->buf.color_range = seq_params->color_range;
+ cm->cur_frame->buf.render_width = cm->render_width;
+ cm->cur_frame->buf.render_height = cm->render_height;
+
+ if (pbi->need_resync) {
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "Keyframe / intra-only frame required to reset decoder"
+ " state");
+ }
+
+ if (features->allow_intrabc) {
+ // Set parameters corresponding to no filtering.
+ struct loopfilter *lf = &cm->lf;
+ lf->filter_level[0] = 0;
+ lf->filter_level[1] = 0;
+ cm->cdef_info.cdef_bits = 0;
+ cm->cdef_info.cdef_strengths[0] = 0;
+ cm->cdef_info.nb_cdef_strengths = 1;
+ cm->cdef_info.cdef_uv_strengths[0] = 0;
+ cm->rst_info[0].frame_restoration_type = RESTORE_NONE;
+ cm->rst_info[1].frame_restoration_type = RESTORE_NONE;
+ cm->rst_info[2].frame_restoration_type = RESTORE_NONE;
+ }
+
+ read_tile_info(pbi, rb);
+ if (!av1_is_min_tile_width_satisfied(cm)) {
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "Minimum tile width requirement not satisfied");
+ }
+
+ CommonQuantParams *const quant_params = &cm->quant_params;
+ setup_quantization(quant_params, av1_num_planes(cm),
+ cm->seq_params->separate_uv_delta_q, rb);
+ xd->bd = (int)seq_params->bit_depth;
+
+ CommonContexts *const above_contexts = &cm->above_contexts;
+ if (above_contexts->num_planes < av1_num_planes(cm) ||
+ above_contexts->num_mi_cols < cm->mi_params.mi_cols ||
+ above_contexts->num_tile_rows < cm->tiles.rows) {
+ av1_free_above_context_buffers(above_contexts);
+ if (av1_alloc_above_context_buffers(above_contexts, cm->tiles.rows,
+ cm->mi_params.mi_cols,
+ av1_num_planes(cm))) {
+ aom_internal_error(&pbi->error, AOM_CODEC_MEM_ERROR,
+ "Failed to allocate context buffers");
+ }
+ }
+
+ if (features->primary_ref_frame == PRIMARY_REF_NONE) {
+ av1_setup_past_independence(cm);
+ }
+
+ setup_segmentation(cm, rb);
+
+ cm->delta_q_info.delta_q_res = 1;
+ cm->delta_q_info.delta_lf_res = 1;
+ cm->delta_q_info.delta_lf_present_flag = 0;
+ cm->delta_q_info.delta_lf_multi = 0;
+ cm->delta_q_info.delta_q_present_flag =
+ quant_params->base_qindex > 0 ? aom_rb_read_bit(rb) : 0;
+ if (cm->delta_q_info.delta_q_present_flag) {
+ xd->current_base_qindex = quant_params->base_qindex;
+ cm->delta_q_info.delta_q_res = 1 << aom_rb_read_literal(rb, 2);
+ if (!features->allow_intrabc)
+ cm->delta_q_info.delta_lf_present_flag = aom_rb_read_bit(rb);
+ if (cm->delta_q_info.delta_lf_present_flag) {
+ cm->delta_q_info.delta_lf_res = 1 << aom_rb_read_literal(rb, 2);
+ cm->delta_q_info.delta_lf_multi = aom_rb_read_bit(rb);
+ av1_reset_loop_filter_delta(xd, av1_num_planes(cm));
+ }
+ }
+
+ xd->cur_frame_force_integer_mv = features->cur_frame_force_integer_mv;
+
+ for (int i = 0; i < MAX_SEGMENTS; ++i) {
+ const int qindex = av1_get_qindex(&cm->seg, i, quant_params->base_qindex);
+ xd->lossless[i] =
+ qindex == 0 && quant_params->y_dc_delta_q == 0 &&
+ quant_params->u_dc_delta_q == 0 && quant_params->u_ac_delta_q == 0 &&
+ quant_params->v_dc_delta_q == 0 && quant_params->v_ac_delta_q == 0;
+ xd->qindex[i] = qindex;
+ }
+ features->coded_lossless = is_coded_lossless(cm, xd);
+ features->all_lossless = features->coded_lossless && !av1_superres_scaled(cm);
+ setup_segmentation_dequant(cm, xd);
+ if (features->coded_lossless) {
+ cm->lf.filter_level[0] = 0;
+ cm->lf.filter_level[1] = 0;
+ }
+ if (features->coded_lossless || !seq_params->enable_cdef) {
+ cm->cdef_info.cdef_bits = 0;
+ cm->cdef_info.cdef_strengths[0] = 0;
+ cm->cdef_info.cdef_uv_strengths[0] = 0;
+ }
+ if (features->all_lossless || !seq_params->enable_restoration) {
+ cm->rst_info[0].frame_restoration_type = RESTORE_NONE;
+ cm->rst_info[1].frame_restoration_type = RESTORE_NONE;
+ cm->rst_info[2].frame_restoration_type = RESTORE_NONE;
+ }
+ setup_loopfilter(cm, rb);
+
+ if (!features->coded_lossless && seq_params->enable_cdef) {
+ setup_cdef(cm, rb);
+ }
+ if (!features->all_lossless && seq_params->enable_restoration) {
+ decode_restoration_mode(cm, rb);
+ }
+
+ features->tx_mode = read_tx_mode(rb, features->coded_lossless);
+ current_frame->reference_mode = read_frame_reference_mode(cm, rb);
+
+ av1_setup_skip_mode_allowed(cm);
+ current_frame->skip_mode_info.skip_mode_flag =
+ current_frame->skip_mode_info.skip_mode_allowed ? aom_rb_read_bit(rb) : 0;
+
+ if (frame_might_allow_warped_motion(cm))
+ features->allow_warped_motion = aom_rb_read_bit(rb);
+ else
+ features->allow_warped_motion = 0;
+
+ features->reduced_tx_set_used = aom_rb_read_bit(rb);
+
+ if (features->allow_ref_frame_mvs && !frame_might_allow_ref_frame_mvs(cm)) {
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "Frame wrongly requests reference frame MVs");
+ }
+
+ if (!frame_is_intra_only(cm)) read_global_motion(cm, rb);
+
+ cm->cur_frame->film_grain_params_present =
+ seq_params->film_grain_params_present;
+ read_film_grain(cm, rb);
+
+#if EXT_TILE_DEBUG
+ if (pbi->ext_tile_debug && cm->tiles.large_scale) {
+ read_ext_tile_info(pbi, rb);
+ av1_set_single_tile_decoding_mode(cm);
+ }
+#endif // EXT_TILE_DEBUG
+ return 0;
+}
+
+struct aom_read_bit_buffer *av1_init_read_bit_buffer(
+ AV1Decoder *pbi, struct aom_read_bit_buffer *rb, const uint8_t *data,
+ const uint8_t *data_end) {
+ rb->bit_offset = 0;
+ rb->error_handler = error_handler;
+ rb->error_handler_data = &pbi->common;
+ rb->bit_buffer = data;
+ rb->bit_buffer_end = data_end;
+ return rb;
+}
+
+void av1_read_frame_size(struct aom_read_bit_buffer *rb, int num_bits_width,
+ int num_bits_height, int *width, int *height) {
+ *width = aom_rb_read_literal(rb, num_bits_width) + 1;
+ *height = aom_rb_read_literal(rb, num_bits_height) + 1;
+}
+
+BITSTREAM_PROFILE av1_read_profile(struct aom_read_bit_buffer *rb) {
+ int profile = aom_rb_read_literal(rb, PROFILE_BITS);
+ return (BITSTREAM_PROFILE)profile;
+}
+
+static AOM_INLINE void superres_post_decode(AV1Decoder *pbi) {
+ AV1_COMMON *const cm = &pbi->common;
+ BufferPool *const pool = cm->buffer_pool;
+
+ if (!av1_superres_scaled(cm)) return;
+ assert(!cm->features.all_lossless);
+
+ av1_superres_upscale(cm, pool, 0);
+}
+
+uint32_t av1_decode_frame_headers_and_setup(AV1Decoder *pbi,
+ struct aom_read_bit_buffer *rb,
+ int trailing_bits_present) {
+ AV1_COMMON *const cm = &pbi->common;
+ const int num_planes = av1_num_planes(cm);
+ MACROBLOCKD *const xd = &pbi->dcb.xd;
+
+#if CONFIG_BITSTREAM_DEBUG
+ if (cm->seq_params->order_hint_info.enable_order_hint) {
+ aom_bitstream_queue_set_frame_read(cm->current_frame.order_hint * 2 +
+ cm->show_frame);
+ } else {
+ // This is currently used in RTC encoding. cm->show_frame is always 1.
+ assert(cm->show_frame);
+ aom_bitstream_queue_set_frame_read(cm->current_frame.frame_number);
+ }
+#endif
+#if CONFIG_MISMATCH_DEBUG
+ mismatch_move_frame_idx_r();
+#endif
+
+ for (int i = LAST_FRAME; i <= ALTREF_FRAME; ++i) {
+ cm->global_motion[i] = default_warp_params;
+ cm->cur_frame->global_motion[i] = default_warp_params;
+ }
+ xd->global_motion = cm->global_motion;
+
+ read_uncompressed_header(pbi, rb);
+
+ if (trailing_bits_present) av1_check_trailing_bits(pbi, rb);
+
+ if (!cm->tiles.single_tile_decoding &&
+ (pbi->dec_tile_row >= 0 || pbi->dec_tile_col >= 0)) {
+ pbi->dec_tile_row = -1;
+ pbi->dec_tile_col = -1;
+ }
+
+ const uint32_t uncomp_hdr_size =
+ (uint32_t)aom_rb_bytes_read(rb); // Size of the uncompressed header
+ YV12_BUFFER_CONFIG *new_fb = &cm->cur_frame->buf;
+ xd->cur_buf = new_fb;
+ if (av1_allow_intrabc(cm)) {
+ av1_setup_scale_factors_for_frame(
+ &cm->sf_identity, xd->cur_buf->y_crop_width, xd->cur_buf->y_crop_height,
+ xd->cur_buf->y_crop_width, xd->cur_buf->y_crop_height);
+ }
+
+ // Showing a frame directly.
+ if (cm->show_existing_frame) {
+ if (pbi->reset_decoder_state) {
+ // Use the default frame context values.
+ *cm->fc = *cm->default_frame_context;
+ if (!cm->fc->initialized)
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "Uninitialized entropy context.");
+ }
+ return uncomp_hdr_size;
+ }
+
+ cm->mi_params.setup_mi(&cm->mi_params);
+
+ av1_calculate_ref_frame_side(cm);
+ if (cm->features.allow_ref_frame_mvs) av1_setup_motion_field(cm);
+
+ av1_setup_block_planes(xd, cm->seq_params->subsampling_x,
+ cm->seq_params->subsampling_y, num_planes);
+ if (cm->features.primary_ref_frame == PRIMARY_REF_NONE) {
+ // use the default frame context values
+ *cm->fc = *cm->default_frame_context;
+ } else {
+ *cm->fc = get_primary_ref_frame_buf(cm)->frame_context;
+ }
+ if (!cm->fc->initialized)
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "Uninitialized entropy context.");
+
+ pbi->dcb.corrupted = 0;
+ return uncomp_hdr_size;
+}
+
+// Once-per-frame initialization
+static AOM_INLINE void setup_frame_info(AV1Decoder *pbi) {
+ AV1_COMMON *const cm = &pbi->common;
+
+ if (cm->rst_info[0].frame_restoration_type != RESTORE_NONE ||
+ cm->rst_info[1].frame_restoration_type != RESTORE_NONE ||
+ cm->rst_info[2].frame_restoration_type != RESTORE_NONE) {
+ av1_alloc_restoration_buffers(cm, /*is_sgr_enabled =*/true);
+ for (int p = 0; p < av1_num_planes(cm); p++) {
+ av1_alloc_restoration_struct(cm, &cm->rst_info[p], p > 0);
+ }
+ }
+
+ const int use_highbd = cm->seq_params->use_highbitdepth;
+ const int buf_size = MC_TEMP_BUF_PELS << use_highbd;
+ if (pbi->td.mc_buf_size != buf_size) {
+ av1_free_mc_tmp_buf(&pbi->td);
+ allocate_mc_tmp_buf(cm, &pbi->td, buf_size, use_highbd);
+ }
+}
+
+void av1_decode_tg_tiles_and_wrapup(AV1Decoder *pbi, const uint8_t *data,
+ const uint8_t *data_end,
+ const uint8_t **p_data_end, int start_tile,
+ int end_tile, int initialize_flag) {
+ AV1_COMMON *const cm = &pbi->common;
+ CommonTileParams *const tiles = &cm->tiles;
+ MACROBLOCKD *const xd = &pbi->dcb.xd;
+ const int tile_count_tg = end_tile - start_tile + 1;
+
+ xd->error_info = cm->error;
+ if (initialize_flag) setup_frame_info(pbi);
+ const int num_planes = av1_num_planes(cm);
+
+ if (pbi->max_threads > 1 && !(tiles->large_scale && !pbi->ext_tile_debug) &&
+ pbi->row_mt)
+ *p_data_end =
+ decode_tiles_row_mt(pbi, data, data_end, start_tile, end_tile);
+ else if (pbi->max_threads > 1 && tile_count_tg > 1 &&
+ !(tiles->large_scale && !pbi->ext_tile_debug))
+ *p_data_end = decode_tiles_mt(pbi, data, data_end, start_tile, end_tile);
+ else
+ *p_data_end = decode_tiles(pbi, data, data_end, start_tile, end_tile);
+
+ // If the bit stream is monochrome, set the U and V buffers to a constant.
+ if (num_planes < 3) {
+ set_planes_to_neutral_grey(cm->seq_params, xd->cur_buf, 1);
+ }
+
+ if (end_tile != tiles->rows * tiles->cols - 1) {
+ return;
+ }
+
+ av1_alloc_cdef_buffers(cm, &pbi->cdef_worker, &pbi->cdef_sync,
+ pbi->num_workers, 1);
+ av1_alloc_cdef_sync(cm, &pbi->cdef_sync, pbi->num_workers);
+
+ if (!cm->features.allow_intrabc && !tiles->single_tile_decoding) {
+ if (cm->lf.filter_level[0] || cm->lf.filter_level[1]) {
+ av1_loop_filter_frame_mt(&cm->cur_frame->buf, cm, &pbi->dcb.xd, 0,
+ num_planes, 0, pbi->tile_workers,
+ pbi->num_workers, &pbi->lf_row_sync, 0);
+ }
+
+ const int do_cdef =
+ !pbi->skip_loop_filter && !cm->features.coded_lossless &&
+ (cm->cdef_info.cdef_bits || cm->cdef_info.cdef_strengths[0] ||
+ cm->cdef_info.cdef_uv_strengths[0]);
+ const int do_superres = av1_superres_scaled(cm);
+ const int optimized_loop_restoration = !do_cdef && !do_superres;
+ const int do_loop_restoration =
+ cm->rst_info[0].frame_restoration_type != RESTORE_NONE ||
+ cm->rst_info[1].frame_restoration_type != RESTORE_NONE ||
+ cm->rst_info[2].frame_restoration_type != RESTORE_NONE;
+ // Frame border extension is not required in the decoder
+ // as it happens in extend_mc_border().
+ int do_extend_border_mt = 0;
+ if (!optimized_loop_restoration) {
+ if (do_loop_restoration)
+ av1_loop_restoration_save_boundary_lines(&pbi->common.cur_frame->buf,
+ cm, 0);
+
+ if (do_cdef) {
+ if (pbi->num_workers > 1) {
+ av1_cdef_frame_mt(cm, &pbi->dcb.xd, pbi->cdef_worker,
+ pbi->tile_workers, &pbi->cdef_sync,
+ pbi->num_workers, av1_cdef_init_fb_row_mt,
+ do_extend_border_mt);
+ } else {
+ av1_cdef_frame(&pbi->common.cur_frame->buf, cm, &pbi->dcb.xd,
+ av1_cdef_init_fb_row);
+ }
+ }
+
+ superres_post_decode(pbi);
+
+ if (do_loop_restoration) {
+ av1_loop_restoration_save_boundary_lines(&pbi->common.cur_frame->buf,
+ cm, 1);
+ if (pbi->num_workers > 1) {
+ av1_loop_restoration_filter_frame_mt(
+ (YV12_BUFFER_CONFIG *)xd->cur_buf, cm, optimized_loop_restoration,
+ pbi->tile_workers, pbi->num_workers, &pbi->lr_row_sync,
+ &pbi->lr_ctxt, do_extend_border_mt);
+ } else {
+ av1_loop_restoration_filter_frame((YV12_BUFFER_CONFIG *)xd->cur_buf,
+ cm, optimized_loop_restoration,
+ &pbi->lr_ctxt);
+ }
+ }
+ } else {
+ // In no cdef and no superres case. Provide an optimized version of
+ // loop_restoration_filter.
+ if (do_loop_restoration) {
+ if (pbi->num_workers > 1) {
+ av1_loop_restoration_filter_frame_mt(
+ (YV12_BUFFER_CONFIG *)xd->cur_buf, cm, optimized_loop_restoration,
+ pbi->tile_workers, pbi->num_workers, &pbi->lr_row_sync,
+ &pbi->lr_ctxt, do_extend_border_mt);
+ } else {
+ av1_loop_restoration_filter_frame((YV12_BUFFER_CONFIG *)xd->cur_buf,
+ cm, optimized_loop_restoration,
+ &pbi->lr_ctxt);
+ }
+ }
+ }
+ }
+
+ if (!pbi->dcb.corrupted) {
+ if (cm->features.refresh_frame_context == REFRESH_FRAME_CONTEXT_BACKWARD) {
+ assert(pbi->context_update_tile_id < pbi->allocated_tiles);
+ *cm->fc = pbi->tile_data[pbi->context_update_tile_id].tctx;
+ av1_reset_cdf_symbol_counters(cm->fc);
+ }
+ } else {
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "Decode failed. Frame data is corrupted.");
+ }
+
+#if CONFIG_INSPECTION
+ if (pbi->inspect_cb != NULL) {
+ (*pbi->inspect_cb)(pbi, pbi->inspect_ctx);
+ }
+#endif
+
+ // Non frame parallel update frame context here.
+ if (!tiles->large_scale) {
+ cm->cur_frame->frame_context = *cm->fc;
+ }
+
+ if (cm->show_frame && !cm->seq_params->order_hint_info.enable_order_hint) {
+ ++cm->current_frame.frame_number;
+ }
+}
diff --git a/third_party/aom/av1/decoder/decodeframe.h b/third_party/aom/av1/decoder/decodeframe.h
new file mode 100644
index 0000000000..46ae475ff5
--- /dev/null
+++ b/third_party/aom/av1/decoder/decodeframe.h
@@ -0,0 +1,84 @@
+/*
+ * Copyright (c) 2016, Alliance for Open Media. All rights reserved
+ *
+ * This source code is subject to the terms of the BSD 2 Clause License and
+ * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
+ * was not distributed with this source code in the LICENSE file, you can
+ * obtain it at www.aomedia.org/license/software. If the Alliance for Open
+ * Media Patent License 1.0 was not distributed with this source code in the
+ * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
+ */
+
+#ifndef AOM_AV1_DECODER_DECODEFRAME_H_
+#define AOM_AV1_DECODER_DECODEFRAME_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct AV1Decoder;
+struct aom_read_bit_buffer;
+struct ThreadData;
+
+// Reads the middle part of the sequence header OBU (from
+// frame_width_bits_minus_1 to enable_restoration) into seq_params.
+// Reports errors by calling rb->error_handler() or aom_internal_error().
+void av1_read_sequence_header(AV1_COMMON *cm, struct aom_read_bit_buffer *rb,
+ SequenceHeader *seq_params);
+
+void av1_read_frame_size(struct aom_read_bit_buffer *rb, int num_bits_width,
+ int num_bits_height, int *width, int *height);
+BITSTREAM_PROFILE av1_read_profile(struct aom_read_bit_buffer *rb);
+
+// Returns 0 on success. Sets pbi->common.error.error_code and returns -1 on
+// failure.
+int av1_check_trailing_bits(struct AV1Decoder *pbi,
+ struct aom_read_bit_buffer *rb);
+
+// On success, returns the frame header size. On failure, calls
+// aom_internal_error and does not return.
+uint32_t av1_decode_frame_headers_and_setup(struct AV1Decoder *pbi,
+ struct aom_read_bit_buffer *rb,
+ int trailing_bits_present);
+
+void av1_decode_tg_tiles_and_wrapup(struct AV1Decoder *pbi, const uint8_t *data,
+ const uint8_t *data_end,
+ const uint8_t **p_data_end, int start_tile,
+ int end_tile, int initialize_flag);
+
+// Implements the color_config() function in the spec. Reports errors by
+// calling rb->error_handler() or aom_internal_error().
+void av1_read_color_config(struct aom_read_bit_buffer *rb,
+ int allow_lowbitdepth, SequenceHeader *seq_params,
+ struct aom_internal_error_info *error_info);
+
+// Implements the timing_info() function in the spec. Reports errors by calling
+// rb->error_handler() or aom_internal_error().
+void av1_read_timing_info_header(aom_timing_info_t *timing_info,
+ struct aom_internal_error_info *error,
+ struct aom_read_bit_buffer *rb);
+
+// Implements the decoder_model_info() function in the spec. Reports errors by
+// calling rb->error_handler().
+void av1_read_decoder_model_info(aom_dec_model_info_t *decoder_model_info,
+ struct aom_read_bit_buffer *rb);
+
+// Implements the operating_parameters_info() function in the spec. Reports
+// errors by calling rb->error_handler().
+void av1_read_op_parameters_info(aom_dec_model_op_parameters_t *op_params,
+ int buffer_delay_length,
+ struct aom_read_bit_buffer *rb);
+
+struct aom_read_bit_buffer *av1_init_read_bit_buffer(
+ struct AV1Decoder *pbi, struct aom_read_bit_buffer *rb, const uint8_t *data,
+ const uint8_t *data_end);
+
+void av1_free_mc_tmp_buf(struct ThreadData *thread_data);
+
+void av1_set_single_tile_decoding_mode(AV1_COMMON *const cm);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif // AOM_AV1_DECODER_DECODEFRAME_H_
diff --git a/third_party/aom/av1/decoder/decodemv.c b/third_party/aom/av1/decoder/decodemv.c
new file mode 100644
index 0000000000..bb0ccf5fd8
--- /dev/null
+++ b/third_party/aom/av1/decoder/decodemv.c
@@ -0,0 +1,1586 @@
+/*
+ * Copyright (c) 2016, Alliance for Open Media. All rights reserved
+ *
+ * This source code is subject to the terms of the BSD 2 Clause License and
+ * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
+ * was not distributed with this source code in the LICENSE file, you can
+ * obtain it at www.aomedia.org/license/software. If the Alliance for Open
+ * Media Patent License 1.0 was not distributed with this source code in the
+ * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
+ */
+
+#include <assert.h>
+
+#include "av1/common/cfl.h"
+#include "av1/common/common.h"
+#include "av1/common/entropy.h"
+#include "av1/common/entropymode.h"
+#include "av1/common/entropymv.h"
+#include "av1/common/mvref_common.h"
+#include "av1/common/pred_common.h"
+#include "av1/common/reconinter.h"
+#include "av1/common/reconintra.h"
+#include "av1/common/seg_common.h"
+#include "av1/common/warped_motion.h"
+
+#include "av1/decoder/decodeframe.h"
+#include "av1/decoder/decodemv.h"
+
+#include "aom_dsp/aom_dsp_common.h"
+
+#define ACCT_STR __func__
+
+#define DEC_MISMATCH_DEBUG 0
+
+static PREDICTION_MODE read_intra_mode(aom_reader *r, aom_cdf_prob *cdf) {
+ return (PREDICTION_MODE)aom_read_symbol(r, cdf, INTRA_MODES, ACCT_STR);
+}
+
+static void read_cdef(AV1_COMMON *cm, aom_reader *r, MACROBLOCKD *const xd) {
+ const int skip_txfm = xd->mi[0]->skip_txfm;
+ if (cm->features.coded_lossless) return;
+ if (cm->features.allow_intrabc) {
+ assert(cm->cdef_info.cdef_bits == 0);
+ return;
+ }
+
+ // At the start of a superblock, mark that we haven't yet read CDEF strengths
+ // for any of the CDEF units contained in this superblock.
+ const int sb_mask = (cm->seq_params->mib_size - 1);
+ const int mi_row_in_sb = (xd->mi_row & sb_mask);
+ const int mi_col_in_sb = (xd->mi_col & sb_mask);
+ if (mi_row_in_sb == 0 && mi_col_in_sb == 0) {
+ xd->cdef_transmitted[0] = xd->cdef_transmitted[1] =
+ xd->cdef_transmitted[2] = xd->cdef_transmitted[3] = false;
+ }
+
+ // CDEF unit size is 64x64 irrespective of the superblock size.
+ const int cdef_size = 1 << (6 - MI_SIZE_LOG2);
+
+ // Find index of this CDEF unit in this superblock.
+ const int index_mask = cdef_size;
+ const int cdef_unit_row_in_sb = ((xd->mi_row & index_mask) != 0);
+ const int cdef_unit_col_in_sb = ((xd->mi_col & index_mask) != 0);
+ const int index = (cm->seq_params->sb_size == BLOCK_128X128)
+ ? cdef_unit_col_in_sb + 2 * cdef_unit_row_in_sb
+ : 0;
+
+ // Read CDEF strength from the first non-skip coding block in this CDEF unit.
+ if (!xd->cdef_transmitted[index] && !skip_txfm) {
+ // CDEF strength for this CDEF unit needs to be read into the MB_MODE_INFO
+ // of the 1st block in this CDEF unit.
+ const int first_block_mask = ~(cdef_size - 1);
+ CommonModeInfoParams *const mi_params = &cm->mi_params;
+ const int grid_idx =
+ get_mi_grid_idx(mi_params, xd->mi_row & first_block_mask,
+ xd->mi_col & first_block_mask);
+ MB_MODE_INFO *const mbmi = mi_params->mi_grid_base[grid_idx];
+ mbmi->cdef_strength =
+ aom_read_literal(r, cm->cdef_info.cdef_bits, ACCT_STR);
+ xd->cdef_transmitted[index] = true;
+ }
+}
+
+static int read_delta_qindex(AV1_COMMON *cm, const MACROBLOCKD *xd,
+ aom_reader *r, MB_MODE_INFO *const mbmi) {
+ int sign, abs, reduced_delta_qindex = 0;
+ BLOCK_SIZE bsize = mbmi->bsize;
+ const int b_col = xd->mi_col & (cm->seq_params->mib_size - 1);
+ const int b_row = xd->mi_row & (cm->seq_params->mib_size - 1);
+ const int read_delta_q_flag = (b_col == 0 && b_row == 0);
+ FRAME_CONTEXT *ec_ctx = xd->tile_ctx;
+
+ if ((bsize != cm->seq_params->sb_size || mbmi->skip_txfm == 0) &&
+ read_delta_q_flag) {
+ abs = aom_read_symbol(r, ec_ctx->delta_q_cdf, DELTA_Q_PROBS + 1, ACCT_STR);
+ const int smallval = (abs < DELTA_Q_SMALL);
+
+ if (!smallval) {
+ const int rem_bits = aom_read_literal(r, 3, ACCT_STR) + 1;
+ const int thr = (1 << rem_bits) + 1;
+ abs = aom_read_literal(r, rem_bits, ACCT_STR) + thr;
+ }
+
+ if (abs) {
+ sign = aom_read_bit(r, ACCT_STR);
+ } else {
+ sign = 1;
+ }
+
+ reduced_delta_qindex = sign ? -abs : abs;
+ }
+ return reduced_delta_qindex;
+}
+static int read_delta_lflevel(const AV1_COMMON *const cm, aom_reader *r,
+ aom_cdf_prob *const cdf,
+ const MB_MODE_INFO *const mbmi, int mi_col,
+ int mi_row) {
+ int reduced_delta_lflevel = 0;
+ const BLOCK_SIZE bsize = mbmi->bsize;
+ const int b_col = mi_col & (cm->seq_params->mib_size - 1);
+ const int b_row = mi_row & (cm->seq_params->mib_size - 1);
+ const int read_delta_lf_flag = (b_col == 0 && b_row == 0);
+
+ if ((bsize != cm->seq_params->sb_size || mbmi->skip_txfm == 0) &&
+ read_delta_lf_flag) {
+ int abs = aom_read_symbol(r, cdf, DELTA_LF_PROBS + 1, ACCT_STR);
+ const int smallval = (abs < DELTA_LF_SMALL);
+ if (!smallval) {
+ const int rem_bits = aom_read_literal(r, 3, ACCT_STR) + 1;
+ const int thr = (1 << rem_bits) + 1;
+ abs = aom_read_literal(r, rem_bits, ACCT_STR) + thr;
+ }
+ const int sign = abs ? aom_read_bit(r, ACCT_STR) : 1;
+ reduced_delta_lflevel = sign ? -abs : abs;
+ }
+ return reduced_delta_lflevel;
+}
+
+static UV_PREDICTION_MODE read_intra_mode_uv(FRAME_CONTEXT *ec_ctx,
+ aom_reader *r,
+ CFL_ALLOWED_TYPE cfl_allowed,
+ PREDICTION_MODE y_mode) {
+ const UV_PREDICTION_MODE uv_mode =
+ aom_read_symbol(r, ec_ctx->uv_mode_cdf[cfl_allowed][y_mode],
+ UV_INTRA_MODES - !cfl_allowed, ACCT_STR);
+ return uv_mode;
+}
+
+static uint8_t read_cfl_alphas(FRAME_CONTEXT *const ec_ctx, aom_reader *r,
+ int8_t *signs_out) {
+ const int8_t joint_sign =
+ aom_read_symbol(r, ec_ctx->cfl_sign_cdf, CFL_JOINT_SIGNS, "cfl:signs");
+ uint8_t idx = 0;
+ // Magnitudes are only coded for nonzero values
+ if (CFL_SIGN_U(joint_sign) != CFL_SIGN_ZERO) {
+ aom_cdf_prob *cdf_u = ec_ctx->cfl_alpha_cdf[CFL_CONTEXT_U(joint_sign)];
+ idx = (uint8_t)aom_read_symbol(r, cdf_u, CFL_ALPHABET_SIZE, "cfl:alpha_u")
+ << CFL_ALPHABET_SIZE_LOG2;
+ }
+ if (CFL_SIGN_V(joint_sign) != CFL_SIGN_ZERO) {
+ aom_cdf_prob *cdf_v = ec_ctx->cfl_alpha_cdf[CFL_CONTEXT_V(joint_sign)];
+ idx += (uint8_t)aom_read_symbol(r, cdf_v, CFL_ALPHABET_SIZE, "cfl:alpha_v");
+ }
+ *signs_out = joint_sign;
+ return idx;
+}
+
+static INTERINTRA_MODE read_interintra_mode(MACROBLOCKD *xd, aom_reader *r,
+ int size_group) {
+ const INTERINTRA_MODE ii_mode = (INTERINTRA_MODE)aom_read_symbol(
+ r, xd->tile_ctx->interintra_mode_cdf[size_group], INTERINTRA_MODES,
+ ACCT_STR);
+ return ii_mode;
+}
+
+static PREDICTION_MODE read_inter_mode(FRAME_CONTEXT *ec_ctx, aom_reader *r,
+ int16_t ctx) {
+ int16_t mode_ctx = ctx & NEWMV_CTX_MASK;
+ int is_newmv, is_zeromv, is_refmv;
+ is_newmv = aom_read_symbol(r, ec_ctx->newmv_cdf[mode_ctx], 2, ACCT_STR) == 0;
+ if (is_newmv) return NEWMV;
+
+ mode_ctx = (ctx >> GLOBALMV_OFFSET) & GLOBALMV_CTX_MASK;
+ is_zeromv =
+ aom_read_symbol(r, ec_ctx->zeromv_cdf[mode_ctx], 2, ACCT_STR) == 0;
+ if (is_zeromv) return GLOBALMV;
+
+ mode_ctx = (ctx >> REFMV_OFFSET) & REFMV_CTX_MASK;
+ is_refmv = aom_read_symbol(r, ec_ctx->refmv_cdf[mode_ctx], 2, ACCT_STR) == 0;
+ if (is_refmv)
+ return NEARESTMV;
+ else
+ return NEARMV;
+}
+
+static void read_drl_idx(FRAME_CONTEXT *ec_ctx, DecoderCodingBlock *dcb,
+ MB_MODE_INFO *mbmi, aom_reader *r) {
+ MACROBLOCKD *const xd = &dcb->xd;
+ uint8_t ref_frame_type = av1_ref_frame_type(mbmi->ref_frame);
+ mbmi->ref_mv_idx = 0;
+ if (mbmi->mode == NEWMV || mbmi->mode == NEW_NEWMV) {
+ for (int idx = 0; idx < 2; ++idx) {
+ if (dcb->ref_mv_count[ref_frame_type] > idx + 1) {
+ uint8_t drl_ctx = av1_drl_ctx(xd->weight[ref_frame_type], idx);
+ int drl_idx = aom_read_symbol(r, ec_ctx->drl_cdf[drl_ctx], 2, ACCT_STR);
+ mbmi->ref_mv_idx = idx + drl_idx;
+ if (!drl_idx) return;
+ }
+ }
+ }
+ if (have_nearmv_in_inter_mode(mbmi->mode)) {
+ // Offset the NEARESTMV mode.
+ // TODO(jingning): Unify the two syntax decoding loops after the NEARESTMV
+ // mode is factored in.
+ for (int idx = 1; idx < 3; ++idx) {
+ if (dcb->ref_mv_count[ref_frame_type] > idx + 1) {
+ uint8_t drl_ctx = av1_drl_ctx(xd->weight[ref_frame_type], idx);
+ int drl_idx = aom_read_symbol(r, ec_ctx->drl_cdf[drl_ctx], 2, ACCT_STR);
+ mbmi->ref_mv_idx = idx + drl_idx - 1;
+ if (!drl_idx) return;
+ }
+ }
+ }
+}
+
+static MOTION_MODE read_motion_mode(AV1_COMMON *cm, MACROBLOCKD *xd,
+ MB_MODE_INFO *mbmi, aom_reader *r) {
+ if (cm->features.switchable_motion_mode == 0) return SIMPLE_TRANSLATION;
+ if (mbmi->skip_mode) return SIMPLE_TRANSLATION;
+
+ const MOTION_MODE last_motion_mode_allowed = motion_mode_allowed(
+ xd->global_motion, xd, mbmi, cm->features.allow_warped_motion);
+ int motion_mode;
+
+ if (last_motion_mode_allowed == SIMPLE_TRANSLATION) return SIMPLE_TRANSLATION;
+
+ if (last_motion_mode_allowed == OBMC_CAUSAL) {
+ motion_mode =
+ aom_read_symbol(r, xd->tile_ctx->obmc_cdf[mbmi->bsize], 2, ACCT_STR);
+ return (MOTION_MODE)(SIMPLE_TRANSLATION + motion_mode);
+ } else {
+ motion_mode = aom_read_symbol(r, xd->tile_ctx->motion_mode_cdf[mbmi->bsize],
+ MOTION_MODES, ACCT_STR);
+ return (MOTION_MODE)(SIMPLE_TRANSLATION + motion_mode);
+ }
+}
+
+static PREDICTION_MODE read_inter_compound_mode(MACROBLOCKD *xd, aom_reader *r,
+ int16_t ctx) {
+ const int mode =
+ aom_read_symbol(r, xd->tile_ctx->inter_compound_mode_cdf[ctx],
+ INTER_COMPOUND_MODES, ACCT_STR);
+ assert(is_inter_compound_mode(NEAREST_NEARESTMV + mode));
+ return NEAREST_NEARESTMV + mode;
+}
+
+int av1_neg_deinterleave(int diff, int ref, int max) {
+ if (!ref) return diff;
+ if (ref >= (max - 1)) return max - diff - 1;
+ if (2 * ref < max) {
+ if (diff <= 2 * ref) {
+ if (diff & 1)
+ return ref + ((diff + 1) >> 1);
+ else
+ return ref - (diff >> 1);
+ }
+ return diff;
+ } else {
+ if (diff <= 2 * (max - ref - 1)) {
+ if (diff & 1)
+ return ref + ((diff + 1) >> 1);
+ else
+ return ref - (diff >> 1);
+ }
+ return max - (diff + 1);
+ }
+}
+
+static int read_segment_id(AV1_COMMON *const cm, const MACROBLOCKD *const xd,
+ aom_reader *r, int skip) {
+ int cdf_num;
+ const uint8_t pred = av1_get_spatial_seg_pred(cm, xd, &cdf_num, 0);
+ if (skip) return pred;
+
+ FRAME_CONTEXT *ec_ctx = xd->tile_ctx;
+ struct segmentation *const seg = &cm->seg;
+ struct segmentation_probs *const segp = &ec_ctx->seg;
+ aom_cdf_prob *pred_cdf = segp->spatial_pred_seg_cdf[cdf_num];
+ const int coded_id = aom_read_symbol(r, pred_cdf, MAX_SEGMENTS, ACCT_STR);
+ const int segment_id =
+ av1_neg_deinterleave(coded_id, pred, seg->last_active_segid + 1);
+
+ if (segment_id < 0 || segment_id > seg->last_active_segid) {
+ aom_internal_error(xd->error_info, AOM_CODEC_CORRUPT_FRAME,
+ "Corrupted segment_ids");
+ }
+ return segment_id;
+}
+
+static int dec_get_segment_id(const AV1_COMMON *cm, const uint8_t *segment_ids,
+ int mi_offset, int x_mis, int y_mis) {
+ int segment_id = INT_MAX;
+
+ for (int y = 0; y < y_mis; y++)
+ for (int x = 0; x < x_mis; x++)
+ segment_id = AOMMIN(
+ segment_id, segment_ids[mi_offset + y * cm->mi_params.mi_cols + x]);
+
+ assert(segment_id >= 0 && segment_id < MAX_SEGMENTS);
+ return segment_id;
+}
+
+static int read_intra_segment_id(AV1_COMMON *const cm,
+ const MACROBLOCKD *const xd, BLOCK_SIZE bsize,
+ aom_reader *r, int skip) {
+ struct segmentation *const seg = &cm->seg;
+ if (!seg->enabled) return 0; // Default for disabled segmentation
+ assert(seg->update_map && !seg->temporal_update);
+
+ const CommonModeInfoParams *const mi_params = &cm->mi_params;
+ const int mi_row = xd->mi_row;
+ const int mi_col = xd->mi_col;
+ const int mi_stride = cm->mi_params.mi_cols;
+ const int mi_offset = mi_row * mi_stride + mi_col;
+ const int bw = mi_size_wide[bsize];
+ const int bh = mi_size_high[bsize];
+ const int x_mis = AOMMIN(mi_params->mi_cols - mi_col, bw);
+ const int y_mis = AOMMIN(mi_params->mi_rows - mi_row, bh);
+ const int segment_id = read_segment_id(cm, xd, r, skip);
+ set_segment_id(cm->cur_frame->seg_map, mi_offset, x_mis, y_mis, mi_stride,
+ segment_id);
+ return segment_id;
+}
+
+static void copy_segment_id(const CommonModeInfoParams *const mi_params,
+ const uint8_t *last_segment_ids,
+ uint8_t *current_segment_ids, int mi_offset,
+ int x_mis, int y_mis) {
+ const int stride = mi_params->mi_cols;
+ if (last_segment_ids) {
+ assert(last_segment_ids != current_segment_ids);
+ for (int y = 0; y < y_mis; y++) {
+ memcpy(&current_segment_ids[mi_offset + y * stride],
+ &last_segment_ids[mi_offset + y * stride],
+ sizeof(current_segment_ids[0]) * x_mis);
+ }
+ } else {
+ for (int y = 0; y < y_mis; y++) {
+ memset(&current_segment_ids[mi_offset + y * stride], 0,
+ sizeof(current_segment_ids[0]) * x_mis);
+ }
+ }
+}
+
+static int get_predicted_segment_id(AV1_COMMON *const cm, int mi_offset,
+ int x_mis, int y_mis) {
+ return cm->last_frame_seg_map ? dec_get_segment_id(cm, cm->last_frame_seg_map,
+ mi_offset, x_mis, y_mis)
+ : 0;
+}
+
+static int read_inter_segment_id(AV1_COMMON *const cm, MACROBLOCKD *const xd,
+ int preskip, aom_reader *r) {
+ struct segmentation *const seg = &cm->seg;
+ const CommonModeInfoParams *const mi_params = &cm->mi_params;
+ MB_MODE_INFO *const mbmi = xd->mi[0];
+ const int mi_row = xd->mi_row;
+ const int mi_col = xd->mi_col;
+ const int mi_offset = mi_row * mi_params->mi_cols + mi_col;
+ const int bw = mi_size_wide[mbmi->bsize];
+ const int bh = mi_size_high[mbmi->bsize];
+
+ // TODO(slavarnway): move x_mis, y_mis into xd ?????
+ const int x_mis = AOMMIN(mi_params->mi_cols - mi_col, bw);
+ const int y_mis = AOMMIN(mi_params->mi_rows - mi_row, bh);
+
+ if (!seg->enabled) return 0; // Default for disabled segmentation
+
+ if (!seg->update_map) {
+ copy_segment_id(mi_params, cm->last_frame_seg_map, cm->cur_frame->seg_map,
+ mi_offset, x_mis, y_mis);
+ return get_predicted_segment_id(cm, mi_offset, x_mis, y_mis);
+ }
+
+ uint8_t segment_id;
+ const int mi_stride = cm->mi_params.mi_cols;
+ if (preskip) {
+ if (!seg->segid_preskip) return 0;
+ } else {
+ if (mbmi->skip_txfm) {
+ if (seg->temporal_update) {
+ mbmi->seg_id_predicted = 0;
+ }
+ segment_id = read_segment_id(cm, xd, r, 1);
+ set_segment_id(cm->cur_frame->seg_map, mi_offset, x_mis, y_mis, mi_stride,
+ segment_id);
+ return segment_id;
+ }
+ }
+
+ if (seg->temporal_update) {
+ const uint8_t ctx = av1_get_pred_context_seg_id(xd);
+ FRAME_CONTEXT *ec_ctx = xd->tile_ctx;
+ struct segmentation_probs *const segp = &ec_ctx->seg;
+ aom_cdf_prob *pred_cdf = segp->pred_cdf[ctx];
+ mbmi->seg_id_predicted = aom_read_symbol(r, pred_cdf, 2, ACCT_STR);
+ if (mbmi->seg_id_predicted) {
+ segment_id = get_predicted_segment_id(cm, mi_offset, x_mis, y_mis);
+ } else {
+ segment_id = read_segment_id(cm, xd, r, 0);
+ }
+ } else {
+ segment_id = read_segment_id(cm, xd, r, 0);
+ }
+ set_segment_id(cm->cur_frame->seg_map, mi_offset, x_mis, y_mis, mi_stride,
+ segment_id);
+ return segment_id;
+}
+
+static int read_skip_mode(AV1_COMMON *cm, const MACROBLOCKD *xd, int segment_id,
+ aom_reader *r) {
+ if (!cm->current_frame.skip_mode_info.skip_mode_flag) return 0;
+
+ if (segfeature_active(&cm->seg, segment_id, SEG_LVL_SKIP)) {
+ return 0;
+ }
+
+ if (!is_comp_ref_allowed(xd->mi[0]->bsize)) return 0;
+
+ if (segfeature_active(&cm->seg, segment_id, SEG_LVL_REF_FRAME) ||
+ segfeature_active(&cm->seg, segment_id, SEG_LVL_GLOBALMV)) {
+ // These features imply single-reference mode, while skip mode implies
+ // compound reference. Hence, the two are mutually exclusive.
+ // In other words, skip_mode is implicitly 0 here.
+ return 0;
+ }
+
+ const int ctx = av1_get_skip_mode_context(xd);
+ FRAME_CONTEXT *ec_ctx = xd->tile_ctx;
+ const int skip_mode =
+ aom_read_symbol(r, ec_ctx->skip_mode_cdfs[ctx], 2, ACCT_STR);
+ return skip_mode;
+}
+
+static int read_skip_txfm(AV1_COMMON *cm, const MACROBLOCKD *xd, int segment_id,
+ aom_reader *r) {
+ if (segfeature_active(&cm->seg, segment_id, SEG_LVL_SKIP)) {
+ return 1;
+ } else {
+ const int ctx = av1_get_skip_txfm_context(xd);
+ FRAME_CONTEXT *ec_ctx = xd->tile_ctx;
+ const int skip_txfm =
+ aom_read_symbol(r, ec_ctx->skip_txfm_cdfs[ctx], 2, ACCT_STR);
+ return skip_txfm;
+ }
+}
+
+// Merge the sorted list of cached colors(cached_colors[0...n_cached_colors-1])
+// and the sorted list of transmitted colors(colors[n_cached_colors...n-1]) into
+// one single sorted list(colors[...]).
+static void merge_colors(uint16_t *colors, uint16_t *cached_colors,
+ int n_colors, int n_cached_colors) {
+ if (n_cached_colors == 0) return;
+ int cache_idx = 0, trans_idx = n_cached_colors;
+ for (int i = 0; i < n_colors; ++i) {
+ if (cache_idx < n_cached_colors &&
+ (trans_idx >= n_colors ||
+ cached_colors[cache_idx] <= colors[trans_idx])) {
+ colors[i] = cached_colors[cache_idx++];
+ } else {
+ assert(trans_idx < n_colors);
+ colors[i] = colors[trans_idx++];
+ }
+ }
+}
+
+static void read_palette_colors_y(MACROBLOCKD *const xd, int bit_depth,
+ PALETTE_MODE_INFO *const pmi, aom_reader *r) {
+ uint16_t color_cache[2 * PALETTE_MAX_SIZE];
+ uint16_t cached_colors[PALETTE_MAX_SIZE];
+ const int n_cache = av1_get_palette_cache(xd, 0, color_cache);
+ const int n = pmi->palette_size[0];
+ int idx = 0;
+ for (int i = 0; i < n_cache && idx < n; ++i)
+ if (aom_read_bit(r, ACCT_STR)) cached_colors[idx++] = color_cache[i];
+ if (idx < n) {
+ const int n_cached_colors = idx;
+ pmi->palette_colors[idx++] = aom_read_literal(r, bit_depth, ACCT_STR);
+ if (idx < n) {
+ const int min_bits = bit_depth - 3;
+ int bits = min_bits + aom_read_literal(r, 2, ACCT_STR);
+ int range = (1 << bit_depth) - pmi->palette_colors[idx - 1] - 1;
+ for (; idx < n; ++idx) {
+ assert(range >= 0);
+ const int delta = aom_read_literal(r, bits, ACCT_STR) + 1;
+ pmi->palette_colors[idx] = clamp(pmi->palette_colors[idx - 1] + delta,
+ 0, (1 << bit_depth) - 1);
+ range -= (pmi->palette_colors[idx] - pmi->palette_colors[idx - 1]);
+ bits = AOMMIN(bits, av1_ceil_log2(range));
+ }
+ }
+ merge_colors(pmi->palette_colors, cached_colors, n, n_cached_colors);
+ } else {
+ memcpy(pmi->palette_colors, cached_colors, n * sizeof(cached_colors[0]));
+ }
+}
+
+static void read_palette_colors_uv(MACROBLOCKD *const xd, int bit_depth,
+ PALETTE_MODE_INFO *const pmi,
+ aom_reader *r) {
+ const int n = pmi->palette_size[1];
+ // U channel colors.
+ uint16_t color_cache[2 * PALETTE_MAX_SIZE];
+ uint16_t cached_colors[PALETTE_MAX_SIZE];
+ const int n_cache = av1_get_palette_cache(xd, 1, color_cache);
+ int idx = 0;
+ for (int i = 0; i < n_cache && idx < n; ++i)
+ if (aom_read_bit(r, ACCT_STR)) cached_colors[idx++] = color_cache[i];
+ if (idx < n) {
+ const int n_cached_colors = idx;
+ idx += PALETTE_MAX_SIZE;
+ pmi->palette_colors[idx++] = aom_read_literal(r, bit_depth, ACCT_STR);
+ if (idx < PALETTE_MAX_SIZE + n) {
+ const int min_bits = bit_depth - 3;
+ int bits = min_bits + aom_read_literal(r, 2, ACCT_STR);
+ int range = (1 << bit_depth) - pmi->palette_colors[idx - 1];
+ for (; idx < PALETTE_MAX_SIZE + n; ++idx) {
+ assert(range >= 0);
+ const int delta = aom_read_literal(r, bits, ACCT_STR);
+ pmi->palette_colors[idx] = clamp(pmi->palette_colors[idx - 1] + delta,
+ 0, (1 << bit_depth) - 1);
+ range -= (pmi->palette_colors[idx] - pmi->palette_colors[idx - 1]);
+ bits = AOMMIN(bits, av1_ceil_log2(range));
+ }
+ }
+ merge_colors(pmi->palette_colors + PALETTE_MAX_SIZE, cached_colors, n,
+ n_cached_colors);
+ } else {
+ memcpy(pmi->palette_colors + PALETTE_MAX_SIZE, cached_colors,
+ n * sizeof(cached_colors[0]));
+ }
+
+ // V channel colors.
+ if (aom_read_bit(r, ACCT_STR)) { // Delta encoding.
+ const int min_bits_v = bit_depth - 4;
+ const int max_val = 1 << bit_depth;
+ int bits = min_bits_v + aom_read_literal(r, 2, ACCT_STR);
+ pmi->palette_colors[2 * PALETTE_MAX_SIZE] =
+ aom_read_literal(r, bit_depth, ACCT_STR);
+ for (int i = 1; i < n; ++i) {
+ int delta = aom_read_literal(r, bits, ACCT_STR);
+ if (delta && aom_read_bit(r, ACCT_STR)) delta = -delta;
+ int val = (int)pmi->palette_colors[2 * PALETTE_MAX_SIZE + i - 1] + delta;
+ if (val < 0) val += max_val;
+ if (val >= max_val) val -= max_val;
+ pmi->palette_colors[2 * PALETTE_MAX_SIZE + i] = val;
+ }
+ } else {
+ for (int i = 0; i < n; ++i) {
+ pmi->palette_colors[2 * PALETTE_MAX_SIZE + i] =
+ aom_read_literal(r, bit_depth, ACCT_STR);
+ }
+ }
+}
+
+static void read_palette_mode_info(AV1_COMMON *const cm, MACROBLOCKD *const xd,
+ aom_reader *r) {
+ const int num_planes = av1_num_planes(cm);
+ MB_MODE_INFO *const mbmi = xd->mi[0];
+ const BLOCK_SIZE bsize = mbmi->bsize;
+ assert(av1_allow_palette(cm->features.allow_screen_content_tools, bsize));
+ PALETTE_MODE_INFO *const pmi = &mbmi->palette_mode_info;
+ const int bsize_ctx = av1_get_palette_bsize_ctx(bsize);
+
+ if (mbmi->mode == DC_PRED) {
+ const int palette_mode_ctx = av1_get_palette_mode_ctx(xd);
+ const int modev = aom_read_symbol(
+ r, xd->tile_ctx->palette_y_mode_cdf[bsize_ctx][palette_mode_ctx], 2,
+ ACCT_STR);
+ if (modev) {
+ pmi->palette_size[0] =
+ aom_read_symbol(r, xd->tile_ctx->palette_y_size_cdf[bsize_ctx],
+ PALETTE_SIZES, ACCT_STR) +
+ 2;
+ read_palette_colors_y(xd, cm->seq_params->bit_depth, pmi, r);
+ }
+ }
+ if (num_planes > 1 && mbmi->uv_mode == UV_DC_PRED && xd->is_chroma_ref) {
+ const int palette_uv_mode_ctx = (pmi->palette_size[0] > 0);
+ const int modev = aom_read_symbol(
+ r, xd->tile_ctx->palette_uv_mode_cdf[palette_uv_mode_ctx], 2, ACCT_STR);
+ if (modev) {
+ pmi->palette_size[1] =
+ aom_read_symbol(r, xd->tile_ctx->palette_uv_size_cdf[bsize_ctx],
+ PALETTE_SIZES, ACCT_STR) +
+ 2;
+ read_palette_colors_uv(xd, cm->seq_params->bit_depth, pmi, r);
+ }
+ }
+}
+
+static int read_angle_delta(aom_reader *r, aom_cdf_prob *cdf) {
+ const int sym = aom_read_symbol(r, cdf, 2 * MAX_ANGLE_DELTA + 1, ACCT_STR);
+ return sym - MAX_ANGLE_DELTA;
+}
+
+static void read_filter_intra_mode_info(const AV1_COMMON *const cm,
+ MACROBLOCKD *const xd, aom_reader *r) {
+ MB_MODE_INFO *const mbmi = xd->mi[0];
+ FILTER_INTRA_MODE_INFO *filter_intra_mode_info =
+ &mbmi->filter_intra_mode_info;
+
+ if (av1_filter_intra_allowed(cm, mbmi)) {
+ filter_intra_mode_info->use_filter_intra = aom_read_symbol(
+ r, xd->tile_ctx->filter_intra_cdfs[mbmi->bsize], 2, ACCT_STR);
+ if (filter_intra_mode_info->use_filter_intra) {
+ filter_intra_mode_info->filter_intra_mode = aom_read_symbol(
+ r, xd->tile_ctx->filter_intra_mode_cdf, FILTER_INTRA_MODES, ACCT_STR);
+ }
+ } else {
+ filter_intra_mode_info->use_filter_intra = 0;
+ }
+}
+
+void av1_read_tx_type(const AV1_COMMON *const cm, MACROBLOCKD *xd, int blk_row,
+ int blk_col, TX_SIZE tx_size, aom_reader *r) {
+ MB_MODE_INFO *mbmi = xd->mi[0];
+ uint8_t *tx_type =
+ &xd->tx_type_map[blk_row * xd->tx_type_map_stride + blk_col];
+ *tx_type = DCT_DCT;
+
+ // No need to read transform type if block is skipped.
+ if (mbmi->skip_txfm ||
+ segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_SKIP))
+ return;
+
+ // No need to read transform type for lossless mode(qindex==0).
+ const int qindex = xd->qindex[mbmi->segment_id];
+ if (qindex == 0) return;
+
+ const int inter_block = is_inter_block(mbmi);
+ if (get_ext_tx_types(tx_size, inter_block, cm->features.reduced_tx_set_used) >
+ 1) {
+ const TxSetType tx_set_type = av1_get_ext_tx_set_type(
+ tx_size, inter_block, cm->features.reduced_tx_set_used);
+ const int eset =
+ get_ext_tx_set(tx_size, inter_block, cm->features.reduced_tx_set_used);
+ // eset == 0 should correspond to a set with only DCT_DCT and
+ // there is no need to read the tx_type
+ assert(eset != 0);
+
+ const TX_SIZE square_tx_size = txsize_sqr_map[tx_size];
+ FRAME_CONTEXT *ec_ctx = xd->tile_ctx;
+ if (inter_block) {
+ *tx_type = av1_ext_tx_inv[tx_set_type][aom_read_symbol(
+ r, ec_ctx->inter_ext_tx_cdf[eset][square_tx_size],
+ av1_num_ext_tx_set[tx_set_type], ACCT_STR)];
+ } else {
+ const PREDICTION_MODE intra_mode =
+ mbmi->filter_intra_mode_info.use_filter_intra
+ ? fimode_to_intradir[mbmi->filter_intra_mode_info
+ .filter_intra_mode]
+ : mbmi->mode;
+ *tx_type = av1_ext_tx_inv[tx_set_type][aom_read_symbol(
+ r, ec_ctx->intra_ext_tx_cdf[eset][square_tx_size][intra_mode],
+ av1_num_ext_tx_set[tx_set_type], ACCT_STR)];
+ }
+ }
+}
+
+static INLINE void read_mv(aom_reader *r, MV *mv, const MV *ref,
+ nmv_context *ctx, MvSubpelPrecision precision);
+
+static INLINE int is_mv_valid(const MV *mv);
+
+static INLINE int assign_dv(AV1_COMMON *cm, MACROBLOCKD *xd, int_mv *mv,
+ const int_mv *ref_mv, int mi_row, int mi_col,
+ BLOCK_SIZE bsize, aom_reader *r) {
+ FRAME_CONTEXT *ec_ctx = xd->tile_ctx;
+ read_mv(r, &mv->as_mv, &ref_mv->as_mv, &ec_ctx->ndvc, MV_SUBPEL_NONE);
+ // DV should not have sub-pel.
+ assert((mv->as_mv.col & 7) == 0);
+ assert((mv->as_mv.row & 7) == 0);
+ mv->as_mv.col = (mv->as_mv.col >> 3) * 8;
+ mv->as_mv.row = (mv->as_mv.row >> 3) * 8;
+ int valid = is_mv_valid(&mv->as_mv) &&
+ av1_is_dv_valid(mv->as_mv, cm, xd, mi_row, mi_col, bsize,
+ cm->seq_params->mib_size_log2);
+ return valid;
+}
+
+static void read_intrabc_info(AV1_COMMON *const cm, DecoderCodingBlock *dcb,
+ aom_reader *r) {
+ MACROBLOCKD *const xd = &dcb->xd;
+ MB_MODE_INFO *const mbmi = xd->mi[0];
+ FRAME_CONTEXT *ec_ctx = xd->tile_ctx;
+ mbmi->use_intrabc = aom_read_symbol(r, ec_ctx->intrabc_cdf, 2, ACCT_STR);
+ if (mbmi->use_intrabc) {
+ BLOCK_SIZE bsize = mbmi->bsize;
+ mbmi->mode = DC_PRED;
+ mbmi->uv_mode = UV_DC_PRED;
+ mbmi->interp_filters = av1_broadcast_interp_filter(BILINEAR);
+ mbmi->motion_mode = SIMPLE_TRANSLATION;
+
+ int16_t inter_mode_ctx[MODE_CTX_REF_FRAMES];
+ int_mv ref_mvs[INTRA_FRAME + 1][MAX_MV_REF_CANDIDATES];
+
+ av1_find_mv_refs(cm, xd, mbmi, INTRA_FRAME, dcb->ref_mv_count,
+ xd->ref_mv_stack, xd->weight, ref_mvs, /*global_mvs=*/NULL,
+ inter_mode_ctx);
+
+ int_mv nearestmv, nearmv;
+
+ av1_find_best_ref_mvs(0, ref_mvs[INTRA_FRAME], &nearestmv, &nearmv, 0);
+ int_mv dv_ref = nearestmv.as_int == 0 ? nearmv : nearestmv;
+ if (dv_ref.as_int == 0)
+ av1_find_ref_dv(&dv_ref, &xd->tile, cm->seq_params->mib_size, xd->mi_row);
+ // Ref DV should not have sub-pel.
+ int valid_dv = (dv_ref.as_mv.col & 7) == 0 && (dv_ref.as_mv.row & 7) == 0;
+ dv_ref.as_mv.col = (dv_ref.as_mv.col >> 3) * 8;
+ dv_ref.as_mv.row = (dv_ref.as_mv.row >> 3) * 8;
+ valid_dv = valid_dv && assign_dv(cm, xd, &mbmi->mv[0], &dv_ref, xd->mi_row,
+ xd->mi_col, bsize, r);
+ if (!valid_dv) {
+ // Intra bc motion vectors are not valid - signal corrupt frame
+ aom_internal_error(xd->error_info, AOM_CODEC_CORRUPT_FRAME,
+ "Invalid intrabc dv");
+ }
+ }
+}
+
+// If delta q is present, reads delta_q index.
+// Also reads delta_q loop filter levels, if present.
+static void read_delta_q_params(AV1_COMMON *const cm, MACROBLOCKD *const xd,
+ aom_reader *r) {
+ DeltaQInfo *const delta_q_info = &cm->delta_q_info;
+
+ if (delta_q_info->delta_q_present_flag) {
+ MB_MODE_INFO *const mbmi = xd->mi[0];
+ xd->current_base_qindex +=
+ read_delta_qindex(cm, xd, r, mbmi) * delta_q_info->delta_q_res;
+ /* Normative: Clamp to [1,MAXQ] to not interfere with lossless mode */
+ xd->current_base_qindex = clamp(xd->current_base_qindex, 1, MAXQ);
+ FRAME_CONTEXT *const ec_ctx = xd->tile_ctx;
+ if (delta_q_info->delta_lf_present_flag) {
+ const int mi_row = xd->mi_row;
+ const int mi_col = xd->mi_col;
+ if (delta_q_info->delta_lf_multi) {
+ const int frame_lf_count =
+ av1_num_planes(cm) > 1 ? FRAME_LF_COUNT : FRAME_LF_COUNT - 2;
+ for (int lf_id = 0; lf_id < frame_lf_count; ++lf_id) {
+ const int tmp_lvl =
+ xd->delta_lf[lf_id] +
+ read_delta_lflevel(cm, r, ec_ctx->delta_lf_multi_cdf[lf_id], mbmi,
+ mi_col, mi_row) *
+ delta_q_info->delta_lf_res;
+ mbmi->delta_lf[lf_id] = xd->delta_lf[lf_id] =
+ clamp(tmp_lvl, -MAX_LOOP_FILTER, MAX_LOOP_FILTER);
+ }
+ } else {
+ const int tmp_lvl = xd->delta_lf_from_base +
+ read_delta_lflevel(cm, r, ec_ctx->delta_lf_cdf,
+ mbmi, mi_col, mi_row) *
+ delta_q_info->delta_lf_res;
+ mbmi->delta_lf_from_base = xd->delta_lf_from_base =
+ clamp(tmp_lvl, -MAX_LOOP_FILTER, MAX_LOOP_FILTER);
+ }
+ }
+ }
+}
+
+static void read_intra_frame_mode_info(AV1_COMMON *const cm,
+ DecoderCodingBlock *dcb, aom_reader *r) {
+ MACROBLOCKD *const xd = &dcb->xd;
+ MB_MODE_INFO *const mbmi = xd->mi[0];
+ const MB_MODE_INFO *above_mi = xd->above_mbmi;
+ const MB_MODE_INFO *left_mi = xd->left_mbmi;
+ const BLOCK_SIZE bsize = mbmi->bsize;
+ struct segmentation *const seg = &cm->seg;
+
+ FRAME_CONTEXT *ec_ctx = xd->tile_ctx;
+
+ if (seg->segid_preskip)
+ mbmi->segment_id = read_intra_segment_id(cm, xd, bsize, r, 0);
+
+ mbmi->skip_txfm = read_skip_txfm(cm, xd, mbmi->segment_id, r);
+
+ if (!seg->segid_preskip)
+ mbmi->segment_id = read_intra_segment_id(cm, xd, bsize, r, mbmi->skip_txfm);
+
+ read_cdef(cm, r, xd);
+
+ read_delta_q_params(cm, xd, r);
+
+ mbmi->current_qindex = xd->current_base_qindex;
+
+ mbmi->ref_frame[0] = INTRA_FRAME;
+ mbmi->ref_frame[1] = NONE_FRAME;
+ mbmi->palette_mode_info.palette_size[0] = 0;
+ mbmi->palette_mode_info.palette_size[1] = 0;
+ mbmi->filter_intra_mode_info.use_filter_intra = 0;
+
+ const int mi_row = xd->mi_row;
+ const int mi_col = xd->mi_col;
+ xd->above_txfm_context = cm->above_contexts.txfm[xd->tile.tile_row] + mi_col;
+ xd->left_txfm_context =
+ xd->left_txfm_context_buffer + (mi_row & MAX_MIB_MASK);
+
+ if (av1_allow_intrabc(cm)) {
+ read_intrabc_info(cm, dcb, r);
+ if (is_intrabc_block(mbmi)) return;
+ }
+
+ mbmi->mode = read_intra_mode(r, get_y_mode_cdf(ec_ctx, above_mi, left_mi));
+
+ const int use_angle_delta = av1_use_angle_delta(bsize);
+ mbmi->angle_delta[PLANE_TYPE_Y] =
+ (use_angle_delta && av1_is_directional_mode(mbmi->mode))
+ ? read_angle_delta(r, ec_ctx->angle_delta_cdf[mbmi->mode - V_PRED])
+ : 0;
+
+ if (!cm->seq_params->monochrome && xd->is_chroma_ref) {
+ mbmi->uv_mode =
+ read_intra_mode_uv(ec_ctx, r, is_cfl_allowed(xd), mbmi->mode);
+ if (mbmi->uv_mode == UV_CFL_PRED) {
+ mbmi->cfl_alpha_idx = read_cfl_alphas(ec_ctx, r, &mbmi->cfl_alpha_signs);
+ }
+ const PREDICTION_MODE intra_mode = get_uv_mode(mbmi->uv_mode);
+ mbmi->angle_delta[PLANE_TYPE_UV] =
+ (use_angle_delta && av1_is_directional_mode(intra_mode))
+ ? read_angle_delta(r, ec_ctx->angle_delta_cdf[intra_mode - V_PRED])
+ : 0;
+ } else {
+ // Avoid decoding angle_info if there is no chroma prediction
+ mbmi->uv_mode = UV_DC_PRED;
+ }
+ xd->cfl.store_y = store_cfl_required(cm, xd);
+
+ if (av1_allow_palette(cm->features.allow_screen_content_tools, bsize))
+ read_palette_mode_info(cm, xd, r);
+
+ read_filter_intra_mode_info(cm, xd, r);
+}
+
+static int read_mv_component(aom_reader *r, nmv_component *mvcomp,
+ int use_subpel, int usehp) {
+ int mag, d, fr, hp;
+ const int sign = aom_read_symbol(r, mvcomp->sign_cdf, 2, ACCT_STR);
+ const int mv_class =
+ aom_read_symbol(r, mvcomp->classes_cdf, MV_CLASSES, ACCT_STR);
+ const int class0 = mv_class == MV_CLASS_0;
+
+ // Integer part
+ if (class0) {
+ d = aom_read_symbol(r, mvcomp->class0_cdf, CLASS0_SIZE, ACCT_STR);
+ mag = 0;
+ } else {
+ const int n = mv_class + CLASS0_BITS - 1; // number of bits
+ d = 0;
+ for (int i = 0; i < n; ++i)
+ d |= aom_read_symbol(r, mvcomp->bits_cdf[i], 2, ACCT_STR) << i;
+ mag = CLASS0_SIZE << (mv_class + 2);
+ }
+
+ if (use_subpel) {
+ // Fractional part
+ fr = aom_read_symbol(r, class0 ? mvcomp->class0_fp_cdf[d] : mvcomp->fp_cdf,
+ MV_FP_SIZE, ACCT_STR);
+
+ // High precision part (if hp is not used, the default value of the hp is 1)
+ hp = usehp ? aom_read_symbol(
+ r, class0 ? mvcomp->class0_hp_cdf : mvcomp->hp_cdf, 2,
+ ACCT_STR)
+ : 1;
+ } else {
+ fr = 3;
+ hp = 1;
+ }
+
+ // Result
+ mag += ((d << 3) | (fr << 1) | hp) + 1;
+ return sign ? -mag : mag;
+}
+
+static INLINE void read_mv(aom_reader *r, MV *mv, const MV *ref,
+ nmv_context *ctx, MvSubpelPrecision precision) {
+ MV diff = kZeroMv;
+ const MV_JOINT_TYPE joint_type =
+ (MV_JOINT_TYPE)aom_read_symbol(r, ctx->joints_cdf, MV_JOINTS, ACCT_STR);
+
+ if (mv_joint_vertical(joint_type))
+ diff.row = read_mv_component(r, &ctx->comps[0], precision > MV_SUBPEL_NONE,
+ precision > MV_SUBPEL_LOW_PRECISION);
+
+ if (mv_joint_horizontal(joint_type))
+ diff.col = read_mv_component(r, &ctx->comps[1], precision > MV_SUBPEL_NONE,
+ precision > MV_SUBPEL_LOW_PRECISION);
+
+ mv->row = ref->row + diff.row;
+ mv->col = ref->col + diff.col;
+}
+
+static REFERENCE_MODE read_block_reference_mode(AV1_COMMON *cm,
+ const MACROBLOCKD *xd,
+ aom_reader *r) {
+ if (!is_comp_ref_allowed(xd->mi[0]->bsize)) return SINGLE_REFERENCE;
+ if (cm->current_frame.reference_mode == REFERENCE_MODE_SELECT) {
+ const int ctx = av1_get_reference_mode_context(xd);
+ const REFERENCE_MODE mode = (REFERENCE_MODE)aom_read_symbol(
+ r, xd->tile_ctx->comp_inter_cdf[ctx], 2, ACCT_STR);
+ return mode; // SINGLE_REFERENCE or COMPOUND_REFERENCE
+ } else {
+ assert(cm->current_frame.reference_mode == SINGLE_REFERENCE);
+ return cm->current_frame.reference_mode;
+ }
+}
+
+#define READ_REF_BIT(pname) \
+ aom_read_symbol(r, av1_get_pred_cdf_##pname(xd), 2, ACCT_STR)
+
+static COMP_REFERENCE_TYPE read_comp_reference_type(const MACROBLOCKD *xd,
+ aom_reader *r) {
+ const int ctx = av1_get_comp_reference_type_context(xd);
+ const COMP_REFERENCE_TYPE comp_ref_type =
+ (COMP_REFERENCE_TYPE)aom_read_symbol(
+ r, xd->tile_ctx->comp_ref_type_cdf[ctx], 2, ACCT_STR);
+ return comp_ref_type; // UNIDIR_COMP_REFERENCE or BIDIR_COMP_REFERENCE
+}
+
+static void set_ref_frames_for_skip_mode(AV1_COMMON *const cm,
+ MV_REFERENCE_FRAME ref_frame[2]) {
+ ref_frame[0] = LAST_FRAME + cm->current_frame.skip_mode_info.ref_frame_idx_0;
+ ref_frame[1] = LAST_FRAME + cm->current_frame.skip_mode_info.ref_frame_idx_1;
+}
+
+// Read the referncence frame
+static void read_ref_frames(AV1_COMMON *const cm, MACROBLOCKD *const xd,
+ aom_reader *r, int segment_id,
+ MV_REFERENCE_FRAME ref_frame[2]) {
+ if (xd->mi[0]->skip_mode) {
+ set_ref_frames_for_skip_mode(cm, ref_frame);
+ return;
+ }
+
+ if (segfeature_active(&cm->seg, segment_id, SEG_LVL_REF_FRAME)) {
+ ref_frame[0] = (MV_REFERENCE_FRAME)get_segdata(&cm->seg, segment_id,
+ SEG_LVL_REF_FRAME);
+ ref_frame[1] = NONE_FRAME;
+ } else if (segfeature_active(&cm->seg, segment_id, SEG_LVL_SKIP) ||
+ segfeature_active(&cm->seg, segment_id, SEG_LVL_GLOBALMV)) {
+ ref_frame[0] = LAST_FRAME;
+ ref_frame[1] = NONE_FRAME;
+ } else {
+ const REFERENCE_MODE mode = read_block_reference_mode(cm, xd, r);
+
+ if (mode == COMPOUND_REFERENCE) {
+ const COMP_REFERENCE_TYPE comp_ref_type = read_comp_reference_type(xd, r);
+
+ if (comp_ref_type == UNIDIR_COMP_REFERENCE) {
+ const int bit = READ_REF_BIT(uni_comp_ref_p);
+ if (bit) {
+ ref_frame[0] = BWDREF_FRAME;
+ ref_frame[1] = ALTREF_FRAME;
+ } else {
+ const int bit1 = READ_REF_BIT(uni_comp_ref_p1);
+ if (bit1) {
+ const int bit2 = READ_REF_BIT(uni_comp_ref_p2);
+ if (bit2) {
+ ref_frame[0] = LAST_FRAME;
+ ref_frame[1] = GOLDEN_FRAME;
+ } else {
+ ref_frame[0] = LAST_FRAME;
+ ref_frame[1] = LAST3_FRAME;
+ }
+ } else {
+ ref_frame[0] = LAST_FRAME;
+ ref_frame[1] = LAST2_FRAME;
+ }
+ }
+
+ return;
+ }
+
+ assert(comp_ref_type == BIDIR_COMP_REFERENCE);
+
+ const int idx = 1;
+ const int bit = READ_REF_BIT(comp_ref_p);
+ // Decode forward references.
+ if (!bit) {
+ const int bit1 = READ_REF_BIT(comp_ref_p1);
+ ref_frame[!idx] = bit1 ? LAST2_FRAME : LAST_FRAME;
+ } else {
+ const int bit2 = READ_REF_BIT(comp_ref_p2);
+ ref_frame[!idx] = bit2 ? GOLDEN_FRAME : LAST3_FRAME;
+ }
+
+ // Decode backward references.
+ const int bit_bwd = READ_REF_BIT(comp_bwdref_p);
+ if (!bit_bwd) {
+ const int bit1_bwd = READ_REF_BIT(comp_bwdref_p1);
+ ref_frame[idx] = bit1_bwd ? ALTREF2_FRAME : BWDREF_FRAME;
+ } else {
+ ref_frame[idx] = ALTREF_FRAME;
+ }
+ } else if (mode == SINGLE_REFERENCE) {
+ const int bit0 = READ_REF_BIT(single_ref_p1);
+ if (bit0) {
+ const int bit1 = READ_REF_BIT(single_ref_p2);
+ if (!bit1) {
+ const int bit5 = READ_REF_BIT(single_ref_p6);
+ ref_frame[0] = bit5 ? ALTREF2_FRAME : BWDREF_FRAME;
+ } else {
+ ref_frame[0] = ALTREF_FRAME;
+ }
+ } else {
+ const int bit2 = READ_REF_BIT(single_ref_p3);
+ if (bit2) {
+ const int bit4 = READ_REF_BIT(single_ref_p5);
+ ref_frame[0] = bit4 ? GOLDEN_FRAME : LAST3_FRAME;
+ } else {
+ const int bit3 = READ_REF_BIT(single_ref_p4);
+ ref_frame[0] = bit3 ? LAST2_FRAME : LAST_FRAME;
+ }
+ }
+
+ ref_frame[1] = NONE_FRAME;
+ } else {
+ assert(0 && "Invalid prediction mode.");
+ }
+ }
+}
+
+static INLINE void read_mb_interp_filter(const MACROBLOCKD *const xd,
+ InterpFilter interp_filter,
+ bool enable_dual_filter,
+ MB_MODE_INFO *const mbmi,
+ aom_reader *r) {
+ FRAME_CONTEXT *ec_ctx = xd->tile_ctx;
+
+ if (!av1_is_interp_needed(xd)) {
+ set_default_interp_filters(mbmi, interp_filter);
+ return;
+ }
+
+ if (interp_filter != SWITCHABLE) {
+ mbmi->interp_filters = av1_broadcast_interp_filter(interp_filter);
+ } else {
+ InterpFilter ref0_filter[2] = { EIGHTTAP_REGULAR, EIGHTTAP_REGULAR };
+ for (int dir = 0; dir < 2; ++dir) {
+ const int ctx = av1_get_pred_context_switchable_interp(xd, dir);
+ ref0_filter[dir] = (InterpFilter)aom_read_symbol(
+ r, ec_ctx->switchable_interp_cdf[ctx], SWITCHABLE_FILTERS, ACCT_STR);
+ if (!enable_dual_filter) {
+ ref0_filter[1] = ref0_filter[0];
+ break;
+ }
+ }
+ // The index system works as: (0, 1) -> (vertical, horizontal) filter types
+ mbmi->interp_filters.as_filters.x_filter = ref0_filter[1];
+ mbmi->interp_filters.as_filters.y_filter = ref0_filter[0];
+ }
+}
+
+static void read_intra_block_mode_info(AV1_COMMON *const cm,
+ MACROBLOCKD *const xd,
+ MB_MODE_INFO *const mbmi,
+ aom_reader *r) {
+ const BLOCK_SIZE bsize = mbmi->bsize;
+ const int use_angle_delta = av1_use_angle_delta(bsize);
+
+ mbmi->ref_frame[0] = INTRA_FRAME;
+ mbmi->ref_frame[1] = NONE_FRAME;
+
+ FRAME_CONTEXT *ec_ctx = xd->tile_ctx;
+
+ mbmi->mode = read_intra_mode(r, ec_ctx->y_mode_cdf[size_group_lookup[bsize]]);
+
+ mbmi->angle_delta[PLANE_TYPE_Y] =
+ use_angle_delta && av1_is_directional_mode(mbmi->mode)
+ ? read_angle_delta(r, ec_ctx->angle_delta_cdf[mbmi->mode - V_PRED])
+ : 0;
+ if (!cm->seq_params->monochrome && xd->is_chroma_ref) {
+ mbmi->uv_mode =
+ read_intra_mode_uv(ec_ctx, r, is_cfl_allowed(xd), mbmi->mode);
+ if (mbmi->uv_mode == UV_CFL_PRED) {
+ mbmi->cfl_alpha_idx =
+ read_cfl_alphas(xd->tile_ctx, r, &mbmi->cfl_alpha_signs);
+ }
+ const PREDICTION_MODE intra_mode = get_uv_mode(mbmi->uv_mode);
+ mbmi->angle_delta[PLANE_TYPE_UV] =
+ use_angle_delta && av1_is_directional_mode(intra_mode)
+ ? read_angle_delta(r, ec_ctx->angle_delta_cdf[intra_mode - V_PRED])
+ : 0;
+ } else {
+ // Avoid decoding angle_info if there is no chroma prediction
+ mbmi->uv_mode = UV_DC_PRED;
+ }
+ xd->cfl.store_y = store_cfl_required(cm, xd);
+
+ mbmi->palette_mode_info.palette_size[0] = 0;
+ mbmi->palette_mode_info.palette_size[1] = 0;
+ if (av1_allow_palette(cm->features.allow_screen_content_tools, bsize))
+ read_palette_mode_info(cm, xd, r);
+
+ read_filter_intra_mode_info(cm, xd, r);
+}
+
+static INLINE int is_mv_valid(const MV *mv) {
+ return mv->row > MV_LOW && mv->row < MV_UPP && mv->col > MV_LOW &&
+ mv->col < MV_UPP;
+}
+
+static INLINE int assign_mv(AV1_COMMON *cm, MACROBLOCKD *xd,
+ PREDICTION_MODE mode,
+ MV_REFERENCE_FRAME ref_frame[2], int_mv mv[2],
+ int_mv ref_mv[2], int_mv nearest_mv[2],
+ int_mv near_mv[2], int is_compound, int allow_hp,
+ aom_reader *r) {
+ FRAME_CONTEXT *ec_ctx = xd->tile_ctx;
+ MB_MODE_INFO *mbmi = xd->mi[0];
+ BLOCK_SIZE bsize = mbmi->bsize;
+ FeatureFlags *const features = &cm->features;
+ if (features->cur_frame_force_integer_mv) {
+ allow_hp = MV_SUBPEL_NONE;
+ }
+ switch (mode) {
+ case NEWMV: {
+ nmv_context *const nmvc = &ec_ctx->nmvc;
+ read_mv(r, &mv[0].as_mv, &ref_mv[0].as_mv, nmvc, allow_hp);
+ break;
+ }
+ case NEARESTMV: {
+ mv[0].as_int = nearest_mv[0].as_int;
+ break;
+ }
+ case NEARMV: {
+ mv[0].as_int = near_mv[0].as_int;
+ break;
+ }
+ case GLOBALMV: {
+ mv[0].as_int = gm_get_motion_vector(&cm->global_motion[ref_frame[0]],
+ features->allow_high_precision_mv,
+ bsize, xd->mi_col, xd->mi_row,
+ features->cur_frame_force_integer_mv)
+ .as_int;
+ break;
+ }
+ case NEW_NEWMV: {
+ assert(is_compound);
+ for (int i = 0; i < 2; ++i) {
+ nmv_context *const nmvc = &ec_ctx->nmvc;
+ read_mv(r, &mv[i].as_mv, &ref_mv[i].as_mv, nmvc, allow_hp);
+ }
+ break;
+ }
+ case NEAREST_NEARESTMV: {
+ assert(is_compound);
+ mv[0].as_int = nearest_mv[0].as_int;
+ mv[1].as_int = nearest_mv[1].as_int;
+ break;
+ }
+ case NEAR_NEARMV: {
+ assert(is_compound);
+ mv[0].as_int = near_mv[0].as_int;
+ mv[1].as_int = near_mv[1].as_int;
+ break;
+ }
+ case NEW_NEARESTMV: {
+ nmv_context *const nmvc = &ec_ctx->nmvc;
+ read_mv(r, &mv[0].as_mv, &ref_mv[0].as_mv, nmvc, allow_hp);
+ assert(is_compound);
+ mv[1].as_int = nearest_mv[1].as_int;
+ break;
+ }
+ case NEAREST_NEWMV: {
+ nmv_context *const nmvc = &ec_ctx->nmvc;
+ mv[0].as_int = nearest_mv[0].as_int;
+ read_mv(r, &mv[1].as_mv, &ref_mv[1].as_mv, nmvc, allow_hp);
+ assert(is_compound);
+ break;
+ }
+ case NEAR_NEWMV: {
+ nmv_context *const nmvc = &ec_ctx->nmvc;
+ mv[0].as_int = near_mv[0].as_int;
+ read_mv(r, &mv[1].as_mv, &ref_mv[1].as_mv, nmvc, allow_hp);
+ assert(is_compound);
+ break;
+ }
+ case NEW_NEARMV: {
+ nmv_context *const nmvc = &ec_ctx->nmvc;
+ read_mv(r, &mv[0].as_mv, &ref_mv[0].as_mv, nmvc, allow_hp);
+ assert(is_compound);
+ mv[1].as_int = near_mv[1].as_int;
+ break;
+ }
+ case GLOBAL_GLOBALMV: {
+ assert(is_compound);
+ mv[0].as_int = gm_get_motion_vector(&cm->global_motion[ref_frame[0]],
+ features->allow_high_precision_mv,
+ bsize, xd->mi_col, xd->mi_row,
+ features->cur_frame_force_integer_mv)
+ .as_int;
+ mv[1].as_int = gm_get_motion_vector(&cm->global_motion[ref_frame[1]],
+ features->allow_high_precision_mv,
+ bsize, xd->mi_col, xd->mi_row,
+ features->cur_frame_force_integer_mv)
+ .as_int;
+ break;
+ }
+ default: {
+ return 0;
+ }
+ }
+
+ int ret = is_mv_valid(&mv[0].as_mv);
+ if (is_compound) {
+ ret = ret && is_mv_valid(&mv[1].as_mv);
+ }
+ return ret;
+}
+
+static int read_is_inter_block(AV1_COMMON *const cm, MACROBLOCKD *const xd,
+ int segment_id, aom_reader *r) {
+ if (segfeature_active(&cm->seg, segment_id, SEG_LVL_REF_FRAME)) {
+ const int frame = get_segdata(&cm->seg, segment_id, SEG_LVL_REF_FRAME);
+ if (frame < LAST_FRAME) return 0;
+ return frame != INTRA_FRAME;
+ }
+ if (segfeature_active(&cm->seg, segment_id, SEG_LVL_GLOBALMV)) {
+ return 1;
+ }
+ const int ctx = av1_get_intra_inter_context(xd);
+ FRAME_CONTEXT *ec_ctx = xd->tile_ctx;
+ const int is_inter =
+ aom_read_symbol(r, ec_ctx->intra_inter_cdf[ctx], 2, ACCT_STR);
+ return is_inter;
+}
+
+#if DEC_MISMATCH_DEBUG
+static void dec_dump_logs(AV1_COMMON *cm, MB_MODE_INFO *const mbmi, int mi_row,
+ int mi_col, int16_t mode_ctx) {
+ int_mv mv[2] = { { 0 } };
+ for (int ref = 0; ref < 1 + has_second_ref(mbmi); ++ref)
+ mv[ref].as_mv = mbmi->mv[ref].as_mv;
+
+ const int16_t newmv_ctx = mode_ctx & NEWMV_CTX_MASK;
+ int16_t zeromv_ctx = -1;
+ int16_t refmv_ctx = -1;
+ if (mbmi->mode != NEWMV) {
+ zeromv_ctx = (mode_ctx >> GLOBALMV_OFFSET) & GLOBALMV_CTX_MASK;
+ if (mbmi->mode != GLOBALMV)
+ refmv_ctx = (mode_ctx >> REFMV_OFFSET) & REFMV_CTX_MASK;
+ }
+
+#define FRAME_TO_CHECK 11
+ if (cm->current_frame.frame_number == FRAME_TO_CHECK && cm->show_frame == 1) {
+ printf(
+ "=== DECODER ===: "
+ "Frame=%d, (mi_row,mi_col)=(%d,%d), skip_mode=%d, mode=%d, bsize=%d, "
+ "show_frame=%d, mv[0]=(%d,%d), mv[1]=(%d,%d), ref[0]=%d, "
+ "ref[1]=%d, motion_mode=%d, mode_ctx=%d, "
+ "newmv_ctx=%d, zeromv_ctx=%d, refmv_ctx=%d, tx_size=%d\n",
+ cm->current_frame.frame_number, mi_row, mi_col, mbmi->skip_mode,
+ mbmi->mode, mbmi->sb_type, cm->show_frame, mv[0].as_mv.row,
+ mv[0].as_mv.col, mv[1].as_mv.row, mv[1].as_mv.col, mbmi->ref_frame[0],
+ mbmi->ref_frame[1], mbmi->motion_mode, mode_ctx, newmv_ctx, zeromv_ctx,
+ refmv_ctx, mbmi->tx_size);
+ }
+}
+#endif // DEC_MISMATCH_DEBUG
+
+static void read_inter_block_mode_info(AV1Decoder *const pbi,
+ DecoderCodingBlock *dcb,
+ MB_MODE_INFO *const mbmi,
+ aom_reader *r) {
+ AV1_COMMON *const cm = &pbi->common;
+ FeatureFlags *const features = &cm->features;
+ const BLOCK_SIZE bsize = mbmi->bsize;
+ const int allow_hp = features->allow_high_precision_mv;
+ int_mv nearestmv[2], nearmv[2];
+ int_mv ref_mvs[MODE_CTX_REF_FRAMES][MAX_MV_REF_CANDIDATES] = { { { 0 } } };
+ int16_t inter_mode_ctx[MODE_CTX_REF_FRAMES];
+ int pts[SAMPLES_ARRAY_SIZE], pts_inref[SAMPLES_ARRAY_SIZE];
+ MACROBLOCKD *const xd = &dcb->xd;
+ FRAME_CONTEXT *ec_ctx = xd->tile_ctx;
+
+ mbmi->uv_mode = UV_DC_PRED;
+ mbmi->palette_mode_info.palette_size[0] = 0;
+ mbmi->palette_mode_info.palette_size[1] = 0;
+
+ av1_collect_neighbors_ref_counts(xd);
+
+ read_ref_frames(cm, xd, r, mbmi->segment_id, mbmi->ref_frame);
+ const int is_compound = has_second_ref(mbmi);
+
+ const MV_REFERENCE_FRAME ref_frame = av1_ref_frame_type(mbmi->ref_frame);
+ av1_find_mv_refs(cm, xd, mbmi, ref_frame, dcb->ref_mv_count, xd->ref_mv_stack,
+ xd->weight, ref_mvs, /*global_mvs=*/NULL, inter_mode_ctx);
+
+ mbmi->ref_mv_idx = 0;
+
+ if (mbmi->skip_mode) {
+ assert(is_compound);
+ mbmi->mode = NEAREST_NEARESTMV;
+ } else {
+ if (segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_SKIP) ||
+ segfeature_active(&cm->seg, mbmi->segment_id, SEG_LVL_GLOBALMV)) {
+ mbmi->mode = GLOBALMV;
+ } else {
+ const int mode_ctx =
+ av1_mode_context_analyzer(inter_mode_ctx, mbmi->ref_frame);
+ if (is_compound)
+ mbmi->mode = read_inter_compound_mode(xd, r, mode_ctx);
+ else
+ mbmi->mode = read_inter_mode(ec_ctx, r, mode_ctx);
+ if (mbmi->mode == NEWMV || mbmi->mode == NEW_NEWMV ||
+ have_nearmv_in_inter_mode(mbmi->mode))
+ read_drl_idx(ec_ctx, dcb, mbmi, r);
+ }
+ }
+
+ if (is_compound != is_inter_compound_mode(mbmi->mode)) {
+ aom_internal_error(xd->error_info, AOM_CODEC_CORRUPT_FRAME,
+ "Prediction mode %d invalid with ref frame %d %d",
+ mbmi->mode, mbmi->ref_frame[0], mbmi->ref_frame[1]);
+ }
+
+ if (!is_compound && mbmi->mode != GLOBALMV) {
+ av1_find_best_ref_mvs(allow_hp, ref_mvs[mbmi->ref_frame[0]], &nearestmv[0],
+ &nearmv[0], features->cur_frame_force_integer_mv);
+ }
+
+ if (is_compound && mbmi->mode != GLOBAL_GLOBALMV) {
+ const int ref_mv_idx = mbmi->ref_mv_idx + 1;
+ nearestmv[0] = xd->ref_mv_stack[ref_frame][0].this_mv;
+ nearestmv[1] = xd->ref_mv_stack[ref_frame][0].comp_mv;
+ nearmv[0] = xd->ref_mv_stack[ref_frame][ref_mv_idx].this_mv;
+ nearmv[1] = xd->ref_mv_stack[ref_frame][ref_mv_idx].comp_mv;
+ lower_mv_precision(&nearestmv[0].as_mv, allow_hp,
+ features->cur_frame_force_integer_mv);
+ lower_mv_precision(&nearestmv[1].as_mv, allow_hp,
+ features->cur_frame_force_integer_mv);
+ lower_mv_precision(&nearmv[0].as_mv, allow_hp,
+ features->cur_frame_force_integer_mv);
+ lower_mv_precision(&nearmv[1].as_mv, allow_hp,
+ features->cur_frame_force_integer_mv);
+ } else if (mbmi->ref_mv_idx > 0 && mbmi->mode == NEARMV) {
+ nearmv[0] =
+ xd->ref_mv_stack[mbmi->ref_frame[0]][1 + mbmi->ref_mv_idx].this_mv;
+ }
+
+ int_mv ref_mv[2] = { nearestmv[0], nearestmv[1] };
+
+ if (is_compound) {
+ int ref_mv_idx = mbmi->ref_mv_idx;
+ // Special case: NEAR_NEWMV and NEW_NEARMV modes use
+ // 1 + mbmi->ref_mv_idx (like NEARMV) instead of
+ // mbmi->ref_mv_idx (like NEWMV)
+ if (mbmi->mode == NEAR_NEWMV || mbmi->mode == NEW_NEARMV)
+ ref_mv_idx = 1 + mbmi->ref_mv_idx;
+
+ // TODO(jingning, yunqing): Do we need a lower_mv_precision() call here?
+ if (compound_ref0_mode(mbmi->mode) == NEWMV)
+ ref_mv[0] = xd->ref_mv_stack[ref_frame][ref_mv_idx].this_mv;
+
+ if (compound_ref1_mode(mbmi->mode) == NEWMV)
+ ref_mv[1] = xd->ref_mv_stack[ref_frame][ref_mv_idx].comp_mv;
+ } else {
+ if (mbmi->mode == NEWMV) {
+ if (dcb->ref_mv_count[ref_frame] > 1)
+ ref_mv[0] = xd->ref_mv_stack[ref_frame][mbmi->ref_mv_idx].this_mv;
+ }
+ }
+
+ if (mbmi->skip_mode) assert(mbmi->mode == NEAREST_NEARESTMV);
+
+ const int mv_corrupted_flag =
+ !assign_mv(cm, xd, mbmi->mode, mbmi->ref_frame, mbmi->mv, ref_mv,
+ nearestmv, nearmv, is_compound, allow_hp, r);
+ aom_merge_corrupted_flag(&dcb->corrupted, mv_corrupted_flag);
+
+ mbmi->use_wedge_interintra = 0;
+ if (cm->seq_params->enable_interintra_compound && !mbmi->skip_mode &&
+ is_interintra_allowed(mbmi)) {
+ const int bsize_group = size_group_lookup[bsize];
+ const int interintra =
+ aom_read_symbol(r, ec_ctx->interintra_cdf[bsize_group], 2, ACCT_STR);
+ assert(mbmi->ref_frame[1] == NONE_FRAME);
+ if (interintra) {
+ const INTERINTRA_MODE interintra_mode =
+ read_interintra_mode(xd, r, bsize_group);
+ mbmi->ref_frame[1] = INTRA_FRAME;
+ mbmi->interintra_mode = interintra_mode;
+ mbmi->angle_delta[PLANE_TYPE_Y] = 0;
+ mbmi->angle_delta[PLANE_TYPE_UV] = 0;
+ mbmi->filter_intra_mode_info.use_filter_intra = 0;
+ if (av1_is_wedge_used(bsize)) {
+ mbmi->use_wedge_interintra = aom_read_symbol(
+ r, ec_ctx->wedge_interintra_cdf[bsize], 2, ACCT_STR);
+ if (mbmi->use_wedge_interintra) {
+ mbmi->interintra_wedge_index = (int8_t)aom_read_symbol(
+ r, ec_ctx->wedge_idx_cdf[bsize], MAX_WEDGE_TYPES, ACCT_STR);
+ }
+ }
+ }
+ }
+
+ for (int ref = 0; ref < 1 + has_second_ref(mbmi); ++ref) {
+ const MV_REFERENCE_FRAME frame = mbmi->ref_frame[ref];
+ xd->block_ref_scale_factors[ref] = get_ref_scale_factors_const(cm, frame);
+ }
+
+ mbmi->motion_mode = SIMPLE_TRANSLATION;
+ if (is_motion_variation_allowed_bsize(mbmi->bsize) && !mbmi->skip_mode &&
+ !has_second_ref(mbmi)) {
+ mbmi->num_proj_ref = av1_findSamples(cm, xd, pts, pts_inref);
+ }
+ av1_count_overlappable_neighbors(cm, xd);
+
+ if (mbmi->ref_frame[1] != INTRA_FRAME)
+ mbmi->motion_mode = read_motion_mode(cm, xd, mbmi, r);
+
+ // init
+ mbmi->comp_group_idx = 0;
+ mbmi->compound_idx = 1;
+ mbmi->interinter_comp.type = COMPOUND_AVERAGE;
+
+ if (has_second_ref(mbmi) && !mbmi->skip_mode) {
+ // Read idx to indicate current compound inter prediction mode group
+ const int masked_compound_used = is_any_masked_compound_used(bsize) &&
+ cm->seq_params->enable_masked_compound;
+
+ if (masked_compound_used) {
+ const int ctx_comp_group_idx = get_comp_group_idx_context(xd);
+ mbmi->comp_group_idx = (uint8_t)aom_read_symbol(
+ r, ec_ctx->comp_group_idx_cdf[ctx_comp_group_idx], 2, ACCT_STR);
+ }
+
+ if (mbmi->comp_group_idx == 0) {
+ if (cm->seq_params->order_hint_info.enable_dist_wtd_comp) {
+ const int comp_index_ctx = get_comp_index_context(cm, xd);
+ mbmi->compound_idx = (uint8_t)aom_read_symbol(
+ r, ec_ctx->compound_index_cdf[comp_index_ctx], 2, ACCT_STR);
+ mbmi->interinter_comp.type =
+ mbmi->compound_idx ? COMPOUND_AVERAGE : COMPOUND_DISTWTD;
+ } else {
+ // Distance-weighted compound is disabled, so always use average
+ mbmi->compound_idx = 1;
+ mbmi->interinter_comp.type = COMPOUND_AVERAGE;
+ }
+ } else {
+ assert(cm->current_frame.reference_mode != SINGLE_REFERENCE &&
+ is_inter_compound_mode(mbmi->mode) &&
+ mbmi->motion_mode == SIMPLE_TRANSLATION);
+ assert(masked_compound_used);
+
+ // compound_diffwtd, wedge
+ if (is_interinter_compound_used(COMPOUND_WEDGE, bsize)) {
+ mbmi->interinter_comp.type =
+ COMPOUND_WEDGE + aom_read_symbol(r,
+ ec_ctx->compound_type_cdf[bsize],
+ MASKED_COMPOUND_TYPES, ACCT_STR);
+ } else {
+ mbmi->interinter_comp.type = COMPOUND_DIFFWTD;
+ }
+
+ if (mbmi->interinter_comp.type == COMPOUND_WEDGE) {
+ assert(is_interinter_compound_used(COMPOUND_WEDGE, bsize));
+ mbmi->interinter_comp.wedge_index = (int8_t)aom_read_symbol(
+ r, ec_ctx->wedge_idx_cdf[bsize], MAX_WEDGE_TYPES, ACCT_STR);
+ mbmi->interinter_comp.wedge_sign = (int8_t)aom_read_bit(r, ACCT_STR);
+ } else {
+ assert(mbmi->interinter_comp.type == COMPOUND_DIFFWTD);
+ mbmi->interinter_comp.mask_type =
+ aom_read_literal(r, MAX_DIFFWTD_MASK_BITS, ACCT_STR);
+ }
+ }
+ }
+
+ read_mb_interp_filter(xd, features->interp_filter,
+ cm->seq_params->enable_dual_filter, mbmi, r);
+
+ if (mbmi->motion_mode == WARPED_CAUSAL) {
+ const int mi_row = xd->mi_row;
+ const int mi_col = xd->mi_col;
+ mbmi->wm_params.wmtype = DEFAULT_WMTYPE;
+ mbmi->wm_params.invalid = 0;
+
+ if (mbmi->num_proj_ref > 1) {
+ mbmi->num_proj_ref = av1_selectSamples(&mbmi->mv[0].as_mv, pts, pts_inref,
+ mbmi->num_proj_ref, bsize);
+ }
+
+ if (av1_find_projection(mbmi->num_proj_ref, pts, pts_inref, bsize,
+ mbmi->mv[0].as_mv.row, mbmi->mv[0].as_mv.col,
+ &mbmi->wm_params, mi_row, mi_col)) {
+#if WARPED_MOTION_DEBUG
+ printf("Warning: unexpected warped model from aomenc\n");
+#endif
+ mbmi->wm_params.invalid = 1;
+ }
+ }
+
+ xd->cfl.store_y = store_cfl_required(cm, xd);
+
+#if DEC_MISMATCH_DEBUG
+ dec_dump_logs(cm, mi, mi_row, mi_col, mode_ctx);
+#endif // DEC_MISMATCH_DEBUG
+}
+
+static void read_inter_frame_mode_info(AV1Decoder *const pbi,
+ DecoderCodingBlock *dcb, aom_reader *r) {
+ AV1_COMMON *const cm = &pbi->common;
+ MACROBLOCKD *const xd = &dcb->xd;
+ MB_MODE_INFO *const mbmi = xd->mi[0];
+ int inter_block = 1;
+
+ mbmi->mv[0].as_int = 0;
+ mbmi->mv[1].as_int = 0;
+ mbmi->segment_id = read_inter_segment_id(cm, xd, 1, r);
+
+ mbmi->skip_mode = read_skip_mode(cm, xd, mbmi->segment_id, r);
+
+ if (mbmi->skip_mode)
+ mbmi->skip_txfm = 1;
+ else
+ mbmi->skip_txfm = read_skip_txfm(cm, xd, mbmi->segment_id, r);
+
+ if (!cm->seg.segid_preskip)
+ mbmi->segment_id = read_inter_segment_id(cm, xd, 0, r);
+
+ read_cdef(cm, r, xd);
+
+ read_delta_q_params(cm, xd, r);
+
+ if (!mbmi->skip_mode)
+ inter_block = read_is_inter_block(cm, xd, mbmi->segment_id, r);
+
+ mbmi->current_qindex = xd->current_base_qindex;
+
+ xd->above_txfm_context =
+ cm->above_contexts.txfm[xd->tile.tile_row] + xd->mi_col;
+ xd->left_txfm_context =
+ xd->left_txfm_context_buffer + (xd->mi_row & MAX_MIB_MASK);
+
+ if (inter_block)
+ read_inter_block_mode_info(pbi, dcb, mbmi, r);
+ else
+ read_intra_block_mode_info(cm, xd, mbmi, r);
+}
+
+static void intra_copy_frame_mvs(AV1_COMMON *const cm, int mi_row, int mi_col,
+ int x_mis, int y_mis) {
+ const int frame_mvs_stride = ROUND_POWER_OF_TWO(cm->mi_params.mi_cols, 1);
+ MV_REF *frame_mvs =
+ cm->cur_frame->mvs + (mi_row >> 1) * frame_mvs_stride + (mi_col >> 1);
+ x_mis = ROUND_POWER_OF_TWO(x_mis, 1);
+ y_mis = ROUND_POWER_OF_TWO(y_mis, 1);
+
+ for (int h = 0; h < y_mis; h++) {
+ MV_REF *mv = frame_mvs;
+ for (int w = 0; w < x_mis; w++) {
+ mv->ref_frame = NONE_FRAME;
+ mv++;
+ }
+ frame_mvs += frame_mvs_stride;
+ }
+}
+
+void av1_read_mode_info(AV1Decoder *const pbi, DecoderCodingBlock *dcb,
+ aom_reader *r, int x_mis, int y_mis) {
+ AV1_COMMON *const cm = &pbi->common;
+ MACROBLOCKD *const xd = &dcb->xd;
+ MB_MODE_INFO *const mi = xd->mi[0];
+ mi->use_intrabc = 0;
+
+ if (frame_is_intra_only(cm)) {
+ read_intra_frame_mode_info(cm, dcb, r);
+ if (cm->seq_params->order_hint_info.enable_ref_frame_mvs)
+ intra_copy_frame_mvs(cm, xd->mi_row, xd->mi_col, x_mis, y_mis);
+ } else {
+ read_inter_frame_mode_info(pbi, dcb, r);
+ if (cm->seq_params->order_hint_info.enable_ref_frame_mvs)
+ av1_copy_frame_mvs(cm, mi, xd->mi_row, xd->mi_col, x_mis, y_mis);
+ }
+}
diff --git a/third_party/aom/av1/decoder/decodemv.h b/third_party/aom/av1/decoder/decodemv.h
new file mode 100644
index 0000000000..3d8629c9a5
--- /dev/null
+++ b/third_party/aom/av1/decoder/decodemv.h
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2016, Alliance for Open Media. All rights reserved
+ *
+ * This source code is subject to the terms of the BSD 2 Clause License and
+ * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
+ * was not distributed with this source code in the LICENSE file, you can
+ * obtain it at www.aomedia.org/license/software. If the Alliance for Open
+ * Media Patent License 1.0 was not distributed with this source code in the
+ * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
+ */
+
+#ifndef AOM_AV1_DECODER_DECODEMV_H_
+#define AOM_AV1_DECODER_DECODEMV_H_
+
+#include "aom_dsp/bitreader.h"
+
+#include "av1/decoder/decoder.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void av1_read_mode_info(AV1Decoder *const pbi, DecoderCodingBlock *dcb,
+ aom_reader *r, int x_mis, int y_mis);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+void av1_read_tx_type(const AV1_COMMON *const cm, MACROBLOCKD *xd, int blk_row,
+ int blk_col, TX_SIZE tx_size, aom_reader *r);
+
+#endif // AOM_AV1_DECODER_DECODEMV_H_
diff --git a/third_party/aom/av1/decoder/decoder.c b/third_party/aom/av1/decoder/decoder.c
new file mode 100644
index 0000000000..32e94840be
--- /dev/null
+++ b/third_party/aom/av1/decoder/decoder.c
@@ -0,0 +1,538 @@
+/*
+ * Copyright (c) 2016, Alliance for Open Media. All rights reserved
+ *
+ * This source code is subject to the terms of the BSD 2 Clause License and
+ * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
+ * was not distributed with this source code in the LICENSE file, you can
+ * obtain it at www.aomedia.org/license/software. If the Alliance for Open
+ * Media Patent License 1.0 was not distributed with this source code in the
+ * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
+ */
+
+#include <assert.h>
+#include <limits.h>
+#include <stdio.h>
+
+#include "config/av1_rtcd.h"
+#include "config/aom_dsp_rtcd.h"
+#include "config/aom_scale_rtcd.h"
+
+#include "aom_dsp/aom_dsp_common.h"
+#include "aom_mem/aom_mem.h"
+#include "aom_ports/aom_timer.h"
+#include "aom_scale/aom_scale.h"
+#include "aom_util/aom_thread.h"
+
+#include "av1/common/alloccommon.h"
+#include "av1/common/av1_common_int.h"
+#include "av1/common/av1_loopfilter.h"
+#include "av1/common/quant_common.h"
+#include "av1/common/reconinter.h"
+#include "av1/common/reconintra.h"
+
+#include "av1/decoder/decodeframe.h"
+#include "av1/decoder/decoder.h"
+#include "av1/decoder/detokenize.h"
+#include "av1/decoder/obu.h"
+
+static void initialize_dec(void) {
+ av1_rtcd();
+ aom_dsp_rtcd();
+ aom_scale_rtcd();
+ av1_init_intra_predictors();
+ av1_init_wedge_masks();
+}
+
+static void dec_set_mb_mi(CommonModeInfoParams *mi_params, int width,
+ int height, BLOCK_SIZE min_partition_size) {
+ (void)min_partition_size;
+ // Ensure that the decoded width and height are both multiples of
+ // 8 luma pixels (note: this may only be a multiple of 4 chroma pixels if
+ // subsampling is used).
+ // This simplifies the implementation of various experiments,
+ // eg. cdef, which operates on units of 8x8 luma pixels.
+ const int aligned_width = ALIGN_POWER_OF_TWO(width, 3);
+ const int aligned_height = ALIGN_POWER_OF_TWO(height, 3);
+
+ mi_params->mi_cols = aligned_width >> MI_SIZE_LOG2;
+ mi_params->mi_rows = aligned_height >> MI_SIZE_LOG2;
+ mi_params->mi_stride = calc_mi_size(mi_params->mi_cols);
+
+ mi_params->mb_cols = ROUND_POWER_OF_TWO(mi_params->mi_cols, 2);
+ mi_params->mb_rows = ROUND_POWER_OF_TWO(mi_params->mi_rows, 2);
+ mi_params->MBs = mi_params->mb_rows * mi_params->mb_cols;
+
+ mi_params->mi_alloc_bsize = BLOCK_4X4;
+ mi_params->mi_alloc_stride = mi_params->mi_stride;
+
+ assert(mi_size_wide[mi_params->mi_alloc_bsize] ==
+ mi_size_high[mi_params->mi_alloc_bsize]);
+}
+
+static void dec_setup_mi(CommonModeInfoParams *mi_params) {
+ const int mi_grid_size =
+ mi_params->mi_stride * calc_mi_size(mi_params->mi_rows);
+ memset(mi_params->mi_grid_base, 0,
+ mi_grid_size * sizeof(*mi_params->mi_grid_base));
+}
+
+static void dec_free_mi(CommonModeInfoParams *mi_params) {
+ aom_free(mi_params->mi_alloc);
+ mi_params->mi_alloc = NULL;
+ mi_params->mi_alloc_size = 0;
+ aom_free(mi_params->mi_grid_base);
+ mi_params->mi_grid_base = NULL;
+ mi_params->mi_grid_size = 0;
+ aom_free(mi_params->tx_type_map);
+ mi_params->tx_type_map = NULL;
+}
+
+AV1Decoder *av1_decoder_create(BufferPool *const pool) {
+ AV1Decoder *volatile const pbi = aom_memalign(32, sizeof(*pbi));
+ if (!pbi) return NULL;
+ av1_zero(*pbi);
+
+ AV1_COMMON *volatile const cm = &pbi->common;
+ cm->seq_params = &pbi->seq_params;
+ cm->error = &pbi->error;
+
+ // The jmp_buf is valid only for the duration of the function that calls
+ // setjmp(). Therefore, this function must reset the 'setjmp' field to 0
+ // before it returns.
+ if (setjmp(pbi->error.jmp)) {
+ pbi->error.setjmp = 0;
+ av1_decoder_remove(pbi);
+ return NULL;
+ }
+
+ pbi->error.setjmp = 1;
+
+ CHECK_MEM_ERROR(cm, cm->fc,
+ (FRAME_CONTEXT *)aom_memalign(32, sizeof(*cm->fc)));
+ CHECK_MEM_ERROR(
+ cm, cm->default_frame_context,
+ (FRAME_CONTEXT *)aom_memalign(32, sizeof(*cm->default_frame_context)));
+ memset(cm->fc, 0, sizeof(*cm->fc));
+ memset(cm->default_frame_context, 0, sizeof(*cm->default_frame_context));
+
+ pbi->need_resync = 1;
+ initialize_dec();
+
+ // Initialize the references to not point to any frame buffers.
+ for (int i = 0; i < REF_FRAMES; i++) {
+ cm->ref_frame_map[i] = NULL;
+ }
+
+ cm->current_frame.frame_number = 0;
+ pbi->decoding_first_frame = 1;
+ pbi->common.buffer_pool = pool;
+
+ cm->seq_params->bit_depth = AOM_BITS_8;
+
+ cm->mi_params.free_mi = dec_free_mi;
+ cm->mi_params.setup_mi = dec_setup_mi;
+ cm->mi_params.set_mb_mi = dec_set_mb_mi;
+
+ av1_loop_filter_init(cm);
+
+ av1_qm_init(&cm->quant_params, av1_num_planes(cm));
+ av1_loop_restoration_precal();
+
+#if CONFIG_ACCOUNTING
+ pbi->acct_enabled = 1;
+ aom_accounting_init(&pbi->accounting);
+#endif
+
+ pbi->error.setjmp = 0;
+
+ aom_get_worker_interface()->init(&pbi->lf_worker);
+ pbi->lf_worker.thread_name = "aom lf worker";
+
+ return pbi;
+}
+
+void av1_dealloc_dec_jobs(struct AV1DecTileMTData *tile_mt_info) {
+ if (tile_mt_info != NULL) {
+#if CONFIG_MULTITHREAD
+ if (tile_mt_info->job_mutex != NULL) {
+ pthread_mutex_destroy(tile_mt_info->job_mutex);
+ aom_free(tile_mt_info->job_mutex);
+ }
+#endif
+ aom_free(tile_mt_info->job_queue);
+ // clear the structure as the source of this call may be a resize in which
+ // case this call will be followed by an _alloc() which may fail.
+ av1_zero(*tile_mt_info);
+ }
+}
+
+void av1_dec_free_cb_buf(AV1Decoder *pbi) {
+ aom_free(pbi->cb_buffer_base);
+ pbi->cb_buffer_base = NULL;
+ pbi->cb_buffer_alloc_size = 0;
+}
+
+void av1_decoder_remove(AV1Decoder *pbi) {
+ int i;
+
+ if (!pbi) return;
+
+ // Free the tile list output buffer.
+ aom_free_frame_buffer(&pbi->tile_list_outbuf);
+
+ aom_get_worker_interface()->end(&pbi->lf_worker);
+ aom_free(pbi->lf_worker.data1);
+
+ if (pbi->thread_data) {
+ for (int worker_idx = 1; worker_idx < pbi->num_workers; worker_idx++) {
+ DecWorkerData *const thread_data = pbi->thread_data + worker_idx;
+ if (thread_data->td != NULL) {
+ av1_free_mc_tmp_buf(thread_data->td);
+ aom_free(thread_data->td);
+ }
+ }
+ aom_free(pbi->thread_data);
+ }
+ aom_free(pbi->dcb.xd.seg_mask);
+
+ for (i = 0; i < pbi->num_workers; ++i) {
+ AVxWorker *const worker = &pbi->tile_workers[i];
+ aom_get_worker_interface()->end(worker);
+ }
+#if CONFIG_MULTITHREAD
+ if (pbi->row_mt_mutex_ != NULL) {
+ pthread_mutex_destroy(pbi->row_mt_mutex_);
+ aom_free(pbi->row_mt_mutex_);
+ }
+ if (pbi->row_mt_cond_ != NULL) {
+ pthread_cond_destroy(pbi->row_mt_cond_);
+ aom_free(pbi->row_mt_cond_);
+ }
+#endif
+ for (i = 0; i < pbi->allocated_tiles; i++) {
+ TileDataDec *const tile_data = pbi->tile_data + i;
+ av1_dec_row_mt_dealloc(&tile_data->dec_row_mt_sync);
+ }
+ aom_free(pbi->tile_data);
+ aom_free(pbi->tile_workers);
+
+ if (pbi->num_workers > 0) {
+ av1_loop_filter_dealloc(&pbi->lf_row_sync);
+ av1_loop_restoration_dealloc(&pbi->lr_row_sync);
+ av1_dealloc_dec_jobs(&pbi->tile_mt_info);
+ }
+
+ av1_dec_free_cb_buf(pbi);
+#if CONFIG_ACCOUNTING
+ aom_accounting_clear(&pbi->accounting);
+#endif
+ av1_free_mc_tmp_buf(&pbi->td);
+ aom_img_metadata_array_free(pbi->metadata);
+ av1_remove_common(&pbi->common);
+ aom_free(pbi);
+}
+
+void av1_visit_palette(AV1Decoder *const pbi, MACROBLOCKD *const xd,
+ aom_reader *r, palette_visitor_fn_t visit) {
+ if (!is_inter_block(xd->mi[0])) {
+ for (int plane = 0; plane < AOMMIN(2, av1_num_planes(&pbi->common));
+ ++plane) {
+ if (plane == 0 || xd->is_chroma_ref) {
+ if (xd->mi[0]->palette_mode_info.palette_size[plane])
+ visit(xd, plane, r);
+ } else {
+ assert(xd->mi[0]->palette_mode_info.palette_size[plane] == 0);
+ }
+ }
+ }
+}
+
+static int equal_dimensions(const YV12_BUFFER_CONFIG *a,
+ const YV12_BUFFER_CONFIG *b) {
+ return a->y_height == b->y_height && a->y_width == b->y_width &&
+ a->uv_height == b->uv_height && a->uv_width == b->uv_width;
+}
+
+aom_codec_err_t av1_copy_reference_dec(AV1Decoder *pbi, int idx,
+ YV12_BUFFER_CONFIG *sd) {
+ AV1_COMMON *cm = &pbi->common;
+ const int num_planes = av1_num_planes(cm);
+
+ const YV12_BUFFER_CONFIG *const cfg = get_ref_frame(cm, idx);
+ if (cfg == NULL) {
+ aom_internal_error(&pbi->error, AOM_CODEC_ERROR, "No reference frame");
+ return AOM_CODEC_ERROR;
+ }
+ if (!equal_dimensions(cfg, sd))
+ aom_internal_error(&pbi->error, AOM_CODEC_ERROR,
+ "Incorrect buffer dimensions");
+ else
+ aom_yv12_copy_frame(cfg, sd, num_planes);
+
+ return pbi->error.error_code;
+}
+
+static int equal_dimensions_and_border(const YV12_BUFFER_CONFIG *a,
+ const YV12_BUFFER_CONFIG *b) {
+ return a->y_height == b->y_height && a->y_width == b->y_width &&
+ a->uv_height == b->uv_height && a->uv_width == b->uv_width &&
+ a->y_stride == b->y_stride && a->uv_stride == b->uv_stride &&
+ a->border == b->border &&
+ (a->flags & YV12_FLAG_HIGHBITDEPTH) ==
+ (b->flags & YV12_FLAG_HIGHBITDEPTH);
+}
+
+aom_codec_err_t av1_set_reference_dec(AV1_COMMON *cm, int idx,
+ int use_external_ref,
+ YV12_BUFFER_CONFIG *sd) {
+ const int num_planes = av1_num_planes(cm);
+ YV12_BUFFER_CONFIG *ref_buf = NULL;
+
+ // Get the destination reference buffer.
+ ref_buf = get_ref_frame(cm, idx);
+
+ if (ref_buf == NULL) {
+ aom_internal_error(cm->error, AOM_CODEC_ERROR, "No reference frame");
+ return AOM_CODEC_ERROR;
+ }
+
+ if (!use_external_ref) {
+ if (!equal_dimensions(ref_buf, sd)) {
+ aom_internal_error(cm->error, AOM_CODEC_ERROR,
+ "Incorrect buffer dimensions");
+ } else {
+ // Overwrite the reference frame buffer.
+ aom_yv12_copy_frame(sd, ref_buf, num_planes);
+ }
+ } else {
+ if (!equal_dimensions_and_border(ref_buf, sd)) {
+ aom_internal_error(cm->error, AOM_CODEC_ERROR,
+ "Incorrect buffer dimensions");
+ } else {
+ // Overwrite the reference frame buffer pointers.
+ // Once we no longer need the external reference buffer, these pointers
+ // are restored.
+ ref_buf->store_buf_adr[0] = ref_buf->y_buffer;
+ ref_buf->store_buf_adr[1] = ref_buf->u_buffer;
+ ref_buf->store_buf_adr[2] = ref_buf->v_buffer;
+ ref_buf->y_buffer = sd->y_buffer;
+ ref_buf->u_buffer = sd->u_buffer;
+ ref_buf->v_buffer = sd->v_buffer;
+ ref_buf->use_external_reference_buffers = 1;
+ }
+ }
+
+ return cm->error->error_code;
+}
+
+aom_codec_err_t av1_copy_new_frame_dec(AV1_COMMON *cm,
+ YV12_BUFFER_CONFIG *new_frame,
+ YV12_BUFFER_CONFIG *sd) {
+ const int num_planes = av1_num_planes(cm);
+
+ if (!equal_dimensions_and_border(new_frame, sd))
+ aom_internal_error(cm->error, AOM_CODEC_ERROR,
+ "Incorrect buffer dimensions");
+ else
+ aom_yv12_copy_frame(new_frame, sd, num_planes);
+
+ return cm->error->error_code;
+}
+
+static void release_current_frame(AV1Decoder *pbi) {
+ AV1_COMMON *const cm = &pbi->common;
+ BufferPool *const pool = cm->buffer_pool;
+
+ cm->cur_frame->buf.corrupted = 1;
+ lock_buffer_pool(pool);
+ decrease_ref_count(cm->cur_frame, pool);
+ unlock_buffer_pool(pool);
+ cm->cur_frame = NULL;
+}
+
+// If any buffer updating is signaled it should be done here.
+// Consumes a reference to cm->cur_frame.
+//
+// This functions returns void. It reports failure by setting
+// pbi->error.error_code.
+static void update_frame_buffers(AV1Decoder *pbi, int frame_decoded) {
+ int ref_index = 0, mask;
+ AV1_COMMON *const cm = &pbi->common;
+ BufferPool *const pool = cm->buffer_pool;
+
+ if (frame_decoded) {
+ lock_buffer_pool(pool);
+
+ // In ext-tile decoding, the camera frame header is only decoded once. So,
+ // we don't update the references here.
+ if (!pbi->camera_frame_header_ready) {
+ // The following for loop needs to release the reference stored in
+ // cm->ref_frame_map[ref_index] before storing a reference to
+ // cm->cur_frame in cm->ref_frame_map[ref_index].
+ for (mask = cm->current_frame.refresh_frame_flags; mask; mask >>= 1) {
+ if (mask & 1) {
+ decrease_ref_count(cm->ref_frame_map[ref_index], pool);
+ cm->ref_frame_map[ref_index] = cm->cur_frame;
+ ++cm->cur_frame->ref_count;
+ }
+ ++ref_index;
+ }
+ }
+
+ if (cm->show_existing_frame || cm->show_frame) {
+ if (pbi->output_all_layers) {
+ // Append this frame to the output queue
+ if (pbi->num_output_frames >= MAX_NUM_SPATIAL_LAYERS) {
+ // We can't store the new frame anywhere, so drop it and return an
+ // error
+ cm->cur_frame->buf.corrupted = 1;
+ decrease_ref_count(cm->cur_frame, pool);
+ pbi->error.error_code = AOM_CODEC_UNSUP_BITSTREAM;
+ } else {
+ pbi->output_frames[pbi->num_output_frames] = cm->cur_frame;
+ pbi->num_output_frames++;
+ }
+ } else {
+ // Replace any existing output frame
+ assert(pbi->num_output_frames == 0 || pbi->num_output_frames == 1);
+ if (pbi->num_output_frames > 0) {
+ decrease_ref_count(pbi->output_frames[0], pool);
+ }
+ pbi->output_frames[0] = cm->cur_frame;
+ pbi->num_output_frames = 1;
+ }
+ } else {
+ decrease_ref_count(cm->cur_frame, pool);
+ }
+
+ unlock_buffer_pool(pool);
+ } else {
+ // Nothing was decoded, so just drop this frame buffer
+ lock_buffer_pool(pool);
+ decrease_ref_count(cm->cur_frame, pool);
+ unlock_buffer_pool(pool);
+ }
+ cm->cur_frame = NULL;
+
+ if (!pbi->camera_frame_header_ready) {
+ // Invalidate these references until the next frame starts.
+ for (ref_index = 0; ref_index < INTER_REFS_PER_FRAME; ref_index++) {
+ cm->remapped_ref_idx[ref_index] = INVALID_IDX;
+ }
+ }
+}
+
+int av1_receive_compressed_data(AV1Decoder *pbi, size_t size,
+ const uint8_t **psource) {
+ AV1_COMMON *volatile const cm = &pbi->common;
+ const uint8_t *source = *psource;
+ pbi->error.error_code = AOM_CODEC_OK;
+ pbi->error.has_detail = 0;
+
+ if (size == 0) {
+ // This is used to signal that we are missing frames.
+ // We do not know if the missing frame(s) was supposed to update
+ // any of the reference buffers, but we act conservative and
+ // mark only the last buffer as corrupted.
+ //
+ // TODO(jkoleszar): Error concealment is undefined and non-normative
+ // at this point, but if it becomes so, [0] may not always be the correct
+ // thing to do here.
+ RefCntBuffer *ref_buf = get_ref_frame_buf(cm, LAST_FRAME);
+ if (ref_buf != NULL) ref_buf->buf.corrupted = 1;
+ }
+
+ if (assign_cur_frame_new_fb(cm) == NULL) {
+ pbi->error.error_code = AOM_CODEC_MEM_ERROR;
+ return 1;
+ }
+
+ // The jmp_buf is valid only for the duration of the function that calls
+ // setjmp(). Therefore, this function must reset the 'setjmp' field to 0
+ // before it returns.
+ if (setjmp(pbi->error.jmp)) {
+ const AVxWorkerInterface *const winterface = aom_get_worker_interface();
+ int i;
+
+ pbi->error.setjmp = 0;
+
+ // Synchronize all threads immediately as a subsequent decode call may
+ // cause a resize invalidating some allocations.
+ winterface->sync(&pbi->lf_worker);
+ for (i = 0; i < pbi->num_workers; ++i) {
+ winterface->sync(&pbi->tile_workers[i]);
+ }
+
+ release_current_frame(pbi);
+ return -1;
+ }
+
+ pbi->error.setjmp = 1;
+
+ int frame_decoded =
+ aom_decode_frame_from_obus(pbi, source, source + size, psource);
+
+ if (frame_decoded < 0) {
+ assert(pbi->error.error_code != AOM_CODEC_OK);
+ release_current_frame(pbi);
+ pbi->error.setjmp = 0;
+ return 1;
+ }
+
+#if TXCOEFF_TIMER
+ cm->cum_txcoeff_timer += cm->txcoeff_timer;
+ fprintf(stderr,
+ "txb coeff block number: %d, frame time: %ld, cum time %ld in us\n",
+ cm->txb_count, cm->txcoeff_timer, cm->cum_txcoeff_timer);
+ cm->txcoeff_timer = 0;
+ cm->txb_count = 0;
+#endif
+
+ // Note: At this point, this function holds a reference to cm->cur_frame
+ // in the buffer pool. This reference is consumed by update_frame_buffers().
+ update_frame_buffers(pbi, frame_decoded);
+
+ if (frame_decoded) {
+ pbi->decoding_first_frame = 0;
+ }
+
+ if (pbi->error.error_code != AOM_CODEC_OK) {
+ pbi->error.setjmp = 0;
+ return 1;
+ }
+
+ if (!cm->show_existing_frame) {
+ if (cm->seg.enabled) {
+ if (cm->prev_frame &&
+ (cm->mi_params.mi_rows == cm->prev_frame->mi_rows) &&
+ (cm->mi_params.mi_cols == cm->prev_frame->mi_cols)) {
+ cm->last_frame_seg_map = cm->prev_frame->seg_map;
+ } else {
+ cm->last_frame_seg_map = NULL;
+ }
+ }
+ }
+
+ // Update progress in frame parallel decode.
+ pbi->error.setjmp = 0;
+
+ return 0;
+}
+
+// Get the frame at a particular index in the output queue
+int av1_get_raw_frame(AV1Decoder *pbi, size_t index, YV12_BUFFER_CONFIG **sd,
+ aom_film_grain_t **grain_params) {
+ if (index >= pbi->num_output_frames) return -1;
+ *sd = &pbi->output_frames[index]->buf;
+ *grain_params = &pbi->output_frames[index]->film_grain_params;
+ return 0;
+}
+
+// Get the highest-spatial-layer output
+// TODO(rachelbarker): What should this do?
+int av1_get_frame_to_show(AV1Decoder *pbi, YV12_BUFFER_CONFIG *frame) {
+ if (pbi->num_output_frames == 0) return -1;
+
+ *frame = pbi->output_frames[pbi->num_output_frames - 1]->buf;
+ return 0;
+}
diff --git a/third_party/aom/av1/decoder/decoder.h b/third_party/aom/av1/decoder/decoder.h
new file mode 100644
index 0000000000..560b1d9f24
--- /dev/null
+++ b/third_party/aom/av1/decoder/decoder.h
@@ -0,0 +1,452 @@
+/*
+ * Copyright (c) 2016, Alliance for Open Media. All rights reserved
+ *
+ * This source code is subject to the terms of the BSD 2 Clause License and
+ * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
+ * was not distributed with this source code in the LICENSE file, you can
+ * obtain it at www.aomedia.org/license/software. If the Alliance for Open
+ * Media Patent License 1.0 was not distributed with this source code in the
+ * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
+ */
+
+#ifndef AOM_AV1_DECODER_DECODER_H_
+#define AOM_AV1_DECODER_DECODER_H_
+
+#include "config/aom_config.h"
+
+#include "aom/aom_codec.h"
+#include "aom_dsp/bitreader.h"
+#include "aom_scale/yv12config.h"
+#include "aom_util/aom_thread.h"
+
+#include "av1/common/av1_common_int.h"
+#include "av1/common/thread_common.h"
+#include "av1/decoder/dthread.h"
+#if CONFIG_ACCOUNTING
+#include "av1/decoder/accounting.h"
+#endif
+#if CONFIG_INSPECTION
+#include "av1/decoder/inspection.h"
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*!
+ * \brief Contains coding block data required by the decoder.
+ *
+ * This includes:
+ * - Coding block info that is common between encoder and decoder.
+ * - Other coding block info only needed by the decoder.
+ * Contrast this with a similar struct MACROBLOCK on encoder side.
+ * This data is also common between ThreadData and AV1Decoder structs.
+ */
+typedef struct DecoderCodingBlock {
+ /*!
+ * Coding block info that is common between encoder and decoder.
+ */
+ DECLARE_ALIGNED(32, MACROBLOCKD, xd);
+ /*!
+ * True if the at least one of the coding blocks decoded was corrupted.
+ */
+ int corrupted;
+ /*!
+ * Pointer to 'mc_buf' inside 'pbi->td' (single-threaded decoding) or
+ * 'pbi->thread_data[i].td' (multi-threaded decoding).
+ */
+ uint8_t *mc_buf[2];
+ /*!
+ * Pointer to 'dqcoeff' inside 'td->cb_buffer_base' or 'pbi->cb_buffer_base'
+ * with appropriate offset for the current superblock, for each plane.
+ */
+ tran_low_t *dqcoeff_block[MAX_MB_PLANE];
+ /*!
+ * cb_offset[p] is the offset into the dqcoeff_block[p] for the current coding
+ * block, for each plane 'p'.
+ */
+ uint16_t cb_offset[MAX_MB_PLANE];
+ /*!
+ * Pointer to 'eob_data' inside 'td->cb_buffer_base' or 'pbi->cb_buffer_base'
+ * with appropriate offset for the current superblock, for each plane.
+ */
+ eob_info *eob_data[MAX_MB_PLANE];
+ /*!
+ * txb_offset[p] is the offset into the eob_data[p] for the current coding
+ * block, for each plane 'p'.
+ */
+ uint16_t txb_offset[MAX_MB_PLANE];
+ /*!
+ * ref_mv_count[i] specifies the number of number of motion vector candidates
+ * in xd->ref_mv_stack[i].
+ */
+ uint8_t ref_mv_count[MODE_CTX_REF_FRAMES];
+} DecoderCodingBlock;
+
+/*!\cond */
+
+typedef void (*decode_block_visitor_fn_t)(const AV1_COMMON *const cm,
+ DecoderCodingBlock *dcb,
+ aom_reader *const r, const int plane,
+ const int row, const int col,
+ const TX_SIZE tx_size);
+
+typedef void (*predict_inter_block_visitor_fn_t)(AV1_COMMON *const cm,
+ DecoderCodingBlock *dcb,
+ BLOCK_SIZE bsize);
+
+typedef void (*cfl_store_inter_block_visitor_fn_t)(AV1_COMMON *const cm,
+ MACROBLOCKD *const xd);
+
+typedef struct ThreadData {
+ DecoderCodingBlock dcb;
+
+ // Coding block buffer for the current superblock.
+ // Used only for single-threaded decoding and multi-threaded decoding with
+ // row_mt == 1 cases.
+ // See also: similar buffer in 'AV1Decoder'.
+ CB_BUFFER cb_buffer_base;
+
+ aom_reader *bit_reader;
+
+ // Motion compensation buffer used to get a prediction buffer with extended
+ // borders. One buffer for each of the two possible references.
+ uint8_t *mc_buf[2];
+ // Mask for this block used for compound prediction.
+ uint8_t *seg_mask;
+ // Allocated size of 'mc_buf'.
+ int32_t mc_buf_size;
+ // If true, the pointers in 'mc_buf' were converted from highbd pointers.
+ int mc_buf_use_highbd; // Boolean: whether the byte pointers stored in
+ // mc_buf were converted from highbd pointers.
+
+ CONV_BUF_TYPE *tmp_conv_dst;
+ uint8_t *tmp_obmc_bufs[2];
+
+ decode_block_visitor_fn_t read_coeffs_tx_intra_block_visit;
+ decode_block_visitor_fn_t predict_and_recon_intra_block_visit;
+ decode_block_visitor_fn_t read_coeffs_tx_inter_block_visit;
+ decode_block_visitor_fn_t inverse_tx_inter_block_visit;
+ predict_inter_block_visitor_fn_t predict_inter_block_visit;
+ cfl_store_inter_block_visitor_fn_t cfl_store_inter_block_visit;
+} ThreadData;
+
+typedef struct AV1DecRowMTJobInfo {
+ int tile_row;
+ int tile_col;
+ int mi_row;
+} AV1DecRowMTJobInfo;
+
+typedef struct AV1DecRowMTSyncData {
+#if CONFIG_MULTITHREAD
+ pthread_mutex_t *mutex_;
+ pthread_cond_t *cond_;
+#endif
+ int allocated_sb_rows;
+ int *cur_sb_col;
+ // Denotes the superblock interval at which conditional signalling should
+ // happen. Also denotes the minimum number of extra superblocks of the top row
+ // to be complete to start decoding the current superblock. A value of 1
+ // indicates top-right dependency.
+ int sync_range;
+ // Denotes the additional number of superblocks in the previous row to be
+ // complete to start decoding the current superblock when intraBC tool is
+ // enabled. This additional top-right delay is required to satisfy the
+ // hardware constraints for intraBC tool when row multithreading is enabled.
+ int intrabc_extra_top_right_sb_delay;
+ int mi_rows;
+ int mi_cols;
+ int mi_rows_parse_done;
+ int mi_rows_decode_started;
+ int num_threads_working;
+} AV1DecRowMTSync;
+
+typedef struct AV1DecRowMTInfo {
+ int tile_rows_start;
+ int tile_rows_end;
+ int tile_cols_start;
+ int tile_cols_end;
+ int start_tile;
+ int end_tile;
+ int mi_rows_to_decode;
+
+ // Invariant:
+ // mi_rows_parse_done >= mi_rows_decode_started.
+ // mi_rows_parse_done and mi_rows_decode_started are both initialized to 0.
+ // mi_rows_parse_done is incremented freely. mi_rows_decode_started may only
+ // be incremented to catch up with mi_rows_parse_done but is not allowed to
+ // surpass mi_rows_parse_done.
+ //
+ // When mi_rows_decode_started reaches mi_rows_to_decode, there are no more
+ // decode jobs.
+
+ // Indicates the progress of the bit-stream parsing of superblocks.
+ // Initialized to 0. Incremented by sb_mi_size when parse sb row is done.
+ int mi_rows_parse_done;
+ // Indicates the progress of the decoding of superblocks.
+ // Initialized to 0. Incremented by sb_mi_size when decode sb row is started.
+ int mi_rows_decode_started;
+ // Boolean: Initialized to 0 (false). Set to 1 (true) on error to abort
+ // decoding.
+ int row_mt_exit;
+} AV1DecRowMTInfo;
+
+typedef struct TileDataDec {
+ TileInfo tile_info;
+ aom_reader bit_reader;
+ DECLARE_ALIGNED(16, FRAME_CONTEXT, tctx);
+ AV1DecRowMTSync dec_row_mt_sync;
+} TileDataDec;
+
+typedef struct TileBufferDec {
+ const uint8_t *data;
+ size_t size;
+} TileBufferDec;
+
+typedef struct DataBuffer {
+ const uint8_t *data;
+ size_t size;
+} DataBuffer;
+
+typedef struct EXTERNAL_REFERENCES {
+ YV12_BUFFER_CONFIG refs[MAX_EXTERNAL_REFERENCES];
+ int num;
+} EXTERNAL_REFERENCES;
+
+typedef struct TileJobsDec {
+ TileBufferDec *tile_buffer;
+ TileDataDec *tile_data;
+} TileJobsDec;
+
+typedef struct AV1DecTileMTData {
+#if CONFIG_MULTITHREAD
+ pthread_mutex_t *job_mutex;
+#endif
+ TileJobsDec *job_queue;
+ int jobs_enqueued;
+ int jobs_dequeued;
+ int alloc_tile_rows;
+ int alloc_tile_cols;
+} AV1DecTileMT;
+
+typedef struct AV1Decoder {
+ DecoderCodingBlock dcb;
+
+ DECLARE_ALIGNED(32, AV1_COMMON, common);
+
+ AVxWorker lf_worker;
+ AV1LfSync lf_row_sync;
+ AV1LrSync lr_row_sync;
+ AV1LrStruct lr_ctxt;
+ AV1CdefSync cdef_sync;
+ AV1CdefWorkerData *cdef_worker;
+ AVxWorker *tile_workers;
+ int num_workers;
+ DecWorkerData *thread_data;
+ ThreadData td;
+ TileDataDec *tile_data;
+ int allocated_tiles;
+
+ TileBufferDec tile_buffers[MAX_TILE_ROWS][MAX_TILE_COLS];
+ AV1DecTileMT tile_mt_info;
+
+ // Each time the decoder is called, we expect to receive a full temporal unit.
+ // This can contain up to one shown frame per spatial layer in the current
+ // operating point (note that some layers may be entirely omitted).
+ // If the 'output_all_layers' option is true, we save all of these shown
+ // frames so that they can be returned to the application. If the
+ // 'output_all_layers' option is false, then we only output one image per
+ // temporal unit.
+ //
+ // Note: The saved buffers are released at the start of the next time the
+ // application calls aom_codec_decode().
+ int output_all_layers;
+ RefCntBuffer *output_frames[MAX_NUM_SPATIAL_LAYERS];
+ size_t num_output_frames; // How many frames are queued up so far?
+
+ // In order to properly support random-access decoding, we need
+ // to behave slightly differently for the very first frame we decode.
+ // So we track whether this is the first frame or not.
+ int decoding_first_frame;
+
+ int allow_lowbitdepth;
+ int max_threads;
+ int inv_tile_order;
+ int need_resync; // wait for key/intra-only frame.
+ int reset_decoder_state;
+
+ int tile_size_bytes;
+ int tile_col_size_bytes;
+ int dec_tile_row, dec_tile_col; // always -1 for non-VR tile encoding
+#if CONFIG_ACCOUNTING
+ int acct_enabled;
+ Accounting accounting;
+#endif
+ int sequence_header_ready;
+ int sequence_header_changed;
+#if CONFIG_INSPECTION
+ aom_inspect_cb inspect_cb;
+ void *inspect_ctx;
+#endif
+ int operating_point;
+ int current_operating_point;
+ int seen_frame_header;
+ // The expected start_tile (tg_start syntax element) of the next tile group.
+ int next_start_tile;
+
+ // State if the camera frame header is already decoded while
+ // large_scale_tile = 1.
+ int camera_frame_header_ready;
+ size_t frame_header_size;
+ DataBuffer obu_size_hdr;
+ int output_frame_width_in_tiles_minus_1;
+ int output_frame_height_in_tiles_minus_1;
+ int tile_count_minus_1;
+ uint32_t coded_tile_data_size;
+ unsigned int ext_tile_debug; // for ext-tile software debug & testing
+
+ // Decoder has 3 modes of operation:
+ // (1) Single-threaded decoding.
+ // (2) Multi-threaded decoding with each tile decoded in parallel.
+ // (3) In addition to (2), each thread decodes 1 superblock row in parallel.
+ // row_mt = 1 triggers mode (3) above, while row_mt = 0, will trigger mode (1)
+ // or (2) depending on 'max_threads'.
+ unsigned int row_mt;
+
+ EXTERNAL_REFERENCES ext_refs;
+ YV12_BUFFER_CONFIG tile_list_outbuf;
+
+ // Coding block buffer for the current frame.
+ // Allocated and used only for multi-threaded decoding with 'row_mt == 0'.
+ // See also: similar buffer in 'ThreadData' struct.
+ CB_BUFFER *cb_buffer_base;
+ // Allocated size of 'cb_buffer_base'. Currently same as the number of
+ // superblocks in the coded frame.
+ int cb_buffer_alloc_size;
+
+ int allocated_row_mt_sync_rows;
+
+#if CONFIG_MULTITHREAD
+ pthread_mutex_t *row_mt_mutex_;
+ pthread_cond_t *row_mt_cond_;
+#endif
+
+ AV1DecRowMTInfo frame_row_mt_info;
+ aom_metadata_array_t *metadata;
+
+ int context_update_tile_id;
+ int skip_loop_filter;
+ int skip_film_grain;
+ int is_annexb;
+ int valid_for_referencing[REF_FRAMES];
+ int is_fwd_kf_present;
+ int is_arf_frame_present;
+ int num_tile_groups;
+ aom_s_frame_info sframe_info;
+
+ /*!
+ * Elements part of the sequence header, that are applicable for all the
+ * frames in the video.
+ */
+ SequenceHeader seq_params;
+
+ /*!
+ * If true, buffer removal times are present.
+ */
+ bool buffer_removal_time_present;
+
+ /*!
+ * Code and details about current error status.
+ */
+ struct aom_internal_error_info error;
+
+ /*!
+ * Number of temporal layers: may be > 1 for SVC (scalable vector coding).
+ */
+ unsigned int number_temporal_layers;
+
+ /*!
+ * Number of spatial layers: may be > 1 for SVC (scalable vector coding).
+ */
+ unsigned int number_spatial_layers;
+} AV1Decoder;
+
+// Returns 0 on success. Sets pbi->common.error.error_code to a nonzero error
+// code and returns a nonzero value on failure.
+int av1_receive_compressed_data(struct AV1Decoder *pbi, size_t size,
+ const uint8_t **psource);
+
+// Get the frame at a particular index in the output queue
+int av1_get_raw_frame(AV1Decoder *pbi, size_t index, YV12_BUFFER_CONFIG **sd,
+ aom_film_grain_t **grain_params);
+
+int av1_get_frame_to_show(struct AV1Decoder *pbi, YV12_BUFFER_CONFIG *frame);
+
+aom_codec_err_t av1_copy_reference_dec(struct AV1Decoder *pbi, int idx,
+ YV12_BUFFER_CONFIG *sd);
+
+aom_codec_err_t av1_set_reference_dec(AV1_COMMON *cm, int idx,
+ int use_external_ref,
+ YV12_BUFFER_CONFIG *sd);
+aom_codec_err_t av1_copy_new_frame_dec(AV1_COMMON *cm,
+ YV12_BUFFER_CONFIG *new_frame,
+ YV12_BUFFER_CONFIG *sd);
+
+struct AV1Decoder *av1_decoder_create(BufferPool *const pool);
+
+void av1_decoder_remove(struct AV1Decoder *pbi);
+void av1_dealloc_dec_jobs(struct AV1DecTileMTData *tile_mt_info);
+
+void av1_dec_row_mt_dealloc(AV1DecRowMTSync *dec_row_mt_sync);
+
+void av1_dec_free_cb_buf(AV1Decoder *pbi);
+
+static INLINE void decrease_ref_count(RefCntBuffer *const buf,
+ BufferPool *const pool) {
+ if (buf != NULL) {
+ --buf->ref_count;
+ // Reference counts should never become negative. If this assertion fails,
+ // there is a bug in our reference count management.
+ assert(buf->ref_count >= 0);
+ // A worker may only get a free framebuffer index when calling get_free_fb.
+ // But the raw frame buffer is not set up until we finish decoding header.
+ // So if any error happens during decoding header, frame_bufs[idx] will not
+ // have a valid raw frame buffer.
+ if (buf->ref_count == 0 && buf->raw_frame_buffer.data) {
+ pool->release_fb_cb(pool->cb_priv, &buf->raw_frame_buffer);
+ buf->raw_frame_buffer.data = NULL;
+ buf->raw_frame_buffer.size = 0;
+ buf->raw_frame_buffer.priv = NULL;
+ }
+ }
+}
+
+#define ACCT_STR __func__
+static INLINE int av1_read_uniform(aom_reader *r, int n) {
+ const int l = get_unsigned_bits(n);
+ const int m = (1 << l) - n;
+ const int v = aom_read_literal(r, l - 1, ACCT_STR);
+ assert(l != 0);
+ if (v < m)
+ return v;
+ else
+ return (v << 1) - m + aom_read_literal(r, 1, ACCT_STR);
+}
+
+typedef void (*palette_visitor_fn_t)(MACROBLOCKD *const xd, int plane,
+ aom_reader *r);
+
+void av1_visit_palette(AV1Decoder *const pbi, MACROBLOCKD *const xd,
+ aom_reader *r, palette_visitor_fn_t visit);
+
+typedef void (*block_visitor_fn_t)(AV1Decoder *const pbi, ThreadData *const td,
+ int mi_row, int mi_col, aom_reader *r,
+ PARTITION_TYPE partition, BLOCK_SIZE bsize);
+
+/*!\endcond */
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif // AOM_AV1_DECODER_DECODER_H_
diff --git a/third_party/aom/av1/decoder/decodetxb.c b/third_party/aom/av1/decoder/decodetxb.c
new file mode 100644
index 0000000000..dd5aa62001
--- /dev/null
+++ b/third_party/aom/av1/decoder/decodetxb.c
@@ -0,0 +1,381 @@
+/*
+ * Copyright (c) 2017, Alliance for Open Media. All rights reserved
+ *
+ * This source code is subject to the terms of the BSD 2 Clause License and
+ * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
+ * was not distributed with this source code in the LICENSE file, you can
+ * obtain it at www.aomedia.org/license/software. If the Alliance for Open
+ * Media Patent License 1.0 was not distributed with this source code in the
+ * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
+ */
+
+#include "av1/decoder/decodetxb.h"
+
+#include "aom_ports/mem.h"
+#include "av1/common/idct.h"
+#include "av1/common/scan.h"
+#include "av1/common/txb_common.h"
+#include "av1/decoder/decodemv.h"
+
+#define ACCT_STR __func__
+
+static int read_golomb(MACROBLOCKD *xd, aom_reader *r) {
+ int x = 1;
+ int length = 0;
+ int i = 0;
+
+ while (!i) {
+ i = aom_read_bit(r, ACCT_STR);
+ ++length;
+ if (length > 20) {
+ aom_internal_error(xd->error_info, AOM_CODEC_CORRUPT_FRAME,
+ "Invalid length in read_golomb");
+ break;
+ }
+ }
+
+ for (i = 0; i < length - 1; ++i) {
+ x <<= 1;
+ x += aom_read_bit(r, ACCT_STR);
+ }
+
+ return x - 1;
+}
+
+static INLINE int rec_eob_pos(const int eob_token, const int extra) {
+ int eob = av1_eob_group_start[eob_token];
+ if (eob > 2) {
+ eob += extra;
+ }
+ return eob;
+}
+
+static INLINE int get_dqv(const int16_t *dequant, int coeff_idx,
+ const qm_val_t *iqmatrix) {
+ int dqv = dequant[!!coeff_idx];
+ if (iqmatrix != NULL)
+ dqv =
+ ((iqmatrix[coeff_idx] * dqv) + (1 << (AOM_QM_BITS - 1))) >> AOM_QM_BITS;
+ return dqv;
+}
+
+static INLINE void read_coeffs_reverse_2d(aom_reader *r, TX_SIZE tx_size,
+ int start_si, int end_si,
+ const int16_t *scan, int bhl,
+ uint8_t *levels,
+ base_cdf_arr base_cdf,
+ br_cdf_arr br_cdf) {
+ for (int c = end_si; c >= start_si; --c) {
+ const int pos = scan[c];
+ const int coeff_ctx = get_lower_levels_ctx_2d(levels, pos, bhl, tx_size);
+ const int nsymbs = 4;
+ int level = aom_read_symbol(r, base_cdf[coeff_ctx], nsymbs, ACCT_STR);
+ if (level > NUM_BASE_LEVELS) {
+ const int br_ctx = get_br_ctx_2d(levels, pos, bhl);
+ aom_cdf_prob *cdf = br_cdf[br_ctx];
+ for (int idx = 0; idx < COEFF_BASE_RANGE; idx += BR_CDF_SIZE - 1) {
+ const int k = aom_read_symbol(r, cdf, BR_CDF_SIZE, ACCT_STR);
+ level += k;
+ if (k < BR_CDF_SIZE - 1) break;
+ }
+ }
+ levels[get_padded_idx(pos, bhl)] = level;
+ }
+}
+
+static INLINE void read_coeffs_reverse(aom_reader *r, TX_SIZE tx_size,
+ TX_CLASS tx_class, int start_si,
+ int end_si, const int16_t *scan, int bhl,
+ uint8_t *levels, base_cdf_arr base_cdf,
+ br_cdf_arr br_cdf) {
+ for (int c = end_si; c >= start_si; --c) {
+ const int pos = scan[c];
+ const int coeff_ctx =
+ get_lower_levels_ctx(levels, pos, bhl, tx_size, tx_class);
+ const int nsymbs = 4;
+ int level = aom_read_symbol(r, base_cdf[coeff_ctx], nsymbs, ACCT_STR);
+ if (level > NUM_BASE_LEVELS) {
+ const int br_ctx = get_br_ctx(levels, pos, bhl, tx_class);
+ aom_cdf_prob *cdf = br_cdf[br_ctx];
+ for (int idx = 0; idx < COEFF_BASE_RANGE; idx += BR_CDF_SIZE - 1) {
+ const int k = aom_read_symbol(r, cdf, BR_CDF_SIZE, ACCT_STR);
+ level += k;
+ if (k < BR_CDF_SIZE - 1) break;
+ }
+ }
+ levels[get_padded_idx(pos, bhl)] = level;
+ }
+}
+
+uint8_t av1_read_coeffs_txb(const AV1_COMMON *const cm, DecoderCodingBlock *dcb,
+ aom_reader *const r, const int blk_row,
+ const int blk_col, const int plane,
+ const TXB_CTX *const txb_ctx,
+ const TX_SIZE tx_size) {
+ MACROBLOCKD *const xd = &dcb->xd;
+ FRAME_CONTEXT *const ec_ctx = xd->tile_ctx;
+ const int32_t max_value = (1 << (7 + xd->bd)) - 1;
+ const int32_t min_value = -(1 << (7 + xd->bd));
+ const TX_SIZE txs_ctx = get_txsize_entropy_ctx(tx_size);
+ const PLANE_TYPE plane_type = get_plane_type(plane);
+ MB_MODE_INFO *const mbmi = xd->mi[0];
+ struct macroblockd_plane *const pd = &xd->plane[plane];
+ const int16_t *const dequant = pd->seg_dequant_QTX[mbmi->segment_id];
+ tran_low_t *const tcoeffs = dcb->dqcoeff_block[plane] + dcb->cb_offset[plane];
+ const int shift = av1_get_tx_scale(tx_size);
+ const int bhl = get_txb_bhl(tx_size);
+ const int width = get_txb_wide(tx_size);
+ const int height = get_txb_high(tx_size);
+ int cul_level = 0;
+ int dc_val = 0;
+ uint8_t levels_buf[TX_PAD_2D];
+ uint8_t *const levels = set_levels(levels_buf, height);
+ const int all_zero = aom_read_symbol(
+ r, ec_ctx->txb_skip_cdf[txs_ctx][txb_ctx->txb_skip_ctx], 2, ACCT_STR);
+ eob_info *eob_data = dcb->eob_data[plane] + dcb->txb_offset[plane];
+ uint16_t *const eob = &(eob_data->eob);
+ uint16_t *const max_scan_line = &(eob_data->max_scan_line);
+ *max_scan_line = 0;
+ *eob = 0;
+
+#if CONFIG_INSPECTION
+ if (plane == 0) {
+ const int txk_type_idx =
+ av1_get_txk_type_index(mbmi->bsize, blk_row, blk_col);
+ mbmi->tx_skip[txk_type_idx] = all_zero;
+ }
+#endif
+
+ if (all_zero) {
+ *max_scan_line = 0;
+ if (plane == 0) {
+ xd->tx_type_map[blk_row * xd->tx_type_map_stride + blk_col] = DCT_DCT;
+ }
+ return 0;
+ }
+
+ if (plane == AOM_PLANE_Y) {
+ // only y plane's tx_type is transmitted
+ av1_read_tx_type(cm, xd, blk_row, blk_col, tx_size, r);
+ }
+ const TX_TYPE tx_type =
+ av1_get_tx_type(xd, plane_type, blk_row, blk_col, tx_size,
+ cm->features.reduced_tx_set_used);
+ const TX_CLASS tx_class = tx_type_to_class[tx_type];
+ const qm_val_t *iqmatrix =
+ av1_get_iqmatrix(&cm->quant_params, xd, plane, tx_size, tx_type);
+ const SCAN_ORDER *const scan_order = get_scan(tx_size, tx_type);
+ const int16_t *const scan = scan_order->scan;
+ int eob_extra = 0;
+ int eob_pt = 1;
+
+ const int eob_multi_size = txsize_log2_minus4[tx_size];
+ const int eob_multi_ctx = (tx_class == TX_CLASS_2D) ? 0 : 1;
+ switch (eob_multi_size) {
+ case 0:
+ eob_pt =
+ aom_read_symbol(r, ec_ctx->eob_flag_cdf16[plane_type][eob_multi_ctx],
+ 5, ACCT_STR) +
+ 1;
+ break;
+ case 1:
+ eob_pt =
+ aom_read_symbol(r, ec_ctx->eob_flag_cdf32[plane_type][eob_multi_ctx],
+ 6, ACCT_STR) +
+ 1;
+ break;
+ case 2:
+ eob_pt =
+ aom_read_symbol(r, ec_ctx->eob_flag_cdf64[plane_type][eob_multi_ctx],
+ 7, ACCT_STR) +
+ 1;
+ break;
+ case 3:
+ eob_pt =
+ aom_read_symbol(r, ec_ctx->eob_flag_cdf128[plane_type][eob_multi_ctx],
+ 8, ACCT_STR) +
+ 1;
+ break;
+ case 4:
+ eob_pt =
+ aom_read_symbol(r, ec_ctx->eob_flag_cdf256[plane_type][eob_multi_ctx],
+ 9, ACCT_STR) +
+ 1;
+ break;
+ case 5:
+ eob_pt =
+ aom_read_symbol(r, ec_ctx->eob_flag_cdf512[plane_type][eob_multi_ctx],
+ 10, ACCT_STR) +
+ 1;
+ break;
+ case 6:
+ default:
+ eob_pt = aom_read_symbol(
+ r, ec_ctx->eob_flag_cdf1024[plane_type][eob_multi_ctx], 11,
+ ACCT_STR) +
+ 1;
+ break;
+ }
+
+ const int eob_offset_bits = av1_eob_offset_bits[eob_pt];
+ if (eob_offset_bits > 0) {
+ const int eob_ctx = eob_pt - 3;
+ int bit = aom_read_symbol(
+ r, ec_ctx->eob_extra_cdf[txs_ctx][plane_type][eob_ctx], 2, ACCT_STR);
+ if (bit) {
+ eob_extra += (1 << (eob_offset_bits - 1));
+ }
+
+ for (int i = 1; i < eob_offset_bits; i++) {
+ bit = aom_read_bit(r, ACCT_STR);
+ if (bit) {
+ eob_extra += (1 << (eob_offset_bits - 1 - i));
+ }
+ }
+ }
+ *eob = rec_eob_pos(eob_pt, eob_extra);
+
+ if (*eob > 1) {
+ memset(levels_buf, 0,
+ sizeof(*levels_buf) *
+ ((height + TX_PAD_HOR) * (width + TX_PAD_VER) + TX_PAD_END));
+ }
+
+ {
+ // Read the non-zero coefficient with scan index eob-1
+ // TODO(angiebird): Put this into a function
+ const int c = *eob - 1;
+ const int pos = scan[c];
+ const int coeff_ctx = get_lower_levels_ctx_eob(bhl, width, c);
+ const int nsymbs = 3;
+ aom_cdf_prob *cdf =
+ ec_ctx->coeff_base_eob_cdf[txs_ctx][plane_type][coeff_ctx];
+ int level = aom_read_symbol(r, cdf, nsymbs, ACCT_STR) + 1;
+ if (level > NUM_BASE_LEVELS) {
+ const int br_ctx = get_br_ctx_eob(pos, bhl, tx_class);
+ cdf = ec_ctx->coeff_br_cdf[AOMMIN(txs_ctx, TX_32X32)][plane_type][br_ctx];
+ for (int idx = 0; idx < COEFF_BASE_RANGE; idx += BR_CDF_SIZE - 1) {
+ const int k = aom_read_symbol(r, cdf, BR_CDF_SIZE, ACCT_STR);
+ level += k;
+ if (k < BR_CDF_SIZE - 1) break;
+ }
+ }
+ levels[get_padded_idx(pos, bhl)] = level;
+ }
+ if (*eob > 1) {
+ base_cdf_arr base_cdf = ec_ctx->coeff_base_cdf[txs_ctx][plane_type];
+ br_cdf_arr br_cdf =
+ ec_ctx->coeff_br_cdf[AOMMIN(txs_ctx, TX_32X32)][plane_type];
+ if (tx_class == TX_CLASS_2D) {
+ read_coeffs_reverse_2d(r, tx_size, 1, *eob - 1 - 1, scan, bhl, levels,
+ base_cdf, br_cdf);
+ read_coeffs_reverse(r, tx_size, tx_class, 0, 0, scan, bhl, levels,
+ base_cdf, br_cdf);
+ } else {
+ read_coeffs_reverse(r, tx_size, tx_class, 0, *eob - 1 - 1, scan, bhl,
+ levels, base_cdf, br_cdf);
+ }
+ }
+
+ for (int c = 0; c < *eob; ++c) {
+ const int pos = scan[c];
+ uint8_t sign;
+ tran_low_t level = levels[get_padded_idx(pos, bhl)];
+ if (level) {
+ *max_scan_line = AOMMAX(*max_scan_line, pos);
+ if (c == 0) {
+ const int dc_sign_ctx = txb_ctx->dc_sign_ctx;
+ sign = aom_read_symbol(r, ec_ctx->dc_sign_cdf[plane_type][dc_sign_ctx],
+ 2, ACCT_STR);
+ } else {
+ sign = aom_read_bit(r, ACCT_STR);
+ }
+ if (level >= MAX_BASE_BR_RANGE) {
+ level += read_golomb(xd, r);
+ }
+
+ if (c == 0) dc_val = sign ? -level : level;
+
+ // Bitmasking to clamp level to valid range:
+ // The valid range for 8/10/12 bit vdieo is at most 14/16/18 bit
+ level &= 0xfffff;
+ cul_level += level;
+ tran_low_t dq_coeff;
+ // Bitmasking to clamp dq_coeff to valid range:
+ // The valid range for 8/10/12 bit video is at most 17/19/21 bit
+ dq_coeff = (tran_low_t)(
+ (int64_t)level * get_dqv(dequant, scan[c], iqmatrix) & 0xffffff);
+ dq_coeff = dq_coeff >> shift;
+ if (sign) {
+ dq_coeff = -dq_coeff;
+ }
+ tcoeffs[pos] = clamp(dq_coeff, min_value, max_value);
+ }
+ }
+
+ cul_level = AOMMIN(COEFF_CONTEXT_MASK, cul_level);
+
+ // DC value
+ set_dc_sign(&cul_level, dc_val);
+
+ return cul_level;
+}
+
+void av1_read_coeffs_txb_facade(const AV1_COMMON *const cm,
+ DecoderCodingBlock *dcb, aom_reader *const r,
+ const int plane, const int row, const int col,
+ const TX_SIZE tx_size) {
+#if TXCOEFF_TIMER
+ struct aom_usec_timer timer;
+ aom_usec_timer_start(&timer);
+#endif
+ MACROBLOCKD *const xd = &dcb->xd;
+ MB_MODE_INFO *const mbmi = xd->mi[0];
+ struct macroblockd_plane *const pd = &xd->plane[plane];
+
+ const BLOCK_SIZE bsize = mbmi->bsize;
+ assert(bsize < BLOCK_SIZES_ALL);
+ const BLOCK_SIZE plane_bsize =
+ get_plane_block_size(bsize, pd->subsampling_x, pd->subsampling_y);
+
+ TXB_CTX txb_ctx;
+ get_txb_ctx(plane_bsize, tx_size, plane, pd->above_entropy_context + col,
+ pd->left_entropy_context + row, &txb_ctx);
+ const uint8_t cul_level =
+ av1_read_coeffs_txb(cm, dcb, r, row, col, plane, &txb_ctx, tx_size);
+ av1_set_entropy_contexts(xd, pd, plane, plane_bsize, tx_size, cul_level, col,
+ row);
+
+ if (is_inter_block(mbmi)) {
+ const PLANE_TYPE plane_type = get_plane_type(plane);
+ // tx_type will be read out in av1_read_coeffs_txb_facade
+ const TX_TYPE tx_type = av1_get_tx_type(xd, plane_type, row, col, tx_size,
+ cm->features.reduced_tx_set_used);
+
+ if (plane == 0) {
+ const int txw = tx_size_wide_unit[tx_size];
+ const int txh = tx_size_high_unit[tx_size];
+ // The 16x16 unit is due to the constraint from tx_64x64 which sets the
+ // maximum tx size for chroma as 32x32. Coupled with 4x1 transform block
+ // size, the constraint takes effect in 32x16 / 16x32 size too. To solve
+ // the intricacy, cover all the 16x16 units inside a 64 level transform.
+ if (txw == tx_size_wide_unit[TX_64X64] ||
+ txh == tx_size_high_unit[TX_64X64]) {
+ const int tx_unit = tx_size_wide_unit[TX_16X16];
+ const int stride = xd->tx_type_map_stride;
+ for (int idy = 0; idy < txh; idy += tx_unit) {
+ for (int idx = 0; idx < txw; idx += tx_unit) {
+ xd->tx_type_map[(row + idy) * stride + col + idx] = tx_type;
+ }
+ }
+ }
+ }
+ }
+
+#if TXCOEFF_TIMER
+ aom_usec_timer_mark(&timer);
+ const int64_t elapsed_time = aom_usec_timer_elapsed(&timer);
+ cm->txcoeff_timer += elapsed_time;
+ ++cm->txb_count;
+#endif
+}
diff --git a/third_party/aom/av1/decoder/decodetxb.h b/third_party/aom/av1/decoder/decodetxb.h
new file mode 100644
index 0000000000..fd34d40341
--- /dev/null
+++ b/third_party/aom/av1/decoder/decodetxb.h
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2017, Alliance for Open Media. All rights reserved
+ *
+ * This source code is subject to the terms of the BSD 2 Clause License and
+ * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
+ * was not distributed with this source code in the LICENSE file, you can
+ * obtain it at www.aomedia.org/license/software. If the Alliance for Open
+ * Media Patent License 1.0 was not distributed with this source code in the
+ * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
+ */
+
+#ifndef AOM_AV1_DECODER_DECODETXB_H_
+#define AOM_AV1_DECODER_DECODETXB_H_
+
+#include "av1/common/enums.h"
+
+struct aom_reader;
+struct AV1Common;
+struct DecoderCodingBlock;
+struct txb_ctx;
+
+uint8_t av1_read_coeffs_txb(const struct AV1Common *const cm,
+ struct DecoderCodingBlock *dcb,
+ struct aom_reader *const r, const int blk_row,
+ const int blk_col, const int plane,
+ const struct txb_ctx *const txb_ctx,
+ const TX_SIZE tx_size);
+
+void av1_read_coeffs_txb_facade(const struct AV1Common *const cm,
+ struct DecoderCodingBlock *dcb,
+ struct aom_reader *const r, const int plane,
+ const int row, const int col,
+ const TX_SIZE tx_size);
+#endif // AOM_AV1_DECODER_DECODETXB_H_
diff --git a/third_party/aom/av1/decoder/detokenize.c b/third_party/aom/av1/decoder/detokenize.c
new file mode 100644
index 0000000000..3c6a006eaf
--- /dev/null
+++ b/third_party/aom/av1/decoder/detokenize.c
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 2016, Alliance for Open Media. All rights reserved
+ *
+ * This source code is subject to the terms of the BSD 2 Clause License and
+ * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
+ * was not distributed with this source code in the LICENSE file, you can
+ * obtain it at www.aomedia.org/license/software. If the Alliance for Open
+ * Media Patent License 1.0 was not distributed with this source code in the
+ * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
+ */
+
+#include "config/aom_config.h"
+
+#include "aom_mem/aom_mem.h"
+#include "aom_ports/mem.h"
+#include "av1/common/blockd.h"
+#include "av1/decoder/detokenize.h"
+
+#define ACCT_STR __func__
+
+#include "av1/common/common.h"
+#include "av1/common/entropy.h"
+#include "av1/common/idct.h"
+
+static void decode_color_map_tokens(Av1ColorMapParam *param, aom_reader *r) {
+ uint8_t color_order[PALETTE_MAX_SIZE];
+ const int n = param->n_colors;
+ uint8_t *const color_map = param->color_map;
+ MapCdf color_map_cdf = param->map_cdf;
+ int plane_block_width = param->plane_width;
+ int plane_block_height = param->plane_height;
+ int rows = param->rows;
+ int cols = param->cols;
+
+ // The first color index.
+ color_map[0] = av1_read_uniform(r, n);
+ assert(color_map[0] < n);
+
+ // Run wavefront on the palette map index decoding.
+ for (int i = 1; i < rows + cols - 1; ++i) {
+ for (int j = AOMMIN(i, cols - 1); j >= AOMMAX(0, i - rows + 1); --j) {
+ const int color_ctx = av1_get_palette_color_index_context(
+ color_map, plane_block_width, (i - j), j, n, color_order, NULL);
+ const int color_idx = aom_read_symbol(
+ r, color_map_cdf[n - PALETTE_MIN_SIZE][color_ctx], n, ACCT_STR);
+ assert(color_idx >= 0 && color_idx < n);
+ color_map[(i - j) * plane_block_width + j] = color_order[color_idx];
+ }
+ }
+ // Copy last column to extra columns.
+ if (cols < plane_block_width) {
+ for (int i = 0; i < rows; ++i) {
+ memset(color_map + i * plane_block_width + cols,
+ color_map[i * plane_block_width + cols - 1],
+ (plane_block_width - cols));
+ }
+ }
+ // Copy last row to extra rows.
+ for (int i = rows; i < plane_block_height; ++i) {
+ memcpy(color_map + i * plane_block_width,
+ color_map + (rows - 1) * plane_block_width, plane_block_width);
+ }
+}
+
+void av1_decode_palette_tokens(MACROBLOCKD *const xd, int plane,
+ aom_reader *r) {
+ assert(plane == 0 || plane == 1);
+ Av1ColorMapParam params;
+ params.color_map =
+ xd->plane[plane].color_index_map + xd->color_index_map_offset[plane];
+ params.map_cdf = plane ? xd->tile_ctx->palette_uv_color_index_cdf
+ : xd->tile_ctx->palette_y_color_index_cdf;
+ const MB_MODE_INFO *const mbmi = xd->mi[0];
+ params.n_colors = mbmi->palette_mode_info.palette_size[plane];
+ av1_get_block_dimensions(mbmi->bsize, plane, xd, &params.plane_width,
+ &params.plane_height, &params.rows, &params.cols);
+ decode_color_map_tokens(&params, r);
+}
diff --git a/third_party/aom/av1/decoder/detokenize.h b/third_party/aom/av1/decoder/detokenize.h
new file mode 100644
index 0000000000..173b437a94
--- /dev/null
+++ b/third_party/aom/av1/decoder/detokenize.h
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2016, Alliance for Open Media. All rights reserved
+ *
+ * This source code is subject to the terms of the BSD 2 Clause License and
+ * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
+ * was not distributed with this source code in the LICENSE file, you can
+ * obtain it at www.aomedia.org/license/software. If the Alliance for Open
+ * Media Patent License 1.0 was not distributed with this source code in the
+ * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
+ */
+
+#ifndef AOM_AV1_DECODER_DETOKENIZE_H_
+#define AOM_AV1_DECODER_DETOKENIZE_H_
+
+#include "config/aom_config.h"
+
+#include "av1/common/scan.h"
+#include "av1/decoder/decoder.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void av1_decode_palette_tokens(MACROBLOCKD *const xd, int plane, aom_reader *r);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+#endif // AOM_AV1_DECODER_DETOKENIZE_H_
diff --git a/third_party/aom/av1/decoder/dthread.h b/third_party/aom/av1/decoder/dthread.h
new file mode 100644
index 0000000000..f82b9d8ccf
--- /dev/null
+++ b/third_party/aom/av1/decoder/dthread.h
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2016, Alliance for Open Media. All rights reserved
+ *
+ * This source code is subject to the terms of the BSD 2 Clause License and
+ * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
+ * was not distributed with this source code in the LICENSE file, you can
+ * obtain it at www.aomedia.org/license/software. If the Alliance for Open
+ * Media Patent License 1.0 was not distributed with this source code in the
+ * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
+ */
+
+#ifndef AOM_AV1_DECODER_DTHREAD_H_
+#define AOM_AV1_DECODER_DTHREAD_H_
+
+#include "config/aom_config.h"
+
+#include "aom_util/aom_thread.h"
+#include "aom/internal/aom_codec_internal.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct AV1Common;
+struct AV1Decoder;
+struct ThreadData;
+
+typedef struct DecWorkerData {
+ struct ThreadData *td;
+ const uint8_t *data_end;
+ struct aom_internal_error_info error_info;
+} DecWorkerData;
+
+// WorkerData for the FrameWorker thread. It contains all the information of
+// the worker and decode structures for decoding a frame.
+typedef struct FrameWorkerData {
+ struct AV1Decoder *pbi;
+ const uint8_t *data;
+ const uint8_t *data_end;
+ size_t data_size;
+ void *user_priv;
+ int received_frame;
+ int frame_context_ready; // Current frame's context is ready to read.
+ int frame_decoded; // Finished decoding current frame.
+} FrameWorkerData;
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif // AOM_AV1_DECODER_DTHREAD_H_
diff --git a/third_party/aom/av1/decoder/grain_synthesis.c b/third_party/aom/av1/decoder/grain_synthesis.c
new file mode 100644
index 0000000000..d276f6f90e
--- /dev/null
+++ b/third_party/aom/av1/decoder/grain_synthesis.c
@@ -0,0 +1,1461 @@
+/*
+ * Copyright (c) 2016, Alliance for Open Media. All rights reserved
+ *
+ * This source code is subject to the terms of the BSD 2 Clause License and
+ * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
+ * was not distributed with this source code in the LICENSE file, you can
+ * obtain it at www.aomedia.org/license/software. If the Alliance for Open
+ * Media Patent License 1.0 was not distributed with this source code in the
+ * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
+ */
+
+/*!\file
+ * \brief Describes film grain parameters and film grain synthesis
+ *
+ */
+
+#include <stdbool.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <assert.h>
+#include "aom_dsp/aom_dsp_common.h"
+#include "aom_mem/aom_mem.h"
+#include "av1/decoder/grain_synthesis.h"
+
+// Samples with Gaussian distribution in the range of [-2048, 2047] (12 bits)
+// with zero mean and standard deviation of about 512.
+// should be divided by 4 for 10-bit range and 16 for 8-bit range.
+static const int gaussian_sequence[2048] = {
+ 56, 568, -180, 172, 124, -84, 172, -64, -900, 24, 820,
+ 224, 1248, 996, 272, -8, -916, -388, -732, -104, -188, 800,
+ 112, -652, -320, -376, 140, -252, 492, -168, 44, -788, 588,
+ -584, 500, -228, 12, 680, 272, -476, 972, -100, 652, 368,
+ 432, -196, -720, -192, 1000, -332, 652, -136, -552, -604, -4,
+ 192, -220, -136, 1000, -52, 372, -96, -624, 124, -24, 396,
+ 540, -12, -104, 640, 464, 244, -208, -84, 368, -528, -740,
+ 248, -968, -848, 608, 376, -60, -292, -40, -156, 252, -292,
+ 248, 224, -280, 400, -244, 244, -60, 76, -80, 212, 532,
+ 340, 128, -36, 824, -352, -60, -264, -96, -612, 416, -704,
+ 220, -204, 640, -160, 1220, -408, 900, 336, 20, -336, -96,
+ -792, 304, 48, -28, -1232, -1172, -448, 104, -292, -520, 244,
+ 60, -948, 0, -708, 268, 108, 356, -548, 488, -344, -136,
+ 488, -196, -224, 656, -236, -1128, 60, 4, 140, 276, -676,
+ -376, 168, -108, 464, 8, 564, 64, 240, 308, -300, -400,
+ -456, -136, 56, 120, -408, -116, 436, 504, -232, 328, 844,
+ -164, -84, 784, -168, 232, -224, 348, -376, 128, 568, 96,
+ -1244, -288, 276, 848, 832, -360, 656, 464, -384, -332, -356,
+ 728, -388, 160, -192, 468, 296, 224, 140, -776, -100, 280,
+ 4, 196, 44, -36, -648, 932, 16, 1428, 28, 528, 808,
+ 772, 20, 268, 88, -332, -284, 124, -384, -448, 208, -228,
+ -1044, -328, 660, 380, -148, -300, 588, 240, 540, 28, 136,
+ -88, -436, 256, 296, -1000, 1400, 0, -48, 1056, -136, 264,
+ -528, -1108, 632, -484, -592, -344, 796, 124, -668, -768, 388,
+ 1296, -232, -188, -200, -288, -4, 308, 100, -168, 256, -500,
+ 204, -508, 648, -136, 372, -272, -120, -1004, -552, -548, -384,
+ 548, -296, 428, -108, -8, -912, -324, -224, -88, -112, -220,
+ -100, 996, -796, 548, 360, -216, 180, 428, -200, -212, 148,
+ 96, 148, 284, 216, -412, -320, 120, -300, -384, -604, -572,
+ -332, -8, -180, -176, 696, 116, -88, 628, 76, 44, -516,
+ 240, -208, -40, 100, -592, 344, -308, -452, -228, 20, 916,
+ -1752, -136, -340, -804, 140, 40, 512, 340, 248, 184, -492,
+ 896, -156, 932, -628, 328, -688, -448, -616, -752, -100, 560,
+ -1020, 180, -800, -64, 76, 576, 1068, 396, 660, 552, -108,
+ -28, 320, -628, 312, -92, -92, -472, 268, 16, 560, 516,
+ -672, -52, 492, -100, 260, 384, 284, 292, 304, -148, 88,
+ -152, 1012, 1064, -228, 164, -376, -684, 592, -392, 156, 196,
+ -524, -64, -884, 160, -176, 636, 648, 404, -396, -436, 864,
+ 424, -728, 988, -604, 904, -592, 296, -224, 536, -176, -920,
+ 436, -48, 1176, -884, 416, -776, -824, -884, 524, -548, -564,
+ -68, -164, -96, 692, 364, -692, -1012, -68, 260, -480, 876,
+ -1116, 452, -332, -352, 892, -1088, 1220, -676, 12, -292, 244,
+ 496, 372, -32, 280, 200, 112, -440, -96, 24, -644, -184,
+ 56, -432, 224, -980, 272, -260, 144, -436, 420, 356, 364,
+ -528, 76, 172, -744, -368, 404, -752, -416, 684, -688, 72,
+ 540, 416, 92, 444, 480, -72, -1416, 164, -1172, -68, 24,
+ 424, 264, 1040, 128, -912, -524, -356, 64, 876, -12, 4,
+ -88, 532, 272, -524, 320, 276, -508, 940, 24, -400, -120,
+ 756, 60, 236, -412, 100, 376, -484, 400, -100, -740, -108,
+ -260, 328, -268, 224, -200, -416, 184, -604, -564, -20, 296,
+ 60, 892, -888, 60, 164, 68, -760, 216, -296, 904, -336,
+ -28, 404, -356, -568, -208, -1480, -512, 296, 328, -360, -164,
+ -1560, -776, 1156, -428, 164, -504, -112, 120, -216, -148, -264,
+ 308, 32, 64, -72, 72, 116, 176, -64, -272, 460, -536,
+ -784, -280, 348, 108, -752, -132, 524, -540, -776, 116, -296,
+ -1196, -288, -560, 1040, -472, 116, -848, -1116, 116, 636, 696,
+ 284, -176, 1016, 204, -864, -648, -248, 356, 972, -584, -204,
+ 264, 880, 528, -24, -184, 116, 448, -144, 828, 524, 212,
+ -212, 52, 12, 200, 268, -488, -404, -880, 824, -672, -40,
+ 908, -248, 500, 716, -576, 492, -576, 16, 720, -108, 384,
+ 124, 344, 280, 576, -500, 252, 104, -308, 196, -188, -8,
+ 1268, 296, 1032, -1196, 436, 316, 372, -432, -200, -660, 704,
+ -224, 596, -132, 268, 32, -452, 884, 104, -1008, 424, -1348,
+ -280, 4, -1168, 368, 476, 696, 300, -8, 24, 180, -592,
+ -196, 388, 304, 500, 724, -160, 244, -84, 272, -256, -420,
+ 320, 208, -144, -156, 156, 364, 452, 28, 540, 316, 220,
+ -644, -248, 464, 72, 360, 32, -388, 496, -680, -48, 208,
+ -116, -408, 60, -604, -392, 548, -840, 784, -460, 656, -544,
+ -388, -264, 908, -800, -628, -612, -568, 572, -220, 164, 288,
+ -16, -308, 308, -112, -636, -760, 280, -668, 432, 364, 240,
+ -196, 604, 340, 384, 196, 592, -44, -500, 432, -580, -132,
+ 636, -76, 392, 4, -412, 540, 508, 328, -356, -36, 16,
+ -220, -64, -248, -60, 24, -192, 368, 1040, 92, -24, -1044,
+ -32, 40, 104, 148, 192, -136, -520, 56, -816, -224, 732,
+ 392, 356, 212, -80, -424, -1008, -324, 588, -1496, 576, 460,
+ -816, -848, 56, -580, -92, -1372, -112, -496, 200, 364, 52,
+ -140, 48, -48, -60, 84, 72, 40, 132, -356, -268, -104,
+ -284, -404, 732, -520, 164, -304, -540, 120, 328, -76, -460,
+ 756, 388, 588, 236, -436, -72, -176, -404, -316, -148, 716,
+ -604, 404, -72, -88, -888, -68, 944, 88, -220, -344, 960,
+ 472, 460, -232, 704, 120, 832, -228, 692, -508, 132, -476,
+ 844, -748, -364, -44, 1116, -1104, -1056, 76, 428, 552, -692,
+ 60, 356, 96, -384, -188, -612, -576, 736, 508, 892, 352,
+ -1132, 504, -24, -352, 324, 332, -600, -312, 292, 508, -144,
+ -8, 484, 48, 284, -260, -240, 256, -100, -292, -204, -44,
+ 472, -204, 908, -188, -1000, -256, 92, 1164, -392, 564, 356,
+ 652, -28, -884, 256, 484, -192, 760, -176, 376, -524, -452,
+ -436, 860, -736, 212, 124, 504, -476, 468, 76, -472, 552,
+ -692, -944, -620, 740, -240, 400, 132, 20, 192, -196, 264,
+ -668, -1012, -60, 296, -316, -828, 76, -156, 284, -768, -448,
+ -832, 148, 248, 652, 616, 1236, 288, -328, -400, -124, 588,
+ 220, 520, -696, 1032, 768, -740, -92, -272, 296, 448, -464,
+ 412, -200, 392, 440, -200, 264, -152, -260, 320, 1032, 216,
+ 320, -8, -64, 156, -1016, 1084, 1172, 536, 484, -432, 132,
+ 372, -52, -256, 84, 116, -352, 48, 116, 304, -384, 412,
+ 924, -300, 528, 628, 180, 648, 44, -980, -220, 1320, 48,
+ 332, 748, 524, -268, -720, 540, -276, 564, -344, -208, -196,
+ 436, 896, 88, -392, 132, 80, -964, -288, 568, 56, -48,
+ -456, 888, 8, 552, -156, -292, 948, 288, 128, -716, -292,
+ 1192, -152, 876, 352, -600, -260, -812, -468, -28, -120, -32,
+ -44, 1284, 496, 192, 464, 312, -76, -516, -380, -456, -1012,
+ -48, 308, -156, 36, 492, -156, -808, 188, 1652, 68, -120,
+ -116, 316, 160, -140, 352, 808, -416, 592, 316, -480, 56,
+ 528, -204, -568, 372, -232, 752, -344, 744, -4, 324, -416,
+ -600, 768, 268, -248, -88, -132, -420, -432, 80, -288, 404,
+ -316, -1216, -588, 520, -108, 92, -320, 368, -480, -216, -92,
+ 1688, -300, 180, 1020, -176, 820, -68, -228, -260, 436, -904,
+ 20, 40, -508, 440, -736, 312, 332, 204, 760, -372, 728,
+ 96, -20, -632, -520, -560, 336, 1076, -64, -532, 776, 584,
+ 192, 396, -728, -520, 276, -188, 80, -52, -612, -252, -48,
+ 648, 212, -688, 228, -52, -260, 428, -412, -272, -404, 180,
+ 816, -796, 48, 152, 484, -88, -216, 988, 696, 188, -528,
+ 648, -116, -180, 316, 476, 12, -564, 96, 476, -252, -364,
+ -376, -392, 556, -256, -576, 260, -352, 120, -16, -136, -260,
+ -492, 72, 556, 660, 580, 616, 772, 436, 424, -32, -324,
+ -1268, 416, -324, -80, 920, 160, 228, 724, 32, -516, 64,
+ 384, 68, -128, 136, 240, 248, -204, -68, 252, -932, -120,
+ -480, -628, -84, 192, 852, -404, -288, -132, 204, 100, 168,
+ -68, -196, -868, 460, 1080, 380, -80, 244, 0, 484, -888,
+ 64, 184, 352, 600, 460, 164, 604, -196, 320, -64, 588,
+ -184, 228, 12, 372, 48, -848, -344, 224, 208, -200, 484,
+ 128, -20, 272, -468, -840, 384, 256, -720, -520, -464, -580,
+ 112, -120, 644, -356, -208, -608, -528, 704, 560, -424, 392,
+ 828, 40, 84, 200, -152, 0, -144, 584, 280, -120, 80,
+ -556, -972, -196, -472, 724, 80, 168, -32, 88, 160, -688,
+ 0, 160, 356, 372, -776, 740, -128, 676, -248, -480, 4,
+ -364, 96, 544, 232, -1032, 956, 236, 356, 20, -40, 300,
+ 24, -676, -596, 132, 1120, -104, 532, -1096, 568, 648, 444,
+ 508, 380, 188, -376, -604, 1488, 424, 24, 756, -220, -192,
+ 716, 120, 920, 688, 168, 44, -460, 568, 284, 1144, 1160,
+ 600, 424, 888, 656, -356, -320, 220, 316, -176, -724, -188,
+ -816, -628, -348, -228, -380, 1012, -452, -660, 736, 928, 404,
+ -696, -72, -268, -892, 128, 184, -344, -780, 360, 336, 400,
+ 344, 428, 548, -112, 136, -228, -216, -820, -516, 340, 92,
+ -136, 116, -300, 376, -244, 100, -316, -520, -284, -12, 824,
+ 164, -548, -180, -128, 116, -924, -828, 268, -368, -580, 620,
+ 192, 160, 0, -1676, 1068, 424, -56, -360, 468, -156, 720,
+ 288, -528, 556, -364, 548, -148, 504, 316, 152, -648, -620,
+ -684, -24, -376, -384, -108, -920, -1032, 768, 180, -264, -508,
+ -1268, -260, -60, 300, -240, 988, 724, -376, -576, -212, -736,
+ 556, 192, 1092, -620, -880, 376, -56, -4, -216, -32, 836,
+ 268, 396, 1332, 864, -600, 100, 56, -412, -92, 356, 180,
+ 884, -468, -436, 292, -388, -804, -704, -840, 368, -348, 140,
+ -724, 1536, 940, 372, 112, -372, 436, -480, 1136, 296, -32,
+ -228, 132, -48, -220, 868, -1016, -60, -1044, -464, 328, 916,
+ 244, 12, -736, -296, 360, 468, -376, -108, -92, 788, 368,
+ -56, 544, 400, -672, -420, 728, 16, 320, 44, -284, -380,
+ -796, 488, 132, 204, -596, -372, 88, -152, -908, -636, -572,
+ -624, -116, -692, -200, -56, 276, -88, 484, -324, 948, 864,
+ 1000, -456, -184, -276, 292, -296, 156, 676, 320, 160, 908,
+ -84, -1236, -288, -116, 260, -372, -644, 732, -756, -96, 84,
+ 344, -520, 348, -688, 240, -84, 216, -1044, -136, -676, -396,
+ -1500, 960, -40, 176, 168, 1516, 420, -504, -344, -364, -360,
+ 1216, -940, -380, -212, 252, -660, -708, 484, -444, -152, 928,
+ -120, 1112, 476, -260, 560, -148, -344, 108, -196, 228, -288,
+ 504, 560, -328, -88, 288, -1008, 460, -228, 468, -836, -196,
+ 76, 388, 232, 412, -1168, -716, -644, 756, -172, -356, -504,
+ 116, 432, 528, 48, 476, -168, -608, 448, 160, -532, -272,
+ 28, -676, -12, 828, 980, 456, 520, 104, -104, 256, -344,
+ -4, -28, -368, -52, -524, -572, -556, -200, 768, 1124, -208,
+ -512, 176, 232, 248, -148, -888, 604, -600, -304, 804, -156,
+ -212, 488, -192, -804, -256, 368, -360, -916, -328, 228, -240,
+ -448, -472, 856, -556, -364, 572, -12, -156, -368, -340, 432,
+ 252, -752, -152, 288, 268, -580, -848, -592, 108, -76, 244,
+ 312, -716, 592, -80, 436, 360, 4, -248, 160, 516, 584,
+ 732, 44, -468, -280, -292, -156, -588, 28, 308, 912, 24,
+ 124, 156, 180, -252, 944, -924, -772, -520, -428, -624, 300,
+ -212, -1144, 32, -724, 800, -1128, -212, -1288, -848, 180, -416,
+ 440, 192, -576, -792, -76, -1080, 80, -532, -352, -132, 380,
+ -820, 148, 1112, 128, 164, 456, 700, -924, 144, -668, -384,
+ 648, -832, 508, 552, -52, -100, -656, 208, -568, 748, -88,
+ 680, 232, 300, 192, -408, -1012, -152, -252, -268, 272, -876,
+ -664, -648, -332, -136, 16, 12, 1152, -28, 332, -536, 320,
+ -672, -460, -316, 532, -260, 228, -40, 1052, -816, 180, 88,
+ -496, -556, -672, -368, 428, 92, 356, 404, -408, 252, 196,
+ -176, -556, 792, 268, 32, 372, 40, 96, -332, 328, 120,
+ 372, -900, -40, 472, -264, -592, 952, 128, 656, 112, 664,
+ -232, 420, 4, -344, -464, 556, 244, -416, -32, 252, 0,
+ -412, 188, -696, 508, -476, 324, -1096, 656, -312, 560, 264,
+ -136, 304, 160, -64, -580, 248, 336, -720, 560, -348, -288,
+ -276, -196, -500, 852, -544, -236, -1128, -992, -776, 116, 56,
+ 52, 860, 884, 212, -12, 168, 1020, 512, -552, 924, -148,
+ 716, 188, 164, -340, -520, -184, 880, -152, -680, -208, -1156,
+ -300, -528, -472, 364, 100, -744, -1056, -32, 540, 280, 144,
+ -676, -32, -232, -280, -224, 96, 568, -76, 172, 148, 148,
+ 104, 32, -296, -32, 788, -80, 32, -16, 280, 288, 944,
+ 428, -484
+};
+
+static const int gauss_bits = 11;
+
+static int luma_subblock_size_y = 32;
+static int luma_subblock_size_x = 32;
+
+static int chroma_subblock_size_y = 16;
+static int chroma_subblock_size_x = 16;
+
+static const int min_luma_legal_range = 16;
+static const int max_luma_legal_range = 235;
+
+static const int min_chroma_legal_range = 16;
+static const int max_chroma_legal_range = 240;
+
+static int scaling_lut_y[256];
+static int scaling_lut_cb[256];
+static int scaling_lut_cr[256];
+
+static int grain_min;
+static int grain_max;
+
+static uint16_t random_register = 0; // random number generator register
+
+static void dealloc_arrays(const aom_film_grain_t *params, int ***pred_pos_luma,
+ int ***pred_pos_chroma, int **luma_grain_block,
+ int **cb_grain_block, int **cr_grain_block,
+ int **y_line_buf, int **cb_line_buf,
+ int **cr_line_buf, int **y_col_buf, int **cb_col_buf,
+ int **cr_col_buf) {
+ int num_pos_luma = 2 * params->ar_coeff_lag * (params->ar_coeff_lag + 1);
+ int num_pos_chroma = num_pos_luma;
+ if (params->num_y_points > 0) ++num_pos_chroma;
+
+ if (*pred_pos_luma) {
+ for (int row = 0; row < num_pos_luma; row++) {
+ aom_free((*pred_pos_luma)[row]);
+ }
+ aom_free(*pred_pos_luma);
+ *pred_pos_luma = NULL;
+ }
+
+ if (*pred_pos_chroma) {
+ for (int row = 0; row < num_pos_chroma; row++) {
+ aom_free((*pred_pos_chroma)[row]);
+ }
+ aom_free(*pred_pos_chroma);
+ *pred_pos_chroma = NULL;
+ }
+
+ aom_free(*y_line_buf);
+ *y_line_buf = NULL;
+
+ aom_free(*cb_line_buf);
+ *cb_line_buf = NULL;
+
+ aom_free(*cr_line_buf);
+ *cr_line_buf = NULL;
+
+ aom_free(*y_col_buf);
+ *y_col_buf = NULL;
+
+ aom_free(*cb_col_buf);
+ *cb_col_buf = NULL;
+
+ aom_free(*cr_col_buf);
+ *cr_col_buf = NULL;
+
+ aom_free(*luma_grain_block);
+ *luma_grain_block = NULL;
+
+ aom_free(*cb_grain_block);
+ *cb_grain_block = NULL;
+
+ aom_free(*cr_grain_block);
+ *cr_grain_block = NULL;
+}
+
+static bool init_arrays(const aom_film_grain_t *params, int luma_stride,
+ int chroma_stride, int ***pred_pos_luma_p,
+ int ***pred_pos_chroma_p, int **luma_grain_block,
+ int **cb_grain_block, int **cr_grain_block,
+ int **y_line_buf, int **cb_line_buf, int **cr_line_buf,
+ int **y_col_buf, int **cb_col_buf, int **cr_col_buf,
+ int luma_grain_samples, int chroma_grain_samples,
+ int chroma_subsamp_y, int chroma_subsamp_x) {
+ *pred_pos_luma_p = NULL;
+ *pred_pos_chroma_p = NULL;
+ *luma_grain_block = NULL;
+ *cb_grain_block = NULL;
+ *cr_grain_block = NULL;
+ *y_line_buf = NULL;
+ *cb_line_buf = NULL;
+ *cr_line_buf = NULL;
+ *y_col_buf = NULL;
+ *cb_col_buf = NULL;
+ *cr_col_buf = NULL;
+
+ memset(scaling_lut_y, 0, sizeof(*scaling_lut_y) * 256);
+ memset(scaling_lut_cb, 0, sizeof(*scaling_lut_cb) * 256);
+ memset(scaling_lut_cr, 0, sizeof(*scaling_lut_cr) * 256);
+
+ int num_pos_luma = 2 * params->ar_coeff_lag * (params->ar_coeff_lag + 1);
+ int num_pos_chroma = num_pos_luma;
+ if (params->num_y_points > 0) ++num_pos_chroma;
+
+ int **pred_pos_luma;
+ int **pred_pos_chroma;
+
+ pred_pos_luma = (int **)aom_calloc(num_pos_luma, sizeof(*pred_pos_luma));
+ if (!pred_pos_luma) return false;
+
+ for (int row = 0; row < num_pos_luma; row++) {
+ pred_pos_luma[row] = (int *)aom_malloc(sizeof(**pred_pos_luma) * 3);
+ if (!pred_pos_luma[row]) {
+ dealloc_arrays(params, pred_pos_luma_p, pred_pos_chroma_p,
+ luma_grain_block, cb_grain_block, cr_grain_block,
+ y_line_buf, cb_line_buf, cr_line_buf, y_col_buf,
+ cb_col_buf, cr_col_buf);
+ return false;
+ }
+ }
+
+ pred_pos_chroma =
+ (int **)aom_calloc(num_pos_chroma, sizeof(*pred_pos_chroma));
+ if (!pred_pos_chroma) {
+ dealloc_arrays(params, pred_pos_luma_p, pred_pos_chroma_p, luma_grain_block,
+ cb_grain_block, cr_grain_block, y_line_buf, cb_line_buf,
+ cr_line_buf, y_col_buf, cb_col_buf, cr_col_buf);
+ return false;
+ }
+
+ for (int row = 0; row < num_pos_chroma; row++) {
+ pred_pos_chroma[row] = (int *)aom_malloc(sizeof(**pred_pos_chroma) * 3);
+ if (!pred_pos_chroma[row]) {
+ dealloc_arrays(params, pred_pos_luma_p, pred_pos_chroma_p,
+ luma_grain_block, cb_grain_block, cr_grain_block,
+ y_line_buf, cb_line_buf, cr_line_buf, y_col_buf,
+ cb_col_buf, cr_col_buf);
+ return false;
+ }
+ }
+
+ int pos_ar_index = 0;
+
+ for (int row = -params->ar_coeff_lag; row < 0; row++) {
+ for (int col = -params->ar_coeff_lag; col < params->ar_coeff_lag + 1;
+ col++) {
+ pred_pos_luma[pos_ar_index][0] = row;
+ pred_pos_luma[pos_ar_index][1] = col;
+ pred_pos_luma[pos_ar_index][2] = 0;
+
+ pred_pos_chroma[pos_ar_index][0] = row;
+ pred_pos_chroma[pos_ar_index][1] = col;
+ pred_pos_chroma[pos_ar_index][2] = 0;
+ ++pos_ar_index;
+ }
+ }
+
+ for (int col = -params->ar_coeff_lag; col < 0; col++) {
+ pred_pos_luma[pos_ar_index][0] = 0;
+ pred_pos_luma[pos_ar_index][1] = col;
+ pred_pos_luma[pos_ar_index][2] = 0;
+
+ pred_pos_chroma[pos_ar_index][0] = 0;
+ pred_pos_chroma[pos_ar_index][1] = col;
+ pred_pos_chroma[pos_ar_index][2] = 0;
+
+ ++pos_ar_index;
+ }
+
+ if (params->num_y_points > 0) {
+ pred_pos_chroma[pos_ar_index][0] = 0;
+ pred_pos_chroma[pos_ar_index][1] = 0;
+ pred_pos_chroma[pos_ar_index][2] = 1;
+ }
+
+ *pred_pos_luma_p = pred_pos_luma;
+ *pred_pos_chroma_p = pred_pos_chroma;
+
+ *y_line_buf = (int *)aom_malloc(sizeof(**y_line_buf) * luma_stride * 2);
+ *cb_line_buf = (int *)aom_malloc(sizeof(**cb_line_buf) * chroma_stride *
+ (2 >> chroma_subsamp_y));
+ *cr_line_buf = (int *)aom_malloc(sizeof(**cr_line_buf) * chroma_stride *
+ (2 >> chroma_subsamp_y));
+
+ *y_col_buf =
+ (int *)aom_malloc(sizeof(**y_col_buf) * (luma_subblock_size_y + 2) * 2);
+ *cb_col_buf =
+ (int *)aom_malloc(sizeof(**cb_col_buf) *
+ (chroma_subblock_size_y + (2 >> chroma_subsamp_y)) *
+ (2 >> chroma_subsamp_x));
+ *cr_col_buf =
+ (int *)aom_malloc(sizeof(**cr_col_buf) *
+ (chroma_subblock_size_y + (2 >> chroma_subsamp_y)) *
+ (2 >> chroma_subsamp_x));
+
+ *luma_grain_block =
+ (int *)aom_malloc(sizeof(**luma_grain_block) * luma_grain_samples);
+ *cb_grain_block =
+ (int *)aom_malloc(sizeof(**cb_grain_block) * chroma_grain_samples);
+ *cr_grain_block =
+ (int *)aom_malloc(sizeof(**cr_grain_block) * chroma_grain_samples);
+ if (!(*pred_pos_luma_p && *pred_pos_chroma_p && *y_line_buf && *cb_line_buf &&
+ *cr_line_buf && *y_col_buf && *cb_col_buf && *cr_col_buf &&
+ *luma_grain_block && *cb_grain_block && *cr_grain_block)) {
+ dealloc_arrays(params, pred_pos_luma_p, pred_pos_chroma_p, luma_grain_block,
+ cb_grain_block, cr_grain_block, y_line_buf, cb_line_buf,
+ cr_line_buf, y_col_buf, cb_col_buf, cr_col_buf);
+ return false;
+ }
+ return true;
+}
+
+// get a number between 0 and 2^bits - 1
+static INLINE int get_random_number(int bits) {
+ uint16_t bit;
+ bit = ((random_register >> 0) ^ (random_register >> 1) ^
+ (random_register >> 3) ^ (random_register >> 12)) &
+ 1;
+ random_register = (random_register >> 1) | (bit << 15);
+ return (random_register >> (16 - bits)) & ((1 << bits) - 1);
+}
+
+static void init_random_generator(int luma_line, uint16_t seed) {
+ // same for the picture
+
+ uint16_t msb = (seed >> 8) & 255;
+ uint16_t lsb = seed & 255;
+
+ random_register = (msb << 8) + lsb;
+
+ // changes for each row
+ int luma_num = luma_line >> 5;
+
+ random_register ^= ((luma_num * 37 + 178) & 255) << 8;
+ random_register ^= ((luma_num * 173 + 105) & 255);
+}
+
+static void generate_luma_grain_block(
+ const aom_film_grain_t *params, int **pred_pos_luma, int *luma_grain_block,
+ int luma_block_size_y, int luma_block_size_x, int luma_grain_stride,
+ int left_pad, int top_pad, int right_pad, int bottom_pad) {
+ if (params->num_y_points == 0) {
+ memset(luma_grain_block, 0,
+ sizeof(*luma_grain_block) * luma_block_size_y * luma_grain_stride);
+ return;
+ }
+
+ int bit_depth = params->bit_depth;
+ int gauss_sec_shift = 12 - bit_depth + params->grain_scale_shift;
+
+ int num_pos_luma = 2 * params->ar_coeff_lag * (params->ar_coeff_lag + 1);
+ int rounding_offset = (1 << (params->ar_coeff_shift - 1));
+
+ for (int i = 0; i < luma_block_size_y; i++)
+ for (int j = 0; j < luma_block_size_x; j++)
+ luma_grain_block[i * luma_grain_stride + j] =
+ (gaussian_sequence[get_random_number(gauss_bits)] +
+ ((1 << gauss_sec_shift) >> 1)) >>
+ gauss_sec_shift;
+
+ for (int i = top_pad; i < luma_block_size_y - bottom_pad; i++)
+ for (int j = left_pad; j < luma_block_size_x - right_pad; j++) {
+ int wsum = 0;
+ for (int pos = 0; pos < num_pos_luma; pos++) {
+ wsum = wsum + params->ar_coeffs_y[pos] *
+ luma_grain_block[(i + pred_pos_luma[pos][0]) *
+ luma_grain_stride +
+ j + pred_pos_luma[pos][1]];
+ }
+ luma_grain_block[i * luma_grain_stride + j] =
+ clamp(luma_grain_block[i * luma_grain_stride + j] +
+ ((wsum + rounding_offset) >> params->ar_coeff_shift),
+ grain_min, grain_max);
+ }
+}
+
+static bool generate_chroma_grain_blocks(
+ const aom_film_grain_t *params, int **pred_pos_chroma,
+ int *luma_grain_block, int *cb_grain_block, int *cr_grain_block,
+ int luma_grain_stride, int chroma_block_size_y, int chroma_block_size_x,
+ int chroma_grain_stride, int left_pad, int top_pad, int right_pad,
+ int bottom_pad, int chroma_subsamp_y, int chroma_subsamp_x) {
+ int bit_depth = params->bit_depth;
+ int gauss_sec_shift = 12 - bit_depth + params->grain_scale_shift;
+
+ int num_pos_chroma = 2 * params->ar_coeff_lag * (params->ar_coeff_lag + 1);
+ if (params->num_y_points > 0) ++num_pos_chroma;
+ int rounding_offset = (1 << (params->ar_coeff_shift - 1));
+ int chroma_grain_block_size = chroma_block_size_y * chroma_grain_stride;
+
+ if (params->num_cb_points || params->chroma_scaling_from_luma) {
+ init_random_generator(7 << 5, params->random_seed);
+
+ for (int i = 0; i < chroma_block_size_y; i++)
+ for (int j = 0; j < chroma_block_size_x; j++)
+ cb_grain_block[i * chroma_grain_stride + j] =
+ (gaussian_sequence[get_random_number(gauss_bits)] +
+ ((1 << gauss_sec_shift) >> 1)) >>
+ gauss_sec_shift;
+ } else {
+ memset(cb_grain_block, 0,
+ sizeof(*cb_grain_block) * chroma_grain_block_size);
+ }
+
+ if (params->num_cr_points || params->chroma_scaling_from_luma) {
+ init_random_generator(11 << 5, params->random_seed);
+
+ for (int i = 0; i < chroma_block_size_y; i++)
+ for (int j = 0; j < chroma_block_size_x; j++)
+ cr_grain_block[i * chroma_grain_stride + j] =
+ (gaussian_sequence[get_random_number(gauss_bits)] +
+ ((1 << gauss_sec_shift) >> 1)) >>
+ gauss_sec_shift;
+ } else {
+ memset(cr_grain_block, 0,
+ sizeof(*cr_grain_block) * chroma_grain_block_size);
+ }
+
+ for (int i = top_pad; i < chroma_block_size_y - bottom_pad; i++)
+ for (int j = left_pad; j < chroma_block_size_x - right_pad; j++) {
+ int wsum_cb = 0;
+ int wsum_cr = 0;
+ for (int pos = 0; pos < num_pos_chroma; pos++) {
+ if (pred_pos_chroma[pos][2] == 0) {
+ wsum_cb = wsum_cb + params->ar_coeffs_cb[pos] *
+ cb_grain_block[(i + pred_pos_chroma[pos][0]) *
+ chroma_grain_stride +
+ j + pred_pos_chroma[pos][1]];
+ wsum_cr = wsum_cr + params->ar_coeffs_cr[pos] *
+ cr_grain_block[(i + pred_pos_chroma[pos][0]) *
+ chroma_grain_stride +
+ j + pred_pos_chroma[pos][1]];
+ } else if (pred_pos_chroma[pos][2] == 1) {
+ int av_luma = 0;
+ int luma_coord_y = ((i - top_pad) << chroma_subsamp_y) + top_pad;
+ int luma_coord_x = ((j - left_pad) << chroma_subsamp_x) + left_pad;
+
+ for (int k = luma_coord_y; k < luma_coord_y + chroma_subsamp_y + 1;
+ k++)
+ for (int l = luma_coord_x; l < luma_coord_x + chroma_subsamp_x + 1;
+ l++)
+ av_luma += luma_grain_block[k * luma_grain_stride + l];
+
+ av_luma =
+ (av_luma + ((1 << (chroma_subsamp_y + chroma_subsamp_x)) >> 1)) >>
+ (chroma_subsamp_y + chroma_subsamp_x);
+
+ wsum_cb = wsum_cb + params->ar_coeffs_cb[pos] * av_luma;
+ wsum_cr = wsum_cr + params->ar_coeffs_cr[pos] * av_luma;
+ } else {
+ fprintf(
+ stderr,
+ "Grain synthesis: prediction between two chroma components is "
+ "not supported!");
+ return false;
+ }
+ }
+ if (params->num_cb_points || params->chroma_scaling_from_luma)
+ cb_grain_block[i * chroma_grain_stride + j] =
+ clamp(cb_grain_block[i * chroma_grain_stride + j] +
+ ((wsum_cb + rounding_offset) >> params->ar_coeff_shift),
+ grain_min, grain_max);
+ if (params->num_cr_points || params->chroma_scaling_from_luma)
+ cr_grain_block[i * chroma_grain_stride + j] =
+ clamp(cr_grain_block[i * chroma_grain_stride + j] +
+ ((wsum_cr + rounding_offset) >> params->ar_coeff_shift),
+ grain_min, grain_max);
+ }
+ return true;
+}
+
+static void init_scaling_function(const int scaling_points[][2], int num_points,
+ int scaling_lut[]) {
+ if (num_points == 0) return;
+
+ for (int i = 0; i < scaling_points[0][0]; i++)
+ scaling_lut[i] = scaling_points[0][1];
+
+ for (int point = 0; point < num_points - 1; point++) {
+ int delta_y = scaling_points[point + 1][1] - scaling_points[point][1];
+ int delta_x = scaling_points[point + 1][0] - scaling_points[point][0];
+
+ int64_t delta = delta_y * ((65536 + (delta_x >> 1)) / delta_x);
+
+ for (int x = 0; x < delta_x; x++) {
+ scaling_lut[scaling_points[point][0] + x] =
+ scaling_points[point][1] + (int)((x * delta + 32768) >> 16);
+ }
+ }
+
+ for (int i = scaling_points[num_points - 1][0]; i < 256; i++)
+ scaling_lut[i] = scaling_points[num_points - 1][1];
+}
+
+// function that extracts samples from a LUT (and interpolates intemediate
+// frames for 10- and 12-bit video)
+static int scale_LUT(int *scaling_lut, int index, int bit_depth) {
+ int x = index >> (bit_depth - 8);
+
+ if (!(bit_depth - 8) || x == 255)
+ return scaling_lut[x];
+ else
+ return scaling_lut[x] + (((scaling_lut[x + 1] - scaling_lut[x]) *
+ (index & ((1 << (bit_depth - 8)) - 1)) +
+ (1 << (bit_depth - 9))) >>
+ (bit_depth - 8));
+}
+
+static void add_noise_to_block(const aom_film_grain_t *params, uint8_t *luma,
+ uint8_t *cb, uint8_t *cr, int luma_stride,
+ int chroma_stride, int *luma_grain,
+ int *cb_grain, int *cr_grain,
+ int luma_grain_stride, int chroma_grain_stride,
+ int half_luma_height, int half_luma_width,
+ int bit_depth, int chroma_subsamp_y,
+ int chroma_subsamp_x, int mc_identity) {
+ int cb_mult = params->cb_mult - 128; // fixed scale
+ int cb_luma_mult = params->cb_luma_mult - 128; // fixed scale
+ int cb_offset = params->cb_offset - 256;
+
+ int cr_mult = params->cr_mult - 128; // fixed scale
+ int cr_luma_mult = params->cr_luma_mult - 128; // fixed scale
+ int cr_offset = params->cr_offset - 256;
+
+ int rounding_offset = (1 << (params->scaling_shift - 1));
+
+ int apply_y = params->num_y_points > 0 ? 1 : 0;
+ int apply_cb =
+ (params->num_cb_points > 0 || params->chroma_scaling_from_luma) ? 1 : 0;
+ int apply_cr =
+ (params->num_cr_points > 0 || params->chroma_scaling_from_luma) ? 1 : 0;
+
+ if (params->chroma_scaling_from_luma) {
+ cb_mult = 0; // fixed scale
+ cb_luma_mult = 64; // fixed scale
+ cb_offset = 0;
+
+ cr_mult = 0; // fixed scale
+ cr_luma_mult = 64; // fixed scale
+ cr_offset = 0;
+ }
+
+ int min_luma, max_luma, min_chroma, max_chroma;
+
+ if (params->clip_to_restricted_range) {
+ min_luma = min_luma_legal_range;
+ max_luma = max_luma_legal_range;
+
+ if (mc_identity) {
+ min_chroma = min_luma_legal_range;
+ max_chroma = max_luma_legal_range;
+ } else {
+ min_chroma = min_chroma_legal_range;
+ max_chroma = max_chroma_legal_range;
+ }
+ } else {
+ min_luma = min_chroma = 0;
+ max_luma = max_chroma = 255;
+ }
+
+ for (int i = 0; i < (half_luma_height << (1 - chroma_subsamp_y)); i++) {
+ for (int j = 0; j < (half_luma_width << (1 - chroma_subsamp_x)); j++) {
+ int average_luma = 0;
+ if (chroma_subsamp_x) {
+ average_luma = (luma[(i << chroma_subsamp_y) * luma_stride +
+ (j << chroma_subsamp_x)] +
+ luma[(i << chroma_subsamp_y) * luma_stride +
+ (j << chroma_subsamp_x) + 1] +
+ 1) >>
+ 1;
+ } else {
+ average_luma = luma[(i << chroma_subsamp_y) * luma_stride + j];
+ }
+
+ if (apply_cb) {
+ cb[i * chroma_stride + j] = clamp(
+ cb[i * chroma_stride + j] +
+ ((scale_LUT(scaling_lut_cb,
+ clamp(((average_luma * cb_luma_mult +
+ cb_mult * cb[i * chroma_stride + j]) >>
+ 6) +
+ cb_offset,
+ 0, (256 << (bit_depth - 8)) - 1),
+ 8) *
+ cb_grain[i * chroma_grain_stride + j] +
+ rounding_offset) >>
+ params->scaling_shift),
+ min_chroma, max_chroma);
+ }
+
+ if (apply_cr) {
+ cr[i * chroma_stride + j] = clamp(
+ cr[i * chroma_stride + j] +
+ ((scale_LUT(scaling_lut_cr,
+ clamp(((average_luma * cr_luma_mult +
+ cr_mult * cr[i * chroma_stride + j]) >>
+ 6) +
+ cr_offset,
+ 0, (256 << (bit_depth - 8)) - 1),
+ 8) *
+ cr_grain[i * chroma_grain_stride + j] +
+ rounding_offset) >>
+ params->scaling_shift),
+ min_chroma, max_chroma);
+ }
+ }
+ }
+
+ if (apply_y) {
+ for (int i = 0; i < (half_luma_height << 1); i++) {
+ for (int j = 0; j < (half_luma_width << 1); j++) {
+ luma[i * luma_stride + j] =
+ clamp(luma[i * luma_stride + j] +
+ ((scale_LUT(scaling_lut_y, luma[i * luma_stride + j], 8) *
+ luma_grain[i * luma_grain_stride + j] +
+ rounding_offset) >>
+ params->scaling_shift),
+ min_luma, max_luma);
+ }
+ }
+ }
+}
+
+static void add_noise_to_block_hbd(
+ const aom_film_grain_t *params, uint16_t *luma, uint16_t *cb, uint16_t *cr,
+ int luma_stride, int chroma_stride, int *luma_grain, int *cb_grain,
+ int *cr_grain, int luma_grain_stride, int chroma_grain_stride,
+ int half_luma_height, int half_luma_width, int bit_depth,
+ int chroma_subsamp_y, int chroma_subsamp_x, int mc_identity) {
+ int cb_mult = params->cb_mult - 128; // fixed scale
+ int cb_luma_mult = params->cb_luma_mult - 128; // fixed scale
+ // offset value depends on the bit depth
+ int cb_offset = (params->cb_offset << (bit_depth - 8)) - (1 << bit_depth);
+
+ int cr_mult = params->cr_mult - 128; // fixed scale
+ int cr_luma_mult = params->cr_luma_mult - 128; // fixed scale
+ // offset value depends on the bit depth
+ int cr_offset = (params->cr_offset << (bit_depth - 8)) - (1 << bit_depth);
+
+ int rounding_offset = (1 << (params->scaling_shift - 1));
+
+ int apply_y = params->num_y_points > 0 ? 1 : 0;
+ int apply_cb =
+ (params->num_cb_points > 0 || params->chroma_scaling_from_luma) > 0 ? 1
+ : 0;
+ int apply_cr =
+ (params->num_cr_points > 0 || params->chroma_scaling_from_luma) > 0 ? 1
+ : 0;
+
+ if (params->chroma_scaling_from_luma) {
+ cb_mult = 0; // fixed scale
+ cb_luma_mult = 64; // fixed scale
+ cb_offset = 0;
+
+ cr_mult = 0; // fixed scale
+ cr_luma_mult = 64; // fixed scale
+ cr_offset = 0;
+ }
+
+ int min_luma, max_luma, min_chroma, max_chroma;
+
+ if (params->clip_to_restricted_range) {
+ min_luma = min_luma_legal_range << (bit_depth - 8);
+ max_luma = max_luma_legal_range << (bit_depth - 8);
+
+ if (mc_identity) {
+ min_chroma = min_luma_legal_range << (bit_depth - 8);
+ max_chroma = max_luma_legal_range << (bit_depth - 8);
+ } else {
+ min_chroma = min_chroma_legal_range << (bit_depth - 8);
+ max_chroma = max_chroma_legal_range << (bit_depth - 8);
+ }
+ } else {
+ min_luma = min_chroma = 0;
+ max_luma = max_chroma = (256 << (bit_depth - 8)) - 1;
+ }
+
+ for (int i = 0; i < (half_luma_height << (1 - chroma_subsamp_y)); i++) {
+ for (int j = 0; j < (half_luma_width << (1 - chroma_subsamp_x)); j++) {
+ int average_luma = 0;
+ if (chroma_subsamp_x) {
+ average_luma = (luma[(i << chroma_subsamp_y) * luma_stride +
+ (j << chroma_subsamp_x)] +
+ luma[(i << chroma_subsamp_y) * luma_stride +
+ (j << chroma_subsamp_x) + 1] +
+ 1) >>
+ 1;
+ } else {
+ average_luma = luma[(i << chroma_subsamp_y) * luma_stride + j];
+ }
+
+ if (apply_cb) {
+ cb[i * chroma_stride + j] = clamp(
+ cb[i * chroma_stride + j] +
+ ((scale_LUT(scaling_lut_cb,
+ clamp(((average_luma * cb_luma_mult +
+ cb_mult * cb[i * chroma_stride + j]) >>
+ 6) +
+ cb_offset,
+ 0, (256 << (bit_depth - 8)) - 1),
+ bit_depth) *
+ cb_grain[i * chroma_grain_stride + j] +
+ rounding_offset) >>
+ params->scaling_shift),
+ min_chroma, max_chroma);
+ }
+ if (apply_cr) {
+ cr[i * chroma_stride + j] = clamp(
+ cr[i * chroma_stride + j] +
+ ((scale_LUT(scaling_lut_cr,
+ clamp(((average_luma * cr_luma_mult +
+ cr_mult * cr[i * chroma_stride + j]) >>
+ 6) +
+ cr_offset,
+ 0, (256 << (bit_depth - 8)) - 1),
+ bit_depth) *
+ cr_grain[i * chroma_grain_stride + j] +
+ rounding_offset) >>
+ params->scaling_shift),
+ min_chroma, max_chroma);
+ }
+ }
+ }
+
+ if (apply_y) {
+ for (int i = 0; i < (half_luma_height << 1); i++) {
+ for (int j = 0; j < (half_luma_width << 1); j++) {
+ luma[i * luma_stride + j] =
+ clamp(luma[i * luma_stride + j] +
+ ((scale_LUT(scaling_lut_y, luma[i * luma_stride + j],
+ bit_depth) *
+ luma_grain[i * luma_grain_stride + j] +
+ rounding_offset) >>
+ params->scaling_shift),
+ min_luma, max_luma);
+ }
+ }
+ }
+}
+
+static void copy_rect(uint8_t *src, int src_stride, uint8_t *dst,
+ int dst_stride, int width, int height,
+ int use_high_bit_depth) {
+ int hbd_coeff = use_high_bit_depth ? 2 : 1;
+ while (height) {
+ memcpy(dst, src, width * sizeof(uint8_t) * hbd_coeff);
+ src += src_stride;
+ dst += dst_stride;
+ --height;
+ }
+ return;
+}
+
+static void copy_area(int *src, int src_stride, int *dst, int dst_stride,
+ int width, int height) {
+ while (height) {
+ memcpy(dst, src, width * sizeof(*src));
+ src += src_stride;
+ dst += dst_stride;
+ --height;
+ }
+ return;
+}
+
+static void extend_even(uint8_t *dst, int dst_stride, int width, int height,
+ int use_high_bit_depth) {
+ if ((width & 1) == 0 && (height & 1) == 0) return;
+ if (use_high_bit_depth) {
+ uint16_t *dst16 = (uint16_t *)dst;
+ int dst16_stride = dst_stride / 2;
+ if (width & 1) {
+ for (int i = 0; i < height; ++i)
+ dst16[i * dst16_stride + width] = dst16[i * dst16_stride + width - 1];
+ }
+ width = (width + 1) & (~1);
+ if (height & 1) {
+ memcpy(&dst16[height * dst16_stride], &dst16[(height - 1) * dst16_stride],
+ sizeof(*dst16) * width);
+ }
+ } else {
+ if (width & 1) {
+ for (int i = 0; i < height; ++i)
+ dst[i * dst_stride + width] = dst[i * dst_stride + width - 1];
+ }
+ width = (width + 1) & (~1);
+ if (height & 1) {
+ memcpy(&dst[height * dst_stride], &dst[(height - 1) * dst_stride],
+ sizeof(*dst) * width);
+ }
+ }
+}
+
+static void ver_boundary_overlap(int *left_block, int left_stride,
+ int *right_block, int right_stride,
+ int *dst_block, int dst_stride, int width,
+ int height) {
+ if (width == 1) {
+ while (height) {
+ *dst_block = clamp((*left_block * 23 + *right_block * 22 + 16) >> 5,
+ grain_min, grain_max);
+ left_block += left_stride;
+ right_block += right_stride;
+ dst_block += dst_stride;
+ --height;
+ }
+ return;
+ } else if (width == 2) {
+ while (height) {
+ dst_block[0] = clamp((27 * left_block[0] + 17 * right_block[0] + 16) >> 5,
+ grain_min, grain_max);
+ dst_block[1] = clamp((17 * left_block[1] + 27 * right_block[1] + 16) >> 5,
+ grain_min, grain_max);
+ left_block += left_stride;
+ right_block += right_stride;
+ dst_block += dst_stride;
+ --height;
+ }
+ return;
+ }
+}
+
+static void hor_boundary_overlap(int *top_block, int top_stride,
+ int *bottom_block, int bottom_stride,
+ int *dst_block, int dst_stride, int width,
+ int height) {
+ if (height == 1) {
+ while (width) {
+ *dst_block = clamp((*top_block * 23 + *bottom_block * 22 + 16) >> 5,
+ grain_min, grain_max);
+ ++top_block;
+ ++bottom_block;
+ ++dst_block;
+ --width;
+ }
+ return;
+ } else if (height == 2) {
+ while (width) {
+ dst_block[0] = clamp((27 * top_block[0] + 17 * bottom_block[0] + 16) >> 5,
+ grain_min, grain_max);
+ dst_block[dst_stride] = clamp((17 * top_block[top_stride] +
+ 27 * bottom_block[bottom_stride] + 16) >>
+ 5,
+ grain_min, grain_max);
+ ++top_block;
+ ++bottom_block;
+ ++dst_block;
+ --width;
+ }
+ return;
+ }
+}
+
+int av1_add_film_grain(const aom_film_grain_t *params, const aom_image_t *src,
+ aom_image_t *dst) {
+ uint8_t *luma, *cb, *cr;
+ int height, width, luma_stride, chroma_stride;
+ int use_high_bit_depth = 0;
+ int chroma_subsamp_x = 0;
+ int chroma_subsamp_y = 0;
+ int mc_identity = src->mc == AOM_CICP_MC_IDENTITY ? 1 : 0;
+
+ switch (src->fmt) {
+ case AOM_IMG_FMT_AOMI420:
+ case AOM_IMG_FMT_I420:
+ use_high_bit_depth = 0;
+ chroma_subsamp_x = 1;
+ chroma_subsamp_y = 1;
+ break;
+ case AOM_IMG_FMT_I42016:
+ use_high_bit_depth = 1;
+ chroma_subsamp_x = 1;
+ chroma_subsamp_y = 1;
+ break;
+ // case AOM_IMG_FMT_444A:
+ case AOM_IMG_FMT_I444:
+ use_high_bit_depth = 0;
+ chroma_subsamp_x = 0;
+ chroma_subsamp_y = 0;
+ break;
+ case AOM_IMG_FMT_I44416:
+ use_high_bit_depth = 1;
+ chroma_subsamp_x = 0;
+ chroma_subsamp_y = 0;
+ break;
+ case AOM_IMG_FMT_I422:
+ use_high_bit_depth = 0;
+ chroma_subsamp_x = 1;
+ chroma_subsamp_y = 0;
+ break;
+ case AOM_IMG_FMT_I42216:
+ use_high_bit_depth = 1;
+ chroma_subsamp_x = 1;
+ chroma_subsamp_y = 0;
+ break;
+ default: // unknown input format
+ fprintf(stderr, "Film grain error: input format is not supported!");
+ return -1;
+ }
+
+ assert(params->bit_depth == src->bit_depth);
+
+ dst->fmt = src->fmt;
+ dst->bit_depth = src->bit_depth;
+
+ dst->r_w = src->r_w;
+ dst->r_h = src->r_h;
+ dst->d_w = src->d_w;
+ dst->d_h = src->d_h;
+
+ dst->cp = src->cp;
+ dst->tc = src->tc;
+ dst->mc = src->mc;
+
+ dst->monochrome = src->monochrome;
+ dst->csp = src->csp;
+ dst->range = src->range;
+
+ dst->x_chroma_shift = src->x_chroma_shift;
+ dst->y_chroma_shift = src->y_chroma_shift;
+
+ dst->temporal_id = src->temporal_id;
+ dst->spatial_id = src->spatial_id;
+
+ width = src->d_w % 2 ? src->d_w + 1 : src->d_w;
+ height = src->d_h % 2 ? src->d_h + 1 : src->d_h;
+
+ copy_rect(src->planes[AOM_PLANE_Y], src->stride[AOM_PLANE_Y],
+ dst->planes[AOM_PLANE_Y], dst->stride[AOM_PLANE_Y], src->d_w,
+ src->d_h, use_high_bit_depth);
+ // Note that dst is already assumed to be aligned to even.
+ extend_even(dst->planes[AOM_PLANE_Y], dst->stride[AOM_PLANE_Y], src->d_w,
+ src->d_h, use_high_bit_depth);
+
+ if (!src->monochrome) {
+ copy_rect(src->planes[AOM_PLANE_U], src->stride[AOM_PLANE_U],
+ dst->planes[AOM_PLANE_U], dst->stride[AOM_PLANE_U],
+ width >> chroma_subsamp_x, height >> chroma_subsamp_y,
+ use_high_bit_depth);
+
+ copy_rect(src->planes[AOM_PLANE_V], src->stride[AOM_PLANE_V],
+ dst->planes[AOM_PLANE_V], dst->stride[AOM_PLANE_V],
+ width >> chroma_subsamp_x, height >> chroma_subsamp_y,
+ use_high_bit_depth);
+ }
+
+ luma = dst->planes[AOM_PLANE_Y];
+ cb = dst->planes[AOM_PLANE_U];
+ cr = dst->planes[AOM_PLANE_V];
+
+ // luma and chroma strides in samples
+ luma_stride = dst->stride[AOM_PLANE_Y] >> use_high_bit_depth;
+ chroma_stride = dst->stride[AOM_PLANE_U] >> use_high_bit_depth;
+
+ return av1_add_film_grain_run(
+ params, luma, cb, cr, height, width, luma_stride, chroma_stride,
+ use_high_bit_depth, chroma_subsamp_y, chroma_subsamp_x, mc_identity);
+}
+
+int av1_add_film_grain_run(const aom_film_grain_t *params, uint8_t *luma,
+ uint8_t *cb, uint8_t *cr, int height, int width,
+ int luma_stride, int chroma_stride,
+ int use_high_bit_depth, int chroma_subsamp_y,
+ int chroma_subsamp_x, int mc_identity) {
+ int **pred_pos_luma;
+ int **pred_pos_chroma;
+ int *luma_grain_block;
+ int *cb_grain_block;
+ int *cr_grain_block;
+
+ int *y_line_buf;
+ int *cb_line_buf;
+ int *cr_line_buf;
+
+ int *y_col_buf;
+ int *cb_col_buf;
+ int *cr_col_buf;
+
+ random_register = params->random_seed;
+
+ int left_pad = 3;
+ int right_pad = 3; // padding to offset for AR coefficients
+ int top_pad = 3;
+ int bottom_pad = 0;
+
+ int ar_padding = 3; // maximum lag used for stabilization of AR coefficients
+
+ luma_subblock_size_y = 32;
+ luma_subblock_size_x = 32;
+
+ chroma_subblock_size_y = luma_subblock_size_y >> chroma_subsamp_y;
+ chroma_subblock_size_x = luma_subblock_size_x >> chroma_subsamp_x;
+
+ // Initial padding is only needed for generation of
+ // film grain templates (to stabilize the AR process)
+ // Only a 64x64 luma and 32x32 chroma part of a template
+ // is used later for adding grain, padding can be discarded
+
+ int luma_block_size_y =
+ top_pad + 2 * ar_padding + luma_subblock_size_y * 2 + bottom_pad;
+ int luma_block_size_x = left_pad + 2 * ar_padding + luma_subblock_size_x * 2 +
+ 2 * ar_padding + right_pad;
+
+ int chroma_block_size_y = top_pad + (2 >> chroma_subsamp_y) * ar_padding +
+ chroma_subblock_size_y * 2 + bottom_pad;
+ int chroma_block_size_x = left_pad + (2 >> chroma_subsamp_x) * ar_padding +
+ chroma_subblock_size_x * 2 +
+ (2 >> chroma_subsamp_x) * ar_padding + right_pad;
+
+ int luma_grain_stride = luma_block_size_x;
+ int chroma_grain_stride = chroma_block_size_x;
+
+ int overlap = params->overlap_flag;
+ int bit_depth = params->bit_depth;
+
+ const int grain_center = 128 << (bit_depth - 8);
+ grain_min = 0 - grain_center;
+ grain_max = grain_center - 1;
+
+ if (!init_arrays(params, luma_stride, chroma_stride, &pred_pos_luma,
+ &pred_pos_chroma, &luma_grain_block, &cb_grain_block,
+ &cr_grain_block, &y_line_buf, &cb_line_buf, &cr_line_buf,
+ &y_col_buf, &cb_col_buf, &cr_col_buf,
+ luma_block_size_y * luma_block_size_x,
+ chroma_block_size_y * chroma_block_size_x, chroma_subsamp_y,
+ chroma_subsamp_x))
+ return -1;
+
+ generate_luma_grain_block(params, pred_pos_luma, luma_grain_block,
+ luma_block_size_y, luma_block_size_x,
+ luma_grain_stride, left_pad, top_pad, right_pad,
+ bottom_pad);
+
+ if (!generate_chroma_grain_blocks(
+ params, pred_pos_chroma, luma_grain_block, cb_grain_block,
+ cr_grain_block, luma_grain_stride, chroma_block_size_y,
+ chroma_block_size_x, chroma_grain_stride, left_pad, top_pad,
+ right_pad, bottom_pad, chroma_subsamp_y, chroma_subsamp_x))
+ return -1;
+
+ init_scaling_function(params->scaling_points_y, params->num_y_points,
+ scaling_lut_y);
+
+ if (params->chroma_scaling_from_luma) {
+ memcpy(scaling_lut_cb, scaling_lut_y, sizeof(*scaling_lut_y) * 256);
+ memcpy(scaling_lut_cr, scaling_lut_y, sizeof(*scaling_lut_y) * 256);
+ } else {
+ init_scaling_function(params->scaling_points_cb, params->num_cb_points,
+ scaling_lut_cb);
+ init_scaling_function(params->scaling_points_cr, params->num_cr_points,
+ scaling_lut_cr);
+ }
+ for (int y = 0; y < height / 2; y += (luma_subblock_size_y >> 1)) {
+ init_random_generator(y * 2, params->random_seed);
+
+ for (int x = 0; x < width / 2; x += (luma_subblock_size_x >> 1)) {
+ int offset_y = get_random_number(8);
+ int offset_x = (offset_y >> 4) & 15;
+ offset_y &= 15;
+
+ int luma_offset_y = left_pad + 2 * ar_padding + (offset_y << 1);
+ int luma_offset_x = top_pad + 2 * ar_padding + (offset_x << 1);
+
+ int chroma_offset_y = top_pad + (2 >> chroma_subsamp_y) * ar_padding +
+ offset_y * (2 >> chroma_subsamp_y);
+ int chroma_offset_x = left_pad + (2 >> chroma_subsamp_x) * ar_padding +
+ offset_x * (2 >> chroma_subsamp_x);
+
+ if (overlap && x) {
+ ver_boundary_overlap(
+ y_col_buf, 2,
+ luma_grain_block + luma_offset_y * luma_grain_stride +
+ luma_offset_x,
+ luma_grain_stride, y_col_buf, 2, 2,
+ AOMMIN(luma_subblock_size_y + 2, height - (y << 1)));
+
+ ver_boundary_overlap(
+ cb_col_buf, 2 >> chroma_subsamp_x,
+ cb_grain_block + chroma_offset_y * chroma_grain_stride +
+ chroma_offset_x,
+ chroma_grain_stride, cb_col_buf, 2 >> chroma_subsamp_x,
+ 2 >> chroma_subsamp_x,
+ AOMMIN(chroma_subblock_size_y + (2 >> chroma_subsamp_y),
+ (height - (y << 1)) >> chroma_subsamp_y));
+
+ ver_boundary_overlap(
+ cr_col_buf, 2 >> chroma_subsamp_x,
+ cr_grain_block + chroma_offset_y * chroma_grain_stride +
+ chroma_offset_x,
+ chroma_grain_stride, cr_col_buf, 2 >> chroma_subsamp_x,
+ 2 >> chroma_subsamp_x,
+ AOMMIN(chroma_subblock_size_y + (2 >> chroma_subsamp_y),
+ (height - (y << 1)) >> chroma_subsamp_y));
+
+ int i = y ? 1 : 0;
+
+ if (use_high_bit_depth) {
+ add_noise_to_block_hbd(
+ params,
+ (uint16_t *)luma + ((y + i) << 1) * luma_stride + (x << 1),
+ (uint16_t *)cb +
+ ((y + i) << (1 - chroma_subsamp_y)) * chroma_stride +
+ (x << (1 - chroma_subsamp_x)),
+ (uint16_t *)cr +
+ ((y + i) << (1 - chroma_subsamp_y)) * chroma_stride +
+ (x << (1 - chroma_subsamp_x)),
+ luma_stride, chroma_stride, y_col_buf + i * 4,
+ cb_col_buf + i * (2 - chroma_subsamp_y) * (2 - chroma_subsamp_x),
+ cr_col_buf + i * (2 - chroma_subsamp_y) * (2 - chroma_subsamp_x),
+ 2, (2 - chroma_subsamp_x),
+ AOMMIN(luma_subblock_size_y >> 1, height / 2 - y) - i, 1,
+ bit_depth, chroma_subsamp_y, chroma_subsamp_x, mc_identity);
+ } else {
+ add_noise_to_block(
+ params, luma + ((y + i) << 1) * luma_stride + (x << 1),
+ cb + ((y + i) << (1 - chroma_subsamp_y)) * chroma_stride +
+ (x << (1 - chroma_subsamp_x)),
+ cr + ((y + i) << (1 - chroma_subsamp_y)) * chroma_stride +
+ (x << (1 - chroma_subsamp_x)),
+ luma_stride, chroma_stride, y_col_buf + i * 4,
+ cb_col_buf + i * (2 - chroma_subsamp_y) * (2 - chroma_subsamp_x),
+ cr_col_buf + i * (2 - chroma_subsamp_y) * (2 - chroma_subsamp_x),
+ 2, (2 - chroma_subsamp_x),
+ AOMMIN(luma_subblock_size_y >> 1, height / 2 - y) - i, 1,
+ bit_depth, chroma_subsamp_y, chroma_subsamp_x, mc_identity);
+ }
+ }
+
+ if (overlap && y) {
+ if (x) {
+ hor_boundary_overlap(y_line_buf + (x << 1), luma_stride, y_col_buf, 2,
+ y_line_buf + (x << 1), luma_stride, 2, 2);
+
+ hor_boundary_overlap(cb_line_buf + x * (2 >> chroma_subsamp_x),
+ chroma_stride, cb_col_buf, 2 >> chroma_subsamp_x,
+ cb_line_buf + x * (2 >> chroma_subsamp_x),
+ chroma_stride, 2 >> chroma_subsamp_x,
+ 2 >> chroma_subsamp_y);
+
+ hor_boundary_overlap(cr_line_buf + x * (2 >> chroma_subsamp_x),
+ chroma_stride, cr_col_buf, 2 >> chroma_subsamp_x,
+ cr_line_buf + x * (2 >> chroma_subsamp_x),
+ chroma_stride, 2 >> chroma_subsamp_x,
+ 2 >> chroma_subsamp_y);
+ }
+
+ hor_boundary_overlap(
+ y_line_buf + ((x ? x + 1 : 0) << 1), luma_stride,
+ luma_grain_block + luma_offset_y * luma_grain_stride +
+ luma_offset_x + (x ? 2 : 0),
+ luma_grain_stride, y_line_buf + ((x ? x + 1 : 0) << 1), luma_stride,
+ AOMMIN(luma_subblock_size_x - ((x ? 1 : 0) << 1),
+ width - ((x ? x + 1 : 0) << 1)),
+ 2);
+
+ hor_boundary_overlap(
+ cb_line_buf + ((x ? x + 1 : 0) << (1 - chroma_subsamp_x)),
+ chroma_stride,
+ cb_grain_block + chroma_offset_y * chroma_grain_stride +
+ chroma_offset_x + ((x ? 1 : 0) << (1 - chroma_subsamp_x)),
+ chroma_grain_stride,
+ cb_line_buf + ((x ? x + 1 : 0) << (1 - chroma_subsamp_x)),
+ chroma_stride,
+ AOMMIN(chroma_subblock_size_x -
+ ((x ? 1 : 0) << (1 - chroma_subsamp_x)),
+ (width - ((x ? x + 1 : 0) << 1)) >> chroma_subsamp_x),
+ 2 >> chroma_subsamp_y);
+
+ hor_boundary_overlap(
+ cr_line_buf + ((x ? x + 1 : 0) << (1 - chroma_subsamp_x)),
+ chroma_stride,
+ cr_grain_block + chroma_offset_y * chroma_grain_stride +
+ chroma_offset_x + ((x ? 1 : 0) << (1 - chroma_subsamp_x)),
+ chroma_grain_stride,
+ cr_line_buf + ((x ? x + 1 : 0) << (1 - chroma_subsamp_x)),
+ chroma_stride,
+ AOMMIN(chroma_subblock_size_x -
+ ((x ? 1 : 0) << (1 - chroma_subsamp_x)),
+ (width - ((x ? x + 1 : 0) << 1)) >> chroma_subsamp_x),
+ 2 >> chroma_subsamp_y);
+
+ if (use_high_bit_depth) {
+ add_noise_to_block_hbd(
+ params, (uint16_t *)luma + (y << 1) * luma_stride + (x << 1),
+ (uint16_t *)cb + (y << (1 - chroma_subsamp_y)) * chroma_stride +
+ (x << ((1 - chroma_subsamp_x))),
+ (uint16_t *)cr + (y << (1 - chroma_subsamp_y)) * chroma_stride +
+ (x << ((1 - chroma_subsamp_x))),
+ luma_stride, chroma_stride, y_line_buf + (x << 1),
+ cb_line_buf + (x << (1 - chroma_subsamp_x)),
+ cr_line_buf + (x << (1 - chroma_subsamp_x)), luma_stride,
+ chroma_stride, 1,
+ AOMMIN(luma_subblock_size_x >> 1, width / 2 - x), bit_depth,
+ chroma_subsamp_y, chroma_subsamp_x, mc_identity);
+ } else {
+ add_noise_to_block(
+ params, luma + (y << 1) * luma_stride + (x << 1),
+ cb + (y << (1 - chroma_subsamp_y)) * chroma_stride +
+ (x << ((1 - chroma_subsamp_x))),
+ cr + (y << (1 - chroma_subsamp_y)) * chroma_stride +
+ (x << ((1 - chroma_subsamp_x))),
+ luma_stride, chroma_stride, y_line_buf + (x << 1),
+ cb_line_buf + (x << (1 - chroma_subsamp_x)),
+ cr_line_buf + (x << (1 - chroma_subsamp_x)), luma_stride,
+ chroma_stride, 1,
+ AOMMIN(luma_subblock_size_x >> 1, width / 2 - x), bit_depth,
+ chroma_subsamp_y, chroma_subsamp_x, mc_identity);
+ }
+ }
+
+ int i = overlap && y ? 1 : 0;
+ int j = overlap && x ? 1 : 0;
+
+ if (use_high_bit_depth) {
+ add_noise_to_block_hbd(
+ params,
+ (uint16_t *)luma + ((y + i) << 1) * luma_stride + ((x + j) << 1),
+ (uint16_t *)cb +
+ ((y + i) << (1 - chroma_subsamp_y)) * chroma_stride +
+ ((x + j) << (1 - chroma_subsamp_x)),
+ (uint16_t *)cr +
+ ((y + i) << (1 - chroma_subsamp_y)) * chroma_stride +
+ ((x + j) << (1 - chroma_subsamp_x)),
+ luma_stride, chroma_stride,
+ luma_grain_block + (luma_offset_y + (i << 1)) * luma_grain_stride +
+ luma_offset_x + (j << 1),
+ cb_grain_block +
+ (chroma_offset_y + (i << (1 - chroma_subsamp_y))) *
+ chroma_grain_stride +
+ chroma_offset_x + (j << (1 - chroma_subsamp_x)),
+ cr_grain_block +
+ (chroma_offset_y + (i << (1 - chroma_subsamp_y))) *
+ chroma_grain_stride +
+ chroma_offset_x + (j << (1 - chroma_subsamp_x)),
+ luma_grain_stride, chroma_grain_stride,
+ AOMMIN(luma_subblock_size_y >> 1, height / 2 - y) - i,
+ AOMMIN(luma_subblock_size_x >> 1, width / 2 - x) - j, bit_depth,
+ chroma_subsamp_y, chroma_subsamp_x, mc_identity);
+ } else {
+ add_noise_to_block(
+ params, luma + ((y + i) << 1) * luma_stride + ((x + j) << 1),
+ cb + ((y + i) << (1 - chroma_subsamp_y)) * chroma_stride +
+ ((x + j) << (1 - chroma_subsamp_x)),
+ cr + ((y + i) << (1 - chroma_subsamp_y)) * chroma_stride +
+ ((x + j) << (1 - chroma_subsamp_x)),
+ luma_stride, chroma_stride,
+ luma_grain_block + (luma_offset_y + (i << 1)) * luma_grain_stride +
+ luma_offset_x + (j << 1),
+ cb_grain_block +
+ (chroma_offset_y + (i << (1 - chroma_subsamp_y))) *
+ chroma_grain_stride +
+ chroma_offset_x + (j << (1 - chroma_subsamp_x)),
+ cr_grain_block +
+ (chroma_offset_y + (i << (1 - chroma_subsamp_y))) *
+ chroma_grain_stride +
+ chroma_offset_x + (j << (1 - chroma_subsamp_x)),
+ luma_grain_stride, chroma_grain_stride,
+ AOMMIN(luma_subblock_size_y >> 1, height / 2 - y) - i,
+ AOMMIN(luma_subblock_size_x >> 1, width / 2 - x) - j, bit_depth,
+ chroma_subsamp_y, chroma_subsamp_x, mc_identity);
+ }
+
+ if (overlap) {
+ if (x) {
+ // Copy overlapped column bufer to line buffer
+ copy_area(y_col_buf + (luma_subblock_size_y << 1), 2,
+ y_line_buf + (x << 1), luma_stride, 2, 2);
+
+ copy_area(
+ cb_col_buf + (chroma_subblock_size_y << (1 - chroma_subsamp_x)),
+ 2 >> chroma_subsamp_x,
+ cb_line_buf + (x << (1 - chroma_subsamp_x)), chroma_stride,
+ 2 >> chroma_subsamp_x, 2 >> chroma_subsamp_y);
+
+ copy_area(
+ cr_col_buf + (chroma_subblock_size_y << (1 - chroma_subsamp_x)),
+ 2 >> chroma_subsamp_x,
+ cr_line_buf + (x << (1 - chroma_subsamp_x)), chroma_stride,
+ 2 >> chroma_subsamp_x, 2 >> chroma_subsamp_y);
+ }
+
+ // Copy grain to the line buffer for overlap with a bottom block
+ copy_area(
+ luma_grain_block +
+ (luma_offset_y + luma_subblock_size_y) * luma_grain_stride +
+ luma_offset_x + ((x ? 2 : 0)),
+ luma_grain_stride, y_line_buf + ((x ? x + 1 : 0) << 1), luma_stride,
+ AOMMIN(luma_subblock_size_x, width - (x << 1)) - (x ? 2 : 0), 2);
+
+ copy_area(cb_grain_block +
+ (chroma_offset_y + chroma_subblock_size_y) *
+ chroma_grain_stride +
+ chroma_offset_x + (x ? 2 >> chroma_subsamp_x : 0),
+ chroma_grain_stride,
+ cb_line_buf + ((x ? x + 1 : 0) << (1 - chroma_subsamp_x)),
+ chroma_stride,
+ AOMMIN(chroma_subblock_size_x,
+ ((width - (x << 1)) >> chroma_subsamp_x)) -
+ (x ? 2 >> chroma_subsamp_x : 0),
+ 2 >> chroma_subsamp_y);
+
+ copy_area(cr_grain_block +
+ (chroma_offset_y + chroma_subblock_size_y) *
+ chroma_grain_stride +
+ chroma_offset_x + (x ? 2 >> chroma_subsamp_x : 0),
+ chroma_grain_stride,
+ cr_line_buf + ((x ? x + 1 : 0) << (1 - chroma_subsamp_x)),
+ chroma_stride,
+ AOMMIN(chroma_subblock_size_x,
+ ((width - (x << 1)) >> chroma_subsamp_x)) -
+ (x ? 2 >> chroma_subsamp_x : 0),
+ 2 >> chroma_subsamp_y);
+
+ // Copy grain to the column buffer for overlap with the next block to
+ // the right
+
+ copy_area(luma_grain_block + luma_offset_y * luma_grain_stride +
+ luma_offset_x + luma_subblock_size_x,
+ luma_grain_stride, y_col_buf, 2, 2,
+ AOMMIN(luma_subblock_size_y + 2, height - (y << 1)));
+
+ copy_area(cb_grain_block + chroma_offset_y * chroma_grain_stride +
+ chroma_offset_x + chroma_subblock_size_x,
+ chroma_grain_stride, cb_col_buf, 2 >> chroma_subsamp_x,
+ 2 >> chroma_subsamp_x,
+ AOMMIN(chroma_subblock_size_y + (2 >> chroma_subsamp_y),
+ (height - (y << 1)) >> chroma_subsamp_y));
+
+ copy_area(cr_grain_block + chroma_offset_y * chroma_grain_stride +
+ chroma_offset_x + chroma_subblock_size_x,
+ chroma_grain_stride, cr_col_buf, 2 >> chroma_subsamp_x,
+ 2 >> chroma_subsamp_x,
+ AOMMIN(chroma_subblock_size_y + (2 >> chroma_subsamp_y),
+ (height - (y << 1)) >> chroma_subsamp_y));
+ }
+ }
+ }
+
+ dealloc_arrays(params, &pred_pos_luma, &pred_pos_chroma, &luma_grain_block,
+ &cb_grain_block, &cr_grain_block, &y_line_buf, &cb_line_buf,
+ &cr_line_buf, &y_col_buf, &cb_col_buf, &cr_col_buf);
+ return 0;
+}
diff --git a/third_party/aom/av1/decoder/grain_synthesis.h b/third_party/aom/av1/decoder/grain_synthesis.h
new file mode 100644
index 0000000000..9858ce0013
--- /dev/null
+++ b/third_party/aom/av1/decoder/grain_synthesis.h
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2016, Alliance for Open Media. All rights reserved
+ *
+ * This source code is subject to the terms of the BSD 2 Clause License and
+ * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
+ * was not distributed with this source code in the LICENSE file, you can
+ * obtain it at www.aomedia.org/license/software. If the Alliance for Open
+ * Media Patent License 1.0 was not distributed with this source code in the
+ * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
+ */
+
+/*!\file
+ * \brief Describes film grain synthesis
+ *
+ */
+#ifndef AOM_AV1_DECODER_GRAIN_SYNTHESIS_H_
+#define AOM_AV1_DECODER_GRAIN_SYNTHESIS_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stdint.h>
+
+#include "aom_dsp/grain_params.h"
+#include "aom/aom_image.h"
+
+/*!\brief Add film grain
+ *
+ * Add film grain to an image
+ *
+ * Returns 0 for success, -1 for failure
+ *
+ * \param[in] grain_params Grain parameters
+ * \param[in] luma luma plane
+ * \param[in] cb cb plane
+ * \param[in] cr cr plane
+ * \param[in] height luma plane height
+ * \param[in] width luma plane width
+ * \param[in] luma_stride luma plane stride
+ * \param[in] chroma_stride chroma plane stride
+ */
+int av1_add_film_grain_run(const aom_film_grain_t *grain_params, uint8_t *luma,
+ uint8_t *cb, uint8_t *cr, int height, int width,
+ int luma_stride, int chroma_stride,
+ int use_high_bit_depth, int chroma_subsamp_y,
+ int chroma_subsamp_x, int mc_identity);
+
+/*!\brief Add film grain
+ *
+ * Add film grain to an image
+ *
+ * Returns 0 for success, -1 for failure
+ *
+ * \param[in] grain_params Grain parameters
+ * \param[in] src Source image
+ * \param[out] dst Resulting image with grain
+ */
+int av1_add_film_grain(const aom_film_grain_t *grain_params,
+ const aom_image_t *src, aom_image_t *dst);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif // AOM_AV1_DECODER_GRAIN_SYNTHESIS_H_
diff --git a/third_party/aom/av1/decoder/inspection.c b/third_party/aom/av1/decoder/inspection.c
new file mode 100644
index 0000000000..288d69a224
--- /dev/null
+++ b/third_party/aom/av1/decoder/inspection.c
@@ -0,0 +1,162 @@
+/*
+ * Copyright (c) 2017, Alliance for Open Media. All rights reserved
+ *
+ * This source code is subject to the terms of the BSD 2 Clause License and
+ * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
+ * was not distributed with this source code in the LICENSE file, you can
+ * obtain it at www.aomedia.org/license/software. If the Alliance for Open
+ * Media Patent License 1.0 was not distributed with this source code in the
+ * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "av1/decoder/decoder.h"
+#include "av1/decoder/inspection.h"
+#include "av1/common/enums.h"
+#include "av1/common/cdef.h"
+
+static void ifd_init_mi_rc(insp_frame_data *fd, int mi_cols, int mi_rows) {
+ fd->mi_cols = mi_cols;
+ fd->mi_rows = mi_rows;
+ fd->mi_grid = (insp_mi_data *)aom_malloc(sizeof(insp_mi_data) * fd->mi_rows *
+ fd->mi_cols);
+ if (!fd->mi_grid) {
+ fprintf(stderr, "Error allocating inspection data\n");
+ abort();
+ }
+}
+
+void ifd_init(insp_frame_data *fd, int frame_width, int frame_height) {
+ int mi_cols = ALIGN_POWER_OF_TWO(frame_width, 3) >> MI_SIZE_LOG2;
+ int mi_rows = ALIGN_POWER_OF_TWO(frame_height, 3) >> MI_SIZE_LOG2;
+ ifd_init_mi_rc(fd, mi_cols, mi_rows);
+}
+
+void ifd_clear(insp_frame_data *fd) {
+ aom_free(fd->mi_grid);
+ fd->mi_grid = NULL;
+}
+
+/* TODO(negge) This function may be called by more than one thread when using
+ a multi-threaded decoder and this may cause a data race. */
+int ifd_inspect(insp_frame_data *fd, void *decoder, int skip_not_transform) {
+ struct AV1Decoder *pbi = (struct AV1Decoder *)decoder;
+ AV1_COMMON *const cm = &pbi->common;
+ const CommonModeInfoParams *const mi_params = &cm->mi_params;
+ const CommonQuantParams *quant_params = &cm->quant_params;
+
+ if (fd->mi_rows != mi_params->mi_rows || fd->mi_cols != mi_params->mi_cols) {
+ ifd_clear(fd);
+ ifd_init_mi_rc(fd, mi_params->mi_rows, mi_params->mi_cols);
+ }
+ fd->show_existing_frame = cm->show_existing_frame;
+ fd->frame_number = cm->current_frame.frame_number;
+ fd->show_frame = cm->show_frame;
+ fd->frame_type = cm->current_frame.frame_type;
+ fd->base_qindex = quant_params->base_qindex;
+ // Set width and height of the first tile until generic support can be added
+ TileInfo tile_info;
+ av1_tile_set_row(&tile_info, cm, 0);
+ av1_tile_set_col(&tile_info, cm, 0);
+ fd->tile_mi_cols = tile_info.mi_col_end - tile_info.mi_col_start;
+ fd->tile_mi_rows = tile_info.mi_row_end - tile_info.mi_row_start;
+ fd->delta_q_present_flag = cm->delta_q_info.delta_q_present_flag;
+ fd->delta_q_res = cm->delta_q_info.delta_q_res;
+#if CONFIG_ACCOUNTING
+ fd->accounting = &pbi->accounting;
+#endif
+ // TODO(negge): copy per frame CDEF data
+ int i, j;
+ for (i = 0; i < MAX_SEGMENTS; i++) {
+ for (j = 0; j < 2; j++) {
+ fd->y_dequant[i][j] = quant_params->y_dequant_QTX[i][j];
+ fd->u_dequant[i][j] = quant_params->u_dequant_QTX[i][j];
+ fd->v_dequant[i][j] = quant_params->v_dequant_QTX[i][j];
+ }
+ }
+ for (j = 0; j < mi_params->mi_rows; j++) {
+ for (i = 0; i < mi_params->mi_cols; i++) {
+ const MB_MODE_INFO *mbmi =
+ mi_params->mi_grid_base[j * mi_params->mi_stride + i];
+ insp_mi_data *mi = &fd->mi_grid[j * mi_params->mi_cols + i];
+ // Segment
+ mi->segment_id = mbmi->segment_id;
+ // Motion Vectors
+ mi->mv[0].row = mbmi->mv[0].as_mv.row;
+ mi->mv[0].col = mbmi->mv[0].as_mv.col;
+ mi->mv[1].row = mbmi->mv[1].as_mv.row;
+ mi->mv[1].col = mbmi->mv[1].as_mv.col;
+ // Reference Frames
+ mi->ref_frame[0] = mbmi->ref_frame[0];
+ mi->ref_frame[1] = mbmi->ref_frame[1];
+ // Prediction Mode
+ mi->mode = mbmi->mode;
+ mi->intrabc = (int16_t)mbmi->use_intrabc;
+ mi->palette = (int16_t)mbmi->palette_mode_info.palette_size[0];
+ mi->uv_palette = (int16_t)mbmi->palette_mode_info.palette_size[1];
+ // Prediction Mode for Chromatic planes
+ if (mi->mode < INTRA_MODES) {
+ mi->uv_mode = mbmi->uv_mode;
+ } else {
+ mi->uv_mode = UV_MODE_INVALID;
+ }
+
+ mi->motion_mode = mbmi->motion_mode;
+ mi->compound_type = mbmi->interinter_comp.type;
+
+ // Block Size
+ mi->bsize = mbmi->bsize;
+ // Skip Flag
+ mi->skip = mbmi->skip_txfm;
+ mi->filter[0] = av1_extract_interp_filter(mbmi->interp_filters, 0);
+ mi->filter[1] = av1_extract_interp_filter(mbmi->interp_filters, 1);
+ mi->dual_filter_type = mi->filter[0] * 3 + mi->filter[1];
+
+ // Transform
+ // TODO(anyone): extract tx type info from mbmi->txk_type[].
+
+ const BLOCK_SIZE bsize = mbmi->bsize;
+ const int c = i % mi_size_wide[bsize];
+ const int r = j % mi_size_high[bsize];
+ if (is_inter_block(mbmi) || is_intrabc_block(mbmi))
+ mi->tx_size = mbmi->inter_tx_size[av1_get_txb_size_index(bsize, r, c)];
+ else
+ mi->tx_size = mbmi->tx_size;
+
+ if (skip_not_transform && mi->skip) mi->tx_size = -1;
+
+ if (mi->skip) {
+ const int tx_type_row = j - j % tx_size_high_unit[mi->tx_size];
+ const int tx_type_col = i - i % tx_size_wide_unit[mi->tx_size];
+ const int tx_type_map_idx =
+ tx_type_row * mi_params->mi_stride + tx_type_col;
+ mi->tx_type = mi_params->tx_type_map[tx_type_map_idx];
+ } else {
+ mi->tx_type = 0;
+ }
+
+ if (skip_not_transform &&
+ (mi->skip || mbmi->tx_skip[av1_get_txk_type_index(bsize, r, c)]))
+ mi->tx_type = -1;
+
+ mi->cdef_level = cm->cdef_info.cdef_strengths[mbmi->cdef_strength] /
+ CDEF_SEC_STRENGTHS;
+ mi->cdef_strength = cm->cdef_info.cdef_strengths[mbmi->cdef_strength] %
+ CDEF_SEC_STRENGTHS;
+
+ mi->cdef_strength += mi->cdef_strength == 3;
+ if (mbmi->uv_mode == UV_CFL_PRED) {
+ mi->cfl_alpha_idx = mbmi->cfl_alpha_idx;
+ mi->cfl_alpha_sign = mbmi->cfl_alpha_signs;
+ } else {
+ mi->cfl_alpha_idx = 0;
+ mi->cfl_alpha_sign = 0;
+ }
+ // delta_q
+ mi->current_qindex = mbmi->current_qindex;
+ }
+ }
+ return 1;
+}
diff --git a/third_party/aom/av1/decoder/inspection.h b/third_party/aom/av1/decoder/inspection.h
new file mode 100644
index 0000000000..70b1c80fab
--- /dev/null
+++ b/third_party/aom/av1/decoder/inspection.h
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2017, Alliance for Open Media. All rights reserved
+ *
+ * This source code is subject to the terms of the BSD 2 Clause License and
+ * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
+ * was not distributed with this source code in the LICENSE file, you can
+ * obtain it at www.aomedia.org/license/software. If the Alliance for Open
+ * Media Patent License 1.0 was not distributed with this source code in the
+ * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
+ */
+#ifndef AOM_AV1_DECODER_INSPECTION_H_
+#define AOM_AV1_DECODER_INSPECTION_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+#include "av1/common/seg_common.h"
+#if CONFIG_ACCOUNTING
+#include "av1/decoder/accounting.h"
+#endif
+
+#ifndef AOM_AOM_AOMDX_H_
+typedef void (*aom_inspect_cb)(void *decoder, void *data);
+#endif
+
+typedef struct insp_mv insp_mv;
+
+struct insp_mv {
+ int16_t row;
+ int16_t col;
+};
+
+typedef struct insp_mi_data insp_mi_data;
+
+struct insp_mi_data {
+ insp_mv mv[2];
+ int16_t ref_frame[2];
+ int16_t mode;
+ int16_t uv_mode;
+ int16_t bsize;
+ int16_t skip;
+ int16_t segment_id;
+ int16_t dual_filter_type;
+ int16_t filter[2];
+ int16_t tx_type;
+ int16_t tx_size;
+ int16_t cdef_level;
+ int16_t cdef_strength;
+ int16_t cfl_alpha_idx;
+ int16_t cfl_alpha_sign;
+ int16_t current_qindex;
+ int16_t compound_type;
+ int16_t motion_mode;
+ int16_t intrabc;
+ int16_t palette;
+ int16_t uv_palette;
+};
+
+typedef struct insp_frame_data insp_frame_data;
+
+struct insp_frame_data {
+#if CONFIG_ACCOUNTING
+ Accounting *accounting;
+#endif
+ insp_mi_data *mi_grid;
+ int16_t frame_number;
+ int show_frame;
+ int frame_type;
+ int base_qindex;
+ int mi_rows;
+ int mi_cols;
+ int tile_mi_rows;
+ int tile_mi_cols;
+ int16_t y_dequant[MAX_SEGMENTS][2];
+ int16_t u_dequant[MAX_SEGMENTS][2];
+ int16_t v_dequant[MAX_SEGMENTS][2];
+ // TODO(negge): add per frame CDEF data
+ int delta_q_present_flag;
+ int delta_q_res;
+ int show_existing_frame;
+};
+
+void ifd_init(insp_frame_data *fd, int frame_width, int frame_height);
+void ifd_clear(insp_frame_data *fd);
+int ifd_inspect(insp_frame_data *fd, void *decoder, int skip_not_transform);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif // __cplusplus
+#endif // AOM_AV1_DECODER_INSPECTION_H_
diff --git a/third_party/aom/av1/decoder/obu.c b/third_party/aom/av1/decoder/obu.c
new file mode 100644
index 0000000000..0e31ce9404
--- /dev/null
+++ b/third_party/aom/av1/decoder/obu.c
@@ -0,0 +1,1101 @@
+/*
+ * Copyright (c) 2017, Alliance for Open Media. All rights reserved
+ *
+ * This source code is subject to the terms of the BSD 2 Clause License and
+ * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
+ * was not distributed with this source code in the LICENSE file, you can
+ * obtain it at www.aomedia.org/license/software. If the Alliance for Open
+ * Media Patent License 1.0 was not distributed with this source code in the
+ * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
+ */
+
+#include <assert.h>
+
+#include "config/aom_config.h"
+#include "config/aom_scale_rtcd.h"
+
+#include "aom/aom_codec.h"
+#include "aom_dsp/bitreader_buffer.h"
+#include "aom_ports/mem_ops.h"
+
+#include "av1/common/common.h"
+#include "av1/common/obu_util.h"
+#include "av1/common/timing.h"
+#include "av1/decoder/decoder.h"
+#include "av1/decoder/decodeframe.h"
+#include "av1/decoder/obu.h"
+
+aom_codec_err_t aom_get_num_layers_from_operating_point_idc(
+ int operating_point_idc, unsigned int *number_spatial_layers,
+ unsigned int *number_temporal_layers) {
+ // derive number of spatial/temporal layers from operating_point_idc
+
+ if (!number_spatial_layers || !number_temporal_layers)
+ return AOM_CODEC_INVALID_PARAM;
+
+ if (operating_point_idc == 0) {
+ *number_temporal_layers = 1;
+ *number_spatial_layers = 1;
+ } else {
+ *number_spatial_layers = 0;
+ *number_temporal_layers = 0;
+ for (int j = 0; j < MAX_NUM_SPATIAL_LAYERS; j++) {
+ *number_spatial_layers +=
+ (operating_point_idc >> (j + MAX_NUM_TEMPORAL_LAYERS)) & 0x1;
+ }
+ for (int j = 0; j < MAX_NUM_TEMPORAL_LAYERS; j++) {
+ *number_temporal_layers += (operating_point_idc >> j) & 0x1;
+ }
+ }
+
+ return AOM_CODEC_OK;
+}
+
+static int is_obu_in_current_operating_point(AV1Decoder *pbi,
+ const ObuHeader *obu_header) {
+ if (!pbi->current_operating_point || !obu_header->has_extension) {
+ return 1;
+ }
+
+ if ((pbi->current_operating_point >> obu_header->temporal_layer_id) & 0x1 &&
+ (pbi->current_operating_point >> (obu_header->spatial_layer_id + 8)) &
+ 0x1) {
+ return 1;
+ }
+ return 0;
+}
+
+static int byte_alignment(AV1_COMMON *const cm,
+ struct aom_read_bit_buffer *const rb) {
+ while (rb->bit_offset & 7) {
+ if (aom_rb_read_bit(rb)) {
+ cm->error->error_code = AOM_CODEC_CORRUPT_FRAME;
+ return -1;
+ }
+ }
+ return 0;
+}
+
+static uint32_t read_temporal_delimiter_obu(void) { return 0; }
+
+// Returns a boolean that indicates success.
+static int read_bitstream_level(AV1_LEVEL *seq_level_idx,
+ struct aom_read_bit_buffer *rb) {
+ *seq_level_idx = aom_rb_read_literal(rb, LEVEL_BITS);
+ if (!is_valid_seq_level_idx(*seq_level_idx)) return 0;
+ return 1;
+}
+
+// Returns whether two sequence headers are consistent with each other.
+// Note that the 'op_params' field is not compared per Section 7.5 in the spec:
+// Within a particular coded video sequence, the contents of
+// sequence_header_obu must be bit-identical each time the sequence header
+// appears except for the contents of operating_parameters_info.
+static int are_seq_headers_consistent(const SequenceHeader *seq_params_old,
+ const SequenceHeader *seq_params_new) {
+ return !memcmp(seq_params_old, seq_params_new,
+ offsetof(SequenceHeader, op_params));
+}
+
+// On success, sets pbi->sequence_header_ready to 1 and returns the number of
+// bytes read from 'rb'.
+// On failure, sets pbi->common.error.error_code and returns 0.
+static uint32_t read_sequence_header_obu(AV1Decoder *pbi,
+ struct aom_read_bit_buffer *rb) {
+ AV1_COMMON *const cm = &pbi->common;
+ const uint32_t saved_bit_offset = rb->bit_offset;
+
+ // Verify rb has been configured to report errors.
+ assert(rb->error_handler);
+
+ // Use a local variable to store the information as we decode. At the end,
+ // if no errors have occurred, cm->seq_params is updated.
+ SequenceHeader sh = *cm->seq_params;
+ SequenceHeader *const seq_params = &sh;
+
+ seq_params->profile = av1_read_profile(rb);
+ if (seq_params->profile > CONFIG_MAX_DECODE_PROFILE) {
+ pbi->error.error_code = AOM_CODEC_UNSUP_BITSTREAM;
+ return 0;
+ }
+
+ // Still picture or not
+ seq_params->still_picture = aom_rb_read_bit(rb);
+ seq_params->reduced_still_picture_hdr = aom_rb_read_bit(rb);
+ // Video must have reduced_still_picture_hdr = 0
+ if (!seq_params->still_picture && seq_params->reduced_still_picture_hdr) {
+ pbi->error.error_code = AOM_CODEC_UNSUP_BITSTREAM;
+ return 0;
+ }
+
+ if (seq_params->reduced_still_picture_hdr) {
+ seq_params->timing_info_present = 0;
+ seq_params->decoder_model_info_present_flag = 0;
+ seq_params->display_model_info_present_flag = 0;
+ seq_params->operating_points_cnt_minus_1 = 0;
+ seq_params->operating_point_idc[0] = 0;
+ if (!read_bitstream_level(&seq_params->seq_level_idx[0], rb)) {
+ pbi->error.error_code = AOM_CODEC_UNSUP_BITSTREAM;
+ return 0;
+ }
+ seq_params->tier[0] = 0;
+ seq_params->op_params[0].decoder_model_param_present_flag = 0;
+ seq_params->op_params[0].display_model_param_present_flag = 0;
+ } else {
+ seq_params->timing_info_present = aom_rb_read_bit(rb);
+ if (seq_params->timing_info_present) {
+ av1_read_timing_info_header(&seq_params->timing_info, &pbi->error, rb);
+
+ seq_params->decoder_model_info_present_flag = aom_rb_read_bit(rb);
+ if (seq_params->decoder_model_info_present_flag)
+ av1_read_decoder_model_info(&seq_params->decoder_model_info, rb);
+ } else {
+ seq_params->decoder_model_info_present_flag = 0;
+ }
+ seq_params->display_model_info_present_flag = aom_rb_read_bit(rb);
+ seq_params->operating_points_cnt_minus_1 =
+ aom_rb_read_literal(rb, OP_POINTS_CNT_MINUS_1_BITS);
+ for (int i = 0; i < seq_params->operating_points_cnt_minus_1 + 1; i++) {
+ seq_params->operating_point_idc[i] =
+ aom_rb_read_literal(rb, OP_POINTS_IDC_BITS);
+ if (!read_bitstream_level(&seq_params->seq_level_idx[i], rb)) {
+ pbi->error.error_code = AOM_CODEC_UNSUP_BITSTREAM;
+ return 0;
+ }
+ // This is the seq_level_idx[i] > 7 check in the spec. seq_level_idx 7
+ // is equivalent to level 3.3.
+ if (seq_params->seq_level_idx[i] >= SEQ_LEVEL_4_0)
+ seq_params->tier[i] = aom_rb_read_bit(rb);
+ else
+ seq_params->tier[i] = 0;
+ if (seq_params->decoder_model_info_present_flag) {
+ seq_params->op_params[i].decoder_model_param_present_flag =
+ aom_rb_read_bit(rb);
+ if (seq_params->op_params[i].decoder_model_param_present_flag)
+ av1_read_op_parameters_info(&seq_params->op_params[i],
+ seq_params->decoder_model_info
+ .encoder_decoder_buffer_delay_length,
+ rb);
+ } else {
+ seq_params->op_params[i].decoder_model_param_present_flag = 0;
+ }
+ if (seq_params->timing_info_present &&
+ (seq_params->timing_info.equal_picture_interval ||
+ seq_params->op_params[i].decoder_model_param_present_flag)) {
+ seq_params->op_params[i].bitrate = av1_max_level_bitrate(
+ seq_params->profile, seq_params->seq_level_idx[i],
+ seq_params->tier[i]);
+ // Level with seq_level_idx = 31 returns a high "dummy" bitrate to pass
+ // the check
+ if (seq_params->op_params[i].bitrate == 0)
+ aom_internal_error(&pbi->error, AOM_CODEC_UNSUP_BITSTREAM,
+ "AV1 does not support this combination of "
+ "profile, level, and tier.");
+ // Buffer size in bits/s is bitrate in bits/s * 1 s
+ seq_params->op_params[i].buffer_size = seq_params->op_params[i].bitrate;
+ }
+ if (seq_params->timing_info_present &&
+ seq_params->timing_info.equal_picture_interval &&
+ !seq_params->op_params[i].decoder_model_param_present_flag) {
+ // When the decoder_model_parameters are not sent for this op, set
+ // the default ones that can be used with the resource availability mode
+ seq_params->op_params[i].decoder_buffer_delay = 70000;
+ seq_params->op_params[i].encoder_buffer_delay = 20000;
+ seq_params->op_params[i].low_delay_mode_flag = 0;
+ }
+
+ if (seq_params->display_model_info_present_flag) {
+ seq_params->op_params[i].display_model_param_present_flag =
+ aom_rb_read_bit(rb);
+ if (seq_params->op_params[i].display_model_param_present_flag) {
+ seq_params->op_params[i].initial_display_delay =
+ aom_rb_read_literal(rb, 4) + 1;
+ if (seq_params->op_params[i].initial_display_delay > 10)
+ aom_internal_error(
+ &pbi->error, AOM_CODEC_UNSUP_BITSTREAM,
+ "AV1 does not support more than 10 decoded frames delay");
+ } else {
+ seq_params->op_params[i].initial_display_delay = 10;
+ }
+ } else {
+ seq_params->op_params[i].display_model_param_present_flag = 0;
+ seq_params->op_params[i].initial_display_delay = 10;
+ }
+ }
+ }
+ // This decoder supports all levels. Choose operating point provided by
+ // external means
+ int operating_point = pbi->operating_point;
+ if (operating_point < 0 ||
+ operating_point > seq_params->operating_points_cnt_minus_1)
+ operating_point = 0;
+ pbi->current_operating_point =
+ seq_params->operating_point_idc[operating_point];
+ if (aom_get_num_layers_from_operating_point_idc(
+ pbi->current_operating_point, &pbi->number_spatial_layers,
+ &pbi->number_temporal_layers) != AOM_CODEC_OK) {
+ pbi->error.error_code = AOM_CODEC_ERROR;
+ return 0;
+ }
+
+ av1_read_sequence_header(cm, rb, seq_params);
+
+ av1_read_color_config(rb, pbi->allow_lowbitdepth, seq_params, &pbi->error);
+ if (!(seq_params->subsampling_x == 0 && seq_params->subsampling_y == 0) &&
+ !(seq_params->subsampling_x == 1 && seq_params->subsampling_y == 1) &&
+ !(seq_params->subsampling_x == 1 && seq_params->subsampling_y == 0)) {
+ aom_internal_error(&pbi->error, AOM_CODEC_UNSUP_BITSTREAM,
+ "Only 4:4:4, 4:2:2 and 4:2:0 are currently supported, "
+ "%d %d subsampling is not supported.\n",
+ seq_params->subsampling_x, seq_params->subsampling_y);
+ }
+
+ seq_params->film_grain_params_present = aom_rb_read_bit(rb);
+
+ if (av1_check_trailing_bits(pbi, rb) != 0) {
+ // pbi->error.error_code is already set.
+ return 0;
+ }
+
+ // If a sequence header has been decoded before, we check if the new
+ // one is consistent with the old one.
+ if (pbi->sequence_header_ready) {
+ if (!are_seq_headers_consistent(cm->seq_params, seq_params))
+ pbi->sequence_header_changed = 1;
+ }
+
+ *cm->seq_params = *seq_params;
+ pbi->sequence_header_ready = 1;
+
+ return ((rb->bit_offset - saved_bit_offset + 7) >> 3);
+}
+
+// On success, returns the frame header size. On failure, calls
+// aom_internal_error and does not return. If show existing frame,
+// also marks the data processing to end after the frame header.
+static uint32_t read_frame_header_obu(AV1Decoder *pbi,
+ struct aom_read_bit_buffer *rb,
+ const uint8_t *data,
+ const uint8_t **p_data_end,
+ int trailing_bits_present) {
+ const uint32_t hdr_size =
+ av1_decode_frame_headers_and_setup(pbi, rb, trailing_bits_present);
+ const AV1_COMMON *cm = &pbi->common;
+ if (cm->show_existing_frame) {
+ *p_data_end = data + hdr_size;
+ }
+ return hdr_size;
+}
+
+// On success, returns the tile group header size. On failure, calls
+// aom_internal_error() and returns -1.
+static int32_t read_tile_group_header(AV1Decoder *pbi,
+ struct aom_read_bit_buffer *rb,
+ int *start_tile, int *end_tile,
+ int tile_start_implicit) {
+ AV1_COMMON *const cm = &pbi->common;
+ CommonTileParams *const tiles = &cm->tiles;
+ uint32_t saved_bit_offset = rb->bit_offset;
+ int tile_start_and_end_present_flag = 0;
+ const int num_tiles = tiles->rows * tiles->cols;
+
+ if (!tiles->large_scale && num_tiles > 1) {
+ tile_start_and_end_present_flag = aom_rb_read_bit(rb);
+ if (tile_start_implicit && tile_start_and_end_present_flag) {
+ aom_internal_error(
+ &pbi->error, AOM_CODEC_UNSUP_BITSTREAM,
+ "For OBU_FRAME type obu tile_start_and_end_present_flag must be 0");
+ return -1;
+ }
+ }
+ if (tiles->large_scale || num_tiles == 1 ||
+ !tile_start_and_end_present_flag) {
+ *start_tile = 0;
+ *end_tile = num_tiles - 1;
+ } else {
+ int tile_bits = tiles->log2_rows + tiles->log2_cols;
+ *start_tile = aom_rb_read_literal(rb, tile_bits);
+ *end_tile = aom_rb_read_literal(rb, tile_bits);
+ }
+ if (*start_tile != pbi->next_start_tile) {
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "tg_start (%d) must be equal to %d", *start_tile,
+ pbi->next_start_tile);
+ return -1;
+ }
+ if (*start_tile > *end_tile) {
+ aom_internal_error(
+ &pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "tg_end (%d) must be greater than or equal to tg_start (%d)", *end_tile,
+ *start_tile);
+ return -1;
+ }
+ if (*end_tile >= num_tiles) {
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "tg_end (%d) must be less than NumTiles (%d)", *end_tile,
+ num_tiles);
+ return -1;
+ }
+ pbi->next_start_tile = (*end_tile == num_tiles - 1) ? 0 : *end_tile + 1;
+
+ return ((rb->bit_offset - saved_bit_offset + 7) >> 3);
+}
+
+// On success, returns the tile group OBU size. On failure, sets
+// pbi->common.error.error_code and returns 0.
+static uint32_t read_one_tile_group_obu(
+ AV1Decoder *pbi, struct aom_read_bit_buffer *rb, int is_first_tg,
+ const uint8_t *data, const uint8_t *data_end, const uint8_t **p_data_end,
+ int *is_last_tg, int tile_start_implicit) {
+ AV1_COMMON *const cm = &pbi->common;
+ int start_tile, end_tile;
+ int32_t header_size, tg_payload_size;
+
+ assert((rb->bit_offset & 7) == 0);
+ assert(rb->bit_buffer + aom_rb_bytes_read(rb) == data);
+
+ header_size = read_tile_group_header(pbi, rb, &start_tile, &end_tile,
+ tile_start_implicit);
+ if (header_size == -1 || byte_alignment(cm, rb)) return 0;
+ data += header_size;
+ av1_decode_tg_tiles_and_wrapup(pbi, data, data_end, p_data_end, start_tile,
+ end_tile, is_first_tg);
+
+ tg_payload_size = (uint32_t)(*p_data_end - data);
+
+ *is_last_tg = end_tile == cm->tiles.rows * cm->tiles.cols - 1;
+ return header_size + tg_payload_size;
+}
+
+static void alloc_tile_list_buffer(AV1Decoder *pbi) {
+ // The resolution of the output frame is read out from the bitstream. The data
+ // are stored in the order of Y plane, U plane and V plane. As an example, for
+ // image format 4:2:0, the output frame of U plane and V plane is 1/4 of the
+ // output frame.
+ AV1_COMMON *const cm = &pbi->common;
+ int tile_width, tile_height;
+ av1_get_uniform_tile_size(cm, &tile_width, &tile_height);
+ const int tile_width_in_pixels = tile_width * MI_SIZE;
+ const int tile_height_in_pixels = tile_height * MI_SIZE;
+ const int output_frame_width =
+ (pbi->output_frame_width_in_tiles_minus_1 + 1) * tile_width_in_pixels;
+ const int output_frame_height =
+ (pbi->output_frame_height_in_tiles_minus_1 + 1) * tile_height_in_pixels;
+ // The output frame is used to store the decoded tile list. The decoded tile
+ // list has to fit into 1 output frame.
+ assert((pbi->tile_count_minus_1 + 1) <=
+ (pbi->output_frame_width_in_tiles_minus_1 + 1) *
+ (pbi->output_frame_height_in_tiles_minus_1 + 1));
+
+ // Allocate the tile list output buffer.
+ // Note: if cm->seq_params->use_highbitdepth is 1 and
+ // cm->seq_params->bit_depth is 8, we could allocate less memory, namely, 8
+ // bits/pixel.
+ if (aom_alloc_frame_buffer(&pbi->tile_list_outbuf, output_frame_width,
+ output_frame_height, cm->seq_params->subsampling_x,
+ cm->seq_params->subsampling_y,
+ (cm->seq_params->use_highbitdepth &&
+ (cm->seq_params->bit_depth > AOM_BITS_8)),
+ 0, cm->features.byte_alignment, 0, 0))
+ aom_internal_error(&pbi->error, AOM_CODEC_MEM_ERROR,
+ "Failed to allocate the tile list output buffer");
+}
+
+static void yv12_tile_copy(const YV12_BUFFER_CONFIG *src, int hstart1,
+ int hend1, int vstart1, int vend1,
+ YV12_BUFFER_CONFIG *dst, int hstart2, int vstart2,
+ int plane) {
+ const int src_stride = (plane > 0) ? src->strides[1] : src->strides[0];
+ const int dst_stride = (plane > 0) ? dst->strides[1] : dst->strides[0];
+ int row, col;
+
+ assert(src->flags & YV12_FLAG_HIGHBITDEPTH);
+ assert(!(dst->flags & YV12_FLAG_HIGHBITDEPTH));
+
+ const uint16_t *src16 =
+ CONVERT_TO_SHORTPTR(src->buffers[plane] + vstart1 * src_stride + hstart1);
+ uint8_t *dst8 = dst->buffers[plane] + vstart2 * dst_stride + hstart2;
+
+ for (row = vstart1; row < vend1; ++row) {
+ for (col = 0; col < (hend1 - hstart1); ++col) *dst8++ = (uint8_t)(*src16++);
+ src16 += src_stride - (hend1 - hstart1);
+ dst8 += dst_stride - (hend1 - hstart1);
+ }
+ return;
+}
+
+static void copy_decoded_tile_to_tile_list_buffer(AV1Decoder *pbi,
+ int tile_idx) {
+ AV1_COMMON *const cm = &pbi->common;
+ int tile_width, tile_height;
+ av1_get_uniform_tile_size(cm, &tile_width, &tile_height);
+ const int tile_width_in_pixels = tile_width * MI_SIZE;
+ const int tile_height_in_pixels = tile_height * MI_SIZE;
+ const int ssy = cm->seq_params->subsampling_y;
+ const int ssx = cm->seq_params->subsampling_x;
+ const int num_planes = av1_num_planes(cm);
+
+ YV12_BUFFER_CONFIG *cur_frame = &cm->cur_frame->buf;
+ const int tr = tile_idx / (pbi->output_frame_width_in_tiles_minus_1 + 1);
+ const int tc = tile_idx % (pbi->output_frame_width_in_tiles_minus_1 + 1);
+ int plane;
+
+ // Copy decoded tile to the tile list output buffer.
+ for (plane = 0; plane < num_planes; ++plane) {
+ const int shift_x = plane > 0 ? ssx : 0;
+ const int shift_y = plane > 0 ? ssy : 0;
+ const int h = tile_height_in_pixels >> shift_y;
+ const int w = tile_width_in_pixels >> shift_x;
+
+ // src offset
+ int vstart1 = pbi->dec_tile_row * h;
+ int vend1 = vstart1 + h;
+ int hstart1 = pbi->dec_tile_col * w;
+ int hend1 = hstart1 + w;
+ // dst offset
+ int vstart2 = tr * h;
+ int hstart2 = tc * w;
+
+ if (cm->seq_params->use_highbitdepth &&
+ cm->seq_params->bit_depth == AOM_BITS_8) {
+ yv12_tile_copy(cur_frame, hstart1, hend1, vstart1, vend1,
+ &pbi->tile_list_outbuf, hstart2, vstart2, plane);
+ } else {
+ switch (plane) {
+ case 0:
+ aom_yv12_partial_copy_y(cur_frame, hstart1, hend1, vstart1, vend1,
+ &pbi->tile_list_outbuf, hstart2, vstart2);
+ break;
+ case 1:
+ aom_yv12_partial_copy_u(cur_frame, hstart1, hend1, vstart1, vend1,
+ &pbi->tile_list_outbuf, hstart2, vstart2);
+ break;
+ case 2:
+ aom_yv12_partial_copy_v(cur_frame, hstart1, hend1, vstart1, vend1,
+ &pbi->tile_list_outbuf, hstart2, vstart2);
+ break;
+ default: assert(0);
+ }
+ }
+ }
+}
+
+// Only called while large_scale_tile = 1.
+//
+// On success, returns the tile list OBU size. On failure, sets
+// pbi->common.error.error_code and returns 0.
+static uint32_t read_and_decode_one_tile_list(AV1Decoder *pbi,
+ struct aom_read_bit_buffer *rb,
+ const uint8_t *data,
+ const uint8_t *data_end,
+ const uint8_t **p_data_end,
+ int *frame_decoding_finished) {
+ AV1_COMMON *const cm = &pbi->common;
+ uint32_t tile_list_payload_size = 0;
+ const int num_tiles = cm->tiles.cols * cm->tiles.rows;
+ const int start_tile = 0;
+ const int end_tile = num_tiles - 1;
+ int i = 0;
+
+ // Process the tile list info.
+ pbi->output_frame_width_in_tiles_minus_1 = aom_rb_read_literal(rb, 8);
+ pbi->output_frame_height_in_tiles_minus_1 = aom_rb_read_literal(rb, 8);
+ pbi->tile_count_minus_1 = aom_rb_read_literal(rb, 16);
+ if (pbi->tile_count_minus_1 > MAX_TILES - 1) {
+ pbi->error.error_code = AOM_CODEC_CORRUPT_FRAME;
+ return 0;
+ }
+
+ // Allocate output frame buffer for the tile list.
+ alloc_tile_list_buffer(pbi);
+
+ uint32_t tile_list_info_bytes = 4;
+ tile_list_payload_size += tile_list_info_bytes;
+ data += tile_list_info_bytes;
+
+ int tile_idx = 0;
+ for (i = 0; i <= pbi->tile_count_minus_1; i++) {
+ // Process 1 tile.
+ // Reset the bit reader.
+ rb->bit_offset = 0;
+ rb->bit_buffer = data;
+
+ // Read out the tile info.
+ uint32_t tile_info_bytes = 5;
+ // Set reference for each tile.
+ int ref_idx = aom_rb_read_literal(rb, 8);
+ if (ref_idx >= MAX_EXTERNAL_REFERENCES) {
+ pbi->error.error_code = AOM_CODEC_CORRUPT_FRAME;
+ return 0;
+ }
+ av1_set_reference_dec(cm, cm->remapped_ref_idx[0], 1,
+ &pbi->ext_refs.refs[ref_idx]);
+
+ pbi->dec_tile_row = aom_rb_read_literal(rb, 8);
+ pbi->dec_tile_col = aom_rb_read_literal(rb, 8);
+ if (pbi->dec_tile_row < 0 || pbi->dec_tile_col < 0 ||
+ pbi->dec_tile_row >= cm->tiles.rows ||
+ pbi->dec_tile_col >= cm->tiles.cols) {
+ pbi->error.error_code = AOM_CODEC_CORRUPT_FRAME;
+ return 0;
+ }
+
+ pbi->coded_tile_data_size = aom_rb_read_literal(rb, 16) + 1;
+ data += tile_info_bytes;
+ if ((size_t)(data_end - data) < pbi->coded_tile_data_size) {
+ pbi->error.error_code = AOM_CODEC_CORRUPT_FRAME;
+ return 0;
+ }
+
+ av1_decode_tg_tiles_and_wrapup(pbi, data, data + pbi->coded_tile_data_size,
+ p_data_end, start_tile, end_tile, 0);
+ uint32_t tile_payload_size = (uint32_t)(*p_data_end - data);
+
+ tile_list_payload_size += tile_info_bytes + tile_payload_size;
+
+ // Update data ptr for next tile decoding.
+ data = *p_data_end;
+ assert(data <= data_end);
+
+ // Copy the decoded tile to the tile list output buffer.
+ copy_decoded_tile_to_tile_list_buffer(pbi, tile_idx);
+ tile_idx++;
+ }
+
+ *frame_decoding_finished = 1;
+ return tile_list_payload_size;
+}
+
+// Returns the last nonzero byte index in 'data'. If there is no nonzero byte in
+// 'data', returns -1.
+static int get_last_nonzero_byte_index(const uint8_t *data, size_t sz) {
+ // Scan backward and return on the first nonzero byte.
+ int i = (int)sz - 1;
+ while (i >= 0 && data[i] == 0) {
+ --i;
+ }
+ return i;
+}
+
+// Allocates metadata that was read and adds it to the decoders metadata array.
+static void alloc_read_metadata(AV1Decoder *const pbi,
+ OBU_METADATA_TYPE metadata_type,
+ const uint8_t *data, size_t sz,
+ aom_metadata_insert_flags_t insert_flag) {
+ if (!pbi->metadata) {
+ pbi->metadata = aom_img_metadata_array_alloc(0);
+ if (!pbi->metadata) {
+ aom_internal_error(&pbi->error, AOM_CODEC_MEM_ERROR,
+ "Failed to allocate metadata array");
+ }
+ }
+ aom_metadata_t *metadata =
+ aom_img_metadata_alloc(metadata_type, data, sz, insert_flag);
+ if (!metadata) {
+ aom_internal_error(&pbi->error, AOM_CODEC_MEM_ERROR,
+ "Error allocating metadata");
+ }
+ aom_metadata_t **metadata_array =
+ (aom_metadata_t **)realloc(pbi->metadata->metadata_array,
+ (pbi->metadata->sz + 1) * sizeof(metadata));
+ if (!metadata_array) {
+ aom_img_metadata_free(metadata);
+ aom_internal_error(&pbi->error, AOM_CODEC_MEM_ERROR,
+ "Error growing metadata array");
+ }
+ pbi->metadata->metadata_array = metadata_array;
+ pbi->metadata->metadata_array[pbi->metadata->sz] = metadata;
+ pbi->metadata->sz++;
+}
+
+// On failure, calls aom_internal_error() and does not return.
+static void read_metadata_itut_t35(AV1Decoder *const pbi, const uint8_t *data,
+ size_t sz) {
+ if (sz == 0) {
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "itu_t_t35_country_code is missing");
+ }
+ int country_code_size = 1;
+ if (*data == 0xFF) {
+ if (sz == 1) {
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "itu_t_t35_country_code_extension_byte is missing");
+ }
+ ++country_code_size;
+ }
+ int end_index = get_last_nonzero_byte_index(data, sz);
+ if (end_index < country_code_size) {
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "No trailing bits found in ITU-T T.35 metadata OBU");
+ }
+ // itu_t_t35_payload_bytes is byte aligned. Section 6.7.2 of the spec says:
+ // itu_t_t35_payload_bytes shall be bytes containing data registered as
+ // specified in Recommendation ITU-T T.35.
+ // Therefore the first trailing byte should be 0x80.
+ if (data[end_index] != 0x80) {
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "The last nonzero byte of the ITU-T T.35 metadata OBU "
+ "is 0x%02x, should be 0x80.",
+ data[end_index]);
+ }
+ alloc_read_metadata(pbi, OBU_METADATA_TYPE_ITUT_T35, data, end_index,
+ AOM_MIF_ANY_FRAME);
+}
+
+// On success, returns the number of bytes read from 'data'. On failure, calls
+// aom_internal_error() and does not return.
+static size_t read_metadata_hdr_cll(AV1Decoder *const pbi, const uint8_t *data,
+ size_t sz) {
+ const size_t kHdrCllPayloadSize = 4;
+ if (sz < kHdrCllPayloadSize) {
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "Incorrect HDR CLL metadata payload size");
+ }
+ alloc_read_metadata(pbi, OBU_METADATA_TYPE_HDR_CLL, data, kHdrCllPayloadSize,
+ AOM_MIF_ANY_FRAME);
+ return kHdrCllPayloadSize;
+}
+
+// On success, returns the number of bytes read from 'data'. On failure, calls
+// aom_internal_error() and does not return.
+static size_t read_metadata_hdr_mdcv(AV1Decoder *const pbi, const uint8_t *data,
+ size_t sz) {
+ const size_t kMdcvPayloadSize = 24;
+ if (sz < kMdcvPayloadSize) {
+ aom_internal_error(&pbi->error, AOM_CODEC_CORRUPT_FRAME,
+ "Incorrect HDR MDCV metadata payload size");
+ }
+ alloc_read_metadata(pbi, OBU_METADATA_TYPE_HDR_MDCV, data, kMdcvPayloadSize,
+ AOM_MIF_ANY_FRAME);
+ return kMdcvPayloadSize;
+}
+
+static void scalability_structure(struct aom_read_bit_buffer *rb) {
+ const int spatial_layers_cnt_minus_1 = aom_rb_read_literal(rb, 2);
+ const int spatial_layer_dimensions_present_flag = aom_rb_read_bit(rb);
+ const int spatial_layer_description_present_flag = aom_rb_read_bit(rb);
+ const int temporal_group_description_present_flag = aom_rb_read_bit(rb);
+ // scalability_structure_reserved_3bits must be set to zero and be ignored by
+ // decoders.
+ aom_rb_read_literal(rb, 3);
+
+ if (spatial_layer_dimensions_present_flag) {
+ for (int i = 0; i <= spatial_layers_cnt_minus_1; i++) {
+ aom_rb_read_literal(rb, 16);
+ aom_rb_read_literal(rb, 16);
+ }
+ }
+ if (spatial_layer_description_present_flag) {
+ for (int i = 0; i <= spatial_layers_cnt_minus_1; i++) {
+ aom_rb_read_literal(rb, 8);
+ }
+ }
+ if (temporal_group_description_present_flag) {
+ const int temporal_group_size = aom_rb_read_literal(rb, 8);
+ for (int i = 0; i < temporal_group_size; i++) {
+ aom_rb_read_literal(rb, 3);
+ aom_rb_read_bit(rb);
+ aom_rb_read_bit(rb);
+ const int temporal_group_ref_cnt = aom_rb_read_literal(rb, 3);
+ for (int j = 0; j < temporal_group_ref_cnt; j++) {
+ aom_rb_read_literal(rb, 8);
+ }
+ }
+ }
+}
+
+static void read_metadata_scalability(struct aom_read_bit_buffer *rb) {
+ const int scalability_mode_idc = aom_rb_read_literal(rb, 8);
+ if (scalability_mode_idc == SCALABILITY_SS) {
+ scalability_structure(rb);
+ }
+}
+
+static void read_metadata_timecode(struct aom_read_bit_buffer *rb) {
+ aom_rb_read_literal(rb, 5); // counting_type f(5)
+ const int full_timestamp_flag =
+ aom_rb_read_bit(rb); // full_timestamp_flag f(1)
+ aom_rb_read_bit(rb); // discontinuity_flag (f1)
+ aom_rb_read_bit(rb); // cnt_dropped_flag f(1)
+ aom_rb_read_literal(rb, 9); // n_frames f(9)
+ if (full_timestamp_flag) {
+ aom_rb_read_literal(rb, 6); // seconds_value f(6)
+ aom_rb_read_literal(rb, 6); // minutes_value f(6)
+ aom_rb_read_literal(rb, 5); // hours_value f(5)
+ } else {
+ const int seconds_flag = aom_rb_read_bit(rb); // seconds_flag f(1)
+ if (seconds_flag) {
+ aom_rb_read_literal(rb, 6); // seconds_value f(6)
+ const int minutes_flag = aom_rb_read_bit(rb); // minutes_flag f(1)
+ if (minutes_flag) {
+ aom_rb_read_literal(rb, 6); // minutes_value f(6)
+ const int hours_flag = aom_rb_read_bit(rb); // hours_flag f(1)
+ if (hours_flag) {
+ aom_rb_read_literal(rb, 5); // hours_value f(5)
+ }
+ }
+ }
+ }
+ // time_offset_length f(5)
+ const int time_offset_length = aom_rb_read_literal(rb, 5);
+ if (time_offset_length) {
+ // time_offset_value f(time_offset_length)
+ aom_rb_read_literal(rb, time_offset_length);
+ }
+}
+
+// Returns the last nonzero byte in 'data'. If there is no nonzero byte in
+// 'data', returns 0.
+//
+// Call this function to check the following requirement in the spec:
+// This implies that when any payload data is present for this OBU type, at
+// least one byte of the payload data (including the trailing bit) shall not
+// be equal to 0.
+static uint8_t get_last_nonzero_byte(const uint8_t *data, size_t sz) {
+ // Scan backward and return on the first nonzero byte.
+ size_t i = sz;
+ while (i != 0) {
+ --i;
+ if (data[i] != 0) return data[i];
+ }
+ return 0;
+}
+
+// Checks the metadata for correct syntax but ignores the parsed metadata.
+//
+// On success, returns the number of bytes read from 'data'. On failure, sets
+// pbi->common.error.error_code and returns 0, or calls aom_internal_error()
+// and does not return.
+static size_t read_metadata(AV1Decoder *pbi, const uint8_t *data, size_t sz) {
+ size_t type_length;
+ uint64_t type_value;
+ if (aom_uleb_decode(data, sz, &type_value, &type_length) < 0) {
+ pbi->error.error_code = AOM_CODEC_CORRUPT_FRAME;
+ return 0;
+ }
+ const OBU_METADATA_TYPE metadata_type = (OBU_METADATA_TYPE)type_value;
+ if (metadata_type == 0 || metadata_type >= 6) {
+ // If metadata_type is reserved for future use or a user private value,
+ // ignore the entire OBU and just check trailing bits.
+ if (get_last_nonzero_byte(data + type_length, sz - type_length) == 0) {
+ pbi->error.error_code = AOM_CODEC_CORRUPT_FRAME;
+ return 0;
+ }
+ return sz;
+ }
+ if (metadata_type == OBU_METADATA_TYPE_ITUT_T35) {
+ // read_metadata_itut_t35() checks trailing bits.
+ read_metadata_itut_t35(pbi, data + type_length, sz - type_length);
+ return sz;
+ } else if (metadata_type == OBU_METADATA_TYPE_HDR_CLL) {
+ size_t bytes_read =
+ type_length +
+ read_metadata_hdr_cll(pbi, data + type_length, sz - type_length);
+ if (get_last_nonzero_byte(data + bytes_read, sz - bytes_read) != 0x80) {
+ pbi->error.error_code = AOM_CODEC_CORRUPT_FRAME;
+ return 0;
+ }
+ return sz;
+ } else if (metadata_type == OBU_METADATA_TYPE_HDR_MDCV) {
+ size_t bytes_read =
+ type_length +
+ read_metadata_hdr_mdcv(pbi, data + type_length, sz - type_length);
+ if (get_last_nonzero_byte(data + bytes_read, sz - bytes_read) != 0x80) {
+ pbi->error.error_code = AOM_CODEC_CORRUPT_FRAME;
+ return 0;
+ }
+ return sz;
+ }
+
+ struct aom_read_bit_buffer rb;
+ av1_init_read_bit_buffer(pbi, &rb, data + type_length, data + sz);
+ if (metadata_type == OBU_METADATA_TYPE_SCALABILITY) {
+ read_metadata_scalability(&rb);
+ } else {
+ assert(metadata_type == OBU_METADATA_TYPE_TIMECODE);
+ read_metadata_timecode(&rb);
+ }
+ if (av1_check_trailing_bits(pbi, &rb) != 0) {
+ // pbi->error.error_code is already set.
+ return 0;
+ }
+ assert((rb.bit_offset & 7) == 0);
+ return type_length + (rb.bit_offset >> 3);
+}
+
+// On success, returns 'sz'. On failure, sets pbi->common.error.error_code and
+// returns 0.
+static size_t read_padding(AV1_COMMON *const cm, const uint8_t *data,
+ size_t sz) {
+ // The spec allows a padding OBU to be header-only (i.e., obu_size = 0). So
+ // check trailing bits only if sz > 0.
+ if (sz > 0) {
+ // The payload of a padding OBU is byte aligned. Therefore the first
+ // trailing byte should be 0x80. See https://crbug.com/aomedia/2393.
+ const uint8_t last_nonzero_byte = get_last_nonzero_byte(data, sz);
+ if (last_nonzero_byte != 0x80) {
+ cm->error->error_code = AOM_CODEC_CORRUPT_FRAME;
+ return 0;
+ }
+ }
+ return sz;
+}
+
+// On success, returns a boolean that indicates whether the decoding of the
+// current frame is finished. On failure, sets pbi->error.error_code and
+// returns -1.
+int aom_decode_frame_from_obus(struct AV1Decoder *pbi, const uint8_t *data,
+ const uint8_t *data_end,
+ const uint8_t **p_data_end) {
+ AV1_COMMON *const cm = &pbi->common;
+ int frame_decoding_finished = 0;
+ int is_first_tg_obu_received = 1;
+ // Whenever pbi->seen_frame_header is set to 1, frame_header is set to the
+ // beginning of the frame_header_obu and frame_header_size is set to its
+ // size. This allows us to check if a redundant frame_header_obu is a copy
+ // of the previous frame_header_obu.
+ //
+ // Initialize frame_header to a dummy nonnull pointer, otherwise the Clang
+ // Static Analyzer in clang 7.0.1 will falsely warn that a null pointer is
+ // passed as an argument to a 'nonnull' parameter of memcmp(). The initial
+ // value will not be used.
+ const uint8_t *frame_header = data;
+ uint32_t frame_header_size = 0;
+ ObuHeader obu_header;
+ memset(&obu_header, 0, sizeof(obu_header));
+ pbi->seen_frame_header = 0;
+ pbi->next_start_tile = 0;
+ pbi->num_tile_groups = 0;
+
+ if (data_end < data) {
+ pbi->error.error_code = AOM_CODEC_CORRUPT_FRAME;
+ return -1;
+ }
+
+ // Reset pbi->camera_frame_header_ready to 0 if cm->tiles.large_scale = 0.
+ if (!cm->tiles.large_scale) pbi->camera_frame_header_ready = 0;
+
+ // decode frame as a series of OBUs
+ while (!frame_decoding_finished && pbi->error.error_code == AOM_CODEC_OK) {
+ struct aom_read_bit_buffer rb;
+ size_t payload_size = 0;
+ size_t decoded_payload_size = 0;
+ size_t obu_payload_offset = 0;
+ size_t bytes_read = 0;
+ const size_t bytes_available = data_end - data;
+
+ if (bytes_available == 0 && !pbi->seen_frame_header) {
+ *p_data_end = data;
+ pbi->error.error_code = AOM_CODEC_OK;
+ break;
+ }
+
+ aom_codec_err_t status =
+ aom_read_obu_header_and_size(data, bytes_available, pbi->is_annexb,
+ &obu_header, &payload_size, &bytes_read);
+
+ if (status != AOM_CODEC_OK) {
+ pbi->error.error_code = status;
+ return -1;
+ }
+
+ // Record obu size header information.
+ pbi->obu_size_hdr.data = data + obu_header.size;
+ pbi->obu_size_hdr.size = bytes_read - obu_header.size;
+
+ // Note: aom_read_obu_header_and_size() takes care of checking that this
+ // doesn't cause 'data' to advance past 'data_end'.
+ data += bytes_read;
+
+ if ((size_t)(data_end - data) < payload_size) {
+ pbi->error.error_code = AOM_CODEC_CORRUPT_FRAME;
+ return -1;
+ }
+
+ cm->temporal_layer_id = obu_header.temporal_layer_id;
+ cm->spatial_layer_id = obu_header.spatial_layer_id;
+
+ if (obu_header.type != OBU_TEMPORAL_DELIMITER &&
+ obu_header.type != OBU_SEQUENCE_HEADER) {
+ // don't decode obu if it's not in current operating mode
+ if (!is_obu_in_current_operating_point(pbi, &obu_header)) {
+ data += payload_size;
+ continue;
+ }
+ }
+
+ av1_init_read_bit_buffer(pbi, &rb, data, data + payload_size);
+
+ switch (obu_header.type) {
+ case OBU_TEMPORAL_DELIMITER:
+ decoded_payload_size = read_temporal_delimiter_obu();
+ if (pbi->seen_frame_header) {
+ // A new temporal unit has started, but the frame in the previous
+ // temporal unit is incomplete.
+ pbi->error.error_code = AOM_CODEC_CORRUPT_FRAME;
+ return -1;
+ }
+ break;
+ case OBU_SEQUENCE_HEADER:
+ decoded_payload_size = read_sequence_header_obu(pbi, &rb);
+ if (pbi->error.error_code != AOM_CODEC_OK) return -1;
+ // The sequence header should not change in the middle of a frame.
+ if (pbi->sequence_header_changed && pbi->seen_frame_header) {
+ pbi->error.error_code = AOM_CODEC_CORRUPT_FRAME;
+ return -1;
+ }
+ break;
+ case OBU_FRAME_HEADER:
+ case OBU_REDUNDANT_FRAME_HEADER:
+ case OBU_FRAME:
+ if (obu_header.type == OBU_REDUNDANT_FRAME_HEADER) {
+ if (!pbi->seen_frame_header) {
+ pbi->error.error_code = AOM_CODEC_CORRUPT_FRAME;
+ return -1;
+ }
+ } else {
+ // OBU_FRAME_HEADER or OBU_FRAME.
+ if (pbi->seen_frame_header) {
+ pbi->error.error_code = AOM_CODEC_CORRUPT_FRAME;
+ return -1;
+ }
+ }
+ // Only decode first frame header received
+ if (!pbi->seen_frame_header ||
+ (cm->tiles.large_scale && !pbi->camera_frame_header_ready)) {
+ frame_header_size = read_frame_header_obu(
+ pbi, &rb, data, p_data_end, obu_header.type != OBU_FRAME);
+ frame_header = data;
+ pbi->seen_frame_header = 1;
+ if (!pbi->ext_tile_debug && cm->tiles.large_scale)
+ pbi->camera_frame_header_ready = 1;
+ } else {
+ // Verify that the frame_header_obu is identical to the original
+ // frame_header_obu.
+ if (frame_header_size > payload_size ||
+ memcmp(data, frame_header, frame_header_size) != 0) {
+ pbi->error.error_code = AOM_CODEC_CORRUPT_FRAME;
+ return -1;
+ }
+ assert(rb.bit_offset == 0);
+ rb.bit_offset = 8 * frame_header_size;
+ }
+
+ decoded_payload_size = frame_header_size;
+ pbi->frame_header_size = frame_header_size;
+ cm->cur_frame->temporal_id = obu_header.temporal_layer_id;
+ cm->cur_frame->spatial_id = obu_header.spatial_layer_id;
+
+ if (cm->show_existing_frame) {
+ if (obu_header.type == OBU_FRAME) {
+ pbi->error.error_code = AOM_CODEC_UNSUP_BITSTREAM;
+ return -1;
+ }
+ frame_decoding_finished = 1;
+ pbi->seen_frame_header = 0;
+
+ if (cm->show_frame &&
+ !cm->seq_params->order_hint_info.enable_order_hint) {
+ ++cm->current_frame.frame_number;
+ }
+ break;
+ }
+
+ // In large scale tile coding, decode the common camera frame header
+ // before any tile list OBU.
+ if (!pbi->ext_tile_debug && pbi->camera_frame_header_ready) {
+ frame_decoding_finished = 1;
+ // Skip the rest of the frame data.
+ decoded_payload_size = payload_size;
+ // Update data_end.
+ *p_data_end = data_end;
+ break;
+ }
+
+ if (obu_header.type != OBU_FRAME) break;
+ obu_payload_offset = frame_header_size;
+ // Byte align the reader before reading the tile group.
+ // byte_alignment() has set pbi->error.error_code if it returns -1.
+ if (byte_alignment(cm, &rb)) return -1;
+ AOM_FALLTHROUGH_INTENDED; // fall through to read tile group.
+ case OBU_TILE_GROUP:
+ if (!pbi->seen_frame_header) {
+ pbi->error.error_code = AOM_CODEC_CORRUPT_FRAME;
+ return -1;
+ }
+ if (obu_payload_offset > payload_size) {
+ pbi->error.error_code = AOM_CODEC_CORRUPT_FRAME;
+ return -1;
+ }
+ decoded_payload_size += read_one_tile_group_obu(
+ pbi, &rb, is_first_tg_obu_received, data + obu_payload_offset,
+ data + payload_size, p_data_end, &frame_decoding_finished,
+ obu_header.type == OBU_FRAME);
+ if (pbi->error.error_code != AOM_CODEC_OK) return -1;
+ is_first_tg_obu_received = 0;
+ if (frame_decoding_finished) {
+ pbi->seen_frame_header = 0;
+ pbi->next_start_tile = 0;
+ }
+ pbi->num_tile_groups++;
+ break;
+ case OBU_METADATA:
+ decoded_payload_size = read_metadata(pbi, data, payload_size);
+ if (pbi->error.error_code != AOM_CODEC_OK) return -1;
+ break;
+ case OBU_TILE_LIST:
+ if (CONFIG_NORMAL_TILE_MODE) {
+ pbi->error.error_code = AOM_CODEC_UNSUP_BITSTREAM;
+ return -1;
+ }
+
+ // This OBU type is purely for the large scale tile coding mode.
+ // The common camera frame header has to be already decoded.
+ if (!pbi->camera_frame_header_ready) {
+ pbi->error.error_code = AOM_CODEC_CORRUPT_FRAME;
+ return -1;
+ }
+
+ cm->tiles.large_scale = 1;
+ av1_set_single_tile_decoding_mode(cm);
+ decoded_payload_size =
+ read_and_decode_one_tile_list(pbi, &rb, data, data + payload_size,
+ p_data_end, &frame_decoding_finished);
+ if (pbi->error.error_code != AOM_CODEC_OK) return -1;
+ break;
+ case OBU_PADDING:
+ decoded_payload_size = read_padding(cm, data, payload_size);
+ if (pbi->error.error_code != AOM_CODEC_OK) return -1;
+ break;
+ default:
+ // Skip unrecognized OBUs
+ if (payload_size > 0 &&
+ get_last_nonzero_byte(data, payload_size) == 0) {
+ pbi->error.error_code = AOM_CODEC_CORRUPT_FRAME;
+ return -1;
+ }
+ decoded_payload_size = payload_size;
+ break;
+ }
+
+ // Check that the signalled OBU size matches the actual amount of data read
+ if (decoded_payload_size > payload_size) {
+ pbi->error.error_code = AOM_CODEC_CORRUPT_FRAME;
+ return -1;
+ }
+
+ // If there are extra padding bytes, they should all be zero
+ while (decoded_payload_size < payload_size) {
+ uint8_t padding_byte = data[decoded_payload_size++];
+ if (padding_byte != 0) {
+ pbi->error.error_code = AOM_CODEC_CORRUPT_FRAME;
+ return -1;
+ }
+ }
+
+ data += payload_size;
+ }
+
+ if (pbi->error.error_code != AOM_CODEC_OK) return -1;
+ return frame_decoding_finished;
+}
diff --git a/third_party/aom/av1/decoder/obu.h b/third_party/aom/av1/decoder/obu.h
new file mode 100644
index 0000000000..d8ebe368e6
--- /dev/null
+++ b/third_party/aom/av1/decoder/obu.h
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2017, Alliance for Open Media. All rights reserved
+ *
+ * This source code is subject to the terms of the BSD 2 Clause License and
+ * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
+ * was not distributed with this source code in the LICENSE file, you can
+ * obtain it at www.aomedia.org/license/software. If the Alliance for Open
+ * Media Patent License 1.0 was not distributed with this source code in the
+ * PATENTS file, you can obtain it at www.aomedia.org/license/patent.
+ */
+
+#ifndef AOM_AV1_DECODER_OBU_H_
+#define AOM_AV1_DECODER_OBU_H_
+
+#include "aom/aom_codec.h"
+#include "av1/decoder/decoder.h"
+
+// Try to decode one frame from a buffer.
+// Returns 1 if we decoded a frame,
+// 0 if we didn't decode a frame but that's okay
+// (eg, if there was a frame but we skipped it),
+// or -1 on error
+int aom_decode_frame_from_obus(struct AV1Decoder *pbi, const uint8_t *data,
+ const uint8_t *data_end,
+ const uint8_t **p_data_end);
+
+aom_codec_err_t aom_get_num_layers_from_operating_point_idc(
+ int operating_point_idc, unsigned int *number_spatial_layers,
+ unsigned int *number_temporal_layers);
+
+#endif // AOM_AV1_DECODER_OBU_H_