• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2011 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 // Incremental decoding
11 //
12 // Author: somnath@google.com (Somnath Banerjee)
13 
14 #include <assert.h>
15 #include <string.h>
16 #include <stdlib.h>
17 
18 #include "src/dec/alphai_dec.h"
19 #include "src/dec/webpi_dec.h"
20 #include "src/dec/vp8i_dec.h"
21 #include "src/utils/utils.h"
22 
23 // In append mode, buffer allocations increase as multiples of this value.
24 // Needs to be a power of 2.
25 #define CHUNK_SIZE 4096
26 #define MAX_MB_SIZE 4096
27 
28 //------------------------------------------------------------------------------
29 // Data structures for memory and states
30 
31 // Decoding states. State normally flows as:
32 // WEBP_HEADER->VP8_HEADER->VP8_PARTS0->VP8_DATA->DONE for a lossy image, and
33 // WEBP_HEADER->VP8L_HEADER->VP8L_DATA->DONE for a lossless image.
34 // If there is any error the decoder goes into state ERROR.
35 typedef enum {
36   STATE_WEBP_HEADER,  // All the data before that of the VP8/VP8L chunk.
37   STATE_VP8_HEADER,   // The VP8 Frame header (within the VP8 chunk).
38   STATE_VP8_PARTS0,
39   STATE_VP8_DATA,
40   STATE_VP8L_HEADER,
41   STATE_VP8L_DATA,
42   STATE_DONE,
43   STATE_ERROR
44 } DecState;
45 
46 // Operating state for the MemBuffer
47 typedef enum {
48   MEM_MODE_NONE = 0,
49   MEM_MODE_APPEND,
50   MEM_MODE_MAP
51 } MemBufferMode;
52 
53 // storage for partition #0 and partial data (in a rolling fashion)
54 typedef struct {
55   MemBufferMode mode_;  // Operation mode
56   size_t start_;        // start location of the data to be decoded
57   size_t end_;          // end location
58   size_t buf_size_;     // size of the allocated buffer
59   uint8_t* buf_;        // We don't own this buffer in case WebPIUpdate()
60 
61   size_t part0_size_;         // size of partition #0
62   const uint8_t* part0_buf_;  // buffer to store partition #0
63 } MemBuffer;
64 
65 struct WebPIDecoder {
66   DecState state_;         // current decoding state
67   WebPDecParams params_;   // Params to store output info
68   int is_lossless_;        // for down-casting 'dec_'.
69   void* dec_;              // either a VP8Decoder or a VP8LDecoder instance
70   VP8Io io_;
71 
72   MemBuffer mem_;          // input memory buffer.
73   WebPDecBuffer output_;   // output buffer (when no external one is supplied,
74                            // or if the external one has slow-memory)
75   WebPDecBuffer* final_output_;  // Slow-memory output to copy to eventually.
76   size_t chunk_size_;      // Compressed VP8/VP8L size extracted from Header.
77 
78   int last_mb_y_;          // last row reached for intra-mode decoding
79 };
80 
81 // MB context to restore in case VP8DecodeMB() fails
82 typedef struct {
83   VP8MB left_;
84   VP8MB info_;
85   VP8BitReader token_br_;
86 } MBContext;
87 
88 //------------------------------------------------------------------------------
89 // MemBuffer: incoming data handling
90 
MemDataSize(const MemBuffer * mem)91 static WEBP_INLINE size_t MemDataSize(const MemBuffer* mem) {
92   return (mem->end_ - mem->start_);
93 }
94 
95 // Check if we need to preserve the compressed alpha data, as it may not have
96 // been decoded yet.
NeedCompressedAlpha(const WebPIDecoder * const idec)97 static int NeedCompressedAlpha(const WebPIDecoder* const idec) {
98   if (idec->state_ == STATE_WEBP_HEADER) {
99     // We haven't parsed the headers yet, so we don't know whether the image is
100     // lossy or lossless. This also means that we haven't parsed the ALPH chunk.
101     return 0;
102   }
103   if (idec->is_lossless_) {
104     return 0;  // ALPH chunk is not present for lossless images.
105   } else {
106     const VP8Decoder* const dec = (VP8Decoder*)idec->dec_;
107     assert(dec != NULL);  // Must be true as idec->state_ != STATE_WEBP_HEADER.
108     return (dec->alpha_data_ != NULL) && !dec->is_alpha_decoded_;
109   }
110 }
111 
DoRemap(WebPIDecoder * const idec,ptrdiff_t offset)112 static void DoRemap(WebPIDecoder* const idec, ptrdiff_t offset) {
113   MemBuffer* const mem = &idec->mem_;
114   const uint8_t* const new_base = mem->buf_ + mem->start_;
115   // note: for VP8, setting up idec->io_ is only really needed at the beginning
116   // of the decoding, till partition #0 is complete.
117   idec->io_.data = new_base;
118   idec->io_.data_size = MemDataSize(mem);
119 
120   if (idec->dec_ != NULL) {
121     if (!idec->is_lossless_) {
122       VP8Decoder* const dec = (VP8Decoder*)idec->dec_;
123       const uint32_t last_part = dec->num_parts_minus_one_;
124       if (offset != 0) {
125         uint32_t p;
126         for (p = 0; p <= last_part; ++p) {
127           VP8RemapBitReader(dec->parts_ + p, offset);
128         }
129         // Remap partition #0 data pointer to new offset, but only in MAP
130         // mode (in APPEND mode, partition #0 is copied into a fixed memory).
131         if (mem->mode_ == MEM_MODE_MAP) {
132           VP8RemapBitReader(&dec->br_, offset);
133         }
134       }
135       {
136         const uint8_t* const last_start = dec->parts_[last_part].buf_;
137         VP8BitReaderSetBuffer(&dec->parts_[last_part], last_start,
138                               mem->buf_ + mem->end_ - last_start);
139       }
140       if (NeedCompressedAlpha(idec)) {
141         ALPHDecoder* const alph_dec = dec->alph_dec_;
142         dec->alpha_data_ += offset;
143         if (alph_dec != NULL && alph_dec->vp8l_dec_ != NULL) {
144           if (alph_dec->method_ == ALPHA_LOSSLESS_COMPRESSION) {
145             VP8LDecoder* const alph_vp8l_dec = alph_dec->vp8l_dec_;
146             assert(dec->alpha_data_size_ >= ALPHA_HEADER_LEN);
147             VP8LBitReaderSetBuffer(&alph_vp8l_dec->br_,
148                                    dec->alpha_data_ + ALPHA_HEADER_LEN,
149                                    dec->alpha_data_size_ - ALPHA_HEADER_LEN);
150           } else {  // alph_dec->method_ == ALPHA_NO_COMPRESSION
151             // Nothing special to do in this case.
152           }
153         }
154       }
155     } else {    // Resize lossless bitreader
156       VP8LDecoder* const dec = (VP8LDecoder*)idec->dec_;
157       VP8LBitReaderSetBuffer(&dec->br_, new_base, MemDataSize(mem));
158     }
159   }
160 }
161 
162 // Appends data to the end of MemBuffer->buf_. It expands the allocated memory
163 // size if required and also updates VP8BitReader's if new memory is allocated.
AppendToMemBuffer(WebPIDecoder * const idec,const uint8_t * const data,size_t data_size)164 static int AppendToMemBuffer(WebPIDecoder* const idec,
165                              const uint8_t* const data, size_t data_size) {
166   VP8Decoder* const dec = (VP8Decoder*)idec->dec_;
167   MemBuffer* const mem = &idec->mem_;
168   const int need_compressed_alpha = NeedCompressedAlpha(idec);
169   const uint8_t* const old_start = mem->buf_ + mem->start_;
170   const uint8_t* const old_base =
171       need_compressed_alpha ? dec->alpha_data_ : old_start;
172   assert(mem->mode_ == MEM_MODE_APPEND);
173   if (data_size > MAX_CHUNK_PAYLOAD) {
174     // security safeguard: trying to allocate more than what the format
175     // allows for a chunk should be considered a smoke smell.
176     return 0;
177   }
178 
179   if (mem->end_ + data_size > mem->buf_size_) {  // Need some free memory
180     const size_t new_mem_start = old_start - old_base;
181     const size_t current_size = MemDataSize(mem) + new_mem_start;
182     const uint64_t new_size = (uint64_t)current_size + data_size;
183     const uint64_t extra_size = (new_size + CHUNK_SIZE - 1) & ~(CHUNK_SIZE - 1);
184     uint8_t* const new_buf =
185         (uint8_t*)WebPSafeMalloc(extra_size, sizeof(*new_buf));
186     if (new_buf == NULL) return 0;
187     memcpy(new_buf, old_base, current_size);
188     WebPSafeFree(mem->buf_);
189     mem->buf_ = new_buf;
190     mem->buf_size_ = (size_t)extra_size;
191     mem->start_ = new_mem_start;
192     mem->end_ = current_size;
193   }
194 
195   memcpy(mem->buf_ + mem->end_, data, data_size);
196   mem->end_ += data_size;
197   assert(mem->end_ <= mem->buf_size_);
198 
199   DoRemap(idec, mem->buf_ + mem->start_ - old_start);
200   return 1;
201 }
202 
RemapMemBuffer(WebPIDecoder * const idec,const uint8_t * const data,size_t data_size)203 static int RemapMemBuffer(WebPIDecoder* const idec,
204                           const uint8_t* const data, size_t data_size) {
205   MemBuffer* const mem = &idec->mem_;
206   const uint8_t* const old_buf = mem->buf_;
207   const uint8_t* const old_start = old_buf + mem->start_;
208   assert(mem->mode_ == MEM_MODE_MAP);
209 
210   if (data_size < mem->buf_size_) return 0;  // can't remap to a shorter buffer!
211 
212   mem->buf_ = (uint8_t*)data;
213   mem->end_ = mem->buf_size_ = data_size;
214 
215   DoRemap(idec, mem->buf_ + mem->start_ - old_start);
216   return 1;
217 }
218 
InitMemBuffer(MemBuffer * const mem)219 static void InitMemBuffer(MemBuffer* const mem) {
220   mem->mode_       = MEM_MODE_NONE;
221   mem->buf_        = NULL;
222   mem->buf_size_   = 0;
223   mem->part0_buf_  = NULL;
224   mem->part0_size_ = 0;
225 }
226 
ClearMemBuffer(MemBuffer * const mem)227 static void ClearMemBuffer(MemBuffer* const mem) {
228   assert(mem);
229   if (mem->mode_ == MEM_MODE_APPEND) {
230     WebPSafeFree(mem->buf_);
231     WebPSafeFree((void*)mem->part0_buf_);
232   }
233 }
234 
CheckMemBufferMode(MemBuffer * const mem,MemBufferMode expected)235 static int CheckMemBufferMode(MemBuffer* const mem, MemBufferMode expected) {
236   if (mem->mode_ == MEM_MODE_NONE) {
237     mem->mode_ = expected;    // switch to the expected mode
238   } else if (mem->mode_ != expected) {
239     return 0;         // we mixed the modes => error
240   }
241   assert(mem->mode_ == expected);   // mode is ok
242   return 1;
243 }
244 
245 // To be called last.
FinishDecoding(WebPIDecoder * const idec)246 static VP8StatusCode FinishDecoding(WebPIDecoder* const idec) {
247   const WebPDecoderOptions* const options = idec->params_.options;
248   WebPDecBuffer* const output = idec->params_.output;
249 
250   idec->state_ = STATE_DONE;
251   if (options != NULL && options->flip) {
252     const VP8StatusCode status = WebPFlipBuffer(output);
253     if (status != VP8_STATUS_OK) return status;
254   }
255   if (idec->final_output_ != NULL) {
256     WebPCopyDecBufferPixels(output, idec->final_output_);  // do the slow-copy
257     WebPFreeDecBuffer(&idec->output_);
258     *output = *idec->final_output_;
259     idec->final_output_ = NULL;
260   }
261   return VP8_STATUS_OK;
262 }
263 
264 //------------------------------------------------------------------------------
265 // Macroblock-decoding contexts
266 
SaveContext(const VP8Decoder * dec,const VP8BitReader * token_br,MBContext * const context)267 static void SaveContext(const VP8Decoder* dec, const VP8BitReader* token_br,
268                         MBContext* const context) {
269   context->left_ = dec->mb_info_[-1];
270   context->info_ = dec->mb_info_[dec->mb_x_];
271   context->token_br_ = *token_br;
272 }
273 
RestoreContext(const MBContext * context,VP8Decoder * const dec,VP8BitReader * const token_br)274 static void RestoreContext(const MBContext* context, VP8Decoder* const dec,
275                            VP8BitReader* const token_br) {
276   dec->mb_info_[-1] = context->left_;
277   dec->mb_info_[dec->mb_x_] = context->info_;
278   *token_br = context->token_br_;
279 }
280 
281 //------------------------------------------------------------------------------
282 
IDecError(WebPIDecoder * const idec,VP8StatusCode error)283 static VP8StatusCode IDecError(WebPIDecoder* const idec, VP8StatusCode error) {
284   if (idec->state_ == STATE_VP8_DATA) {
285     // Synchronize the thread, clean-up and check for errors.
286     VP8ExitCritical((VP8Decoder*)idec->dec_, &idec->io_);
287   }
288   idec->state_ = STATE_ERROR;
289   return error;
290 }
291 
ChangeState(WebPIDecoder * const idec,DecState new_state,size_t consumed_bytes)292 static void ChangeState(WebPIDecoder* const idec, DecState new_state,
293                         size_t consumed_bytes) {
294   MemBuffer* const mem = &idec->mem_;
295   idec->state_ = new_state;
296   mem->start_ += consumed_bytes;
297   assert(mem->start_ <= mem->end_);
298   idec->io_.data = mem->buf_ + mem->start_;
299   idec->io_.data_size = MemDataSize(mem);
300 }
301 
302 // Headers
DecodeWebPHeaders(WebPIDecoder * const idec)303 static VP8StatusCode DecodeWebPHeaders(WebPIDecoder* const idec) {
304   MemBuffer* const mem = &idec->mem_;
305   const uint8_t* data = mem->buf_ + mem->start_;
306   size_t curr_size = MemDataSize(mem);
307   VP8StatusCode status;
308   WebPHeaderStructure headers;
309 
310   headers.data = data;
311   headers.data_size = curr_size;
312   headers.have_all_data = 0;
313   status = WebPParseHeaders(&headers);
314   if (status == VP8_STATUS_NOT_ENOUGH_DATA) {
315     return VP8_STATUS_SUSPENDED;  // We haven't found a VP8 chunk yet.
316   } else if (status != VP8_STATUS_OK) {
317     return IDecError(idec, status);
318   }
319 
320   idec->chunk_size_ = headers.compressed_size;
321   idec->is_lossless_ = headers.is_lossless;
322   if (!idec->is_lossless_) {
323     VP8Decoder* const dec = VP8New();
324     if (dec == NULL) {
325       return VP8_STATUS_OUT_OF_MEMORY;
326     }
327     idec->dec_ = dec;
328     dec->alpha_data_ = headers.alpha_data;
329     dec->alpha_data_size_ = headers.alpha_data_size;
330     ChangeState(idec, STATE_VP8_HEADER, headers.offset);
331   } else {
332     VP8LDecoder* const dec = VP8LNew();
333     if (dec == NULL) {
334       return VP8_STATUS_OUT_OF_MEMORY;
335     }
336     idec->dec_ = dec;
337     ChangeState(idec, STATE_VP8L_HEADER, headers.offset);
338   }
339   return VP8_STATUS_OK;
340 }
341 
DecodeVP8FrameHeader(WebPIDecoder * const idec)342 static VP8StatusCode DecodeVP8FrameHeader(WebPIDecoder* const idec) {
343   const uint8_t* data = idec->mem_.buf_ + idec->mem_.start_;
344   const size_t curr_size = MemDataSize(&idec->mem_);
345   int width, height;
346   uint32_t bits;
347 
348   if (curr_size < VP8_FRAME_HEADER_SIZE) {
349     // Not enough data bytes to extract VP8 Frame Header.
350     return VP8_STATUS_SUSPENDED;
351   }
352   if (!VP8GetInfo(data, curr_size, idec->chunk_size_, &width, &height)) {
353     return IDecError(idec, VP8_STATUS_BITSTREAM_ERROR);
354   }
355 
356   bits = data[0] | (data[1] << 8) | (data[2] << 16);
357   idec->mem_.part0_size_ = (bits >> 5) + VP8_FRAME_HEADER_SIZE;
358 
359   idec->io_.data = data;
360   idec->io_.data_size = curr_size;
361   idec->state_ = STATE_VP8_PARTS0;
362   return VP8_STATUS_OK;
363 }
364 
365 // Partition #0
CopyParts0Data(WebPIDecoder * const idec)366 static VP8StatusCode CopyParts0Data(WebPIDecoder* const idec) {
367   VP8Decoder* const dec = (VP8Decoder*)idec->dec_;
368   VP8BitReader* const br = &dec->br_;
369   const size_t part_size = br->buf_end_ - br->buf_;
370   MemBuffer* const mem = &idec->mem_;
371   assert(!idec->is_lossless_);
372   assert(mem->part0_buf_ == NULL);
373   // the following is a format limitation, no need for runtime check:
374   assert(part_size <= mem->part0_size_);
375   if (part_size == 0) {   // can't have zero-size partition #0
376     return VP8_STATUS_BITSTREAM_ERROR;
377   }
378   if (mem->mode_ == MEM_MODE_APPEND) {
379     // We copy and grab ownership of the partition #0 data.
380     uint8_t* const part0_buf = (uint8_t*)WebPSafeMalloc(1ULL, part_size);
381     if (part0_buf == NULL) {
382       return VP8_STATUS_OUT_OF_MEMORY;
383     }
384     memcpy(part0_buf, br->buf_, part_size);
385     mem->part0_buf_ = part0_buf;
386     VP8BitReaderSetBuffer(br, part0_buf, part_size);
387   } else {
388     // Else: just keep pointers to the partition #0's data in dec_->br_.
389   }
390   mem->start_ += part_size;
391   return VP8_STATUS_OK;
392 }
393 
DecodePartition0(WebPIDecoder * const idec)394 static VP8StatusCode DecodePartition0(WebPIDecoder* const idec) {
395   VP8Decoder* const dec = (VP8Decoder*)idec->dec_;
396   VP8Io* const io = &idec->io_;
397   const WebPDecParams* const params = &idec->params_;
398   WebPDecBuffer* const output = params->output;
399 
400   // Wait till we have enough data for the whole partition #0
401   if (MemDataSize(&idec->mem_) < idec->mem_.part0_size_) {
402     return VP8_STATUS_SUSPENDED;
403   }
404 
405   if (!VP8GetHeaders(dec, io)) {
406     const VP8StatusCode status = dec->status_;
407     if (status == VP8_STATUS_SUSPENDED ||
408         status == VP8_STATUS_NOT_ENOUGH_DATA) {
409       // treating NOT_ENOUGH_DATA as SUSPENDED state
410       return VP8_STATUS_SUSPENDED;
411     }
412     return IDecError(idec, status);
413   }
414 
415   // Allocate/Verify output buffer now
416   dec->status_ = WebPAllocateDecBuffer(io->width, io->height, params->options,
417                                        output);
418   if (dec->status_ != VP8_STATUS_OK) {
419     return IDecError(idec, dec->status_);
420   }
421   // This change must be done before calling VP8InitFrame()
422   dec->mt_method_ = VP8GetThreadMethod(params->options, NULL,
423                                        io->width, io->height);
424   VP8InitDithering(params->options, dec);
425 
426   dec->status_ = CopyParts0Data(idec);
427   if (dec->status_ != VP8_STATUS_OK) {
428     return IDecError(idec, dec->status_);
429   }
430 
431   // Finish setting up the decoding parameters. Will call io->setup().
432   if (VP8EnterCritical(dec, io) != VP8_STATUS_OK) {
433     return IDecError(idec, dec->status_);
434   }
435 
436   // Note: past this point, teardown() must always be called
437   // in case of error.
438   idec->state_ = STATE_VP8_DATA;
439   // Allocate memory and prepare everything.
440   if (!VP8InitFrame(dec, io)) {
441     return IDecError(idec, dec->status_);
442   }
443   return VP8_STATUS_OK;
444 }
445 
446 // Remaining partitions
DecodeRemaining(WebPIDecoder * const idec)447 static VP8StatusCode DecodeRemaining(WebPIDecoder* const idec) {
448   VP8Decoder* const dec = (VP8Decoder*)idec->dec_;
449   VP8Io* const io = &idec->io_;
450 
451   // Make sure partition #0 has been read before, to set dec to ready_.
452   if (!dec->ready_) {
453     return IDecError(idec, VP8_STATUS_BITSTREAM_ERROR);
454   }
455   for (; dec->mb_y_ < dec->mb_h_; ++dec->mb_y_) {
456     if (idec->last_mb_y_ != dec->mb_y_) {
457       if (!VP8ParseIntraModeRow(&dec->br_, dec)) {
458         // note: normally, error shouldn't occur since we already have the whole
459         // partition0 available here in DecodeRemaining(). Reaching EOF while
460         // reading intra modes really means a BITSTREAM_ERROR.
461         return IDecError(idec, VP8_STATUS_BITSTREAM_ERROR);
462       }
463       idec->last_mb_y_ = dec->mb_y_;
464     }
465     for (; dec->mb_x_ < dec->mb_w_; ++dec->mb_x_) {
466       VP8BitReader* const token_br =
467           &dec->parts_[dec->mb_y_ & dec->num_parts_minus_one_];
468       MBContext context;
469       SaveContext(dec, token_br, &context);
470       if (!VP8DecodeMB(dec, token_br)) {
471         // We shouldn't fail when MAX_MB data was available
472         if (dec->num_parts_minus_one_ == 0 &&
473             MemDataSize(&idec->mem_) > MAX_MB_SIZE) {
474           return IDecError(idec, VP8_STATUS_BITSTREAM_ERROR);
475         }
476         // Synchronize the threads.
477         if (dec->mt_method_ > 0) {
478           if (!WebPGetWorkerInterface()->Sync(&dec->worker_)) {
479             return IDecError(idec, VP8_STATUS_BITSTREAM_ERROR);
480           }
481         }
482         RestoreContext(&context, dec, token_br);
483         return VP8_STATUS_SUSPENDED;
484       }
485       // Release buffer only if there is only one partition
486       if (dec->num_parts_minus_one_ == 0) {
487         idec->mem_.start_ = token_br->buf_ - idec->mem_.buf_;
488         assert(idec->mem_.start_ <= idec->mem_.end_);
489       }
490     }
491     VP8InitScanline(dec);   // Prepare for next scanline
492 
493     // Reconstruct, filter and emit the row.
494     if (!VP8ProcessRow(dec, io)) {
495       return IDecError(idec, VP8_STATUS_USER_ABORT);
496     }
497   }
498   // Synchronize the thread and check for errors.
499   if (!VP8ExitCritical(dec, io)) {
500     idec->state_ = STATE_ERROR;  // prevent re-entry in IDecError
501     return IDecError(idec, VP8_STATUS_USER_ABORT);
502   }
503   dec->ready_ = 0;
504   return FinishDecoding(idec);
505 }
506 
ErrorStatusLossless(WebPIDecoder * const idec,VP8StatusCode status)507 static VP8StatusCode ErrorStatusLossless(WebPIDecoder* const idec,
508                                          VP8StatusCode status) {
509   if (status == VP8_STATUS_SUSPENDED || status == VP8_STATUS_NOT_ENOUGH_DATA) {
510     return VP8_STATUS_SUSPENDED;
511   }
512   return IDecError(idec, status);
513 }
514 
DecodeVP8LHeader(WebPIDecoder * const idec)515 static VP8StatusCode DecodeVP8LHeader(WebPIDecoder* const idec) {
516   VP8Io* const io = &idec->io_;
517   VP8LDecoder* const dec = (VP8LDecoder*)idec->dec_;
518   const WebPDecParams* const params = &idec->params_;
519   WebPDecBuffer* const output = params->output;
520   size_t curr_size = MemDataSize(&idec->mem_);
521   assert(idec->is_lossless_);
522 
523   // Wait until there's enough data for decoding header.
524   if (curr_size < (idec->chunk_size_ >> 3)) {
525     dec->status_ = VP8_STATUS_SUSPENDED;
526     return ErrorStatusLossless(idec, dec->status_);
527   }
528 
529   if (!VP8LDecodeHeader(dec, io)) {
530     if (dec->status_ == VP8_STATUS_BITSTREAM_ERROR &&
531         curr_size < idec->chunk_size_) {
532       dec->status_ = VP8_STATUS_SUSPENDED;
533     }
534     return ErrorStatusLossless(idec, dec->status_);
535   }
536   // Allocate/verify output buffer now.
537   dec->status_ = WebPAllocateDecBuffer(io->width, io->height, params->options,
538                                        output);
539   if (dec->status_ != VP8_STATUS_OK) {
540     return IDecError(idec, dec->status_);
541   }
542 
543   idec->state_ = STATE_VP8L_DATA;
544   return VP8_STATUS_OK;
545 }
546 
DecodeVP8LData(WebPIDecoder * const idec)547 static VP8StatusCode DecodeVP8LData(WebPIDecoder* const idec) {
548   VP8LDecoder* const dec = (VP8LDecoder*)idec->dec_;
549   const size_t curr_size = MemDataSize(&idec->mem_);
550   assert(idec->is_lossless_);
551 
552   // Switch to incremental decoding if we don't have all the bytes available.
553   dec->incremental_ = (curr_size < idec->chunk_size_);
554 
555   if (!VP8LDecodeImage(dec)) {
556     return ErrorStatusLossless(idec, dec->status_);
557   }
558   assert(dec->status_ == VP8_STATUS_OK || dec->status_ == VP8_STATUS_SUSPENDED);
559   return (dec->status_ == VP8_STATUS_SUSPENDED) ? dec->status_
560                                                 : FinishDecoding(idec);
561 }
562 
563   // Main decoding loop
IDecode(WebPIDecoder * idec)564 static VP8StatusCode IDecode(WebPIDecoder* idec) {
565   VP8StatusCode status = VP8_STATUS_SUSPENDED;
566 
567   if (idec->state_ == STATE_WEBP_HEADER) {
568     status = DecodeWebPHeaders(idec);
569   } else {
570     if (idec->dec_ == NULL) {
571       return VP8_STATUS_SUSPENDED;    // can't continue if we have no decoder.
572     }
573   }
574   if (idec->state_ == STATE_VP8_HEADER) {
575     status = DecodeVP8FrameHeader(idec);
576   }
577   if (idec->state_ == STATE_VP8_PARTS0) {
578     status = DecodePartition0(idec);
579   }
580   if (idec->state_ == STATE_VP8_DATA) {
581     const VP8Decoder* const dec = (VP8Decoder*)idec->dec_;
582     if (dec == NULL) {
583       return VP8_STATUS_SUSPENDED;  // can't continue if we have no decoder.
584     }
585     status = DecodeRemaining(idec);
586   }
587   if (idec->state_ == STATE_VP8L_HEADER) {
588     status = DecodeVP8LHeader(idec);
589   }
590   if (idec->state_ == STATE_VP8L_DATA) {
591     status = DecodeVP8LData(idec);
592   }
593   return status;
594 }
595 
596 //------------------------------------------------------------------------------
597 // Internal constructor
598 
NewDecoder(WebPDecBuffer * const output_buffer,const WebPBitstreamFeatures * const features)599 static WebPIDecoder* NewDecoder(WebPDecBuffer* const output_buffer,
600                                 const WebPBitstreamFeatures* const features) {
601   WebPIDecoder* idec = (WebPIDecoder*)WebPSafeCalloc(1ULL, sizeof(*idec));
602   if (idec == NULL) {
603     return NULL;
604   }
605 
606   idec->state_ = STATE_WEBP_HEADER;
607   idec->chunk_size_ = 0;
608 
609   idec->last_mb_y_ = -1;
610 
611   InitMemBuffer(&idec->mem_);
612   WebPInitDecBuffer(&idec->output_);
613   VP8InitIo(&idec->io_);
614 
615   WebPResetDecParams(&idec->params_);
616   if (output_buffer == NULL || WebPAvoidSlowMemory(output_buffer, features)) {
617     idec->params_.output = &idec->output_;
618     idec->final_output_ = output_buffer;
619     if (output_buffer != NULL) {
620       idec->params_.output->colorspace = output_buffer->colorspace;
621     }
622   } else {
623     idec->params_.output = output_buffer;
624     idec->final_output_ = NULL;
625   }
626   WebPInitCustomIo(&idec->params_, &idec->io_);  // Plug the I/O functions.
627 
628   return idec;
629 }
630 
631 //------------------------------------------------------------------------------
632 // Public functions
633 
WebPINewDecoder(WebPDecBuffer * output_buffer)634 WebPIDecoder* WebPINewDecoder(WebPDecBuffer* output_buffer) {
635   return NewDecoder(output_buffer, NULL);
636 }
637 
WebPIDecode(const uint8_t * data,size_t data_size,WebPDecoderConfig * config)638 WebPIDecoder* WebPIDecode(const uint8_t* data, size_t data_size,
639                           WebPDecoderConfig* config) {
640   WebPIDecoder* idec;
641   WebPBitstreamFeatures tmp_features;
642   WebPBitstreamFeatures* const features =
643       (config == NULL) ? &tmp_features : &config->input;
644   memset(&tmp_features, 0, sizeof(tmp_features));
645 
646   // Parse the bitstream's features, if requested:
647   if (data != NULL && data_size > 0) {
648     if (WebPGetFeatures(data, data_size, features) != VP8_STATUS_OK) {
649       return NULL;
650     }
651   }
652 
653   // Create an instance of the incremental decoder
654   idec = (config != NULL) ? NewDecoder(&config->output, features)
655                           : NewDecoder(NULL, features);
656   if (idec == NULL) {
657     return NULL;
658   }
659   // Finish initialization
660   if (config != NULL) {
661     idec->params_.options = &config->options;
662   }
663   return idec;
664 }
665 
WebPIDelete(WebPIDecoder * idec)666 void WebPIDelete(WebPIDecoder* idec) {
667   if (idec == NULL) return;
668   if (idec->dec_ != NULL) {
669     if (!idec->is_lossless_) {
670       if (idec->state_ == STATE_VP8_DATA) {
671         // Synchronize the thread, clean-up and check for errors.
672         VP8ExitCritical((VP8Decoder*)idec->dec_, &idec->io_);
673       }
674       VP8Delete((VP8Decoder*)idec->dec_);
675     } else {
676       VP8LDelete((VP8LDecoder*)idec->dec_);
677     }
678   }
679   ClearMemBuffer(&idec->mem_);
680   WebPFreeDecBuffer(&idec->output_);
681   WebPSafeFree(idec);
682 }
683 
684 //------------------------------------------------------------------------------
685 // Wrapper toward WebPINewDecoder
686 
WebPINewRGB(WEBP_CSP_MODE csp,uint8_t * output_buffer,size_t output_buffer_size,int output_stride)687 WebPIDecoder* WebPINewRGB(WEBP_CSP_MODE csp, uint8_t* output_buffer,
688                           size_t output_buffer_size, int output_stride) {
689   const int is_external_memory = (output_buffer != NULL) ? 1 : 0;
690   WebPIDecoder* idec;
691 
692   if (csp >= MODE_YUV) return NULL;
693   if (is_external_memory == 0) {    // Overwrite parameters to sane values.
694     output_buffer_size = 0;
695     output_stride = 0;
696   } else {  // A buffer was passed. Validate the other params.
697     if (output_stride == 0 || output_buffer_size == 0) {
698       return NULL;   // invalid parameter.
699     }
700   }
701   idec = WebPINewDecoder(NULL);
702   if (idec == NULL) return NULL;
703   idec->output_.colorspace = csp;
704   idec->output_.is_external_memory = is_external_memory;
705   idec->output_.u.RGBA.rgba = output_buffer;
706   idec->output_.u.RGBA.stride = output_stride;
707   idec->output_.u.RGBA.size = output_buffer_size;
708   return idec;
709 }
710 
WebPINewYUVA(uint8_t * luma,size_t luma_size,int luma_stride,uint8_t * u,size_t u_size,int u_stride,uint8_t * v,size_t v_size,int v_stride,uint8_t * a,size_t a_size,int a_stride)711 WebPIDecoder* WebPINewYUVA(uint8_t* luma, size_t luma_size, int luma_stride,
712                            uint8_t* u, size_t u_size, int u_stride,
713                            uint8_t* v, size_t v_size, int v_stride,
714                            uint8_t* a, size_t a_size, int a_stride) {
715   const int is_external_memory = (luma != NULL) ? 1 : 0;
716   WebPIDecoder* idec;
717   WEBP_CSP_MODE colorspace;
718 
719   if (is_external_memory == 0) {    // Overwrite parameters to sane values.
720     luma_size = u_size = v_size = a_size = 0;
721     luma_stride = u_stride = v_stride = a_stride = 0;
722     u = v = a = NULL;
723     colorspace = MODE_YUVA;
724   } else {  // A luma buffer was passed. Validate the other parameters.
725     if (u == NULL || v == NULL) return NULL;
726     if (luma_size == 0 || u_size == 0 || v_size == 0) return NULL;
727     if (luma_stride == 0 || u_stride == 0 || v_stride == 0) return NULL;
728     if (a != NULL) {
729       if (a_size == 0 || a_stride == 0) return NULL;
730     }
731     colorspace = (a == NULL) ? MODE_YUV : MODE_YUVA;
732   }
733 
734   idec = WebPINewDecoder(NULL);
735   if (idec == NULL) return NULL;
736 
737   idec->output_.colorspace = colorspace;
738   idec->output_.is_external_memory = is_external_memory;
739   idec->output_.u.YUVA.y = luma;
740   idec->output_.u.YUVA.y_stride = luma_stride;
741   idec->output_.u.YUVA.y_size = luma_size;
742   idec->output_.u.YUVA.u = u;
743   idec->output_.u.YUVA.u_stride = u_stride;
744   idec->output_.u.YUVA.u_size = u_size;
745   idec->output_.u.YUVA.v = v;
746   idec->output_.u.YUVA.v_stride = v_stride;
747   idec->output_.u.YUVA.v_size = v_size;
748   idec->output_.u.YUVA.a = a;
749   idec->output_.u.YUVA.a_stride = a_stride;
750   idec->output_.u.YUVA.a_size = a_size;
751   return idec;
752 }
753 
WebPINewYUV(uint8_t * luma,size_t luma_size,int luma_stride,uint8_t * u,size_t u_size,int u_stride,uint8_t * v,size_t v_size,int v_stride)754 WebPIDecoder* WebPINewYUV(uint8_t* luma, size_t luma_size, int luma_stride,
755                           uint8_t* u, size_t u_size, int u_stride,
756                           uint8_t* v, size_t v_size, int v_stride) {
757   return WebPINewYUVA(luma, luma_size, luma_stride,
758                       u, u_size, u_stride,
759                       v, v_size, v_stride,
760                       NULL, 0, 0);
761 }
762 
763 //------------------------------------------------------------------------------
764 
IDecCheckStatus(const WebPIDecoder * const idec)765 static VP8StatusCode IDecCheckStatus(const WebPIDecoder* const idec) {
766   assert(idec);
767   if (idec->state_ == STATE_ERROR) {
768     return VP8_STATUS_BITSTREAM_ERROR;
769   }
770   if (idec->state_ == STATE_DONE) {
771     return VP8_STATUS_OK;
772   }
773   return VP8_STATUS_SUSPENDED;
774 }
775 
WebPIAppend(WebPIDecoder * idec,const uint8_t * data,size_t data_size)776 VP8StatusCode WebPIAppend(WebPIDecoder* idec,
777                           const uint8_t* data, size_t data_size) {
778   VP8StatusCode status;
779   if (idec == NULL || data == NULL) {
780     return VP8_STATUS_INVALID_PARAM;
781   }
782   status = IDecCheckStatus(idec);
783   if (status != VP8_STATUS_SUSPENDED) {
784     return status;
785   }
786   // Check mixed calls between RemapMemBuffer and AppendToMemBuffer.
787   if (!CheckMemBufferMode(&idec->mem_, MEM_MODE_APPEND)) {
788     return VP8_STATUS_INVALID_PARAM;
789   }
790   // Append data to memory buffer
791   if (!AppendToMemBuffer(idec, data, data_size)) {
792     return VP8_STATUS_OUT_OF_MEMORY;
793   }
794   return IDecode(idec);
795 }
796 
WebPIUpdate(WebPIDecoder * idec,const uint8_t * data,size_t data_size)797 VP8StatusCode WebPIUpdate(WebPIDecoder* idec,
798                           const uint8_t* data, size_t data_size) {
799   VP8StatusCode status;
800   if (idec == NULL || data == NULL) {
801     return VP8_STATUS_INVALID_PARAM;
802   }
803   status = IDecCheckStatus(idec);
804   if (status != VP8_STATUS_SUSPENDED) {
805     return status;
806   }
807   // Check mixed calls between RemapMemBuffer and AppendToMemBuffer.
808   if (!CheckMemBufferMode(&idec->mem_, MEM_MODE_MAP)) {
809     return VP8_STATUS_INVALID_PARAM;
810   }
811   // Make the memory buffer point to the new buffer
812   if (!RemapMemBuffer(idec, data, data_size)) {
813     return VP8_STATUS_INVALID_PARAM;
814   }
815   return IDecode(idec);
816 }
817 
818 //------------------------------------------------------------------------------
819 
GetOutputBuffer(const WebPIDecoder * const idec)820 static const WebPDecBuffer* GetOutputBuffer(const WebPIDecoder* const idec) {
821   if (idec == NULL || idec->dec_ == NULL) {
822     return NULL;
823   }
824   if (idec->state_ <= STATE_VP8_PARTS0) {
825     return NULL;
826   }
827   if (idec->final_output_ != NULL) {
828     return NULL;   // not yet slow-copied
829   }
830   return idec->params_.output;
831 }
832 
WebPIDecodedArea(const WebPIDecoder * idec,int * left,int * top,int * width,int * height)833 const WebPDecBuffer* WebPIDecodedArea(const WebPIDecoder* idec,
834                                       int* left, int* top,
835                                       int* width, int* height) {
836   const WebPDecBuffer* const src = GetOutputBuffer(idec);
837   if (left != NULL) *left = 0;
838   if (top != NULL) *top = 0;
839   if (src != NULL) {
840     if (width != NULL) *width = src->width;
841     if (height != NULL) *height = idec->params_.last_y;
842   } else {
843     if (width != NULL) *width = 0;
844     if (height != NULL) *height = 0;
845   }
846   return src;
847 }
848 
WebPIDecGetRGB(const WebPIDecoder * idec,int * last_y,int * width,int * height,int * stride)849 uint8_t* WebPIDecGetRGB(const WebPIDecoder* idec, int* last_y,
850                         int* width, int* height, int* stride) {
851   const WebPDecBuffer* const src = GetOutputBuffer(idec);
852   if (src == NULL) return NULL;
853   if (src->colorspace >= MODE_YUV) {
854     return NULL;
855   }
856 
857   if (last_y != NULL) *last_y = idec->params_.last_y;
858   if (width != NULL) *width = src->width;
859   if (height != NULL) *height = src->height;
860   if (stride != NULL) *stride = src->u.RGBA.stride;
861 
862   return src->u.RGBA.rgba;
863 }
864 
WebPIDecGetYUVA(const WebPIDecoder * idec,int * last_y,uint8_t ** u,uint8_t ** v,uint8_t ** a,int * width,int * height,int * stride,int * uv_stride,int * a_stride)865 uint8_t* WebPIDecGetYUVA(const WebPIDecoder* idec, int* last_y,
866                          uint8_t** u, uint8_t** v, uint8_t** a,
867                          int* width, int* height,
868                          int* stride, int* uv_stride, int* a_stride) {
869   const WebPDecBuffer* const src = GetOutputBuffer(idec);
870   if (src == NULL) return NULL;
871   if (src->colorspace < MODE_YUV) {
872     return NULL;
873   }
874 
875   if (last_y != NULL) *last_y = idec->params_.last_y;
876   if (u != NULL) *u = src->u.YUVA.u;
877   if (v != NULL) *v = src->u.YUVA.v;
878   if (a != NULL) *a = src->u.YUVA.a;
879   if (width != NULL) *width = src->width;
880   if (height != NULL) *height = src->height;
881   if (stride != NULL) *stride = src->u.YUVA.y_stride;
882   if (uv_stride != NULL) *uv_stride = src->u.YUVA.u_stride;
883   if (a_stride != NULL) *a_stride = src->u.YUVA.a_stride;
884 
885   return src->u.YUVA.y;
886 }
887 
WebPISetIOHooks(WebPIDecoder * const idec,VP8IoPutHook put,VP8IoSetupHook setup,VP8IoTeardownHook teardown,void * user_data)888 int WebPISetIOHooks(WebPIDecoder* const idec,
889                     VP8IoPutHook put,
890                     VP8IoSetupHook setup,
891                     VP8IoTeardownHook teardown,
892                     void* user_data) {
893   if (idec == NULL || idec->state_ > STATE_WEBP_HEADER) {
894     return 0;
895   }
896 
897   idec->io_.put = put;
898   idec->io_.setup = setup;
899   idec->io_.teardown = teardown;
900   idec->io_.opaque = user_data;
901 
902   return 1;
903 }
904