vp8l.c 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404
  1. // Copyright 2012 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. // main entry for the decoder
  11. //
  12. // Authors: Vikas Arora (vikaas.arora@gmail.com)
  13. // Jyrki Alakuijala (jyrki@google.com)
  14. #include <stdlib.h>
  15. #include "./alphai.h"
  16. #include "./vp8li.h"
  17. #include "../dsp/dsp.h"
  18. #include "../dsp/lossless.h"
  19. #include "../dsp/yuv.h"
  20. #include "../utils/huffman.h"
  21. #include "../utils/utils.h"
  22. #define NUM_ARGB_CACHE_ROWS 16
  23. static const int kCodeLengthLiterals = 16;
  24. static const int kCodeLengthRepeatCode = 16;
  25. static const int kCodeLengthExtraBits[3] = { 2, 3, 7 };
  26. static const int kCodeLengthRepeatOffsets[3] = { 3, 3, 11 };
  27. // -----------------------------------------------------------------------------
  28. // Five Huffman codes are used at each meta code:
  29. // 1. green + length prefix codes + color cache codes,
  30. // 2. alpha,
  31. // 3. red,
  32. // 4. blue, and,
  33. // 5. distance prefix codes.
  34. typedef enum {
  35. GREEN = 0,
  36. RED = 1,
  37. BLUE = 2,
  38. ALPHA = 3,
  39. DIST = 4
  40. } HuffIndex;
  41. static const uint16_t kAlphabetSize[HUFFMAN_CODES_PER_META_CODE] = {
  42. NUM_LITERAL_CODES + NUM_LENGTH_CODES,
  43. NUM_LITERAL_CODES, NUM_LITERAL_CODES, NUM_LITERAL_CODES,
  44. NUM_DISTANCE_CODES
  45. };
  46. #define NUM_CODE_LENGTH_CODES 19
  47. static const uint8_t kCodeLengthCodeOrder[NUM_CODE_LENGTH_CODES] = {
  48. 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
  49. };
  50. #define CODE_TO_PLANE_CODES 120
  51. static const uint8_t kCodeToPlane[CODE_TO_PLANE_CODES] = {
  52. 0x18, 0x07, 0x17, 0x19, 0x28, 0x06, 0x27, 0x29, 0x16, 0x1a,
  53. 0x26, 0x2a, 0x38, 0x05, 0x37, 0x39, 0x15, 0x1b, 0x36, 0x3a,
  54. 0x25, 0x2b, 0x48, 0x04, 0x47, 0x49, 0x14, 0x1c, 0x35, 0x3b,
  55. 0x46, 0x4a, 0x24, 0x2c, 0x58, 0x45, 0x4b, 0x34, 0x3c, 0x03,
  56. 0x57, 0x59, 0x13, 0x1d, 0x56, 0x5a, 0x23, 0x2d, 0x44, 0x4c,
  57. 0x55, 0x5b, 0x33, 0x3d, 0x68, 0x02, 0x67, 0x69, 0x12, 0x1e,
  58. 0x66, 0x6a, 0x22, 0x2e, 0x54, 0x5c, 0x43, 0x4d, 0x65, 0x6b,
  59. 0x32, 0x3e, 0x78, 0x01, 0x77, 0x79, 0x53, 0x5d, 0x11, 0x1f,
  60. 0x64, 0x6c, 0x42, 0x4e, 0x76, 0x7a, 0x21, 0x2f, 0x75, 0x7b,
  61. 0x31, 0x3f, 0x63, 0x6d, 0x52, 0x5e, 0x00, 0x74, 0x7c, 0x41,
  62. 0x4f, 0x10, 0x20, 0x62, 0x6e, 0x30, 0x73, 0x7d, 0x51, 0x5f,
  63. 0x40, 0x72, 0x7e, 0x61, 0x6f, 0x50, 0x71, 0x7f, 0x60, 0x70
  64. };
  65. static int DecodeImageStream(int xsize, int ysize,
  66. int is_level0,
  67. VP8LDecoder* const dec,
  68. uint32_t** const decoded_data);
  69. //------------------------------------------------------------------------------
  70. int VP8LCheckSignature(const uint8_t* const data, size_t size) {
  71. return (size >= VP8L_FRAME_HEADER_SIZE &&
  72. data[0] == VP8L_MAGIC_BYTE &&
  73. (data[4] >> 5) == 0); // version
  74. }
  75. static int ReadImageInfo(VP8LBitReader* const br,
  76. int* const width, int* const height,
  77. int* const has_alpha) {
  78. if (VP8LReadBits(br, 8) != VP8L_MAGIC_BYTE) return 0;
  79. *width = VP8LReadBits(br, VP8L_IMAGE_SIZE_BITS) + 1;
  80. *height = VP8LReadBits(br, VP8L_IMAGE_SIZE_BITS) + 1;
  81. *has_alpha = VP8LReadBits(br, 1);
  82. if (VP8LReadBits(br, VP8L_VERSION_BITS) != 0) return 0;
  83. return 1;
  84. }
  85. int VP8LGetInfo(const uint8_t* data, size_t data_size,
  86. int* const width, int* const height, int* const has_alpha) {
  87. if (data == NULL || data_size < VP8L_FRAME_HEADER_SIZE) {
  88. return 0; // not enough data
  89. } else if (!VP8LCheckSignature(data, data_size)) {
  90. return 0; // bad signature
  91. } else {
  92. int w, h, a;
  93. VP8LBitReader br;
  94. VP8LInitBitReader(&br, data, data_size);
  95. if (!ReadImageInfo(&br, &w, &h, &a)) {
  96. return 0;
  97. }
  98. if (width != NULL) *width = w;
  99. if (height != NULL) *height = h;
  100. if (has_alpha != NULL) *has_alpha = a;
  101. return 1;
  102. }
  103. }
  104. //------------------------------------------------------------------------------
  105. static WEBP_INLINE int GetCopyDistance(int distance_symbol,
  106. VP8LBitReader* const br) {
  107. int extra_bits, offset;
  108. if (distance_symbol < 4) {
  109. return distance_symbol + 1;
  110. }
  111. extra_bits = (distance_symbol - 2) >> 1;
  112. offset = (2 + (distance_symbol & 1)) << extra_bits;
  113. return offset + VP8LReadBits(br, extra_bits) + 1;
  114. }
  115. static WEBP_INLINE int GetCopyLength(int length_symbol,
  116. VP8LBitReader* const br) {
  117. // Length and distance prefixes are encoded the same way.
  118. return GetCopyDistance(length_symbol, br);
  119. }
  120. static WEBP_INLINE int PlaneCodeToDistance(int xsize, int plane_code) {
  121. if (plane_code > CODE_TO_PLANE_CODES) {
  122. return plane_code - CODE_TO_PLANE_CODES;
  123. } else {
  124. const int dist_code = kCodeToPlane[plane_code - 1];
  125. const int yoffset = dist_code >> 4;
  126. const int xoffset = 8 - (dist_code & 0xf);
  127. const int dist = yoffset * xsize + xoffset;
  128. return (dist >= 1) ? dist : 1; // dist<1 can happen if xsize is very small
  129. }
  130. }
  131. //------------------------------------------------------------------------------
  132. // Decodes the next Huffman code from bit-stream.
  133. // FillBitWindow(br) needs to be called at minimum every second call
  134. // to ReadSymbol, in order to pre-fetch enough bits.
  135. static WEBP_INLINE int ReadSymbol(const HuffmanTree* tree,
  136. VP8LBitReader* const br) {
  137. const HuffmanTreeNode* node = tree->root_;
  138. uint32_t bits = VP8LPrefetchBits(br);
  139. int bitpos = br->bit_pos_;
  140. // Check if we find the bit combination from the Huffman lookup table.
  141. const int lut_ix = bits & (HUFF_LUT - 1);
  142. const int lut_bits = tree->lut_bits_[lut_ix];
  143. if (lut_bits <= HUFF_LUT_BITS) {
  144. VP8LSetBitPos(br, bitpos + lut_bits);
  145. return tree->lut_symbol_[lut_ix];
  146. }
  147. node += tree->lut_jump_[lut_ix];
  148. bitpos += HUFF_LUT_BITS;
  149. bits >>= HUFF_LUT_BITS;
  150. // Decode the value from a binary tree.
  151. assert(node != NULL);
  152. do {
  153. node = HuffmanTreeNextNode(node, bits & 1);
  154. bits >>= 1;
  155. ++bitpos;
  156. } while (HuffmanTreeNodeIsNotLeaf(node));
  157. VP8LSetBitPos(br, bitpos);
  158. return node->symbol_;
  159. }
  160. static int ReadHuffmanCodeLengths(
  161. VP8LDecoder* const dec, const int* const code_length_code_lengths,
  162. int num_symbols, int* const code_lengths) {
  163. int ok = 0;
  164. VP8LBitReader* const br = &dec->br_;
  165. int symbol;
  166. int max_symbol;
  167. int prev_code_len = DEFAULT_CODE_LENGTH;
  168. HuffmanTree tree;
  169. int huff_codes[NUM_CODE_LENGTH_CODES] = { 0 };
  170. if (!VP8LHuffmanTreeBuildImplicit(&tree, code_length_code_lengths,
  171. huff_codes, NUM_CODE_LENGTH_CODES)) {
  172. dec->status_ = VP8_STATUS_BITSTREAM_ERROR;
  173. return 0;
  174. }
  175. if (VP8LReadBits(br, 1)) { // use length
  176. const int length_nbits = 2 + 2 * VP8LReadBits(br, 3);
  177. max_symbol = 2 + VP8LReadBits(br, length_nbits);
  178. if (max_symbol > num_symbols) {
  179. dec->status_ = VP8_STATUS_BITSTREAM_ERROR;
  180. goto End;
  181. }
  182. } else {
  183. max_symbol = num_symbols;
  184. }
  185. symbol = 0;
  186. while (symbol < num_symbols) {
  187. int code_len;
  188. if (max_symbol-- == 0) break;
  189. VP8LFillBitWindow(br);
  190. code_len = ReadSymbol(&tree, br);
  191. if (code_len < kCodeLengthLiterals) {
  192. code_lengths[symbol++] = code_len;
  193. if (code_len != 0) prev_code_len = code_len;
  194. } else {
  195. const int use_prev = (code_len == kCodeLengthRepeatCode);
  196. const int slot = code_len - kCodeLengthLiterals;
  197. const int extra_bits = kCodeLengthExtraBits[slot];
  198. const int repeat_offset = kCodeLengthRepeatOffsets[slot];
  199. int repeat = VP8LReadBits(br, extra_bits) + repeat_offset;
  200. if (symbol + repeat > num_symbols) {
  201. dec->status_ = VP8_STATUS_BITSTREAM_ERROR;
  202. goto End;
  203. } else {
  204. const int length = use_prev ? prev_code_len : 0;
  205. while (repeat-- > 0) code_lengths[symbol++] = length;
  206. }
  207. }
  208. }
  209. ok = 1;
  210. End:
  211. VP8LHuffmanTreeFree(&tree);
  212. if (!ok) dec->status_ = VP8_STATUS_BITSTREAM_ERROR;
  213. return ok;
  214. }
  215. // 'code_lengths' is pre-allocated temporary buffer, used for creating Huffman
  216. // tree.
  217. static int ReadHuffmanCode(int alphabet_size, VP8LDecoder* const dec,
  218. int* const code_lengths, int* const huff_codes,
  219. HuffmanTree* const tree) {
  220. int ok = 0;
  221. VP8LBitReader* const br = &dec->br_;
  222. const int simple_code = VP8LReadBits(br, 1);
  223. if (simple_code) { // Read symbols, codes & code lengths directly.
  224. int symbols[2];
  225. int codes[2];
  226. const int num_symbols = VP8LReadBits(br, 1) + 1;
  227. const int first_symbol_len_code = VP8LReadBits(br, 1);
  228. // The first code is either 1 bit or 8 bit code.
  229. symbols[0] = VP8LReadBits(br, (first_symbol_len_code == 0) ? 1 : 8);
  230. codes[0] = 0;
  231. code_lengths[0] = num_symbols - 1;
  232. // The second code (if present), is always 8 bit long.
  233. if (num_symbols == 2) {
  234. symbols[1] = VP8LReadBits(br, 8);
  235. codes[1] = 1;
  236. code_lengths[1] = num_symbols - 1;
  237. }
  238. ok = VP8LHuffmanTreeBuildExplicit(tree, code_lengths, codes, symbols,
  239. alphabet_size, num_symbols);
  240. } else { // Decode Huffman-coded code lengths.
  241. int i;
  242. int code_length_code_lengths[NUM_CODE_LENGTH_CODES] = { 0 };
  243. const int num_codes = VP8LReadBits(br, 4) + 4;
  244. if (num_codes > NUM_CODE_LENGTH_CODES) {
  245. dec->status_ = VP8_STATUS_BITSTREAM_ERROR;
  246. return 0;
  247. }
  248. memset(code_lengths, 0, alphabet_size * sizeof(*code_lengths));
  249. for (i = 0; i < num_codes; ++i) {
  250. code_length_code_lengths[kCodeLengthCodeOrder[i]] = VP8LReadBits(br, 3);
  251. }
  252. ok = ReadHuffmanCodeLengths(dec, code_length_code_lengths, alphabet_size,
  253. code_lengths);
  254. ok = ok && VP8LHuffmanTreeBuildImplicit(tree, code_lengths, huff_codes,
  255. alphabet_size);
  256. }
  257. ok = ok && !br->error_;
  258. if (!ok) {
  259. dec->status_ = VP8_STATUS_BITSTREAM_ERROR;
  260. return 0;
  261. }
  262. return 1;
  263. }
  264. static int ReadHuffmanCodes(VP8LDecoder* const dec, int xsize, int ysize,
  265. int color_cache_bits, int allow_recursion) {
  266. int i, j;
  267. VP8LBitReader* const br = &dec->br_;
  268. VP8LMetadata* const hdr = &dec->hdr_;
  269. uint32_t* huffman_image = NULL;
  270. HTreeGroup* htree_groups = NULL;
  271. int num_htree_groups = 1;
  272. int max_alphabet_size = 0;
  273. int* code_lengths = NULL;
  274. int* huff_codes = NULL;
  275. if (allow_recursion && VP8LReadBits(br, 1)) {
  276. // use meta Huffman codes.
  277. const int huffman_precision = VP8LReadBits(br, 3) + 2;
  278. const int huffman_xsize = VP8LSubSampleSize(xsize, huffman_precision);
  279. const int huffman_ysize = VP8LSubSampleSize(ysize, huffman_precision);
  280. const int huffman_pixs = huffman_xsize * huffman_ysize;
  281. if (!DecodeImageStream(huffman_xsize, huffman_ysize, 0, dec,
  282. &huffman_image)) {
  283. dec->status_ = VP8_STATUS_BITSTREAM_ERROR;
  284. goto Error;
  285. }
  286. hdr->huffman_subsample_bits_ = huffman_precision;
  287. for (i = 0; i < huffman_pixs; ++i) {
  288. // The huffman data is stored in red and green bytes.
  289. const int group = (huffman_image[i] >> 8) & 0xffff;
  290. huffman_image[i] = group;
  291. if (group >= num_htree_groups) {
  292. num_htree_groups = group + 1;
  293. }
  294. }
  295. }
  296. if (br->error_) goto Error;
  297. // Find maximum alphabet size for the htree group.
  298. for (j = 0; j < HUFFMAN_CODES_PER_META_CODE; ++j) {
  299. int alphabet_size = kAlphabetSize[j];
  300. if (j == 0 && color_cache_bits > 0) {
  301. alphabet_size += 1 << color_cache_bits;
  302. }
  303. if (max_alphabet_size < alphabet_size) {
  304. max_alphabet_size = alphabet_size;
  305. }
  306. }
  307. htree_groups = VP8LHtreeGroupsNew(num_htree_groups);
  308. code_lengths =
  309. (int*)WebPSafeCalloc((uint64_t)max_alphabet_size, sizeof(*code_lengths));
  310. huff_codes =
  311. (int*)WebPSafeMalloc((uint64_t)max_alphabet_size, sizeof(*huff_codes));
  312. if (htree_groups == NULL || code_lengths == NULL || huff_codes == NULL) {
  313. dec->status_ = VP8_STATUS_OUT_OF_MEMORY;
  314. goto Error;
  315. }
  316. for (i = 0; i < num_htree_groups; ++i) {
  317. HuffmanTree* const htrees = htree_groups[i].htrees_;
  318. for (j = 0; j < HUFFMAN_CODES_PER_META_CODE; ++j) {
  319. int alphabet_size = kAlphabetSize[j];
  320. HuffmanTree* const htree = htrees + j;
  321. if (j == 0 && color_cache_bits > 0) {
  322. alphabet_size += 1 << color_cache_bits;
  323. }
  324. if (!ReadHuffmanCode(alphabet_size, dec, code_lengths, huff_codes,
  325. htree)) {
  326. goto Error;
  327. }
  328. }
  329. }
  330. WebPSafeFree(huff_codes);
  331. WebPSafeFree(code_lengths);
  332. // All OK. Finalize pointers and return.
  333. hdr->huffman_image_ = huffman_image;
  334. hdr->num_htree_groups_ = num_htree_groups;
  335. hdr->htree_groups_ = htree_groups;
  336. return 1;
  337. Error:
  338. WebPSafeFree(huff_codes);
  339. WebPSafeFree(code_lengths);
  340. WebPSafeFree(huffman_image);
  341. VP8LHtreeGroupsFree(htree_groups, num_htree_groups);
  342. return 0;
  343. }
  344. //------------------------------------------------------------------------------
  345. // Scaling.
  346. static int AllocateAndInitRescaler(VP8LDecoder* const dec, VP8Io* const io) {
  347. const int num_channels = 4;
  348. const int in_width = io->mb_w;
  349. const int out_width = io->scaled_width;
  350. const int in_height = io->mb_h;
  351. const int out_height = io->scaled_height;
  352. const uint64_t work_size = 2 * num_channels * (uint64_t)out_width;
  353. int32_t* work; // Rescaler work area.
  354. const uint64_t scaled_data_size = num_channels * (uint64_t)out_width;
  355. uint32_t* scaled_data; // Temporary storage for scaled BGRA data.
  356. const uint64_t memory_size = sizeof(*dec->rescaler) +
  357. work_size * sizeof(*work) +
  358. scaled_data_size * sizeof(*scaled_data);
  359. uint8_t* memory = (uint8_t*)WebPSafeCalloc(memory_size, sizeof(*memory));
  360. if (memory == NULL) {
  361. dec->status_ = VP8_STATUS_OUT_OF_MEMORY;
  362. return 0;
  363. }
  364. assert(dec->rescaler_memory == NULL);
  365. dec->rescaler_memory = memory;
  366. dec->rescaler = (WebPRescaler*)memory;
  367. memory += sizeof(*dec->rescaler);
  368. work = (int32_t*)memory;
  369. memory += work_size * sizeof(*work);
  370. scaled_data = (uint32_t*)memory;
  371. WebPRescalerInit(dec->rescaler, in_width, in_height, (uint8_t*)scaled_data,
  372. out_width, out_height, 0, num_channels,
  373. in_width, out_width, in_height, out_height, work);
  374. return 1;
  375. }
  376. //------------------------------------------------------------------------------
  377. // Export to ARGB
  378. // We have special "export" function since we need to convert from BGRA
  379. static int Export(WebPRescaler* const rescaler, WEBP_CSP_MODE colorspace,
  380. int rgba_stride, uint8_t* const rgba) {
  381. uint32_t* const src = (uint32_t*)rescaler->dst;
  382. const int dst_width = rescaler->dst_width;
  383. int num_lines_out = 0;
  384. while (WebPRescalerHasPendingOutput(rescaler)) {
  385. uint8_t* const dst = rgba + num_lines_out * rgba_stride;
  386. WebPRescalerExportRow(rescaler, 0);
  387. WebPMultARGBRow(src, dst_width, 1);
  388. VP8LConvertFromBGRA(src, dst_width, colorspace, dst);
  389. ++num_lines_out;
  390. }
  391. return num_lines_out;
  392. }
  393. // Emit scaled rows.
  394. static int EmitRescaledRowsRGBA(const VP8LDecoder* const dec,
  395. uint8_t* in, int in_stride, int mb_h,
  396. uint8_t* const out, int out_stride) {
  397. const WEBP_CSP_MODE colorspace = dec->output_->colorspace;
  398. int num_lines_in = 0;
  399. int num_lines_out = 0;
  400. while (num_lines_in < mb_h) {
  401. uint8_t* const row_in = in + num_lines_in * in_stride;
  402. uint8_t* const row_out = out + num_lines_out * out_stride;
  403. const int lines_left = mb_h - num_lines_in;
  404. const int needed_lines = WebPRescaleNeededLines(dec->rescaler, lines_left);
  405. assert(needed_lines > 0 && needed_lines <= lines_left);
  406. WebPMultARGBRows(row_in, in_stride,
  407. dec->rescaler->src_width, needed_lines, 0);
  408. WebPRescalerImport(dec->rescaler, lines_left, row_in, in_stride);
  409. num_lines_in += needed_lines;
  410. num_lines_out += Export(dec->rescaler, colorspace, out_stride, row_out);
  411. }
  412. return num_lines_out;
  413. }
  414. // Emit rows without any scaling.
  415. static int EmitRows(WEBP_CSP_MODE colorspace,
  416. const uint8_t* row_in, int in_stride,
  417. int mb_w, int mb_h,
  418. uint8_t* const out, int out_stride) {
  419. int lines = mb_h;
  420. uint8_t* row_out = out;
  421. while (lines-- > 0) {
  422. VP8LConvertFromBGRA((const uint32_t*)row_in, mb_w, colorspace, row_out);
  423. row_in += in_stride;
  424. row_out += out_stride;
  425. }
  426. return mb_h; // Num rows out == num rows in.
  427. }
  428. //------------------------------------------------------------------------------
  429. // Export to YUVA
  430. // TODO(skal): should be in yuv.c
  431. static void ConvertToYUVA(const uint32_t* const src, int width, int y_pos,
  432. const WebPDecBuffer* const output) {
  433. const WebPYUVABuffer* const buf = &output->u.YUVA;
  434. // first, the luma plane
  435. {
  436. int i;
  437. uint8_t* const y = buf->y + y_pos * buf->y_stride;
  438. for (i = 0; i < width; ++i) {
  439. const uint32_t p = src[i];
  440. y[i] = VP8RGBToY((p >> 16) & 0xff, (p >> 8) & 0xff, (p >> 0) & 0xff,
  441. YUV_HALF);
  442. }
  443. }
  444. // then U/V planes
  445. {
  446. uint8_t* const u = buf->u + (y_pos >> 1) * buf->u_stride;
  447. uint8_t* const v = buf->v + (y_pos >> 1) * buf->v_stride;
  448. const int uv_width = width >> 1;
  449. int i;
  450. for (i = 0; i < uv_width; ++i) {
  451. const uint32_t v0 = src[2 * i + 0];
  452. const uint32_t v1 = src[2 * i + 1];
  453. // VP8RGBToU/V expects four accumulated pixels. Hence we need to
  454. // scale r/g/b value by a factor 2. We just shift v0/v1 one bit less.
  455. const int r = ((v0 >> 15) & 0x1fe) + ((v1 >> 15) & 0x1fe);
  456. const int g = ((v0 >> 7) & 0x1fe) + ((v1 >> 7) & 0x1fe);
  457. const int b = ((v0 << 1) & 0x1fe) + ((v1 << 1) & 0x1fe);
  458. if (!(y_pos & 1)) { // even lines: store values
  459. u[i] = VP8RGBToU(r, g, b, YUV_HALF << 2);
  460. v[i] = VP8RGBToV(r, g, b, YUV_HALF << 2);
  461. } else { // odd lines: average with previous values
  462. const int tmp_u = VP8RGBToU(r, g, b, YUV_HALF << 2);
  463. const int tmp_v = VP8RGBToV(r, g, b, YUV_HALF << 2);
  464. // Approximated average-of-four. But it's an acceptable diff.
  465. u[i] = (u[i] + tmp_u + 1) >> 1;
  466. v[i] = (v[i] + tmp_v + 1) >> 1;
  467. }
  468. }
  469. if (width & 1) { // last pixel
  470. const uint32_t v0 = src[2 * i + 0];
  471. const int r = (v0 >> 14) & 0x3fc;
  472. const int g = (v0 >> 6) & 0x3fc;
  473. const int b = (v0 << 2) & 0x3fc;
  474. if (!(y_pos & 1)) { // even lines
  475. u[i] = VP8RGBToU(r, g, b, YUV_HALF << 2);
  476. v[i] = VP8RGBToV(r, g, b, YUV_HALF << 2);
  477. } else { // odd lines (note: we could just skip this)
  478. const int tmp_u = VP8RGBToU(r, g, b, YUV_HALF << 2);
  479. const int tmp_v = VP8RGBToV(r, g, b, YUV_HALF << 2);
  480. u[i] = (u[i] + tmp_u + 1) >> 1;
  481. v[i] = (v[i] + tmp_v + 1) >> 1;
  482. }
  483. }
  484. }
  485. // Lastly, store alpha if needed.
  486. if (buf->a != NULL) {
  487. int i;
  488. uint8_t* const a = buf->a + y_pos * buf->a_stride;
  489. for (i = 0; i < width; ++i) a[i] = (src[i] >> 24);
  490. }
  491. }
  492. static int ExportYUVA(const VP8LDecoder* const dec, int y_pos) {
  493. WebPRescaler* const rescaler = dec->rescaler;
  494. uint32_t* const src = (uint32_t*)rescaler->dst;
  495. const int dst_width = rescaler->dst_width;
  496. int num_lines_out = 0;
  497. while (WebPRescalerHasPendingOutput(rescaler)) {
  498. WebPRescalerExportRow(rescaler, 0);
  499. WebPMultARGBRow(src, dst_width, 1);
  500. ConvertToYUVA(src, dst_width, y_pos, dec->output_);
  501. ++y_pos;
  502. ++num_lines_out;
  503. }
  504. return num_lines_out;
  505. }
  506. static int EmitRescaledRowsYUVA(const VP8LDecoder* const dec,
  507. uint8_t* in, int in_stride, int mb_h) {
  508. int num_lines_in = 0;
  509. int y_pos = dec->last_out_row_;
  510. while (num_lines_in < mb_h) {
  511. const int lines_left = mb_h - num_lines_in;
  512. const int needed_lines = WebPRescaleNeededLines(dec->rescaler, lines_left);
  513. WebPMultARGBRows(in, in_stride, dec->rescaler->src_width, needed_lines, 0);
  514. WebPRescalerImport(dec->rescaler, lines_left, in, in_stride);
  515. num_lines_in += needed_lines;
  516. in += needed_lines * in_stride;
  517. y_pos += ExportYUVA(dec, y_pos);
  518. }
  519. return y_pos;
  520. }
  521. static int EmitRowsYUVA(const VP8LDecoder* const dec,
  522. const uint8_t* in, int in_stride,
  523. int mb_w, int num_rows) {
  524. int y_pos = dec->last_out_row_;
  525. while (num_rows-- > 0) {
  526. ConvertToYUVA((const uint32_t*)in, mb_w, y_pos, dec->output_);
  527. in += in_stride;
  528. ++y_pos;
  529. }
  530. return y_pos;
  531. }
  532. //------------------------------------------------------------------------------
  533. // Cropping.
  534. // Sets io->mb_y, io->mb_h & io->mb_w according to start row, end row and
  535. // crop options. Also updates the input data pointer, so that it points to the
  536. // start of the cropped window. Note that pixels are in ARGB format even if
  537. // 'in_data' is uint8_t*.
  538. // Returns true if the crop window is not empty.
  539. static int SetCropWindow(VP8Io* const io, int y_start, int y_end,
  540. uint8_t** const in_data, int pixel_stride) {
  541. assert(y_start < y_end);
  542. assert(io->crop_left < io->crop_right);
  543. if (y_end > io->crop_bottom) {
  544. y_end = io->crop_bottom; // make sure we don't overflow on last row.
  545. }
  546. if (y_start < io->crop_top) {
  547. const int delta = io->crop_top - y_start;
  548. y_start = io->crop_top;
  549. *in_data += delta * pixel_stride;
  550. }
  551. if (y_start >= y_end) return 0; // Crop window is empty.
  552. *in_data += io->crop_left * sizeof(uint32_t);
  553. io->mb_y = y_start - io->crop_top;
  554. io->mb_w = io->crop_right - io->crop_left;
  555. io->mb_h = y_end - y_start;
  556. return 1; // Non-empty crop window.
  557. }
  558. //------------------------------------------------------------------------------
  559. static WEBP_INLINE int GetMetaIndex(
  560. const uint32_t* const image, int xsize, int bits, int x, int y) {
  561. if (bits == 0) return 0;
  562. return image[xsize * (y >> bits) + (x >> bits)];
  563. }
  564. static WEBP_INLINE HTreeGroup* GetHtreeGroupForPos(VP8LMetadata* const hdr,
  565. int x, int y) {
  566. const int meta_index = GetMetaIndex(hdr->huffman_image_, hdr->huffman_xsize_,
  567. hdr->huffman_subsample_bits_, x, y);
  568. assert(meta_index < hdr->num_htree_groups_);
  569. return hdr->htree_groups_ + meta_index;
  570. }
  571. //------------------------------------------------------------------------------
  572. // Main loop, with custom row-processing function
  573. typedef void (*ProcessRowsFunc)(VP8LDecoder* const dec, int row);
  574. static void ApplyInverseTransforms(VP8LDecoder* const dec, int num_rows,
  575. const uint32_t* const rows) {
  576. int n = dec->next_transform_;
  577. const int cache_pixs = dec->width_ * num_rows;
  578. const int start_row = dec->last_row_;
  579. const int end_row = start_row + num_rows;
  580. const uint32_t* rows_in = rows;
  581. uint32_t* const rows_out = dec->argb_cache_;
  582. // Inverse transforms.
  583. // TODO: most transforms only need to operate on the cropped region only.
  584. memcpy(rows_out, rows_in, cache_pixs * sizeof(*rows_out));
  585. while (n-- > 0) {
  586. VP8LTransform* const transform = &dec->transforms_[n];
  587. VP8LInverseTransform(transform, start_row, end_row, rows_in, rows_out);
  588. rows_in = rows_out;
  589. }
  590. }
  591. // Special method for paletted alpha data.
  592. static void ApplyInverseTransformsAlpha(VP8LDecoder* const dec, int num_rows,
  593. const uint8_t* const rows) {
  594. const int start_row = dec->last_row_;
  595. const int end_row = start_row + num_rows;
  596. const uint8_t* rows_in = rows;
  597. uint8_t* rows_out = (uint8_t*)dec->io_->opaque + dec->io_->width * start_row;
  598. VP8LTransform* const transform = &dec->transforms_[0];
  599. assert(dec->next_transform_ == 1);
  600. assert(transform->type_ == COLOR_INDEXING_TRANSFORM);
  601. VP8LColorIndexInverseTransformAlpha(transform, start_row, end_row, rows_in,
  602. rows_out);
  603. }
  604. // Processes (transforms, scales & color-converts) the rows decoded after the
  605. // last call.
  606. static void ProcessRows(VP8LDecoder* const dec, int row) {
  607. const uint32_t* const rows = dec->pixels_ + dec->width_ * dec->last_row_;
  608. const int num_rows = row - dec->last_row_;
  609. if (num_rows <= 0) return; // Nothing to be done.
  610. ApplyInverseTransforms(dec, num_rows, rows);
  611. // Emit output.
  612. {
  613. VP8Io* const io = dec->io_;
  614. uint8_t* rows_data = (uint8_t*)dec->argb_cache_;
  615. const int in_stride = io->width * sizeof(uint32_t); // in unit of RGBA
  616. if (!SetCropWindow(io, dec->last_row_, row, &rows_data, in_stride)) {
  617. // Nothing to output (this time).
  618. } else {
  619. const WebPDecBuffer* const output = dec->output_;
  620. if (output->colorspace < MODE_YUV) { // convert to RGBA
  621. const WebPRGBABuffer* const buf = &output->u.RGBA;
  622. uint8_t* const rgba = buf->rgba + dec->last_out_row_ * buf->stride;
  623. const int num_rows_out = io->use_scaling ?
  624. EmitRescaledRowsRGBA(dec, rows_data, in_stride, io->mb_h,
  625. rgba, buf->stride) :
  626. EmitRows(output->colorspace, rows_data, in_stride,
  627. io->mb_w, io->mb_h, rgba, buf->stride);
  628. // Update 'last_out_row_'.
  629. dec->last_out_row_ += num_rows_out;
  630. } else { // convert to YUVA
  631. dec->last_out_row_ = io->use_scaling ?
  632. EmitRescaledRowsYUVA(dec, rows_data, in_stride, io->mb_h) :
  633. EmitRowsYUVA(dec, rows_data, in_stride, io->mb_w, io->mb_h);
  634. }
  635. assert(dec->last_out_row_ <= output->height);
  636. }
  637. }
  638. // Update 'last_row_'.
  639. dec->last_row_ = row;
  640. assert(dec->last_row_ <= dec->height_);
  641. }
  642. // Row-processing for the special case when alpha data contains only one
  643. // transform (color indexing), and trivial non-green literals.
  644. static int Is8bOptimizable(const VP8LMetadata* const hdr) {
  645. int i;
  646. if (hdr->color_cache_size_ > 0) return 0;
  647. // When the Huffman tree contains only one symbol, we can skip the
  648. // call to ReadSymbol() for red/blue/alpha channels.
  649. for (i = 0; i < hdr->num_htree_groups_; ++i) {
  650. const HuffmanTree* const htrees = hdr->htree_groups_[i].htrees_;
  651. if (htrees[RED].num_nodes_ > 1) return 0;
  652. if (htrees[BLUE].num_nodes_ > 1) return 0;
  653. if (htrees[ALPHA].num_nodes_ > 1) return 0;
  654. }
  655. return 1;
  656. }
  657. static void ExtractPalettedAlphaRows(VP8LDecoder* const dec, int row) {
  658. const int num_rows = row - dec->last_row_;
  659. const uint8_t* const in =
  660. (uint8_t*)dec->pixels_ + dec->width_ * dec->last_row_;
  661. if (num_rows > 0) {
  662. ApplyInverseTransformsAlpha(dec, num_rows, in);
  663. }
  664. dec->last_row_ = dec->last_out_row_ = row;
  665. }
  666. static int DecodeAlphaData(VP8LDecoder* const dec, uint8_t* const data,
  667. int width, int height, int last_row) {
  668. int ok = 1;
  669. int row = dec->last_pixel_ / width;
  670. int col = dec->last_pixel_ % width;
  671. VP8LBitReader* const br = &dec->br_;
  672. VP8LMetadata* const hdr = &dec->hdr_;
  673. const HTreeGroup* htree_group = GetHtreeGroupForPos(hdr, col, row);
  674. int pos = dec->last_pixel_; // current position
  675. const int end = width * height; // End of data
  676. const int last = width * last_row; // Last pixel to decode
  677. const int len_code_limit = NUM_LITERAL_CODES + NUM_LENGTH_CODES;
  678. const int mask = hdr->huffman_mask_;
  679. assert(htree_group != NULL);
  680. assert(pos < end);
  681. assert(last_row <= height);
  682. assert(Is8bOptimizable(hdr));
  683. while (!br->eos_ && pos < last) {
  684. int code;
  685. // Only update when changing tile.
  686. if ((col & mask) == 0) {
  687. htree_group = GetHtreeGroupForPos(hdr, col, row);
  688. }
  689. VP8LFillBitWindow(br);
  690. code = ReadSymbol(&htree_group->htrees_[GREEN], br);
  691. if (code < NUM_LITERAL_CODES) { // Literal
  692. data[pos] = code;
  693. ++pos;
  694. ++col;
  695. if (col >= width) {
  696. col = 0;
  697. ++row;
  698. if (row % NUM_ARGB_CACHE_ROWS == 0) {
  699. ExtractPalettedAlphaRows(dec, row);
  700. }
  701. }
  702. } else if (code < len_code_limit) { // Backward reference
  703. int dist_code, dist;
  704. const int length_sym = code - NUM_LITERAL_CODES;
  705. const int length = GetCopyLength(length_sym, br);
  706. const int dist_symbol = ReadSymbol(&htree_group->htrees_[DIST], br);
  707. VP8LFillBitWindow(br);
  708. dist_code = GetCopyDistance(dist_symbol, br);
  709. dist = PlaneCodeToDistance(width, dist_code);
  710. if (pos >= dist && end - pos >= length) {
  711. int i;
  712. for (i = 0; i < length; ++i) data[pos + i] = data[pos + i - dist];
  713. } else {
  714. ok = 0;
  715. goto End;
  716. }
  717. pos += length;
  718. col += length;
  719. while (col >= width) {
  720. col -= width;
  721. ++row;
  722. if (row % NUM_ARGB_CACHE_ROWS == 0) {
  723. ExtractPalettedAlphaRows(dec, row);
  724. }
  725. }
  726. if (pos < last && (col & mask)) {
  727. htree_group = GetHtreeGroupForPos(hdr, col, row);
  728. }
  729. } else { // Not reached
  730. ok = 0;
  731. goto End;
  732. }
  733. assert(br->eos_ == VP8LIsEndOfStream(br));
  734. ok = !br->error_;
  735. if (!ok) goto End;
  736. }
  737. // Process the remaining rows corresponding to last row-block.
  738. ExtractPalettedAlphaRows(dec, row);
  739. End:
  740. if (br->error_ || !ok || (br->eos_ && pos < end)) {
  741. ok = 0;
  742. dec->status_ = br->eos_ ? VP8_STATUS_SUSPENDED
  743. : VP8_STATUS_BITSTREAM_ERROR;
  744. } else {
  745. dec->last_pixel_ = (int)pos;
  746. if (pos == end) dec->state_ = READ_DATA;
  747. }
  748. return ok;
  749. }
  750. static int DecodeImageData(VP8LDecoder* const dec, uint32_t* const data,
  751. int width, int height, int last_row,
  752. ProcessRowsFunc process_func) {
  753. int ok = 1;
  754. int row = dec->last_pixel_ / width;
  755. int col = dec->last_pixel_ % width;
  756. VP8LBitReader* const br = &dec->br_;
  757. VP8LMetadata* const hdr = &dec->hdr_;
  758. HTreeGroup* htree_group = GetHtreeGroupForPos(hdr, col, row);
  759. uint32_t* src = data + dec->last_pixel_;
  760. uint32_t* last_cached = src;
  761. uint32_t* const src_end = data + width * height; // End of data
  762. uint32_t* const src_last = data + width * last_row; // Last pixel to decode
  763. const int len_code_limit = NUM_LITERAL_CODES + NUM_LENGTH_CODES;
  764. const int color_cache_limit = len_code_limit + hdr->color_cache_size_;
  765. VP8LColorCache* const color_cache =
  766. (hdr->color_cache_size_ > 0) ? &hdr->color_cache_ : NULL;
  767. const int mask = hdr->huffman_mask_;
  768. assert(htree_group != NULL);
  769. assert(src < src_end);
  770. assert(src_last <= src_end);
  771. while (!br->eos_ && src < src_last) {
  772. int code;
  773. // Only update when changing tile. Note we could use this test:
  774. // if "((((prev_col ^ col) | prev_row ^ row)) > mask)" -> tile changed
  775. // but that's actually slower and needs storing the previous col/row.
  776. if ((col & mask) == 0) {
  777. htree_group = GetHtreeGroupForPos(hdr, col, row);
  778. }
  779. VP8LFillBitWindow(br);
  780. code = ReadSymbol(&htree_group->htrees_[GREEN], br);
  781. if (code < NUM_LITERAL_CODES) { // Literal
  782. int red, green, blue, alpha;
  783. red = ReadSymbol(&htree_group->htrees_[RED], br);
  784. green = code;
  785. VP8LFillBitWindow(br);
  786. blue = ReadSymbol(&htree_group->htrees_[BLUE], br);
  787. alpha = ReadSymbol(&htree_group->htrees_[ALPHA], br);
  788. *src = ((uint32_t)alpha << 24) | (red << 16) | (green << 8) | blue;
  789. AdvanceByOne:
  790. ++src;
  791. ++col;
  792. if (col >= width) {
  793. col = 0;
  794. ++row;
  795. if ((row % NUM_ARGB_CACHE_ROWS == 0) && (process_func != NULL)) {
  796. process_func(dec, row);
  797. }
  798. if (color_cache != NULL) {
  799. while (last_cached < src) {
  800. VP8LColorCacheInsert(color_cache, *last_cached++);
  801. }
  802. }
  803. }
  804. } else if (code < len_code_limit) { // Backward reference
  805. int dist_code, dist;
  806. const int length_sym = code - NUM_LITERAL_CODES;
  807. const int length = GetCopyLength(length_sym, br);
  808. const int dist_symbol = ReadSymbol(&htree_group->htrees_[DIST], br);
  809. VP8LFillBitWindow(br);
  810. dist_code = GetCopyDistance(dist_symbol, br);
  811. dist = PlaneCodeToDistance(width, dist_code);
  812. if (src - data < (ptrdiff_t)dist || src_end - src < (ptrdiff_t)length) {
  813. ok = 0;
  814. goto End;
  815. } else {
  816. int i;
  817. for (i = 0; i < length; ++i) src[i] = src[i - dist];
  818. src += length;
  819. }
  820. col += length;
  821. while (col >= width) {
  822. col -= width;
  823. ++row;
  824. if ((row % NUM_ARGB_CACHE_ROWS == 0) && (process_func != NULL)) {
  825. process_func(dec, row);
  826. }
  827. }
  828. if (src < src_last) {
  829. if (col & mask) htree_group = GetHtreeGroupForPos(hdr, col, row);
  830. if (color_cache != NULL) {
  831. while (last_cached < src) {
  832. VP8LColorCacheInsert(color_cache, *last_cached++);
  833. }
  834. }
  835. }
  836. } else if (code < color_cache_limit) { // Color cache
  837. const int key = code - len_code_limit;
  838. assert(color_cache != NULL);
  839. while (last_cached < src) {
  840. VP8LColorCacheInsert(color_cache, *last_cached++);
  841. }
  842. *src = VP8LColorCacheLookup(color_cache, key);
  843. goto AdvanceByOne;
  844. } else { // Not reached
  845. ok = 0;
  846. goto End;
  847. }
  848. assert(br->eos_ == VP8LIsEndOfStream(br));
  849. ok = !br->error_;
  850. if (!ok) goto End;
  851. }
  852. // Process the remaining rows corresponding to last row-block.
  853. if (process_func != NULL) process_func(dec, row);
  854. End:
  855. if (br->error_ || !ok || (br->eos_ && src < src_end)) {
  856. ok = 0;
  857. dec->status_ = br->eos_ ? VP8_STATUS_SUSPENDED
  858. : VP8_STATUS_BITSTREAM_ERROR;
  859. } else {
  860. dec->last_pixel_ = (int)(src - data);
  861. if (src == src_end) dec->state_ = READ_DATA;
  862. }
  863. return ok;
  864. }
  865. // -----------------------------------------------------------------------------
  866. // VP8LTransform
  867. static void ClearTransform(VP8LTransform* const transform) {
  868. WebPSafeFree(transform->data_);
  869. transform->data_ = NULL;
  870. }
  871. // For security reason, we need to remap the color map to span
  872. // the total possible bundled values, and not just the num_colors.
  873. static int ExpandColorMap(int num_colors, VP8LTransform* const transform) {
  874. int i;
  875. const int final_num_colors = 1 << (8 >> transform->bits_);
  876. uint32_t* const new_color_map =
  877. (uint32_t*)WebPSafeMalloc((uint64_t)final_num_colors,
  878. sizeof(*new_color_map));
  879. if (new_color_map == NULL) {
  880. return 0;
  881. } else {
  882. uint8_t* const data = (uint8_t*)transform->data_;
  883. uint8_t* const new_data = (uint8_t*)new_color_map;
  884. new_color_map[0] = transform->data_[0];
  885. for (i = 4; i < 4 * num_colors; ++i) {
  886. // Equivalent to AddPixelEq(), on a byte-basis.
  887. new_data[i] = (data[i] + new_data[i - 4]) & 0xff;
  888. }
  889. for (; i < 4 * final_num_colors; ++i)
  890. new_data[i] = 0; // black tail.
  891. WebPSafeFree(transform->data_);
  892. transform->data_ = new_color_map;
  893. }
  894. return 1;
  895. }
  896. static int ReadTransform(int* const xsize, int const* ysize,
  897. VP8LDecoder* const dec) {
  898. int ok = 1;
  899. VP8LBitReader* const br = &dec->br_;
  900. VP8LTransform* transform = &dec->transforms_[dec->next_transform_];
  901. const VP8LImageTransformType type =
  902. (VP8LImageTransformType)VP8LReadBits(br, 2);
  903. // Each transform type can only be present once in the stream.
  904. if (dec->transforms_seen_ & (1U << type)) {
  905. return 0; // Already there, let's not accept the second same transform.
  906. }
  907. dec->transforms_seen_ |= (1U << type);
  908. transform->type_ = type;
  909. transform->xsize_ = *xsize;
  910. transform->ysize_ = *ysize;
  911. transform->data_ = NULL;
  912. ++dec->next_transform_;
  913. assert(dec->next_transform_ <= NUM_TRANSFORMS);
  914. switch (type) {
  915. case PREDICTOR_TRANSFORM:
  916. case CROSS_COLOR_TRANSFORM:
  917. transform->bits_ = VP8LReadBits(br, 3) + 2;
  918. ok = DecodeImageStream(VP8LSubSampleSize(transform->xsize_,
  919. transform->bits_),
  920. VP8LSubSampleSize(transform->ysize_,
  921. transform->bits_),
  922. 0, dec, &transform->data_);
  923. break;
  924. case COLOR_INDEXING_TRANSFORM: {
  925. const int num_colors = VP8LReadBits(br, 8) + 1;
  926. const int bits = (num_colors > 16) ? 0
  927. : (num_colors > 4) ? 1
  928. : (num_colors > 2) ? 2
  929. : 3;
  930. *xsize = VP8LSubSampleSize(transform->xsize_, bits);
  931. transform->bits_ = bits;
  932. ok = DecodeImageStream(num_colors, 1, 0, dec, &transform->data_);
  933. ok = ok && ExpandColorMap(num_colors, transform);
  934. break;
  935. }
  936. case SUBTRACT_GREEN:
  937. break;
  938. default:
  939. assert(0); // can't happen
  940. break;
  941. }
  942. return ok;
  943. }
  944. // -----------------------------------------------------------------------------
  945. // VP8LMetadata
  946. static void InitMetadata(VP8LMetadata* const hdr) {
  947. assert(hdr);
  948. memset(hdr, 0, sizeof(*hdr));
  949. }
  950. static void ClearMetadata(VP8LMetadata* const hdr) {
  951. assert(hdr);
  952. WebPSafeFree(hdr->huffman_image_);
  953. VP8LHtreeGroupsFree(hdr->htree_groups_, hdr->num_htree_groups_);
  954. VP8LColorCacheClear(&hdr->color_cache_);
  955. InitMetadata(hdr);
  956. }
  957. // -----------------------------------------------------------------------------
  958. // VP8LDecoder
  959. VP8LDecoder* VP8LNew(void) {
  960. VP8LDecoder* const dec = (VP8LDecoder*)WebPSafeCalloc(1ULL, sizeof(*dec));
  961. if (dec == NULL) return NULL;
  962. dec->status_ = VP8_STATUS_OK;
  963. dec->action_ = READ_DIM;
  964. dec->state_ = READ_DIM;
  965. VP8LDspInit(); // Init critical function pointers.
  966. return dec;
  967. }
  968. void VP8LClear(VP8LDecoder* const dec) {
  969. int i;
  970. if (dec == NULL) return;
  971. ClearMetadata(&dec->hdr_);
  972. WebPSafeFree(dec->pixels_);
  973. dec->pixels_ = NULL;
  974. for (i = 0; i < dec->next_transform_; ++i) {
  975. ClearTransform(&dec->transforms_[i]);
  976. }
  977. dec->next_transform_ = 0;
  978. dec->transforms_seen_ = 0;
  979. WebPSafeFree(dec->rescaler_memory);
  980. dec->rescaler_memory = NULL;
  981. dec->output_ = NULL; // leave no trace behind
  982. }
  983. void VP8LDelete(VP8LDecoder* const dec) {
  984. if (dec != NULL) {
  985. VP8LClear(dec);
  986. WebPSafeFree(dec);
  987. }
  988. }
  989. static void UpdateDecoder(VP8LDecoder* const dec, int width, int height) {
  990. VP8LMetadata* const hdr = &dec->hdr_;
  991. const int num_bits = hdr->huffman_subsample_bits_;
  992. dec->width_ = width;
  993. dec->height_ = height;
  994. hdr->huffman_xsize_ = VP8LSubSampleSize(width, num_bits);
  995. hdr->huffman_mask_ = (num_bits == 0) ? ~0 : (1 << num_bits) - 1;
  996. }
  997. static int DecodeImageStream(int xsize, int ysize,
  998. int is_level0,
  999. VP8LDecoder* const dec,
  1000. uint32_t** const decoded_data) {
  1001. int ok = 1;
  1002. int transform_xsize = xsize;
  1003. int transform_ysize = ysize;
  1004. VP8LBitReader* const br = &dec->br_;
  1005. VP8LMetadata* const hdr = &dec->hdr_;
  1006. uint32_t* data = NULL;
  1007. int color_cache_bits = 0;
  1008. // Read the transforms (may recurse).
  1009. if (is_level0) {
  1010. while (ok && VP8LReadBits(br, 1)) {
  1011. ok = ReadTransform(&transform_xsize, &transform_ysize, dec);
  1012. }
  1013. }
  1014. // Color cache
  1015. if (ok && VP8LReadBits(br, 1)) {
  1016. color_cache_bits = VP8LReadBits(br, 4);
  1017. ok = (color_cache_bits >= 1 && color_cache_bits <= MAX_CACHE_BITS);
  1018. if (!ok) {
  1019. dec->status_ = VP8_STATUS_BITSTREAM_ERROR;
  1020. goto End;
  1021. }
  1022. }
  1023. // Read the Huffman codes (may recurse).
  1024. ok = ok && ReadHuffmanCodes(dec, transform_xsize, transform_ysize,
  1025. color_cache_bits, is_level0);
  1026. if (!ok) {
  1027. dec->status_ = VP8_STATUS_BITSTREAM_ERROR;
  1028. goto End;
  1029. }
  1030. // Finish setting up the color-cache
  1031. if (color_cache_bits > 0) {
  1032. hdr->color_cache_size_ = 1 << color_cache_bits;
  1033. if (!VP8LColorCacheInit(&hdr->color_cache_, color_cache_bits)) {
  1034. dec->status_ = VP8_STATUS_OUT_OF_MEMORY;
  1035. ok = 0;
  1036. goto End;
  1037. }
  1038. } else {
  1039. hdr->color_cache_size_ = 0;
  1040. }
  1041. UpdateDecoder(dec, transform_xsize, transform_ysize);
  1042. if (is_level0) { // level 0 complete
  1043. dec->state_ = READ_HDR;
  1044. goto End;
  1045. }
  1046. {
  1047. const uint64_t total_size = (uint64_t)transform_xsize * transform_ysize;
  1048. data = (uint32_t*)WebPSafeMalloc(total_size, sizeof(*data));
  1049. if (data == NULL) {
  1050. dec->status_ = VP8_STATUS_OUT_OF_MEMORY;
  1051. ok = 0;
  1052. goto End;
  1053. }
  1054. }
  1055. // Use the Huffman trees to decode the LZ77 encoded data.
  1056. ok = DecodeImageData(dec, data, transform_xsize, transform_ysize,
  1057. transform_ysize, NULL);
  1058. ok = ok && !br->error_;
  1059. End:
  1060. if (!ok) {
  1061. WebPSafeFree(data);
  1062. ClearMetadata(hdr);
  1063. // If not enough data (br.eos_) resulted in BIT_STREAM_ERROR, update the
  1064. // status appropriately.
  1065. if (dec->status_ == VP8_STATUS_BITSTREAM_ERROR && dec->br_.eos_) {
  1066. dec->status_ = VP8_STATUS_SUSPENDED;
  1067. }
  1068. } else {
  1069. if (decoded_data != NULL) {
  1070. *decoded_data = data;
  1071. } else {
  1072. // We allocate image data in this function only for transforms. At level 0
  1073. // (that is: not the transforms), we shouldn't have allocated anything.
  1074. assert(data == NULL);
  1075. assert(is_level0);
  1076. }
  1077. dec->last_pixel_ = 0; // Reset for future DECODE_DATA_FUNC() calls.
  1078. if (!is_level0) ClearMetadata(hdr); // Clean up temporary data behind.
  1079. }
  1080. return ok;
  1081. }
  1082. //------------------------------------------------------------------------------
  1083. // Allocate internal buffers dec->pixels_ and dec->argb_cache_.
  1084. static int AllocateInternalBuffers32b(VP8LDecoder* const dec, int final_width) {
  1085. const uint64_t num_pixels = (uint64_t)dec->width_ * dec->height_;
  1086. // Scratch buffer corresponding to top-prediction row for transforming the
  1087. // first row in the row-blocks. Not needed for paletted alpha.
  1088. const uint64_t cache_top_pixels = (uint16_t)final_width;
  1089. // Scratch buffer for temporary BGRA storage. Not needed for paletted alpha.
  1090. const uint64_t cache_pixels = (uint64_t)final_width * NUM_ARGB_CACHE_ROWS;
  1091. const uint64_t total_num_pixels =
  1092. num_pixels + cache_top_pixels + cache_pixels;
  1093. assert(dec->width_ <= final_width);
  1094. dec->pixels_ = (uint32_t*)WebPSafeMalloc(total_num_pixels, sizeof(uint32_t));
  1095. if (dec->pixels_ == NULL) {
  1096. dec->argb_cache_ = NULL; // for sanity check
  1097. dec->status_ = VP8_STATUS_OUT_OF_MEMORY;
  1098. return 0;
  1099. }
  1100. dec->argb_cache_ = dec->pixels_ + num_pixels + cache_top_pixels;
  1101. return 1;
  1102. }
  1103. static int AllocateInternalBuffers8b(VP8LDecoder* const dec) {
  1104. const uint64_t total_num_pixels = (uint64_t)dec->width_ * dec->height_;
  1105. dec->argb_cache_ = NULL; // for sanity check
  1106. dec->pixels_ = (uint32_t*)WebPSafeMalloc(total_num_pixels, sizeof(uint8_t));
  1107. if (dec->pixels_ == NULL) {
  1108. dec->status_ = VP8_STATUS_OUT_OF_MEMORY;
  1109. return 0;
  1110. }
  1111. return 1;
  1112. }
  1113. //------------------------------------------------------------------------------
  1114. // Special row-processing that only stores the alpha data.
  1115. static void ExtractAlphaRows(VP8LDecoder* const dec, int row) {
  1116. const int num_rows = row - dec->last_row_;
  1117. const uint32_t* const in = dec->pixels_ + dec->width_ * dec->last_row_;
  1118. if (num_rows <= 0) return; // Nothing to be done.
  1119. ApplyInverseTransforms(dec, num_rows, in);
  1120. // Extract alpha (which is stored in the green plane).
  1121. {
  1122. const int width = dec->io_->width; // the final width (!= dec->width_)
  1123. const int cache_pixs = width * num_rows;
  1124. uint8_t* const dst = (uint8_t*)dec->io_->opaque + width * dec->last_row_;
  1125. const uint32_t* const src = dec->argb_cache_;
  1126. int i;
  1127. for (i = 0; i < cache_pixs; ++i) dst[i] = (src[i] >> 8) & 0xff;
  1128. }
  1129. dec->last_row_ = dec->last_out_row_ = row;
  1130. }
  1131. int VP8LDecodeAlphaHeader(ALPHDecoder* const alph_dec,
  1132. const uint8_t* const data, size_t data_size,
  1133. uint8_t* const output) {
  1134. int ok = 0;
  1135. VP8LDecoder* dec;
  1136. VP8Io* io;
  1137. assert(alph_dec != NULL);
  1138. alph_dec->vp8l_dec_ = VP8LNew();
  1139. if (alph_dec->vp8l_dec_ == NULL) return 0;
  1140. dec = alph_dec->vp8l_dec_;
  1141. dec->width_ = alph_dec->width_;
  1142. dec->height_ = alph_dec->height_;
  1143. dec->io_ = &alph_dec->io_;
  1144. io = dec->io_;
  1145. VP8InitIo(io);
  1146. WebPInitCustomIo(NULL, io); // Just a sanity Init. io won't be used.
  1147. io->opaque = output;
  1148. io->width = alph_dec->width_;
  1149. io->height = alph_dec->height_;
  1150. dec->status_ = VP8_STATUS_OK;
  1151. VP8LInitBitReader(&dec->br_, data, data_size);
  1152. dec->action_ = READ_HDR;
  1153. if (!DecodeImageStream(alph_dec->width_, alph_dec->height_, 1, dec, NULL)) {
  1154. goto Err;
  1155. }
  1156. // Special case: if alpha data uses only the color indexing transform and
  1157. // doesn't use color cache (a frequent case), we will use DecodeAlphaData()
  1158. // method that only needs allocation of 1 byte per pixel (alpha channel).
  1159. if (dec->next_transform_ == 1 &&
  1160. dec->transforms_[0].type_ == COLOR_INDEXING_TRANSFORM &&
  1161. Is8bOptimizable(&dec->hdr_)) {
  1162. alph_dec->use_8b_decode = 1;
  1163. ok = AllocateInternalBuffers8b(dec);
  1164. } else {
  1165. // Allocate internal buffers (note that dec->width_ may have changed here).
  1166. alph_dec->use_8b_decode = 0;
  1167. ok = AllocateInternalBuffers32b(dec, alph_dec->width_);
  1168. }
  1169. if (!ok) goto Err;
  1170. dec->action_ = READ_DATA;
  1171. return 1;
  1172. Err:
  1173. VP8LDelete(alph_dec->vp8l_dec_);
  1174. alph_dec->vp8l_dec_ = NULL;
  1175. return 0;
  1176. }
  1177. int VP8LDecodeAlphaImageStream(ALPHDecoder* const alph_dec, int last_row) {
  1178. VP8LDecoder* const dec = alph_dec->vp8l_dec_;
  1179. assert(dec != NULL);
  1180. assert(dec->action_ == READ_DATA);
  1181. assert(last_row <= dec->height_);
  1182. if (dec->last_pixel_ == dec->width_ * dec->height_) {
  1183. return 1; // done
  1184. }
  1185. // Decode (with special row processing).
  1186. return alph_dec->use_8b_decode ?
  1187. DecodeAlphaData(dec, (uint8_t*)dec->pixels_, dec->width_, dec->height_,
  1188. last_row) :
  1189. DecodeImageData(dec, dec->pixels_, dec->width_, dec->height_,
  1190. last_row, ExtractAlphaRows);
  1191. }
  1192. //------------------------------------------------------------------------------
  1193. int VP8LDecodeHeader(VP8LDecoder* const dec, VP8Io* const io) {
  1194. int width, height, has_alpha;
  1195. if (dec == NULL) return 0;
  1196. if (io == NULL) {
  1197. dec->status_ = VP8_STATUS_INVALID_PARAM;
  1198. return 0;
  1199. }
  1200. dec->io_ = io;
  1201. dec->status_ = VP8_STATUS_OK;
  1202. VP8LInitBitReader(&dec->br_, io->data, io->data_size);
  1203. if (!ReadImageInfo(&dec->br_, &width, &height, &has_alpha)) {
  1204. dec->status_ = VP8_STATUS_BITSTREAM_ERROR;
  1205. goto Error;
  1206. }
  1207. dec->state_ = READ_DIM;
  1208. io->width = width;
  1209. io->height = height;
  1210. dec->action_ = READ_HDR;
  1211. if (!DecodeImageStream(width, height, 1, dec, NULL)) goto Error;
  1212. return 1;
  1213. Error:
  1214. VP8LClear(dec);
  1215. assert(dec->status_ != VP8_STATUS_OK);
  1216. return 0;
  1217. }
  1218. int VP8LDecodeImage(VP8LDecoder* const dec) {
  1219. VP8Io* io = NULL;
  1220. WebPDecParams* params = NULL;
  1221. // Sanity checks.
  1222. if (dec == NULL) return 0;
  1223. dec->status_ = VP8_STATUS_BITSTREAM_ERROR;
  1224. assert(dec->hdr_.htree_groups_ != NULL);
  1225. assert(dec->hdr_.num_htree_groups_ > 0);
  1226. io = dec->io_;
  1227. assert(io != NULL);
  1228. params = (WebPDecParams*)io->opaque;
  1229. assert(params != NULL);
  1230. dec->output_ = params->output;
  1231. assert(dec->output_ != NULL);
  1232. // Initialization.
  1233. if (!WebPIoInitFromOptions(params->options, io, MODE_BGRA)) {
  1234. dec->status_ = VP8_STATUS_INVALID_PARAM;
  1235. goto Err;
  1236. }
  1237. if (!AllocateInternalBuffers32b(dec, io->width)) goto Err;
  1238. if (io->use_scaling && !AllocateAndInitRescaler(dec, io)) goto Err;
  1239. if (io->use_scaling || WebPIsPremultipliedMode(dec->output_->colorspace)) {
  1240. // need the alpha-multiply functions for premultiplied output or rescaling
  1241. WebPInitAlphaProcessing();
  1242. }
  1243. // Decode.
  1244. dec->action_ = READ_DATA;
  1245. if (!DecodeImageData(dec, dec->pixels_, dec->width_, dec->height_,
  1246. dec->height_, ProcessRows)) {
  1247. goto Err;
  1248. }
  1249. // Cleanup.
  1250. params->last_y = dec->last_out_row_;
  1251. VP8LClear(dec);
  1252. return 1;
  1253. Err:
  1254. VP8LClear(dec);
  1255. assert(dec->status_ != VP8_STATUS_OK);
  1256. return 0;
  1257. }
  1258. //------------------------------------------------------------------------------