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