Home | History | Annotate | Download | only in dec
      1 // Copyright 2010 Google Inc.
      2 //
      3 // This code is licensed under the same terms as WebM:
      4 //  Software License Agreement:  http://www.webmproject.org/license/software/
      5 //  Additional IP Rights Grant:  http://www.webmproject.org/license/additional/
      6 // -----------------------------------------------------------------------------
      7 //
      8 // main entry for the decoder
      9 //
     10 // Author: Skal (pascal.massimino (at) gmail.com)
     11 
     12 #include <stdlib.h>
     13 #include "vp8i.h"
     14 
     15 #if defined(__cplusplus) || defined(c_plusplus)
     16 extern "C" {
     17 #endif
     18 
     19 //-----------------------------------------------------------------------------
     20 
     21 int WebPGetDecoderVersion(void) {
     22   return (DEC_MAJ_VERSION << 16) | (DEC_MIN_VERSION << 8) | DEC_REV_VERSION;
     23 }
     24 
     25 //-----------------------------------------------------------------------------
     26 // VP8Decoder
     27 
     28 static void SetOk(VP8Decoder* const dec) {
     29   dec->status_ = VP8_STATUS_OK;
     30   dec->error_msg_ = "OK";
     31 }
     32 
     33 int VP8InitIoInternal(VP8Io* const io, int version) {
     34   if (version != WEBP_DECODER_ABI_VERSION)
     35     return 0;  // mismatch error
     36   if (io) {
     37     memset(io, 0, sizeof(*io));
     38   }
     39   return 1;
     40 }
     41 
     42 VP8Decoder* VP8New(void) {
     43   VP8Decoder* dec = (VP8Decoder*)calloc(1, sizeof(VP8Decoder));
     44   if (dec) {
     45     SetOk(dec);
     46     dec->ready_ = 0;
     47   }
     48   return dec;
     49 }
     50 
     51 VP8StatusCode VP8Status(VP8Decoder* const dec) {
     52   if (!dec) return VP8_STATUS_INVALID_PARAM;
     53   return dec->status_;
     54 }
     55 
     56 const char* VP8StatusMessage(VP8Decoder* const dec) {
     57   if (!dec) return "no object";
     58   if (!dec->error_msg_) return "OK";
     59   return dec->error_msg_;
     60 }
     61 
     62 void VP8Delete(VP8Decoder* const dec) {
     63   if (dec) {
     64     VP8Clear(dec);
     65     free(dec);
     66   }
     67 }
     68 
     69 int VP8SetError(VP8Decoder* const dec,
     70                 VP8StatusCode error, const char * const msg) {
     71   dec->status_ = error;
     72   dec->error_msg_ = msg;
     73   dec->ready_ = 0;
     74   return 0;
     75 }
     76 
     77 //-----------------------------------------------------------------------------
     78 
     79 int VP8GetInfo(const uint8_t* data,
     80                uint32_t data_size, uint32_t chunk_size,
     81                int* width, int* height, int* has_alpha) {
     82   if (data_size < 10) {
     83     return 0;         // not enough data
     84   }
     85   // check signature
     86   if (data[3] != 0x9d || data[4] != 0x01 || data[5] != 0x2a) {
     87     return 0;         // Wrong signature.
     88   } else {
     89     const uint32_t bits = data[0] | (data[1] << 8) | (data[2] << 16);
     90     const int key_frame = !(bits & 1);
     91     const int w = ((data[7] << 8) | data[6]) & 0x3fff;
     92     const int h = ((data[9] << 8) | data[8]) & 0x3fff;
     93 
     94     if (has_alpha) {
     95 #ifdef WEBP_EXPERIMENTAL_FEATURES
     96       if (data_size < 11) return 0;
     97       *has_alpha = !!(data[10] & 0x80);    // the colorspace_ bit
     98 #else
     99       *has_alpha = 0;
    100 #endif
    101     }
    102     if (!key_frame) {   // Not a keyframe.
    103       return 0;
    104     }
    105 
    106     if (((bits >> 1) & 7) > 3) {
    107       return 0;         // unknown profile
    108     }
    109     if (!((bits >> 4) & 1)) {
    110       return 0;         // first frame is invisible!
    111     }
    112     if (((bits >> 5)) >= chunk_size) {  // partition_length
    113       return 0;         // inconsistent size information.
    114     }
    115 
    116     if (width) {
    117       *width = w;
    118     }
    119     if (height) {
    120       *height = h;
    121     }
    122 
    123     return 1;
    124   }
    125 }
    126 
    127 //-----------------------------------------------------------------------------
    128 // Header parsing
    129 
    130 static void ResetSegmentHeader(VP8SegmentHeader* const hdr) {
    131   assert(hdr);
    132   hdr->use_segment_ = 0;
    133   hdr->update_map_ = 0;
    134   hdr->absolute_delta_ = 1;
    135   memset(hdr->quantizer_, 0, sizeof(hdr->quantizer_));
    136   memset(hdr->filter_strength_, 0, sizeof(hdr->filter_strength_));
    137 }
    138 
    139 // Paragraph 9.3
    140 static int ParseSegmentHeader(VP8BitReader* br,
    141                               VP8SegmentHeader* hdr, VP8Proba* proba) {
    142   assert(br);
    143   assert(hdr);
    144   hdr->use_segment_ = VP8Get(br);
    145   if (hdr->use_segment_) {
    146     hdr->update_map_ = VP8Get(br);
    147     if (VP8Get(br)) {   // update data
    148       int s;
    149       hdr->absolute_delta_ = VP8Get(br);
    150       for (s = 0; s < NUM_MB_SEGMENTS; ++s) {
    151         hdr->quantizer_[s] = VP8Get(br) ? VP8GetSignedValue(br, 7) : 0;
    152       }
    153       for (s = 0; s < NUM_MB_SEGMENTS; ++s) {
    154         hdr->filter_strength_[s] = VP8Get(br) ? VP8GetSignedValue(br, 6) : 0;
    155       }
    156     }
    157     if (hdr->update_map_) {
    158       int s;
    159       for (s = 0; s < MB_FEATURE_TREE_PROBS; ++s) {
    160         proba->segments_[s] = VP8Get(br) ? VP8GetValue(br, 8) : 255u;
    161       }
    162     }
    163   } else {
    164     hdr->update_map_ = 0;
    165   }
    166   return !br->eof_;
    167 }
    168 
    169 // Paragraph 9.5
    170 // This function returns VP8_STATUS_SUSPENDED if we don't have all the
    171 // necessary data in 'buf'.
    172 // This case is not necessarily an error (for incremental decoding).
    173 // Still, no bitreader is ever initialized to make it possible to read
    174 // unavailable memory.
    175 // If we don't even have the partitions' sizes, than VP8_STATUS_NOT_ENOUGH_DATA
    176 // is returned, and this is an unrecoverable error.
    177 // If the partitions were positioned ok, VP8_STATUS_OK is returned.
    178 static VP8StatusCode ParsePartitions(VP8Decoder* const dec,
    179                                      const uint8_t* buf, uint32_t size) {
    180   VP8BitReader* const br = &dec->br_;
    181   const uint8_t* sz = buf;
    182   const uint8_t* buf_end = buf + size;
    183   const uint8_t* part_start;
    184   int last_part;
    185   int p;
    186 
    187   dec->num_parts_ = 1 << VP8GetValue(br, 2);
    188   last_part = dec->num_parts_ - 1;
    189   part_start = buf + last_part * 3;
    190   if (buf_end < part_start) {
    191     // we can't even read the sizes with sz[]! That's a failure.
    192     return VP8_STATUS_NOT_ENOUGH_DATA;
    193   }
    194   for (p = 0; p < last_part; ++p) {
    195     const uint32_t psize = sz[0] | (sz[1] << 8) | (sz[2] << 16);
    196     const uint8_t* part_end = part_start + psize;
    197     if (part_end > buf_end) part_end = buf_end;
    198     VP8InitBitReader(dec->parts_ + p, part_start, part_end);
    199     part_start = part_end;
    200     sz += 3;
    201   }
    202   VP8InitBitReader(dec->parts_ + last_part, part_start, buf_end);
    203   return (part_start < buf_end) ? VP8_STATUS_OK :
    204            VP8_STATUS_SUSPENDED;   // Init is ok, but there's not enough data
    205 }
    206 
    207 // Paragraph 9.4
    208 static int ParseFilterHeader(VP8BitReader* br, VP8Decoder* const dec) {
    209   VP8FilterHeader* const hdr = &dec->filter_hdr_;
    210   hdr->simple_    = VP8Get(br);
    211   hdr->level_     = VP8GetValue(br, 6);
    212   hdr->sharpness_ = VP8GetValue(br, 3);
    213   hdr->use_lf_delta_ = VP8Get(br);
    214   if (hdr->use_lf_delta_) {
    215     if (VP8Get(br)) {   // update lf-delta?
    216       int i;
    217       for (i = 0; i < NUM_REF_LF_DELTAS; ++i) {
    218         if (VP8Get(br)) {
    219           hdr->ref_lf_delta_[i] = VP8GetSignedValue(br, 6);
    220         }
    221       }
    222       for (i = 0; i < NUM_MODE_LF_DELTAS; ++i) {
    223         if (VP8Get(br)) {
    224           hdr->mode_lf_delta_[i] = VP8GetSignedValue(br, 6);
    225         }
    226       }
    227     }
    228   }
    229   dec->filter_type_ = (hdr->level_ == 0) ? 0 : hdr->simple_ ? 1 : 2;
    230   if (dec->filter_type_ > 0) {    // precompute filter levels per segment
    231     if (dec->segment_hdr_.use_segment_) {
    232       int s;
    233       for (s = 0; s < NUM_MB_SEGMENTS; ++s) {
    234         int strength = dec->segment_hdr_.filter_strength_[s];
    235         if (!dec->segment_hdr_.absolute_delta_) {
    236           strength += hdr->level_;
    237         }
    238         dec->filter_levels_[s] = strength;
    239       }
    240     } else {
    241       dec->filter_levels_[0] = hdr->level_;
    242     }
    243   }
    244   return !br->eof_;
    245 }
    246 
    247 static inline uint32_t get_le32(const uint8_t* const data) {
    248   return data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
    249 }
    250 
    251 // Topmost call
    252 int VP8GetHeaders(VP8Decoder* const dec, VP8Io* const io) {
    253   uint8_t* buf;
    254   uint32_t buf_size;
    255   VP8FrameHeader* frm_hdr;
    256   VP8PictureHeader* pic_hdr;
    257   VP8BitReader* br;
    258   VP8StatusCode status;
    259 
    260   if (dec == NULL) {
    261     return 0;
    262   }
    263   SetOk(dec);
    264   if (io == NULL) {
    265     return VP8SetError(dec, VP8_STATUS_INVALID_PARAM,
    266                        "null VP8Io passed to VP8GetHeaders()");
    267   }
    268 
    269   buf = (uint8_t*)io->data;
    270   buf_size = io->data_size;
    271   if (buf == NULL || buf_size <= 4) {
    272     return VP8SetError(dec, VP8_STATUS_NOT_ENOUGH_DATA,
    273                        "Not enough data to parse frame header");
    274   }
    275 
    276   // Skip over valid RIFF headers
    277   if (!memcmp(buf, "RIFF", 4)) {
    278     uint32_t riff_size;
    279     uint32_t chunk_size;
    280     if (buf_size < 20 + 4) {
    281       return VP8SetError(dec, VP8_STATUS_NOT_ENOUGH_DATA,
    282                          "RIFF: Truncated header.");
    283     }
    284     if (memcmp(buf + 8, "WEBP", 4)) {   // wrong image file signature
    285       return VP8SetError(dec, VP8_STATUS_BITSTREAM_ERROR,
    286                          "RIFF: WEBP signature not found.");
    287     }
    288     riff_size = get_le32(buf + 4);
    289     if (riff_size < 12) {
    290       return VP8SetError(dec, VP8_STATUS_NOT_ENOUGH_DATA,
    291                          "RIFF: Truncated header.");
    292     }
    293     if (memcmp(buf + 12, "VP8 ", 4)) {
    294       return VP8SetError(dec, VP8_STATUS_BITSTREAM_ERROR,
    295                          "RIFF: Invalid compression format.");
    296     }
    297     chunk_size = get_le32(buf + 16);
    298     if (chunk_size > riff_size - 12) {
    299       return VP8SetError(dec, VP8_STATUS_BITSTREAM_ERROR,
    300                          "RIFF: Inconsistent size information.");
    301     }
    302     buf += 20;
    303     buf_size -= 20;
    304   }
    305 
    306   // Paragraph 9.1
    307   {
    308     const uint32_t bits = buf[0] | (buf[1] << 8) | (buf[2] << 16);
    309     frm_hdr = &dec->frm_hdr_;
    310     frm_hdr->key_frame_ = !(bits & 1);
    311     frm_hdr->profile_ = (bits >> 1) & 7;
    312     frm_hdr->show_ = (bits >> 4) & 1;
    313     frm_hdr->partition_length_ = (bits >> 5);
    314     if (frm_hdr->profile_ > 3)
    315       return VP8SetError(dec, VP8_STATUS_BITSTREAM_ERROR,
    316                          "Incorrect keyframe parameters.");
    317     if (!frm_hdr->show_)
    318       return VP8SetError(dec, VP8_STATUS_UNSUPPORTED_FEATURE,
    319                          "Frame not displayable.");
    320     buf += 3;
    321     buf_size -= 3;
    322   }
    323 
    324   pic_hdr = &dec->pic_hdr_;
    325   if (frm_hdr->key_frame_) {
    326     // Paragraph 9.2
    327     if (buf_size < 7) {
    328       return VP8SetError(dec, VP8_STATUS_NOT_ENOUGH_DATA,
    329                          "cannot parse picture header");
    330     }
    331     if (buf[0] != 0x9d || buf[1] != 0x01 || buf[2] != 0x2a) {
    332       return VP8SetError(dec, VP8_STATUS_BITSTREAM_ERROR,
    333                          "Bad code word");
    334     }
    335     pic_hdr->width_ = ((buf[4] << 8) | buf[3]) & 0x3fff;
    336     pic_hdr->xscale_ = buf[4] >> 6;   // ratio: 1, 5/4 5/3 or 2
    337     pic_hdr->height_ = ((buf[6] << 8) | buf[5]) & 0x3fff;
    338     pic_hdr->yscale_ = buf[6] >> 6;
    339     buf += 7;
    340     buf_size -= 7;
    341 
    342     dec->mb_w_ = (pic_hdr->width_ + 15) >> 4;
    343     dec->mb_h_ = (pic_hdr->height_ + 15) >> 4;
    344     // Setup default output area (can be later modified during io->setup())
    345     io->width = pic_hdr->width_;
    346     io->height = pic_hdr->height_;
    347     io->use_scaling  = 0;
    348     io->use_cropping = 0;
    349     io->crop_top  = 0;
    350     io->crop_left = 0;
    351     io->crop_right  = io->width;
    352     io->crop_bottom = io->height;
    353     io->mb_w = io->width;   // sanity check
    354     io->mb_h = io->height;  // ditto
    355 
    356     VP8ResetProba(&dec->proba_);
    357     ResetSegmentHeader(&dec->segment_hdr_);
    358     dec->segment_ = 0;    // default for intra
    359   }
    360 
    361   // Check if we have all the partition #0 available, and initialize dec->br_
    362   // to read this partition (and this partition only).
    363   if (frm_hdr->partition_length_ > buf_size) {
    364     return VP8SetError(dec, VP8_STATUS_NOT_ENOUGH_DATA,
    365                        "bad partition length");
    366   }
    367 
    368   dec->alpha_data_ = NULL;
    369   dec->alpha_data_size_ = 0;
    370 
    371   br = &dec->br_;
    372   VP8InitBitReader(br, buf, buf + frm_hdr->partition_length_);
    373   buf += frm_hdr->partition_length_;
    374   buf_size -= frm_hdr->partition_length_;
    375 
    376   if (frm_hdr->key_frame_) {
    377     pic_hdr->colorspace_ = VP8Get(br);
    378     pic_hdr->clamp_type_ = VP8Get(br);
    379   }
    380   if (!ParseSegmentHeader(br, &dec->segment_hdr_, &dec->proba_)) {
    381     return VP8SetError(dec, VP8_STATUS_BITSTREAM_ERROR,
    382                        "cannot parse segment header");
    383   }
    384   // Filter specs
    385   if (!ParseFilterHeader(br, dec)) {
    386     return VP8SetError(dec, VP8_STATUS_BITSTREAM_ERROR,
    387                        "cannot parse filter header");
    388   }
    389   status = ParsePartitions(dec, buf, buf_size);
    390   if (status != VP8_STATUS_OK) {
    391     return VP8SetError(dec, status, "cannot parse partitions");
    392   }
    393 
    394   // quantizer change
    395   VP8ParseQuant(dec);
    396 
    397   // Frame buffer marking
    398   if (!frm_hdr->key_frame_) {
    399     // Paragraph 9.7
    400 #ifndef ONLY_KEYFRAME_CODE
    401     dec->buffer_flags_ = VP8Get(br) << 0;   // update golden
    402     dec->buffer_flags_ |= VP8Get(br) << 1;  // update alt ref
    403     if (!(dec->buffer_flags_ & 1)) {
    404       dec->buffer_flags_ |= VP8GetValue(br, 2) << 2;
    405     }
    406     if (!(dec->buffer_flags_ & 2)) {
    407       dec->buffer_flags_ |= VP8GetValue(br, 2) << 4;
    408     }
    409     dec->buffer_flags_ |= VP8Get(br) << 6;    // sign bias golden
    410     dec->buffer_flags_ |= VP8Get(br) << 7;    // sign bias alt ref
    411 #else
    412     return VP8SetError(dec, VP8_STATUS_UNSUPPORTED_FEATURE,
    413                        "Not a key frame.");
    414 #endif
    415   } else {
    416     dec->buffer_flags_ = 0x003 | 0x100;
    417   }
    418 
    419   // Paragraph 9.8
    420 #ifndef ONLY_KEYFRAME_CODE
    421   dec->update_proba_ = VP8Get(br);
    422   if (!dec->update_proba_) {    // save for later restore
    423     dec->proba_saved_ = dec->proba_;
    424   }
    425   dec->buffer_flags_ &= 1 << 8;
    426   dec->buffer_flags_ |=
    427       (frm_hdr->key_frame_ || VP8Get(br)) << 8;    // refresh last frame
    428 #else
    429   VP8Get(br);   // just ignore the value of update_proba_
    430 #endif
    431 
    432   VP8ParseProba(br, dec);
    433 
    434 #ifdef WEBP_EXPERIMENTAL_FEATURES
    435   // Extensions
    436   if (dec->pic_hdr_.colorspace_) {
    437     const size_t kTrailerSize = 8;
    438     const uint8_t kTrailerMarker = 0x01;
    439     uint8_t* const ext_buf = buf - kTrailerSize;
    440     size_t size;
    441 
    442     if (frm_hdr->partition_length_ < kTrailerSize ||
    443         ext_buf[kTrailerSize - 1] != kTrailerMarker) {
    444  Error:
    445       return VP8SetError(dec, VP8_STATUS_BITSTREAM_ERROR,
    446                          "RIFF: Inconsistent extra information.");
    447     }
    448     // Alpha
    449     size = (ext_buf[4] << 0) | (ext_buf[5] << 8) | (ext_buf[6] << 16);
    450     if (frm_hdr->partition_length_ < size + kTrailerSize) {
    451       goto Error;
    452     }
    453     dec->alpha_data_ = (size > 0) ? ext_buf - size : NULL;
    454     dec->alpha_data_size_ = size;
    455 
    456     // Layer
    457     size = (ext_buf[0] << 0) | (ext_buf[1] << 8) | (ext_buf[2] << 16);
    458     dec->layer_data_size_ = size;
    459     dec->layer_data_ = NULL;  // will be set later
    460     dec->layer_colorspace_ = ext_buf[3];
    461   }
    462 #endif
    463 
    464   // sanitized state
    465   dec->ready_ = 1;
    466   return 1;
    467 }
    468 
    469 //-----------------------------------------------------------------------------
    470 // Residual decoding (Paragraph 13.2 / 13.3)
    471 
    472 static const uint8_t kBands[16 + 1] = {
    473   0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7,
    474   0  // extra entry as sentinel
    475 };
    476 
    477 static const uint8_t kCat3[] = { 173, 148, 140, 0 };
    478 static const uint8_t kCat4[] = { 176, 155, 140, 135, 0 };
    479 static const uint8_t kCat5[] = { 180, 157, 141, 134, 130, 0 };
    480 static const uint8_t kCat6[] =
    481   { 254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129, 0 };
    482 static const uint8_t* const kCat3456[] = { kCat3, kCat4, kCat5, kCat6 };
    483 static const uint8_t kZigzag[16] = {
    484   0, 1, 4, 8,  5, 2, 3, 6,  9, 12, 13, 10,  7, 11, 14, 15
    485 };
    486 
    487 typedef const uint8_t (*ProbaArray)[NUM_CTX][NUM_PROBAS];  // for const-casting
    488 
    489 // Returns the position of the last non-zero coeff plus one
    490 // (and 0 if there's no coeff at all)
    491 static int GetCoeffs(VP8BitReader* const br, ProbaArray prob,
    492                      int ctx, const uint16_t dq[2], int n, int16_t* out) {
    493   const uint8_t* p = prob[kBands[n]][ctx];
    494   if (!VP8GetBit(br, p[0])) {   // first EOB is more a 'CBP' bit.
    495     return 0;
    496   }
    497   while (1) {
    498     ++n;
    499     if (!VP8GetBit(br, p[1])) {
    500       p = prob[kBands[n]][0];
    501     } else {  // non zero coeff
    502       int v, j;
    503       if (!VP8GetBit(br, p[2])) {
    504         p = prob[kBands[n]][1];
    505         v = 1;
    506       } else {
    507         if (!VP8GetBit(br, p[3])) {
    508           if (!VP8GetBit(br, p[4])) {
    509             v = 2;
    510           } else {
    511             v = 3 + VP8GetBit(br, p[5]);
    512           }
    513         } else {
    514           if (!VP8GetBit(br, p[6])) {
    515             if (!VP8GetBit(br, p[7])) {
    516               v = 5 + VP8GetBit(br, 159);
    517             } else {
    518               v = 7 + 2 * VP8GetBit(br, 165);
    519               v += VP8GetBit(br, 145);
    520             }
    521           } else {
    522             const uint8_t* tab;
    523             const int bit1 = VP8GetBit(br, p[8]);
    524             const int bit0 = VP8GetBit(br, p[9 + bit1]);
    525             const int cat = 2 * bit1 + bit0;
    526             v = 0;
    527             for (tab = kCat3456[cat]; *tab; ++tab) {
    528               v += v + VP8GetBit(br, *tab);
    529             }
    530             v += 3 + (8 << cat);
    531           }
    532         }
    533         p = prob[kBands[n]][2];
    534       }
    535       j = kZigzag[n - 1];
    536       out[j] = VP8GetSigned(br, v) * dq[j > 0];
    537       if (n == 16 || !VP8GetBit(br, p[0])) {   // EOB
    538         return n;
    539       }
    540     }
    541     if (n == 16) {
    542       return 16;
    543     }
    544   }
    545 }
    546 
    547 // Alias-safe way of converting 4bytes to 32bits.
    548 typedef union {
    549   uint8_t  i8[4];
    550   uint32_t i32;
    551 } PackedNz;
    552 
    553 // Table to unpack four bits into four bytes
    554 static const PackedNz kUnpackTab[16] = {
    555   {{0, 0, 0, 0}},  {{1, 0, 0, 0}},  {{0, 1, 0, 0}},  {{1, 1, 0, 0}},
    556   {{0, 0, 1, 0}},  {{1, 0, 1, 0}},  {{0, 1, 1, 0}},  {{1, 1, 1, 0}},
    557   {{0, 0, 0, 1}},  {{1, 0, 0, 1}},  {{0, 1, 0, 1}},  {{1, 1, 0, 1}},
    558   {{0, 0, 1, 1}},  {{1, 0, 1, 1}},  {{0, 1, 1, 1}},  {{1, 1, 1, 1}} };
    559 
    560 // Macro to pack four LSB of four bytes into four bits.
    561 #if defined(__PPC__) || defined(_M_PPC) || defined(_ARCH_PPC) || \
    562     defined(__BIG_ENDIAN__)
    563 #define PACK_CST 0x08040201U
    564 #else
    565 #define PACK_CST 0x01020408U
    566 #endif
    567 #define PACK(X, S) ((((X).i32 * PACK_CST) & 0xff000000) >> (S))
    568 
    569 static void ParseResiduals(VP8Decoder* const dec,
    570                            VP8MB* const mb, VP8BitReader* const token_br) {
    571   int out_t_nz, out_l_nz, first;
    572   ProbaArray ac_prob;
    573   const VP8QuantMatrix* q = &dec->dqm_[dec->segment_];
    574   int16_t* dst = dec->coeffs_;
    575   VP8MB* const left_mb = dec->mb_info_ - 1;
    576   PackedNz nz_ac, nz_dc;
    577   PackedNz tnz, lnz;
    578   uint32_t non_zero_ac = 0;
    579   uint32_t non_zero_dc = 0;
    580   int x, y, ch;
    581 
    582   memset(dst, 0, 384 * sizeof(*dst));
    583   if (!dec->is_i4x4_) {    // parse DC
    584     int16_t dc[16] = { 0 };
    585     const int ctx = mb->dc_nz_ + left_mb->dc_nz_;
    586     mb->dc_nz_ = left_mb->dc_nz_ =
    587         (GetCoeffs(token_br, (ProbaArray)dec->proba_.coeffs_[1],
    588                    ctx, q->y2_mat_, 0, dc) > 0);
    589     first = 1;
    590     ac_prob = (ProbaArray)dec->proba_.coeffs_[0];
    591     VP8TransformWHT(dc, dst);
    592   } else {
    593     first = 0;
    594     ac_prob = (ProbaArray)dec->proba_.coeffs_[3];
    595   }
    596 
    597   tnz = kUnpackTab[mb->nz_ & 0xf];
    598   lnz = kUnpackTab[left_mb->nz_ & 0xf];
    599   for (y = 0; y < 4; ++y) {
    600     int l = lnz.i8[y];
    601     for (x = 0; x < 4; ++x) {
    602       const int ctx = l + tnz.i8[x];
    603       const int nz = GetCoeffs(token_br, ac_prob, ctx,
    604                                q->y1_mat_, first, dst);
    605       tnz.i8[x] = l = (nz > 0);
    606       nz_dc.i8[x] = (dst[0] != 0);
    607       nz_ac.i8[x] = (nz > 1);
    608       dst += 16;
    609     }
    610     lnz.i8[y] = l;
    611     non_zero_dc |= PACK(nz_dc, 24 - y * 4);
    612     non_zero_ac |= PACK(nz_ac, 24 - y * 4);
    613   }
    614   out_t_nz = PACK(tnz, 24);
    615   out_l_nz = PACK(lnz, 24);
    616 
    617   tnz = kUnpackTab[mb->nz_ >> 4];
    618   lnz = kUnpackTab[left_mb->nz_ >> 4];
    619   for (ch = 0; ch < 4; ch += 2) {
    620     for (y = 0; y < 2; ++y) {
    621       int l = lnz.i8[ch + y];
    622       for (x = 0; x < 2; ++x) {
    623         const int ctx = l + tnz.i8[ch + x];
    624         const int nz =
    625             GetCoeffs(token_br, (ProbaArray)dec->proba_.coeffs_[2],
    626                       ctx, q->uv_mat_, 0, dst);
    627         tnz.i8[ch + x] = l = (nz > 0);
    628         nz_dc.i8[y * 2 + x] = (dst[0] != 0);
    629         nz_ac.i8[y * 2 + x] = (nz > 1);
    630         dst += 16;
    631       }
    632       lnz.i8[ch + y] = l;
    633     }
    634     non_zero_dc |= PACK(nz_dc, 8 - ch * 2);
    635     non_zero_ac |= PACK(nz_ac, 8 - ch * 2);
    636   }
    637   out_t_nz |= PACK(tnz, 20);
    638   out_l_nz |= PACK(lnz, 20);
    639   mb->nz_ = out_t_nz;
    640   left_mb->nz_ = out_l_nz;
    641 
    642   dec->non_zero_ac_ = non_zero_ac;
    643   dec->non_zero_ = non_zero_ac | non_zero_dc;
    644   mb->skip_ = !dec->non_zero_;
    645 }
    646 #undef PACK
    647 
    648 //-----------------------------------------------------------------------------
    649 // Main loop
    650 
    651 int VP8DecodeMB(VP8Decoder* const dec, VP8BitReader* const token_br) {
    652   VP8BitReader* const br = &dec->br_;
    653   VP8MB* const left = dec->mb_info_ - 1;
    654   VP8MB* const info = dec->mb_info_ + dec->mb_x_;
    655 
    656   // Note: we don't save segment map (yet), as we don't expect
    657   // to decode more than 1 keyframe.
    658   if (dec->segment_hdr_.update_map_) {
    659     // Hardcoded tree parsing
    660     dec->segment_ = !VP8GetBit(br, dec->proba_.segments_[0]) ?
    661         VP8GetBit(br, dec->proba_.segments_[1]) :
    662         2 + VP8GetBit(br, dec->proba_.segments_[2]);
    663   }
    664   info->skip_ = dec->use_skip_proba_ ? VP8GetBit(br, dec->skip_p_) : 0;
    665 
    666   VP8ParseIntraMode(br, dec);
    667   if (br->eof_) {
    668     return 0;
    669   }
    670 
    671   if (!info->skip_) {
    672     ParseResiduals(dec, info, token_br);
    673   } else {
    674     left->nz_ = info->nz_ = 0;
    675     if (!dec->is_i4x4_) {
    676       left->dc_nz_ = info->dc_nz_ = 0;
    677     }
    678     dec->non_zero_ = 0;
    679     dec->non_zero_ac_ = 0;
    680   }
    681 
    682   return (!token_br->eof_);
    683 }
    684 
    685 static int ParseFrame(VP8Decoder* const dec, VP8Io* io) {
    686   for (dec->mb_y_ = 0; dec->mb_y_ < dec->br_mb_y_; ++dec->mb_y_) {
    687     VP8MB* const left = dec->mb_info_ - 1;
    688     VP8BitReader* const token_br =
    689         &dec->parts_[dec->mb_y_ & (dec->num_parts_ - 1)];
    690     left->nz_ = 0;
    691     left->dc_nz_ = 0;
    692     memset(dec->intra_l_, B_DC_PRED, sizeof(dec->intra_l_));
    693 
    694     for (dec->mb_x_ = 0; dec->mb_x_ < dec->mb_w_;  dec->mb_x_++) {
    695       if (!VP8DecodeMB(dec, token_br)) {
    696         return VP8SetError(dec, VP8_STATUS_NOT_ENOUGH_DATA,
    697                            "Premature end-of-file encountered.");
    698       }
    699       VP8ReconstructBlock(dec);
    700 
    701       // Store data and save block's filtering params
    702       VP8StoreBlock(dec);
    703     }
    704     if (dec->filter_type_ > 0) {
    705       VP8FilterRow(dec);
    706     }
    707     if (!VP8FinishRow(dec, io)) {
    708       return VP8SetError(dec, VP8_STATUS_USER_ABORT, "Output aborted.");
    709     }
    710   }
    711 
    712   // Finish
    713 #ifndef ONLY_KEYFRAME_CODE
    714   if (!dec->update_proba_) {
    715     dec->proba_ = dec->proba_saved_;
    716   }
    717 #endif
    718 
    719 #ifdef WEBP_EXPERIMENTAL_FEATURES
    720   if (dec->layer_data_size_ > 0) {
    721     if (!VP8DecodeLayer(dec)) {
    722       return 0;
    723     }
    724   }
    725 #endif
    726 
    727   return 1;
    728 }
    729 
    730 // Main entry point
    731 int VP8Decode(VP8Decoder* const dec, VP8Io* const io) {
    732   if (dec == NULL) {
    733     return 0;
    734   }
    735   if (io == NULL) {
    736     return VP8SetError(dec, VP8_STATUS_INVALID_PARAM,
    737                        "NULL VP8Io parameter in VP8Decode().");
    738   }
    739 
    740   if (!dec->ready_) {
    741     if (!VP8GetHeaders(dec, io)) {
    742       return 0;
    743     }
    744   }
    745   assert(dec->ready_);
    746 
    747   // Will allocate memory and prepare everything.
    748   if (!VP8InitFrame(dec, io)) {
    749     VP8Clear(dec);
    750     return 0;
    751   }
    752 
    753   // Finish setting up the decoding parameter
    754   if (VP8FinishFrameSetup(dec, io) != VP8_STATUS_OK) {
    755     VP8Clear(dec);
    756     return 0;
    757   }
    758 
    759   // Main decoding loop
    760   {
    761     const int ret = ParseFrame(dec, io);
    762     if (io->teardown) {
    763       io->teardown(io);
    764     }
    765     if (!ret) {
    766       VP8Clear(dec);
    767       return 0;
    768     }
    769   }
    770 
    771   dec->ready_ = 0;
    772   return 1;
    773 }
    774 
    775 void VP8Clear(VP8Decoder* const dec) {
    776   if (dec == NULL) {
    777     return;
    778   }
    779   if (dec->mem_) {
    780     free(dec->mem_);
    781   }
    782   dec->mem_ = NULL;
    783   dec->mem_size_ = 0;
    784   memset(&dec->br_, 0, sizeof(dec->br_));
    785   dec->ready_ = 0;
    786 }
    787 
    788 //-----------------------------------------------------------------------------
    789 
    790 #if defined(__cplusplus) || defined(c_plusplus)
    791 }    // extern "C"
    792 #endif
    793