fix vp8_ namespace issues
[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 "vpx_config.h"
13 #include "vpx_rtcd.h"
14 #include "onyxd_int.h"
15 #include "vp8/common/header.h"
16 #include "vp8/common/reconintra4x4.h"
17 #include "vp8/common/reconinter.h"
18 #include "detokenize.h"
19 #include "vp8/common/invtrans.h"
20 #include "vp8/common/alloccommon.h"
21 #include "vp8/common/entropymode.h"
22 #include "vp8/common/quant_common.h"
23 #include "vpx_scale/vpxscale.h"
24 #include "vp8/common/setupintrarecon.h"
25
26 #include "decodemv.h"
27 #include "vp8/common/extend.h"
28 #if CONFIG_ERROR_CONCEALMENT
29 #include "error_concealment.h"
30 #endif
31 #include "vpx_mem/vpx_mem.h"
32 #include "vp8/common/threading.h"
33 #include "decoderthreading.h"
34 #include "dboolhuff.h"
35
36 #include <assert.h>
37 #include <stdio.h>
38
39 void vp8cx_init_de_quantizer(VP8D_COMP *pbi)
40 {
41     int Q;
42     VP8_COMMON *const pc = & pbi->common;
43
44     for (Q = 0; Q < QINDEX_RANGE; Q++)
45     {
46         pc->Y1dequant[Q][0] = (short)vp8_dc_quant(Q, pc->y1dc_delta_q);
47         pc->Y2dequant[Q][0] = (short)vp8_dc2quant(Q, pc->y2dc_delta_q);
48         pc->UVdequant[Q][0] = (short)vp8_dc_uv_quant(Q, pc->uvdc_delta_q);
49
50         pc->Y1dequant[Q][1] = (short)vp8_ac_yquant(Q);
51         pc->Y2dequant[Q][1] = (short)vp8_ac2quant(Q, pc->y2ac_delta_q);
52         pc->UVdequant[Q][1] = (short)vp8_ac_uv_quant(Q, pc->uvac_delta_q);
53     }
54 }
55
56 void vp8_mb_init_dequantizer(VP8D_COMP *pbi, MACROBLOCKD *xd)
57 {
58     int i;
59     int QIndex;
60     MB_MODE_INFO *mbmi = &xd->mode_info_context->mbmi;
61     VP8_COMMON *const pc = & pbi->common;
62
63     /* Decide whether to use the default or alternate baseline Q value. */
64     if (xd->segmentation_enabled)
65     {
66         /* Abs Value */
67         if (xd->mb_segement_abs_delta == SEGMENT_ABSDATA)
68             QIndex = xd->segment_feature_data[MB_LVL_ALT_Q][mbmi->segment_id];
69
70         /* Delta Value */
71         else
72         {
73             QIndex = pc->base_qindex + xd->segment_feature_data[MB_LVL_ALT_Q][mbmi->segment_id];
74             QIndex = (QIndex >= 0) ? ((QIndex <= MAXQ) ? QIndex : MAXQ) : 0;    /* Clamp to valid range */
75         }
76     }
77     else
78         QIndex = pc->base_qindex;
79
80     /* Set up the macroblock dequant constants */
81     xd->dequant_y1_dc[0] = 1;
82     xd->dequant_y1[0] = pc->Y1dequant[QIndex][0];
83     xd->dequant_y2[0] = pc->Y2dequant[QIndex][0];
84     xd->dequant_uv[0] = pc->UVdequant[QIndex][0];
85
86     for (i = 1; i < 16; i++)
87     {
88         xd->dequant_y1_dc[i] =
89         xd->dequant_y1[i] = pc->Y1dequant[QIndex][1];
90         xd->dequant_y2[i] = pc->Y2dequant[QIndex][1];
91         xd->dequant_uv[i] = pc->UVdequant[QIndex][1];
92     }
93 }
94
95 static void decode_macroblock(VP8D_COMP *pbi, MACROBLOCKD *xd,
96                               unsigned int mb_idx)
97 {
98     MB_PREDICTION_MODE mode;
99     int i;
100 #if CONFIG_ERROR_CONCEALMENT
101     int corruption_detected = 0;
102 #endif
103
104     if (xd->mode_info_context->mbmi.mb_skip_coeff)
105     {
106         vp8_reset_mb_tokens_context(xd);
107     }
108     else if (!vp8dx_bool_error(xd->current_bc))
109     {
110         int eobtotal;
111         eobtotal = vp8_decode_mb_tokens(pbi, xd);
112
113         /* Special case:  Force the loopfilter to skip when eobtotal is zero */
114         xd->mode_info_context->mbmi.mb_skip_coeff = (eobtotal==0);
115     }
116
117     mode = xd->mode_info_context->mbmi.mode;
118
119     if (xd->segmentation_enabled)
120         vp8_mb_init_dequantizer(pbi, xd);
121
122
123 #if CONFIG_ERROR_CONCEALMENT
124
125     if(pbi->ec_active)
126     {
127         int throw_residual;
128         /* When we have independent partitions we can apply residual even
129          * though other partitions within the frame are corrupt.
130          */
131         throw_residual = (!pbi->independent_partitions &&
132                           pbi->frame_corrupt_residual);
133         throw_residual = (throw_residual || vp8dx_bool_error(xd->current_bc));
134
135         if ((mb_idx >= pbi->mvs_corrupt_from_mb || throw_residual))
136         {
137             /* MB with corrupt residuals or corrupt mode/motion vectors.
138              * Better to use the predictor as reconstruction.
139              */
140             pbi->frame_corrupt_residual = 1;
141             vpx_memset(xd->qcoeff, 0, sizeof(xd->qcoeff));
142             vp8_conceal_corrupt_mb(xd);
143
144
145             corruption_detected = 1;
146
147             /* force idct to be skipped for B_PRED and use the
148              * prediction only for reconstruction
149              * */
150             vpx_memset(xd->eobs, 0, 25);
151         }
152     }
153 #endif
154
155     /* do prediction */
156     if (xd->mode_info_context->mbmi.ref_frame == INTRA_FRAME)
157     {
158         vp8_build_intra_predictors_mbuv_s(xd,
159                                           xd->recon_above[1],
160                                           xd->recon_above[2],
161                                           xd->recon_left[1],
162                                           xd->recon_left[2],
163                                           xd->recon_left_stride[1],
164                                           xd->dst.u_buffer, xd->dst.v_buffer,
165                                           xd->dst.uv_stride);
166
167         if (mode != B_PRED)
168         {
169             vp8_build_intra_predictors_mby_s(xd,
170                                                  xd->recon_above[0],
171                                                  xd->recon_left[0],
172                                                  xd->recon_left_stride[0],
173                                                  xd->dst.y_buffer,
174                                                  xd->dst.y_stride);
175         }
176         else
177         {
178             short *DQC = xd->dequant_y1;
179             int dst_stride = xd->dst.y_stride;
180             unsigned char *base_dst = xd->dst.y_buffer;
181
182             /* clear out residual eob info */
183             if(xd->mode_info_context->mbmi.mb_skip_coeff)
184                 vpx_memset(xd->eobs, 0, 25);
185
186             intra_prediction_down_copy(xd, xd->recon_above[0] + 16);
187
188             for (i = 0; i < 16; i++)
189             {
190                 BLOCKD *b = &xd->block[i];
191                 int b_mode = xd->mode_info_context->bmi[i].as_mode;
192                 unsigned char *yabove;
193                 unsigned char *yleft;
194                 int left_stride;
195                 unsigned char top_left;
196
197                 yabove = base_dst + b->offset - dst_stride;
198                 yleft = base_dst + b->offset - 1;
199                 left_stride = dst_stride;
200                 top_left = yabove[-1];
201
202                 //                vp8_intra4x4_predict (base_dst + b->offset, dst_stride, b_mode,
203                   //                                    base_dst + b->offset, dst_stride );
204                 vp8_intra4x4_predict_d_c(yabove, yleft, left_stride,
205                                        b_mode,
206                                        base_dst + b->offset, dst_stride,
207                                        top_left);
208
209                 if (xd->eobs[i])
210                 {
211                     if (xd->eobs[i] > 1)
212                     {
213                     vp8_dequant_idct_add
214                             (b->qcoeff, DQC,
215                                 base_dst + b->offset, dst_stride);
216                     }
217                     else
218                     {
219                         vp8_dc_only_idct_add
220                             (b->qcoeff[0] * DQC[0],
221                                 base_dst + b->offset, dst_stride,
222                                 base_dst + b->offset, dst_stride);
223                         ((int *)b->qcoeff)[0] = 0;
224                     }
225                 }
226             }
227         }
228     }
229     else
230     {
231         vp8_build_inter_predictors_mb(xd);
232     }
233
234
235 #if CONFIG_ERROR_CONCEALMENT
236     if (corruption_detected)
237     {
238         return;
239     }
240 #endif
241
242     if(!xd->mode_info_context->mbmi.mb_skip_coeff)
243     {
244         /* dequantization and idct */
245         if (mode != B_PRED)
246         {
247             short *DQC = xd->dequant_y1;
248
249             if (mode != SPLITMV)
250             {
251                 BLOCKD *b = &xd->block[24];
252
253                 /* do 2nd order transform on the dc block */
254                 if (xd->eobs[24] > 1)
255                 {
256                     vp8_dequantize_b(b, xd->dequant_y2);
257
258                     vp8_short_inv_walsh4x4(&b->dqcoeff[0],
259                         xd->qcoeff);
260                     ((int *)b->qcoeff)[0] = 0;
261                     ((int *)b->qcoeff)[1] = 0;
262                     ((int *)b->qcoeff)[2] = 0;
263                     ((int *)b->qcoeff)[3] = 0;
264                     ((int *)b->qcoeff)[4] = 0;
265                     ((int *)b->qcoeff)[5] = 0;
266                     ((int *)b->qcoeff)[6] = 0;
267                     ((int *)b->qcoeff)[7] = 0;
268                 }
269                 else
270                 {
271                     b->dqcoeff[0] = b->qcoeff[0] * xd->dequant_y2[0];
272                     vp8_short_inv_walsh4x4_1(&b->dqcoeff[0],
273                         xd->qcoeff);
274                     ((int *)b->qcoeff)[0] = 0;
275                 }
276
277                 /* override the dc dequant constant in order to preserve the
278                  * dc components
279                  */
280                 DQC = xd->dequant_y1_dc;
281             }
282
283             vp8_dequant_idct_add_y_block
284                             (xd->qcoeff, DQC,
285                              xd->dst.y_buffer,
286                              xd->dst.y_stride, xd->eobs);
287         }
288
289         vp8_dequant_idct_add_uv_block
290                         (xd->qcoeff+16*16, xd->dequant_uv,
291                          xd->dst.u_buffer, xd->dst.v_buffer,
292                          xd->dst.uv_stride, xd->eobs+16);
293     }
294 }
295
296 static int get_delta_q(vp8_reader *bc, int prev, int *q_update)
297 {
298     int ret_val = 0;
299
300     if (vp8_read_bit(bc))
301     {
302         ret_val = vp8_read_literal(bc, 4);
303
304         if (vp8_read_bit(bc))
305             ret_val = -ret_val;
306     }
307
308     /* Trigger a quantizer update if the delta-q value has changed */
309     if (ret_val != prev)
310         *q_update = 1;
311
312     return ret_val;
313 }
314
315 #ifdef PACKET_TESTING
316 #include <stdio.h>
317 FILE *vpxlog = 0;
318 #endif
319
320 static void decode_mb_rows(VP8D_COMP *pbi)
321 {
322     VP8_COMMON *const pc = & pbi->common;
323     MACROBLOCKD *const xd  = & pbi->mb;
324
325     int ibc = 0;
326     int num_part = 1 << pc->multi_token_partition;
327
328     int recon_yoffset, recon_uvoffset;
329     int mb_row, mb_col;
330     int mb_idx = 0;
331     int dst_fb_idx = pc->new_fb_idx;
332     int recon_y_stride = pc->yv12_fb[dst_fb_idx].y_stride;
333     int recon_uv_stride = pc->yv12_fb[dst_fb_idx].uv_stride;
334
335     unsigned char *ref_buffer[MAX_REF_FRAMES][3];
336     unsigned char *dst_buffer[3];
337     int i;
338     int ref_fb_index[MAX_REF_FRAMES];
339     int ref_fb_corrupted[MAX_REF_FRAMES];
340
341     ref_fb_corrupted[INTRA_FRAME] = 0;
342
343     ref_fb_index[LAST_FRAME]    = pc->lst_fb_idx;
344     ref_fb_index[GOLDEN_FRAME]  = pc->gld_fb_idx;
345     ref_fb_index[ALTREF_FRAME]  = pc->alt_fb_idx;
346
347     for(i = 1; i < MAX_REF_FRAMES; i++)
348     {
349         ref_buffer[i][0] = pc->yv12_fb[ref_fb_index[i]].y_buffer;
350         ref_buffer[i][1] = pc->yv12_fb[ref_fb_index[i]].u_buffer;
351         ref_buffer[i][2] = pc->yv12_fb[ref_fb_index[i]].v_buffer;
352
353         ref_fb_corrupted[i] = pc->yv12_fb[ref_fb_index[i]].corrupted;
354     }
355
356     dst_buffer[0] = pc->yv12_fb[dst_fb_idx].y_buffer;
357     dst_buffer[1] = pc->yv12_fb[dst_fb_idx].u_buffer;
358     dst_buffer[2] = pc->yv12_fb[dst_fb_idx].v_buffer;
359
360     xd->up_available = 0;
361
362     /* Decode the individual macro block */
363     for (mb_row = 0; mb_row < pc->mb_rows; mb_row++)
364     {
365         if (num_part > 1)
366         {
367             xd->current_bc = & pbi->mbc[ibc];
368             ibc++;
369
370             if (ibc == num_part)
371                 ibc = 0;
372         }
373
374         recon_yoffset = mb_row * recon_y_stride * 16;
375         recon_uvoffset = mb_row * recon_uv_stride * 8;
376
377         /* reset contexts */
378         xd->above_context = pc->above_context;
379         vpx_memset(xd->left_context, 0, sizeof(ENTROPY_CONTEXT_PLANES));
380
381         xd->left_available = 0;
382
383         xd->mb_to_top_edge = -((mb_row * 16)) << 3;
384         xd->mb_to_bottom_edge = ((pc->mb_rows - 1 - mb_row) * 16) << 3;
385
386         xd->recon_above[0] = dst_buffer[0] + recon_yoffset;
387         xd->recon_above[1] = dst_buffer[1] + recon_uvoffset;
388         xd->recon_above[2] = dst_buffer[2] + recon_uvoffset;
389
390         xd->recon_left[0] = xd->recon_above[0] - 1;
391         xd->recon_left[1] = xd->recon_above[1] - 1;
392         xd->recon_left[2] = xd->recon_above[2] - 1;
393
394         xd->recon_above[0] -= xd->dst.y_stride;
395         xd->recon_above[1] -= xd->dst.uv_stride;
396         xd->recon_above[2] -= xd->dst.uv_stride;
397
398         //TODO: move to outside row loop
399         xd->recon_left_stride[0] = xd->dst.y_stride;
400         xd->recon_left_stride[1] = xd->dst.uv_stride;
401
402         for (mb_col = 0; mb_col < pc->mb_cols; mb_col++)
403         {
404             /* Distance of Mb to the various image edges.
405              * These are specified to 8th pel as they are always compared to values
406              * that are in 1/8th pel units
407              */
408             xd->mb_to_left_edge = -((mb_col * 16) << 3);
409             xd->mb_to_right_edge = ((pc->mb_cols - 1 - mb_col) * 16) << 3;
410
411 #if CONFIG_ERROR_CONCEALMENT
412             {
413                 int corrupt_residual = (!pbi->independent_partitions &&
414                                        pbi->frame_corrupt_residual) ||
415                                        vp8dx_bool_error(xd->current_bc);
416                 if (pbi->ec_active &&
417                     xd->mode_info_context->mbmi.ref_frame == INTRA_FRAME &&
418                     corrupt_residual)
419                 {
420                     /* We have an intra block with corrupt coefficients, better to
421                      * conceal with an inter block. Interpolate MVs from neighboring
422                      * MBs.
423                      *
424                      * Note that for the first mb with corrupt residual in a frame,
425                      * we might not discover that before decoding the residual. That
426                      * happens after this check, and therefore no inter concealment
427                      * will be done.
428                      */
429                     vp8_interpolate_motion(xd,
430                                            mb_row, mb_col,
431                                            pc->mb_rows, pc->mb_cols,
432                                            pc->mode_info_stride);
433                 }
434             }
435 #endif
436
437             xd->dst.y_buffer = dst_buffer[0] + recon_yoffset;
438             xd->dst.u_buffer = dst_buffer[1] + recon_uvoffset;
439             xd->dst.v_buffer = dst_buffer[2] + recon_uvoffset;
440
441             xd->pre.y_buffer = ref_buffer[xd->mode_info_context->mbmi.ref_frame][0] + recon_yoffset;
442             xd->pre.u_buffer = ref_buffer[xd->mode_info_context->mbmi.ref_frame][1] + recon_uvoffset;
443             xd->pre.v_buffer = ref_buffer[xd->mode_info_context->mbmi.ref_frame][2] + recon_uvoffset;
444
445             /* propagate errors from reference frames */
446             xd->corrupted |= ref_fb_corrupted[xd->mode_info_context->mbmi.ref_frame];
447
448             decode_macroblock(pbi, xd, mb_idx);
449
450             mb_idx++;
451             xd->left_available = 1;
452
453             /* check if the boolean decoder has suffered an error */
454             xd->corrupted |= vp8dx_bool_error(xd->current_bc);
455
456             xd->recon_above[0] += 16;
457             xd->recon_above[1] += 8;
458             xd->recon_above[2] += 8;
459             xd->recon_left[0] += 16;
460             xd->recon_left[1] += 8;
461             xd->recon_left[2] += 8;
462
463
464             recon_yoffset += 16;
465             recon_uvoffset += 8;
466
467             ++xd->mode_info_context;  /* next mb */
468
469             xd->above_context++;
470
471         }
472
473         /* adjust to the next row of mbs */
474         vp8_extend_mb_row(
475             &pc->yv12_fb[dst_fb_idx],
476             xd->dst.y_buffer + 16, xd->dst.u_buffer + 8, xd->dst.v_buffer + 8
477         );
478
479         ++xd->mode_info_context;      /* skip prediction column */
480         xd->up_available = 1;
481
482     }
483 }
484
485 static unsigned int read_partition_size(const unsigned char *cx_size)
486 {
487     const unsigned int size =
488         cx_size[0] + (cx_size[1] << 8) + (cx_size[2] << 16);
489     return size;
490 }
491
492 static int read_is_valid(const unsigned char *start,
493                          size_t               len,
494                          const unsigned char *end)
495 {
496     return (start + len > start && start + len <= end);
497 }
498
499 static unsigned int read_available_partition_size(
500                                        VP8D_COMP *pbi,
501                                        const unsigned char *token_part_sizes,
502                                        const unsigned char *fragment_start,
503                                        const unsigned char *first_fragment_end,
504                                        const unsigned char *fragment_end,
505                                        int i,
506                                        int num_part)
507 {
508     VP8_COMMON* pc = &pbi->common;
509     const unsigned char *partition_size_ptr = token_part_sizes + i * 3;
510     unsigned int partition_size = 0;
511     ptrdiff_t bytes_left = fragment_end - fragment_start;
512     /* Calculate the length of this partition. The last partition
513      * size is implicit. If the partition size can't be read, then
514      * either use the remaining data in the buffer (for EC mode)
515      * or throw an error.
516      */
517     if (i < num_part - 1)
518     {
519         if (read_is_valid(partition_size_ptr, 3, first_fragment_end))
520             partition_size = read_partition_size(partition_size_ptr);
521         else if (pbi->ec_active)
522             partition_size = bytes_left;
523         else
524             vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME,
525                                "Truncated partition size data");
526     }
527     else
528         partition_size = bytes_left;
529
530     /* Validate the calculated partition length. If the buffer
531      * described by the partition can't be fully read, then restrict
532      * it to the portion that can be (for EC mode) or throw an error.
533      */
534     if (!read_is_valid(fragment_start, partition_size, fragment_end))
535     {
536         if (pbi->ec_active)
537             partition_size = bytes_left;
538         else
539             vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME,
540                                "Truncated packet or corrupt partition "
541                                "%d length", i + 1);
542     }
543     return partition_size;
544 }
545
546
547 static void setup_token_decoder(VP8D_COMP *pbi,
548                                 const unsigned char* token_part_sizes)
549 {
550     vp8_reader *bool_decoder = &pbi->bc2;
551     unsigned int partition_idx;
552     int fragment_idx;
553     int num_token_partitions;
554     const unsigned char *first_fragment_end = pbi->fragments[0] +
555                                           pbi->fragment_sizes[0];
556
557     TOKEN_PARTITION multi_token_partition =
558             (TOKEN_PARTITION)vp8_read_literal(&pbi->bc, 2);
559     if (!vp8dx_bool_error(&pbi->bc))
560         pbi->common.multi_token_partition = multi_token_partition;
561     num_token_partitions = 1 << pbi->common.multi_token_partition;
562     if (num_token_partitions > 1)
563     {
564         CHECK_MEM_ERROR(pbi->mbc, vpx_malloc(num_token_partitions *
565                                              sizeof(vp8_reader)));
566         bool_decoder = pbi->mbc;
567     }
568
569     /* Check for partitions within the fragments and unpack the fragments
570      * so that each fragment pointer points to its corresponding partition. */
571     for (fragment_idx = 0; fragment_idx < pbi->num_fragments; ++fragment_idx)
572     {
573         unsigned int fragment_size = pbi->fragment_sizes[fragment_idx];
574         const unsigned char *fragment_end = pbi->fragments[fragment_idx] +
575                                             fragment_size;
576         /* Special case for handling the first partition since we have already
577          * read its size. */
578         if (fragment_idx == 0)
579         {
580             /* Size of first partition + token partition sizes element */
581             ptrdiff_t ext_first_part_size = token_part_sizes -
582                 pbi->fragments[0] + 3 * (num_token_partitions - 1);
583             fragment_size -= ext_first_part_size;
584             if (fragment_size > 0)
585             {
586                 pbi->fragment_sizes[0] = ext_first_part_size;
587                 /* The fragment contains an additional partition. Move to
588                  * next. */
589                 fragment_idx++;
590                 pbi->fragments[fragment_idx] = pbi->fragments[0] +
591                   pbi->fragment_sizes[0];
592             }
593         }
594         /* Split the chunk into partitions read from the bitstream */
595         while (fragment_size > 0)
596         {
597             ptrdiff_t partition_size = read_available_partition_size(
598                                                  pbi,
599                                                  token_part_sizes,
600                                                  pbi->fragments[fragment_idx],
601                                                  first_fragment_end,
602                                                  fragment_end,
603                                                  fragment_idx - 1,
604                                                  num_token_partitions);
605             pbi->fragment_sizes[fragment_idx] = partition_size;
606             fragment_size -= partition_size;
607             assert(fragment_idx <= num_token_partitions);
608             if (fragment_size > 0)
609             {
610                 /* The fragment contains an additional partition.
611                  * Move to next. */
612                 fragment_idx++;
613                 pbi->fragments[fragment_idx] =
614                     pbi->fragments[fragment_idx - 1] + partition_size;
615             }
616         }
617     }
618
619     pbi->num_fragments = num_token_partitions + 1;
620
621     for (partition_idx = 1; partition_idx < pbi->num_fragments; ++partition_idx)
622     {
623         if (vp8dx_start_decode(bool_decoder,
624                                pbi->fragments[partition_idx],
625                                pbi->fragment_sizes[partition_idx]))
626             vpx_internal_error(&pbi->common.error, VPX_CODEC_MEM_ERROR,
627                                "Failed to allocate bool decoder %d",
628                                partition_idx);
629
630         bool_decoder++;
631     }
632
633 #if CONFIG_MULTITHREAD
634     /* Clamp number of decoder threads */
635     if (pbi->decoding_thread_count > num_token_partitions - 1)
636         pbi->decoding_thread_count = num_token_partitions - 1;
637 #endif
638 }
639
640 static void stop_token_decoder(VP8D_COMP *pbi)
641 {
642     VP8_COMMON *pc = &pbi->common;
643
644     if (pc->multi_token_partition != ONE_PARTITION)
645     {
646         vpx_free(pbi->mbc);
647         pbi->mbc = NULL;
648     }
649 }
650
651 static void init_frame(VP8D_COMP *pbi)
652 {
653     VP8_COMMON *const pc = & pbi->common;
654     MACROBLOCKD *const xd  = & pbi->mb;
655
656     if (pc->frame_type == KEY_FRAME)
657     {
658         /* Various keyframe initializations */
659         vpx_memcpy(pc->fc.mvc, vp8_default_mv_context, sizeof(vp8_default_mv_context));
660
661         vp8_init_mbmode_probs(pc);
662
663         vp8_default_coef_probs(pc);
664         vp8_kf_default_bmode_probs(pc->kf_bmode_prob);
665
666         /* reset the segment feature data to 0 with delta coding (Default state). */
667         vpx_memset(xd->segment_feature_data, 0, sizeof(xd->segment_feature_data));
668         xd->mb_segement_abs_delta = SEGMENT_DELTADATA;
669
670         /* reset the mode ref deltasa for loop filter */
671         vpx_memset(xd->ref_lf_deltas, 0, sizeof(xd->ref_lf_deltas));
672         vpx_memset(xd->mode_lf_deltas, 0, sizeof(xd->mode_lf_deltas));
673
674         /* All buffers are implicitly updated on key frames. */
675         pc->refresh_golden_frame = 1;
676         pc->refresh_alt_ref_frame = 1;
677         pc->copy_buffer_to_gf = 0;
678         pc->copy_buffer_to_arf = 0;
679
680         /* Note that Golden and Altref modes cannot be used on a key frame so
681          * ref_frame_sign_bias[] is undefined and meaningless
682          */
683         pc->ref_frame_sign_bias[GOLDEN_FRAME] = 0;
684         pc->ref_frame_sign_bias[ALTREF_FRAME] = 0;
685     }
686     else
687     {
688         if (!pc->use_bilinear_mc_filter)
689             pc->mcomp_filter_type = SIXTAP;
690         else
691             pc->mcomp_filter_type = BILINEAR;
692
693         /* To enable choice of different interploation filters */
694         if (pc->mcomp_filter_type == SIXTAP)
695         {
696             xd->subpixel_predict        = vp8_sixtap_predict4x4;
697             xd->subpixel_predict8x4     = vp8_sixtap_predict8x4;
698             xd->subpixel_predict8x8     = vp8_sixtap_predict8x8;
699             xd->subpixel_predict16x16   = vp8_sixtap_predict16x16;
700         }
701         else
702         {
703             xd->subpixel_predict        = vp8_bilinear_predict4x4;
704             xd->subpixel_predict8x4     = vp8_bilinear_predict8x4;
705             xd->subpixel_predict8x8     = vp8_bilinear_predict8x8;
706             xd->subpixel_predict16x16   = vp8_bilinear_predict16x16;
707         }
708
709         if (pbi->decoded_key_frame && pbi->ec_enabled && !pbi->ec_active)
710             pbi->ec_active = 1;
711     }
712
713     xd->left_context = &pc->left_context;
714     xd->mode_info_context = pc->mi;
715     xd->frame_type = pc->frame_type;
716     xd->mode_info_context->mbmi.mode = DC_PRED;
717     xd->mode_info_stride = pc->mode_info_stride;
718     xd->corrupted = 0; /* init without corruption */
719
720     xd->fullpixel_mask = 0xffffffff;
721     if(pc->full_pixel)
722         xd->fullpixel_mask = 0xfffffff8;
723
724 }
725
726 int vp8_decode_frame(VP8D_COMP *pbi)
727 {
728     vp8_reader *const bc = & pbi->bc;
729     VP8_COMMON *const pc = & pbi->common;
730     MACROBLOCKD *const xd  = & pbi->mb;
731     const unsigned char *data = pbi->fragments[0];
732     const unsigned char *data_end =  data + pbi->fragment_sizes[0];
733     ptrdiff_t first_partition_length_in_bytes;
734
735     int i, j, k, l;
736     const int *const mb_feature_data_bits = vp8_mb_feature_data_bits;
737     int corrupt_tokens = 0;
738     int prev_independent_partitions = pbi->independent_partitions;
739
740     /* start with no corruption of current frame */
741     xd->corrupted = 0;
742     pc->yv12_fb[pc->new_fb_idx].corrupted = 0;
743
744     if (data_end - data < 3)
745     {
746         if (!pbi->ec_active)
747         {
748             vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME,
749                                "Truncated packet");
750         }
751
752         /* Declare the missing frame as an inter frame since it will
753            be handled as an inter frame when we have estimated its
754            motion vectors. */
755         pc->frame_type = INTER_FRAME;
756         pc->version = 0;
757         pc->show_frame = 1;
758         first_partition_length_in_bytes = 0;
759     }
760     else
761     {
762         pc->frame_type = (FRAME_TYPE)(data[0] & 1);
763         pc->version = (data[0] >> 1) & 7;
764         pc->show_frame = (data[0] >> 4) & 1;
765         first_partition_length_in_bytes =
766             (data[0] | (data[1] << 8) | (data[2] << 16)) >> 5;
767
768         if (!pbi->ec_active && (data + first_partition_length_in_bytes > data_end
769             || data + first_partition_length_in_bytes < data))
770             vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME,
771                                "Truncated packet or corrupt partition 0 length");
772
773         data += 3;
774
775         vp8_setup_version(pc);
776
777         if (pc->frame_type == KEY_FRAME)
778         {
779             const int Width = pc->Width;
780             const int Height = pc->Height;
781
782             /* vet via sync code */
783             /* When error concealment is enabled we should only check the sync
784              * code if we have enough bits available
785              */
786             if (!pbi->ec_active || data + 3 < data_end)
787             {
788                 if (data[0] != 0x9d || data[1] != 0x01 || data[2] != 0x2a)
789                     vpx_internal_error(&pc->error, VPX_CODEC_UNSUP_BITSTREAM,
790                                    "Invalid frame sync code");
791             }
792
793             /* If error concealment is enabled we should only parse the new size
794              * if we have enough data. Otherwise we will end up with the wrong
795              * size.
796              */
797             if (!pbi->ec_active || data + 6 < data_end)
798             {
799                 pc->Width = (data[3] | (data[4] << 8)) & 0x3fff;
800                 pc->horiz_scale = data[4] >> 6;
801                 pc->Height = (data[5] | (data[6] << 8)) & 0x3fff;
802                 pc->vert_scale = data[6] >> 6;
803             }
804             data += 7;
805
806             if (Width != pc->Width  ||  Height != pc->Height)
807             {
808                 int prev_mb_rows = pc->mb_rows;
809
810                 if (pc->Width <= 0)
811                 {
812                     pc->Width = Width;
813                     vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME,
814                                        "Invalid frame width");
815                 }
816
817                 if (pc->Height <= 0)
818                 {
819                     pc->Height = Height;
820                     vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME,
821                                        "Invalid frame height");
822                 }
823
824                 if (vp8_alloc_frame_buffers(pc, pc->Width, pc->Height))
825                     vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR,
826                                        "Failed to allocate frame buffers");
827
828 #if CONFIG_ERROR_CONCEALMENT
829                 pbi->overlaps = NULL;
830                 if (pbi->ec_enabled)
831                 {
832                     if (vp8_alloc_overlap_lists(pbi))
833                         vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR,
834                                            "Failed to allocate overlap lists "
835                                            "for error concealment");
836                 }
837 #endif
838
839 #if CONFIG_MULTITHREAD
840                 if (pbi->b_multithreaded_rd)
841                     vp8mt_alloc_temp_buffers(pbi, pc->Width, prev_mb_rows);
842 #endif
843             }
844         }
845     }
846
847     if ((!pbi->decoded_key_frame && pc->frame_type != KEY_FRAME) ||
848         pc->Width == 0 || pc->Height == 0)
849     {
850         return -1;
851     }
852
853     init_frame(pbi);
854
855     if (vp8dx_start_decode(bc, data, data_end - data))
856         vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR,
857                            "Failed to allocate bool decoder 0");
858     if (pc->frame_type == KEY_FRAME) {
859         pc->clr_type    = (YUV_TYPE)vp8_read_bit(bc);
860         pc->clamp_type  = (CLAMP_TYPE)vp8_read_bit(bc);
861     }
862
863     /* Is segmentation enabled */
864     xd->segmentation_enabled = (unsigned char)vp8_read_bit(bc);
865
866     if (xd->segmentation_enabled)
867     {
868         /* Signal whether or not the segmentation map is being explicitly updated this frame. */
869         xd->update_mb_segmentation_map = (unsigned char)vp8_read_bit(bc);
870         xd->update_mb_segmentation_data = (unsigned char)vp8_read_bit(bc);
871
872         if (xd->update_mb_segmentation_data)
873         {
874             xd->mb_segement_abs_delta = (unsigned char)vp8_read_bit(bc);
875
876             vpx_memset(xd->segment_feature_data, 0, sizeof(xd->segment_feature_data));
877
878             /* For each segmentation feature (Quant and loop filter level) */
879             for (i = 0; i < MB_LVL_MAX; i++)
880             {
881                 for (j = 0; j < MAX_MB_SEGMENTS; j++)
882                 {
883                     /* Frame level data */
884                     if (vp8_read_bit(bc))
885                     {
886                         xd->segment_feature_data[i][j] = (signed char)vp8_read_literal(bc, mb_feature_data_bits[i]);
887
888                         if (vp8_read_bit(bc))
889                             xd->segment_feature_data[i][j] = -xd->segment_feature_data[i][j];
890                     }
891                     else
892                         xd->segment_feature_data[i][j] = 0;
893                 }
894             }
895         }
896
897         if (xd->update_mb_segmentation_map)
898         {
899             /* Which macro block level features are enabled */
900             vpx_memset(xd->mb_segment_tree_probs, 255, sizeof(xd->mb_segment_tree_probs));
901
902             /* Read the probs used to decode the segment id for each macro block. */
903             for (i = 0; i < MB_FEATURE_TREE_PROBS; i++)
904             {
905                 /* If not explicitly set value is defaulted to 255 by memset above */
906                 if (vp8_read_bit(bc))
907                     xd->mb_segment_tree_probs[i] = (vp8_prob)vp8_read_literal(bc, 8);
908             }
909         }
910     }
911     else
912     {
913         /* No segmentation updates on this frame */
914         xd->update_mb_segmentation_map = 0;
915         xd->update_mb_segmentation_data = 0;
916     }
917
918     /* Read the loop filter level and type */
919     pc->filter_type = (LOOPFILTERTYPE) vp8_read_bit(bc);
920     pc->filter_level = vp8_read_literal(bc, 6);
921     pc->sharpness_level = vp8_read_literal(bc, 3);
922
923     /* Read in loop filter deltas applied at the MB level based on mode or ref frame. */
924     xd->mode_ref_lf_delta_update = 0;
925     xd->mode_ref_lf_delta_enabled = (unsigned char)vp8_read_bit(bc);
926
927     if (xd->mode_ref_lf_delta_enabled)
928     {
929         /* Do the deltas need to be updated */
930         xd->mode_ref_lf_delta_update = (unsigned char)vp8_read_bit(bc);
931
932         if (xd->mode_ref_lf_delta_update)
933         {
934             /* Send update */
935             for (i = 0; i < MAX_REF_LF_DELTAS; i++)
936             {
937                 if (vp8_read_bit(bc))
938                 {
939                     /*sign = vp8_read_bit( bc );*/
940                     xd->ref_lf_deltas[i] = (signed char)vp8_read_literal(bc, 6);
941
942                     if (vp8_read_bit(bc))        /* Apply sign */
943                         xd->ref_lf_deltas[i] = xd->ref_lf_deltas[i] * -1;
944                 }
945             }
946
947             /* Send update */
948             for (i = 0; i < MAX_MODE_LF_DELTAS; i++)
949             {
950                 if (vp8_read_bit(bc))
951                 {
952                     /*sign = vp8_read_bit( bc );*/
953                     xd->mode_lf_deltas[i] = (signed char)vp8_read_literal(bc, 6);
954
955                     if (vp8_read_bit(bc))        /* Apply sign */
956                         xd->mode_lf_deltas[i] = xd->mode_lf_deltas[i] * -1;
957                 }
958             }
959         }
960     }
961
962     setup_token_decoder(pbi, data + first_partition_length_in_bytes);
963
964     xd->current_bc = &pbi->bc2;
965
966     /* Read the default quantizers. */
967     {
968         int Q, q_update;
969
970         Q = vp8_read_literal(bc, 7);  /* AC 1st order Q = default */
971         pc->base_qindex = Q;
972         q_update = 0;
973         pc->y1dc_delta_q = get_delta_q(bc, pc->y1dc_delta_q, &q_update);
974         pc->y2dc_delta_q = get_delta_q(bc, pc->y2dc_delta_q, &q_update);
975         pc->y2ac_delta_q = get_delta_q(bc, pc->y2ac_delta_q, &q_update);
976         pc->uvdc_delta_q = get_delta_q(bc, pc->uvdc_delta_q, &q_update);
977         pc->uvac_delta_q = get_delta_q(bc, pc->uvac_delta_q, &q_update);
978
979         if (q_update)
980             vp8cx_init_de_quantizer(pbi);
981
982         /* MB level dequantizer setup */
983         vp8_mb_init_dequantizer(pbi, &pbi->mb);
984     }
985
986     /* Determine if the golden frame or ARF buffer should be updated and how.
987      * For all non key frames the GF and ARF refresh flags and sign bias
988      * flags must be set explicitly.
989      */
990     if (pc->frame_type != KEY_FRAME)
991     {
992         /* Should the GF or ARF be updated from the current frame */
993         pc->refresh_golden_frame = vp8_read_bit(bc);
994 #if CONFIG_ERROR_CONCEALMENT
995         /* Assume we shouldn't refresh golden if the bit is missing */
996         xd->corrupted |= vp8dx_bool_error(bc);
997         if (pbi->ec_active && xd->corrupted)
998             pc->refresh_golden_frame = 0;
999 #endif
1000
1001         pc->refresh_alt_ref_frame = vp8_read_bit(bc);
1002 #if CONFIG_ERROR_CONCEALMENT
1003         /* Assume we shouldn't refresh altref if the bit is missing */
1004         xd->corrupted |= vp8dx_bool_error(bc);
1005         if (pbi->ec_active && xd->corrupted)
1006             pc->refresh_alt_ref_frame = 0;
1007 #endif
1008
1009         /* Buffer to buffer copy flags. */
1010         pc->copy_buffer_to_gf = 0;
1011
1012         if (!pc->refresh_golden_frame)
1013             pc->copy_buffer_to_gf = vp8_read_literal(bc, 2);
1014
1015 #if CONFIG_ERROR_CONCEALMENT
1016         /* Assume we shouldn't copy to the golden if the bit is missing */
1017         xd->corrupted |= vp8dx_bool_error(bc);
1018         if (pbi->ec_active && xd->corrupted)
1019             pc->copy_buffer_to_gf = 0;
1020 #endif
1021
1022         pc->copy_buffer_to_arf = 0;
1023
1024         if (!pc->refresh_alt_ref_frame)
1025             pc->copy_buffer_to_arf = vp8_read_literal(bc, 2);
1026
1027 #if CONFIG_ERROR_CONCEALMENT
1028         /* Assume we shouldn't copy to the alt-ref if the bit is missing */
1029         xd->corrupted |= vp8dx_bool_error(bc);
1030         if (pbi->ec_active && xd->corrupted)
1031             pc->copy_buffer_to_arf = 0;
1032 #endif
1033
1034
1035         pc->ref_frame_sign_bias[GOLDEN_FRAME] = vp8_read_bit(bc);
1036         pc->ref_frame_sign_bias[ALTREF_FRAME] = vp8_read_bit(bc);
1037     }
1038
1039     pc->refresh_entropy_probs = vp8_read_bit(bc);
1040 #if CONFIG_ERROR_CONCEALMENT
1041     /* Assume we shouldn't refresh the probabilities if the bit is
1042      * missing */
1043     xd->corrupted |= vp8dx_bool_error(bc);
1044     if (pbi->ec_active && xd->corrupted)
1045         pc->refresh_entropy_probs = 0;
1046 #endif
1047     if (pc->refresh_entropy_probs == 0)
1048     {
1049         vpx_memcpy(&pc->lfc, &pc->fc, sizeof(pc->fc));
1050     }
1051
1052     pc->refresh_last_frame = pc->frame_type == KEY_FRAME  ||  vp8_read_bit(bc);
1053
1054 #if CONFIG_ERROR_CONCEALMENT
1055     /* Assume we should refresh the last frame if the bit is missing */
1056     xd->corrupted |= vp8dx_bool_error(bc);
1057     if (pbi->ec_active && xd->corrupted)
1058         pc->refresh_last_frame = 1;
1059 #endif
1060
1061     if (0)
1062     {
1063         FILE *z = fopen("decodestats.stt", "a");
1064         fprintf(z, "%6d F:%d,G:%d,A:%d,L:%d,Q:%d\n",
1065                 pc->current_video_frame,
1066                 pc->frame_type,
1067                 pc->refresh_golden_frame,
1068                 pc->refresh_alt_ref_frame,
1069                 pc->refresh_last_frame,
1070                 pc->base_qindex);
1071         fclose(z);
1072     }
1073
1074     {
1075         pbi->independent_partitions = 1;
1076
1077         /* read coef probability tree */
1078         for (i = 0; i < BLOCK_TYPES; i++)
1079             for (j = 0; j < COEF_BANDS; j++)
1080                 for (k = 0; k < PREV_COEF_CONTEXTS; k++)
1081                     for (l = 0; l < ENTROPY_NODES; l++)
1082                     {
1083
1084                         vp8_prob *const p = pc->fc.coef_probs [i][j][k] + l;
1085
1086                         if (vp8_read(bc, vp8_coef_update_probs [i][j][k][l]))
1087                         {
1088                             *p = (vp8_prob)vp8_read_literal(bc, 8);
1089
1090                         }
1091                         if (k > 0 && *p != pc->fc.coef_probs[i][j][k-1][l])
1092                             pbi->independent_partitions = 0;
1093
1094                     }
1095     }
1096
1097     vpx_memcpy(&xd->pre, &pc->yv12_fb[pc->lst_fb_idx], sizeof(YV12_BUFFER_CONFIG));
1098     vpx_memcpy(&xd->dst, &pc->yv12_fb[pc->new_fb_idx], sizeof(YV12_BUFFER_CONFIG));
1099
1100     /* set up frame new frame for intra coded blocks */
1101 #if CONFIG_MULTITHREAD
1102     if (!(pbi->b_multithreaded_rd) || pc->multi_token_partition == ONE_PARTITION || !(pc->filter_level))
1103 #endif
1104         vp8_setup_intra_recon(&pc->yv12_fb[pc->new_fb_idx]);
1105
1106     vp8_setup_block_dptrs(xd);
1107
1108     vp8_build_block_doffsets(xd);
1109
1110     /* clear out the coeff buffer */
1111     vpx_memset(xd->qcoeff, 0, sizeof(xd->qcoeff));
1112
1113     /* Read the mb_no_coeff_skip flag */
1114     pc->mb_no_coeff_skip = (int)vp8_read_bit(bc);
1115
1116
1117     vp8_decode_mode_mvs(pbi);
1118
1119 #if CONFIG_ERROR_CONCEALMENT
1120     if (pbi->ec_active &&
1121             pbi->mvs_corrupt_from_mb < (unsigned int)pc->mb_cols * pc->mb_rows)
1122     {
1123         /* Motion vectors are missing in this frame. We will try to estimate
1124          * them and then continue decoding the frame as usual */
1125         vp8_estimate_missing_mvs(pbi);
1126     }
1127 #endif
1128
1129     vpx_memset(pc->above_context, 0, sizeof(ENTROPY_CONTEXT_PLANES) * pc->mb_cols);
1130     pbi->frame_corrupt_residual = 0;
1131
1132 #if CONFIG_MULTITHREAD
1133     if (pbi->b_multithreaded_rd && pc->multi_token_partition != ONE_PARTITION)
1134     {
1135         int i;
1136         vp8mt_decode_mb_rows(pbi, xd);
1137         vp8_yv12_extend_frame_borders(&pc->yv12_fb[pc->new_fb_idx]);    /*cm->frame_to_show);*/
1138         for (i = 0; i < pbi->decoding_thread_count; ++i)
1139             corrupt_tokens |= pbi->mb_row_di[i].mbd.corrupted;
1140     }
1141     else
1142 #endif
1143     {
1144         decode_mb_rows(pbi);
1145         corrupt_tokens |= xd->corrupted;
1146     }
1147
1148     stop_token_decoder(pbi);
1149
1150     /* Collect information about decoder corruption. */
1151     /* 1. Check first boolean decoder for errors. */
1152     pc->yv12_fb[pc->new_fb_idx].corrupted = vp8dx_bool_error(bc);
1153     /* 2. Check the macroblock information */
1154     pc->yv12_fb[pc->new_fb_idx].corrupted |= corrupt_tokens;
1155
1156     if (!pbi->decoded_key_frame)
1157     {
1158         if (pc->frame_type == KEY_FRAME &&
1159             !pc->yv12_fb[pc->new_fb_idx].corrupted)
1160             pbi->decoded_key_frame = 1;
1161         else
1162             vpx_internal_error(&pbi->common.error, VPX_CODEC_CORRUPT_FRAME,
1163                                "A stream must start with a complete key frame");
1164     }
1165
1166     /* vpx_log("Decoder: Frame Decoded, Size Roughly:%d bytes  \n",bc->pos+pbi->bc2.pos); */
1167
1168     /* If this was a kf or Gf note the Q used */
1169     if ((pc->frame_type == KEY_FRAME) ||
1170          pc->refresh_golden_frame || pc->refresh_alt_ref_frame)
1171     {
1172         pc->last_kf_gf_q = pc->base_qindex;
1173     }
1174
1175     if (pc->refresh_entropy_probs == 0)
1176     {
1177         vpx_memcpy(&pc->fc, &pc->lfc, sizeof(pc->fc));
1178         pbi->independent_partitions = prev_independent_partitions;
1179     }
1180
1181 #ifdef PACKET_TESTING
1182     {
1183         FILE *f = fopen("decompressor.VP8", "ab");
1184         unsigned int size = pbi->bc2.pos + pbi->bc.pos + 8;
1185         fwrite((void *) &size, 4, 1, f);
1186         fwrite((void *) pbi->Source, size, 1, f);
1187         fclose(f);
1188     }
1189 #endif
1190
1191     return 0;
1192 }