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