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