1 // Copyright 2012 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 // Authors: Vikas Arora (vikaas.arora@gmail.com)
13 //          Jyrki Alakuijala (jyrki@google.com)
14 
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include "./vp8li.h"
18 #include "../dsp/lossless.h"
19 #include "../dsp/yuv.h"
20 #include "../utils/huffman.h"
21 #include "../utils/utils.h"
22 
23 #if defined(__cplusplus) || defined(c_plusplus)
24 extern "C" {
25 #endif
26 
27 #define NUM_ARGB_CACHE_ROWS          16
28 
29 static const int kCodeLengthLiterals = 16;
30 static const int kCodeLengthRepeatCode = 16;
31 static const int kCodeLengthExtraBits[3] = { 2, 3, 7 };
32 static const int kCodeLengthRepeatOffsets[3] = { 3, 3, 11 };
33 
34 // -----------------------------------------------------------------------------
35 //  Five Huffman codes are used at each meta code:
36 //  1. green + length prefix codes + color cache codes,
37 //  2. alpha,
38 //  3. red,
39 //  4. blue, and,
40 //  5. distance prefix codes.
41 typedef enum {
42   GREEN = 0,
43   RED   = 1,
44   BLUE  = 2,
45   ALPHA = 3,
46   DIST  = 4
47 } HuffIndex;
48 
49 static const uint16_t kAlphabetSize[HUFFMAN_CODES_PER_META_CODE] = {
50   NUM_LITERAL_CODES + NUM_LENGTH_CODES,
51   NUM_LITERAL_CODES, NUM_LITERAL_CODES, NUM_LITERAL_CODES,
52   NUM_DISTANCE_CODES
53 };
54 
55 
56 #define NUM_CODE_LENGTH_CODES       19
57 static const uint8_t kCodeLengthCodeOrder[NUM_CODE_LENGTH_CODES] = {
58   17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
59 };
60 
61 #define CODE_TO_PLANE_CODES        120
62 static const uint8_t code_to_plane_lut[CODE_TO_PLANE_CODES] = {
63   0x18, 0x07, 0x17, 0x19, 0x28, 0x06, 0x27, 0x29, 0x16, 0x1a,
64   0x26, 0x2a, 0x38, 0x05, 0x37, 0x39, 0x15, 0x1b, 0x36, 0x3a,
65   0x25, 0x2b, 0x48, 0x04, 0x47, 0x49, 0x14, 0x1c, 0x35, 0x3b,
66   0x46, 0x4a, 0x24, 0x2c, 0x58, 0x45, 0x4b, 0x34, 0x3c, 0x03,
67   0x57, 0x59, 0x13, 0x1d, 0x56, 0x5a, 0x23, 0x2d, 0x44, 0x4c,
68   0x55, 0x5b, 0x33, 0x3d, 0x68, 0x02, 0x67, 0x69, 0x12, 0x1e,
69   0x66, 0x6a, 0x22, 0x2e, 0x54, 0x5c, 0x43, 0x4d, 0x65, 0x6b,
70   0x32, 0x3e, 0x78, 0x01, 0x77, 0x79, 0x53, 0x5d, 0x11, 0x1f,
71   0x64, 0x6c, 0x42, 0x4e, 0x76, 0x7a, 0x21, 0x2f, 0x75, 0x7b,
72   0x31, 0x3f, 0x63, 0x6d, 0x52, 0x5e, 0x00, 0x74, 0x7c, 0x41,
73   0x4f, 0x10, 0x20, 0x62, 0x6e, 0x30, 0x73, 0x7d, 0x51, 0x5f,
74   0x40, 0x72, 0x7e, 0x61, 0x6f, 0x50, 0x71, 0x7f, 0x60, 0x70
75 };
76 
77 static int DecodeImageStream(int xsize, int ysize,
78                              int is_level0,
79                              VP8LDecoder* const dec,
80                              uint32_t** const decoded_data);
81 
82 //------------------------------------------------------------------------------
83 
VP8LCheckSignature(const uint8_t * const data,size_t size)84 int VP8LCheckSignature(const uint8_t* const data, size_t size) {
85   return (size >= 1) && (data[0] == VP8L_MAGIC_BYTE);
86 }
87 
ReadImageInfo(VP8LBitReader * const br,int * const width,int * const height,int * const has_alpha)88 static int ReadImageInfo(VP8LBitReader* const br,
89                          int* const width, int* const height,
90                          int* const has_alpha) {
91   const uint8_t signature = VP8LReadBits(br, 8);
92   if (!VP8LCheckSignature(&signature, 1)) {
93     return 0;
94   }
95   *width = VP8LReadBits(br, VP8L_IMAGE_SIZE_BITS) + 1;
96   *height = VP8LReadBits(br, VP8L_IMAGE_SIZE_BITS) + 1;
97   *has_alpha = VP8LReadBits(br, 1);
98   VP8LReadBits(br, VP8L_VERSION_BITS);  // Read/ignore the version number.
99   return 1;
100 }
101 
VP8LGetInfo(const uint8_t * data,size_t data_size,int * const width,int * const height,int * const has_alpha)102 int VP8LGetInfo(const uint8_t* data, size_t data_size,
103                 int* const width, int* const height, int* const has_alpha) {
104   if (data == NULL || data_size < VP8L_FRAME_HEADER_SIZE) {
105     return 0;         // not enough data
106   } else {
107     int w, h, a;
108     VP8LBitReader br;
109     VP8LInitBitReader(&br, data, data_size);
110     if (!ReadImageInfo(&br, &w, &h, &a)) {
111       return 0;
112     }
113     if (width != NULL) *width = w;
114     if (height != NULL) *height = h;
115     if (has_alpha != NULL) *has_alpha = a;
116     return 1;
117   }
118 }
119 
120 //------------------------------------------------------------------------------
121 
GetCopyDistance(int distance_symbol,VP8LBitReader * const br)122 static WEBP_INLINE int GetCopyDistance(int distance_symbol,
123                                        VP8LBitReader* const br) {
124   int extra_bits, offset;
125   if (distance_symbol < 4) {
126     return distance_symbol + 1;
127   }
128   extra_bits = (distance_symbol - 2) >> 1;
129   offset = (2 + (distance_symbol & 1)) << extra_bits;
130   return offset + VP8LReadBits(br, extra_bits) + 1;
131 }
132 
GetCopyLength(int length_symbol,VP8LBitReader * const br)133 static WEBP_INLINE int GetCopyLength(int length_symbol,
134                                      VP8LBitReader* const br) {
135   // Length and distance prefixes are encoded the same way.
136   return GetCopyDistance(length_symbol, br);
137 }
138 
PlaneCodeToDistance(int xsize,int plane_code)139 static WEBP_INLINE int PlaneCodeToDistance(int xsize, int plane_code) {
140   if (plane_code > CODE_TO_PLANE_CODES) {
141     return plane_code - CODE_TO_PLANE_CODES;
142   } else {
143     const int dist_code = code_to_plane_lut[plane_code - 1];
144     const int yoffset = dist_code >> 4;
145     const int xoffset = 8 - (dist_code & 0xf);
146     const int dist = yoffset * xsize + xoffset;
147     return (dist >= 1) ? dist : 1;
148   }
149 }
150 
151 //------------------------------------------------------------------------------
152 // Decodes the next Huffman code from bit-stream.
153 // FillBitWindow(br) needs to be called at minimum every second call
154 // to ReadSymbol, in order to pre-fetch enough bits.
ReadSymbol(const HuffmanTree * tree,VP8LBitReader * const br)155 static WEBP_INLINE int ReadSymbol(const HuffmanTree* tree,
156                                   VP8LBitReader* const br) {
157   const HuffmanTreeNode* node = tree->root_;
158   int num_bits = 0;
159   uint32_t bits = VP8LPrefetchBits(br);
160   assert(node != NULL);
161   while (!HuffmanTreeNodeIsLeaf(node)) {
162     node = HuffmanTreeNextNode(node, bits & 1);
163     bits >>= 1;
164     ++num_bits;
165   }
166   VP8LDiscardBits(br, num_bits);
167   return node->symbol_;
168 }
169 
ReadHuffmanCodeLengths(VP8LDecoder * const dec,const int * const code_length_code_lengths,int num_symbols,int * const code_lengths)170 static int ReadHuffmanCodeLengths(
171     VP8LDecoder* const dec, const int* const code_length_code_lengths,
172     int num_symbols, int* const code_lengths) {
173   int ok = 0;
174   VP8LBitReader* const br = &dec->br_;
175   int symbol;
176   int max_symbol;
177   int prev_code_len = DEFAULT_CODE_LENGTH;
178   HuffmanTree tree;
179 
180   if (!HuffmanTreeBuildImplicit(&tree, code_length_code_lengths,
181                                 NUM_CODE_LENGTH_CODES)) {
182     dec->status_ = VP8_STATUS_BITSTREAM_ERROR;
183     return 0;
184   }
185 
186   if (VP8LReadBits(br, 1)) {    // use length
187     const int length_nbits = 2 + 2 * VP8LReadBits(br, 3);
188     max_symbol = 2 + VP8LReadBits(br, length_nbits);
189     if (max_symbol > num_symbols) {
190       dec->status_ = VP8_STATUS_BITSTREAM_ERROR;
191       goto End;
192     }
193   } else {
194     max_symbol = num_symbols;
195   }
196 
197   symbol = 0;
198   while (symbol < num_symbols) {
199     int code_len;
200     if (max_symbol-- == 0) break;
201     VP8LFillBitWindow(br);
202     code_len = ReadSymbol(&tree, br);
203     if (code_len < kCodeLengthLiterals) {
204       code_lengths[symbol++] = code_len;
205       if (code_len != 0) prev_code_len = code_len;
206     } else {
207       const int use_prev = (code_len == kCodeLengthRepeatCode);
208       const int slot = code_len - kCodeLengthLiterals;
209       const int extra_bits = kCodeLengthExtraBits[slot];
210       const int repeat_offset = kCodeLengthRepeatOffsets[slot];
211       int repeat = VP8LReadBits(br, extra_bits) + repeat_offset;
212       if (symbol + repeat > num_symbols) {
213         dec->status_ = VP8_STATUS_BITSTREAM_ERROR;
214         goto End;
215       } else {
216         const int length = use_prev ? prev_code_len : 0;
217         while (repeat-- > 0) code_lengths[symbol++] = length;
218       }
219     }
220   }
221   ok = 1;
222 
223  End:
224   HuffmanTreeRelease(&tree);
225   return ok;
226 }
227 
ReadHuffmanCode(int alphabet_size,VP8LDecoder * const dec,HuffmanTree * const tree)228 static int ReadHuffmanCode(int alphabet_size, VP8LDecoder* const dec,
229                            HuffmanTree* const tree) {
230   int ok = 0;
231   VP8LBitReader* const br = &dec->br_;
232   const int simple_code = VP8LReadBits(br, 1);
233 
234   if (simple_code) {  // Read symbols, codes & code lengths directly.
235     int symbols[2];
236     int codes[2];
237     int code_lengths[2];
238     const int num_symbols = VP8LReadBits(br, 1) + 1;
239     const int first_symbol_len_code = VP8LReadBits(br, 1);
240     // The first code is either 1 bit or 8 bit code.
241     symbols[0] = VP8LReadBits(br, (first_symbol_len_code == 0) ? 1 : 8);
242     codes[0] = 0;
243     code_lengths[0] = num_symbols - 1;
244     // The second code (if present), is always 8 bit long.
245     if (num_symbols == 2) {
246       symbols[1] = VP8LReadBits(br, 8);
247       codes[1] = 1;
248       code_lengths[1] = num_symbols - 1;
249     }
250     ok = HuffmanTreeBuildExplicit(tree, code_lengths, codes, symbols,
251                                   alphabet_size, num_symbols);
252   } else {  // Decode Huffman-coded code lengths.
253     int* code_lengths = NULL;
254     int i;
255     int code_length_code_lengths[NUM_CODE_LENGTH_CODES] = { 0 };
256     const int num_codes = VP8LReadBits(br, 4) + 4;
257     if (num_codes > NUM_CODE_LENGTH_CODES) {
258       dec->status_ = VP8_STATUS_BITSTREAM_ERROR;
259       return 0;
260     }
261 
262     code_lengths =
263         (int*)WebPSafeCalloc((uint64_t)alphabet_size, sizeof(*code_lengths));
264     if (code_lengths == NULL) {
265       dec->status_ = VP8_STATUS_OUT_OF_MEMORY;
266       return 0;
267     }
268 
269     for (i = 0; i < num_codes; ++i) {
270       code_length_code_lengths[kCodeLengthCodeOrder[i]] = VP8LReadBits(br, 3);
271     }
272     ok = ReadHuffmanCodeLengths(dec, code_length_code_lengths, alphabet_size,
273                                 code_lengths);
274     if (ok) {
275       ok = HuffmanTreeBuildImplicit(tree, code_lengths, alphabet_size);
276     }
277     free(code_lengths);
278   }
279   ok = ok && !br->error_;
280   if (!ok) {
281     dec->status_ = VP8_STATUS_BITSTREAM_ERROR;
282     return 0;
283   }
284   return 1;
285 }
286 
DeleteHtreeGroups(HTreeGroup * htree_groups,int num_htree_groups)287 static void DeleteHtreeGroups(HTreeGroup* htree_groups, int num_htree_groups) {
288   if (htree_groups != NULL) {
289     int i, j;
290     for (i = 0; i < num_htree_groups; ++i) {
291       HuffmanTree* const htrees = htree_groups[i].htrees_;
292       for (j = 0; j < HUFFMAN_CODES_PER_META_CODE; ++j) {
293         HuffmanTreeRelease(&htrees[j]);
294       }
295     }
296     free(htree_groups);
297   }
298 }
299 
ReadHuffmanCodes(VP8LDecoder * const dec,int xsize,int ysize,int color_cache_bits,int allow_recursion)300 static int ReadHuffmanCodes(VP8LDecoder* const dec, int xsize, int ysize,
301                             int color_cache_bits, int allow_recursion) {
302   int i, j;
303   VP8LBitReader* const br = &dec->br_;
304   VP8LMetadata* const hdr = &dec->hdr_;
305   uint32_t* huffman_image = NULL;
306   HTreeGroup* htree_groups = NULL;
307   int num_htree_groups = 1;
308 
309   if (allow_recursion && VP8LReadBits(br, 1)) {
310     // use meta Huffman codes.
311     const int huffman_precision = VP8LReadBits(br, 3) + 2;
312     const int huffman_xsize = VP8LSubSampleSize(xsize, huffman_precision);
313     const int huffman_ysize = VP8LSubSampleSize(ysize, huffman_precision);
314     const int huffman_pixs = huffman_xsize * huffman_ysize;
315     if (!DecodeImageStream(huffman_xsize, huffman_ysize, 0, dec,
316                            &huffman_image)) {
317       dec->status_ = VP8_STATUS_BITSTREAM_ERROR;
318       goto Error;
319     }
320     hdr->huffman_subsample_bits_ = huffman_precision;
321     for (i = 0; i < huffman_pixs; ++i) {
322       // The huffman data is stored in red and green bytes.
323       const int group = (huffman_image[i] >> 8) & 0xffff;
324       huffman_image[i] = group;
325       if (group >= num_htree_groups) {
326         num_htree_groups = group + 1;
327       }
328     }
329   }
330 
331   if (br->error_) goto Error;
332 
333   assert(num_htree_groups <= 0x10000);
334   htree_groups =
335       (HTreeGroup*)WebPSafeCalloc((uint64_t)num_htree_groups,
336                                   sizeof(*htree_groups));
337   if (htree_groups == NULL) {
338     dec->status_ = VP8_STATUS_OUT_OF_MEMORY;
339     goto Error;
340   }
341 
342   for (i = 0; i < num_htree_groups; ++i) {
343     HuffmanTree* const htrees = htree_groups[i].htrees_;
344     for (j = 0; j < HUFFMAN_CODES_PER_META_CODE; ++j) {
345       int alphabet_size = kAlphabetSize[j];
346       if (j == 0 && color_cache_bits > 0) {
347         alphabet_size += 1 << color_cache_bits;
348       }
349       if (!ReadHuffmanCode(alphabet_size, dec, htrees + j)) goto Error;
350     }
351   }
352 
353   // All OK. Finalize pointers and return.
354   hdr->huffman_image_ = huffman_image;
355   hdr->num_htree_groups_ = num_htree_groups;
356   hdr->htree_groups_ = htree_groups;
357   return 1;
358 
359  Error:
360   free(huffman_image);
361   DeleteHtreeGroups(htree_groups, num_htree_groups);
362   return 0;
363 }
364 
365 //------------------------------------------------------------------------------
366 // Scaling.
367 
AllocateAndInitRescaler(VP8LDecoder * const dec,VP8Io * const io)368 static int AllocateAndInitRescaler(VP8LDecoder* const dec, VP8Io* const io) {
369   const int num_channels = 4;
370   const int in_width = io->mb_w;
371   const int out_width = io->scaled_width;
372   const int in_height = io->mb_h;
373   const int out_height = io->scaled_height;
374   const uint64_t work_size = 2 * num_channels * (uint64_t)out_width;
375   int32_t* work;        // Rescaler work area.
376   const uint64_t scaled_data_size = num_channels * (uint64_t)out_width;
377   uint32_t* scaled_data;  // Temporary storage for scaled BGRA data.
378   const uint64_t memory_size = sizeof(*dec->rescaler) +
379                                work_size * sizeof(*work) +
380                                scaled_data_size * sizeof(*scaled_data);
381   uint8_t* memory = (uint8_t*)WebPSafeCalloc(memory_size, sizeof(*memory));
382   if (memory == NULL) {
383     dec->status_ = VP8_STATUS_OUT_OF_MEMORY;
384     return 0;
385   }
386   assert(dec->rescaler_memory == NULL);
387   dec->rescaler_memory = memory;
388 
389   dec->rescaler = (WebPRescaler*)memory;
390   memory += sizeof(*dec->rescaler);
391   work = (int32_t*)memory;
392   memory += work_size * sizeof(*work);
393   scaled_data = (uint32_t*)memory;
394 
395   WebPRescalerInit(dec->rescaler, in_width, in_height, (uint8_t*)scaled_data,
396                    out_width, out_height, 0, num_channels,
397                    in_width, out_width, in_height, out_height, work);
398   return 1;
399 }
400 
401 //------------------------------------------------------------------------------
402 // Export to ARGB
403 
404 // We have special "export" function since we need to convert from BGRA
Export(WebPRescaler * const rescaler,WEBP_CSP_MODE colorspace,int rgba_stride,uint8_t * const rgba)405 static int Export(WebPRescaler* const rescaler, WEBP_CSP_MODE colorspace,
406                   int rgba_stride, uint8_t* const rgba) {
407   const uint32_t* const src = (const uint32_t*)rescaler->dst;
408   const int dst_width = rescaler->dst_width;
409   int num_lines_out = 0;
410   while (WebPRescalerHasPendingOutput(rescaler)) {
411     uint8_t* const dst = rgba + num_lines_out * rgba_stride;
412     WebPRescalerExportRow(rescaler);
413     VP8LConvertFromBGRA(src, dst_width, colorspace, dst);
414     ++num_lines_out;
415   }
416   return num_lines_out;
417 }
418 
419 // Emit scaled rows.
EmitRescaledRows(const VP8LDecoder * const dec,const uint32_t * const data,int in_stride,int mb_h,uint8_t * const out,int out_stride)420 static int EmitRescaledRows(const VP8LDecoder* const dec,
421                             const uint32_t* const data, int in_stride, int mb_h,
422                             uint8_t* const out, int out_stride) {
423   const WEBP_CSP_MODE colorspace = dec->output_->colorspace;
424   const uint8_t* const in = (const uint8_t*)data;
425   int num_lines_in = 0;
426   int num_lines_out = 0;
427   while (num_lines_in < mb_h) {
428     const uint8_t* const row_in = in + num_lines_in * in_stride;
429     uint8_t* const row_out = out + num_lines_out * out_stride;
430     num_lines_in += WebPRescalerImport(dec->rescaler, mb_h - num_lines_in,
431                                        row_in, in_stride);
432     num_lines_out += Export(dec->rescaler, colorspace, out_stride, row_out);
433   }
434   return num_lines_out;
435 }
436 
437 // Emit rows without any scaling.
EmitRows(WEBP_CSP_MODE colorspace,const uint32_t * const data,int in_stride,int mb_w,int mb_h,uint8_t * const out,int out_stride)438 static int EmitRows(WEBP_CSP_MODE colorspace,
439                     const uint32_t* const data, int in_stride,
440                     int mb_w, int mb_h,
441                     uint8_t* const out, int out_stride) {
442   int lines = mb_h;
443   const uint8_t* row_in = (const uint8_t*)data;
444   uint8_t* row_out = out;
445   while (lines-- > 0) {
446     VP8LConvertFromBGRA((const uint32_t*)row_in, mb_w, colorspace, row_out);
447     row_in += in_stride;
448     row_out += out_stride;
449   }
450   return mb_h;  // Num rows out == num rows in.
451 }
452 
453 //------------------------------------------------------------------------------
454 // Export to YUVA
455 
ConvertToYUVA(const uint32_t * const src,int width,int y_pos,const WebPDecBuffer * const output)456 static void ConvertToYUVA(const uint32_t* const src, int width, int y_pos,
457                           const WebPDecBuffer* const output) {
458   const WebPYUVABuffer* const buf = &output->u.YUVA;
459   // first, the luma plane
460   {
461     int i;
462     uint8_t* const y = buf->y + y_pos * buf->y_stride;
463     for (i = 0; i < width; ++i) {
464       const uint32_t p = src[i];
465       y[i] = VP8RGBToY((p >> 16) & 0xff, (p >> 8) & 0xff, (p >> 0) & 0xff);
466     }
467   }
468 
469   // then U/V planes
470   {
471     uint8_t* const u = buf->u + (y_pos >> 1) * buf->u_stride;
472     uint8_t* const v = buf->v + (y_pos >> 1) * buf->v_stride;
473     const int uv_width = width >> 1;
474     int i;
475     for (i = 0; i < uv_width; ++i) {
476       const uint32_t v0 = src[2 * i + 0];
477       const uint32_t v1 = src[2 * i + 1];
478       // VP8RGBToU/V expects four accumulated pixels. Hence we need to
479       // scale r/g/b value by a factor 2. We just shift v0/v1 one bit less.
480       const int r = ((v0 >> 15) & 0x1fe) + ((v1 >> 15) & 0x1fe);
481       const int g = ((v0 >>  7) & 0x1fe) + ((v1 >>  7) & 0x1fe);
482       const int b = ((v0 <<  1) & 0x1fe) + ((v1 <<  1) & 0x1fe);
483       if (!(y_pos & 1)) {  // even lines: store values
484         u[i] = VP8RGBToU(r, g, b);
485         v[i] = VP8RGBToV(r, g, b);
486       } else {             // odd lines: average with previous values
487         const int tmp_u = VP8RGBToU(r, g, b);
488         const int tmp_v = VP8RGBToV(r, g, b);
489         // Approximated average-of-four. But it's an acceptable diff.
490         u[i] = (u[i] + tmp_u + 1) >> 1;
491         v[i] = (v[i] + tmp_v + 1) >> 1;
492       }
493     }
494     if (width & 1) {       // last pixel
495       const uint32_t v0 = src[2 * i + 0];
496       const int r = (v0 >> 14) & 0x3fc;
497       const int g = (v0 >>  6) & 0x3fc;
498       const int b = (v0 <<  2) & 0x3fc;
499       if (!(y_pos & 1)) {  // even lines
500         u[i] = VP8RGBToU(r, g, b);
501         v[i] = VP8RGBToV(r, g, b);
502       } else {             // odd lines (note: we could just skip this)
503         const int tmp_u = VP8RGBToU(r, g, b);
504         const int tmp_v = VP8RGBToV(r, g, b);
505         u[i] = (u[i] + tmp_u + 1) >> 1;
506         v[i] = (v[i] + tmp_v + 1) >> 1;
507       }
508     }
509   }
510   // Lastly, store alpha if needed.
511   if (buf->a != NULL) {
512     int i;
513     uint8_t* const a = buf->a + y_pos * buf->a_stride;
514     for (i = 0; i < width; ++i) a[i] = (src[i] >> 24);
515   }
516 }
517 
ExportYUVA(const VP8LDecoder * const dec,int y_pos)518 static int ExportYUVA(const VP8LDecoder* const dec, int y_pos) {
519   WebPRescaler* const rescaler = dec->rescaler;
520   const uint32_t* const src = (const uint32_t*)rescaler->dst;
521   const int dst_width = rescaler->dst_width;
522   int num_lines_out = 0;
523   while (WebPRescalerHasPendingOutput(rescaler)) {
524     WebPRescalerExportRow(rescaler);
525     ConvertToYUVA(src, dst_width, y_pos, dec->output_);
526     ++y_pos;
527     ++num_lines_out;
528   }
529   return num_lines_out;
530 }
531 
EmitRescaledRowsYUVA(const VP8LDecoder * const dec,const uint32_t * const data,int in_stride,int mb_h)532 static int EmitRescaledRowsYUVA(const VP8LDecoder* const dec,
533                                 const uint32_t* const data,
534                                 int in_stride, int mb_h) {
535   const uint8_t* const in = (const uint8_t*)data;
536   int num_lines_in = 0;
537   int y_pos = dec->last_out_row_;
538   while (num_lines_in < mb_h) {
539     const uint8_t* const row_in = in + num_lines_in * in_stride;
540     num_lines_in += WebPRescalerImport(dec->rescaler, mb_h - num_lines_in,
541                                        row_in, in_stride);
542     y_pos += ExportYUVA(dec, y_pos);
543   }
544   return y_pos;
545 }
546 
EmitRowsYUVA(const VP8LDecoder * const dec,const uint32_t * const data,int in_stride,int mb_w,int num_rows)547 static int EmitRowsYUVA(const VP8LDecoder* const dec,
548                         const uint32_t* const data, int in_stride,
549                         int mb_w, int num_rows) {
550   int y_pos = dec->last_out_row_;
551   const uint8_t* row_in = (const uint8_t*)data;
552   while (num_rows-- > 0) {
553     ConvertToYUVA((const uint32_t*)row_in, mb_w, y_pos, dec->output_);
554     row_in += in_stride;
555     ++y_pos;
556   }
557   return y_pos;
558 }
559 
560 //------------------------------------------------------------------------------
561 // Cropping.
562 
563 // Sets io->mb_y, io->mb_h & io->mb_w according to start row, end row and
564 // crop options. Also updates the input data pointer, so that it points to the
565 // start of the cropped window.
566 // Note that 'pixel_stride' is in units of 'uint32_t' (and not 'bytes).
567 // Returns true if the crop window is not empty.
SetCropWindow(VP8Io * const io,int y_start,int y_end,const uint32_t ** const in_data,int pixel_stride)568 static int SetCropWindow(VP8Io* const io, int y_start, int y_end,
569                          const uint32_t** const in_data, int pixel_stride) {
570   assert(y_start < y_end);
571   assert(io->crop_left < io->crop_right);
572   if (y_end > io->crop_bottom) {
573     y_end = io->crop_bottom;  // make sure we don't overflow on last row.
574   }
575   if (y_start < io->crop_top) {
576     const int delta = io->crop_top - y_start;
577     y_start = io->crop_top;
578     *in_data += pixel_stride * delta;
579   }
580   if (y_start >= y_end) return 0;  // Crop window is empty.
581 
582   *in_data += io->crop_left;
583 
584   io->mb_y = y_start - io->crop_top;
585   io->mb_w = io->crop_right - io->crop_left;
586   io->mb_h = y_end - y_start;
587   return 1;  // Non-empty crop window.
588 }
589 
590 //------------------------------------------------------------------------------
591 
GetMetaIndex(const uint32_t * const image,int xsize,int bits,int x,int y)592 static WEBP_INLINE int GetMetaIndex(
593     const uint32_t* const image, int xsize, int bits, int x, int y) {
594   if (bits == 0) return 0;
595   return image[xsize * (y >> bits) + (x >> bits)];
596 }
597 
GetHtreeGroupForPos(VP8LMetadata * const hdr,int x,int y)598 static WEBP_INLINE HTreeGroup* GetHtreeGroupForPos(VP8LMetadata* const hdr,
599                                                    int x, int y) {
600   const int meta_index = GetMetaIndex(hdr->huffman_image_, hdr->huffman_xsize_,
601                                       hdr->huffman_subsample_bits_, x, y);
602   assert(meta_index < hdr->num_htree_groups_);
603   return hdr->htree_groups_ + meta_index;
604 }
605 
606 //------------------------------------------------------------------------------
607 // Main loop, with custom row-processing function
608 
609 typedef void (*ProcessRowsFunc)(VP8LDecoder* const dec, int row);
610 
ApplyInverseTransforms(VP8LDecoder * const dec,int num_rows,const uint32_t * const rows)611 static void ApplyInverseTransforms(VP8LDecoder* const dec, int num_rows,
612                                    const uint32_t* const rows) {
613   int n = dec->next_transform_;
614   const int cache_pixs = dec->width_ * num_rows;
615   const int start_row = dec->last_row_;
616   const int end_row = start_row + num_rows;
617   const uint32_t* rows_in = rows;
618   uint32_t* const rows_out = dec->argb_cache_;
619 
620   // Inverse transforms.
621   // TODO: most transforms only need to operate on the cropped region only.
622   memcpy(rows_out, rows_in, cache_pixs * sizeof(*rows_out));
623   while (n-- > 0) {
624     VP8LTransform* const transform = &dec->transforms_[n];
625     VP8LInverseTransform(transform, start_row, end_row, rows_in, rows_out);
626     rows_in = rows_out;
627   }
628 }
629 
630 // Special method for paletted alpha data.
ApplyInverseTransformsAlpha(VP8LDecoder * const dec,int num_rows,const uint8_t * const rows)631 static void ApplyInverseTransformsAlpha(VP8LDecoder* const dec, int num_rows,
632                                         const uint8_t* const rows) {
633   const int start_row = dec->last_row_;
634   const int end_row = start_row + num_rows;
635   const uint8_t* rows_in = rows;
636   uint8_t* rows_out = (uint8_t*)dec->io_->opaque + dec->io_->width * start_row;
637   VP8LTransform* const transform = &dec->transforms_[0];
638   assert(dec->next_transform_ == 1);
639   assert(transform->type_ == COLOR_INDEXING_TRANSFORM);
640   VP8LColorIndexInverseTransformAlpha(transform, start_row, end_row, rows_in,
641                                       rows_out);
642 }
643 
644 // Processes (transforms, scales & color-converts) the rows decoded after the
645 // last call.
ProcessRows(VP8LDecoder * const dec,int row)646 static void ProcessRows(VP8LDecoder* const dec, int row) {
647   const uint32_t* const rows = dec->pixels_ + dec->width_ * dec->last_row_;
648   const int num_rows = row - dec->last_row_;
649 
650   if (num_rows <= 0) return;  // Nothing to be done.
651   ApplyInverseTransforms(dec, num_rows, rows);
652 
653   // Emit output.
654   {
655     VP8Io* const io = dec->io_;
656     const uint32_t* rows_data = dec->argb_cache_;
657     if (!SetCropWindow(io, dec->last_row_, row, &rows_data, io->width)) {
658       // Nothing to output (this time).
659     } else {
660       const WebPDecBuffer* const output = dec->output_;
661       const int in_stride = io->width * sizeof(*rows_data);
662       if (output->colorspace < MODE_YUV) {  // convert to RGBA
663         const WebPRGBABuffer* const buf = &output->u.RGBA;
664         uint8_t* const rgba = buf->rgba + dec->last_out_row_ * buf->stride;
665         const int num_rows_out = io->use_scaling ?
666             EmitRescaledRows(dec, rows_data, in_stride, io->mb_h,
667                              rgba, buf->stride) :
668             EmitRows(output->colorspace, rows_data, in_stride,
669                      io->mb_w, io->mb_h, rgba, buf->stride);
670         // Update 'last_out_row_'.
671         dec->last_out_row_ += num_rows_out;
672       } else {                              // convert to YUVA
673         dec->last_out_row_ = io->use_scaling ?
674             EmitRescaledRowsYUVA(dec, rows_data, in_stride, io->mb_h) :
675             EmitRowsYUVA(dec, rows_data, in_stride, io->mb_w, io->mb_h);
676       }
677       assert(dec->last_out_row_ <= output->height);
678     }
679   }
680 
681   // Update 'last_row_'.
682   dec->last_row_ = row;
683   assert(dec->last_row_ <= dec->height_);
684 }
685 
686 #define DECODE_DATA_FUNC(FUNC_NAME, TYPE, STORE_PIXEL)                         \
687 static int FUNC_NAME(VP8LDecoder* const dec, TYPE* const data, int width,      \
688                      int height, ProcessRowsFunc process_func) {               \
689   int ok = 1;                                                                  \
690   int col = 0, row = 0;                                                        \
691   VP8LBitReader* const br = &dec->br_;                                         \
692   VP8LMetadata* const hdr = &dec->hdr_;                                        \
693   HTreeGroup* htree_group = hdr->htree_groups_;                                \
694   TYPE* src = data;                                                            \
695   TYPE* last_cached = data;                                                    \
696   TYPE* const src_end = data + width * height;                                 \
697   const int len_code_limit = NUM_LITERAL_CODES + NUM_LENGTH_CODES;             \
698   const int color_cache_limit = len_code_limit + hdr->color_cache_size_;       \
699   VP8LColorCache* const color_cache =                                          \
700       (hdr->color_cache_size_ > 0) ? &hdr->color_cache_ : NULL;                \
701   const int mask = hdr->huffman_mask_;                                         \
702   assert(htree_group != NULL);                                                 \
703   while (!br->eos_ && src < src_end) {                                         \
704     int code;                                                                  \
705     /* Only update when changing tile. Note we could use this test:        */  \
706     /* if "((((prev_col ^ col) | prev_row ^ row)) > mask)" -> tile changed */  \
707     /* but that's actually slower and needs storing the previous col/row.  */  \
708     if ((col & mask) == 0) {                                                   \
709       htree_group = GetHtreeGroupForPos(hdr, col, row);                        \
710     }                                                                          \
711     VP8LFillBitWindow(br);                                                     \
712     code = ReadSymbol(&htree_group->htrees_[GREEN], br);                       \
713     if (code < NUM_LITERAL_CODES) {  /* Literal*/                              \
714       int red, green, blue, alpha;                                             \
715       red = ReadSymbol(&htree_group->htrees_[RED], br);                        \
716       green = code;                                                            \
717       VP8LFillBitWindow(br);                                                   \
718       blue = ReadSymbol(&htree_group->htrees_[BLUE], br);                      \
719       alpha = ReadSymbol(&htree_group->htrees_[ALPHA], br);                    \
720       *src = STORE_PIXEL(alpha, red, green, blue);                             \
721     AdvanceByOne:                                                              \
722       ++src;                                                                   \
723       ++col;                                                                   \
724       if (col >= width) {                                                      \
725         col = 0;                                                               \
726         ++row;                                                                 \
727         if ((process_func != NULL) && (row % NUM_ARGB_CACHE_ROWS == 0)) {      \
728           process_func(dec, row);                                              \
729         }                                                                      \
730         if (color_cache != NULL) {                                             \
731           while (last_cached < src) {                                          \
732             VP8LColorCacheInsert(color_cache, *last_cached++);                 \
733           }                                                                    \
734         }                                                                      \
735       }                                                                        \
736     } else if (code < len_code_limit) {  /* Backward reference */              \
737       int dist_code, dist;                                                     \
738       const int length_sym = code - NUM_LITERAL_CODES;                         \
739       const int length = GetCopyLength(length_sym, br);                        \
740       const int dist_symbol = ReadSymbol(&htree_group->htrees_[DIST], br);     \
741       VP8LFillBitWindow(br);                                                   \
742       dist_code = GetCopyDistance(dist_symbol, br);                            \
743       dist = PlaneCodeToDistance(width, dist_code);                            \
744       if (src - data < dist || src_end - src < length) {                       \
745         ok = 0;                                                                \
746         goto End;                                                              \
747       }                                                                        \
748       {                                                                        \
749         int i;                                                                 \
750         for (i = 0; i < length; ++i) src[i] = src[i - dist];                   \
751         src += length;                                                         \
752       }                                                                        \
753       col += length;                                                           \
754       while (col >= width) {                                                   \
755         col -= width;                                                          \
756         ++row;                                                                 \
757         if ((process_func != NULL) && (row % NUM_ARGB_CACHE_ROWS == 0)) {      \
758           process_func(dec, row);                                              \
759         }                                                                      \
760       }                                                                        \
761       if (src < src_end) {                                                     \
762         htree_group = GetHtreeGroupForPos(hdr, col, row);                      \
763         if (color_cache != NULL) {                                             \
764           while (last_cached < src) {                                          \
765             VP8LColorCacheInsert(color_cache, *last_cached++);                 \
766           }                                                                    \
767         }                                                                      \
768       }                                                                        \
769     } else if (code < color_cache_limit) {  /* Color cache */                  \
770       const int key = code - len_code_limit;                                   \
771       assert(color_cache != NULL);                                             \
772       while (last_cached < src) {                                              \
773         VP8LColorCacheInsert(color_cache, *last_cached++);                     \
774       }                                                                        \
775       *src = VP8LColorCacheLookup(color_cache, key);                           \
776       goto AdvanceByOne;                                                       \
777     } else {  /* Not reached */                                                \
778       ok = 0;                                                                  \
779       goto End;                                                                \
780     }                                                                          \
781     ok = !br->error_;                                                          \
782     if (!ok) goto End;                                                         \
783   }                                                                            \
784   /* Process the remaining rows corresponding to last row-block. */            \
785   if (process_func != NULL) process_func(dec, row);                            \
786 End:                                                                           \
787   if (br->error_ || !ok || (br->eos_ && src < src_end)) {                      \
788     ok = 0;                                                                    \
789     dec->status_ =                                                             \
790         (!br->eos_) ? VP8_STATUS_BITSTREAM_ERROR : VP8_STATUS_SUSPENDED;       \
791   } else if (src == src_end) {                                                 \
792     dec->state_ = READ_DATA;                                                   \
793   }                                                                            \
794   return ok;                                                                   \
795 }
796 
GetARGBPixel(int alpha,int red,int green,int blue)797 static WEBP_INLINE uint32_t GetARGBPixel(int alpha, int red, int green,
798                                          int blue) {
799   return (alpha << 24) | (red << 16) | (green << 8) | blue;
800 }
801 
GetAlphaPixel(int alpha,int red,int green,int blue)802 static WEBP_INLINE uint8_t GetAlphaPixel(int alpha, int red, int green,
803                                          int blue) {
804   (void)alpha;
805   (void)red;
806   (void)blue;
807   return green;  // Alpha value is stored in green channel.
808 }
809 
DECODE_DATA_FUNC(DecodeImageData,uint32_t,GetARGBPixel)810 DECODE_DATA_FUNC(DecodeImageData, uint32_t, GetARGBPixel)
811 DECODE_DATA_FUNC(DecodeAlphaData, uint8_t, GetAlphaPixel)
812 
813 #undef DECODE_DATA_FUNC
814 
815 // -----------------------------------------------------------------------------
816 // VP8LTransform
817 
818 static void ClearTransform(VP8LTransform* const transform) {
819   free(transform->data_);
820   transform->data_ = NULL;
821 }
822 
823 // For security reason, we need to remap the color map to span
824 // the total possible bundled values, and not just the num_colors.
ExpandColorMap(int num_colors,VP8LTransform * const transform)825 static int ExpandColorMap(int num_colors, VP8LTransform* const transform) {
826   int i;
827   const int final_num_colors = 1 << (8 >> transform->bits_);
828   uint32_t* const new_color_map =
829       (uint32_t*)WebPSafeMalloc((uint64_t)final_num_colors,
830                                 sizeof(*new_color_map));
831   if (new_color_map == NULL) {
832     return 0;
833   } else {
834     uint8_t* const data = (uint8_t*)transform->data_;
835     uint8_t* const new_data = (uint8_t*)new_color_map;
836     new_color_map[0] = transform->data_[0];
837     for (i = 4; i < 4 * num_colors; ++i) {
838       // Equivalent to AddPixelEq(), on a byte-basis.
839       new_data[i] = (data[i] + new_data[i - 4]) & 0xff;
840     }
841     for (; i < 4 * final_num_colors; ++i)
842       new_data[i] = 0;  // black tail.
843     free(transform->data_);
844     transform->data_ = new_color_map;
845   }
846   return 1;
847 }
848 
ReadTransform(int * const xsize,int const * ysize,VP8LDecoder * const dec)849 static int ReadTransform(int* const xsize, int const* ysize,
850                          VP8LDecoder* const dec) {
851   int ok = 1;
852   VP8LBitReader* const br = &dec->br_;
853   VP8LTransform* transform = &dec->transforms_[dec->next_transform_];
854   const VP8LImageTransformType type =
855       (VP8LImageTransformType)VP8LReadBits(br, 2);
856 
857   // Each transform type can only be present once in the stream.
858   if (dec->transforms_seen_ & (1U << type)) {
859     return 0;  // Already there, let's not accept the second same transform.
860   }
861   dec->transforms_seen_ |= (1U << type);
862 
863   transform->type_ = type;
864   transform->xsize_ = *xsize;
865   transform->ysize_ = *ysize;
866   transform->data_ = NULL;
867   ++dec->next_transform_;
868   assert(dec->next_transform_ <= NUM_TRANSFORMS);
869 
870   switch (type) {
871     case PREDICTOR_TRANSFORM:
872     case CROSS_COLOR_TRANSFORM:
873       transform->bits_ = VP8LReadBits(br, 3) + 2;
874       ok = DecodeImageStream(VP8LSubSampleSize(transform->xsize_,
875                                                transform->bits_),
876                              VP8LSubSampleSize(transform->ysize_,
877                                                transform->bits_),
878                              0, dec, &transform->data_);
879       break;
880     case COLOR_INDEXING_TRANSFORM: {
881        const int num_colors = VP8LReadBits(br, 8) + 1;
882        const int bits = (num_colors > 16) ? 0
883                       : (num_colors > 4) ? 1
884                       : (num_colors > 2) ? 2
885                       : 3;
886        *xsize = VP8LSubSampleSize(transform->xsize_, bits);
887        transform->bits_ = bits;
888        ok = DecodeImageStream(num_colors, 1, 0, dec, &transform->data_);
889        ok = ok && ExpandColorMap(num_colors, transform);
890       break;
891     }
892     case SUBTRACT_GREEN:
893       break;
894     default:
895       assert(0);    // can't happen
896       break;
897   }
898 
899   return ok;
900 }
901 
902 // -----------------------------------------------------------------------------
903 // VP8LMetadata
904 
InitMetadata(VP8LMetadata * const hdr)905 static void InitMetadata(VP8LMetadata* const hdr) {
906   assert(hdr);
907   memset(hdr, 0, sizeof(*hdr));
908 }
909 
ClearMetadata(VP8LMetadata * const hdr)910 static void ClearMetadata(VP8LMetadata* const hdr) {
911   assert(hdr);
912 
913   free(hdr->huffman_image_);
914   DeleteHtreeGroups(hdr->htree_groups_, hdr->num_htree_groups_);
915   VP8LColorCacheClear(&hdr->color_cache_);
916   InitMetadata(hdr);
917 }
918 
919 // -----------------------------------------------------------------------------
920 // VP8LDecoder
921 
VP8LNew(void)922 VP8LDecoder* VP8LNew(void) {
923   VP8LDecoder* const dec = (VP8LDecoder*)calloc(1, sizeof(*dec));
924   if (dec == NULL) return NULL;
925   dec->status_ = VP8_STATUS_OK;
926   dec->action_ = READ_DIM;
927   dec->state_ = READ_DIM;
928   return dec;
929 }
930 
VP8LClear(VP8LDecoder * const dec)931 void VP8LClear(VP8LDecoder* const dec) {
932   int i;
933   if (dec == NULL) return;
934   ClearMetadata(&dec->hdr_);
935 
936   free(dec->pixels_);
937   dec->pixels_ = NULL;
938   for (i = 0; i < dec->next_transform_; ++i) {
939     ClearTransform(&dec->transforms_[i]);
940   }
941   dec->next_transform_ = 0;
942   dec->transforms_seen_ = 0;
943 
944   free(dec->rescaler_memory);
945   dec->rescaler_memory = NULL;
946 
947   dec->output_ = NULL;   // leave no trace behind
948 }
949 
VP8LDelete(VP8LDecoder * const dec)950 void VP8LDelete(VP8LDecoder* const dec) {
951   if (dec != NULL) {
952     VP8LClear(dec);
953     free(dec);
954   }
955 }
956 
UpdateDecoder(VP8LDecoder * const dec,int width,int height)957 static void UpdateDecoder(VP8LDecoder* const dec, int width, int height) {
958   VP8LMetadata* const hdr = &dec->hdr_;
959   const int num_bits = hdr->huffman_subsample_bits_;
960   dec->width_ = width;
961   dec->height_ = height;
962 
963   hdr->huffman_xsize_ = VP8LSubSampleSize(width, num_bits);
964   hdr->huffman_mask_ = (num_bits == 0) ? ~0 : (1 << num_bits) - 1;
965 }
966 
DecodeImageStream(int xsize,int ysize,int is_level0,VP8LDecoder * const dec,uint32_t ** const decoded_data)967 static int DecodeImageStream(int xsize, int ysize,
968                              int is_level0,
969                              VP8LDecoder* const dec,
970                              uint32_t** const decoded_data) {
971   int ok = 1;
972   int transform_xsize = xsize;
973   int transform_ysize = ysize;
974   VP8LBitReader* const br = &dec->br_;
975   VP8LMetadata* const hdr = &dec->hdr_;
976   uint32_t* data = NULL;
977   int color_cache_bits = 0;
978 
979   // Read the transforms (may recurse).
980   if (is_level0) {
981     while (ok && VP8LReadBits(br, 1)) {
982       ok = ReadTransform(&transform_xsize, &transform_ysize, dec);
983     }
984   }
985 
986   // Color cache
987   if (ok && VP8LReadBits(br, 1)) {
988     color_cache_bits = VP8LReadBits(br, 4);
989     ok = (color_cache_bits >= 1 && color_cache_bits <= MAX_CACHE_BITS);
990     if (!ok) {
991       dec->status_ = VP8_STATUS_BITSTREAM_ERROR;
992       goto End;
993     }
994   }
995 
996   // Read the Huffman codes (may recurse).
997   ok = ok && ReadHuffmanCodes(dec, transform_xsize, transform_ysize,
998                               color_cache_bits, is_level0);
999   if (!ok) {
1000     dec->status_ = VP8_STATUS_BITSTREAM_ERROR;
1001     goto End;
1002   }
1003 
1004   // Finish setting up the color-cache
1005   if (color_cache_bits > 0) {
1006     hdr->color_cache_size_ = 1 << color_cache_bits;
1007     if (!VP8LColorCacheInit(&hdr->color_cache_, color_cache_bits)) {
1008       dec->status_ = VP8_STATUS_OUT_OF_MEMORY;
1009       ok = 0;
1010       goto End;
1011     }
1012   } else {
1013     hdr->color_cache_size_ = 0;
1014   }
1015   UpdateDecoder(dec, transform_xsize, transform_ysize);
1016 
1017   if (is_level0) {   // level 0 complete
1018     dec->state_ = READ_HDR;
1019     goto End;
1020   }
1021 
1022   {
1023     const uint64_t total_size = (uint64_t)transform_xsize * transform_ysize;
1024     data = (uint32_t*)WebPSafeMalloc(total_size, sizeof(*data));
1025     if (data == NULL) {
1026       dec->status_ = VP8_STATUS_OUT_OF_MEMORY;
1027       ok = 0;
1028       goto End;
1029     }
1030   }
1031 
1032   // Use the Huffman trees to decode the LZ77 encoded data.
1033   ok = DecodeImageData(dec, data, transform_xsize, transform_ysize, NULL);
1034   ok = ok && !br->error_;
1035 
1036  End:
1037 
1038   if (!ok) {
1039     free(data);
1040     ClearMetadata(hdr);
1041     // If not enough data (br.eos_) resulted in BIT_STREAM_ERROR, update the
1042     // status appropriately.
1043     if (dec->status_ == VP8_STATUS_BITSTREAM_ERROR && dec->br_.eos_) {
1044       dec->status_ = VP8_STATUS_SUSPENDED;
1045     }
1046   } else {
1047     if (decoded_data != NULL) {
1048       *decoded_data = data;
1049     } else {
1050       // We allocate image data in this function only for transforms. At level 0
1051       // (that is: not the transforms), we shouldn't have allocated anything.
1052       assert(data == NULL);
1053       assert(is_level0);
1054     }
1055     if (!is_level0) ClearMetadata(hdr);  // Clean up temporary data behind.
1056   }
1057   return ok;
1058 }
1059 
1060 //------------------------------------------------------------------------------
1061 // Allocate internal buffers dec->pixels_ and dec->argb_cache_.
AllocateInternalBuffers(VP8LDecoder * const dec,int final_width,size_t bytes_per_pixel)1062 static int AllocateInternalBuffers(VP8LDecoder* const dec, int final_width,
1063                                    size_t bytes_per_pixel) {
1064   const int argb_cache_needed = (bytes_per_pixel == sizeof(uint32_t));
1065   const uint64_t num_pixels = (uint64_t)dec->width_ * dec->height_;
1066   // Scratch buffer corresponding to top-prediction row for transforming the
1067   // first row in the row-blocks. Not needed for paletted alpha.
1068   const uint64_t cache_top_pixels =
1069       argb_cache_needed ? (uint16_t)final_width : 0ULL;
1070   // Scratch buffer for temporary BGRA storage. Not needed for paletted alpha.
1071   const uint64_t cache_pixels =
1072       argb_cache_needed ? (uint64_t)final_width * NUM_ARGB_CACHE_ROWS : 0ULL;
1073   const uint64_t total_num_pixels =
1074       num_pixels + cache_top_pixels + cache_pixels;
1075 
1076   assert(dec->width_ <= final_width);
1077   dec->pixels_ = (uint32_t*)WebPSafeMalloc(total_num_pixels, bytes_per_pixel);
1078   if (dec->pixels_ == NULL) {
1079     dec->argb_cache_ = NULL;    // for sanity check
1080     dec->status_ = VP8_STATUS_OUT_OF_MEMORY;
1081     return 0;
1082   }
1083   dec->argb_cache_ =
1084       argb_cache_needed ? dec->pixels_ + num_pixels + cache_top_pixels : NULL;
1085   return 1;
1086 }
1087 
1088 //------------------------------------------------------------------------------
1089 
1090 // Special row-processing that only stores the alpha data.
ExtractAlphaRows(VP8LDecoder * const dec,int row)1091 static void ExtractAlphaRows(VP8LDecoder* const dec, int row) {
1092   const int num_rows = row - dec->last_row_;
1093   const uint32_t* const in = dec->pixels_ + dec->width_ * dec->last_row_;
1094 
1095   if (num_rows <= 0) return;  // Nothing to be done.
1096   ApplyInverseTransforms(dec, num_rows, in);
1097 
1098   // Extract alpha (which is stored in the green plane).
1099   {
1100     const int width = dec->io_->width;      // the final width (!= dec->width_)
1101     const int cache_pixs = width * num_rows;
1102     uint8_t* const dst = (uint8_t*)dec->io_->opaque + width * dec->last_row_;
1103     const uint32_t* const src = dec->argb_cache_;
1104     int i;
1105     for (i = 0; i < cache_pixs; ++i) dst[i] = (src[i] >> 8) & 0xff;
1106   }
1107   dec->last_row_ = dec->last_out_row_ = row;
1108 }
1109 
1110 // Row-processing for the special case when alpha data contains only one
1111 // transform: color indexing.
ExtractPalettedAlphaRows(VP8LDecoder * const dec,int row)1112 static void ExtractPalettedAlphaRows(VP8LDecoder* const dec, int row) {
1113   const int num_rows = row - dec->last_row_;
1114   const uint8_t* const in =
1115       (uint8_t*)dec->pixels_ + dec->width_ * dec->last_row_;
1116   if (num_rows <= 0) return;  // Nothing to be done.
1117   ApplyInverseTransformsAlpha(dec, num_rows, in);
1118   dec->last_row_ = dec->last_out_row_ = row;
1119 }
1120 
VP8LDecodeAlphaImageStream(int width,int height,const uint8_t * const data,size_t data_size,uint8_t * const output)1121 int VP8LDecodeAlphaImageStream(int width, int height, const uint8_t* const data,
1122                                size_t data_size, uint8_t* const output) {
1123   VP8Io io;
1124   int ok = 0;
1125   VP8LDecoder* const dec = VP8LNew();
1126   size_t bytes_per_pixel = sizeof(uint32_t);  // Default: BGRA mode.
1127   if (dec == NULL) return 0;
1128 
1129   dec->width_ = width;
1130   dec->height_ = height;
1131   dec->io_ = &io;
1132 
1133   VP8InitIo(&io);
1134   WebPInitCustomIo(NULL, &io);    // Just a sanity Init. io won't be used.
1135   io.opaque = output;
1136   io.width = width;
1137   io.height = height;
1138 
1139   dec->status_ = VP8_STATUS_OK;
1140   VP8LInitBitReader(&dec->br_, data, data_size);
1141 
1142   dec->action_ = READ_HDR;
1143   if (!DecodeImageStream(width, height, 1, dec, NULL)) goto Err;
1144 
1145   // Special case: if alpha data uses only the color indexing transform and
1146   // doesn't use color cache (a frequent case), we will use DecodeAlphaData()
1147   // method that only needs allocation of 1 byte per pixel (alpha channel).
1148   if (dec->next_transform_ == 1 &&
1149       dec->transforms_[0].type_ == COLOR_INDEXING_TRANSFORM &&
1150       dec->hdr_.color_cache_size_ == 0) {
1151     bytes_per_pixel = sizeof(uint8_t);
1152   }
1153 
1154   // Allocate internal buffers (note that dec->width_ may have changed here).
1155   if (!AllocateInternalBuffers(dec, width, bytes_per_pixel)) goto Err;
1156 
1157   // Decode (with special row processing).
1158   dec->action_ = READ_DATA;
1159   ok = (bytes_per_pixel == sizeof(uint8_t)) ?
1160       DecodeAlphaData(dec, (uint8_t*)dec->pixels_, dec->width_, dec->height_,
1161                       ExtractPalettedAlphaRows) :
1162       DecodeImageData(dec, dec->pixels_, dec->width_, dec->height_,
1163                       ExtractAlphaRows);
1164 
1165  Err:
1166   VP8LDelete(dec);
1167   return ok;
1168 }
1169 
1170 //------------------------------------------------------------------------------
1171 
VP8LDecodeHeader(VP8LDecoder * const dec,VP8Io * const io)1172 int VP8LDecodeHeader(VP8LDecoder* const dec, VP8Io* const io) {
1173   int width, height, has_alpha;
1174 
1175   if (dec == NULL) return 0;
1176   if (io == NULL) {
1177     dec->status_ = VP8_STATUS_INVALID_PARAM;
1178     return 0;
1179   }
1180 
1181   dec->io_ = io;
1182   dec->status_ = VP8_STATUS_OK;
1183   VP8LInitBitReader(&dec->br_, io->data, io->data_size);
1184   if (!ReadImageInfo(&dec->br_, &width, &height, &has_alpha)) {
1185     dec->status_ = VP8_STATUS_BITSTREAM_ERROR;
1186     goto Error;
1187   }
1188   dec->state_ = READ_DIM;
1189   io->width = width;
1190   io->height = height;
1191 
1192   dec->action_ = READ_HDR;
1193   if (!DecodeImageStream(width, height, 1, dec, NULL)) goto Error;
1194   return 1;
1195 
1196  Error:
1197   VP8LClear(dec);
1198   assert(dec->status_ != VP8_STATUS_OK);
1199   return 0;
1200 }
1201 
VP8LDecodeImage(VP8LDecoder * const dec)1202 int VP8LDecodeImage(VP8LDecoder* const dec) {
1203   const size_t bytes_per_pixel = sizeof(uint32_t);
1204   VP8Io* io = NULL;
1205   WebPDecParams* params = NULL;
1206 
1207   // Sanity checks.
1208   if (dec == NULL) return 0;
1209 
1210   io = dec->io_;
1211   assert(io != NULL);
1212   params = (WebPDecParams*)io->opaque;
1213   assert(params != NULL);
1214   dec->output_ = params->output;
1215   assert(dec->output_ != NULL);
1216 
1217   // Initialization.
1218   if (!WebPIoInitFromOptions(params->options, io, MODE_BGRA)) {
1219     dec->status_ = VP8_STATUS_INVALID_PARAM;
1220     goto Err;
1221   }
1222 
1223   if (!AllocateInternalBuffers(dec, io->width, bytes_per_pixel)) goto Err;
1224 
1225   if (io->use_scaling && !AllocateAndInitRescaler(dec, io)) goto Err;
1226 
1227   // Decode.
1228   dec->action_ = READ_DATA;
1229   if (!DecodeImageData(dec, dec->pixels_, dec->width_, dec->height_,
1230                        ProcessRows)) {
1231     goto Err;
1232   }
1233 
1234   // Cleanup.
1235   params->last_y = dec->last_out_row_;
1236   VP8LClear(dec);
1237   return 1;
1238 
1239  Err:
1240   VP8LClear(dec);
1241   assert(dec->status_ != VP8_STATUS_OK);
1242   return 0;
1243 }
1244 
1245 //------------------------------------------------------------------------------
1246 
1247 #if defined(__cplusplus) || defined(c_plusplus)
1248 }    // extern "C"
1249 #endif
1250