2 * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
12 #include <stdlib.h> // qsort()
14 #include "./vp9_rtcd.h"
15 #include "./vpx_scale_rtcd.h"
17 #include "vpx_mem/vpx_mem.h"
18 #include "vpx_ports/mem_ops.h"
19 #include "vpx_scale/vpx_scale.h"
21 #include "vp9/common/vp9_alloccommon.h"
22 #include "vp9/common/vp9_common.h"
23 #include "vp9/common/vp9_entropy.h"
24 #include "vp9/common/vp9_entropymode.h"
25 #include "vp9/common/vp9_idct.h"
26 #include "vp9/common/vp9_pred_common.h"
27 #include "vp9/common/vp9_quant_common.h"
28 #include "vp9/common/vp9_reconintra.h"
29 #include "vp9/common/vp9_reconinter.h"
30 #include "vp9/common/vp9_seg_common.h"
31 #include "vp9/common/vp9_thread.h"
32 #include "vp9/common/vp9_tile_common.h"
34 #include "vp9/decoder/vp9_decodeframe.h"
35 #include "vp9/decoder/vp9_detokenize.h"
36 #include "vp9/decoder/vp9_decodemv.h"
37 #include "vp9/decoder/vp9_decoder.h"
38 #include "vp9/decoder/vp9_dsubexp.h"
39 #include "vp9/decoder/vp9_dthread.h"
40 #include "vp9/decoder/vp9_read_bit_buffer.h"
41 #include "vp9/decoder/vp9_reader.h"
43 #define MAX_VP9_HEADER_SIZE 80
45 static int is_compound_reference_allowed(const VP9_COMMON *cm) {
47 for (i = 1; i < REFS_PER_FRAME; ++i)
48 if (cm->ref_frame_sign_bias[i + 1] != cm->ref_frame_sign_bias[1])
54 static void setup_compound_reference_mode(VP9_COMMON *cm) {
55 if (cm->ref_frame_sign_bias[LAST_FRAME] ==
56 cm->ref_frame_sign_bias[GOLDEN_FRAME]) {
57 cm->comp_fixed_ref = ALTREF_FRAME;
58 cm->comp_var_ref[0] = LAST_FRAME;
59 cm->comp_var_ref[1] = GOLDEN_FRAME;
60 } else if (cm->ref_frame_sign_bias[LAST_FRAME] ==
61 cm->ref_frame_sign_bias[ALTREF_FRAME]) {
62 cm->comp_fixed_ref = GOLDEN_FRAME;
63 cm->comp_var_ref[0] = LAST_FRAME;
64 cm->comp_var_ref[1] = ALTREF_FRAME;
66 cm->comp_fixed_ref = LAST_FRAME;
67 cm->comp_var_ref[0] = GOLDEN_FRAME;
68 cm->comp_var_ref[1] = ALTREF_FRAME;
72 static int read_is_valid(const uint8_t *start, size_t len, const uint8_t *end) {
73 return len != 0 && len <= (size_t)(end - start);
76 static int decode_unsigned_max(struct vp9_read_bit_buffer *rb, int max) {
77 const int data = vp9_rb_read_literal(rb, get_unsigned_bits(max));
78 return data > max ? max : data;
81 static TX_MODE read_tx_mode(vp9_reader *r) {
82 TX_MODE tx_mode = vp9_read_literal(r, 2);
83 if (tx_mode == ALLOW_32X32)
84 tx_mode += vp9_read_bit(r);
88 static void read_tx_mode_probs(struct tx_probs *tx_probs, vp9_reader *r) {
91 for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
92 for (j = 0; j < TX_SIZES - 3; ++j)
93 vp9_diff_update_prob(r, &tx_probs->p8x8[i][j]);
95 for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
96 for (j = 0; j < TX_SIZES - 2; ++j)
97 vp9_diff_update_prob(r, &tx_probs->p16x16[i][j]);
99 for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
100 for (j = 0; j < TX_SIZES - 1; ++j)
101 vp9_diff_update_prob(r, &tx_probs->p32x32[i][j]);
104 static void read_switchable_interp_probs(FRAME_CONTEXT *fc, vp9_reader *r) {
106 for (j = 0; j < SWITCHABLE_FILTER_CONTEXTS; ++j)
107 for (i = 0; i < SWITCHABLE_FILTERS - 1; ++i)
108 vp9_diff_update_prob(r, &fc->switchable_interp_prob[j][i]);
111 static void read_inter_mode_probs(FRAME_CONTEXT *fc, vp9_reader *r) {
113 for (i = 0; i < INTER_MODE_CONTEXTS; ++i)
114 for (j = 0; j < INTER_MODES - 1; ++j)
115 vp9_diff_update_prob(r, &fc->inter_mode_probs[i][j]);
118 static REFERENCE_MODE read_frame_reference_mode(const VP9_COMMON *cm,
120 if (is_compound_reference_allowed(cm)) {
121 return vp9_read_bit(r) ? (vp9_read_bit(r) ? REFERENCE_MODE_SELECT
122 : COMPOUND_REFERENCE)
125 return SINGLE_REFERENCE;
129 static void read_frame_reference_mode_probs(VP9_COMMON *cm, vp9_reader *r) {
130 FRAME_CONTEXT *const fc = cm->fc;
133 if (cm->reference_mode == REFERENCE_MODE_SELECT)
134 for (i = 0; i < COMP_INTER_CONTEXTS; ++i)
135 vp9_diff_update_prob(r, &fc->comp_inter_prob[i]);
137 if (cm->reference_mode != COMPOUND_REFERENCE)
138 for (i = 0; i < REF_CONTEXTS; ++i) {
139 vp9_diff_update_prob(r, &fc->single_ref_prob[i][0]);
140 vp9_diff_update_prob(r, &fc->single_ref_prob[i][1]);
143 if (cm->reference_mode != SINGLE_REFERENCE)
144 for (i = 0; i < REF_CONTEXTS; ++i)
145 vp9_diff_update_prob(r, &fc->comp_ref_prob[i]);
148 static void update_mv_probs(vp9_prob *p, int n, vp9_reader *r) {
150 for (i = 0; i < n; ++i)
151 if (vp9_read(r, MV_UPDATE_PROB))
152 p[i] = (vp9_read_literal(r, 7) << 1) | 1;
155 static void read_mv_probs(nmv_context *ctx, int allow_hp, vp9_reader *r) {
158 update_mv_probs(ctx->joints, MV_JOINTS - 1, r);
160 for (i = 0; i < 2; ++i) {
161 nmv_component *const comp_ctx = &ctx->comps[i];
162 update_mv_probs(&comp_ctx->sign, 1, r);
163 update_mv_probs(comp_ctx->classes, MV_CLASSES - 1, r);
164 update_mv_probs(comp_ctx->class0, CLASS0_SIZE - 1, r);
165 update_mv_probs(comp_ctx->bits, MV_OFFSET_BITS, r);
168 for (i = 0; i < 2; ++i) {
169 nmv_component *const comp_ctx = &ctx->comps[i];
170 for (j = 0; j < CLASS0_SIZE; ++j)
171 update_mv_probs(comp_ctx->class0_fp[j], MV_FP_SIZE - 1, r);
172 update_mv_probs(comp_ctx->fp, 3, r);
176 for (i = 0; i < 2; ++i) {
177 nmv_component *const comp_ctx = &ctx->comps[i];
178 update_mv_probs(&comp_ctx->class0_hp, 1, r);
179 update_mv_probs(&comp_ctx->hp, 1, r);
184 static void setup_plane_dequants(VP9_COMMON *cm, MACROBLOCKD *xd, int q_index) {
186 xd->plane[0].dequant = cm->y_dequant[q_index];
188 for (i = 1; i < MAX_MB_PLANE; i++)
189 xd->plane[i].dequant = cm->uv_dequant[q_index];
192 static void inverse_transform_block(MACROBLOCKD* xd, int plane, int block,
193 TX_SIZE tx_size, uint8_t *dst, int stride,
195 struct macroblockd_plane *const pd = &xd->plane[plane];
197 TX_TYPE tx_type = DCT_DCT;
198 tran_low_t *const dqcoeff = BLOCK_OFFSET(pd->dqcoeff, block);
199 #if CONFIG_VP9_HIGHBITDEPTH
200 if (xd->cur_buf->flags & YV12_FLAG_HIGHBITDEPTH) {
203 vp9_highbd_iwht4x4_add(dqcoeff, dst, stride, eob, xd->bd);
205 const PLANE_TYPE plane_type = pd->plane_type;
208 tx_type = get_tx_type_4x4(plane_type, xd, block);
209 vp9_highbd_iht4x4_add(tx_type, dqcoeff, dst, stride, eob, xd->bd);
212 tx_type = get_tx_type(plane_type, xd);
213 vp9_highbd_iht8x8_add(tx_type, dqcoeff, dst, stride, eob, xd->bd);
216 tx_type = get_tx_type(plane_type, xd);
217 vp9_highbd_iht16x16_add(tx_type, dqcoeff, dst, stride, eob, xd->bd);
221 vp9_highbd_idct32x32_add(dqcoeff, dst, stride, eob, xd->bd);
224 assert(0 && "Invalid transform size");
230 vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
232 const PLANE_TYPE plane_type = pd->plane_type;
235 tx_type = get_tx_type_4x4(plane_type, xd, block);
236 vp9_iht4x4_add(tx_type, dqcoeff, dst, stride, eob);
239 tx_type = get_tx_type(plane_type, xd);
240 vp9_iht8x8_add(tx_type, dqcoeff, dst, stride, eob);
243 tx_type = get_tx_type(plane_type, xd);
244 vp9_iht16x16_add(tx_type, dqcoeff, dst, stride, eob);
248 vp9_idct32x32_add(dqcoeff, dst, stride, eob);
251 assert(0 && "Invalid transform size");
259 vp9_iwht4x4_add(dqcoeff, dst, stride, eob);
261 const PLANE_TYPE plane_type = pd->plane_type;
264 tx_type = get_tx_type_4x4(plane_type, xd, block);
265 vp9_iht4x4_add(tx_type, dqcoeff, dst, stride, eob);
268 tx_type = get_tx_type(plane_type, xd);
269 vp9_iht8x8_add(tx_type, dqcoeff, dst, stride, eob);
272 tx_type = get_tx_type(plane_type, xd);
273 vp9_iht16x16_add(tx_type, dqcoeff, dst, stride, eob);
277 vp9_idct32x32_add(dqcoeff, dst, stride, eob);
280 assert(0 && "Invalid transform size");
284 #endif // CONFIG_VP9_HIGHBITDEPTH
287 vpx_memset(dqcoeff, 0, 2 * sizeof(dqcoeff[0]));
289 if (tx_type == DCT_DCT && tx_size <= TX_16X16 && eob <= 10)
290 vpx_memset(dqcoeff, 0, 4 * (4 << tx_size) * sizeof(dqcoeff[0]));
291 else if (tx_size == TX_32X32 && eob <= 34)
292 vpx_memset(dqcoeff, 0, 256 * sizeof(dqcoeff[0]));
294 vpx_memset(dqcoeff, 0, (16 << (tx_size << 1)) * sizeof(dqcoeff[0]));
305 static void predict_and_reconstruct_intra_block(int plane, int block,
306 BLOCK_SIZE plane_bsize,
307 TX_SIZE tx_size, void *arg) {
308 struct intra_args *const args = (struct intra_args *)arg;
309 VP9_COMMON *const cm = args->cm;
310 MACROBLOCKD *const xd = args->xd;
311 struct macroblockd_plane *const pd = &xd->plane[plane];
312 MODE_INFO *const mi = xd->mi[0].src_mi;
313 const PREDICTION_MODE mode = (plane == 0) ? get_y_mode(mi, block)
317 txfrm_block_to_raster_xy(plane_bsize, tx_size, block, &x, &y);
318 dst = &pd->dst.buf[4 * y * pd->dst.stride + 4 * x];
320 vp9_predict_intra_block(xd, block >> (tx_size << 1),
321 b_width_log2_lookup[plane_bsize], tx_size, mode,
322 dst, pd->dst.stride, dst, pd->dst.stride,
325 if (!mi->mbmi.skip) {
326 const int eob = vp9_decode_block_tokens(cm, xd, plane, block,
327 plane_bsize, x, y, tx_size,
329 inverse_transform_block(xd, plane, block, tx_size, dst, pd->dst.stride,
341 static void reconstruct_inter_block(int plane, int block,
342 BLOCK_SIZE plane_bsize,
343 TX_SIZE tx_size, void *arg) {
344 struct inter_args *args = (struct inter_args *)arg;
345 VP9_COMMON *const cm = args->cm;
346 MACROBLOCKD *const xd = args->xd;
347 struct macroblockd_plane *const pd = &xd->plane[plane];
349 txfrm_block_to_raster_xy(plane_bsize, tx_size, block, &x, &y);
350 eob = vp9_decode_block_tokens(cm, xd, plane, block, plane_bsize, x, y,
352 inverse_transform_block(xd, plane, block, tx_size,
353 &pd->dst.buf[4 * y * pd->dst.stride + 4 * x],
354 pd->dst.stride, eob);
355 *args->eobtotal += eob;
358 static MB_MODE_INFO *set_offsets(VP9_COMMON *const cm, MACROBLOCKD *const xd,
359 const TileInfo *const tile,
360 BLOCK_SIZE bsize, int mi_row, int mi_col) {
361 const int bw = num_8x8_blocks_wide_lookup[bsize];
362 const int bh = num_8x8_blocks_high_lookup[bsize];
363 const int x_mis = MIN(bw, cm->mi_cols - mi_col);
364 const int y_mis = MIN(bh, cm->mi_rows - mi_row);
365 const int offset = mi_row * cm->mi_stride + mi_col;
368 xd->mi = cm->mi + offset;
369 xd->mi[0].src_mi = &xd->mi[0]; // Point to self.
370 xd->mi[0].mbmi.sb_type = bsize;
372 for (y = 0; y < y_mis; ++y)
373 for (x = !y; x < x_mis; ++x) {
374 xd->mi[y * cm->mi_stride + x].src_mi = &xd->mi[0];
377 set_skip_context(xd, mi_row, mi_col);
379 // Distance of Mb to the various image edges. These are specified to 8th pel
380 // as they are always compared to values that are in 1/8th pel units
381 set_mi_row_col(xd, tile, mi_row, bh, mi_col, bw, cm->mi_rows, cm->mi_cols);
383 vp9_setup_dst_planes(xd->plane, get_frame_new_buffer(cm), mi_row, mi_col);
384 return &xd->mi[0].mbmi;
387 static void decode_block(VP9_COMMON *const cm, MACROBLOCKD *const xd,
388 const TileInfo *const tile,
389 int mi_row, int mi_col,
390 vp9_reader *r, BLOCK_SIZE bsize) {
391 const int less8x8 = bsize < BLOCK_8X8;
392 MB_MODE_INFO *mbmi = set_offsets(cm, xd, tile, bsize, mi_row, mi_col);
393 vp9_read_mode_info(cm, xd, tile, mi_row, mi_col, r);
399 reset_skip_context(xd, bsize);
402 setup_plane_dequants(cm, xd, vp9_get_qindex(&cm->seg, mbmi->segment_id,
406 if (!is_inter_block(mbmi)) {
407 struct intra_args arg = { cm, xd, r };
408 vp9_foreach_transformed_block(xd, bsize,
409 predict_and_reconstruct_intra_block, &arg);
412 vp9_dec_build_inter_predictors_sb(xd, mi_row, mi_col, bsize);
417 struct inter_args arg = { cm, xd, r, &eobtotal };
418 vp9_foreach_transformed_block(xd, bsize, reconstruct_inter_block, &arg);
419 if (!less8x8 && eobtotal == 0)
420 mbmi->skip = 1; // skip loopfilter
424 xd->corrupted |= vp9_reader_has_error(r);
427 static PARTITION_TYPE read_partition(VP9_COMMON *cm, MACROBLOCKD *xd, int hbs,
428 int mi_row, int mi_col, BLOCK_SIZE bsize,
430 const int ctx = partition_plane_context(xd, mi_row, mi_col, bsize);
431 const vp9_prob *const probs = get_partition_probs(cm, ctx);
432 const int has_rows = (mi_row + hbs) < cm->mi_rows;
433 const int has_cols = (mi_col + hbs) < cm->mi_cols;
436 if (has_rows && has_cols)
437 p = (PARTITION_TYPE)vp9_read_tree(r, vp9_partition_tree, probs);
438 else if (!has_rows && has_cols)
439 p = vp9_read(r, probs[1]) ? PARTITION_SPLIT : PARTITION_HORZ;
440 else if (has_rows && !has_cols)
441 p = vp9_read(r, probs[2]) ? PARTITION_SPLIT : PARTITION_VERT;
445 if (!cm->frame_parallel_decoding_mode)
446 ++cm->counts.partition[ctx][p];
451 static void decode_partition(VP9_COMMON *const cm, MACROBLOCKD *const xd,
452 const TileInfo *const tile,
453 int mi_row, int mi_col,
454 vp9_reader* r, BLOCK_SIZE bsize) {
455 const int hbs = num_8x8_blocks_wide_lookup[bsize] / 2;
456 PARTITION_TYPE partition;
457 BLOCK_SIZE subsize, uv_subsize;
459 if (mi_row >= cm->mi_rows || mi_col >= cm->mi_cols)
462 partition = read_partition(cm, xd, hbs, mi_row, mi_col, bsize, r);
463 subsize = get_subsize(bsize, partition);
464 uv_subsize = ss_size_lookup[subsize][cm->subsampling_x][cm->subsampling_y];
465 if (subsize >= BLOCK_8X8 && uv_subsize == BLOCK_INVALID)
466 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
467 "Invalid block size.");
468 if (subsize < BLOCK_8X8) {
469 decode_block(cm, xd, tile, mi_row, mi_col, r, subsize);
473 decode_block(cm, xd, tile, mi_row, mi_col, r, subsize);
476 decode_block(cm, xd, tile, mi_row, mi_col, r, subsize);
477 if (mi_row + hbs < cm->mi_rows)
478 decode_block(cm, xd, tile, mi_row + hbs, mi_col, r, subsize);
481 decode_block(cm, xd, tile, mi_row, mi_col, r, subsize);
482 if (mi_col + hbs < cm->mi_cols)
483 decode_block(cm, xd, tile, mi_row, mi_col + hbs, r, subsize);
485 case PARTITION_SPLIT:
486 decode_partition(cm, xd, tile, mi_row, mi_col, r, subsize);
487 decode_partition(cm, xd, tile, mi_row, mi_col + hbs, r, subsize);
488 decode_partition(cm, xd, tile, mi_row + hbs, mi_col, r, subsize);
489 decode_partition(cm, xd, tile, mi_row + hbs, mi_col + hbs, r, subsize);
492 assert(0 && "Invalid partition type");
496 // update partition context
497 if (bsize >= BLOCK_8X8 &&
498 (bsize == BLOCK_8X8 || partition != PARTITION_SPLIT))
499 update_partition_context(xd, mi_row, mi_col, subsize, bsize);
502 static void setup_token_decoder(const uint8_t *data,
503 const uint8_t *data_end,
505 struct vpx_internal_error_info *error_info,
507 vpx_decrypt_cb decrypt_cb,
508 void *decrypt_state) {
509 // Validate the calculated partition length. If the buffer
510 // described by the partition can't be fully read, then restrict
511 // it to the portion that can be (for EC mode) or throw an error.
512 if (!read_is_valid(data, read_size, data_end))
513 vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
514 "Truncated packet or corrupt tile length");
516 if (vp9_reader_init(r, data, read_size, decrypt_cb, decrypt_state))
517 vpx_internal_error(error_info, VPX_CODEC_MEM_ERROR,
518 "Failed to allocate bool decoder %d", 1);
521 static void read_coef_probs_common(vp9_coeff_probs_model *coef_probs,
526 for (i = 0; i < PLANE_TYPES; ++i)
527 for (j = 0; j < REF_TYPES; ++j)
528 for (k = 0; k < COEF_BANDS; ++k)
529 for (l = 0; l < BAND_COEFF_CONTEXTS(k); ++l)
530 for (m = 0; m < UNCONSTRAINED_NODES; ++m)
531 vp9_diff_update_prob(r, &coef_probs[i][j][k][l][m]);
534 static void read_coef_probs(FRAME_CONTEXT *fc, TX_MODE tx_mode,
536 const TX_SIZE max_tx_size = tx_mode_to_biggest_tx_size[tx_mode];
538 for (tx_size = TX_4X4; tx_size <= max_tx_size; ++tx_size)
539 read_coef_probs_common(fc->coef_probs[tx_size], r);
542 static void setup_segmentation(struct segmentation *seg,
543 struct vp9_read_bit_buffer *rb) {
547 seg->update_data = 0;
549 seg->enabled = vp9_rb_read_bit(rb);
553 // Segmentation map update
554 seg->update_map = vp9_rb_read_bit(rb);
555 if (seg->update_map) {
556 for (i = 0; i < SEG_TREE_PROBS; i++)
557 seg->tree_probs[i] = vp9_rb_read_bit(rb) ? vp9_rb_read_literal(rb, 8)
560 seg->temporal_update = vp9_rb_read_bit(rb);
561 if (seg->temporal_update) {
562 for (i = 0; i < PREDICTION_PROBS; i++)
563 seg->pred_probs[i] = vp9_rb_read_bit(rb) ? vp9_rb_read_literal(rb, 8)
566 for (i = 0; i < PREDICTION_PROBS; i++)
567 seg->pred_probs[i] = MAX_PROB;
571 // Segmentation data update
572 seg->update_data = vp9_rb_read_bit(rb);
573 if (seg->update_data) {
574 seg->abs_delta = vp9_rb_read_bit(rb);
576 vp9_clearall_segfeatures(seg);
578 for (i = 0; i < MAX_SEGMENTS; i++) {
579 for (j = 0; j < SEG_LVL_MAX; j++) {
581 const int feature_enabled = vp9_rb_read_bit(rb);
582 if (feature_enabled) {
583 vp9_enable_segfeature(seg, i, j);
584 data = decode_unsigned_max(rb, vp9_seg_feature_data_max(j));
585 if (vp9_is_segfeature_signed(j))
586 data = vp9_rb_read_bit(rb) ? -data : data;
588 vp9_set_segdata(seg, i, j, data);
594 static void setup_loopfilter(struct loopfilter *lf,
595 struct vp9_read_bit_buffer *rb) {
596 lf->filter_level = vp9_rb_read_literal(rb, 6);
597 lf->sharpness_level = vp9_rb_read_literal(rb, 3);
599 // Read in loop filter deltas applied at the MB level based on mode or ref
601 lf->mode_ref_delta_update = 0;
603 lf->mode_ref_delta_enabled = vp9_rb_read_bit(rb);
604 if (lf->mode_ref_delta_enabled) {
605 lf->mode_ref_delta_update = vp9_rb_read_bit(rb);
606 if (lf->mode_ref_delta_update) {
609 for (i = 0; i < MAX_REF_LF_DELTAS; i++)
610 if (vp9_rb_read_bit(rb))
611 lf->ref_deltas[i] = vp9_rb_read_signed_literal(rb, 6);
613 for (i = 0; i < MAX_MODE_LF_DELTAS; i++)
614 if (vp9_rb_read_bit(rb))
615 lf->mode_deltas[i] = vp9_rb_read_signed_literal(rb, 6);
620 static int read_delta_q(struct vp9_read_bit_buffer *rb, int *delta_q) {
621 const int old = *delta_q;
622 *delta_q = vp9_rb_read_bit(rb) ? vp9_rb_read_signed_literal(rb, 4) : 0;
623 return old != *delta_q;
626 static void setup_quantization(VP9_COMMON *const cm, MACROBLOCKD *const xd,
627 struct vp9_read_bit_buffer *rb) {
630 cm->base_qindex = vp9_rb_read_literal(rb, QINDEX_BITS);
631 update |= read_delta_q(rb, &cm->y_dc_delta_q);
632 update |= read_delta_q(rb, &cm->uv_dc_delta_q);
633 update |= read_delta_q(rb, &cm->uv_ac_delta_q);
634 if (update || cm->bit_depth != cm->dequant_bit_depth) {
635 vp9_init_dequantizer(cm);
636 cm->dequant_bit_depth = cm->bit_depth;
639 xd->lossless = cm->base_qindex == 0 &&
640 cm->y_dc_delta_q == 0 &&
641 cm->uv_dc_delta_q == 0 &&
642 cm->uv_ac_delta_q == 0;
643 #if CONFIG_VP9_HIGHBITDEPTH
644 xd->bd = (int)cm->bit_depth;
648 static INTERP_FILTER read_interp_filter(struct vp9_read_bit_buffer *rb) {
649 const INTERP_FILTER literal_to_filter[] = { EIGHTTAP_SMOOTH,
653 return vp9_rb_read_bit(rb) ? SWITCHABLE
654 : literal_to_filter[vp9_rb_read_literal(rb, 2)];
657 void vp9_read_frame_size(struct vp9_read_bit_buffer *rb,
658 int *width, int *height) {
659 *width = vp9_rb_read_literal(rb, 16) + 1;
660 *height = vp9_rb_read_literal(rb, 16) + 1;
663 static void setup_display_size(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
664 cm->display_width = cm->width;
665 cm->display_height = cm->height;
666 if (vp9_rb_read_bit(rb))
667 vp9_read_frame_size(rb, &cm->display_width, &cm->display_height);
670 static void resize_mv_buffer(VP9_COMMON *cm) {
671 vpx_free(cm->cur_frame->mvs);
672 cm->cur_frame->mi_rows = cm->mi_rows;
673 cm->cur_frame->mi_cols = cm->mi_cols;
674 cm->cur_frame->mvs = (MV_REF *)vpx_calloc(cm->mi_rows * cm->mi_cols,
675 sizeof(*cm->cur_frame->mvs));
678 static void resize_context_buffers(VP9_COMMON *cm, int width, int height) {
679 #if CONFIG_SIZE_LIMIT
680 if (width > DECODE_WIDTH_LIMIT || height > DECODE_HEIGHT_LIMIT)
681 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
682 "Width and height beyond allowed size.");
684 if (cm->width != width || cm->height != height) {
685 const int new_mi_rows =
686 ALIGN_POWER_OF_TWO(height, MI_SIZE_LOG2) >> MI_SIZE_LOG2;
687 const int new_mi_cols =
688 ALIGN_POWER_OF_TWO(width, MI_SIZE_LOG2) >> MI_SIZE_LOG2;
690 // Allocations in vp9_alloc_context_buffers() depend on individual
691 // dimensions as well as the overall size.
692 if (new_mi_cols > cm->mi_cols || new_mi_rows > cm->mi_rows) {
693 if (vp9_alloc_context_buffers(cm, width, height))
694 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
695 "Failed to allocate context buffers");
697 vp9_set_mb_mi(cm, width, height);
699 vp9_init_context_buffers(cm);
703 if (cm->cur_frame->mvs == NULL || cm->mi_rows > cm->cur_frame->mi_rows ||
704 cm->mi_cols > cm->cur_frame->mi_cols) {
705 resize_mv_buffer(cm);
709 static void setup_frame_size(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
711 vp9_read_frame_size(rb, &width, &height);
712 resize_context_buffers(cm, width, height);
713 setup_display_size(cm, rb);
715 if (vp9_realloc_frame_buffer(
716 get_frame_new_buffer(cm), cm->width, cm->height,
717 cm->subsampling_x, cm->subsampling_y,
718 #if CONFIG_VP9_HIGHBITDEPTH
719 cm->use_highbitdepth,
721 VP9_DEC_BORDER_IN_PIXELS,
723 &cm->frame_bufs[cm->new_fb_idx].raw_frame_buffer, cm->get_fb_cb,
725 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
726 "Failed to allocate frame buffer");
728 cm->frame_bufs[cm->new_fb_idx].buf.subsampling_x = cm->subsampling_x;
729 cm->frame_bufs[cm->new_fb_idx].buf.subsampling_y = cm->subsampling_y;
730 cm->frame_bufs[cm->new_fb_idx].buf.bit_depth = (unsigned int)cm->bit_depth;
733 static INLINE int valid_ref_frame_img_fmt(vpx_bit_depth_t ref_bit_depth,
734 int ref_xss, int ref_yss,
735 vpx_bit_depth_t this_bit_depth,
736 int this_xss, int this_yss) {
737 return ref_bit_depth == this_bit_depth && ref_xss == this_xss &&
741 static void setup_frame_size_with_refs(VP9_COMMON *cm,
742 struct vp9_read_bit_buffer *rb) {
745 int has_valid_ref_frame = 0;
746 for (i = 0; i < REFS_PER_FRAME; ++i) {
747 if (vp9_rb_read_bit(rb)) {
748 YV12_BUFFER_CONFIG *const buf = cm->frame_refs[i].buf;
749 width = buf->y_crop_width;
750 height = buf->y_crop_height;
757 vp9_read_frame_size(rb, &width, &height);
759 if (width <= 0 || height <= 0)
760 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
761 "Invalid frame size");
763 // Check to make sure at least one of frames that this frame references
764 // has valid dimensions.
765 for (i = 0; i < REFS_PER_FRAME; ++i) {
766 RefBuffer *const ref_frame = &cm->frame_refs[i];
767 has_valid_ref_frame |= valid_ref_frame_size(ref_frame->buf->y_crop_width,
768 ref_frame->buf->y_crop_height,
771 if (!has_valid_ref_frame)
772 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
773 "Referenced frame has invalid size");
774 for (i = 0; i < REFS_PER_FRAME; ++i) {
775 RefBuffer *const ref_frame = &cm->frame_refs[i];
776 if (!valid_ref_frame_img_fmt(
777 ref_frame->buf->bit_depth,
778 ref_frame->buf->subsampling_x,
779 ref_frame->buf->subsampling_y,
783 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
784 "Referenced frame has incompatible color space");
787 resize_context_buffers(cm, width, height);
788 setup_display_size(cm, rb);
790 if (vp9_realloc_frame_buffer(
791 get_frame_new_buffer(cm), cm->width, cm->height,
792 cm->subsampling_x, cm->subsampling_y,
793 #if CONFIG_VP9_HIGHBITDEPTH
794 cm->use_highbitdepth,
796 VP9_DEC_BORDER_IN_PIXELS,
798 &cm->frame_bufs[cm->new_fb_idx].raw_frame_buffer, cm->get_fb_cb,
800 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
801 "Failed to allocate frame buffer");
803 cm->frame_bufs[cm->new_fb_idx].buf.subsampling_x = cm->subsampling_x;
804 cm->frame_bufs[cm->new_fb_idx].buf.subsampling_y = cm->subsampling_y;
805 cm->frame_bufs[cm->new_fb_idx].buf.bit_depth = (unsigned int)cm->bit_depth;
808 static void setup_tile_info(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
809 int min_log2_tile_cols, max_log2_tile_cols, max_ones;
810 vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
813 max_ones = max_log2_tile_cols - min_log2_tile_cols;
814 cm->log2_tile_cols = min_log2_tile_cols;
815 while (max_ones-- && vp9_rb_read_bit(rb))
816 cm->log2_tile_cols++;
818 if (cm->log2_tile_cols > 6)
819 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
820 "Invalid number of tile columns");
823 cm->log2_tile_rows = vp9_rb_read_bit(rb);
824 if (cm->log2_tile_rows)
825 cm->log2_tile_rows += vp9_rb_read_bit(rb);
828 typedef struct TileBuffer {
831 int col; // only used with multi-threaded decoding
834 // Reads the next tile returning its size and adjusting '*data' accordingly
835 // based on 'is_last'.
836 static void get_tile_buffer(const uint8_t *const data_end,
838 struct vpx_internal_error_info *error_info,
839 const uint8_t **data,
840 vpx_decrypt_cb decrypt_cb, void *decrypt_state,
845 if (!read_is_valid(*data, 4, data_end))
846 vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
847 "Truncated packet or corrupt tile length");
851 decrypt_cb(decrypt_state, *data, be_data, 4);
852 size = mem_get_be32(be_data);
854 size = mem_get_be32(*data);
858 if (size > (size_t)(data_end - *data))
859 vpx_internal_error(error_info, VPX_CODEC_CORRUPT_FRAME,
860 "Truncated packet or corrupt tile size");
862 size = data_end - *data;
871 static void get_tile_buffers(VP9Decoder *pbi,
872 const uint8_t *data, const uint8_t *data_end,
873 int tile_cols, int tile_rows,
874 TileBuffer (*tile_buffers)[1 << 6]) {
877 for (r = 0; r < tile_rows; ++r) {
878 for (c = 0; c < tile_cols; ++c) {
879 const int is_last = (r == tile_rows - 1) && (c == tile_cols - 1);
880 TileBuffer *const buf = &tile_buffers[r][c];
882 get_tile_buffer(data_end, is_last, &pbi->common.error, &data,
883 pbi->decrypt_cb, pbi->decrypt_state, buf);
888 static const uint8_t *decode_tiles(VP9Decoder *pbi,
890 const uint8_t *data_end) {
891 VP9_COMMON *const cm = &pbi->common;
892 const VP9WorkerInterface *const winterface = vp9_get_worker_interface();
893 const int aligned_cols = mi_cols_aligned_to_sb(cm->mi_cols);
894 const int tile_cols = 1 << cm->log2_tile_cols;
895 const int tile_rows = 1 << cm->log2_tile_rows;
896 TileBuffer tile_buffers[4][1 << 6];
897 int tile_row, tile_col;
899 TileData *tile_data = NULL;
901 if (cm->lf.filter_level && pbi->lf_worker.data1 == NULL) {
902 CHECK_MEM_ERROR(cm, pbi->lf_worker.data1,
903 vpx_memalign(32, sizeof(LFWorkerData)));
904 pbi->lf_worker.hook = (VP9WorkerHook)vp9_loop_filter_worker;
905 if (pbi->max_threads > 1 && !winterface->reset(&pbi->lf_worker)) {
906 vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
907 "Loop filter thread creation failed");
911 if (cm->lf.filter_level) {
912 LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
913 // Be sure to sync as we might be resuming after a failed frame decode.
914 winterface->sync(&pbi->lf_worker);
915 vp9_loop_filter_data_reset(lf_data, get_frame_new_buffer(cm), cm,
917 vp9_loop_filter_frame_init(cm, cm->lf.filter_level);
920 assert(tile_rows <= 4);
921 assert(tile_cols <= (1 << 6));
923 // Note: this memset assumes above_context[0], [1] and [2]
924 // are allocated as part of the same buffer.
925 vpx_memset(cm->above_context, 0,
926 sizeof(*cm->above_context) * MAX_MB_PLANE * 2 * aligned_cols);
928 vpx_memset(cm->above_seg_context, 0,
929 sizeof(*cm->above_seg_context) * aligned_cols);
931 get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows, tile_buffers);
933 if (pbi->tile_data == NULL ||
934 (tile_cols * tile_rows) != pbi->total_tiles) {
935 vpx_free(pbi->tile_data);
939 vpx_memalign(32, tile_cols * tile_rows * (sizeof(*pbi->tile_data))));
940 pbi->total_tiles = tile_rows * tile_cols;
943 // Load all tile information into tile_data.
944 for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
945 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
947 const TileBuffer *const buf = &tile_buffers[tile_row][tile_col];
948 tile_data = pbi->tile_data + tile_cols * tile_row + tile_col;
950 tile_data->xd = pbi->mb;
951 tile_data->xd.corrupted = 0;
952 vp9_tile_init(&tile, tile_data->cm, tile_row, tile_col);
953 setup_token_decoder(buf->data, data_end, buf->size, &cm->error,
954 &tile_data->bit_reader, pbi->decrypt_cb,
956 init_macroblockd(cm, &tile_data->xd);
960 for (tile_row = 0; tile_row < tile_rows; ++tile_row) {
962 vp9_tile_set_row(&tile, cm, tile_row);
963 for (mi_row = tile.mi_row_start; mi_row < tile.mi_row_end;
964 mi_row += MI_BLOCK_SIZE) {
965 for (tile_col = 0; tile_col < tile_cols; ++tile_col) {
966 const int col = pbi->inv_tile_order ?
967 tile_cols - tile_col - 1 : tile_col;
968 tile_data = pbi->tile_data + tile_cols * tile_row + col;
969 vp9_tile_set_col(&tile, tile_data->cm, col);
970 vp9_zero(tile_data->xd.left_context);
971 vp9_zero(tile_data->xd.left_seg_context);
972 for (mi_col = tile.mi_col_start; mi_col < tile.mi_col_end;
973 mi_col += MI_BLOCK_SIZE) {
974 decode_partition(tile_data->cm, &tile_data->xd, &tile, mi_row, mi_col,
975 &tile_data->bit_reader, BLOCK_64X64);
977 pbi->mb.corrupted |= tile_data->xd.corrupted;
978 if (pbi->mb.corrupted)
979 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
980 "Failed to decode tile data");
982 // Loopfilter one row.
983 if (cm->lf.filter_level) {
984 const int lf_start = mi_row - MI_BLOCK_SIZE;
985 LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
987 // delay the loopfilter by 1 macroblock row.
988 if (lf_start < 0) continue;
990 // decoding has completed: finish up the loop filter in this thread.
991 if (mi_row + MI_BLOCK_SIZE >= cm->mi_rows) continue;
993 winterface->sync(&pbi->lf_worker);
994 lf_data->start = lf_start;
995 lf_data->stop = mi_row;
996 if (pbi->max_threads > 1) {
997 winterface->launch(&pbi->lf_worker);
999 winterface->execute(&pbi->lf_worker);
1005 // Loopfilter remaining rows in the frame.
1006 if (cm->lf.filter_level) {
1007 LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
1008 winterface->sync(&pbi->lf_worker);
1009 lf_data->start = lf_data->stop;
1010 lf_data->stop = cm->mi_rows;
1011 winterface->execute(&pbi->lf_worker);
1014 // Get last tile data.
1015 tile_data = pbi->tile_data + tile_cols * tile_rows - 1;
1017 return vp9_reader_find_end(&tile_data->bit_reader);
1020 static int tile_worker_hook(TileWorkerData *const tile_data,
1021 const TileInfo *const tile) {
1024 for (mi_row = tile->mi_row_start; mi_row < tile->mi_row_end;
1025 mi_row += MI_BLOCK_SIZE) {
1026 vp9_zero(tile_data->xd.left_context);
1027 vp9_zero(tile_data->xd.left_seg_context);
1028 for (mi_col = tile->mi_col_start; mi_col < tile->mi_col_end;
1029 mi_col += MI_BLOCK_SIZE) {
1030 decode_partition(tile_data->cm, &tile_data->xd, tile,
1031 mi_row, mi_col, &tile_data->bit_reader, BLOCK_64X64);
1034 return !tile_data->xd.corrupted;
1037 // sorts in descending order
1038 static int compare_tile_buffers(const void *a, const void *b) {
1039 const TileBuffer *const buf1 = (const TileBuffer*)a;
1040 const TileBuffer *const buf2 = (const TileBuffer*)b;
1041 if (buf1->size < buf2->size) {
1043 } else if (buf1->size == buf2->size) {
1050 static const uint8_t *decode_tiles_mt(VP9Decoder *pbi,
1051 const uint8_t *data,
1052 const uint8_t *data_end) {
1053 VP9_COMMON *const cm = &pbi->common;
1054 const VP9WorkerInterface *const winterface = vp9_get_worker_interface();
1055 const uint8_t *bit_reader_end = NULL;
1056 const int aligned_mi_cols = mi_cols_aligned_to_sb(cm->mi_cols);
1057 const int tile_cols = 1 << cm->log2_tile_cols;
1058 const int tile_rows = 1 << cm->log2_tile_rows;
1059 const int num_workers = MIN(pbi->max_threads & ~1, tile_cols);
1060 TileBuffer tile_buffers[1][1 << 6];
1062 int final_worker = -1;
1064 assert(tile_cols <= (1 << 6));
1065 assert(tile_rows == 1);
1068 // TODO(jzern): See if we can remove the restriction of passing in max
1069 // threads to the decoder.
1070 if (pbi->num_tile_workers == 0) {
1071 const int num_threads = pbi->max_threads & ~1;
1073 // TODO(jzern): Allocate one less worker, as in the current code we only
1074 // use num_threads - 1 workers.
1075 CHECK_MEM_ERROR(cm, pbi->tile_workers,
1076 vpx_malloc(num_threads * sizeof(*pbi->tile_workers)));
1077 // Ensure tile data offsets will be properly aligned. This may fail on
1078 // platforms without DECLARE_ALIGNED().
1079 assert((sizeof(*pbi->tile_worker_data) % 16) == 0);
1080 CHECK_MEM_ERROR(cm, pbi->tile_worker_data,
1081 vpx_memalign(32, num_threads *
1082 sizeof(*pbi->tile_worker_data)));
1083 CHECK_MEM_ERROR(cm, pbi->tile_worker_info,
1084 vpx_malloc(num_threads * sizeof(*pbi->tile_worker_info)));
1085 for (i = 0; i < num_threads; ++i) {
1086 VP9Worker *const worker = &pbi->tile_workers[i];
1087 ++pbi->num_tile_workers;
1089 winterface->init(worker);
1090 if (i < num_threads - 1 && !winterface->reset(worker)) {
1091 vpx_internal_error(&cm->error, VPX_CODEC_ERROR,
1092 "Tile decoder thread creation failed");
1097 // Reset tile decoding hook
1098 for (n = 0; n < num_workers; ++n) {
1099 VP9Worker *const worker = &pbi->tile_workers[n];
1100 winterface->sync(worker);
1101 worker->hook = (VP9WorkerHook)tile_worker_hook;
1102 worker->data1 = &pbi->tile_worker_data[n];
1103 worker->data2 = &pbi->tile_worker_info[n];
1106 // Note: this memset assumes above_context[0], [1] and [2]
1107 // are allocated as part of the same buffer.
1108 vpx_memset(cm->above_context, 0,
1109 sizeof(*cm->above_context) * MAX_MB_PLANE * 2 * aligned_mi_cols);
1110 vpx_memset(cm->above_seg_context, 0,
1111 sizeof(*cm->above_seg_context) * aligned_mi_cols);
1113 // Load tile data into tile_buffers
1114 get_tile_buffers(pbi, data, data_end, tile_cols, tile_rows, tile_buffers);
1116 // Sort the buffers based on size in descending order.
1117 qsort(tile_buffers[0], tile_cols, sizeof(tile_buffers[0][0]),
1118 compare_tile_buffers);
1120 // Rearrange the tile buffers such that per-tile group the largest, and
1121 // presumably the most difficult, tile will be decoded in the main thread.
1122 // This should help minimize the number of instances where the main thread is
1123 // waiting for a worker to complete.
1125 int group_start = 0;
1126 while (group_start < tile_cols) {
1127 const TileBuffer largest = tile_buffers[0][group_start];
1128 const int group_end = MIN(group_start + num_workers, tile_cols) - 1;
1129 memmove(tile_buffers[0] + group_start, tile_buffers[0] + group_start + 1,
1130 (group_end - group_start) * sizeof(tile_buffers[0][0]));
1131 tile_buffers[0][group_end] = largest;
1132 group_start = group_end + 1;
1137 while (n < tile_cols) {
1139 for (i = 0; i < num_workers && n < tile_cols; ++i) {
1140 VP9Worker *const worker = &pbi->tile_workers[i];
1141 TileWorkerData *const tile_data = (TileWorkerData*)worker->data1;
1142 TileInfo *const tile = (TileInfo*)worker->data2;
1143 TileBuffer *const buf = &tile_buffers[0][n];
1146 tile_data->xd = pbi->mb;
1147 tile_data->xd.corrupted = 0;
1148 vp9_tile_init(tile, tile_data->cm, 0, buf->col);
1149 setup_token_decoder(buf->data, data_end, buf->size, &cm->error,
1150 &tile_data->bit_reader, pbi->decrypt_cb,
1151 pbi->decrypt_state);
1152 init_macroblockd(cm, &tile_data->xd);
1154 worker->had_error = 0;
1155 if (i == num_workers - 1 || n == tile_cols - 1) {
1156 winterface->execute(worker);
1158 winterface->launch(worker);
1161 if (buf->col == tile_cols - 1) {
1168 for (; i > 0; --i) {
1169 VP9Worker *const worker = &pbi->tile_workers[i - 1];
1170 pbi->mb.corrupted |= !winterface->sync(worker);
1172 if (final_worker > -1) {
1173 TileWorkerData *const tile_data =
1174 (TileWorkerData*)pbi->tile_workers[final_worker].data1;
1175 bit_reader_end = vp9_reader_find_end(&tile_data->bit_reader);
1180 return bit_reader_end;
1183 static void error_handler(void *data) {
1184 VP9_COMMON *const cm = (VP9_COMMON *)data;
1185 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME, "Truncated packet");
1188 int vp9_read_sync_code(struct vp9_read_bit_buffer *const rb) {
1189 return vp9_rb_read_literal(rb, 8) == VP9_SYNC_CODE_0 &&
1190 vp9_rb_read_literal(rb, 8) == VP9_SYNC_CODE_1 &&
1191 vp9_rb_read_literal(rb, 8) == VP9_SYNC_CODE_2;
1194 BITSTREAM_PROFILE vp9_read_profile(struct vp9_read_bit_buffer *rb) {
1195 int profile = vp9_rb_read_bit(rb);
1196 profile |= vp9_rb_read_bit(rb) << 1;
1198 profile += vp9_rb_read_bit(rb);
1199 return (BITSTREAM_PROFILE) profile;
1202 static void read_bitdepth_colorspace_sampling(
1203 VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
1204 if (cm->profile >= PROFILE_2) {
1205 cm->bit_depth = vp9_rb_read_bit(rb) ? VPX_BITS_12 : VPX_BITS_10;
1206 #if CONFIG_VP9_HIGHBITDEPTH
1207 cm->use_highbitdepth = 1;
1210 cm->bit_depth = VPX_BITS_8;
1211 #if CONFIG_VP9_HIGHBITDEPTH
1212 cm->use_highbitdepth = 0;
1215 cm->color_space = (COLOR_SPACE)vp9_rb_read_literal(rb, 3);
1216 if (cm->color_space != SRGB) {
1217 vp9_rb_read_bit(rb); // [16,235] (including xvycc) vs [0,255] range
1218 if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
1219 cm->subsampling_x = vp9_rb_read_bit(rb);
1220 cm->subsampling_y = vp9_rb_read_bit(rb);
1221 if (cm->subsampling_x == 1 && cm->subsampling_y == 1)
1222 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1223 "4:2:0 color not supported in profile 1 or 3");
1224 if (vp9_rb_read_bit(rb))
1225 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1226 "Reserved bit set");
1228 cm->subsampling_y = cm->subsampling_x = 1;
1231 if (cm->profile == PROFILE_1 || cm->profile == PROFILE_3) {
1232 // Note if colorspace is SRGB then 4:4:4 chroma sampling is assumed.
1233 // 4:2:2 or 4:4:0 chroma sampling is not allowed.
1234 cm->subsampling_y = cm->subsampling_x = 0;
1235 if (vp9_rb_read_bit(rb))
1236 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1237 "Reserved bit set");
1239 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1240 "4:4:4 color not supported in profile 0 or 2");
1245 static size_t read_uncompressed_header(VP9Decoder *pbi,
1246 struct vp9_read_bit_buffer *rb) {
1247 VP9_COMMON *const cm = &pbi->common;
1251 cm->last_frame_type = cm->frame_type;
1253 if (vp9_rb_read_literal(rb, 2) != VP9_FRAME_MARKER)
1254 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1255 "Invalid frame marker");
1257 cm->profile = vp9_read_profile(rb);
1259 if (cm->profile >= MAX_PROFILES)
1260 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1261 "Unsupported bitstream profile");
1263 cm->show_existing_frame = vp9_rb_read_bit(rb);
1264 if (cm->show_existing_frame) {
1265 // Show an existing frame directly.
1266 const int frame_to_show = cm->ref_frame_map[vp9_rb_read_literal(rb, 3)];
1268 if (frame_to_show < 0 || cm->frame_bufs[frame_to_show].ref_count < 1)
1269 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1270 "Buffer %d does not contain a decoded frame",
1273 ref_cnt_fb(cm->frame_bufs, &cm->new_fb_idx, frame_to_show);
1274 pbi->refresh_frame_flags = 0;
1275 cm->lf.filter_level = 0;
1280 cm->frame_type = (FRAME_TYPE) vp9_rb_read_bit(rb);
1281 cm->show_frame = vp9_rb_read_bit(rb);
1282 cm->error_resilient_mode = vp9_rb_read_bit(rb);
1284 if (cm->frame_type == KEY_FRAME) {
1285 if (!vp9_read_sync_code(rb))
1286 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1287 "Invalid frame sync code");
1289 read_bitdepth_colorspace_sampling(cm, rb);
1290 pbi->refresh_frame_flags = (1 << REF_FRAMES) - 1;
1292 for (i = 0; i < REFS_PER_FRAME; ++i) {
1293 cm->frame_refs[i].idx = -1;
1294 cm->frame_refs[i].buf = NULL;
1297 setup_frame_size(cm, rb);
1298 pbi->need_resync = 0;
1300 cm->intra_only = cm->show_frame ? 0 : vp9_rb_read_bit(rb);
1302 cm->reset_frame_context = cm->error_resilient_mode ?
1303 0 : vp9_rb_read_literal(rb, 2);
1305 if (cm->intra_only) {
1306 if (!vp9_read_sync_code(rb))
1307 vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
1308 "Invalid frame sync code");
1309 if (cm->profile > PROFILE_0) {
1310 read_bitdepth_colorspace_sampling(cm, rb);
1312 // NOTE: The intra-only frame header does not include the specification
1313 // of either the color format or color sub-sampling in profile 0. VP9
1314 // specifies that the default color space should be YUV 4:2:0 in this
1315 // case (normative).
1316 cm->color_space = BT_601;
1317 cm->subsampling_y = cm->subsampling_x = 1;
1318 cm->bit_depth = VPX_BITS_8;
1319 #if CONFIG_VP9_HIGHBITDEPTH
1320 cm->use_highbitdepth = 0;
1324 pbi->refresh_frame_flags = vp9_rb_read_literal(rb, REF_FRAMES);
1325 setup_frame_size(cm, rb);
1326 pbi->need_resync = 0;
1328 pbi->refresh_frame_flags = vp9_rb_read_literal(rb, REF_FRAMES);
1329 for (i = 0; i < REFS_PER_FRAME; ++i) {
1330 const int ref = vp9_rb_read_literal(rb, REF_FRAMES_LOG2);
1331 const int idx = cm->ref_frame_map[ref];
1332 RefBuffer *const ref_frame = &cm->frame_refs[i];
1333 ref_frame->idx = idx;
1334 ref_frame->buf = &cm->frame_bufs[idx].buf;
1335 cm->ref_frame_sign_bias[LAST_FRAME + i] = vp9_rb_read_bit(rb);
1338 setup_frame_size_with_refs(cm, rb);
1340 cm->allow_high_precision_mv = vp9_rb_read_bit(rb);
1341 cm->interp_filter = read_interp_filter(rb);
1343 for (i = 0; i < REFS_PER_FRAME; ++i) {
1344 RefBuffer *const ref_buf = &cm->frame_refs[i];
1345 #if CONFIG_VP9_HIGHBITDEPTH
1346 vp9_setup_scale_factors_for_frame(&ref_buf->sf,
1347 ref_buf->buf->y_crop_width,
1348 ref_buf->buf->y_crop_height,
1349 cm->width, cm->height,
1350 cm->use_highbitdepth);
1352 vp9_setup_scale_factors_for_frame(&ref_buf->sf,
1353 ref_buf->buf->y_crop_width,
1354 ref_buf->buf->y_crop_height,
1355 cm->width, cm->height);
1357 if (vp9_is_scaled(&ref_buf->sf))
1358 vp9_extend_frame_borders(ref_buf->buf);
1362 #if CONFIG_VP9_HIGHBITDEPTH
1363 get_frame_new_buffer(cm)->bit_depth = cm->bit_depth;
1366 if (pbi->need_resync) {
1367 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1368 "Keyframe / intra-only frame required to reset decoder"
1372 if (!cm->error_resilient_mode) {
1373 cm->refresh_frame_context = vp9_rb_read_bit(rb);
1374 cm->frame_parallel_decoding_mode = vp9_rb_read_bit(rb);
1376 cm->refresh_frame_context = 0;
1377 cm->frame_parallel_decoding_mode = 1;
1380 // This flag will be overridden by the call to vp9_setup_past_independence
1381 // below, forcing the use of context 0 for those frame types.
1382 cm->frame_context_idx = vp9_rb_read_literal(rb, FRAME_CONTEXTS_LOG2);
1384 if (frame_is_intra_only(cm) || cm->error_resilient_mode)
1385 vp9_setup_past_independence(cm);
1387 setup_loopfilter(&cm->lf, rb);
1388 setup_quantization(cm, &pbi->mb, rb);
1389 setup_segmentation(&cm->seg, rb);
1391 setup_tile_info(cm, rb);
1392 sz = vp9_rb_read_literal(rb, 16);
1395 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1396 "Invalid header size");
1401 static int read_compressed_header(VP9Decoder *pbi, const uint8_t *data,
1402 size_t partition_size) {
1403 VP9_COMMON *const cm = &pbi->common;
1404 MACROBLOCKD *const xd = &pbi->mb;
1405 FRAME_CONTEXT *const fc = cm->fc;
1409 if (vp9_reader_init(&r, data, partition_size, pbi->decrypt_cb,
1410 pbi->decrypt_state))
1411 vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
1412 "Failed to allocate bool decoder 0");
1414 cm->tx_mode = xd->lossless ? ONLY_4X4 : read_tx_mode(&r);
1415 if (cm->tx_mode == TX_MODE_SELECT)
1416 read_tx_mode_probs(&fc->tx_probs, &r);
1417 read_coef_probs(fc, cm->tx_mode, &r);
1419 for (k = 0; k < SKIP_CONTEXTS; ++k)
1420 vp9_diff_update_prob(&r, &fc->skip_probs[k]);
1422 if (!frame_is_intra_only(cm)) {
1423 nmv_context *const nmvc = &fc->nmvc;
1426 read_inter_mode_probs(fc, &r);
1428 if (cm->interp_filter == SWITCHABLE)
1429 read_switchable_interp_probs(fc, &r);
1431 for (i = 0; i < INTRA_INTER_CONTEXTS; i++)
1432 vp9_diff_update_prob(&r, &fc->intra_inter_prob[i]);
1434 cm->reference_mode = read_frame_reference_mode(cm, &r);
1435 if (cm->reference_mode != SINGLE_REFERENCE)
1436 setup_compound_reference_mode(cm);
1437 read_frame_reference_mode_probs(cm, &r);
1439 for (j = 0; j < BLOCK_SIZE_GROUPS; j++)
1440 for (i = 0; i < INTRA_MODES - 1; ++i)
1441 vp9_diff_update_prob(&r, &fc->y_mode_prob[j][i]);
1443 for (j = 0; j < PARTITION_CONTEXTS; ++j)
1444 for (i = 0; i < PARTITION_TYPES - 1; ++i)
1445 vp9_diff_update_prob(&r, &fc->partition_prob[j][i]);
1447 read_mv_probs(nmvc, cm->allow_high_precision_mv, &r);
1450 return vp9_reader_has_error(&r);
1453 void vp9_init_dequantizer(VP9_COMMON *cm) {
1456 for (q = 0; q < QINDEX_RANGE; q++) {
1457 cm->y_dequant[q][0] = vp9_dc_quant(q, cm->y_dc_delta_q, cm->bit_depth);
1458 cm->y_dequant[q][1] = vp9_ac_quant(q, 0, cm->bit_depth);
1460 cm->uv_dequant[q][0] = vp9_dc_quant(q, cm->uv_dc_delta_q, cm->bit_depth);
1461 cm->uv_dequant[q][1] = vp9_ac_quant(q, cm->uv_ac_delta_q, cm->bit_depth);
1466 #define debug_check_frame_counts(cm) (void)0
1468 // Counts should only be incremented when frame_parallel_decoding_mode and
1469 // error_resilient_mode are disabled.
1470 static void debug_check_frame_counts(const VP9_COMMON *const cm) {
1471 FRAME_COUNTS zero_counts;
1472 vp9_zero(zero_counts);
1473 assert(cm->frame_parallel_decoding_mode || cm->error_resilient_mode);
1474 assert(!memcmp(cm->counts.y_mode, zero_counts.y_mode,
1475 sizeof(cm->counts.y_mode)));
1476 assert(!memcmp(cm->counts.uv_mode, zero_counts.uv_mode,
1477 sizeof(cm->counts.uv_mode)));
1478 assert(!memcmp(cm->counts.partition, zero_counts.partition,
1479 sizeof(cm->counts.partition)));
1480 assert(!memcmp(cm->counts.coef, zero_counts.coef,
1481 sizeof(cm->counts.coef)));
1482 assert(!memcmp(cm->counts.eob_branch, zero_counts.eob_branch,
1483 sizeof(cm->counts.eob_branch)));
1484 assert(!memcmp(cm->counts.switchable_interp, zero_counts.switchable_interp,
1485 sizeof(cm->counts.switchable_interp)));
1486 assert(!memcmp(cm->counts.inter_mode, zero_counts.inter_mode,
1487 sizeof(cm->counts.inter_mode)));
1488 assert(!memcmp(cm->counts.intra_inter, zero_counts.intra_inter,
1489 sizeof(cm->counts.intra_inter)));
1490 assert(!memcmp(cm->counts.comp_inter, zero_counts.comp_inter,
1491 sizeof(cm->counts.comp_inter)));
1492 assert(!memcmp(cm->counts.single_ref, zero_counts.single_ref,
1493 sizeof(cm->counts.single_ref)));
1494 assert(!memcmp(cm->counts.comp_ref, zero_counts.comp_ref,
1495 sizeof(cm->counts.comp_ref)));
1496 assert(!memcmp(&cm->counts.tx, &zero_counts.tx, sizeof(cm->counts.tx)));
1497 assert(!memcmp(cm->counts.skip, zero_counts.skip, sizeof(cm->counts.skip)));
1498 assert(!memcmp(&cm->counts.mv, &zero_counts.mv, sizeof(cm->counts.mv)));
1502 static struct vp9_read_bit_buffer* init_read_bit_buffer(
1504 struct vp9_read_bit_buffer *rb,
1505 const uint8_t *data,
1506 const uint8_t *data_end,
1507 uint8_t *clear_data /* buffer size MAX_VP9_HEADER_SIZE */) {
1509 rb->error_handler = error_handler;
1510 rb->error_handler_data = &pbi->common;
1511 if (pbi->decrypt_cb) {
1512 const int n = (int)MIN(MAX_VP9_HEADER_SIZE, data_end - data);
1513 pbi->decrypt_cb(pbi->decrypt_state, data, clear_data, n);
1514 rb->bit_buffer = clear_data;
1515 rb->bit_buffer_end = clear_data + n;
1517 rb->bit_buffer = data;
1518 rb->bit_buffer_end = data_end;
1523 void vp9_decode_frame(VP9Decoder *pbi,
1524 const uint8_t *data, const uint8_t *data_end,
1525 const uint8_t **p_data_end) {
1526 VP9_COMMON *const cm = &pbi->common;
1527 MACROBLOCKD *const xd = &pbi->mb;
1528 struct vp9_read_bit_buffer rb = { NULL, NULL, 0, NULL, 0};
1530 uint8_t clear_data[MAX_VP9_HEADER_SIZE];
1531 const size_t first_partition_size = read_uncompressed_header(pbi,
1532 init_read_bit_buffer(pbi, &rb, data, data_end, clear_data));
1533 const int tile_rows = 1 << cm->log2_tile_rows;
1534 const int tile_cols = 1 << cm->log2_tile_cols;
1535 YV12_BUFFER_CONFIG *const new_fb = get_frame_new_buffer(cm);
1536 xd->cur_buf = new_fb;
1538 if (!first_partition_size) {
1539 // showing a frame directly
1540 *p_data_end = data + (cm->profile <= PROFILE_2 ? 1 : 2);
1544 data += vp9_rb_bytes_read(&rb);
1545 if (!read_is_valid(data, first_partition_size, data_end))
1546 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1547 "Truncated packet or corrupt header length");
1549 init_macroblockd(cm, &pbi->mb);
1551 cm->use_prev_frame_mvs = !cm->error_resilient_mode &&
1552 cm->width == cm->last_width &&
1553 cm->height == cm->last_height &&
1555 cm->last_show_frame;
1557 setup_plane_dequants(cm, xd, cm->base_qindex);
1558 vp9_setup_block_planes(xd, cm->subsampling_x, cm->subsampling_y);
1560 *cm->fc = cm->frame_contexts[cm->frame_context_idx];
1561 vp9_zero(cm->counts);
1564 new_fb->corrupted = read_compressed_header(pbi, data, first_partition_size);
1565 if (new_fb->corrupted)
1566 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1567 "Decode failed. Frame data header is corrupted.");
1569 // TODO(jzern): remove frame_parallel_decoding_mode restriction for
1570 // single-frame tile decoding.
1571 if (pbi->max_threads > 1 && tile_rows == 1 && tile_cols > 1 &&
1572 cm->frame_parallel_decoding_mode) {
1573 *p_data_end = decode_tiles_mt(pbi, data + first_partition_size, data_end);
1574 if (!xd->corrupted) {
1575 // If multiple threads are used to decode tiles, then we use those threads
1576 // to do parallel loopfiltering.
1577 vp9_loop_filter_frame_mt(&pbi->lf_row_sync, new_fb, pbi->mb.plane, cm,
1578 pbi->tile_workers, pbi->num_tile_workers,
1579 cm->lf.filter_level, 0);
1581 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1582 "Decode failed. Frame data is corrupted.");
1586 *p_data_end = decode_tiles(pbi, data + first_partition_size, data_end);
1589 new_fb->corrupted |= xd->corrupted;
1591 if (!new_fb->corrupted) {
1592 if (!cm->error_resilient_mode && !cm->frame_parallel_decoding_mode) {
1593 vp9_adapt_coef_probs(cm);
1595 if (!frame_is_intra_only(cm)) {
1596 vp9_adapt_mode_probs(cm);
1597 vp9_adapt_mv_probs(cm, cm->allow_high_precision_mv);
1600 debug_check_frame_counts(cm);
1603 vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
1604 "Decode failed. Frame data is corrupted.");
1607 if (cm->refresh_frame_context)
1608 cm->frame_contexts[cm->frame_context_idx] = *cm->fc;