idec_dec.c 30 KB

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