]> granicus.if.org Git - libvpx/blob - vp9/decoder/vp9_decodframe.c
Merge "Renaming in MB_MODE_INFO"
[libvpx] / vp9 / decoder / vp9_decodframe.c
1 /*
2  *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3  *
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.
9  */
10
11 #include <assert.h>
12
13 #include "./vp9_rtcd.h"
14 #include "vpx_mem/vpx_mem.h"
15 #include "vpx_scale/vpx_scale.h"
16
17 #include "vp9/common/vp9_alloccommon.h"
18 #include "vp9/common/vp9_common.h"
19 #include "vp9/common/vp9_entropy.h"
20 #include "vp9/common/vp9_entropymode.h"
21 #include "vp9/common/vp9_extend.h"
22 #include "vp9/common/vp9_pred_common.h"
23 #include "vp9/common/vp9_quant_common.h"
24 #include "vp9/common/vp9_reconintra.h"
25 #include "vp9/common/vp9_reconinter.h"
26 #include "vp9/common/vp9_seg_common.h"
27 #include "vp9/common/vp9_tile_common.h"
28
29 #include "vp9/decoder/vp9_dboolhuff.h"
30 #include "vp9/decoder/vp9_decodframe.h"
31 #include "vp9/decoder/vp9_detokenize.h"
32 #include "vp9/decoder/vp9_decodemv.h"
33 #include "vp9/decoder/vp9_dsubexp.h"
34 #include "vp9/decoder/vp9_idct_blk.h"
35 #include "vp9/decoder/vp9_onyxd_int.h"
36 #include "vp9/decoder/vp9_read_bit_buffer.h"
37 #include "vp9/decoder/vp9_thread.h"
38 #include "vp9/decoder/vp9_treereader.h"
39
40 static int read_be32(const uint8_t *p) {
41   return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
42 }
43
44 // len == 0 is not allowed
45 static int read_is_valid(const uint8_t *start, size_t len, const uint8_t *end) {
46   return start + len > start && start + len <= end;
47 }
48
49 static int decode_unsigned_max(struct vp9_read_bit_buffer *rb, int max) {
50   const int data = vp9_rb_read_literal(rb, get_unsigned_bits(max));
51   return data > max ? max : data;
52 }
53
54 static TX_MODE read_tx_mode(vp9_reader *r) {
55   TX_MODE tx_mode = vp9_read_literal(r, 2);
56   if (tx_mode == ALLOW_32X32)
57     tx_mode += vp9_read_bit(r);
58   return tx_mode;
59 }
60
61 static void read_tx_probs(struct tx_probs *tx_probs, vp9_reader *r) {
62   int i, j;
63
64   for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
65     for (j = 0; j < TX_SIZES - 3; ++j)
66       if (vp9_read(r, VP9_MODE_UPDATE_PROB))
67         vp9_diff_update_prob(r, &tx_probs->p8x8[i][j]);
68
69   for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
70     for (j = 0; j < TX_SIZES - 2; ++j)
71       if (vp9_read(r, VP9_MODE_UPDATE_PROB))
72         vp9_diff_update_prob(r, &tx_probs->p16x16[i][j]);
73
74   for (i = 0; i < TX_SIZE_CONTEXTS; ++i)
75     for (j = 0; j < TX_SIZES - 1; ++j)
76       if (vp9_read(r, VP9_MODE_UPDATE_PROB))
77         vp9_diff_update_prob(r, &tx_probs->p32x32[i][j]);
78 }
79
80 static void init_dequantizer(VP9_COMMON *cm, MACROBLOCKD *xd) {
81   int i;
82   const int segment_id = xd->mode_info_context->mbmi.segment_id;
83   xd->q_index = vp9_get_qindex(xd, segment_id, cm->base_qindex);
84
85   xd->plane[0].dequant = cm->y_dequant[xd->q_index];
86   for (i = 1; i < MAX_MB_PLANE; i++)
87     xd->plane[i].dequant = cm->uv_dequant[xd->q_index];
88 }
89
90 static void decode_block(int plane, int block, BLOCK_SIZE_TYPE bsize,
91                          int ss_txfrm_size, void *arg) {
92   MACROBLOCKD* const xd = arg;
93   struct macroblockd_plane *pd = &xd->plane[plane];
94   int16_t* const qcoeff = BLOCK_OFFSET(pd->qcoeff, block);
95   const int stride = pd->dst.stride;
96   const int eob = pd->eobs[block];
97   const int raster_block = txfrm_block_to_raster_block(xd, bsize, plane,
98                                                        block, ss_txfrm_size);
99   uint8_t* const dst = raster_block_offset_uint8(xd, bsize, plane,
100                                                  raster_block,
101                                                  pd->dst.buf, stride);
102   const TX_SIZE tx_size = (TX_SIZE)(ss_txfrm_size >> 1);
103
104   switch (tx_size) {
105     case TX_4X4: {
106       const TX_TYPE tx_type = get_tx_type_4x4(pd->plane_type, xd, raster_block);
107       if (tx_type == DCT_DCT)
108         xd->itxm_add(qcoeff, dst, stride, eob);
109       else
110         vp9_iht_add_c(tx_type, qcoeff, dst, stride, eob);
111       break;
112     }
113     case TX_8X8:
114       vp9_iht_add_8x8_c(get_tx_type_8x8(pd->plane_type, xd), qcoeff, dst,
115                         stride, eob);
116       break;
117     case TX_16X16:
118       vp9_iht_add_16x16_c(get_tx_type_16x16(pd->plane_type, xd), qcoeff, dst,
119                           stride, eob);
120       break;
121     case TX_32X32:
122       vp9_idct_add_32x32(qcoeff, dst, stride, eob);
123       break;
124     default:
125       assert(!"Invalid transform size");
126   }
127 }
128
129 static void decode_block_intra(int plane, int block, BLOCK_SIZE_TYPE bsize,
130                                int ss_txfrm_size, void *arg) {
131   MACROBLOCKD* const xd = arg;
132   struct macroblockd_plane *pd = &xd->plane[plane];
133   MODE_INFO *const mi = xd->mode_info_context;
134
135   const int raster_block = txfrm_block_to_raster_block(xd, bsize, plane,
136                                                        block, ss_txfrm_size);
137   uint8_t* const dst = raster_block_offset_uint8(xd, bsize, plane,
138                                                  raster_block,
139                                                  pd->dst.buf, pd->dst.stride);
140   const TX_SIZE tx_size = (TX_SIZE)(ss_txfrm_size >> 1);
141   int b_mode;
142   int plane_b_size;
143   const int tx_ib = raster_block >> tx_size;
144   const int mode = plane == 0 ? mi->mbmi.mode
145                               : mi->mbmi.uv_mode;
146
147   if (plane == 0 && mi->mbmi.sb_type < BLOCK_8X8) {
148     assert(bsize == BLOCK_8X8);
149     b_mode = mi->bmi[raster_block].as_mode;
150   } else {
151     b_mode = mode;
152   }
153
154   if (xd->mb_to_right_edge < 0 || xd->mb_to_bottom_edge < 0)
155     extend_for_intra(xd, plane, block, bsize, ss_txfrm_size);
156
157   plane_b_size = b_width_log2(bsize) - pd->subsampling_x;
158   vp9_predict_intra_block(xd, tx_ib, plane_b_size, tx_size, b_mode,
159                           dst, pd->dst.stride,
160                           dst, pd->dst.stride);
161
162   // Early exit if there are no coefficients
163   if (mi->mbmi.skip_coeff)
164     return;
165
166   decode_block(plane, block, bsize, ss_txfrm_size, arg);
167 }
168
169 static int decode_tokens(VP9D_COMP *pbi, BLOCK_SIZE_TYPE bsize, vp9_reader *r) {
170   MACROBLOCKD *const xd = &pbi->mb;
171
172   if (xd->mode_info_context->mbmi.skip_coeff) {
173       reset_skip_context(xd, bsize);
174     return -1;
175   } else {
176     if (xd->seg.enabled)
177       init_dequantizer(&pbi->common, xd);
178
179     // TODO(dkovalev) if (!vp9_reader_has_error(r))
180     return vp9_decode_tokens(pbi, r, bsize);
181   }
182 }
183
184 static void set_offsets(VP9D_COMP *pbi, BLOCK_SIZE_TYPE bsize,
185                         int mi_row, int mi_col) {
186   VP9_COMMON *const cm = &pbi->common;
187   MACROBLOCKD *const xd = &pbi->mb;
188   const int bh = 1 << mi_height_log2(bsize);
189   const int bw = 1 << mi_width_log2(bsize);
190   const int mi_idx = mi_row * cm->mode_info_stride + mi_col;
191
192   xd->mode_info_context = cm->mi + mi_idx;
193   xd->mode_info_context->mbmi.sb_type = bsize;
194   // Special case: if prev_mi is NULL, the previous mode info context
195   // cannot be used.
196   xd->prev_mode_info_context = cm->prev_mi ? cm->prev_mi + mi_idx : NULL;
197
198
199   set_skip_context(cm, xd, mi_row, mi_col);
200   set_partition_seg_context(cm, xd, mi_row, mi_col);
201
202   // Distance of Mb to the various image edges. These are specified to 8th pel
203   // as they are always compared to values that are in 1/8th pel units
204   set_mi_row_col(cm, xd, mi_row, bh, mi_col, bw);
205
206   setup_dst_planes(xd, &cm->yv12_fb[cm->new_fb_idx], mi_row, mi_col);
207 }
208
209 static void set_ref(VP9D_COMP *pbi, int i, int mi_row, int mi_col) {
210   VP9_COMMON *const cm = &pbi->common;
211   MACROBLOCKD *const xd = &pbi->mb;
212   MB_MODE_INFO *const mbmi = &xd->mode_info_context->mbmi;
213   const int ref = mbmi->ref_frame[i] - 1;
214
215   const YV12_BUFFER_CONFIG *cfg = &cm->yv12_fb[cm->active_ref_idx[ref]];
216   xd->scale_factor[i] = cm->active_ref_scale[ref];
217   setup_pre_planes(xd, i, cfg, mi_row, mi_col, &xd->scale_factor[i]);
218   xd->corrupted |= cfg->corrupted;
219 }
220
221 static void decode_modes_b(VP9D_COMP *pbi, int mi_row, int mi_col,
222                            vp9_reader *r, BLOCK_SIZE_TYPE bsize) {
223   VP9_COMMON *const cm = &pbi->common;
224   MACROBLOCKD *const xd = &pbi->mb;
225   const int less8x8 = bsize < BLOCK_8X8;
226   MB_MODE_INFO *mbmi;
227
228   if (less8x8)
229     if (xd->ab_index > 0)
230       return;
231
232   set_offsets(pbi, bsize, mi_row, mi_col);
233   vp9_read_mode_info(pbi, mi_row, mi_col, r);
234
235   if (less8x8)
236     bsize = BLOCK_8X8;
237
238   // Has to be called after set_offsets
239   mbmi = &xd->mode_info_context->mbmi;
240
241   if (!is_inter_block(mbmi)) {
242     // Intra reconstruction
243     decode_tokens(pbi, bsize, r);
244     foreach_transformed_block(xd, bsize, decode_block_intra, xd);
245   } else {
246     // Inter reconstruction
247     int eobtotal;
248
249     set_ref(pbi, 0, mi_row, mi_col);
250     if (mbmi->ref_frame[1] > INTRA_FRAME)
251       set_ref(pbi, 1, mi_row, mi_col);
252
253     vp9_setup_interp_filters(xd, mbmi->interp_filter, cm);
254     vp9_build_inter_predictors_sb(xd, mi_row, mi_col, bsize);
255     eobtotal = decode_tokens(pbi, bsize, r);
256     if (less8x8) {
257       if (eobtotal >= 0)
258         foreach_transformed_block(xd, bsize, decode_block, xd);
259     } else {
260       assert(mbmi->sb_type == bsize);
261       if (eobtotal == 0)
262         // skip loopfilter
263         vp9_set_pred_flag_mbskip(cm, bsize, mi_row, mi_col, 1);
264       else if (eobtotal > 0)
265         foreach_transformed_block(xd, bsize, decode_block, xd);
266     }
267   }
268   xd->corrupted |= vp9_reader_has_error(r);
269 }
270
271 static void decode_modes_sb(VP9D_COMP *pbi, int mi_row, int mi_col,
272                             vp9_reader* r, BLOCK_SIZE_TYPE bsize) {
273   VP9_COMMON *const pc = &pbi->common;
274   MACROBLOCKD *const xd = &pbi->mb;
275   int bs = (1 << mi_width_log2(bsize)) / 2, n;
276   PARTITION_TYPE partition = PARTITION_NONE;
277   BLOCK_SIZE_TYPE subsize;
278
279   if (mi_row >= pc->mi_rows || mi_col >= pc->mi_cols)
280     return;
281
282   if (bsize < BLOCK_8X8) {
283     if (xd->ab_index != 0)
284       return;
285   } else {
286     int pl;
287     const int idx = check_bsize_coverage(pc, mi_row, mi_col, bsize);
288     set_partition_seg_context(pc, xd, mi_row, mi_col);
289     pl = partition_plane_context(xd, bsize);
290
291     if (idx == 0)
292       partition = treed_read(r, vp9_partition_tree,
293                              pc->fc.partition_prob[pc->frame_type][pl]);
294     else if (idx > 0 &&
295         !vp9_read(r, pc->fc.partition_prob[pc->frame_type][pl][idx]))
296       partition = (idx == 1) ? PARTITION_HORZ : PARTITION_VERT;
297     else
298       partition = PARTITION_SPLIT;
299
300     pc->counts.partition[pl][partition]++;
301   }
302
303   subsize = get_subsize(bsize, partition);
304   *(get_sb_index(xd, subsize)) = 0;
305
306   switch (partition) {
307     case PARTITION_NONE:
308       decode_modes_b(pbi, mi_row, mi_col, r, subsize);
309       break;
310     case PARTITION_HORZ:
311       decode_modes_b(pbi, mi_row, mi_col, r, subsize);
312       *(get_sb_index(xd, subsize)) = 1;
313       if (mi_row + bs < pc->mi_rows)
314         decode_modes_b(pbi, mi_row + bs, mi_col, r, subsize);
315       break;
316     case PARTITION_VERT:
317       decode_modes_b(pbi, mi_row, mi_col, r, subsize);
318       *(get_sb_index(xd, subsize)) = 1;
319       if (mi_col + bs < pc->mi_cols)
320         decode_modes_b(pbi, mi_row, mi_col + bs, r, subsize);
321       break;
322     case PARTITION_SPLIT:
323       for (n = 0; n < 4; n++) {
324         int j = n >> 1, i = n & 0x01;
325         *(get_sb_index(xd, subsize)) = n;
326         decode_modes_sb(pbi, mi_row + j * bs, mi_col + i * bs, r, subsize);
327       }
328       break;
329     default:
330       assert(!"Invalid partition type");
331   }
332
333   // update partition context
334   if (bsize >= BLOCK_8X8 &&
335       (bsize == BLOCK_8X8 || partition != PARTITION_SPLIT)) {
336     set_partition_seg_context(pc, xd, mi_row, mi_col);
337     update_partition_context(xd, subsize, bsize);
338   }
339 }
340
341 static void setup_token_decoder(VP9D_COMP *pbi,
342                                 const uint8_t *data, size_t read_size,
343                                 vp9_reader *r) {
344   VP9_COMMON *pc = &pbi->common;
345   const uint8_t *data_end = pbi->source + pbi->source_sz;
346
347   // Validate the calculated partition length. If the buffer
348   // described by the partition can't be fully read, then restrict
349   // it to the portion that can be (for EC mode) or throw an error.
350   if (!read_is_valid(data, read_size, data_end))
351     vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME,
352                        "Truncated packet or corrupt tile length");
353
354   if (vp9_reader_init(r, data, read_size))
355     vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR,
356                        "Failed to allocate bool decoder %d", 1);
357 }
358
359 static void read_coef_probs_common(vp9_coeff_probs_model *coef_probs,
360                                    vp9_reader *r) {
361   int i, j, k, l, m;
362
363   if (vp9_read_bit(r))
364     for (i = 0; i < BLOCK_TYPES; i++)
365       for (j = 0; j < REF_TYPES; j++)
366         for (k = 0; k < COEF_BANDS; k++)
367           for (l = 0; l < PREV_COEF_CONTEXTS; l++)
368             if (k > 0 || l < 3)
369               for (m = 0; m < UNCONSTRAINED_NODES; m++)
370                 if (vp9_read(r, VP9_COEF_UPDATE_PROB))
371                   vp9_diff_update_prob(r, &coef_probs[i][j][k][l][m]);
372 }
373
374 static void read_coef_probs(FRAME_CONTEXT *fc, TX_MODE tx_mode,
375                             vp9_reader *r) {
376   read_coef_probs_common(fc->coef_probs[TX_4X4], r);
377
378   if (tx_mode > ONLY_4X4)
379     read_coef_probs_common(fc->coef_probs[TX_8X8], r);
380
381   if (tx_mode > ALLOW_8X8)
382     read_coef_probs_common(fc->coef_probs[TX_16X16], r);
383
384   if (tx_mode > ALLOW_16X16)
385     read_coef_probs_common(fc->coef_probs[TX_32X32], r);
386 }
387
388 static void setup_segmentation(struct segmentation *seg,
389                                struct vp9_read_bit_buffer *rb) {
390   int i, j;
391
392   seg->update_map = 0;
393   seg->update_data = 0;
394
395   seg->enabled = vp9_rb_read_bit(rb);
396   if (!seg->enabled)
397     return;
398
399   // Segmentation map update
400   seg->update_map = vp9_rb_read_bit(rb);
401   if (seg->update_map) {
402     for (i = 0; i < SEG_TREE_PROBS; i++)
403       seg->tree_probs[i] = vp9_rb_read_bit(rb) ? vp9_rb_read_literal(rb, 8)
404                                                : MAX_PROB;
405
406     seg->temporal_update = vp9_rb_read_bit(rb);
407     if (seg->temporal_update) {
408       for (i = 0; i < PREDICTION_PROBS; i++)
409         seg->pred_probs[i] = vp9_rb_read_bit(rb) ? vp9_rb_read_literal(rb, 8)
410                                                  : MAX_PROB;
411     } else {
412       for (i = 0; i < PREDICTION_PROBS; i++)
413         seg->pred_probs[i] = MAX_PROB;
414     }
415   }
416
417   // Segmentation data update
418   seg->update_data = vp9_rb_read_bit(rb);
419   if (seg->update_data) {
420     seg->abs_delta = vp9_rb_read_bit(rb);
421
422     vp9_clearall_segfeatures(seg);
423
424     for (i = 0; i < MAX_SEGMENTS; i++) {
425       for (j = 0; j < SEG_LVL_MAX; j++) {
426         int data = 0;
427         const int feature_enabled = vp9_rb_read_bit(rb);
428         if (feature_enabled) {
429           vp9_enable_segfeature(seg, i, j);
430           data = decode_unsigned_max(rb, vp9_seg_feature_data_max(j));
431           if (vp9_is_segfeature_signed(j))
432             data = vp9_rb_read_bit(rb) ? -data : data;
433         }
434         vp9_set_segdata(seg, i, j, data);
435       }
436     }
437   }
438 }
439
440 static void setup_loopfilter(struct loopfilter *lf,
441                              struct vp9_read_bit_buffer *rb) {
442
443   lf->filter_level = vp9_rb_read_literal(rb, 6);
444   lf->sharpness_level = vp9_rb_read_literal(rb, 3);
445
446   // Read in loop filter deltas applied at the MB level based on mode or ref
447   // frame.
448   lf->mode_ref_delta_update = 0;
449
450   lf->mode_ref_delta_enabled = vp9_rb_read_bit(rb);
451   if (lf->mode_ref_delta_enabled) {
452     lf->mode_ref_delta_update = vp9_rb_read_bit(rb);
453     if (lf->mode_ref_delta_update) {
454       int i;
455
456       for (i = 0; i < MAX_REF_LF_DELTAS; i++)
457         if (vp9_rb_read_bit(rb))
458           lf->ref_deltas[i] = vp9_rb_read_signed_literal(rb, 6);
459
460       for (i = 0; i < MAX_MODE_LF_DELTAS; i++)
461         if (vp9_rb_read_bit(rb))
462           lf->mode_deltas[i] = vp9_rb_read_signed_literal(rb, 6);
463     }
464   }
465 }
466
467 static int read_delta_q(struct vp9_read_bit_buffer *rb, int *delta_q) {
468   const int old = *delta_q;
469   if (vp9_rb_read_bit(rb))
470     *delta_q = vp9_rb_read_signed_literal(rb, 4);
471   return old != *delta_q;
472 }
473
474 static void setup_quantization(VP9D_COMP *pbi, struct vp9_read_bit_buffer *rb) {
475   MACROBLOCKD *const xd = &pbi->mb;
476   VP9_COMMON *const cm = &pbi->common;
477   int update = 0;
478
479   cm->base_qindex = vp9_rb_read_literal(rb, QINDEX_BITS);
480   update |= read_delta_q(rb, &cm->y_dc_delta_q);
481   update |= read_delta_q(rb, &cm->uv_dc_delta_q);
482   update |= read_delta_q(rb, &cm->uv_ac_delta_q);
483   if (update)
484     vp9_init_dequantizer(cm);
485
486   xd->lossless = cm->base_qindex == 0 &&
487                  cm->y_dc_delta_q == 0 &&
488                  cm->uv_dc_delta_q == 0 &&
489                  cm->uv_ac_delta_q == 0;
490
491   xd->itxm_add = xd->lossless ? vp9_idct_add_lossless_c
492                               : vp9_idct_add;
493 }
494
495 static INTERPOLATIONFILTERTYPE read_interp_filter_type(
496     struct vp9_read_bit_buffer *rb) {
497   const INTERPOLATIONFILTERTYPE literal_to_type[] = { EIGHTTAP_SMOOTH,
498                                                       EIGHTTAP,
499                                                       EIGHTTAP_SHARP };
500   return vp9_rb_read_bit(rb) ? SWITCHABLE
501                              : literal_to_type[vp9_rb_read_literal(rb, 2)];
502 }
503
504 static void read_frame_size(struct vp9_read_bit_buffer *rb,
505                             int *width, int *height) {
506   const int w = vp9_rb_read_literal(rb, 16) + 1;
507   const int h = vp9_rb_read_literal(rb, 16) + 1;
508   *width = w;
509   *height = h;
510 }
511
512 static void setup_display_size(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
513   cm->display_width = cm->width;
514   cm->display_height = cm->height;
515   if (vp9_rb_read_bit(rb))
516     read_frame_size(rb, &cm->display_width, &cm->display_height);
517 }
518
519 static void apply_frame_size(VP9D_COMP *pbi, int width, int height) {
520   VP9_COMMON *cm = &pbi->common;
521
522   if (cm->width != width || cm->height != height) {
523     if (!pbi->initial_width || !pbi->initial_height) {
524       if (vp9_alloc_frame_buffers(cm, width, height))
525         vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
526                            "Failed to allocate frame buffers");
527       pbi->initial_width = width;
528       pbi->initial_height = height;
529     } else {
530       if (width > pbi->initial_width)
531         vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
532                            "Frame width too large");
533
534       if (height > pbi->initial_height)
535         vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
536                            "Frame height too large");
537     }
538
539     cm->width = width;
540     cm->height = height;
541
542     vp9_update_frame_size(cm);
543   }
544
545   vp9_realloc_frame_buffer(&cm->yv12_fb[cm->new_fb_idx], cm->width, cm->height,
546                            cm->subsampling_x, cm->subsampling_y,
547                            VP9BORDERINPIXELS);
548 }
549
550 static void setup_frame_size(VP9D_COMP *pbi,
551                              struct vp9_read_bit_buffer *rb) {
552   int width, height;
553   read_frame_size(rb, &width, &height);
554   setup_display_size(&pbi->common, rb);
555   apply_frame_size(pbi, width, height);
556 }
557
558 static void setup_frame_size_with_refs(VP9D_COMP *pbi,
559                                        struct vp9_read_bit_buffer *rb) {
560   VP9_COMMON *const cm = &pbi->common;
561
562   int width, height;
563   int found = 0, i;
564   for (i = 0; i < ALLOWED_REFS_PER_FRAME; ++i) {
565     if (vp9_rb_read_bit(rb)) {
566       YV12_BUFFER_CONFIG *cfg = &cm->yv12_fb[cm->active_ref_idx[i]];
567       width = cfg->y_crop_width;
568       height = cfg->y_crop_height;
569       found = 1;
570       break;
571     }
572   }
573
574   if (!found)
575     read_frame_size(rb, &width, &height);
576
577   if (!width || !height)
578     vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME,
579                        "Referenced frame with invalid size");
580
581   setup_display_size(cm, rb);
582   apply_frame_size(pbi, width, height);
583 }
584
585 static void decode_tile(VP9D_COMP *pbi, vp9_reader *r) {
586   const int num_threads = pbi->oxcf.max_threads;
587   VP9_COMMON *const pc = &pbi->common;
588   int mi_row, mi_col;
589   YV12_BUFFER_CONFIG *const fb = &pc->yv12_fb[pc->new_fb_idx];
590
591   if (pbi->do_loopfilter_inline) {
592     if (num_threads > 1) {
593       LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
594       lf_data->frame_buffer = fb;
595       lf_data->cm = pc;
596       lf_data->xd = pbi->mb;
597       lf_data->y_only = 0;
598     }
599     vp9_loop_filter_frame_init(pc, &pbi->mb, pc->lf.filter_level);
600   }
601
602   for (mi_row = pc->cur_tile_mi_row_start; mi_row < pc->cur_tile_mi_row_end;
603        mi_row += MI_BLOCK_SIZE) {
604     // For a SB there are 2 left contexts, each pertaining to a MB row within
605     vp9_zero(pc->left_context);
606     vp9_zero(pc->left_seg_context);
607     for (mi_col = pc->cur_tile_mi_col_start; mi_col < pc->cur_tile_mi_col_end;
608          mi_col += MI_BLOCK_SIZE) {
609       decode_modes_sb(pbi, mi_row, mi_col, r, BLOCK_64X64);
610     }
611
612     if (pbi->do_loopfilter_inline) {
613       // delay the loopfilter by 1 macroblock row.
614       const int lf_start = mi_row - MI_BLOCK_SIZE;
615       if (lf_start < 0) continue;
616
617       if (num_threads > 1) {
618         LFWorkerData *const lf_data = (LFWorkerData*)pbi->lf_worker.data1;
619
620         vp9_worker_sync(&pbi->lf_worker);
621         lf_data->start = lf_start;
622         lf_data->stop = mi_row;
623         pbi->lf_worker.hook = vp9_loop_filter_worker;
624         vp9_worker_launch(&pbi->lf_worker);
625       } else {
626         vp9_loop_filter_rows(fb, pc, &pbi->mb, lf_start, mi_row, 0);
627       }
628     }
629   }
630
631   if (pbi->do_loopfilter_inline) {
632     if (num_threads > 1) {
633       // TODO(jzern): since the loop filter is delayed one mb row, this will be
634       // forced to wait for the last row scheduled in the for loop.
635       vp9_worker_sync(&pbi->lf_worker);
636     }
637     vp9_loop_filter_rows(fb, pc, &pbi->mb,
638                          mi_row - MI_BLOCK_SIZE, pc->mi_rows, 0);
639   }
640 }
641
642 static void setup_tile_info(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
643   int min_log2_tile_cols, max_log2_tile_cols, max_ones;
644   vp9_get_tile_n_bits(cm->mi_cols, &min_log2_tile_cols, &max_log2_tile_cols);
645
646   // columns
647   max_ones = max_log2_tile_cols - min_log2_tile_cols;
648   cm->log2_tile_cols = min_log2_tile_cols;
649   while (max_ones-- && vp9_rb_read_bit(rb))
650     cm->log2_tile_cols++;
651
652   // rows
653   cm->log2_tile_rows = vp9_rb_read_bit(rb);
654   if (cm->log2_tile_rows)
655     cm->log2_tile_rows += vp9_rb_read_bit(rb);
656 }
657
658 static const uint8_t *decode_tiles(VP9D_COMP *pbi, const uint8_t *data) {
659   vp9_reader residual_bc;
660
661   VP9_COMMON *const pc = &pbi->common;
662
663   const uint8_t *const data_end = pbi->source + pbi->source_sz;
664   const int aligned_mi_cols = mi_cols_aligned_to_sb(pc->mi_cols);
665   const int tile_cols = 1 << pc->log2_tile_cols;
666   const int tile_rows = 1 << pc->log2_tile_rows;
667   int tile_row, tile_col;
668
669   // Note: this memset assumes above_context[0], [1] and [2]
670   // are allocated as part of the same buffer.
671   vpx_memset(pc->above_context[0], 0,
672              sizeof(ENTROPY_CONTEXT) * MAX_MB_PLANE * (2 * aligned_mi_cols));
673
674   vpx_memset(pc->above_seg_context, 0,
675              sizeof(PARTITION_CONTEXT) * aligned_mi_cols);
676
677   if (pbi->oxcf.inv_tile_order) {
678     const uint8_t *data_ptr2[4][1 << 6];
679     vp9_reader bc_bak = {0};
680
681     // pre-initialize the offsets, we're going to read in inverse order
682     data_ptr2[0][0] = data;
683     for (tile_row = 0; tile_row < tile_rows; tile_row++) {
684       if (tile_row) {
685         const int size = read_be32(data_ptr2[tile_row - 1][tile_cols - 1]);
686         data_ptr2[tile_row - 1][tile_cols - 1] += 4;
687         data_ptr2[tile_row][0] = data_ptr2[tile_row - 1][tile_cols - 1] + size;
688       }
689
690       for (tile_col = 1; tile_col < tile_cols; tile_col++) {
691         const int size = read_be32(data_ptr2[tile_row][tile_col - 1]);
692         data_ptr2[tile_row][tile_col - 1] += 4;
693         data_ptr2[tile_row][tile_col] =
694             data_ptr2[tile_row][tile_col - 1] + size;
695       }
696     }
697
698     for (tile_row = 0; tile_row < tile_rows; tile_row++) {
699       vp9_get_tile_row_offsets(pc, tile_row);
700       for (tile_col = tile_cols - 1; tile_col >= 0; tile_col--) {
701         vp9_get_tile_col_offsets(pc, tile_col);
702         setup_token_decoder(pbi, data_ptr2[tile_row][tile_col],
703                             data_end - data_ptr2[tile_row][tile_col],
704                             &residual_bc);
705         decode_tile(pbi, &residual_bc);
706         if (tile_row == tile_rows - 1 && tile_col == tile_cols - 1)
707           bc_bak = residual_bc;
708       }
709     }
710     residual_bc = bc_bak;
711   } else {
712     int has_more;
713
714     for (tile_row = 0; tile_row < tile_rows; tile_row++) {
715       vp9_get_tile_row_offsets(pc, tile_row);
716       for (tile_col = 0; tile_col < tile_cols; tile_col++) {
717         size_t size;
718
719         vp9_get_tile_col_offsets(pc, tile_col);
720
721         has_more = tile_col < tile_cols - 1 || tile_row < tile_rows - 1;
722         if (has_more) {
723           if (!read_is_valid(data, 4, data_end))
724             vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME,
725                          "Truncated packet or corrupt tile length");
726
727           size = read_be32(data);
728           data += 4;
729         } else {
730           size = data_end - data;
731         }
732
733         setup_token_decoder(pbi, data, size, &residual_bc);
734         decode_tile(pbi, &residual_bc);
735         data += size;
736       }
737     }
738   }
739
740   return vp9_reader_find_end(&residual_bc);
741 }
742
743 static void check_sync_code(VP9_COMMON *cm, struct vp9_read_bit_buffer *rb) {
744   if (vp9_rb_read_literal(rb, 8) != SYNC_CODE_0 ||
745       vp9_rb_read_literal(rb, 8) != SYNC_CODE_1 ||
746       vp9_rb_read_literal(rb, 8) != SYNC_CODE_2) {
747     vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
748                        "Invalid frame sync code");
749   }
750 }
751
752 static void error_handler(void *data, size_t bit_offset) {
753   VP9_COMMON *const cm = (VP9_COMMON *)data;
754   vpx_internal_error(&cm->error, VPX_CODEC_CORRUPT_FRAME, "Truncated packet");
755 }
756
757 static void setup_inter_inter(VP9_COMMON *cm) {
758   int i;
759
760   cm->allow_comp_inter_inter = 0;
761   for (i = 1; i < ALLOWED_REFS_PER_FRAME; ++i)
762     cm->allow_comp_inter_inter |=
763         cm->ref_frame_sign_bias[i + 1] != cm->ref_frame_sign_bias[1];
764
765   if (cm->allow_comp_inter_inter) {
766     // which one is always-on in comp inter-inter?
767     if (cm->ref_frame_sign_bias[LAST_FRAME] ==
768         cm->ref_frame_sign_bias[GOLDEN_FRAME]) {
769       cm->comp_fixed_ref = ALTREF_FRAME;
770       cm->comp_var_ref[0] = LAST_FRAME;
771       cm->comp_var_ref[1] = GOLDEN_FRAME;
772     } else if (cm->ref_frame_sign_bias[LAST_FRAME] ==
773                cm->ref_frame_sign_bias[ALTREF_FRAME]) {
774       cm->comp_fixed_ref = GOLDEN_FRAME;
775       cm->comp_var_ref[0] = LAST_FRAME;
776       cm->comp_var_ref[1] = ALTREF_FRAME;
777     } else {
778       cm->comp_fixed_ref = LAST_FRAME;
779       cm->comp_var_ref[0] = GOLDEN_FRAME;
780       cm->comp_var_ref[1] = ALTREF_FRAME;
781     }
782   }
783 }
784
785 #define RESERVED \
786   if (vp9_rb_read_bit(rb)) \
787       vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM, \
788                          "Reserved bit must be unset")
789
790 static size_t read_uncompressed_header(VP9D_COMP *pbi,
791                                        struct vp9_read_bit_buffer *rb) {
792   VP9_COMMON *const cm = &pbi->common;
793   MACROBLOCKD *const xd = &pbi->mb;
794   int i;
795
796   cm->last_frame_type = cm->frame_type;
797
798   if (vp9_rb_read_literal(rb, 2) != 0x2)
799       vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
800                          "Invalid frame marker");
801
802   cm->version = vp9_rb_read_bit(rb);
803   RESERVED;
804
805   if (vp9_rb_read_bit(rb)) {
806     // show an existing frame directly
807     int frame_to_show = cm->ref_frame_map[vp9_rb_read_literal(rb, 3)];
808     ref_cnt_fb(cm->fb_idx_ref_cnt, &cm->new_fb_idx, frame_to_show);
809     pbi->refresh_frame_flags = 0;
810     cm->lf.filter_level = 0;
811     return 0;
812   }
813
814   cm->frame_type = (FRAME_TYPE) vp9_rb_read_bit(rb);
815   cm->show_frame = vp9_rb_read_bit(rb);
816   cm->error_resilient_mode = vp9_rb_read_bit(rb);
817
818   if (cm->frame_type == KEY_FRAME) {
819     int csp;
820
821     check_sync_code(cm, rb);
822
823     csp = vp9_rb_read_literal(rb, 3);  // colorspace
824     if (csp != 7) {  // != sRGB
825       vp9_rb_read_bit(rb);  // [16,235] (including xvycc) vs [0,255] range
826       if (cm->version == 1) {
827         cm->subsampling_x = vp9_rb_read_bit(rb);
828         cm->subsampling_y = vp9_rb_read_bit(rb);
829         vp9_rb_read_bit(rb);  // has extra plane
830       } else {
831         cm->subsampling_y = cm->subsampling_x = 1;
832       }
833     } else {
834       if (cm->version == 1) {
835         cm->subsampling_y = cm->subsampling_x = 0;
836         vp9_rb_read_bit(rb);  // has extra plane
837       } else {
838         vpx_internal_error(&cm->error, VPX_CODEC_UNSUP_BITSTREAM,
839                            "RGB not supported in profile 0");
840       }
841     }
842
843     pbi->refresh_frame_flags = (1 << NUM_REF_FRAMES) - 1;
844
845     for (i = 0; i < ALLOWED_REFS_PER_FRAME; ++i)
846       cm->active_ref_idx[i] = cm->new_fb_idx;
847
848     setup_frame_size(pbi, rb);
849   } else {
850     cm->intra_only = cm->show_frame ? 0 : vp9_rb_read_bit(rb);
851
852     cm->reset_frame_context = cm->error_resilient_mode ?
853         0 : vp9_rb_read_literal(rb, 2);
854
855     if (cm->intra_only) {
856       check_sync_code(cm, rb);
857
858       pbi->refresh_frame_flags = vp9_rb_read_literal(rb, NUM_REF_FRAMES);
859       setup_frame_size(pbi, rb);
860     } else {
861       pbi->refresh_frame_flags = vp9_rb_read_literal(rb, NUM_REF_FRAMES);
862
863       for (i = 0; i < ALLOWED_REFS_PER_FRAME; ++i) {
864         const int ref = vp9_rb_read_literal(rb, NUM_REF_FRAMES_LOG2);
865         cm->active_ref_idx[i] = cm->ref_frame_map[ref];
866         cm->ref_frame_sign_bias[LAST_FRAME + i] = vp9_rb_read_bit(rb);
867       }
868
869       setup_frame_size_with_refs(pbi, rb);
870
871       xd->allow_high_precision_mv = vp9_rb_read_bit(rb);
872       cm->mcomp_filter_type = read_interp_filter_type(rb);
873
874       for (i = 0; i < ALLOWED_REFS_PER_FRAME; ++i)
875         vp9_setup_scale_factors(cm, i);
876
877       setup_inter_inter(cm);
878     }
879   }
880
881   if (!cm->error_resilient_mode) {
882     cm->refresh_frame_context = vp9_rb_read_bit(rb);
883     cm->frame_parallel_decoding_mode = vp9_rb_read_bit(rb);
884   } else {
885     cm->refresh_frame_context = 0;
886     cm->frame_parallel_decoding_mode = 1;
887   }
888
889   cm->frame_context_idx = vp9_rb_read_literal(rb, NUM_FRAME_CONTEXTS_LOG2);
890
891   if (cm->frame_type == KEY_FRAME || cm->error_resilient_mode || cm->intra_only)
892     vp9_setup_past_independence(cm, xd);
893
894   setup_loopfilter(&cm->lf, rb);
895   setup_quantization(pbi, rb);
896   setup_segmentation(&xd->seg, rb);
897
898   setup_tile_info(cm, rb);
899
900   return vp9_rb_read_literal(rb, 16);
901 }
902
903 static int read_compressed_header(VP9D_COMP *pbi, const uint8_t *data,
904                                   size_t partition_size) {
905   VP9_COMMON *const cm = &pbi->common;
906   MACROBLOCKD *const xd = &pbi->mb;
907   vp9_reader r;
908
909   if (vp9_reader_init(&r, data, partition_size))
910     vpx_internal_error(&cm->error, VPX_CODEC_MEM_ERROR,
911                        "Failed to allocate bool decoder 0");
912
913   cm->tx_mode = xd->lossless ? ONLY_4X4 : read_tx_mode(&r);
914   if (cm->tx_mode == TX_MODE_SELECT)
915     read_tx_probs(&cm->fc.tx_probs, &r);
916   read_coef_probs(&cm->fc, cm->tx_mode, &r);
917
918   vp9_prepare_read_mode_info(pbi, &r);
919
920   return vp9_reader_has_error(&r);
921 }
922
923 void vp9_init_dequantizer(VP9_COMMON *cm) {
924   int q;
925
926   for (q = 0; q < QINDEX_RANGE; q++) {
927     cm->y_dequant[q][0] = vp9_dc_quant(q, cm->y_dc_delta_q);
928     cm->y_dequant[q][1] = vp9_ac_quant(q, 0);
929
930     cm->uv_dequant[q][0] = vp9_dc_quant(q, cm->uv_dc_delta_q);
931     cm->uv_dequant[q][1] = vp9_ac_quant(q, cm->uv_ac_delta_q);
932   }
933 }
934
935 int vp9_decode_frame(VP9D_COMP *pbi, const uint8_t **p_data_end) {
936   int i;
937   VP9_COMMON *const pc = &pbi->common;
938   MACROBLOCKD *const xd = &pbi->mb;
939
940   const uint8_t *data = pbi->source;
941   const uint8_t *data_end = pbi->source + pbi->source_sz;
942
943   struct vp9_read_bit_buffer rb = { data, data_end, 0,
944                                     pc, error_handler };
945   const size_t first_partition_size = read_uncompressed_header(pbi, &rb);
946   const int keyframe = pc->frame_type == KEY_FRAME;
947   YV12_BUFFER_CONFIG *new_fb = &pc->yv12_fb[pc->new_fb_idx];
948
949   if (!first_partition_size) {
950     // showing a frame directly
951     *p_data_end = data + 1;
952     return 0;
953   }
954   data += vp9_rb_bytes_read(&rb);
955   xd->corrupted = 0;
956   new_fb->corrupted = 0;
957   pbi->do_loopfilter_inline =
958       (pc->log2_tile_rows | pc->log2_tile_cols) == 0 && pc->lf.filter_level;
959
960   if (!pbi->decoded_key_frame && !keyframe)
961     return -1;
962
963   if (!read_is_valid(data, first_partition_size, data_end))
964     vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME,
965                        "Truncated packet or corrupt header length");
966
967   xd->mode_info_context = pc->mi;
968   xd->prev_mode_info_context = pc->prev_mi;
969   xd->mode_info_stride = pc->mode_info_stride;
970
971   init_dequantizer(pc, &pbi->mb);
972
973   if (!keyframe)
974     vp9_setup_interp_filters(xd, pc->mcomp_filter_type, pc);
975
976   pc->fc = pc->frame_contexts[pc->frame_context_idx];
977
978   vp9_zero(pc->counts);
979
980   // Initialize xd pointers. Any reference should do for xd->pre, so use 0.
981   setup_pre_planes(xd, 0, &pc->yv12_fb[pc->active_ref_idx[0]], 0, 0, NULL);
982   setup_dst_planes(xd, new_fb, 0, 0);
983
984   new_fb->corrupted |= read_compressed_header(pbi, data, first_partition_size);
985
986   // Create the segmentation map structure and set to 0
987   if (!pc->last_frame_seg_map)
988     CHECK_MEM_ERROR(pc, pc->last_frame_seg_map,
989                     vpx_calloc((pc->mi_rows * pc->mi_cols), 1));
990
991   setup_block_dptrs(xd, pc->subsampling_x, pc->subsampling_y);
992
993   // clear out the coeff buffer
994   for (i = 0; i < MAX_MB_PLANE; ++i)
995     vp9_zero(xd->plane[i].qcoeff);
996
997   set_prev_mi(pc);
998
999   *p_data_end = decode_tiles(pbi, data + first_partition_size);
1000
1001   pc->last_width = pc->width;
1002   pc->last_height = pc->height;
1003
1004   new_fb->corrupted |= xd->corrupted;
1005
1006   if (!pbi->decoded_key_frame) {
1007     if (keyframe && !new_fb->corrupted)
1008       pbi->decoded_key_frame = 1;
1009     else
1010       vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME,
1011                          "A stream must start with a complete key frame");
1012   }
1013
1014   if (!pc->error_resilient_mode && !pc->frame_parallel_decoding_mode) {
1015     vp9_adapt_coef_probs(pc);
1016
1017     if (!keyframe && !pc->intra_only) {
1018       vp9_adapt_mode_probs(pc);
1019       vp9_adapt_mv_probs(pc, xd->allow_high_precision_mv);
1020     }
1021   }
1022
1023   if (pc->refresh_frame_context)
1024     pc->frame_contexts[pc->frame_context_idx] = pc->fc;
1025
1026   return 0;
1027 }