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