• 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 =
170       (mem->buf_ == NULL) ? NULL : mem->buf_ + mem->start_;
171   const uint8_t* const old_base =
172       need_compressed_alpha ? dec->alpha_data_ : old_start;
173   assert(mem->buf_ != NULL || mem->start_ == 0);
174   assert(mem->mode_ == MEM_MODE_APPEND);
175   if (data_size > MAX_CHUNK_PAYLOAD) {
176     // security safeguard: trying to allocate more than what the format
177     // allows for a chunk should be considered a smoke smell.
178     return 0;
179   }
180 
181   if (mem->end_ + data_size > mem->buf_size_) {  // Need some free memory
182     const size_t new_mem_start = old_start - old_base;
183     const size_t current_size = MemDataSize(mem) + new_mem_start;
184     const uint64_t new_size = (uint64_t)current_size + data_size;
185     const uint64_t extra_size = (new_size + CHUNK_SIZE - 1) & ~(CHUNK_SIZE - 1);
186     uint8_t* const new_buf =
187         (uint8_t*)WebPSafeMalloc(extra_size, sizeof(*new_buf));
188     if (new_buf == NULL) return 0;
189     if (old_base != NULL) memcpy(new_buf, old_base, current_size);
190     WebPSafeFree(mem->buf_);
191     mem->buf_ = new_buf;
192     mem->buf_size_ = (size_t)extra_size;
193     mem->start_ = new_mem_start;
194     mem->end_ = current_size;
195   }
196 
197   assert(mem->buf_ != NULL);
198   memcpy(mem->buf_ + mem->end_, data, data_size);
199   mem->end_ += data_size;
200   assert(mem->end_ <= mem->buf_size_);
201 
202   DoRemap(idec, mem->buf_ + mem->start_ - old_start);
203   return 1;
204 }
205 
RemapMemBuffer(WebPIDecoder * const idec,const uint8_t * const data,size_t data_size)206 static int RemapMemBuffer(WebPIDecoder* const idec,
207                           const uint8_t* const data, size_t data_size) {
208   MemBuffer* const mem = &idec->mem_;
209   const uint8_t* const old_buf = mem->buf_;
210   const uint8_t* const old_start =
211       (old_buf == NULL) ? NULL : old_buf + mem->start_;
212   assert(old_buf != NULL || mem->start_ == 0);
213   assert(mem->mode_ == MEM_MODE_MAP);
214 
215   if (data_size < mem->buf_size_) return 0;  // can't remap to a shorter buffer!
216 
217   mem->buf_ = (uint8_t*)data;
218   mem->end_ = mem->buf_size_ = data_size;
219 
220   DoRemap(idec, mem->buf_ + mem->start_ - old_start);
221   return 1;
222 }
223 
InitMemBuffer(MemBuffer * const mem)224 static void InitMemBuffer(MemBuffer* const mem) {
225   mem->mode_       = MEM_MODE_NONE;
226   mem->buf_        = NULL;
227   mem->buf_size_   = 0;
228   mem->part0_buf_  = NULL;
229   mem->part0_size_ = 0;
230 }
231 
ClearMemBuffer(MemBuffer * const mem)232 static void ClearMemBuffer(MemBuffer* const mem) {
233   assert(mem);
234   if (mem->mode_ == MEM_MODE_APPEND) {
235     WebPSafeFree(mem->buf_);
236     WebPSafeFree((void*)mem->part0_buf_);
237   }
238 }
239 
CheckMemBufferMode(MemBuffer * const mem,MemBufferMode expected)240 static int CheckMemBufferMode(MemBuffer* const mem, MemBufferMode expected) {
241   if (mem->mode_ == MEM_MODE_NONE) {
242     mem->mode_ = expected;    // switch to the expected mode
243   } else if (mem->mode_ != expected) {
244     return 0;         // we mixed the modes => error
245   }
246   assert(mem->mode_ == expected);   // mode is ok
247   return 1;
248 }
249 
250 // To be called last.
FinishDecoding(WebPIDecoder * const idec)251 static VP8StatusCode FinishDecoding(WebPIDecoder* const idec) {
252   const WebPDecoderOptions* const options = idec->params_.options;
253   WebPDecBuffer* const output = idec->params_.output;
254 
255   idec->state_ = STATE_DONE;
256   if (options != NULL && options->flip) {
257     const VP8StatusCode status = WebPFlipBuffer(output);
258     if (status != VP8_STATUS_OK) return status;
259   }
260   if (idec->final_output_ != NULL) {
261     WebPCopyDecBufferPixels(output, idec->final_output_);  // do the slow-copy
262     WebPFreeDecBuffer(&idec->output_);
263     *output = *idec->final_output_;
264     idec->final_output_ = NULL;
265   }
266   return VP8_STATUS_OK;
267 }
268 
269 //------------------------------------------------------------------------------
270 // Macroblock-decoding contexts
271 
SaveContext(const VP8Decoder * dec,const VP8BitReader * token_br,MBContext * const context)272 static void SaveContext(const VP8Decoder* dec, const VP8BitReader* token_br,
273                         MBContext* const context) {
274   context->left_ = dec->mb_info_[-1];
275   context->info_ = dec->mb_info_[dec->mb_x_];
276   context->token_br_ = *token_br;
277 }
278 
RestoreContext(const MBContext * context,VP8Decoder * const dec,VP8BitReader * const token_br)279 static void RestoreContext(const MBContext* context, VP8Decoder* const dec,
280                            VP8BitReader* const token_br) {
281   dec->mb_info_[-1] = context->left_;
282   dec->mb_info_[dec->mb_x_] = context->info_;
283   *token_br = context->token_br_;
284 }
285 
286 //------------------------------------------------------------------------------
287 
IDecError(WebPIDecoder * const idec,VP8StatusCode error)288 static VP8StatusCode IDecError(WebPIDecoder* const idec, VP8StatusCode error) {
289   if (idec->state_ == STATE_VP8_DATA) {
290     // Synchronize the thread, clean-up and check for errors.
291     VP8ExitCritical((VP8Decoder*)idec->dec_, &idec->io_);
292   }
293   idec->state_ = STATE_ERROR;
294   return error;
295 }
296 
ChangeState(WebPIDecoder * const idec,DecState new_state,size_t consumed_bytes)297 static void ChangeState(WebPIDecoder* const idec, DecState new_state,
298                         size_t consumed_bytes) {
299   MemBuffer* const mem = &idec->mem_;
300   idec->state_ = new_state;
301   mem->start_ += consumed_bytes;
302   assert(mem->start_ <= mem->end_);
303   idec->io_.data = mem->buf_ + mem->start_;
304   idec->io_.data_size = MemDataSize(mem);
305 }
306 
307 // Headers
DecodeWebPHeaders(WebPIDecoder * const idec)308 static VP8StatusCode DecodeWebPHeaders(WebPIDecoder* const idec) {
309   MemBuffer* const mem = &idec->mem_;
310   const uint8_t* data = mem->buf_ + mem->start_;
311   size_t curr_size = MemDataSize(mem);
312   VP8StatusCode status;
313   WebPHeaderStructure headers;
314 
315   headers.data = data;
316   headers.data_size = curr_size;
317   headers.have_all_data = 0;
318   status = WebPParseHeaders(&headers);
319   if (status == VP8_STATUS_NOT_ENOUGH_DATA) {
320     return VP8_STATUS_SUSPENDED;  // We haven't found a VP8 chunk yet.
321   } else if (status != VP8_STATUS_OK) {
322     return IDecError(idec, status);
323   }
324 
325   idec->chunk_size_ = headers.compressed_size;
326   idec->is_lossless_ = headers.is_lossless;
327   if (!idec->is_lossless_) {
328     VP8Decoder* const dec = VP8New();
329     if (dec == NULL) {
330       return VP8_STATUS_OUT_OF_MEMORY;
331     }
332     idec->dec_ = dec;
333     dec->alpha_data_ = headers.alpha_data;
334     dec->alpha_data_size_ = headers.alpha_data_size;
335     ChangeState(idec, STATE_VP8_HEADER, headers.offset);
336   } else {
337     VP8LDecoder* const dec = VP8LNew();
338     if (dec == NULL) {
339       return VP8_STATUS_OUT_OF_MEMORY;
340     }
341     idec->dec_ = dec;
342     ChangeState(idec, STATE_VP8L_HEADER, headers.offset);
343   }
344   return VP8_STATUS_OK;
345 }
346 
DecodeVP8FrameHeader(WebPIDecoder * const idec)347 static VP8StatusCode DecodeVP8FrameHeader(WebPIDecoder* const idec) {
348   const uint8_t* data = idec->mem_.buf_ + idec->mem_.start_;
349   const size_t curr_size = MemDataSize(&idec->mem_);
350   int width, height;
351   uint32_t bits;
352 
353   if (curr_size < VP8_FRAME_HEADER_SIZE) {
354     // Not enough data bytes to extract VP8 Frame Header.
355     return VP8_STATUS_SUSPENDED;
356   }
357   if (!VP8GetInfo(data, curr_size, idec->chunk_size_, &width, &height)) {
358     return IDecError(idec, VP8_STATUS_BITSTREAM_ERROR);
359   }
360 
361   bits = data[0] | (data[1] << 8) | (data[2] << 16);
362   idec->mem_.part0_size_ = (bits >> 5) + VP8_FRAME_HEADER_SIZE;
363 
364   idec->io_.data = data;
365   idec->io_.data_size = curr_size;
366   idec->state_ = STATE_VP8_PARTS0;
367   return VP8_STATUS_OK;
368 }
369 
370 // Partition #0
CopyParts0Data(WebPIDecoder * const idec)371 static VP8StatusCode CopyParts0Data(WebPIDecoder* const idec) {
372   VP8Decoder* const dec = (VP8Decoder*)idec->dec_;
373   VP8BitReader* const br = &dec->br_;
374   const size_t part_size = br->buf_end_ - br->buf_;
375   MemBuffer* const mem = &idec->mem_;
376   assert(!idec->is_lossless_);
377   assert(mem->part0_buf_ == NULL);
378   // the following is a format limitation, no need for runtime check:
379   assert(part_size <= mem->part0_size_);
380   if (part_size == 0) {   // can't have zero-size partition #0
381     return VP8_STATUS_BITSTREAM_ERROR;
382   }
383   if (mem->mode_ == MEM_MODE_APPEND) {
384     // We copy and grab ownership of the partition #0 data.
385     uint8_t* const part0_buf = (uint8_t*)WebPSafeMalloc(1ULL, part_size);
386     if (part0_buf == NULL) {
387       return VP8_STATUS_OUT_OF_MEMORY;
388     }
389     memcpy(part0_buf, br->buf_, part_size);
390     mem->part0_buf_ = part0_buf;
391     VP8BitReaderSetBuffer(br, part0_buf, part_size);
392   } else {
393     // Else: just keep pointers to the partition #0's data in dec_->br_.
394   }
395   mem->start_ += part_size;
396   return VP8_STATUS_OK;
397 }
398 
DecodePartition0(WebPIDecoder * const idec)399 static VP8StatusCode DecodePartition0(WebPIDecoder* const idec) {
400   VP8Decoder* const dec = (VP8Decoder*)idec->dec_;
401   VP8Io* const io = &idec->io_;
402   const WebPDecParams* const params = &idec->params_;
403   WebPDecBuffer* const output = params->output;
404 
405   // Wait till we have enough data for the whole partition #0
406   if (MemDataSize(&idec->mem_) < idec->mem_.part0_size_) {
407     return VP8_STATUS_SUSPENDED;
408   }
409 
410   if (!VP8GetHeaders(dec, io)) {
411     const VP8StatusCode status = dec->status_;
412     if (status == VP8_STATUS_SUSPENDED ||
413         status == VP8_STATUS_NOT_ENOUGH_DATA) {
414       // treating NOT_ENOUGH_DATA as SUSPENDED state
415       return VP8_STATUS_SUSPENDED;
416     }
417     return IDecError(idec, status);
418   }
419 
420   // Allocate/Verify output buffer now
421   dec->status_ = WebPAllocateDecBuffer(io->width, io->height, params->options,
422                                        output);
423   if (dec->status_ != VP8_STATUS_OK) {
424     return IDecError(idec, dec->status_);
425   }
426   // This change must be done before calling VP8InitFrame()
427   dec->mt_method_ = VP8GetThreadMethod(params->options, NULL,
428                                        io->width, io->height);
429   VP8InitDithering(params->options, dec);
430 
431   dec->status_ = CopyParts0Data(idec);
432   if (dec->status_ != VP8_STATUS_OK) {
433     return IDecError(idec, dec->status_);
434   }
435 
436   // Finish setting up the decoding parameters. Will call io->setup().
437   if (VP8EnterCritical(dec, io) != VP8_STATUS_OK) {
438     return IDecError(idec, dec->status_);
439   }
440 
441   // Note: past this point, teardown() must always be called
442   // in case of error.
443   idec->state_ = STATE_VP8_DATA;
444   // Allocate memory and prepare everything.
445   if (!VP8InitFrame(dec, io)) {
446     return IDecError(idec, dec->status_);
447   }
448   return VP8_STATUS_OK;
449 }
450 
451 // Remaining partitions
DecodeRemaining(WebPIDecoder * const idec)452 static VP8StatusCode DecodeRemaining(WebPIDecoder* const idec) {
453   VP8Decoder* const dec = (VP8Decoder*)idec->dec_;
454   VP8Io* const io = &idec->io_;
455 
456   // Make sure partition #0 has been read before, to set dec to ready_.
457   if (!dec->ready_) {
458     return IDecError(idec, VP8_STATUS_BITSTREAM_ERROR);
459   }
460   for (; dec->mb_y_ < dec->mb_h_; ++dec->mb_y_) {
461     if (idec->last_mb_y_ != dec->mb_y_) {
462       if (!VP8ParseIntraModeRow(&dec->br_, dec)) {
463         // note: normally, error shouldn't occur since we already have the whole
464         // partition0 available here in DecodeRemaining(). Reaching EOF while
465         // reading intra modes really means a BITSTREAM_ERROR.
466         return IDecError(idec, VP8_STATUS_BITSTREAM_ERROR);
467       }
468       idec->last_mb_y_ = dec->mb_y_;
469     }
470     for (; dec->mb_x_ < dec->mb_w_; ++dec->mb_x_) {
471       VP8BitReader* const token_br =
472           &dec->parts_[dec->mb_y_ & dec->num_parts_minus_one_];
473       MBContext context;
474       SaveContext(dec, token_br, &context);
475       if (!VP8DecodeMB(dec, token_br)) {
476         // We shouldn't fail when MAX_MB data was available
477         if (dec->num_parts_minus_one_ == 0 &&
478             MemDataSize(&idec->mem_) > MAX_MB_SIZE) {
479           return IDecError(idec, VP8_STATUS_BITSTREAM_ERROR);
480         }
481         // Synchronize the threads.
482         if (dec->mt_method_ > 0) {
483           if (!WebPGetWorkerInterface()->Sync(&dec->worker_)) {
484             return IDecError(idec, VP8_STATUS_BITSTREAM_ERROR);
485           }
486         }
487         RestoreContext(&context, dec, token_br);
488         return VP8_STATUS_SUSPENDED;
489       }
490       // Release buffer only if there is only one partition
491       if (dec->num_parts_minus_one_ == 0) {
492         idec->mem_.start_ = token_br->buf_ - idec->mem_.buf_;
493         assert(idec->mem_.start_ <= idec->mem_.end_);
494       }
495     }
496     VP8InitScanline(dec);   // Prepare for next scanline
497 
498     // Reconstruct, filter and emit the row.
499     if (!VP8ProcessRow(dec, io)) {
500       return IDecError(idec, VP8_STATUS_USER_ABORT);
501     }
502   }
503   // Synchronize the thread and check for errors.
504   if (!VP8ExitCritical(dec, io)) {
505     idec->state_ = STATE_ERROR;  // prevent re-entry in IDecError
506     return IDecError(idec, VP8_STATUS_USER_ABORT);
507   }
508   dec->ready_ = 0;
509   return FinishDecoding(idec);
510 }
511 
ErrorStatusLossless(WebPIDecoder * const idec,VP8StatusCode status)512 static VP8StatusCode ErrorStatusLossless(WebPIDecoder* const idec,
513                                          VP8StatusCode status) {
514   if (status == VP8_STATUS_SUSPENDED || status == VP8_STATUS_NOT_ENOUGH_DATA) {
515     return VP8_STATUS_SUSPENDED;
516   }
517   return IDecError(idec, status);
518 }
519 
DecodeVP8LHeader(WebPIDecoder * const idec)520 static VP8StatusCode DecodeVP8LHeader(WebPIDecoder* const idec) {
521   VP8Io* const io = &idec->io_;
522   VP8LDecoder* const dec = (VP8LDecoder*)idec->dec_;
523   const WebPDecParams* const params = &idec->params_;
524   WebPDecBuffer* const output = params->output;
525   size_t curr_size = MemDataSize(&idec->mem_);
526   assert(idec->is_lossless_);
527 
528   // Wait until there's enough data for decoding header.
529   if (curr_size < (idec->chunk_size_ >> 3)) {
530     dec->status_ = VP8_STATUS_SUSPENDED;
531     return ErrorStatusLossless(idec, dec->status_);
532   }
533 
534   if (!VP8LDecodeHeader(dec, io)) {
535     if (dec->status_ == VP8_STATUS_BITSTREAM_ERROR &&
536         curr_size < idec->chunk_size_) {
537       dec->status_ = VP8_STATUS_SUSPENDED;
538     }
539     return ErrorStatusLossless(idec, dec->status_);
540   }
541   // Allocate/verify output buffer now.
542   dec->status_ = WebPAllocateDecBuffer(io->width, io->height, params->options,
543                                        output);
544   if (dec->status_ != VP8_STATUS_OK) {
545     return IDecError(idec, dec->status_);
546   }
547 
548   idec->state_ = STATE_VP8L_DATA;
549   return VP8_STATUS_OK;
550 }
551 
DecodeVP8LData(WebPIDecoder * const idec)552 static VP8StatusCode DecodeVP8LData(WebPIDecoder* const idec) {
553   VP8LDecoder* const dec = (VP8LDecoder*)idec->dec_;
554   const size_t curr_size = MemDataSize(&idec->mem_);
555   assert(idec->is_lossless_);
556 
557   // Switch to incremental decoding if we don't have all the bytes available.
558   dec->incremental_ = (curr_size < idec->chunk_size_);
559 
560   if (!VP8LDecodeImage(dec)) {
561     return ErrorStatusLossless(idec, dec->status_);
562   }
563   assert(dec->status_ == VP8_STATUS_OK || dec->status_ == VP8_STATUS_SUSPENDED);
564   return (dec->status_ == VP8_STATUS_SUSPENDED) ? dec->status_
565                                                 : FinishDecoding(idec);
566 }
567 
568   // Main decoding loop
IDecode(WebPIDecoder * idec)569 static VP8StatusCode IDecode(WebPIDecoder* idec) {
570   VP8StatusCode status = VP8_STATUS_SUSPENDED;
571 
572   if (idec->state_ == STATE_WEBP_HEADER) {
573     status = DecodeWebPHeaders(idec);
574   } else {
575     if (idec->dec_ == NULL) {
576       return VP8_STATUS_SUSPENDED;    // can't continue if we have no decoder.
577     }
578   }
579   if (idec->state_ == STATE_VP8_HEADER) {
580     status = DecodeVP8FrameHeader(idec);
581   }
582   if (idec->state_ == STATE_VP8_PARTS0) {
583     status = DecodePartition0(idec);
584   }
585   if (idec->state_ == STATE_VP8_DATA) {
586     const VP8Decoder* const dec = (VP8Decoder*)idec->dec_;
587     if (dec == NULL) {
588       return VP8_STATUS_SUSPENDED;  // can't continue if we have no decoder.
589     }
590     status = DecodeRemaining(idec);
591   }
592   if (idec->state_ == STATE_VP8L_HEADER) {
593     status = DecodeVP8LHeader(idec);
594   }
595   if (idec->state_ == STATE_VP8L_DATA) {
596     status = DecodeVP8LData(idec);
597   }
598   return status;
599 }
600 
601 //------------------------------------------------------------------------------
602 // Internal constructor
603 
NewDecoder(WebPDecBuffer * const output_buffer,const WebPBitstreamFeatures * const features)604 static WebPIDecoder* NewDecoder(WebPDecBuffer* const output_buffer,
605                                 const WebPBitstreamFeatures* const features) {
606   WebPIDecoder* idec = (WebPIDecoder*)WebPSafeCalloc(1ULL, sizeof(*idec));
607   if (idec == NULL) {
608     return NULL;
609   }
610 
611   idec->state_ = STATE_WEBP_HEADER;
612   idec->chunk_size_ = 0;
613 
614   idec->last_mb_y_ = -1;
615 
616   InitMemBuffer(&idec->mem_);
617   WebPInitDecBuffer(&idec->output_);
618   VP8InitIo(&idec->io_);
619 
620   WebPResetDecParams(&idec->params_);
621   if (output_buffer == NULL || WebPAvoidSlowMemory(output_buffer, features)) {
622     idec->params_.output = &idec->output_;
623     idec->final_output_ = output_buffer;
624     if (output_buffer != NULL) {
625       idec->params_.output->colorspace = output_buffer->colorspace;
626     }
627   } else {
628     idec->params_.output = output_buffer;
629     idec->final_output_ = NULL;
630   }
631   WebPInitCustomIo(&idec->params_, &idec->io_);  // Plug the I/O functions.
632 
633   return idec;
634 }
635 
636 //------------------------------------------------------------------------------
637 // Public functions
638 
WebPINewDecoder(WebPDecBuffer * output_buffer)639 WebPIDecoder* WebPINewDecoder(WebPDecBuffer* output_buffer) {
640   return NewDecoder(output_buffer, NULL);
641 }
642 
WebPIDecode(const uint8_t * data,size_t data_size,WebPDecoderConfig * config)643 WebPIDecoder* WebPIDecode(const uint8_t* data, size_t data_size,
644                           WebPDecoderConfig* config) {
645   WebPIDecoder* idec;
646   WebPBitstreamFeatures tmp_features;
647   WebPBitstreamFeatures* const features =
648       (config == NULL) ? &tmp_features : &config->input;
649   memset(&tmp_features, 0, sizeof(tmp_features));
650 
651   // Parse the bitstream's features, if requested:
652   if (data != NULL && data_size > 0) {
653     if (WebPGetFeatures(data, data_size, features) != VP8_STATUS_OK) {
654       return NULL;
655     }
656   }
657 
658   // Create an instance of the incremental decoder
659   idec = (config != NULL) ? NewDecoder(&config->output, features)
660                           : NewDecoder(NULL, features);
661   if (idec == NULL) {
662     return NULL;
663   }
664   // Finish initialization
665   if (config != NULL) {
666     idec->params_.options = &config->options;
667   }
668   return idec;
669 }
670 
WebPIDelete(WebPIDecoder * idec)671 void WebPIDelete(WebPIDecoder* idec) {
672   if (idec == NULL) return;
673   if (idec->dec_ != NULL) {
674     if (!idec->is_lossless_) {
675       if (idec->state_ == STATE_VP8_DATA) {
676         // Synchronize the thread, clean-up and check for errors.
677         VP8ExitCritical((VP8Decoder*)idec->dec_, &idec->io_);
678       }
679       VP8Delete((VP8Decoder*)idec->dec_);
680     } else {
681       VP8LDelete((VP8LDecoder*)idec->dec_);
682     }
683   }
684   ClearMemBuffer(&idec->mem_);
685   WebPFreeDecBuffer(&idec->output_);
686   WebPSafeFree(idec);
687 }
688 
689 //------------------------------------------------------------------------------
690 // Wrapper toward WebPINewDecoder
691 
WebPINewRGB(WEBP_CSP_MODE csp,uint8_t * output_buffer,size_t output_buffer_size,int output_stride)692 WebPIDecoder* WebPINewRGB(WEBP_CSP_MODE csp, uint8_t* output_buffer,
693                           size_t output_buffer_size, int output_stride) {
694   const int is_external_memory = (output_buffer != NULL) ? 1 : 0;
695   WebPIDecoder* idec;
696 
697   if (csp >= MODE_YUV) return NULL;
698   if (is_external_memory == 0) {    // Overwrite parameters to sane values.
699     output_buffer_size = 0;
700     output_stride = 0;
701   } else {  // A buffer was passed. Validate the other params.
702     if (output_stride == 0 || output_buffer_size == 0) {
703       return NULL;   // invalid parameter.
704     }
705   }
706   idec = WebPINewDecoder(NULL);
707   if (idec == NULL) return NULL;
708   idec->output_.colorspace = csp;
709   idec->output_.is_external_memory = is_external_memory;
710   idec->output_.u.RGBA.rgba = output_buffer;
711   idec->output_.u.RGBA.stride = output_stride;
712   idec->output_.u.RGBA.size = output_buffer_size;
713   return idec;
714 }
715 
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)716 WebPIDecoder* WebPINewYUVA(uint8_t* luma, size_t luma_size, int luma_stride,
717                            uint8_t* u, size_t u_size, int u_stride,
718                            uint8_t* v, size_t v_size, int v_stride,
719                            uint8_t* a, size_t a_size, int a_stride) {
720   const int is_external_memory = (luma != NULL) ? 1 : 0;
721   WebPIDecoder* idec;
722   WEBP_CSP_MODE colorspace;
723 
724   if (is_external_memory == 0) {    // Overwrite parameters to sane values.
725     luma_size = u_size = v_size = a_size = 0;
726     luma_stride = u_stride = v_stride = a_stride = 0;
727     u = v = a = NULL;
728     colorspace = MODE_YUVA;
729   } else {  // A luma buffer was passed. Validate the other parameters.
730     if (u == NULL || v == NULL) return NULL;
731     if (luma_size == 0 || u_size == 0 || v_size == 0) return NULL;
732     if (luma_stride == 0 || u_stride == 0 || v_stride == 0) return NULL;
733     if (a != NULL) {
734       if (a_size == 0 || a_stride == 0) return NULL;
735     }
736     colorspace = (a == NULL) ? MODE_YUV : MODE_YUVA;
737   }
738 
739   idec = WebPINewDecoder(NULL);
740   if (idec == NULL) return NULL;
741 
742   idec->output_.colorspace = colorspace;
743   idec->output_.is_external_memory = is_external_memory;
744   idec->output_.u.YUVA.y = luma;
745   idec->output_.u.YUVA.y_stride = luma_stride;
746   idec->output_.u.YUVA.y_size = luma_size;
747   idec->output_.u.YUVA.u = u;
748   idec->output_.u.YUVA.u_stride = u_stride;
749   idec->output_.u.YUVA.u_size = u_size;
750   idec->output_.u.YUVA.v = v;
751   idec->output_.u.YUVA.v_stride = v_stride;
752   idec->output_.u.YUVA.v_size = v_size;
753   idec->output_.u.YUVA.a = a;
754   idec->output_.u.YUVA.a_stride = a_stride;
755   idec->output_.u.YUVA.a_size = a_size;
756   return idec;
757 }
758 
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)759 WebPIDecoder* WebPINewYUV(uint8_t* luma, size_t luma_size, int luma_stride,
760                           uint8_t* u, size_t u_size, int u_stride,
761                           uint8_t* v, size_t v_size, int v_stride) {
762   return WebPINewYUVA(luma, luma_size, luma_stride,
763                       u, u_size, u_stride,
764                       v, v_size, v_stride,
765                       NULL, 0, 0);
766 }
767 
768 //------------------------------------------------------------------------------
769 
IDecCheckStatus(const WebPIDecoder * const idec)770 static VP8StatusCode IDecCheckStatus(const WebPIDecoder* const idec) {
771   assert(idec);
772   if (idec->state_ == STATE_ERROR) {
773     return VP8_STATUS_BITSTREAM_ERROR;
774   }
775   if (idec->state_ == STATE_DONE) {
776     return VP8_STATUS_OK;
777   }
778   return VP8_STATUS_SUSPENDED;
779 }
780 
WebPIAppend(WebPIDecoder * idec,const uint8_t * data,size_t data_size)781 VP8StatusCode WebPIAppend(WebPIDecoder* idec,
782                           const uint8_t* data, size_t data_size) {
783   VP8StatusCode status;
784   if (idec == NULL || data == NULL) {
785     return VP8_STATUS_INVALID_PARAM;
786   }
787   status = IDecCheckStatus(idec);
788   if (status != VP8_STATUS_SUSPENDED) {
789     return status;
790   }
791   // Check mixed calls between RemapMemBuffer and AppendToMemBuffer.
792   if (!CheckMemBufferMode(&idec->mem_, MEM_MODE_APPEND)) {
793     return VP8_STATUS_INVALID_PARAM;
794   }
795   // Append data to memory buffer
796   if (!AppendToMemBuffer(idec, data, data_size)) {
797     return VP8_STATUS_OUT_OF_MEMORY;
798   }
799   return IDecode(idec);
800 }
801 
WebPIUpdate(WebPIDecoder * idec,const uint8_t * data,size_t data_size)802 VP8StatusCode WebPIUpdate(WebPIDecoder* idec,
803                           const uint8_t* data, size_t data_size) {
804   VP8StatusCode status;
805   if (idec == NULL || data == NULL) {
806     return VP8_STATUS_INVALID_PARAM;
807   }
808   status = IDecCheckStatus(idec);
809   if (status != VP8_STATUS_SUSPENDED) {
810     return status;
811   }
812   // Check mixed calls between RemapMemBuffer and AppendToMemBuffer.
813   if (!CheckMemBufferMode(&idec->mem_, MEM_MODE_MAP)) {
814     return VP8_STATUS_INVALID_PARAM;
815   }
816   // Make the memory buffer point to the new buffer
817   if (!RemapMemBuffer(idec, data, data_size)) {
818     return VP8_STATUS_INVALID_PARAM;
819   }
820   return IDecode(idec);
821 }
822 
823 //------------------------------------------------------------------------------
824 
GetOutputBuffer(const WebPIDecoder * const idec)825 static const WebPDecBuffer* GetOutputBuffer(const WebPIDecoder* const idec) {
826   if (idec == NULL || idec->dec_ == NULL) {
827     return NULL;
828   }
829   if (idec->state_ <= STATE_VP8_PARTS0) {
830     return NULL;
831   }
832   if (idec->final_output_ != NULL) {
833     return NULL;   // not yet slow-copied
834   }
835   return idec->params_.output;
836 }
837 
WebPIDecodedArea(const WebPIDecoder * idec,int * left,int * top,int * width,int * height)838 const WebPDecBuffer* WebPIDecodedArea(const WebPIDecoder* idec,
839                                       int* left, int* top,
840                                       int* width, int* height) {
841   const WebPDecBuffer* const src = GetOutputBuffer(idec);
842   if (left != NULL) *left = 0;
843   if (top != NULL) *top = 0;
844   if (src != NULL) {
845     if (width != NULL) *width = src->width;
846     if (height != NULL) *height = idec->params_.last_y;
847   } else {
848     if (width != NULL) *width = 0;
849     if (height != NULL) *height = 0;
850   }
851   return src;
852 }
853 
WebPIDecGetRGB(const WebPIDecoder * idec,int * last_y,int * width,int * height,int * stride)854 uint8_t* WebPIDecGetRGB(const WebPIDecoder* idec, int* last_y,
855                         int* width, int* height, int* stride) {
856   const WebPDecBuffer* const src = GetOutputBuffer(idec);
857   if (src == NULL) return NULL;
858   if (src->colorspace >= MODE_YUV) {
859     return NULL;
860   }
861 
862   if (last_y != NULL) *last_y = idec->params_.last_y;
863   if (width != NULL) *width = src->width;
864   if (height != NULL) *height = src->height;
865   if (stride != NULL) *stride = src->u.RGBA.stride;
866 
867   return src->u.RGBA.rgba;
868 }
869 
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)870 uint8_t* WebPIDecGetYUVA(const WebPIDecoder* idec, int* last_y,
871                          uint8_t** u, uint8_t** v, uint8_t** a,
872                          int* width, int* height,
873                          int* stride, int* uv_stride, int* a_stride) {
874   const WebPDecBuffer* const src = GetOutputBuffer(idec);
875   if (src == NULL) return NULL;
876   if (src->colorspace < MODE_YUV) {
877     return NULL;
878   }
879 
880   if (last_y != NULL) *last_y = idec->params_.last_y;
881   if (u != NULL) *u = src->u.YUVA.u;
882   if (v != NULL) *v = src->u.YUVA.v;
883   if (a != NULL) *a = src->u.YUVA.a;
884   if (width != NULL) *width = src->width;
885   if (height != NULL) *height = src->height;
886   if (stride != NULL) *stride = src->u.YUVA.y_stride;
887   if (uv_stride != NULL) *uv_stride = src->u.YUVA.u_stride;
888   if (a_stride != NULL) *a_stride = src->u.YUVA.a_stride;
889 
890   return src->u.YUVA.y;
891 }
892 
WebPISetIOHooks(WebPIDecoder * const idec,VP8IoPutHook put,VP8IoSetupHook setup,VP8IoTeardownHook teardown,void * user_data)893 int WebPISetIOHooks(WebPIDecoder* const idec,
894                     VP8IoPutHook put,
895                     VP8IoSetupHook setup,
896                     VP8IoTeardownHook teardown,
897                     void* user_data) {
898   if (idec == NULL || idec->state_ > STATE_WEBP_HEADER) {
899     return 0;
900   }
901 
902   idec->io_.put = put;
903   idec->io_.setup = setup;
904   idec->io_.teardown = teardown;
905   idec->io_.opaque = user_data;
906 
907   return 1;
908 }
909