• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2010 Google Inc. All Rights Reserved.
2 //
3 // Use of this source code is governed by a BSD-style license
4 // that can be found in the COPYING file in the root of the source
5 // tree. An additional intellectual property rights grant can be found
6 // in the file PATENTS. All contributing project authors may
7 // be found in the AUTHORS file in the root of the source tree.
8 // -----------------------------------------------------------------------------
9 //
10 // main entry for the decoder
11 //
12 // Author: Skal (pascal.massimino@gmail.com)
13 
14 #include <stdlib.h>
15 
16 #include "./alphai.h"
17 #include "./vp8i.h"
18 #include "./vp8li.h"
19 #include "./webpi.h"
20 #include "../utils/bit_reader_inl.h"
21 #include "../utils/utils.h"
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*)WebPSafeCalloc(1ULL, sizeof(*dec));
49   if (dec != NULL) {
50     SetOk(dec);
51     WebPGetWorkerInterface()->Init(&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     WebPSafeFree(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   // The oldest error reported takes precedence over the new one.
79   if (dec->status_ == VP8_STATUS_OK) {
80     dec->status_ = error;
81     dec->error_msg_ = msg;
82     dec->ready_ = 0;
83   }
84   return 0;
85 }
86 
87 //------------------------------------------------------------------------------
88 
VP8CheckSignature(const uint8_t * const data,size_t data_size)89 int VP8CheckSignature(const uint8_t* const data, size_t data_size) {
90   return (data_size >= 3 &&
91           data[0] == 0x9d && data[1] == 0x01 && data[2] == 0x2a);
92 }
93 
VP8GetInfo(const uint8_t * data,size_t data_size,size_t chunk_size,int * const width,int * const height)94 int VP8GetInfo(const uint8_t* data, size_t data_size, size_t chunk_size,
95                int* const width, int* const height) {
96   if (data == NULL || data_size < VP8_FRAME_HEADER_SIZE) {
97     return 0;         // not enough data
98   }
99   // check signature
100   if (!VP8CheckSignature(data + 3, data_size - 3)) {
101     return 0;         // Wrong signature.
102   } else {
103     const uint32_t bits = data[0] | (data[1] << 8) | (data[2] << 16);
104     const int key_frame = !(bits & 1);
105     const int w = ((data[7] << 8) | data[6]) & 0x3fff;
106     const int h = ((data[9] << 8) | data[8]) & 0x3fff;
107 
108     if (!key_frame) {   // Not a keyframe.
109       return 0;
110     }
111 
112     if (((bits >> 1) & 7) > 3) {
113       return 0;         // unknown profile
114     }
115     if (!((bits >> 4) & 1)) {
116       return 0;         // first frame is invisible!
117     }
118     if (((bits >> 5)) >= chunk_size) {  // partition_length
119       return 0;         // inconsistent size information.
120     }
121     if (w == 0 || h == 0) {
122       return 0;         // We don't support both width and height to be zero.
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   size_t size_left = size;
194   size_t last_part;
195   size_t p;
196 
197   dec->num_parts_ = 1 << VP8GetValue(br, 2);
198   last_part = dec->num_parts_ - 1;
199   if (size < 3 * last_part) {
200     // we can't even read the sizes with sz[]! That's a failure.
201     return VP8_STATUS_NOT_ENOUGH_DATA;
202   }
203   part_start = buf + last_part * 3;
204   size_left -= last_part * 3;
205   for (p = 0; p < last_part; ++p) {
206     size_t psize = sz[0] | (sz[1] << 8) | (sz[2] << 16);
207     if (psize > size_left) psize = size_left;
208     VP8InitBitReader(dec->parts_ + p, part_start, psize);
209     part_start += psize;
210     size_left -= psize;
211     sz += 3;
212   }
213   VP8InitBitReader(dec->parts_ + last_part, part_start, size_left);
214   return (part_start < buf_end) ? VP8_STATUS_OK :
215            VP8_STATUS_SUSPENDED;   // Init is ok, but there's not enough data
216 }
217 
218 // Paragraph 9.4
ParseFilterHeader(VP8BitReader * br,VP8Decoder * const dec)219 static int ParseFilterHeader(VP8BitReader* br, VP8Decoder* const dec) {
220   VP8FilterHeader* const hdr = &dec->filter_hdr_;
221   hdr->simple_    = VP8Get(br);
222   hdr->level_     = VP8GetValue(br, 6);
223   hdr->sharpness_ = VP8GetValue(br, 3);
224   hdr->use_lf_delta_ = VP8Get(br);
225   if (hdr->use_lf_delta_) {
226     if (VP8Get(br)) {   // update lf-delta?
227       int i;
228       for (i = 0; i < NUM_REF_LF_DELTAS; ++i) {
229         if (VP8Get(br)) {
230           hdr->ref_lf_delta_[i] = VP8GetSignedValue(br, 6);
231         }
232       }
233       for (i = 0; i < NUM_MODE_LF_DELTAS; ++i) {
234         if (VP8Get(br)) {
235           hdr->mode_lf_delta_[i] = VP8GetSignedValue(br, 6);
236         }
237       }
238     }
239   }
240   dec->filter_type_ = (hdr->level_ == 0) ? 0 : hdr->simple_ ? 1 : 2;
241   return !br->eof_;
242 }
243 
244 // Topmost call
VP8GetHeaders(VP8Decoder * const dec,VP8Io * const io)245 int VP8GetHeaders(VP8Decoder* const dec, VP8Io* const io) {
246   const uint8_t* buf;
247   size_t buf_size;
248   VP8FrameHeader* frm_hdr;
249   VP8PictureHeader* pic_hdr;
250   VP8BitReader* br;
251   VP8StatusCode status;
252 
253   if (dec == NULL) {
254     return 0;
255   }
256   SetOk(dec);
257   if (io == NULL) {
258     return VP8SetError(dec, VP8_STATUS_INVALID_PARAM,
259                        "null VP8Io passed to VP8GetHeaders()");
260   }
261   buf = io->data;
262   buf_size = io->data_size;
263   if (buf_size < 4) {
264     return VP8SetError(dec, VP8_STATUS_NOT_ENOUGH_DATA,
265                        "Truncated header.");
266   }
267 
268   // Paragraph 9.1
269   {
270     const uint32_t bits = buf[0] | (buf[1] << 8) | (buf[2] << 16);
271     frm_hdr = &dec->frm_hdr_;
272     frm_hdr->key_frame_ = !(bits & 1);
273     frm_hdr->profile_ = (bits >> 1) & 7;
274     frm_hdr->show_ = (bits >> 4) & 1;
275     frm_hdr->partition_length_ = (bits >> 5);
276     if (frm_hdr->profile_ > 3)
277       return VP8SetError(dec, VP8_STATUS_BITSTREAM_ERROR,
278                          "Incorrect keyframe parameters.");
279     if (!frm_hdr->show_)
280       return VP8SetError(dec, VP8_STATUS_UNSUPPORTED_FEATURE,
281                          "Frame not displayable.");
282     buf += 3;
283     buf_size -= 3;
284   }
285 
286   pic_hdr = &dec->pic_hdr_;
287   if (frm_hdr->key_frame_) {
288     // Paragraph 9.2
289     if (buf_size < 7) {
290       return VP8SetError(dec, VP8_STATUS_NOT_ENOUGH_DATA,
291                          "cannot parse picture header");
292     }
293     if (!VP8CheckSignature(buf, buf_size)) {
294       return VP8SetError(dec, VP8_STATUS_BITSTREAM_ERROR,
295                          "Bad code word");
296     }
297     pic_hdr->width_ = ((buf[4] << 8) | buf[3]) & 0x3fff;
298     pic_hdr->xscale_ = buf[4] >> 6;   // ratio: 1, 5/4 5/3 or 2
299     pic_hdr->height_ = ((buf[6] << 8) | buf[5]) & 0x3fff;
300     pic_hdr->yscale_ = buf[6] >> 6;
301     buf += 7;
302     buf_size -= 7;
303 
304     dec->mb_w_ = (pic_hdr->width_ + 15) >> 4;
305     dec->mb_h_ = (pic_hdr->height_ + 15) >> 4;
306     // Setup default output area (can be later modified during io->setup())
307     io->width = pic_hdr->width_;
308     io->height = pic_hdr->height_;
309     io->use_scaling  = 0;
310     io->use_cropping = 0;
311     io->crop_top  = 0;
312     io->crop_left = 0;
313     io->crop_right  = io->width;
314     io->crop_bottom = io->height;
315     io->mb_w = io->width;   // sanity check
316     io->mb_h = io->height;  // ditto
317 
318     VP8ResetProba(&dec->proba_);
319     ResetSegmentHeader(&dec->segment_hdr_);
320   }
321 
322   // Check if we have all the partition #0 available, and initialize dec->br_
323   // to read this partition (and this partition only).
324   if (frm_hdr->partition_length_ > buf_size) {
325     return VP8SetError(dec, VP8_STATUS_NOT_ENOUGH_DATA,
326                        "bad partition length");
327   }
328 
329   br = &dec->br_;
330   VP8InitBitReader(br, buf, frm_hdr->partition_length_);
331   buf += frm_hdr->partition_length_;
332   buf_size -= frm_hdr->partition_length_;
333 
334   if (frm_hdr->key_frame_) {
335     pic_hdr->colorspace_ = VP8Get(br);
336     pic_hdr->clamp_type_ = VP8Get(br);
337   }
338   if (!ParseSegmentHeader(br, &dec->segment_hdr_, &dec->proba_)) {
339     return VP8SetError(dec, VP8_STATUS_BITSTREAM_ERROR,
340                        "cannot parse segment header");
341   }
342   // Filter specs
343   if (!ParseFilterHeader(br, dec)) {
344     return VP8SetError(dec, VP8_STATUS_BITSTREAM_ERROR,
345                        "cannot parse filter header");
346   }
347   status = ParsePartitions(dec, buf, buf_size);
348   if (status != VP8_STATUS_OK) {
349     return VP8SetError(dec, status, "cannot parse partitions");
350   }
351 
352   // quantizer change
353   VP8ParseQuant(dec);
354 
355   // Frame buffer marking
356   if (!frm_hdr->key_frame_) {
357     return VP8SetError(dec, VP8_STATUS_UNSUPPORTED_FEATURE,
358                        "Not a key frame.");
359   }
360 
361   VP8Get(br);   // ignore the value of update_proba_
362 
363   VP8ParseProba(br, dec);
364 
365   // sanitized state
366   dec->ready_ = 1;
367   return 1;
368 }
369 
370 //------------------------------------------------------------------------------
371 // Residual decoding (Paragraph 13.2 / 13.3)
372 
373 static const uint8_t kCat3[] = { 173, 148, 140, 0 };
374 static const uint8_t kCat4[] = { 176, 155, 140, 135, 0 };
375 static const uint8_t kCat5[] = { 180, 157, 141, 134, 130, 0 };
376 static const uint8_t kCat6[] =
377   { 254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129, 0 };
378 static const uint8_t* const kCat3456[] = { kCat3, kCat4, kCat5, kCat6 };
379 static const uint8_t kZigzag[16] = {
380   0, 1, 4, 8,  5, 2, 3, 6,  9, 12, 13, 10,  7, 11, 14, 15
381 };
382 
383 // See section 13-2: http://tools.ietf.org/html/rfc6386#section-13.2
GetLargeValue(VP8BitReader * const br,const uint8_t * const p)384 static int GetLargeValue(VP8BitReader* const br, const uint8_t* const p) {
385   int v;
386   if (!VP8GetBit(br, p[3])) {
387     if (!VP8GetBit(br, p[4])) {
388       v = 2;
389     } else {
390       v = 3 + VP8GetBit(br, p[5]);
391     }
392   } else {
393     if (!VP8GetBit(br, p[6])) {
394       if (!VP8GetBit(br, p[7])) {
395         v = 5 + VP8GetBit(br, 159);
396       } else {
397         v = 7 + 2 * VP8GetBit(br, 165);
398         v += VP8GetBit(br, 145);
399       }
400     } else {
401       const uint8_t* tab;
402       const int bit1 = VP8GetBit(br, p[8]);
403       const int bit0 = VP8GetBit(br, p[9 + bit1]);
404       const int cat = 2 * bit1 + bit0;
405       v = 0;
406       for (tab = kCat3456[cat]; *tab; ++tab) {
407         v += v + VP8GetBit(br, *tab);
408       }
409       v += 3 + (8 << cat);
410     }
411   }
412   return v;
413 }
414 
415 // Returns the position of the last non-zero coeff plus one
GetCoeffs(VP8BitReader * const br,const VP8BandProbas * const prob[],int ctx,const quant_t dq,int n,int16_t * out)416 static int GetCoeffs(VP8BitReader* const br, const VP8BandProbas* const prob[],
417                      int ctx, const quant_t dq, int n, int16_t* out) {
418   const uint8_t* p = prob[n]->probas_[ctx];
419   for (; n < 16; ++n) {
420     if (!VP8GetBit(br, p[0])) {
421       return n;  // previous coeff was last non-zero coeff
422     }
423     while (!VP8GetBit(br, p[1])) {       // sequence of zero coeffs
424       p = prob[++n]->probas_[0];
425       if (n == 16) return 16;
426     }
427     {        // non zero coeff
428       const VP8ProbaArray* const p_ctx = &prob[n + 1]->probas_[0];
429       int v;
430       if (!VP8GetBit(br, p[2])) {
431         v = 1;
432         p = p_ctx[1];
433       } else {
434         v = GetLargeValue(br, p);
435         p = p_ctx[2];
436       }
437       out[kZigzag[n]] = VP8GetSigned(br, v) * dq[n > 0];
438     }
439   }
440   return 16;
441 }
442 
NzCodeBits(uint32_t nz_coeffs,int nz,int dc_nz)443 static WEBP_INLINE uint32_t NzCodeBits(uint32_t nz_coeffs, int nz, int dc_nz) {
444   nz_coeffs <<= 2;
445   nz_coeffs |= (nz > 3) ? 3 : (nz > 1) ? 2 : dc_nz;
446   return nz_coeffs;
447 }
448 
ParseResiduals(VP8Decoder * const dec,VP8MB * const mb,VP8BitReader * const token_br)449 static int ParseResiduals(VP8Decoder* const dec,
450                           VP8MB* const mb, VP8BitReader* const token_br) {
451   const VP8BandProbas* (* const bands)[16 + 1] = dec->proba_.bands_ptr_;
452   const VP8BandProbas* const * ac_proba;
453   VP8MBData* const block = dec->mb_data_ + dec->mb_x_;
454   const VP8QuantMatrix* const q = &dec->dqm_[block->segment_];
455   int16_t* dst = block->coeffs_;
456   VP8MB* const left_mb = dec->mb_info_ - 1;
457   uint8_t tnz, lnz;
458   uint32_t non_zero_y = 0;
459   uint32_t non_zero_uv = 0;
460   int x, y, ch;
461   uint32_t out_t_nz, out_l_nz;
462   int first;
463 
464   memset(dst, 0, 384 * sizeof(*dst));
465   if (!block->is_i4x4_) {    // parse DC
466     int16_t dc[16] = { 0 };
467     const int ctx = mb->nz_dc_ + left_mb->nz_dc_;
468     const int nz = GetCoeffs(token_br, bands[1], ctx, q->y2_mat_, 0, dc);
469     mb->nz_dc_ = left_mb->nz_dc_ = (nz > 0);
470     if (nz > 1) {   // more than just the DC -> perform the full transform
471       VP8TransformWHT(dc, dst);
472     } else {        // only DC is non-zero -> inlined simplified transform
473       int i;
474       const int dc0 = (dc[0] + 3) >> 3;
475       for (i = 0; i < 16 * 16; i += 16) dst[i] = dc0;
476     }
477     first = 1;
478     ac_proba = bands[0];
479   } else {
480     first = 0;
481     ac_proba = bands[3];
482   }
483 
484   tnz = mb->nz_ & 0x0f;
485   lnz = left_mb->nz_ & 0x0f;
486   for (y = 0; y < 4; ++y) {
487     int l = lnz & 1;
488     uint32_t nz_coeffs = 0;
489     for (x = 0; x < 4; ++x) {
490       const int ctx = l + (tnz & 1);
491       const int nz = GetCoeffs(token_br, ac_proba, ctx, q->y1_mat_, first, dst);
492       l = (nz > first);
493       tnz = (tnz >> 1) | (l << 7);
494       nz_coeffs = NzCodeBits(nz_coeffs, nz, dst[0] != 0);
495       dst += 16;
496     }
497     tnz >>= 4;
498     lnz = (lnz >> 1) | (l << 7);
499     non_zero_y = (non_zero_y << 8) | nz_coeffs;
500   }
501   out_t_nz = tnz;
502   out_l_nz = lnz >> 4;
503 
504   for (ch = 0; ch < 4; ch += 2) {
505     uint32_t nz_coeffs = 0;
506     tnz = mb->nz_ >> (4 + ch);
507     lnz = left_mb->nz_ >> (4 + ch);
508     for (y = 0; y < 2; ++y) {
509       int l = lnz & 1;
510       for (x = 0; x < 2; ++x) {
511         const int ctx = l + (tnz & 1);
512         const int nz = GetCoeffs(token_br, bands[2], ctx, q->uv_mat_, 0, dst);
513         l = (nz > 0);
514         tnz = (tnz >> 1) | (l << 3);
515         nz_coeffs = NzCodeBits(nz_coeffs, nz, dst[0] != 0);
516         dst += 16;
517       }
518       tnz >>= 2;
519       lnz = (lnz >> 1) | (l << 5);
520     }
521     // Note: we don't really need the per-4x4 details for U/V blocks.
522     non_zero_uv |= nz_coeffs << (4 * ch);
523     out_t_nz |= (tnz << 4) << ch;
524     out_l_nz |= (lnz & 0xf0) << ch;
525   }
526   mb->nz_ = out_t_nz;
527   left_mb->nz_ = out_l_nz;
528 
529   block->non_zero_y_ = non_zero_y;
530   block->non_zero_uv_ = non_zero_uv;
531 
532   // We look at the mode-code of each block and check if some blocks have less
533   // than three non-zero coeffs (code < 2). This is to avoid dithering flat and
534   // empty blocks.
535   block->dither_ = (non_zero_uv & 0xaaaa) ? 0 : q->dither_;
536 
537   return !(non_zero_y | non_zero_uv);  // will be used for further optimization
538 }
539 
540 //------------------------------------------------------------------------------
541 // Main loop
542 
VP8DecodeMB(VP8Decoder * const dec,VP8BitReader * const token_br)543 int VP8DecodeMB(VP8Decoder* const dec, VP8BitReader* const token_br) {
544   VP8MB* const left = dec->mb_info_ - 1;
545   VP8MB* const mb = dec->mb_info_ + dec->mb_x_;
546   VP8MBData* const block = dec->mb_data_ + dec->mb_x_;
547   int skip = dec->use_skip_proba_ ? block->skip_ : 0;
548 
549   if (!skip) {
550     skip = ParseResiduals(dec, mb, token_br);
551   } else {
552     left->nz_ = mb->nz_ = 0;
553     if (!block->is_i4x4_) {
554       left->nz_dc_ = mb->nz_dc_ = 0;
555     }
556     block->non_zero_y_ = 0;
557     block->non_zero_uv_ = 0;
558     block->dither_ = 0;
559   }
560 
561   if (dec->filter_type_ > 0) {  // store filter info
562     VP8FInfo* const finfo = dec->f_info_ + dec->mb_x_;
563     *finfo = dec->fstrengths_[block->segment_][block->is_i4x4_];
564     finfo->f_inner_ |= !skip;
565   }
566 
567   return !token_br->eof_;
568 }
569 
VP8InitScanline(VP8Decoder * const dec)570 void VP8InitScanline(VP8Decoder* const dec) {
571   VP8MB* const left = dec->mb_info_ - 1;
572   left->nz_ = 0;
573   left->nz_dc_ = 0;
574   memset(dec->intra_l_, B_DC_PRED, sizeof(dec->intra_l_));
575   dec->mb_x_ = 0;
576 }
577 
ParseFrame(VP8Decoder * const dec,VP8Io * io)578 static int ParseFrame(VP8Decoder* const dec, VP8Io* io) {
579   for (dec->mb_y_ = 0; dec->mb_y_ < dec->br_mb_y_; ++dec->mb_y_) {
580     // Parse bitstream for this row.
581     VP8BitReader* const token_br =
582         &dec->parts_[dec->mb_y_ & (dec->num_parts_ - 1)];
583     if (!VP8ParseIntraModeRow(&dec->br_, dec)) {
584       return VP8SetError(dec, VP8_STATUS_NOT_ENOUGH_DATA,
585                          "Premature end-of-partition0 encountered.");
586     }
587     for (; dec->mb_x_ < dec->mb_w_; ++dec->mb_x_) {
588       if (!VP8DecodeMB(dec, token_br)) {
589         return VP8SetError(dec, VP8_STATUS_NOT_ENOUGH_DATA,
590                            "Premature end-of-file encountered.");
591       }
592     }
593     VP8InitScanline(dec);   // Prepare for next scanline
594 
595     // Reconstruct, filter and emit the row.
596     if (!VP8ProcessRow(dec, io)) {
597       return VP8SetError(dec, VP8_STATUS_USER_ABORT, "Output aborted.");
598     }
599   }
600   if (dec->mt_method_ > 0) {
601     if (!WebPGetWorkerInterface()->Sync(&dec->worker_)) return 0;
602   }
603 
604   return 1;
605 }
606 
607 // Main entry point
VP8Decode(VP8Decoder * const dec,VP8Io * const io)608 int VP8Decode(VP8Decoder* const dec, VP8Io* const io) {
609   int ok = 0;
610   if (dec == NULL) {
611     return 0;
612   }
613   if (io == NULL) {
614     return VP8SetError(dec, VP8_STATUS_INVALID_PARAM,
615                        "NULL VP8Io parameter in VP8Decode().");
616   }
617 
618   if (!dec->ready_) {
619     if (!VP8GetHeaders(dec, io)) {
620       return 0;
621     }
622   }
623   assert(dec->ready_);
624 
625   // Finish setting up the decoding parameter. Will call io->setup().
626   ok = (VP8EnterCritical(dec, io) == VP8_STATUS_OK);
627   if (ok) {   // good to go.
628     // Will allocate memory and prepare everything.
629     if (ok) ok = VP8InitFrame(dec, io);
630 
631     // Main decoding loop
632     if (ok) ok = ParseFrame(dec, io);
633 
634     // Exit.
635     ok &= VP8ExitCritical(dec, io);
636   }
637 
638   if (!ok) {
639     VP8Clear(dec);
640     return 0;
641   }
642 
643   dec->ready_ = 0;
644   return ok;
645 }
646 
VP8Clear(VP8Decoder * const dec)647 void VP8Clear(VP8Decoder* const dec) {
648   if (dec == NULL) {
649     return;
650   }
651   WebPGetWorkerInterface()->End(&dec->worker_);
652   ALPHDelete(dec->alph_dec_);
653   dec->alph_dec_ = NULL;
654   WebPSafeFree(dec->mem_);
655   dec->mem_ = NULL;
656   dec->mem_size_ = 0;
657   memset(&dec->br_, 0, sizeof(dec->br_));
658   dec->ready_ = 0;
659 }
660 
661 //------------------------------------------------------------------------------
662 
663