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
12#include "onyxd_int.h"
13#include "vp8/common/header.h"
14#include "vp8/common/reconintra.h"
15#include "vp8/common/reconintra4x4.h"
16#include "vp8/common/recon.h"
17#include "vp8/common/reconinter.h"
18#include "dequantize.h"
19#include "detokenize.h"
20#include "vp8/common/invtrans.h"
21#include "vp8/common/alloccommon.h"
22#include "vp8/common/entropymode.h"
23#include "vp8/common/quant_common.h"
24#include "vpx_scale/vpxscale.h"
25#include "vpx_scale/yv12extend.h"
26#include "vp8/common/setupintrarecon.h"
27
28#include "decodemv.h"
29#include "vp8/common/extend.h"
30#include "vpx_mem/vpx_mem.h"
31#include "vp8/common/idct.h"
32#include "dequantize.h"
33#include "vp8/common/threading.h"
34#include "decoderthreading.h"
35#include "dboolhuff.h"
36
37#include <assert.h>
38#include <stdio.h>
39
40void vp8cx_init_de_quantizer(VP8D_COMP *pbi)
41{
42    int i;
43    int Q;
44    VP8_COMMON *const pc = & pbi->common;
45
46    for (Q = 0; Q < QINDEX_RANGE; Q++)
47    {
48        pc->Y1dequant[Q][0] = (short)vp8_dc_quant(Q, pc->y1dc_delta_q);
49        pc->Y2dequant[Q][0] = (short)vp8_dc2quant(Q, pc->y2dc_delta_q);
50        pc->UVdequant[Q][0] = (short)vp8_dc_uv_quant(Q, pc->uvdc_delta_q);
51
52        /* all the ac values = ; */
53        for (i = 1; i < 16; i++)
54        {
55            int rc = vp8_default_zig_zag1d[i];
56
57            pc->Y1dequant[Q][rc] = (short)vp8_ac_yquant(Q);
58            pc->Y2dequant[Q][rc] = (short)vp8_ac2quant(Q, pc->y2ac_delta_q);
59            pc->UVdequant[Q][rc] = (short)vp8_ac_uv_quant(Q, pc->uvac_delta_q);
60        }
61    }
62}
63
64void mb_init_dequantizer(VP8D_COMP *pbi, MACROBLOCKD *xd)
65{
66    int i;
67    int QIndex;
68    MB_MODE_INFO *mbmi = &xd->mode_info_context->mbmi;
69    VP8_COMMON *const pc = & pbi->common;
70
71    /* Decide whether to use the default or alternate baseline Q value. */
72    if (xd->segmentation_enabled)
73    {
74        /* Abs Value */
75        if (xd->mb_segement_abs_delta == SEGMENT_ABSDATA)
76            QIndex = xd->segment_feature_data[MB_LVL_ALT_Q][mbmi->segment_id];
77
78        /* Delta Value */
79        else
80        {
81            QIndex = pc->base_qindex + xd->segment_feature_data[MB_LVL_ALT_Q][mbmi->segment_id];
82            QIndex = (QIndex >= 0) ? ((QIndex <= MAXQ) ? QIndex : MAXQ) : 0;    /* Clamp to valid range */
83        }
84    }
85    else
86        QIndex = pc->base_qindex;
87
88    /* Set up the block level dequant pointers */
89    for (i = 0; i < 16; i++)
90    {
91        xd->block[i].dequant = pc->Y1dequant[QIndex];
92    }
93
94    for (i = 16; i < 24; i++)
95    {
96        xd->block[i].dequant = pc->UVdequant[QIndex];
97    }
98
99    xd->block[24].dequant = pc->Y2dequant[QIndex];
100
101}
102
103#if CONFIG_RUNTIME_CPU_DETECT
104#define RTCD_VTABLE(x) (&(pbi)->common.rtcd.x)
105#else
106#define RTCD_VTABLE(x) NULL
107#endif
108
109/* skip_recon_mb() is Modified: Instead of writing the result to predictor buffer and then copying it
110 *  to dst buffer, we can write the result directly to dst buffer. This eliminates unnecessary copy.
111 */
112static void skip_recon_mb(VP8D_COMP *pbi, MACROBLOCKD *xd)
113{
114    if (xd->frame_type == KEY_FRAME  ||  xd->mode_info_context->mbmi.ref_frame == INTRA_FRAME)
115    {
116
117        vp8_build_intra_predictors_mbuv_s(xd);
118        RECON_INVOKE(&pbi->common.rtcd.recon,
119                     build_intra_predictors_mby_s)(xd);
120    }
121    else
122    {
123        vp8_build_inter_predictors_mb_s(xd);
124    }
125}
126
127static void clamp_mv_to_umv_border(MV *mv, const MACROBLOCKD *xd)
128{
129    /* If the MV points so far into the UMV border that no visible pixels
130     * are used for reconstruction, the subpel part of the MV can be
131     * discarded and the MV limited to 16 pixels with equivalent results.
132     *
133     * This limit kicks in at 19 pixels for the top and left edges, for
134     * the 16 pixels plus 3 taps right of the central pixel when subpel
135     * filtering. The bottom and right edges use 16 pixels plus 2 pixels
136     * left of the central pixel when filtering.
137     */
138    if (mv->col < (xd->mb_to_left_edge - (19 << 3)))
139        mv->col = xd->mb_to_left_edge - (16 << 3);
140    else if (mv->col > xd->mb_to_right_edge + (18 << 3))
141        mv->col = xd->mb_to_right_edge + (16 << 3);
142
143    if (mv->row < (xd->mb_to_top_edge - (19 << 3)))
144        mv->row = xd->mb_to_top_edge - (16 << 3);
145    else if (mv->row > xd->mb_to_bottom_edge + (18 << 3))
146        mv->row = xd->mb_to_bottom_edge + (16 << 3);
147}
148
149/* A version of the above function for chroma block MVs.*/
150static void clamp_uvmv_to_umv_border(MV *mv, const MACROBLOCKD *xd)
151{
152    mv->col = (2*mv->col < (xd->mb_to_left_edge - (19 << 3))) ? (xd->mb_to_left_edge - (16 << 3)) >> 1 : mv->col;
153    mv->col = (2*mv->col > xd->mb_to_right_edge + (18 << 3)) ? (xd->mb_to_right_edge + (16 << 3)) >> 1 : mv->col;
154
155    mv->row = (2*mv->row < (xd->mb_to_top_edge - (19 << 3))) ? (xd->mb_to_top_edge - (16 << 3)) >> 1 : mv->row;
156    mv->row = (2*mv->row > xd->mb_to_bottom_edge + (18 << 3)) ? (xd->mb_to_bottom_edge + (16 << 3)) >> 1 : mv->row;
157}
158
159void clamp_mvs(MACROBLOCKD *xd)
160{
161    if (xd->mode_info_context->mbmi.mode == SPLITMV)
162    {
163        int i;
164
165        for (i=0; i<16; i++)
166            clamp_mv_to_umv_border(&xd->block[i].bmi.mv.as_mv, xd);
167        for (i=16; i<24; i++)
168            clamp_uvmv_to_umv_border(&xd->block[i].bmi.mv.as_mv, xd);
169    }
170    else
171    {
172        clamp_mv_to_umv_border(&xd->mode_info_context->mbmi.mv.as_mv, xd);
173        clamp_uvmv_to_umv_border(&xd->block[16].bmi.mv.as_mv, xd);
174    }
175
176}
177
178static void decode_macroblock(VP8D_COMP *pbi, MACROBLOCKD *xd)
179{
180    int eobtotal = 0;
181    int i, do_clamp = xd->mode_info_context->mbmi.need_to_clamp_mvs;
182
183    if (xd->mode_info_context->mbmi.mb_skip_coeff)
184    {
185        vp8_reset_mb_tokens_context(xd);
186    }
187    else
188    {
189        eobtotal = vp8_decode_mb_tokens(pbi, xd);
190    }
191
192    /* Perform temporary clamping of the MV to be used for prediction */
193    if (do_clamp)
194    {
195        clamp_mvs(xd);
196    }
197
198    xd->mode_info_context->mbmi.dc_diff = 1;
199
200    if (xd->mode_info_context->mbmi.mode != B_PRED && xd->mode_info_context->mbmi.mode != SPLITMV && eobtotal == 0)
201    {
202        xd->mode_info_context->mbmi.dc_diff = 0;
203        skip_recon_mb(pbi, xd);
204        return;
205    }
206
207    if (xd->segmentation_enabled)
208        mb_init_dequantizer(pbi, xd);
209
210    /* do prediction */
211    if (xd->frame_type == KEY_FRAME  ||  xd->mode_info_context->mbmi.ref_frame == INTRA_FRAME)
212    {
213        vp8_build_intra_predictors_mbuv(xd);
214
215        if (xd->mode_info_context->mbmi.mode != B_PRED)
216        {
217            RECON_INVOKE(&pbi->common.rtcd.recon,
218                         build_intra_predictors_mby)(xd);
219        } else {
220            vp8_intra_prediction_down_copy(xd);
221        }
222    }
223    else
224    {
225        vp8_build_inter_predictors_mb(xd);
226    }
227
228    /* dequantization and idct */
229    if (xd->mode_info_context->mbmi.mode != B_PRED && xd->mode_info_context->mbmi.mode != SPLITMV)
230    {
231        BLOCKD *b = &xd->block[24];
232        DEQUANT_INVOKE(&pbi->dequant, block)(b);
233
234        /* do 2nd order transform on the dc block */
235        if (xd->eobs[24] > 1)
236        {
237            IDCT_INVOKE(RTCD_VTABLE(idct), iwalsh16)(&b->dqcoeff[0], b->diff);
238            ((int *)b->qcoeff)[0] = 0;
239            ((int *)b->qcoeff)[1] = 0;
240            ((int *)b->qcoeff)[2] = 0;
241            ((int *)b->qcoeff)[3] = 0;
242            ((int *)b->qcoeff)[4] = 0;
243            ((int *)b->qcoeff)[5] = 0;
244            ((int *)b->qcoeff)[6] = 0;
245            ((int *)b->qcoeff)[7] = 0;
246        }
247        else
248        {
249            IDCT_INVOKE(RTCD_VTABLE(idct), iwalsh1)(&b->dqcoeff[0], b->diff);
250            ((int *)b->qcoeff)[0] = 0;
251        }
252
253        DEQUANT_INVOKE (&pbi->dequant, dc_idct_add_y_block)
254                        (xd->qcoeff, xd->block[0].dequant,
255                         xd->predictor, xd->dst.y_buffer,
256                         xd->dst.y_stride, xd->eobs, xd->block[24].diff);
257    }
258    else if ((xd->frame_type == KEY_FRAME  ||  xd->mode_info_context->mbmi.ref_frame == INTRA_FRAME) && xd->mode_info_context->mbmi.mode == B_PRED)
259    {
260        for (i = 0; i < 16; i++)
261        {
262
263            BLOCKD *b = &xd->block[i];
264            vp8_predict_intra4x4(b, b->bmi.mode, b->predictor);
265
266            if (xd->eobs[i] > 1)
267            {
268                DEQUANT_INVOKE(&pbi->dequant, idct_add)
269                    (b->qcoeff, b->dequant,  b->predictor,
270                    *(b->base_dst) + b->dst, 16, b->dst_stride);
271            }
272            else
273            {
274                IDCT_INVOKE(RTCD_VTABLE(idct), idct1_scalar_add)
275                    (b->qcoeff[0] * b->dequant[0], b->predictor,
276                    *(b->base_dst) + b->dst, 16, b->dst_stride);
277                ((int *)b->qcoeff)[0] = 0;
278            }
279        }
280
281    }
282    else
283    {
284        DEQUANT_INVOKE (&pbi->dequant, idct_add_y_block)
285                        (xd->qcoeff, xd->block[0].dequant,
286                         xd->predictor, xd->dst.y_buffer,
287                         xd->dst.y_stride, xd->eobs);
288    }
289
290    DEQUANT_INVOKE (&pbi->dequant, idct_add_uv_block)
291                    (xd->qcoeff+16*16, xd->block[16].dequant,
292                     xd->predictor+16*16, xd->dst.u_buffer, xd->dst.v_buffer,
293                     xd->dst.uv_stride, xd->eobs+16);
294}
295
296
297static int get_delta_q(vp8_reader *bc, int prev, int *q_update)
298{
299    int ret_val = 0;
300
301    if (vp8_read_bit(bc))
302    {
303        ret_val = vp8_read_literal(bc, 4);
304
305        if (vp8_read_bit(bc))
306            ret_val = -ret_val;
307    }
308
309    /* Trigger a quantizer update if the delta-q value has changed */
310    if (ret_val != prev)
311        *q_update = 1;
312
313    return ret_val;
314}
315
316#ifdef PACKET_TESTING
317#include <stdio.h>
318FILE *vpxlog = 0;
319#endif
320
321
322
323static void
324decode_mb_row(VP8D_COMP *pbi, VP8_COMMON *pc, int mb_row, MACROBLOCKD *xd)
325{
326
327    int i;
328    int recon_yoffset, recon_uvoffset;
329    int mb_col;
330    int ref_fb_idx = pc->lst_fb_idx;
331    int dst_fb_idx = pc->new_fb_idx;
332    int recon_y_stride = pc->yv12_fb[ref_fb_idx].y_stride;
333    int recon_uv_stride = pc->yv12_fb[ref_fb_idx].uv_stride;
334
335    vpx_memset(&pc->left_context, 0, sizeof(pc->left_context));
336    recon_yoffset = mb_row * recon_y_stride * 16;
337    recon_uvoffset = mb_row * recon_uv_stride * 8;
338    /* reset above block coeffs */
339
340    xd->above_context = pc->above_context;
341    xd->up_available = (mb_row != 0);
342
343    xd->mb_to_top_edge = -((mb_row * 16)) << 3;
344    xd->mb_to_bottom_edge = ((pc->mb_rows - 1 - mb_row) * 16) << 3;
345
346    for (mb_col = 0; mb_col < pc->mb_cols; mb_col++)
347    {
348
349        if (xd->mode_info_context->mbmi.mode == SPLITMV || xd->mode_info_context->mbmi.mode == B_PRED)
350        {
351            for (i = 0; i < 16; i++)
352            {
353                BLOCKD *d = &xd->block[i];
354                vpx_memcpy(&d->bmi, &xd->mode_info_context->bmi[i], sizeof(B_MODE_INFO));
355            }
356        }
357
358        /* Distance of Mb to the various image edges.
359         * These are specified to 8th pel as they are always compared to values that are in 1/8th pel units
360         */
361        xd->mb_to_left_edge = -((mb_col * 16) << 3);
362        xd->mb_to_right_edge = ((pc->mb_cols - 1 - mb_col) * 16) << 3;
363
364        xd->dst.y_buffer = pc->yv12_fb[dst_fb_idx].y_buffer + recon_yoffset;
365        xd->dst.u_buffer = pc->yv12_fb[dst_fb_idx].u_buffer + recon_uvoffset;
366        xd->dst.v_buffer = pc->yv12_fb[dst_fb_idx].v_buffer + recon_uvoffset;
367
368        xd->left_available = (mb_col != 0);
369
370        /* Select the appropriate reference frame for this MB */
371        if (xd->mode_info_context->mbmi.ref_frame == LAST_FRAME)
372            ref_fb_idx = pc->lst_fb_idx;
373        else if (xd->mode_info_context->mbmi.ref_frame == GOLDEN_FRAME)
374            ref_fb_idx = pc->gld_fb_idx;
375        else
376            ref_fb_idx = pc->alt_fb_idx;
377
378        xd->pre.y_buffer = pc->yv12_fb[ref_fb_idx].y_buffer + recon_yoffset;
379        xd->pre.u_buffer = pc->yv12_fb[ref_fb_idx].u_buffer + recon_uvoffset;
380        xd->pre.v_buffer = pc->yv12_fb[ref_fb_idx].v_buffer + recon_uvoffset;
381
382        if (xd->mode_info_context->mbmi.ref_frame != INTRA_FRAME)
383        {
384            /* propagate errors from reference frames */
385            xd->corrupted |= pc->yv12_fb[ref_fb_idx].corrupted;
386        }
387
388        vp8_build_uvmvs(xd, pc->full_pixel);
389
390        /*
391        if(pc->current_video_frame==0 &&mb_col==1 && mb_row==0)
392        pbi->debugoutput =1;
393        else
394        pbi->debugoutput =0;
395        */
396        decode_macroblock(pbi, xd);
397
398        /* check if the boolean decoder has suffered an error */
399        xd->corrupted |= vp8dx_bool_error(xd->current_bc);
400
401        recon_yoffset += 16;
402        recon_uvoffset += 8;
403
404        ++xd->mode_info_context;  /* next mb */
405
406        xd->above_context++;
407
408    }
409
410    /* adjust to the next row of mbs */
411    vp8_extend_mb_row(
412        &pc->yv12_fb[dst_fb_idx],
413        xd->dst.y_buffer + 16, xd->dst.u_buffer + 8, xd->dst.v_buffer + 8
414    );
415
416    ++xd->mode_info_context;      /* skip prediction column */
417}
418
419
420static unsigned int read_partition_size(const unsigned char *cx_size)
421{
422    const unsigned int size =
423        cx_size[0] + (cx_size[1] << 8) + (cx_size[2] << 16);
424    return size;
425}
426
427
428static void setup_token_decoder(VP8D_COMP *pbi,
429                                const unsigned char *cx_data)
430{
431    int num_part;
432    int i;
433    VP8_COMMON          *pc = &pbi->common;
434    const unsigned char *user_data_end = pbi->Source + pbi->source_sz;
435    vp8_reader          *bool_decoder;
436    const unsigned char *partition;
437
438    /* Parse number of token partitions to use */
439    pc->multi_token_partition = (TOKEN_PARTITION)vp8_read_literal(&pbi->bc, 2);
440    num_part = 1 << pc->multi_token_partition;
441
442    /* Set up pointers to the first partition */
443    partition = cx_data;
444    bool_decoder = &pbi->bc2;
445
446    if (num_part > 1)
447    {
448        CHECK_MEM_ERROR(pbi->mbc, vpx_malloc(num_part * sizeof(vp8_reader)));
449        bool_decoder = pbi->mbc;
450        partition += 3 * (num_part - 1);
451    }
452
453    for (i = 0; i < num_part; i++)
454    {
455        const unsigned char *partition_size_ptr = cx_data + i * 3;
456        ptrdiff_t            partition_size;
457
458        /* Calculate the length of this partition. The last partition
459         * size is implicit.
460         */
461        if (i < num_part - 1)
462        {
463            partition_size = read_partition_size(partition_size_ptr);
464        }
465        else
466        {
467            partition_size = user_data_end - partition;
468        }
469
470        if (partition + partition_size > user_data_end
471            || partition + partition_size < partition)
472            vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME,
473                               "Truncated packet or corrupt partition "
474                               "%d length", i + 1);
475
476        if (vp8dx_start_decode(bool_decoder, partition, partition_size))
477            vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR,
478                               "Failed to allocate bool decoder %d", i + 1);
479
480        /* Advance to the next partition */
481        partition += partition_size;
482        bool_decoder++;
483    }
484
485#if CONFIG_MULTITHREAD
486    /* Clamp number of decoder threads */
487    if (pbi->decoding_thread_count > num_part - 1)
488        pbi->decoding_thread_count = num_part - 1;
489#endif
490}
491
492
493static void stop_token_decoder(VP8D_COMP *pbi)
494{
495    VP8_COMMON *pc = &pbi->common;
496
497    if (pc->multi_token_partition != ONE_PARTITION)
498        vpx_free(pbi->mbc);
499}
500
501static void init_frame(VP8D_COMP *pbi)
502{
503    VP8_COMMON *const pc = & pbi->common;
504    MACROBLOCKD *const xd  = & pbi->mb;
505
506    if (pc->frame_type == KEY_FRAME)
507    {
508        /* Various keyframe initializations */
509        vpx_memcpy(pc->fc.mvc, vp8_default_mv_context, sizeof(vp8_default_mv_context));
510
511        vp8_init_mbmode_probs(pc);
512
513        vp8_default_coef_probs(pc);
514        vp8_kf_default_bmode_probs(pc->kf_bmode_prob);
515
516        /* reset the segment feature data to 0 with delta coding (Default state). */
517        vpx_memset(xd->segment_feature_data, 0, sizeof(xd->segment_feature_data));
518        xd->mb_segement_abs_delta = SEGMENT_DELTADATA;
519
520        /* reset the mode ref deltasa for loop filter */
521        vpx_memset(xd->ref_lf_deltas, 0, sizeof(xd->ref_lf_deltas));
522        vpx_memset(xd->mode_lf_deltas, 0, sizeof(xd->mode_lf_deltas));
523
524        /* All buffers are implicitly updated on key frames. */
525        pc->refresh_golden_frame = 1;
526        pc->refresh_alt_ref_frame = 1;
527        pc->copy_buffer_to_gf = 0;
528        pc->copy_buffer_to_arf = 0;
529
530        /* Note that Golden and Altref modes cannot be used on a key frame so
531         * ref_frame_sign_bias[] is undefined and meaningless
532         */
533        pc->ref_frame_sign_bias[GOLDEN_FRAME] = 0;
534        pc->ref_frame_sign_bias[ALTREF_FRAME] = 0;
535    }
536    else
537    {
538        if (!pc->use_bilinear_mc_filter)
539            pc->mcomp_filter_type = SIXTAP;
540        else
541            pc->mcomp_filter_type = BILINEAR;
542
543        /* To enable choice of different interploation filters */
544        if (pc->mcomp_filter_type == SIXTAP)
545        {
546            xd->subpixel_predict      = SUBPIX_INVOKE(RTCD_VTABLE(subpix), sixtap4x4);
547            xd->subpixel_predict8x4   = SUBPIX_INVOKE(RTCD_VTABLE(subpix), sixtap8x4);
548            xd->subpixel_predict8x8   = SUBPIX_INVOKE(RTCD_VTABLE(subpix), sixtap8x8);
549            xd->subpixel_predict16x16 = SUBPIX_INVOKE(RTCD_VTABLE(subpix), sixtap16x16);
550        }
551        else
552        {
553            xd->subpixel_predict      = SUBPIX_INVOKE(RTCD_VTABLE(subpix), bilinear4x4);
554            xd->subpixel_predict8x4   = SUBPIX_INVOKE(RTCD_VTABLE(subpix), bilinear8x4);
555            xd->subpixel_predict8x8   = SUBPIX_INVOKE(RTCD_VTABLE(subpix), bilinear8x8);
556            xd->subpixel_predict16x16 = SUBPIX_INVOKE(RTCD_VTABLE(subpix), bilinear16x16);
557        }
558    }
559
560    xd->left_context = &pc->left_context;
561    xd->mode_info_context = pc->mi;
562    xd->frame_type = pc->frame_type;
563    xd->mode_info_context->mbmi.mode = DC_PRED;
564    xd->mode_info_stride = pc->mode_info_stride;
565    xd->corrupted = 0; /* init without corruption */
566}
567
568int vp8_decode_frame(VP8D_COMP *pbi)
569{
570    vp8_reader *const bc = & pbi->bc;
571    VP8_COMMON *const pc = & pbi->common;
572    MACROBLOCKD *const xd  = & pbi->mb;
573    const unsigned char *data = (const unsigned char *)pbi->Source;
574    const unsigned char *const data_end = data + pbi->source_sz;
575    ptrdiff_t first_partition_length_in_bytes;
576
577    int mb_row;
578    int i, j, k, l;
579    const int *const mb_feature_data_bits = vp8_mb_feature_data_bits;
580
581    /* start with no corruption of current frame */
582    xd->corrupted = 0;
583    pc->yv12_fb[pc->new_fb_idx].corrupted = 0;
584
585    if (data_end - data < 3)
586        vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME,
587                           "Truncated packet");
588    pc->frame_type = (FRAME_TYPE)(data[0] & 1);
589    pc->version = (data[0] >> 1) & 7;
590    pc->show_frame = (data[0] >> 4) & 1;
591    first_partition_length_in_bytes =
592        (data[0] | (data[1] << 8) | (data[2] << 16)) >> 5;
593    data += 3;
594
595    if (data + first_partition_length_in_bytes > data_end
596        || data + first_partition_length_in_bytes < data)
597        vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME,
598                           "Truncated packet or corrupt partition 0 length");
599    vp8_setup_version(pc);
600
601    if (pc->frame_type == KEY_FRAME)
602    {
603        const int Width = pc->Width;
604        const int Height = pc->Height;
605
606        /* vet via sync code */
607        if (data[0] != 0x9d || data[1] != 0x01 || data[2] != 0x2a)
608            vpx_internal_error(&pc->error, VPX_CODEC_UNSUP_BITSTREAM,
609                               "Invalid frame sync code");
610
611        pc->Width = (data[3] | (data[4] << 8)) & 0x3fff;
612        pc->horiz_scale = data[4] >> 6;
613        pc->Height = (data[5] | (data[6] << 8)) & 0x3fff;
614        pc->vert_scale = data[6] >> 6;
615        data += 7;
616
617        if (Width != pc->Width  ||  Height != pc->Height)
618        {
619            int prev_mb_rows = pc->mb_rows;
620
621            if (pc->Width <= 0)
622            {
623                pc->Width = Width;
624                vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME,
625                                   "Invalid frame width");
626            }
627
628            if (pc->Height <= 0)
629            {
630                pc->Height = Height;
631                vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME,
632                                   "Invalid frame height");
633            }
634
635            if (vp8_alloc_frame_buffers(pc, pc->Width, pc->Height))
636                vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR,
637                                   "Failed to allocate frame buffers");
638
639#if CONFIG_MULTITHREAD
640            if (pbi->b_multithreaded_rd)
641                vp8mt_alloc_temp_buffers(pbi, pc->Width, prev_mb_rows);
642#endif
643        }
644    }
645
646    if (pc->Width == 0 || pc->Height == 0)
647    {
648        return -1;
649    }
650
651    init_frame(pbi);
652
653    if (vp8dx_start_decode(bc, data, data_end - data))
654        vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR,
655                           "Failed to allocate bool decoder 0");
656    if (pc->frame_type == KEY_FRAME) {
657        pc->clr_type    = (YUV_TYPE)vp8_read_bit(bc);
658        pc->clamp_type  = (CLAMP_TYPE)vp8_read_bit(bc);
659    }
660
661    /* Is segmentation enabled */
662    xd->segmentation_enabled = (unsigned char)vp8_read_bit(bc);
663
664    if (xd->segmentation_enabled)
665    {
666        /* Signal whether or not the segmentation map is being explicitly updated this frame. */
667        xd->update_mb_segmentation_map = (unsigned char)vp8_read_bit(bc);
668        xd->update_mb_segmentation_data = (unsigned char)vp8_read_bit(bc);
669
670        if (xd->update_mb_segmentation_data)
671        {
672            xd->mb_segement_abs_delta = (unsigned char)vp8_read_bit(bc);
673
674            vpx_memset(xd->segment_feature_data, 0, sizeof(xd->segment_feature_data));
675
676            /* For each segmentation feature (Quant and loop filter level) */
677            for (i = 0; i < MB_LVL_MAX; i++)
678            {
679                for (j = 0; j < MAX_MB_SEGMENTS; j++)
680                {
681                    /* Frame level data */
682                    if (vp8_read_bit(bc))
683                    {
684                        xd->segment_feature_data[i][j] = (signed char)vp8_read_literal(bc, mb_feature_data_bits[i]);
685
686                        if (vp8_read_bit(bc))
687                            xd->segment_feature_data[i][j] = -xd->segment_feature_data[i][j];
688                    }
689                    else
690                        xd->segment_feature_data[i][j] = 0;
691                }
692            }
693        }
694
695        if (xd->update_mb_segmentation_map)
696        {
697            /* Which macro block level features are enabled */
698            vpx_memset(xd->mb_segment_tree_probs, 255, sizeof(xd->mb_segment_tree_probs));
699
700            /* Read the probs used to decode the segment id for each macro block. */
701            for (i = 0; i < MB_FEATURE_TREE_PROBS; i++)
702            {
703                /* If not explicitly set value is defaulted to 255 by memset above */
704                if (vp8_read_bit(bc))
705                    xd->mb_segment_tree_probs[i] = (vp8_prob)vp8_read_literal(bc, 8);
706            }
707        }
708    }
709
710    /* Read the loop filter level and type */
711    pc->filter_type = (LOOPFILTERTYPE) vp8_read_bit(bc);
712    pc->filter_level = vp8_read_literal(bc, 6);
713    pc->sharpness_level = vp8_read_literal(bc, 3);
714
715    /* Read in loop filter deltas applied at the MB level based on mode or ref frame. */
716    xd->mode_ref_lf_delta_update = 0;
717    xd->mode_ref_lf_delta_enabled = (unsigned char)vp8_read_bit(bc);
718
719    if (xd->mode_ref_lf_delta_enabled)
720    {
721        /* Do the deltas need to be updated */
722        xd->mode_ref_lf_delta_update = (unsigned char)vp8_read_bit(bc);
723
724        if (xd->mode_ref_lf_delta_update)
725        {
726            /* Send update */
727            for (i = 0; i < MAX_REF_LF_DELTAS; i++)
728            {
729                if (vp8_read_bit(bc))
730                {
731                    /*sign = vp8_read_bit( bc );*/
732                    xd->ref_lf_deltas[i] = (signed char)vp8_read_literal(bc, 6);
733
734                    if (vp8_read_bit(bc))        /* Apply sign */
735                        xd->ref_lf_deltas[i] = xd->ref_lf_deltas[i] * -1;
736                }
737            }
738
739            /* Send update */
740            for (i = 0; i < MAX_MODE_LF_DELTAS; i++)
741            {
742                if (vp8_read_bit(bc))
743                {
744                    /*sign = vp8_read_bit( bc );*/
745                    xd->mode_lf_deltas[i] = (signed char)vp8_read_literal(bc, 6);
746
747                    if (vp8_read_bit(bc))        /* Apply sign */
748                        xd->mode_lf_deltas[i] = xd->mode_lf_deltas[i] * -1;
749                }
750            }
751        }
752    }
753
754    setup_token_decoder(pbi, data + first_partition_length_in_bytes);
755    xd->current_bc = &pbi->bc2;
756
757    /* Read the default quantizers. */
758    {
759        int Q, q_update;
760
761        Q = vp8_read_literal(bc, 7);  /* AC 1st order Q = default */
762        pc->base_qindex = Q;
763        q_update = 0;
764        pc->y1dc_delta_q = get_delta_q(bc, pc->y1dc_delta_q, &q_update);
765        pc->y2dc_delta_q = get_delta_q(bc, pc->y2dc_delta_q, &q_update);
766        pc->y2ac_delta_q = get_delta_q(bc, pc->y2ac_delta_q, &q_update);
767        pc->uvdc_delta_q = get_delta_q(bc, pc->uvdc_delta_q, &q_update);
768        pc->uvac_delta_q = get_delta_q(bc, pc->uvac_delta_q, &q_update);
769
770        if (q_update)
771            vp8cx_init_de_quantizer(pbi);
772
773        /* MB level dequantizer setup */
774        mb_init_dequantizer(pbi, &pbi->mb);
775    }
776
777    /* Determine if the golden frame or ARF buffer should be updated and how.
778     * For all non key frames the GF and ARF refresh flags and sign bias
779     * flags must be set explicitly.
780     */
781    if (pc->frame_type != KEY_FRAME)
782    {
783        /* Should the GF or ARF be updated from the current frame */
784        pc->refresh_golden_frame = vp8_read_bit(bc);
785        pc->refresh_alt_ref_frame = vp8_read_bit(bc);
786
787        /* Buffer to buffer copy flags. */
788        pc->copy_buffer_to_gf = 0;
789
790        if (!pc->refresh_golden_frame)
791            pc->copy_buffer_to_gf = vp8_read_literal(bc, 2);
792
793        pc->copy_buffer_to_arf = 0;
794
795        if (!pc->refresh_alt_ref_frame)
796            pc->copy_buffer_to_arf = vp8_read_literal(bc, 2);
797
798        pc->ref_frame_sign_bias[GOLDEN_FRAME] = vp8_read_bit(bc);
799        pc->ref_frame_sign_bias[ALTREF_FRAME] = vp8_read_bit(bc);
800    }
801
802    pc->refresh_entropy_probs = vp8_read_bit(bc);
803    if (pc->refresh_entropy_probs == 0)
804    {
805        vpx_memcpy(&pc->lfc, &pc->fc, sizeof(pc->fc));
806    }
807
808    pc->refresh_last_frame = pc->frame_type == KEY_FRAME  ||  vp8_read_bit(bc);
809
810    if (0)
811    {
812        FILE *z = fopen("decodestats.stt", "a");
813        fprintf(z, "%6d F:%d,G:%d,A:%d,L:%d,Q:%d\n",
814                pc->current_video_frame,
815                pc->frame_type,
816                pc->refresh_golden_frame,
817                pc->refresh_alt_ref_frame,
818                pc->refresh_last_frame,
819                pc->base_qindex);
820        fclose(z);
821    }
822
823
824    {
825        /* read coef probability tree */
826
827        for (i = 0; i < BLOCK_TYPES; i++)
828            for (j = 0; j < COEF_BANDS; j++)
829                for (k = 0; k < PREV_COEF_CONTEXTS; k++)
830                    for (l = 0; l < MAX_ENTROPY_TOKENS - 1; l++)
831                    {
832
833                        vp8_prob *const p = pc->fc.coef_probs [i][j][k] + l;
834
835                        if (vp8_read(bc, vp8_coef_update_probs [i][j][k][l]))
836                        {
837                            *p = (vp8_prob)vp8_read_literal(bc, 8);
838
839                        }
840                    }
841    }
842
843    vpx_memcpy(&xd->pre, &pc->yv12_fb[pc->lst_fb_idx], sizeof(YV12_BUFFER_CONFIG));
844    vpx_memcpy(&xd->dst, &pc->yv12_fb[pc->new_fb_idx], sizeof(YV12_BUFFER_CONFIG));
845
846    /* set up frame new frame for intra coded blocks */
847#if CONFIG_MULTITHREAD
848    if (!(pbi->b_multithreaded_rd) || pc->multi_token_partition == ONE_PARTITION || !(pc->filter_level))
849#endif
850        vp8_setup_intra_recon(&pc->yv12_fb[pc->new_fb_idx]);
851
852    vp8_setup_block_dptrs(xd);
853
854    vp8_build_block_doffsets(xd);
855
856    /* clear out the coeff buffer */
857    vpx_memset(xd->qcoeff, 0, sizeof(xd->qcoeff));
858
859    /* Read the mb_no_coeff_skip flag */
860    pc->mb_no_coeff_skip = (int)vp8_read_bit(bc);
861
862
863    vp8_decode_mode_mvs(pbi);
864
865    vpx_memset(pc->above_context, 0, sizeof(ENTROPY_CONTEXT_PLANES) * pc->mb_cols);
866
867    vpx_memcpy(&xd->block[0].bmi, &xd->mode_info_context->bmi[0], sizeof(B_MODE_INFO));
868
869#if CONFIG_MULTITHREAD
870    if (pbi->b_multithreaded_rd && pc->multi_token_partition != ONE_PARTITION)
871    {
872        vp8mt_decode_mb_rows(pbi, xd);
873        if(pbi->common.filter_level)
874        {
875            /*vp8_mt_loop_filter_frame(pbi);*/ /*cm, &pbi->mb, cm->filter_level);*/
876
877            pc->last_frame_type = pc->frame_type;
878            pc->last_filter_type = pc->filter_type;
879            pc->last_sharpness_level = pc->sharpness_level;
880        }
881        vp8_yv12_extend_frame_borders_ptr(&pc->yv12_fb[pc->new_fb_idx]);    /*cm->frame_to_show);*/
882    }
883    else
884#endif
885    {
886        int ibc = 0;
887        int num_part = 1 << pc->multi_token_partition;
888
889        /* Decode the individual macro block */
890        for (mb_row = 0; mb_row < pc->mb_rows; mb_row++)
891        {
892
893            if (num_part > 1)
894            {
895                xd->current_bc = & pbi->mbc[ibc];
896                ibc++;
897
898                if (ibc == num_part)
899                    ibc = 0;
900            }
901
902            decode_mb_row(pbi, pc, mb_row, xd);
903        }
904    }
905
906
907    stop_token_decoder(pbi);
908
909    /* Collect information about decoder corruption. */
910    /* 1. Check first boolean decoder for errors. */
911    pc->yv12_fb[pc->new_fb_idx].corrupted =
912        vp8dx_bool_error(bc);
913    /* 2. Check the macroblock information */
914    pc->yv12_fb[pc->new_fb_idx].corrupted |=
915        xd->corrupted;
916
917    /* vpx_log("Decoder: Frame Decoded, Size Roughly:%d bytes  \n",bc->pos+pbi->bc2.pos); */
918
919    /* If this was a kf or Gf note the Q used */
920    if ((pc->frame_type == KEY_FRAME) ||
921         pc->refresh_golden_frame || pc->refresh_alt_ref_frame)
922    {
923        pc->last_kf_gf_q = pc->base_qindex;
924    }
925
926    if (pc->refresh_entropy_probs == 0)
927    {
928        vpx_memcpy(&pc->fc, &pc->lfc, sizeof(pc->fc));
929    }
930
931#ifdef PACKET_TESTING
932    {
933        FILE *f = fopen("decompressor.VP8", "ab");
934        unsigned int size = pbi->bc2.pos + pbi->bc.pos + 8;
935        fwrite((void *) &size, 4, 1, f);
936        fwrite((void *) pbi->Source, size, 1, f);
937        fclose(f);
938    }
939#endif
940
941    return 0;
942}
943