• 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 "./alphai.h"
19 #include "./webpi.h"
20 #include "./vp8i.h"
21 #include "../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   size_t chunk_size_;      // Compressed VP8/VP8L size extracted from Header.
75 
76   int last_mb_y_;          // last row reached for intra-mode decoding
77 };
78 
79 // MB context to restore in case VP8DecodeMB() fails
80 typedef struct {
81   VP8MB left_;
82   VP8MB info_;
83   VP8BitReader token_br_;
84 } MBContext;
85 
86 //------------------------------------------------------------------------------
87 // MemBuffer: incoming data handling
88 
MemDataSize(const MemBuffer * mem)89 static WEBP_INLINE size_t MemDataSize(const MemBuffer* mem) {
90   return (mem->end_ - mem->start_);
91 }
92 
93 // Check if we need to preserve the compressed alpha data, as it may not have
94 // been decoded yet.
NeedCompressedAlpha(const WebPIDecoder * const idec)95 static int NeedCompressedAlpha(const WebPIDecoder* const idec) {
96   if (idec->state_ == STATE_WEBP_HEADER) {
97     // We haven't parsed the headers yet, so we don't know whether the image is
98     // lossy or lossless. This also means that we haven't parsed the ALPH chunk.
99     return 0;
100   }
101   if (idec->is_lossless_) {
102     return 0;  // ALPH chunk is not present for lossless images.
103   } else {
104     const VP8Decoder* const dec = (VP8Decoder*)idec->dec_;
105     assert(dec != NULL);  // Must be true as idec->state_ != STATE_WEBP_HEADER.
106     return (dec->alpha_data_ != NULL) && !dec->is_alpha_decoded_;
107   }
108 }
109 
DoRemap(WebPIDecoder * const idec,ptrdiff_t offset)110 static void DoRemap(WebPIDecoder* const idec, ptrdiff_t offset) {
111   MemBuffer* const mem = &idec->mem_;
112   const uint8_t* const new_base = mem->buf_ + mem->start_;
113   // note: for VP8, setting up idec->io_ is only really needed at the beginning
114   // of the decoding, till partition #0 is complete.
115   idec->io_.data = new_base;
116   idec->io_.data_size = MemDataSize(mem);
117 
118   if (idec->dec_ != NULL) {
119     if (!idec->is_lossless_) {
120       VP8Decoder* const dec = (VP8Decoder*)idec->dec_;
121       const int last_part = dec->num_parts_ - 1;
122       if (offset != 0) {
123         int p;
124         for (p = 0; p <= last_part; ++p) {
125           VP8RemapBitReader(dec->parts_ + p, offset);
126         }
127         // Remap partition #0 data pointer to new offset, but only in MAP
128         // mode (in APPEND mode, partition #0 is copied into a fixed memory).
129         if (mem->mode_ == MEM_MODE_MAP) {
130           VP8RemapBitReader(&dec->br_, offset);
131         }
132       }
133       {
134         const uint8_t* const last_start = dec->parts_[last_part].buf_;
135         assert(last_part >= 0);
136         VP8BitReaderSetBuffer(&dec->parts_[last_part], last_start,
137                               mem->buf_ + mem->end_ - last_start);
138       }
139       if (NeedCompressedAlpha(idec)) {
140         ALPHDecoder* const alph_dec = dec->alph_dec_;
141         dec->alpha_data_ += offset;
142         if (alph_dec != NULL) {
143           if (alph_dec->method_ == ALPHA_LOSSLESS_COMPRESSION) {
144             VP8LDecoder* const alph_vp8l_dec = alph_dec->vp8l_dec_;
145             assert(alph_vp8l_dec != NULL);
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     return WebPFlipBuffer(output);
253   } else {
254     return VP8_STATUS_OK;
255   }
256 }
257 
258 //------------------------------------------------------------------------------
259 // Macroblock-decoding contexts
260 
SaveContext(const VP8Decoder * dec,const VP8BitReader * token_br,MBContext * const context)261 static void SaveContext(const VP8Decoder* dec, const VP8BitReader* token_br,
262                         MBContext* const context) {
263   context->left_ = dec->mb_info_[-1];
264   context->info_ = dec->mb_info_[dec->mb_x_];
265   context->token_br_ = *token_br;
266 }
267 
RestoreContext(const MBContext * context,VP8Decoder * const dec,VP8BitReader * const token_br)268 static void RestoreContext(const MBContext* context, VP8Decoder* const dec,
269                            VP8BitReader* const token_br) {
270   dec->mb_info_[-1] = context->left_;
271   dec->mb_info_[dec->mb_x_] = context->info_;
272   *token_br = context->token_br_;
273 }
274 
275 //------------------------------------------------------------------------------
276 
IDecError(WebPIDecoder * const idec,VP8StatusCode error)277 static VP8StatusCode IDecError(WebPIDecoder* const idec, VP8StatusCode error) {
278   if (idec->state_ == STATE_VP8_DATA) {
279     VP8Io* const io = &idec->io_;
280     if (io->teardown != NULL) {
281       io->teardown(io);
282     }
283   }
284   idec->state_ = STATE_ERROR;
285   return error;
286 }
287 
ChangeState(WebPIDecoder * const idec,DecState new_state,size_t consumed_bytes)288 static void ChangeState(WebPIDecoder* const idec, DecState new_state,
289                         size_t consumed_bytes) {
290   MemBuffer* const mem = &idec->mem_;
291   idec->state_ = new_state;
292   mem->start_ += consumed_bytes;
293   assert(mem->start_ <= mem->end_);
294   idec->io_.data = mem->buf_ + mem->start_;
295   idec->io_.data_size = MemDataSize(mem);
296 }
297 
298 // Headers
DecodeWebPHeaders(WebPIDecoder * const idec)299 static VP8StatusCode DecodeWebPHeaders(WebPIDecoder* const idec) {
300   MemBuffer* const mem = &idec->mem_;
301   const uint8_t* data = mem->buf_ + mem->start_;
302   size_t curr_size = MemDataSize(mem);
303   VP8StatusCode status;
304   WebPHeaderStructure headers;
305 
306   headers.data = data;
307   headers.data_size = curr_size;
308   headers.have_all_data = 0;
309   status = WebPParseHeaders(&headers);
310   if (status == VP8_STATUS_NOT_ENOUGH_DATA) {
311     return VP8_STATUS_SUSPENDED;  // We haven't found a VP8 chunk yet.
312   } else if (status != VP8_STATUS_OK) {
313     return IDecError(idec, status);
314   }
315 
316   idec->chunk_size_ = headers.compressed_size;
317   idec->is_lossless_ = headers.is_lossless;
318   if (!idec->is_lossless_) {
319     VP8Decoder* const dec = VP8New();
320     if (dec == NULL) {
321       return VP8_STATUS_OUT_OF_MEMORY;
322     }
323     idec->dec_ = dec;
324     dec->alpha_data_ = headers.alpha_data;
325     dec->alpha_data_size_ = headers.alpha_data_size;
326     ChangeState(idec, STATE_VP8_HEADER, headers.offset);
327   } else {
328     VP8LDecoder* const dec = VP8LNew();
329     if (dec == NULL) {
330       return VP8_STATUS_OUT_OF_MEMORY;
331     }
332     idec->dec_ = dec;
333     ChangeState(idec, STATE_VP8L_HEADER, headers.offset);
334   }
335   return VP8_STATUS_OK;
336 }
337 
DecodeVP8FrameHeader(WebPIDecoder * const idec)338 static VP8StatusCode DecodeVP8FrameHeader(WebPIDecoder* const idec) {
339   const uint8_t* data = idec->mem_.buf_ + idec->mem_.start_;
340   const size_t curr_size = MemDataSize(&idec->mem_);
341   int width, height;
342   uint32_t bits;
343 
344   if (curr_size < VP8_FRAME_HEADER_SIZE) {
345     // Not enough data bytes to extract VP8 Frame Header.
346     return VP8_STATUS_SUSPENDED;
347   }
348   if (!VP8GetInfo(data, curr_size, idec->chunk_size_, &width, &height)) {
349     return IDecError(idec, VP8_STATUS_BITSTREAM_ERROR);
350   }
351 
352   bits = data[0] | (data[1] << 8) | (data[2] << 16);
353   idec->mem_.part0_size_ = (bits >> 5) + VP8_FRAME_HEADER_SIZE;
354 
355   idec->io_.data = data;
356   idec->io_.data_size = curr_size;
357   idec->state_ = STATE_VP8_PARTS0;
358   return VP8_STATUS_OK;
359 }
360 
361 // Partition #0
CopyParts0Data(WebPIDecoder * const idec)362 static VP8StatusCode CopyParts0Data(WebPIDecoder* const idec) {
363   VP8Decoder* const dec = (VP8Decoder*)idec->dec_;
364   VP8BitReader* const br = &dec->br_;
365   const size_t part_size = br->buf_end_ - br->buf_;
366   MemBuffer* const mem = &idec->mem_;
367   assert(!idec->is_lossless_);
368   assert(mem->part0_buf_ == NULL);
369   // the following is a format limitation, no need for runtime check:
370   assert(part_size <= mem->part0_size_);
371   if (part_size == 0) {   // can't have zero-size partition #0
372     return VP8_STATUS_BITSTREAM_ERROR;
373   }
374   if (mem->mode_ == MEM_MODE_APPEND) {
375     // We copy and grab ownership of the partition #0 data.
376     uint8_t* const part0_buf = (uint8_t*)WebPSafeMalloc(1ULL, part_size);
377     if (part0_buf == NULL) {
378       return VP8_STATUS_OUT_OF_MEMORY;
379     }
380     memcpy(part0_buf, br->buf_, part_size);
381     mem->part0_buf_ = part0_buf;
382     VP8BitReaderSetBuffer(br, part0_buf, part_size);
383   } else {
384     // Else: just keep pointers to the partition #0's data in dec_->br_.
385   }
386   mem->start_ += part_size;
387   return VP8_STATUS_OK;
388 }
389 
DecodePartition0(WebPIDecoder * const idec)390 static VP8StatusCode DecodePartition0(WebPIDecoder* const idec) {
391   VP8Decoder* const dec = (VP8Decoder*)idec->dec_;
392   VP8Io* const io = &idec->io_;
393   const WebPDecParams* const params = &idec->params_;
394   WebPDecBuffer* const output = params->output;
395 
396   // Wait till we have enough data for the whole partition #0
397   if (MemDataSize(&idec->mem_) < idec->mem_.part0_size_) {
398     return VP8_STATUS_SUSPENDED;
399   }
400 
401   if (!VP8GetHeaders(dec, io)) {
402     const VP8StatusCode status = dec->status_;
403     if (status == VP8_STATUS_SUSPENDED ||
404         status == VP8_STATUS_NOT_ENOUGH_DATA) {
405       // treating NOT_ENOUGH_DATA as SUSPENDED state
406       return VP8_STATUS_SUSPENDED;
407     }
408     return IDecError(idec, status);
409   }
410 
411   // Allocate/Verify output buffer now
412   dec->status_ = WebPAllocateDecBuffer(io->width, io->height, params->options,
413                                        output);
414   if (dec->status_ != VP8_STATUS_OK) {
415     return IDecError(idec, dec->status_);
416   }
417   // This change must be done before calling VP8InitFrame()
418   dec->mt_method_ = VP8GetThreadMethod(params->options, NULL,
419                                        io->width, io->height);
420   VP8InitDithering(params->options, dec);
421 
422   dec->status_ = CopyParts0Data(idec);
423   if (dec->status_ != VP8_STATUS_OK) {
424     return IDecError(idec, dec->status_);
425   }
426 
427   // Finish setting up the decoding parameters. Will call io->setup().
428   if (VP8EnterCritical(dec, io) != VP8_STATUS_OK) {
429     return IDecError(idec, dec->status_);
430   }
431 
432   // Note: past this point, teardown() must always be called
433   // in case of error.
434   idec->state_ = STATE_VP8_DATA;
435   // Allocate memory and prepare everything.
436   if (!VP8InitFrame(dec, io)) {
437     return IDecError(idec, dec->status_);
438   }
439   return VP8_STATUS_OK;
440 }
441 
442 // Remaining partitions
DecodeRemaining(WebPIDecoder * const idec)443 static VP8StatusCode DecodeRemaining(WebPIDecoder* const idec) {
444   VP8Decoder* const dec = (VP8Decoder*)idec->dec_;
445   VP8Io* const io = &idec->io_;
446 
447   assert(dec->ready_);
448   for (; dec->mb_y_ < dec->mb_h_; ++dec->mb_y_) {
449     if (idec->last_mb_y_ != dec->mb_y_) {
450       if (!VP8ParseIntraModeRow(&dec->br_, dec)) {
451         // note: normally, error shouldn't occur since we already have the whole
452         // partition0 available here in DecodeRemaining(). Reaching EOF while
453         // reading intra modes really means a BITSTREAM_ERROR.
454         return IDecError(idec, VP8_STATUS_BITSTREAM_ERROR);
455       }
456       idec->last_mb_y_ = dec->mb_y_;
457     }
458     for (; dec->mb_x_ < dec->mb_w_; ++dec->mb_x_) {
459       VP8BitReader* const token_br =
460           &dec->parts_[dec->mb_y_ & (dec->num_parts_ - 1)];
461       MBContext context;
462       SaveContext(dec, token_br, &context);
463       if (!VP8DecodeMB(dec, token_br)) {
464         // We shouldn't fail when MAX_MB data was available
465         if (dec->num_parts_ == 1 && MemDataSize(&idec->mem_) > MAX_MB_SIZE) {
466           return IDecError(idec, VP8_STATUS_BITSTREAM_ERROR);
467         }
468         RestoreContext(&context, dec, token_br);
469         return VP8_STATUS_SUSPENDED;
470       }
471       // Release buffer only if there is only one partition
472       if (dec->num_parts_ == 1) {
473         idec->mem_.start_ = token_br->buf_ - idec->mem_.buf_;
474         assert(idec->mem_.start_ <= idec->mem_.end_);
475       }
476     }
477     VP8InitScanline(dec);   // Prepare for next scanline
478 
479     // Reconstruct, filter and emit the row.
480     if (!VP8ProcessRow(dec, io)) {
481       return IDecError(idec, VP8_STATUS_USER_ABORT);
482     }
483   }
484   // Synchronize the thread and check for errors.
485   if (!VP8ExitCritical(dec, io)) {
486     return IDecError(idec, VP8_STATUS_USER_ABORT);
487   }
488   dec->ready_ = 0;
489   return FinishDecoding(idec);
490 }
491 
ErrorStatusLossless(WebPIDecoder * const idec,VP8StatusCode status)492 static VP8StatusCode ErrorStatusLossless(WebPIDecoder* const idec,
493                                          VP8StatusCode status) {
494   if (status == VP8_STATUS_SUSPENDED || status == VP8_STATUS_NOT_ENOUGH_DATA) {
495     return VP8_STATUS_SUSPENDED;
496   }
497   return IDecError(idec, status);
498 }
499 
DecodeVP8LHeader(WebPIDecoder * const idec)500 static VP8StatusCode DecodeVP8LHeader(WebPIDecoder* const idec) {
501   VP8Io* const io = &idec->io_;
502   VP8LDecoder* const dec = (VP8LDecoder*)idec->dec_;
503   const WebPDecParams* const params = &idec->params_;
504   WebPDecBuffer* const output = params->output;
505   size_t curr_size = MemDataSize(&idec->mem_);
506   assert(idec->is_lossless_);
507 
508   // Wait until there's enough data for decoding header.
509   if (curr_size < (idec->chunk_size_ >> 3)) {
510     dec->status_ = VP8_STATUS_SUSPENDED;
511     return ErrorStatusLossless(idec, dec->status_);
512   }
513 
514   if (!VP8LDecodeHeader(dec, io)) {
515     if (dec->status_ == VP8_STATUS_BITSTREAM_ERROR &&
516         curr_size < idec->chunk_size_) {
517       dec->status_ = VP8_STATUS_SUSPENDED;
518     }
519     return ErrorStatusLossless(idec, dec->status_);
520   }
521   // Allocate/verify output buffer now.
522   dec->status_ = WebPAllocateDecBuffer(io->width, io->height, params->options,
523                                        output);
524   if (dec->status_ != VP8_STATUS_OK) {
525     return IDecError(idec, dec->status_);
526   }
527 
528   idec->state_ = STATE_VP8L_DATA;
529   return VP8_STATUS_OK;
530 }
531 
DecodeVP8LData(WebPIDecoder * const idec)532 static VP8StatusCode DecodeVP8LData(WebPIDecoder* const idec) {
533   VP8LDecoder* const dec = (VP8LDecoder*)idec->dec_;
534   const size_t curr_size = MemDataSize(&idec->mem_);
535   assert(idec->is_lossless_);
536 
537   // Switch to incremental decoding if we don't have all the bytes available.
538   dec->incremental_ = (curr_size < idec->chunk_size_);
539 
540   if (!VP8LDecodeImage(dec)) {
541     return ErrorStatusLossless(idec, dec->status_);
542   }
543   assert(dec->status_ == VP8_STATUS_OK || dec->status_ == VP8_STATUS_SUSPENDED);
544   return (dec->status_ == VP8_STATUS_SUSPENDED) ? dec->status_
545                                                 : FinishDecoding(idec);
546 }
547 
548   // Main decoding loop
IDecode(WebPIDecoder * idec)549 static VP8StatusCode IDecode(WebPIDecoder* idec) {
550   VP8StatusCode status = VP8_STATUS_SUSPENDED;
551 
552   if (idec->state_ == STATE_WEBP_HEADER) {
553     status = DecodeWebPHeaders(idec);
554   } else {
555     if (idec->dec_ == NULL) {
556       return VP8_STATUS_SUSPENDED;    // can't continue if we have no decoder.
557     }
558   }
559   if (idec->state_ == STATE_VP8_HEADER) {
560     status = DecodeVP8FrameHeader(idec);
561   }
562   if (idec->state_ == STATE_VP8_PARTS0) {
563     status = DecodePartition0(idec);
564   }
565   if (idec->state_ == STATE_VP8_DATA) {
566     status = DecodeRemaining(idec);
567   }
568   if (idec->state_ == STATE_VP8L_HEADER) {
569     status = DecodeVP8LHeader(idec);
570   }
571   if (idec->state_ == STATE_VP8L_DATA) {
572     status = DecodeVP8LData(idec);
573   }
574   return status;
575 }
576 
577 //------------------------------------------------------------------------------
578 // Public functions
579 
WebPINewDecoder(WebPDecBuffer * output_buffer)580 WebPIDecoder* WebPINewDecoder(WebPDecBuffer* output_buffer) {
581   WebPIDecoder* idec = (WebPIDecoder*)WebPSafeCalloc(1ULL, sizeof(*idec));
582   if (idec == NULL) {
583     return NULL;
584   }
585 
586   idec->state_ = STATE_WEBP_HEADER;
587   idec->chunk_size_ = 0;
588 
589   idec->last_mb_y_ = -1;
590 
591   InitMemBuffer(&idec->mem_);
592   WebPInitDecBuffer(&idec->output_);
593   VP8InitIo(&idec->io_);
594 
595   WebPResetDecParams(&idec->params_);
596   idec->params_.output = (output_buffer != NULL) ? output_buffer
597                                                  : &idec->output_;
598   WebPInitCustomIo(&idec->params_, &idec->io_);  // Plug the I/O functions.
599 
600   return idec;
601 }
602 
WebPIDecode(const uint8_t * data,size_t data_size,WebPDecoderConfig * config)603 WebPIDecoder* WebPIDecode(const uint8_t* data, size_t data_size,
604                           WebPDecoderConfig* config) {
605   WebPIDecoder* idec;
606 
607   // Parse the bitstream's features, if requested:
608   if (data != NULL && data_size > 0 && config != NULL) {
609     if (WebPGetFeatures(data, data_size, &config->input) != VP8_STATUS_OK) {
610       return NULL;
611     }
612   }
613   // Create an instance of the incremental decoder
614   idec = WebPINewDecoder(config ? &config->output : NULL);
615   if (idec == NULL) {
616     return NULL;
617   }
618   // Finish initialization
619   if (config != NULL) {
620     idec->params_.options = &config->options;
621   }
622   return idec;
623 }
624 
WebPIDelete(WebPIDecoder * idec)625 void WebPIDelete(WebPIDecoder* idec) {
626   if (idec == NULL) return;
627   if (idec->dec_ != NULL) {
628     if (!idec->is_lossless_) {
629       if (idec->state_ == STATE_VP8_DATA) {
630         // Synchronize the thread, clean-up and check for errors.
631         VP8ExitCritical((VP8Decoder*)idec->dec_, &idec->io_);
632       }
633       VP8Delete((VP8Decoder*)idec->dec_);
634     } else {
635       VP8LDelete((VP8LDecoder*)idec->dec_);
636     }
637   }
638   ClearMemBuffer(&idec->mem_);
639   WebPFreeDecBuffer(&idec->output_);
640   WebPSafeFree(idec);
641 }
642 
643 //------------------------------------------------------------------------------
644 // Wrapper toward WebPINewDecoder
645 
WebPINewRGB(WEBP_CSP_MODE mode,uint8_t * output_buffer,size_t output_buffer_size,int output_stride)646 WebPIDecoder* WebPINewRGB(WEBP_CSP_MODE mode, uint8_t* output_buffer,
647                           size_t output_buffer_size, int output_stride) {
648   const int is_external_memory = (output_buffer != NULL);
649   WebPIDecoder* idec;
650 
651   if (mode >= MODE_YUV) return NULL;
652   if (!is_external_memory) {    // Overwrite parameters to sane values.
653     output_buffer_size = 0;
654     output_stride = 0;
655   } else {  // A buffer was passed. Validate the other params.
656     if (output_stride == 0 || output_buffer_size == 0) {
657       return NULL;   // invalid parameter.
658     }
659   }
660   idec = WebPINewDecoder(NULL);
661   if (idec == NULL) return NULL;
662   idec->output_.colorspace = mode;
663   idec->output_.is_external_memory = is_external_memory;
664   idec->output_.u.RGBA.rgba = output_buffer;
665   idec->output_.u.RGBA.stride = output_stride;
666   idec->output_.u.RGBA.size = output_buffer_size;
667   return idec;
668 }
669 
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)670 WebPIDecoder* WebPINewYUVA(uint8_t* luma, size_t luma_size, int luma_stride,
671                            uint8_t* u, size_t u_size, int u_stride,
672                            uint8_t* v, size_t v_size, int v_stride,
673                            uint8_t* a, size_t a_size, int a_stride) {
674   const int is_external_memory = (luma != NULL);
675   WebPIDecoder* idec;
676   WEBP_CSP_MODE colorspace;
677 
678   if (!is_external_memory) {    // Overwrite parameters to sane values.
679     luma_size = u_size = v_size = a_size = 0;
680     luma_stride = u_stride = v_stride = a_stride = 0;
681     u = v = a = NULL;
682     colorspace = MODE_YUVA;
683   } else {  // A luma buffer was passed. Validate the other parameters.
684     if (u == NULL || v == NULL) return NULL;
685     if (luma_size == 0 || u_size == 0 || v_size == 0) return NULL;
686     if (luma_stride == 0 || u_stride == 0 || v_stride == 0) return NULL;
687     if (a != NULL) {
688       if (a_size == 0 || a_stride == 0) return NULL;
689     }
690     colorspace = (a == NULL) ? MODE_YUV : MODE_YUVA;
691   }
692 
693   idec = WebPINewDecoder(NULL);
694   if (idec == NULL) return NULL;
695 
696   idec->output_.colorspace = colorspace;
697   idec->output_.is_external_memory = is_external_memory;
698   idec->output_.u.YUVA.y = luma;
699   idec->output_.u.YUVA.y_stride = luma_stride;
700   idec->output_.u.YUVA.y_size = luma_size;
701   idec->output_.u.YUVA.u = u;
702   idec->output_.u.YUVA.u_stride = u_stride;
703   idec->output_.u.YUVA.u_size = u_size;
704   idec->output_.u.YUVA.v = v;
705   idec->output_.u.YUVA.v_stride = v_stride;
706   idec->output_.u.YUVA.v_size = v_size;
707   idec->output_.u.YUVA.a = a;
708   idec->output_.u.YUVA.a_stride = a_stride;
709   idec->output_.u.YUVA.a_size = a_size;
710   return idec;
711 }
712 
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)713 WebPIDecoder* WebPINewYUV(uint8_t* luma, size_t luma_size, int luma_stride,
714                           uint8_t* u, size_t u_size, int u_stride,
715                           uint8_t* v, size_t v_size, int v_stride) {
716   return WebPINewYUVA(luma, luma_size, luma_stride,
717                       u, u_size, u_stride,
718                       v, v_size, v_stride,
719                       NULL, 0, 0);
720 }
721 
722 //------------------------------------------------------------------------------
723 
IDecCheckStatus(const WebPIDecoder * const idec)724 static VP8StatusCode IDecCheckStatus(const WebPIDecoder* const idec) {
725   assert(idec);
726   if (idec->state_ == STATE_ERROR) {
727     return VP8_STATUS_BITSTREAM_ERROR;
728   }
729   if (idec->state_ == STATE_DONE) {
730     return VP8_STATUS_OK;
731   }
732   return VP8_STATUS_SUSPENDED;
733 }
734 
WebPIAppend(WebPIDecoder * idec,const uint8_t * data,size_t data_size)735 VP8StatusCode WebPIAppend(WebPIDecoder* idec,
736                           const uint8_t* data, size_t data_size) {
737   VP8StatusCode status;
738   if (idec == NULL || data == NULL) {
739     return VP8_STATUS_INVALID_PARAM;
740   }
741   status = IDecCheckStatus(idec);
742   if (status != VP8_STATUS_SUSPENDED) {
743     return status;
744   }
745   // Check mixed calls between RemapMemBuffer and AppendToMemBuffer.
746   if (!CheckMemBufferMode(&idec->mem_, MEM_MODE_APPEND)) {
747     return VP8_STATUS_INVALID_PARAM;
748   }
749   // Append data to memory buffer
750   if (!AppendToMemBuffer(idec, data, data_size)) {
751     return VP8_STATUS_OUT_OF_MEMORY;
752   }
753   return IDecode(idec);
754 }
755 
WebPIUpdate(WebPIDecoder * idec,const uint8_t * data,size_t data_size)756 VP8StatusCode WebPIUpdate(WebPIDecoder* idec,
757                           const uint8_t* data, size_t data_size) {
758   VP8StatusCode status;
759   if (idec == NULL || data == NULL) {
760     return VP8_STATUS_INVALID_PARAM;
761   }
762   status = IDecCheckStatus(idec);
763   if (status != VP8_STATUS_SUSPENDED) {
764     return status;
765   }
766   // Check mixed calls between RemapMemBuffer and AppendToMemBuffer.
767   if (!CheckMemBufferMode(&idec->mem_, MEM_MODE_MAP)) {
768     return VP8_STATUS_INVALID_PARAM;
769   }
770   // Make the memory buffer point to the new buffer
771   if (!RemapMemBuffer(idec, data, data_size)) {
772     return VP8_STATUS_INVALID_PARAM;
773   }
774   return IDecode(idec);
775 }
776 
777 //------------------------------------------------------------------------------
778 
GetOutputBuffer(const WebPIDecoder * const idec)779 static const WebPDecBuffer* GetOutputBuffer(const WebPIDecoder* const idec) {
780   if (idec == NULL || idec->dec_ == NULL) {
781     return NULL;
782   }
783   if (idec->state_ <= STATE_VP8_PARTS0) {
784     return NULL;
785   }
786   return idec->params_.output;
787 }
788 
WebPIDecodedArea(const WebPIDecoder * idec,int * left,int * top,int * width,int * height)789 const WebPDecBuffer* WebPIDecodedArea(const WebPIDecoder* idec,
790                                       int* left, int* top,
791                                       int* width, int* height) {
792   const WebPDecBuffer* const src = GetOutputBuffer(idec);
793   if (left != NULL) *left = 0;
794   if (top != NULL) *top = 0;
795   if (src) {
796     if (width != NULL) *width = src->width;
797     if (height != NULL) *height = idec->params_.last_y;
798   } else {
799     if (width != NULL) *width = 0;
800     if (height != NULL) *height = 0;
801   }
802   return src;
803 }
804 
WebPIDecGetRGB(const WebPIDecoder * idec,int * last_y,int * width,int * height,int * stride)805 uint8_t* WebPIDecGetRGB(const WebPIDecoder* idec, int* last_y,
806                         int* width, int* height, int* stride) {
807   const WebPDecBuffer* const src = GetOutputBuffer(idec);
808   if (src == NULL) return NULL;
809   if (src->colorspace >= MODE_YUV) {
810     return NULL;
811   }
812 
813   if (last_y != NULL) *last_y = idec->params_.last_y;
814   if (width != NULL) *width = src->width;
815   if (height != NULL) *height = src->height;
816   if (stride != NULL) *stride = src->u.RGBA.stride;
817 
818   return src->u.RGBA.rgba;
819 }
820 
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)821 uint8_t* WebPIDecGetYUVA(const WebPIDecoder* idec, int* last_y,
822                          uint8_t** u, uint8_t** v, uint8_t** a,
823                          int* width, int* height,
824                          int* stride, int* uv_stride, int* a_stride) {
825   const WebPDecBuffer* const src = GetOutputBuffer(idec);
826   if (src == NULL) return NULL;
827   if (src->colorspace < MODE_YUV) {
828     return NULL;
829   }
830 
831   if (last_y != NULL) *last_y = idec->params_.last_y;
832   if (u != NULL) *u = src->u.YUVA.u;
833   if (v != NULL) *v = src->u.YUVA.v;
834   if (a != NULL) *a = src->u.YUVA.a;
835   if (width != NULL) *width = src->width;
836   if (height != NULL) *height = src->height;
837   if (stride != NULL) *stride = src->u.YUVA.y_stride;
838   if (uv_stride != NULL) *uv_stride = src->u.YUVA.u_stride;
839   if (a_stride != NULL) *a_stride = src->u.YUVA.a_stride;
840 
841   return src->u.YUVA.y;
842 }
843 
WebPISetIOHooks(WebPIDecoder * const idec,VP8IoPutHook put,VP8IoSetupHook setup,VP8IoTeardownHook teardown,void * user_data)844 int WebPISetIOHooks(WebPIDecoder* const idec,
845                     VP8IoPutHook put,
846                     VP8IoSetupHook setup,
847                     VP8IoTeardownHook teardown,
848                     void* user_data) {
849   if (idec == NULL || idec->state_ > STATE_WEBP_HEADER) {
850     return 0;
851   }
852 
853   idec->io_.put = put;
854   idec->io_.setup = setup;
855   idec->io_.teardown = teardown;
856   idec->io_.opaque = user_data;
857 
858   return 1;
859 }
860