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