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