a300bb5fd84e59e700047248a6860170da31e359
[profile/ivi/libvpx.git] / vp8 / decoder / decodframe.c
1 /*
2  *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10
11
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 #if CONFIG_ERROR_CONCEALMENT
31 #include "error_concealment.h"
32 #endif
33 #include "vpx_mem/vpx_mem.h"
34 #include "vp8/common/idct.h"
35 #include "dequantize.h"
36 #include "vp8/common/threading.h"
37 #include "decoderthreading.h"
38 #include "dboolhuff.h"
39
40 #include <assert.h>
41 #include <stdio.h>
42
43 void vp8cx_init_de_quantizer(VP8D_COMP *pbi)
44 {
45     int i;
46     int Q;
47     VP8_COMMON *const pc = & pbi->common;
48
49     for (Q = 0; Q < QINDEX_RANGE; Q++)
50     {
51         pc->Y1dequant[Q][0] = (short)vp8_dc_quant(Q, pc->y1dc_delta_q);
52         pc->Y2dequant[Q][0] = (short)vp8_dc2quant(Q, pc->y2dc_delta_q);
53         pc->UVdequant[Q][0] = (short)vp8_dc_uv_quant(Q, pc->uvdc_delta_q);
54
55         /* all the ac values = ; */
56         for (i = 1; i < 16; i++)
57         {
58             int rc = vp8_default_zig_zag1d[i];
59
60             pc->Y1dequant[Q][rc] = (short)vp8_ac_yquant(Q);
61             pc->Y2dequant[Q][rc] = (short)vp8_ac2quant(Q, pc->y2ac_delta_q);
62             pc->UVdequant[Q][rc] = (short)vp8_ac_uv_quant(Q, pc->uvac_delta_q);
63         }
64     }
65 }
66
67 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  */
115 static void skip_recon_mb(VP8D_COMP *pbi, MACROBLOCKD *xd)
116 {
117     if (xd->mode_info_context->mbmi.ref_frame == INTRA_FRAME)
118     {
119         RECON_INVOKE(&pbi->common.rtcd.recon, build_intra_predictors_mbuv_s)(xd);
120         RECON_INVOKE(&pbi->common.rtcd.recon,
121                      build_intra_predictors_mby_s)(xd);
122     }
123     else
124     {
125         vp8_build_inter16x16_predictors_mb(xd, xd->dst.y_buffer,
126                                            xd->dst.u_buffer, xd->dst.v_buffer,
127                                            xd->dst.y_stride, xd->dst.uv_stride);
128     }
129 }
130
131 static void clamp_mv_to_umv_border(MV *mv, const MACROBLOCKD *xd)
132 {
133     /* If the MV points so far into the UMV border that no visible pixels
134      * are used for reconstruction, the subpel part of the MV can be
135      * discarded and the MV limited to 16 pixels with equivalent results.
136      *
137      * This limit kicks in at 19 pixels for the top and left edges, for
138      * the 16 pixels plus 3 taps right of the central pixel when subpel
139      * filtering. The bottom and right edges use 16 pixels plus 2 pixels
140      * left of the central pixel when filtering.
141      */
142     if (mv->col < (xd->mb_to_left_edge - (19 << 3)))
143         mv->col = xd->mb_to_left_edge - (16 << 3);
144     else if (mv->col > xd->mb_to_right_edge + (18 << 3))
145         mv->col = xd->mb_to_right_edge + (16 << 3);
146
147     if (mv->row < (xd->mb_to_top_edge - (19 << 3)))
148         mv->row = xd->mb_to_top_edge - (16 << 3);
149     else if (mv->row > xd->mb_to_bottom_edge + (18 << 3))
150         mv->row = xd->mb_to_bottom_edge + (16 << 3);
151 }
152
153 /* A version of the above function for chroma block MVs.*/
154 static void clamp_uvmv_to_umv_border(MV *mv, const MACROBLOCKD *xd)
155 {
156     mv->col = (2*mv->col < (xd->mb_to_left_edge - (19 << 3))) ? (xd->mb_to_left_edge - (16 << 3)) >> 1 : mv->col;
157     mv->col = (2*mv->col > xd->mb_to_right_edge + (18 << 3)) ? (xd->mb_to_right_edge + (16 << 3)) >> 1 : mv->col;
158
159     mv->row = (2*mv->row < (xd->mb_to_top_edge - (19 << 3))) ? (xd->mb_to_top_edge - (16 << 3)) >> 1 : mv->row;
160     mv->row = (2*mv->row > xd->mb_to_bottom_edge + (18 << 3)) ? (xd->mb_to_bottom_edge + (16 << 3)) >> 1 : mv->row;
161 }
162
163 void clamp_mvs(MACROBLOCKD *xd)
164 {
165     if (xd->mode_info_context->mbmi.mode == SPLITMV)
166     {
167         int i;
168
169         for (i=0; i<16; i++)
170             clamp_mv_to_umv_border(&xd->block[i].bmi.mv.as_mv, xd);
171         for (i=16; i<24; i++)
172             clamp_uvmv_to_umv_border(&xd->block[i].bmi.mv.as_mv, xd);
173     }
174     else
175     {
176         clamp_mv_to_umv_border(&xd->mode_info_context->mbmi.mv.as_mv, xd);
177         clamp_uvmv_to_umv_border(&xd->block[16].bmi.mv.as_mv, xd);
178     }
179
180 }
181
182 static void decode_macroblock(VP8D_COMP *pbi, MACROBLOCKD *xd,
183                               unsigned int mb_idx)
184 {
185     int eobtotal = 0;
186     MB_PREDICTION_MODE mode;
187     int i;
188
189     if (xd->mode_info_context->mbmi.mb_skip_coeff)
190     {
191         vp8_reset_mb_tokens_context(xd);
192     }
193     else
194     {
195         eobtotal = vp8_decode_mb_tokens(pbi, xd);
196     }
197
198     /* Perform temporary clamping of the MV to be used for prediction */
199     if (xd->mode_info_context->mbmi.need_to_clamp_mvs)
200     {
201         clamp_mvs(xd);
202     }
203
204     mode = xd->mode_info_context->mbmi.mode;
205
206     if (eobtotal == 0 && mode != B_PRED && mode != SPLITMV)
207     {
208         /* Special case:  Force the loopfilter to skip when eobtotal and
209          * mb_skip_coeff are zero.
210          * */
211         xd->mode_info_context->mbmi.mb_skip_coeff = 1;
212
213         skip_recon_mb(pbi, xd);
214         return;
215     }
216
217     if (xd->segmentation_enabled)
218         mb_init_dequantizer(pbi, xd);
219
220     /* do prediction */
221     if (xd->mode_info_context->mbmi.ref_frame == INTRA_FRAME)
222     {
223         RECON_INVOKE(&pbi->common.rtcd.recon, build_intra_predictors_mbuv)(xd);
224
225         if (mode != B_PRED)
226         {
227             RECON_INVOKE(&pbi->common.rtcd.recon,
228                          build_intra_predictors_mby)(xd);
229         } else {
230             vp8_intra_prediction_down_copy(xd);
231         }
232     }
233     else
234     {
235         vp8_build_inter_predictors_mb(xd);
236     }
237
238 #if CONFIG_ERROR_CONCEALMENT
239     if (pbi->ec_enabled &&
240         (mb_idx >= pbi->mvs_corrupt_from_mb ||
241         vp8dx_bool_error(xd->current_bc)))
242     {
243         /* MB with corrupt residuals or corrupt mode/motion vectors.
244          * Better to use the predictor as reconstruction.
245          */
246         vpx_memset(xd->qcoeff, 0, sizeof(xd->qcoeff));
247         vp8_conceal_corrupt_mb(xd);
248         return;
249     }
250 #endif
251
252     /* dequantization and idct */
253     if (mode == B_PRED)
254     {
255         for (i = 0; i < 16; i++)
256         {
257             BLOCKD *b = &xd->block[i];
258             RECON_INVOKE(RTCD_VTABLE(recon), intra4x4_predict)
259                           (b, b->bmi.as_mode, b->predictor);
260
261             if (xd->eobs[i] > 1)
262             {
263                 DEQUANT_INVOKE(&pbi->dequant, idct_add)
264                     (b->qcoeff, b->dequant,  b->predictor,
265                     *(b->base_dst) + b->dst, 16, b->dst_stride);
266             }
267             else
268             {
269                 IDCT_INVOKE(RTCD_VTABLE(idct), idct1_scalar_add)
270                     (b->qcoeff[0] * b->dequant[0], b->predictor,
271                     *(b->base_dst) + b->dst, 16, b->dst_stride);
272                 ((int *)b->qcoeff)[0] = 0;
273             }
274         }
275
276     }
277     else if (mode == SPLITMV)
278     {
279         DEQUANT_INVOKE (&pbi->dequant, idct_add_y_block)
280                         (xd->qcoeff, xd->block[0].dequant,
281                          xd->predictor, xd->dst.y_buffer,
282                          xd->dst.y_stride, xd->eobs);
283     }
284     else
285     {
286         BLOCKD *b = &xd->block[24];
287
288         DEQUANT_INVOKE(&pbi->dequant, block)(b);
289
290         /* do 2nd order transform on the dc block */
291         if (xd->eobs[24] > 1)
292         {
293             IDCT_INVOKE(RTCD_VTABLE(idct), iwalsh16)(&b->dqcoeff[0], b->diff);
294             ((int *)b->qcoeff)[0] = 0;
295             ((int *)b->qcoeff)[1] = 0;
296             ((int *)b->qcoeff)[2] = 0;
297             ((int *)b->qcoeff)[3] = 0;
298             ((int *)b->qcoeff)[4] = 0;
299             ((int *)b->qcoeff)[5] = 0;
300             ((int *)b->qcoeff)[6] = 0;
301             ((int *)b->qcoeff)[7] = 0;
302         }
303         else
304         {
305             IDCT_INVOKE(RTCD_VTABLE(idct), iwalsh1)(&b->dqcoeff[0], b->diff);
306             ((int *)b->qcoeff)[0] = 0;
307         }
308
309         DEQUANT_INVOKE (&pbi->dequant, dc_idct_add_y_block)
310                         (xd->qcoeff, xd->block[0].dequant,
311                          xd->predictor, xd->dst.y_buffer,
312                          xd->dst.y_stride, xd->eobs, xd->block[24].diff);
313     }
314
315     DEQUANT_INVOKE (&pbi->dequant, idct_add_uv_block)
316                     (xd->qcoeff+16*16, xd->block[16].dequant,
317                      xd->predictor+16*16, xd->dst.u_buffer, xd->dst.v_buffer,
318                      xd->dst.uv_stride, xd->eobs+16);
319 }
320
321
322 static int get_delta_q(vp8_reader *bc, int prev, int *q_update)
323 {
324     int ret_val = 0;
325
326     if (vp8_read_bit(bc))
327     {
328         ret_val = vp8_read_literal(bc, 4);
329
330         if (vp8_read_bit(bc))
331             ret_val = -ret_val;
332     }
333
334     /* Trigger a quantizer update if the delta-q value has changed */
335     if (ret_val != prev)
336         *q_update = 1;
337
338     return ret_val;
339 }
340
341 #ifdef PACKET_TESTING
342 #include <stdio.h>
343 FILE *vpxlog = 0;
344 #endif
345
346
347
348 static void
349 decode_mb_row(VP8D_COMP *pbi, VP8_COMMON *pc, int mb_row, MACROBLOCKD *xd)
350 {
351     int recon_yoffset, recon_uvoffset;
352     int mb_col;
353     int ref_fb_idx = pc->lst_fb_idx;
354     int dst_fb_idx = pc->new_fb_idx;
355     int recon_y_stride = pc->yv12_fb[ref_fb_idx].y_stride;
356     int recon_uv_stride = pc->yv12_fb[ref_fb_idx].uv_stride;
357
358     vpx_memset(&pc->left_context, 0, sizeof(pc->left_context));
359     recon_yoffset = mb_row * recon_y_stride * 16;
360     recon_uvoffset = mb_row * recon_uv_stride * 8;
361     /* reset above block coeffs */
362
363     xd->above_context = pc->above_context;
364     xd->up_available = (mb_row != 0);
365
366     xd->mb_to_top_edge = -((mb_row * 16)) << 3;
367     xd->mb_to_bottom_edge = ((pc->mb_rows - 1 - mb_row) * 16) << 3;
368
369     for (mb_col = 0; mb_col < pc->mb_cols; mb_col++)
370     {
371         /* Distance of Mb to the various image edges.
372          * These are specified to 8th pel as they are always compared to values
373          * that are in 1/8th pel units
374          */
375         xd->mb_to_left_edge = -((mb_col * 16) << 3);
376         xd->mb_to_right_edge = ((pc->mb_cols - 1 - mb_col) * 16) << 3;
377
378 #if CONFIG_ERROR_CONCEALMENT
379         if (pbi->ec_enabled &&
380             xd->mode_info_context->mbmi.ref_frame == INTRA_FRAME &&
381             vp8dx_bool_error(xd->current_bc))
382         {
383             /* We have an intra block with corrupt coefficients, better to
384              * conceal with an inter block. Interpolate MVs from neighboring MBs
385              *
386              * Note that for the first mb with corrupt residual in a frame,
387              * we might not discover that before decoding the residual. That
388              * happens after this check, and therefore no inter concealment will
389              * be done.
390              */
391             vp8_interpolate_motion(xd,
392                                    mb_row, mb_col,
393                                    pc->mb_rows, pc->mb_cols,
394                                    pc->mode_info_stride);
395         }
396 #endif
397
398         update_blockd_bmi(xd);
399
400         xd->dst.y_buffer = pc->yv12_fb[dst_fb_idx].y_buffer + recon_yoffset;
401         xd->dst.u_buffer = pc->yv12_fb[dst_fb_idx].u_buffer + recon_uvoffset;
402         xd->dst.v_buffer = pc->yv12_fb[dst_fb_idx].v_buffer + recon_uvoffset;
403
404         xd->left_available = (mb_col != 0);
405
406         /* Select the appropriate reference frame for this MB */
407         if (xd->mode_info_context->mbmi.ref_frame == LAST_FRAME)
408             ref_fb_idx = pc->lst_fb_idx;
409         else if (xd->mode_info_context->mbmi.ref_frame == GOLDEN_FRAME)
410             ref_fb_idx = pc->gld_fb_idx;
411         else
412             ref_fb_idx = pc->alt_fb_idx;
413
414         xd->pre.y_buffer = pc->yv12_fb[ref_fb_idx].y_buffer + recon_yoffset;
415         xd->pre.u_buffer = pc->yv12_fb[ref_fb_idx].u_buffer + recon_uvoffset;
416         xd->pre.v_buffer = pc->yv12_fb[ref_fb_idx].v_buffer + recon_uvoffset;
417
418         if (xd->mode_info_context->mbmi.ref_frame != INTRA_FRAME)
419         {
420             /* propagate errors from reference frames */
421             xd->corrupted |= pc->yv12_fb[ref_fb_idx].corrupted;
422         }
423
424         vp8_build_uvmvs(xd, pc->full_pixel);
425
426         /*
427         if(pc->current_video_frame==0 &&mb_col==1 && mb_row==0)
428         pbi->debugoutput =1;
429         else
430         pbi->debugoutput =0;
431         */
432         decode_macroblock(pbi, xd, mb_row * pc->mb_cols  + mb_col);
433
434         /* check if the boolean decoder has suffered an error */
435         xd->corrupted |= vp8dx_bool_error(xd->current_bc);
436
437         recon_yoffset += 16;
438         recon_uvoffset += 8;
439
440         ++xd->mode_info_context;  /* next mb */
441
442         xd->above_context++;
443
444     }
445
446     /* adjust to the next row of mbs */
447     vp8_extend_mb_row(
448         &pc->yv12_fb[dst_fb_idx],
449         xd->dst.y_buffer + 16, xd->dst.u_buffer + 8, xd->dst.v_buffer + 8
450     );
451
452     ++xd->mode_info_context;      /* skip prediction column */
453 }
454
455
456 static unsigned int read_partition_size(const unsigned char *cx_size)
457 {
458     const unsigned int size =
459         cx_size[0] + (cx_size[1] << 8) + (cx_size[2] << 16);
460     return size;
461 }
462
463 static void setup_token_decoder_partition_input(VP8D_COMP *pbi)
464 {
465     vp8_reader *bool_decoder = &pbi->bc2;
466     int part_idx = 1;
467
468     TOKEN_PARTITION multi_token_partition =
469             (TOKEN_PARTITION)vp8_read_literal(&pbi->bc, 2);
470     assert(vp8dx_bool_error(&pbi->bc) ||
471            multi_token_partition == pbi->common.multi_token_partition);
472     if (pbi->num_partitions > 2)
473     {
474         CHECK_MEM_ERROR(pbi->mbc, vpx_malloc((pbi->num_partitions - 1) *
475                                              sizeof(vp8_reader)));
476         bool_decoder = pbi->mbc;
477     }
478
479     for (; part_idx < pbi->num_partitions; ++part_idx)
480     {
481         if (vp8dx_start_decode(bool_decoder,
482                                pbi->partitions[part_idx],
483                                pbi->partition_sizes[part_idx]))
484             vpx_internal_error(&pbi->common.error, VPX_CODEC_MEM_ERROR,
485                                "Failed to allocate bool decoder %d",
486                                part_idx);
487
488         bool_decoder++;
489     }
490
491 #if CONFIG_MULTITHREAD
492     /* Clamp number of decoder threads */
493     if (pbi->decoding_thread_count > pbi->num_partitions - 1)
494         pbi->decoding_thread_count = pbi->num_partitions - 1;
495 #endif
496 }
497
498 static void setup_token_decoder(VP8D_COMP *pbi,
499                                 const unsigned char *cx_data)
500 {
501     int num_part;
502     int i;
503     VP8_COMMON          *pc = &pbi->common;
504     const unsigned char *user_data_end = pbi->Source + pbi->source_sz;
505     vp8_reader          *bool_decoder;
506     const unsigned char *partition;
507
508     /* Parse number of token partitions to use */
509     const TOKEN_PARTITION multi_token_partition =
510             (TOKEN_PARTITION)vp8_read_literal(&pbi->bc, 2);
511     /* Only update the multi_token_partition field if we are sure the value
512      * is correct. */
513     if (!pbi->ec_enabled || !vp8dx_bool_error(&pbi->bc))
514         pc->multi_token_partition = multi_token_partition;
515
516     num_part = 1 << pc->multi_token_partition;
517
518     /* Set up pointers to the first partition */
519     partition = cx_data;
520     bool_decoder = &pbi->bc2;
521
522     if (num_part > 1)
523     {
524         CHECK_MEM_ERROR(pbi->mbc, vpx_malloc(num_part * sizeof(vp8_reader)));
525         bool_decoder = pbi->mbc;
526         partition += 3 * (num_part - 1);
527     }
528
529     for (i = 0; i < num_part; i++)
530     {
531         const unsigned char *partition_size_ptr = cx_data + i * 3;
532         ptrdiff_t            partition_size;
533
534         /* Calculate the length of this partition. The last partition
535          * size is implicit.
536          */
537         if (i < num_part - 1)
538         {
539             partition_size = read_partition_size(partition_size_ptr);
540         }
541         else
542         {
543             partition_size = user_data_end - partition;
544         }
545
546         if (!pbi->ec_enabled && (partition + partition_size > user_data_end
547             || partition + partition_size < partition))
548             vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME,
549                                "Truncated packet or corrupt partition "
550                                "%d length", i + 1);
551
552         if (vp8dx_start_decode(bool_decoder, partition, partition_size))
553             vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR,
554                                "Failed to allocate bool decoder %d", i + 1);
555
556         /* Advance to the next partition */
557         partition += partition_size;
558         bool_decoder++;
559     }
560
561 #if CONFIG_MULTITHREAD
562     /* Clamp number of decoder threads */
563     if (pbi->decoding_thread_count > num_part - 1)
564         pbi->decoding_thread_count = num_part - 1;
565 #endif
566 }
567
568
569 static void stop_token_decoder(VP8D_COMP *pbi)
570 {
571     VP8_COMMON *pc = &pbi->common;
572
573     if (pc->multi_token_partition != ONE_PARTITION)
574     {
575         vpx_free(pbi->mbc);
576         pbi->mbc = NULL;
577     }
578 }
579
580 static void init_frame(VP8D_COMP *pbi)
581 {
582     VP8_COMMON *const pc = & pbi->common;
583     MACROBLOCKD *const xd  = & pbi->mb;
584
585     if (pc->frame_type == KEY_FRAME)
586     {
587         /* Various keyframe initializations */
588         vpx_memcpy(pc->fc.mvc, vp8_default_mv_context, sizeof(vp8_default_mv_context));
589
590         vp8_init_mbmode_probs(pc);
591
592         vp8_default_coef_probs(pc);
593         vp8_kf_default_bmode_probs(pc->kf_bmode_prob);
594
595         /* reset the segment feature data to 0 with delta coding (Default state). */
596         vpx_memset(xd->segment_feature_data, 0, sizeof(xd->segment_feature_data));
597         xd->mb_segement_abs_delta = SEGMENT_DELTADATA;
598
599         /* reset the mode ref deltasa for loop filter */
600         vpx_memset(xd->ref_lf_deltas, 0, sizeof(xd->ref_lf_deltas));
601         vpx_memset(xd->mode_lf_deltas, 0, sizeof(xd->mode_lf_deltas));
602
603         /* All buffers are implicitly updated on key frames. */
604         pc->refresh_golden_frame = 1;
605         pc->refresh_alt_ref_frame = 1;
606         pc->copy_buffer_to_gf = 0;
607         pc->copy_buffer_to_arf = 0;
608
609         /* Note that Golden and Altref modes cannot be used on a key frame so
610          * ref_frame_sign_bias[] is undefined and meaningless
611          */
612         pc->ref_frame_sign_bias[GOLDEN_FRAME] = 0;
613         pc->ref_frame_sign_bias[ALTREF_FRAME] = 0;
614     }
615     else
616     {
617         if (!pc->use_bilinear_mc_filter)
618             pc->mcomp_filter_type = SIXTAP;
619         else
620             pc->mcomp_filter_type = BILINEAR;
621
622         /* To enable choice of different interploation filters */
623         if (pc->mcomp_filter_type == SIXTAP)
624         {
625             xd->subpixel_predict      = SUBPIX_INVOKE(RTCD_VTABLE(subpix), sixtap4x4);
626             xd->subpixel_predict8x4   = SUBPIX_INVOKE(RTCD_VTABLE(subpix), sixtap8x4);
627             xd->subpixel_predict8x8   = SUBPIX_INVOKE(RTCD_VTABLE(subpix), sixtap8x8);
628             xd->subpixel_predict16x16 = SUBPIX_INVOKE(RTCD_VTABLE(subpix), sixtap16x16);
629         }
630         else
631         {
632             xd->subpixel_predict      = SUBPIX_INVOKE(RTCD_VTABLE(subpix), bilinear4x4);
633             xd->subpixel_predict8x4   = SUBPIX_INVOKE(RTCD_VTABLE(subpix), bilinear8x4);
634             xd->subpixel_predict8x8   = SUBPIX_INVOKE(RTCD_VTABLE(subpix), bilinear8x8);
635             xd->subpixel_predict16x16 = SUBPIX_INVOKE(RTCD_VTABLE(subpix), bilinear16x16);
636         }
637     }
638
639     xd->left_context = &pc->left_context;
640     xd->mode_info_context = pc->mi;
641     xd->frame_type = pc->frame_type;
642     xd->mode_info_context->mbmi.mode = DC_PRED;
643     xd->mode_info_stride = pc->mode_info_stride;
644     xd->corrupted = 0; /* init without corruption */
645 }
646
647 int vp8_decode_frame(VP8D_COMP *pbi)
648 {
649     vp8_reader *const bc = & pbi->bc;
650     VP8_COMMON *const pc = & pbi->common;
651     MACROBLOCKD *const xd  = & pbi->mb;
652     const unsigned char *data = (const unsigned char *)pbi->Source;
653     const unsigned char *data_end = data + pbi->source_sz;
654     ptrdiff_t first_partition_length_in_bytes;
655
656     int mb_row;
657     int i, j, k, l;
658     const int *const mb_feature_data_bits = vp8_mb_feature_data_bits;
659
660     if (pbi->input_partition)
661     {
662         data = pbi->partitions[0];
663         data_end =  data + pbi->partition_sizes[0];
664     }
665
666     /* start with no corruption of current frame */
667     xd->corrupted = 0;
668     pc->yv12_fb[pc->new_fb_idx].corrupted = 0;
669
670     if (data_end - data < 3)
671     {
672         if (pbi->ec_enabled)
673         {
674             /* Declare the missing frame as an inter frame since it will
675                be handled as an inter frame when we have estimated its
676                motion vectors. */
677             pc->frame_type = INTER_FRAME;
678             pc->version = 0;
679             pc->show_frame = 1;
680             first_partition_length_in_bytes = 0;
681         }
682         else
683         {
684             vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME,
685                                "Truncated packet");
686         }
687     }
688     else
689     {
690         pc->frame_type = (FRAME_TYPE)(data[0] & 1);
691         pc->version = (data[0] >> 1) & 7;
692         pc->show_frame = (data[0] >> 4) & 1;
693         first_partition_length_in_bytes =
694             (data[0] | (data[1] << 8) | (data[2] << 16)) >> 5;
695         data += 3;
696
697         if (!pbi->ec_enabled && (data + first_partition_length_in_bytes > data_end
698             || data + first_partition_length_in_bytes < data))
699             vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME,
700                                "Truncated packet or corrupt partition 0 length");
701         vp8_setup_version(pc);
702
703         if (pc->frame_type == KEY_FRAME)
704         {
705             const int Width = pc->Width;
706             const int Height = pc->Height;
707
708             /* vet via sync code */
709             /* When error concealment is enabled we should only check the sync
710              * code if we have enough bits available
711              */
712             if (!pbi->ec_enabled || data + 3 < data_end)
713             {
714                 if (data[0] != 0x9d || data[1] != 0x01 || data[2] != 0x2a)
715                     vpx_internal_error(&pc->error, VPX_CODEC_UNSUP_BITSTREAM,
716                                    "Invalid frame sync code");
717             }
718
719             /* If error concealment is enabled we should only parse the new size
720              * if we have enough data. Otherwise we will end up with the wrong
721              * size.
722              */
723             if (!pbi->ec_enabled || data + 6 < data_end)
724             {
725                 pc->Width = (data[3] | (data[4] << 8)) & 0x3fff;
726                 pc->horiz_scale = data[4] >> 6;
727                 pc->Height = (data[5] | (data[6] << 8)) & 0x3fff;
728                 pc->vert_scale = data[6] >> 6;
729             }
730             data += 7;
731
732             if (Width != pc->Width  ||  Height != pc->Height)
733             {
734                 int prev_mb_rows = pc->mb_rows;
735
736                 if (pc->Width <= 0)
737                 {
738                     pc->Width = Width;
739                     vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME,
740                                        "Invalid frame width");
741                 }
742
743                 if (pc->Height <= 0)
744                 {
745                     pc->Height = Height;
746                     vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME,
747                                        "Invalid frame height");
748                 }
749
750                 if (vp8_alloc_frame_buffers(pc, pc->Width, pc->Height))
751                     vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR,
752                                        "Failed to allocate frame buffers");
753
754 #if CONFIG_ERROR_CONCEALMENT
755                 pbi->overlaps = NULL;
756                 if (pbi->ec_enabled)
757                 {
758                     if (vp8_alloc_overlap_lists(pbi))
759                         vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR,
760                                            "Failed to allocate overlap lists "
761                                            "for error concealment");
762                 }
763 #endif
764
765 #if CONFIG_MULTITHREAD
766                 if (pbi->b_multithreaded_rd)
767                     vp8mt_alloc_temp_buffers(pbi, pc->Width, prev_mb_rows);
768 #endif
769             }
770         }
771     }
772
773     if (pc->Width == 0 || pc->Height == 0)
774     {
775         return -1;
776     }
777
778     init_frame(pbi);
779
780     if (vp8dx_start_decode(bc, data, data_end - data))
781         vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR,
782                            "Failed to allocate bool decoder 0");
783     if (pc->frame_type == KEY_FRAME) {
784         pc->clr_type    = (YUV_TYPE)vp8_read_bit(bc);
785         pc->clamp_type  = (CLAMP_TYPE)vp8_read_bit(bc);
786     }
787
788     /* Is segmentation enabled */
789     xd->segmentation_enabled = (unsigned char)vp8_read_bit(bc);
790
791     if (xd->segmentation_enabled)
792     {
793         /* Signal whether or not the segmentation map is being explicitly updated this frame. */
794         xd->update_mb_segmentation_map = (unsigned char)vp8_read_bit(bc);
795         xd->update_mb_segmentation_data = (unsigned char)vp8_read_bit(bc);
796
797         if (xd->update_mb_segmentation_data)
798         {
799             xd->mb_segement_abs_delta = (unsigned char)vp8_read_bit(bc);
800
801             vpx_memset(xd->segment_feature_data, 0, sizeof(xd->segment_feature_data));
802
803             /* For each segmentation feature (Quant and loop filter level) */
804             for (i = 0; i < MB_LVL_MAX; i++)
805             {
806                 for (j = 0; j < MAX_MB_SEGMENTS; j++)
807                 {
808                     /* Frame level data */
809                     if (vp8_read_bit(bc))
810                     {
811                         xd->segment_feature_data[i][j] = (signed char)vp8_read_literal(bc, mb_feature_data_bits[i]);
812
813                         if (vp8_read_bit(bc))
814                             xd->segment_feature_data[i][j] = -xd->segment_feature_data[i][j];
815                     }
816                     else
817                         xd->segment_feature_data[i][j] = 0;
818                 }
819             }
820         }
821
822         if (xd->update_mb_segmentation_map)
823         {
824             /* Which macro block level features are enabled */
825             vpx_memset(xd->mb_segment_tree_probs, 255, sizeof(xd->mb_segment_tree_probs));
826
827             /* Read the probs used to decode the segment id for each macro block. */
828             for (i = 0; i < MB_FEATURE_TREE_PROBS; i++)
829             {
830                 /* If not explicitly set value is defaulted to 255 by memset above */
831                 if (vp8_read_bit(bc))
832                     xd->mb_segment_tree_probs[i] = (vp8_prob)vp8_read_literal(bc, 8);
833             }
834         }
835     }
836
837     /* Read the loop filter level and type */
838     pc->filter_type = (LOOPFILTERTYPE) vp8_read_bit(bc);
839     pc->filter_level = vp8_read_literal(bc, 6);
840     pc->sharpness_level = vp8_read_literal(bc, 3);
841
842     /* Read in loop filter deltas applied at the MB level based on mode or ref frame. */
843     xd->mode_ref_lf_delta_update = 0;
844     xd->mode_ref_lf_delta_enabled = (unsigned char)vp8_read_bit(bc);
845
846     if (xd->mode_ref_lf_delta_enabled)
847     {
848         /* Do the deltas need to be updated */
849         xd->mode_ref_lf_delta_update = (unsigned char)vp8_read_bit(bc);
850
851         if (xd->mode_ref_lf_delta_update)
852         {
853             /* Send update */
854             for (i = 0; i < MAX_REF_LF_DELTAS; i++)
855             {
856                 if (vp8_read_bit(bc))
857                 {
858                     /*sign = vp8_read_bit( bc );*/
859                     xd->ref_lf_deltas[i] = (signed char)vp8_read_literal(bc, 6);
860
861                     if (vp8_read_bit(bc))        /* Apply sign */
862                         xd->ref_lf_deltas[i] = xd->ref_lf_deltas[i] * -1;
863                 }
864             }
865
866             /* Send update */
867             for (i = 0; i < MAX_MODE_LF_DELTAS; i++)
868             {
869                 if (vp8_read_bit(bc))
870                 {
871                     /*sign = vp8_read_bit( bc );*/
872                     xd->mode_lf_deltas[i] = (signed char)vp8_read_literal(bc, 6);
873
874                     if (vp8_read_bit(bc))        /* Apply sign */
875                         xd->mode_lf_deltas[i] = xd->mode_lf_deltas[i] * -1;
876                 }
877             }
878         }
879     }
880
881     if (pbi->input_partition)
882     {
883         setup_token_decoder_partition_input(pbi);
884     }
885     else
886     {
887         setup_token_decoder(pbi, data + first_partition_length_in_bytes);
888     }
889     xd->current_bc = &pbi->bc2;
890
891     /* Read the default quantizers. */
892     {
893         int Q, q_update;
894
895         Q = vp8_read_literal(bc, 7);  /* AC 1st order Q = default */
896         pc->base_qindex = Q;
897         q_update = 0;
898         pc->y1dc_delta_q = get_delta_q(bc, pc->y1dc_delta_q, &q_update);
899         pc->y2dc_delta_q = get_delta_q(bc, pc->y2dc_delta_q, &q_update);
900         pc->y2ac_delta_q = get_delta_q(bc, pc->y2ac_delta_q, &q_update);
901         pc->uvdc_delta_q = get_delta_q(bc, pc->uvdc_delta_q, &q_update);
902         pc->uvac_delta_q = get_delta_q(bc, pc->uvac_delta_q, &q_update);
903
904         if (q_update)
905             vp8cx_init_de_quantizer(pbi);
906
907         /* MB level dequantizer setup */
908         mb_init_dequantizer(pbi, &pbi->mb);
909     }
910
911     /* Determine if the golden frame or ARF buffer should be updated and how.
912      * For all non key frames the GF and ARF refresh flags and sign bias
913      * flags must be set explicitly.
914      */
915     if (pc->frame_type != KEY_FRAME)
916     {
917         /* Should the GF or ARF be updated from the current frame */
918         pc->refresh_golden_frame = vp8_read_bit(bc);
919 #if CONFIG_ERROR_CONCEALMENT
920         /* Assume we shouldn't refresh golden if the bit is missing */
921         xd->corrupted |= vp8dx_bool_error(bc);
922         if (pbi->ec_enabled && xd->corrupted)
923             pc->refresh_golden_frame = 0;
924 #endif
925
926         pc->refresh_alt_ref_frame = vp8_read_bit(bc);
927 #if CONFIG_ERROR_CONCEALMENT
928         /* Assume we shouldn't refresh altref if the bit is missing */
929         xd->corrupted |= vp8dx_bool_error(bc);
930         if (pbi->ec_enabled && xd->corrupted)
931             pc->refresh_alt_ref_frame = 0;
932 #endif
933
934         /* Buffer to buffer copy flags. */
935         pc->copy_buffer_to_gf = 0;
936
937         if (!pc->refresh_golden_frame)
938             pc->copy_buffer_to_gf = vp8_read_literal(bc, 2);
939
940         pc->copy_buffer_to_arf = 0;
941
942         if (!pc->refresh_alt_ref_frame)
943             pc->copy_buffer_to_arf = vp8_read_literal(bc, 2);
944
945         pc->ref_frame_sign_bias[GOLDEN_FRAME] = vp8_read_bit(bc);
946         pc->ref_frame_sign_bias[ALTREF_FRAME] = vp8_read_bit(bc);
947     }
948
949     pc->refresh_entropy_probs = vp8_read_bit(bc);
950     if (pc->refresh_entropy_probs == 0)
951     {
952         vpx_memcpy(&pc->lfc, &pc->fc, sizeof(pc->fc));
953     }
954
955     pc->refresh_last_frame = pc->frame_type == KEY_FRAME  ||  vp8_read_bit(bc);
956
957 #if CONFIG_ERROR_CONCEALMENT
958     /* Assume we should refresh the last frame if the bit is missing */
959     xd->corrupted |= vp8dx_bool_error(bc);
960     if (pbi->ec_enabled && xd->corrupted)
961         pc->refresh_last_frame = 1;
962 #endif
963
964     if (0)
965     {
966         FILE *z = fopen("decodestats.stt", "a");
967         fprintf(z, "%6d F:%d,G:%d,A:%d,L:%d,Q:%d\n",
968                 pc->current_video_frame,
969                 pc->frame_type,
970                 pc->refresh_golden_frame,
971                 pc->refresh_alt_ref_frame,
972                 pc->refresh_last_frame,
973                 pc->base_qindex);
974         fclose(z);
975     }
976
977     {
978         /* read coef probability tree */
979         for (i = 0; i < BLOCK_TYPES; i++)
980             for (j = 0; j < COEF_BANDS; j++)
981                 for (k = 0; k < PREV_COEF_CONTEXTS; k++)
982                     for (l = 0; l < ENTROPY_NODES; l++)
983                     {
984
985                         vp8_prob *const p = pc->fc.coef_probs [i][j][k] + l;
986
987                         if (vp8_read(bc, vp8_coef_update_probs [i][j][k][l]))
988                         {
989                             *p = (vp8_prob)vp8_read_literal(bc, 8);
990
991                         }
992                     }
993     }
994
995     vpx_memcpy(&xd->pre, &pc->yv12_fb[pc->lst_fb_idx], sizeof(YV12_BUFFER_CONFIG));
996     vpx_memcpy(&xd->dst, &pc->yv12_fb[pc->new_fb_idx], sizeof(YV12_BUFFER_CONFIG));
997
998     /* set up frame new frame for intra coded blocks */
999 #if CONFIG_MULTITHREAD
1000     if (!(pbi->b_multithreaded_rd) || pc->multi_token_partition == ONE_PARTITION || !(pc->filter_level))
1001 #endif
1002         vp8_setup_intra_recon(&pc->yv12_fb[pc->new_fb_idx]);
1003
1004     vp8_setup_block_dptrs(xd);
1005
1006     vp8_build_block_doffsets(xd);
1007
1008     /* clear out the coeff buffer */
1009     vpx_memset(xd->qcoeff, 0, sizeof(xd->qcoeff));
1010
1011     /* Read the mb_no_coeff_skip flag */
1012     pc->mb_no_coeff_skip = (int)vp8_read_bit(bc);
1013
1014
1015     vp8_decode_mode_mvs(pbi);
1016
1017 #if CONFIG_ERROR_CONCEALMENT
1018     if (pbi->ec_enabled &&
1019             pbi->mvs_corrupt_from_mb < (unsigned int)pc->mb_cols * pc->mb_rows)
1020     {
1021         /* Motion vectors are missing in this frame. We will try to estimate
1022          * them and then continue decoding the frame as usual */
1023         vp8_estimate_missing_mvs(pbi);
1024     }
1025 #endif
1026
1027     vpx_memset(pc->above_context, 0, sizeof(ENTROPY_CONTEXT_PLANES) * pc->mb_cols);
1028
1029 #if CONFIG_MULTITHREAD
1030     if (pbi->b_multithreaded_rd && pc->multi_token_partition != ONE_PARTITION)
1031     {
1032         vp8mt_decode_mb_rows(pbi, xd);
1033         if(pbi->common.filter_level)
1034         {
1035             /*vp8_mt_loop_filter_frame(pbi);*/ /*cm, &pbi->mb, cm->filter_level);*/
1036
1037             pc->last_frame_type = pc->frame_type;
1038             pc->last_filter_type = pc->filter_type;
1039             pc->last_sharpness_level = pc->sharpness_level;
1040         }
1041         vp8_yv12_extend_frame_borders_ptr(&pc->yv12_fb[pc->new_fb_idx]);    /*cm->frame_to_show);*/
1042     }
1043     else
1044 #endif
1045     {
1046         int ibc = 0;
1047         int num_part = 1 << pc->multi_token_partition;
1048
1049         /* Decode the individual macro block */
1050         for (mb_row = 0; mb_row < pc->mb_rows; mb_row++)
1051         {
1052
1053             if (num_part > 1)
1054             {
1055                 xd->current_bc = & pbi->mbc[ibc];
1056                 ibc++;
1057
1058                 if (ibc == num_part)
1059                     ibc = 0;
1060             }
1061
1062             decode_mb_row(pbi, pc, mb_row, xd);
1063         }
1064     }
1065
1066     stop_token_decoder(pbi);
1067
1068     /* Collect information about decoder corruption. */
1069     /* 1. Check first boolean decoder for errors. */
1070     pc->yv12_fb[pc->new_fb_idx].corrupted =
1071         vp8dx_bool_error(bc);
1072     /* 2. Check the macroblock information */
1073     pc->yv12_fb[pc->new_fb_idx].corrupted |=
1074         xd->corrupted;
1075
1076     /* vpx_log("Decoder: Frame Decoded, Size Roughly:%d bytes  \n",bc->pos+pbi->bc2.pos); */
1077
1078     /* If this was a kf or Gf note the Q used */
1079     if ((pc->frame_type == KEY_FRAME) ||
1080          pc->refresh_golden_frame || pc->refresh_alt_ref_frame)
1081     {
1082         pc->last_kf_gf_q = pc->base_qindex;
1083     }
1084
1085     if (pc->refresh_entropy_probs == 0)
1086     {
1087         vpx_memcpy(&pc->fc, &pc->lfc, sizeof(pc->fc));
1088     }
1089
1090 #ifdef PACKET_TESTING
1091     {
1092         FILE *f = fopen("decompressor.VP8", "ab");
1093         unsigned int size = pbi->bc2.pos + pbi->bc.pos + 8;
1094         fwrite((void *) &size, 4, 1, f);
1095         fwrite((void *) pbi->Source, size, 1, f);
1096         fclose(f);
1097     }
1098 #endif
1099
1100     return 0;
1101 }