vp8l_dec.c 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742
  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_dec.h"
  16. #include "./vp8li_dec.h"
  17. #include "../dsp/dsp.h"
  18. #include "../dsp/lossless.h"
  19. #include "../dsp/lossless_common.h"
  20. #include "../dsp/yuv.h"
  21. #include "../utils/endian_inl_utils.h"
  22. #include "../utils/huffman_utils.h"
  23. #include "../utils/utils.h"
  24. #define NUM_ARGB_CACHE_ROWS 16
  25. static const int kCodeLengthLiterals = 16;
  26. static const int kCodeLengthRepeatCode = 16;
  27. static const uint8_t kCodeLengthExtraBits[3] = { 2, 3, 7 };
  28. static const uint8_t kCodeLengthRepeatOffsets[3] = { 3, 3, 11 };
  29. // -----------------------------------------------------------------------------
  30. // Five Huffman codes are used at each meta code:
  31. // 1. green + length prefix codes + color cache codes,
  32. // 2. alpha,
  33. // 3. red,
  34. // 4. blue, and,
  35. // 5. distance prefix codes.
  36. typedef enum {
  37. GREEN = 0,
  38. RED = 1,
  39. BLUE = 2,
  40. ALPHA = 3,
  41. DIST = 4
  42. } HuffIndex;
  43. static const uint16_t kAlphabetSize[HUFFMAN_CODES_PER_META_CODE] = {
  44. NUM_LITERAL_CODES + NUM_LENGTH_CODES,
  45. NUM_LITERAL_CODES, NUM_LITERAL_CODES, NUM_LITERAL_CODES,
  46. NUM_DISTANCE_CODES
  47. };
  48. static const uint8_t kLiteralMap[HUFFMAN_CODES_PER_META_CODE] = {
  49. 0, 1, 1, 1, 0
  50. };
  51. #define NUM_CODE_LENGTH_CODES 19
  52. static const uint8_t kCodeLengthCodeOrder[NUM_CODE_LENGTH_CODES] = {
  53. 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
  54. };
  55. #define CODE_TO_PLANE_CODES 120
  56. static const uint8_t kCodeToPlane[CODE_TO_PLANE_CODES] = {
  57. 0x18, 0x07, 0x17, 0x19, 0x28, 0x06, 0x27, 0x29, 0x16, 0x1a,
  58. 0x26, 0x2a, 0x38, 0x05, 0x37, 0x39, 0x15, 0x1b, 0x36, 0x3a,
  59. 0x25, 0x2b, 0x48, 0x04, 0x47, 0x49, 0x14, 0x1c, 0x35, 0x3b,
  60. 0x46, 0x4a, 0x24, 0x2c, 0x58, 0x45, 0x4b, 0x34, 0x3c, 0x03,
  61. 0x57, 0x59, 0x13, 0x1d, 0x56, 0x5a, 0x23, 0x2d, 0x44, 0x4c,
  62. 0x55, 0x5b, 0x33, 0x3d, 0x68, 0x02, 0x67, 0x69, 0x12, 0x1e,
  63. 0x66, 0x6a, 0x22, 0x2e, 0x54, 0x5c, 0x43, 0x4d, 0x65, 0x6b,
  64. 0x32, 0x3e, 0x78, 0x01, 0x77, 0x79, 0x53, 0x5d, 0x11, 0x1f,
  65. 0x64, 0x6c, 0x42, 0x4e, 0x76, 0x7a, 0x21, 0x2f, 0x75, 0x7b,
  66. 0x31, 0x3f, 0x63, 0x6d, 0x52, 0x5e, 0x00, 0x74, 0x7c, 0x41,
  67. 0x4f, 0x10, 0x20, 0x62, 0x6e, 0x30, 0x73, 0x7d, 0x51, 0x5f,
  68. 0x40, 0x72, 0x7e, 0x61, 0x6f, 0x50, 0x71, 0x7f, 0x60, 0x70
  69. };
  70. // Memory needed for lookup tables of one Huffman tree group. Red, blue, alpha
  71. // and distance alphabets are constant (256 for red, blue and alpha, 40 for
  72. // distance) and lookup table sizes for them in worst case are 630 and 410
  73. // respectively. Size of green alphabet depends on color cache size and is equal
  74. // to 256 (green component values) + 24 (length prefix values)
  75. // + color_cache_size (between 0 and 2048).
  76. // All values computed for 8-bit first level lookup with Mark Adler's tool:
  77. // https://github.com/madler/zlib/blob/v1.2.5/examples/enough.c
  78. #define FIXED_TABLE_SIZE (630 * 3 + 410)
  79. static const uint16_t kTableSize[12] = {
  80. FIXED_TABLE_SIZE + 654,
  81. FIXED_TABLE_SIZE + 656,
  82. FIXED_TABLE_SIZE + 658,
  83. FIXED_TABLE_SIZE + 662,
  84. FIXED_TABLE_SIZE + 670,
  85. FIXED_TABLE_SIZE + 686,
  86. FIXED_TABLE_SIZE + 718,
  87. FIXED_TABLE_SIZE + 782,
  88. FIXED_TABLE_SIZE + 912,
  89. FIXED_TABLE_SIZE + 1168,
  90. FIXED_TABLE_SIZE + 1680,
  91. FIXED_TABLE_SIZE + 2704
  92. };
  93. static int DecodeImageStream(int xsize, int ysize,
  94. int is_level0,
  95. VP8LDecoder* const dec,
  96. uint32_t** const decoded_data);
  97. //------------------------------------------------------------------------------
  98. int VP8LCheckSignature(const uint8_t* const data, size_t size) {
  99. return (size >= VP8L_FRAME_HEADER_SIZE &&
  100. data[0] == VP8L_MAGIC_BYTE &&
  101. (data[4] >> 5) == 0); // version
  102. }
  103. static int ReadImageInfo(VP8LBitReader* const br,
  104. int* const width, int* const height,
  105. int* const has_alpha) {
  106. if (VP8LReadBits(br, 8) != VP8L_MAGIC_BYTE) return 0;
  107. *width = VP8LReadBits(br, VP8L_IMAGE_SIZE_BITS) + 1;
  108. *height = VP8LReadBits(br, VP8L_IMAGE_SIZE_BITS) + 1;
  109. *has_alpha = VP8LReadBits(br, 1);
  110. if (VP8LReadBits(br, VP8L_VERSION_BITS) != 0) return 0;
  111. return !br->eos_;
  112. }
  113. int VP8LGetInfo(const uint8_t* data, size_t data_size,
  114. int* const width, int* const height, int* const has_alpha) {
  115. if (data == NULL || data_size < VP8L_FRAME_HEADER_SIZE) {
  116. return 0; // not enough data
  117. } else if (!VP8LCheckSignature(data, data_size)) {
  118. return 0; // bad signature
  119. } else {
  120. int w, h, a;
  121. VP8LBitReader br;
  122. VP8LInitBitReader(&br, data, data_size);
  123. if (!ReadImageInfo(&br, &w, &h, &a)) {
  124. return 0;
  125. }
  126. if (width != NULL) *width = w;
  127. if (height != NULL) *height = h;
  128. if (has_alpha != NULL) *has_alpha = a;
  129. return 1;
  130. }
  131. }
  132. //------------------------------------------------------------------------------
  133. static WEBP_INLINE int GetCopyDistance(int distance_symbol,
  134. VP8LBitReader* const br) {
  135. int extra_bits, offset;
  136. if (distance_symbol < 4) {
  137. return distance_symbol + 1;
  138. }
  139. extra_bits = (distance_symbol - 2) >> 1;
  140. offset = (2 + (distance_symbol & 1)) << extra_bits;
  141. return offset + VP8LReadBits(br, extra_bits) + 1;
  142. }
  143. static WEBP_INLINE int GetCopyLength(int length_symbol,
  144. VP8LBitReader* const br) {
  145. // Length and distance prefixes are encoded the same way.
  146. return GetCopyDistance(length_symbol, br);
  147. }
  148. static WEBP_INLINE int PlaneCodeToDistance(int xsize, int plane_code) {
  149. if (plane_code > CODE_TO_PLANE_CODES) {
  150. return plane_code - CODE_TO_PLANE_CODES;
  151. } else {
  152. const int dist_code = kCodeToPlane[plane_code - 1];
  153. const int yoffset = dist_code >> 4;
  154. const int xoffset = 8 - (dist_code & 0xf);
  155. const int dist = yoffset * xsize + xoffset;
  156. return (dist >= 1) ? dist : 1; // dist<1 can happen if xsize is very small
  157. }
  158. }
  159. //------------------------------------------------------------------------------
  160. // Decodes the next Huffman code from bit-stream.
  161. // FillBitWindow(br) needs to be called at minimum every second call
  162. // to ReadSymbol, in order to pre-fetch enough bits.
  163. static WEBP_INLINE int ReadSymbol(const HuffmanCode* table,
  164. VP8LBitReader* const br) {
  165. int nbits;
  166. uint32_t val = VP8LPrefetchBits(br);
  167. table += val & HUFFMAN_TABLE_MASK;
  168. nbits = table->bits - HUFFMAN_TABLE_BITS;
  169. if (nbits > 0) {
  170. VP8LSetBitPos(br, br->bit_pos_ + HUFFMAN_TABLE_BITS);
  171. val = VP8LPrefetchBits(br);
  172. table += table->value;
  173. table += val & ((1 << nbits) - 1);
  174. }
  175. VP8LSetBitPos(br, br->bit_pos_ + table->bits);
  176. return table->value;
  177. }
  178. // Reads packed symbol depending on GREEN channel
  179. #define BITS_SPECIAL_MARKER 0x100 // something large enough (and a bit-mask)
  180. #define PACKED_NON_LITERAL_CODE 0 // must be < NUM_LITERAL_CODES
  181. static WEBP_INLINE int ReadPackedSymbols(const HTreeGroup* group,
  182. VP8LBitReader* const br,
  183. uint32_t* const dst) {
  184. const uint32_t val = VP8LPrefetchBits(br) & (HUFFMAN_PACKED_TABLE_SIZE - 1);
  185. const HuffmanCode32 code = group->packed_table[val];
  186. assert(group->use_packed_table);
  187. if (code.bits < BITS_SPECIAL_MARKER) {
  188. VP8LSetBitPos(br, br->bit_pos_ + code.bits);
  189. *dst = code.value;
  190. return PACKED_NON_LITERAL_CODE;
  191. } else {
  192. VP8LSetBitPos(br, br->bit_pos_ + code.bits - BITS_SPECIAL_MARKER);
  193. assert(code.value >= NUM_LITERAL_CODES);
  194. return code.value;
  195. }
  196. }
  197. static int AccumulateHCode(HuffmanCode hcode, int shift,
  198. HuffmanCode32* const huff) {
  199. huff->bits += hcode.bits;
  200. huff->value |= (uint32_t)hcode.value << shift;
  201. assert(huff->bits <= HUFFMAN_TABLE_BITS);
  202. return hcode.bits;
  203. }
  204. static void BuildPackedTable(HTreeGroup* const htree_group) {
  205. uint32_t code;
  206. for (code = 0; code < HUFFMAN_PACKED_TABLE_SIZE; ++code) {
  207. uint32_t bits = code;
  208. HuffmanCode32* const huff = &htree_group->packed_table[bits];
  209. HuffmanCode hcode = htree_group->htrees[GREEN][bits];
  210. if (hcode.value >= NUM_LITERAL_CODES) {
  211. huff->bits = hcode.bits + BITS_SPECIAL_MARKER;
  212. huff->value = hcode.value;
  213. } else {
  214. huff->bits = 0;
  215. huff->value = 0;
  216. bits >>= AccumulateHCode(hcode, 8, huff);
  217. bits >>= AccumulateHCode(htree_group->htrees[RED][bits], 16, huff);
  218. bits >>= AccumulateHCode(htree_group->htrees[BLUE][bits], 0, huff);
  219. bits >>= AccumulateHCode(htree_group->htrees[ALPHA][bits], 24, huff);
  220. (void)bits;
  221. }
  222. }
  223. }
  224. static int ReadHuffmanCodeLengths(
  225. VP8LDecoder* const dec, const int* const code_length_code_lengths,
  226. int num_symbols, int* const code_lengths) {
  227. int ok = 0;
  228. VP8LBitReader* const br = &dec->br_;
  229. int symbol;
  230. int max_symbol;
  231. int prev_code_len = DEFAULT_CODE_LENGTH;
  232. HuffmanCode table[1 << LENGTHS_TABLE_BITS];
  233. if (!VP8LBuildHuffmanTable(table, LENGTHS_TABLE_BITS,
  234. code_length_code_lengths,
  235. NUM_CODE_LENGTH_CODES)) {
  236. goto End;
  237. }
  238. if (VP8LReadBits(br, 1)) { // use length
  239. const int length_nbits = 2 + 2 * VP8LReadBits(br, 3);
  240. max_symbol = 2 + VP8LReadBits(br, length_nbits);
  241. if (max_symbol > num_symbols) {
  242. goto End;
  243. }
  244. } else {
  245. max_symbol = num_symbols;
  246. }
  247. symbol = 0;
  248. while (symbol < num_symbols) {
  249. const HuffmanCode* p;
  250. int code_len;
  251. if (max_symbol-- == 0) break;
  252. VP8LFillBitWindow(br);
  253. p = &table[VP8LPrefetchBits(br) & LENGTHS_TABLE_MASK];
  254. VP8LSetBitPos(br, br->bit_pos_ + p->bits);
  255. code_len = p->value;
  256. if (code_len < kCodeLengthLiterals) {
  257. code_lengths[symbol++] = code_len;
  258. if (code_len != 0) prev_code_len = code_len;
  259. } else {
  260. const int use_prev = (code_len == kCodeLengthRepeatCode);
  261. const int slot = code_len - kCodeLengthLiterals;
  262. const int extra_bits = kCodeLengthExtraBits[slot];
  263. const int repeat_offset = kCodeLengthRepeatOffsets[slot];
  264. int repeat = VP8LReadBits(br, extra_bits) + repeat_offset;
  265. if (symbol + repeat > num_symbols) {
  266. goto End;
  267. } else {
  268. const int length = use_prev ? prev_code_len : 0;
  269. while (repeat-- > 0) code_lengths[symbol++] = length;
  270. }
  271. }
  272. }
  273. ok = 1;
  274. End:
  275. if (!ok) dec->status_ = VP8_STATUS_BITSTREAM_ERROR;
  276. return ok;
  277. }
  278. // 'code_lengths' is pre-allocated temporary buffer, used for creating Huffman
  279. // tree.
  280. static int ReadHuffmanCode(int alphabet_size, VP8LDecoder* const dec,
  281. int* const code_lengths, HuffmanCode* const table) {
  282. int ok = 0;
  283. int size = 0;
  284. VP8LBitReader* const br = &dec->br_;
  285. const int simple_code = VP8LReadBits(br, 1);
  286. memset(code_lengths, 0, alphabet_size * sizeof(*code_lengths));
  287. if (simple_code) { // Read symbols, codes & code lengths directly.
  288. const int num_symbols = VP8LReadBits(br, 1) + 1;
  289. const int first_symbol_len_code = VP8LReadBits(br, 1);
  290. // The first code is either 1 bit or 8 bit code.
  291. int symbol = VP8LReadBits(br, (first_symbol_len_code == 0) ? 1 : 8);
  292. code_lengths[symbol] = 1;
  293. // The second code (if present), is always 8 bit long.
  294. if (num_symbols == 2) {
  295. symbol = VP8LReadBits(br, 8);
  296. code_lengths[symbol] = 1;
  297. }
  298. ok = 1;
  299. } else { // Decode Huffman-coded code lengths.
  300. int i;
  301. int code_length_code_lengths[NUM_CODE_LENGTH_CODES] = { 0 };
  302. const int num_codes = VP8LReadBits(br, 4) + 4;
  303. if (num_codes > NUM_CODE_LENGTH_CODES) {
  304. dec->status_ = VP8_STATUS_BITSTREAM_ERROR;
  305. return 0;
  306. }
  307. for (i = 0; i < num_codes; ++i) {
  308. code_length_code_lengths[kCodeLengthCodeOrder[i]] = VP8LReadBits(br, 3);
  309. }
  310. ok = ReadHuffmanCodeLengths(dec, code_length_code_lengths, alphabet_size,
  311. code_lengths);
  312. }
  313. ok = ok && !br->eos_;
  314. if (ok) {
  315. size = VP8LBuildHuffmanTable(table, HUFFMAN_TABLE_BITS,
  316. code_lengths, alphabet_size);
  317. }
  318. if (!ok || size == 0) {
  319. dec->status_ = VP8_STATUS_BITSTREAM_ERROR;
  320. return 0;
  321. }
  322. return size;
  323. }
  324. static int ReadHuffmanCodes(VP8LDecoder* const dec, int xsize, int ysize,
  325. int color_cache_bits, int allow_recursion) {
  326. int i, j;
  327. VP8LBitReader* const br = &dec->br_;
  328. VP8LMetadata* const hdr = &dec->hdr_;
  329. uint32_t* huffman_image = NULL;
  330. HTreeGroup* htree_groups = NULL;
  331. HuffmanCode* huffman_tables = NULL;
  332. HuffmanCode* huffman_table = NULL;
  333. int num_htree_groups = 1;
  334. int num_htree_groups_max = 1;
  335. int max_alphabet_size = 0;
  336. int* code_lengths = NULL;
  337. const int table_size = kTableSize[color_cache_bits];
  338. int* mapping = NULL;
  339. int ok = 0;
  340. if (allow_recursion && VP8LReadBits(br, 1)) {
  341. // use meta Huffman codes.
  342. const int huffman_precision = VP8LReadBits(br, 3) + 2;
  343. const int huffman_xsize = VP8LSubSampleSize(xsize, huffman_precision);
  344. const int huffman_ysize = VP8LSubSampleSize(ysize, huffman_precision);
  345. const int huffman_pixs = huffman_xsize * huffman_ysize;
  346. if (!DecodeImageStream(huffman_xsize, huffman_ysize, 0, dec,
  347. &huffman_image)) {
  348. goto Error;
  349. }
  350. hdr->huffman_subsample_bits_ = huffman_precision;
  351. for (i = 0; i < huffman_pixs; ++i) {
  352. // The huffman data is stored in red and green bytes.
  353. const int group = (huffman_image[i] >> 8) & 0xffff;
  354. huffman_image[i] = group;
  355. if (group >= num_htree_groups_max) {
  356. num_htree_groups_max = group + 1;
  357. }
  358. }
  359. // Check the validity of num_htree_groups_max. If it seems too big, use a
  360. // smaller value for later. This will prevent big memory allocations to end
  361. // up with a bad bitstream anyway.
  362. // The value of 1000 is totally arbitrary. We know that num_htree_groups_max
  363. // is smaller than (1 << 16) and should be smaller than the number of pixels
  364. // (though the format allows it to be bigger).
  365. if (num_htree_groups_max > 1000 || num_htree_groups_max > xsize * ysize) {
  366. // Create a mapping from the used indices to the minimal set of used
  367. // values [0, num_htree_groups)
  368. mapping = (int*)WebPSafeMalloc(num_htree_groups_max, sizeof(*mapping));
  369. if (mapping == NULL) {
  370. dec->status_ = VP8_STATUS_OUT_OF_MEMORY;
  371. goto Error;
  372. }
  373. // -1 means a value is unmapped, and therefore unused in the Huffman
  374. // image.
  375. memset(mapping, 0xff, num_htree_groups_max * sizeof(*mapping));
  376. for (num_htree_groups = 0, i = 0; i < huffman_pixs; ++i) {
  377. // Get the current mapping for the group and remap the Huffman image.
  378. int* const mapped_group = &mapping[huffman_image[i]];
  379. if (*mapped_group == -1) *mapped_group = num_htree_groups++;
  380. huffman_image[i] = *mapped_group;
  381. }
  382. } else {
  383. num_htree_groups = num_htree_groups_max;
  384. }
  385. }
  386. if (br->eos_) goto Error;
  387. // Find maximum alphabet size for the htree group.
  388. for (j = 0; j < HUFFMAN_CODES_PER_META_CODE; ++j) {
  389. int alphabet_size = kAlphabetSize[j];
  390. if (j == 0 && color_cache_bits > 0) {
  391. alphabet_size += 1 << color_cache_bits;
  392. }
  393. if (max_alphabet_size < alphabet_size) {
  394. max_alphabet_size = alphabet_size;
  395. }
  396. }
  397. code_lengths = (int*)WebPSafeCalloc((uint64_t)max_alphabet_size,
  398. sizeof(*code_lengths));
  399. huffman_tables = (HuffmanCode*)WebPSafeMalloc(num_htree_groups * table_size,
  400. sizeof(*huffman_tables));
  401. htree_groups = VP8LHtreeGroupsNew(num_htree_groups);
  402. if (htree_groups == NULL || code_lengths == NULL || huffman_tables == NULL) {
  403. dec->status_ = VP8_STATUS_OUT_OF_MEMORY;
  404. goto Error;
  405. }
  406. huffman_table = huffman_tables;
  407. for (i = 0; i < num_htree_groups_max; ++i) {
  408. // If the index "i" is unused in the Huffman image, just make sure the
  409. // coefficients are valid but do not store them.
  410. if (mapping != NULL && mapping[i] == -1) {
  411. for (j = 0; j < HUFFMAN_CODES_PER_META_CODE; ++j) {
  412. int alphabet_size = kAlphabetSize[j];
  413. if (j == 0 && color_cache_bits > 0) {
  414. alphabet_size += (1 << color_cache_bits);
  415. }
  416. // Passing in NULL so that nothing gets filled.
  417. if (!ReadHuffmanCode(alphabet_size, dec, code_lengths, NULL)) {
  418. goto Error;
  419. }
  420. }
  421. } else {
  422. HTreeGroup* const htree_group =
  423. &htree_groups[(mapping == NULL) ? i : mapping[i]];
  424. HuffmanCode** const htrees = htree_group->htrees;
  425. int size;
  426. int total_size = 0;
  427. int is_trivial_literal = 1;
  428. int max_bits = 0;
  429. for (j = 0; j < HUFFMAN_CODES_PER_META_CODE; ++j) {
  430. int alphabet_size = kAlphabetSize[j];
  431. htrees[j] = huffman_table;
  432. if (j == 0 && color_cache_bits > 0) {
  433. alphabet_size += (1 << color_cache_bits);
  434. }
  435. size = ReadHuffmanCode(alphabet_size, dec, code_lengths, huffman_table);
  436. if (size == 0) {
  437. goto Error;
  438. }
  439. if (is_trivial_literal && kLiteralMap[j] == 1) {
  440. is_trivial_literal = (huffman_table->bits == 0);
  441. }
  442. total_size += huffman_table->bits;
  443. huffman_table += size;
  444. if (j <= ALPHA) {
  445. int local_max_bits = code_lengths[0];
  446. int k;
  447. for (k = 1; k < alphabet_size; ++k) {
  448. if (code_lengths[k] > local_max_bits) {
  449. local_max_bits = code_lengths[k];
  450. }
  451. }
  452. max_bits += local_max_bits;
  453. }
  454. }
  455. htree_group->is_trivial_literal = is_trivial_literal;
  456. htree_group->is_trivial_code = 0;
  457. if (is_trivial_literal) {
  458. const int red = htrees[RED][0].value;
  459. const int blue = htrees[BLUE][0].value;
  460. const int alpha = htrees[ALPHA][0].value;
  461. htree_group->literal_arb = ((uint32_t)alpha << 24) | (red << 16) | blue;
  462. if (total_size == 0 && htrees[GREEN][0].value < NUM_LITERAL_CODES) {
  463. htree_group->is_trivial_code = 1;
  464. htree_group->literal_arb |= htrees[GREEN][0].value << 8;
  465. }
  466. }
  467. htree_group->use_packed_table =
  468. !htree_group->is_trivial_code && (max_bits < HUFFMAN_PACKED_BITS);
  469. if (htree_group->use_packed_table) BuildPackedTable(htree_group);
  470. }
  471. }
  472. ok = 1;
  473. // All OK. Finalize pointers.
  474. hdr->huffman_image_ = huffman_image;
  475. hdr->num_htree_groups_ = num_htree_groups;
  476. hdr->htree_groups_ = htree_groups;
  477. hdr->huffman_tables_ = huffman_tables;
  478. Error:
  479. WebPSafeFree(code_lengths);
  480. WebPSafeFree(mapping);
  481. if (!ok) {
  482. WebPSafeFree(huffman_image);
  483. WebPSafeFree(huffman_tables);
  484. VP8LHtreeGroupsFree(htree_groups);
  485. }
  486. return ok;
  487. }
  488. //------------------------------------------------------------------------------
  489. // Scaling.
  490. #if !defined(WEBP_REDUCE_SIZE)
  491. static int AllocateAndInitRescaler(VP8LDecoder* const dec, VP8Io* const io) {
  492. const int num_channels = 4;
  493. const int in_width = io->mb_w;
  494. const int out_width = io->scaled_width;
  495. const int in_height = io->mb_h;
  496. const int out_height = io->scaled_height;
  497. const uint64_t work_size = 2 * num_channels * (uint64_t)out_width;
  498. rescaler_t* work; // Rescaler work area.
  499. const uint64_t scaled_data_size = (uint64_t)out_width;
  500. uint32_t* scaled_data; // Temporary storage for scaled BGRA data.
  501. const uint64_t memory_size = sizeof(*dec->rescaler) +
  502. work_size * sizeof(*work) +
  503. scaled_data_size * sizeof(*scaled_data);
  504. uint8_t* memory = (uint8_t*)WebPSafeMalloc(memory_size, sizeof(*memory));
  505. if (memory == NULL) {
  506. dec->status_ = VP8_STATUS_OUT_OF_MEMORY;
  507. return 0;
  508. }
  509. assert(dec->rescaler_memory == NULL);
  510. dec->rescaler_memory = memory;
  511. dec->rescaler = (WebPRescaler*)memory;
  512. memory += sizeof(*dec->rescaler);
  513. work = (rescaler_t*)memory;
  514. memory += work_size * sizeof(*work);
  515. scaled_data = (uint32_t*)memory;
  516. if (!WebPRescalerInit(dec->rescaler, in_width, in_height,
  517. (uint8_t*)scaled_data, out_width, out_height,
  518. 0, num_channels, work)) {
  519. return 0;
  520. }
  521. return 1;
  522. }
  523. #endif // WEBP_REDUCE_SIZE
  524. //------------------------------------------------------------------------------
  525. // Export to ARGB
  526. #if !defined(WEBP_REDUCE_SIZE)
  527. // We have special "export" function since we need to convert from BGRA
  528. static int Export(WebPRescaler* const rescaler, WEBP_CSP_MODE colorspace,
  529. int rgba_stride, uint8_t* const rgba) {
  530. uint32_t* const src = (uint32_t*)rescaler->dst;
  531. uint8_t* dst = rgba;
  532. const int dst_width = rescaler->dst_width;
  533. int num_lines_out = 0;
  534. while (WebPRescalerHasPendingOutput(rescaler)) {
  535. WebPRescalerExportRow(rescaler);
  536. WebPMultARGBRow(src, dst_width, 1);
  537. VP8LConvertFromBGRA(src, dst_width, colorspace, dst);
  538. dst += rgba_stride;
  539. ++num_lines_out;
  540. }
  541. return num_lines_out;
  542. }
  543. // Emit scaled rows.
  544. static int EmitRescaledRowsRGBA(const VP8LDecoder* const dec,
  545. uint8_t* in, int in_stride, int mb_h,
  546. uint8_t* const out, int out_stride) {
  547. const WEBP_CSP_MODE colorspace = dec->output_->colorspace;
  548. int num_lines_in = 0;
  549. int num_lines_out = 0;
  550. while (num_lines_in < mb_h) {
  551. uint8_t* const row_in = in + (uint64_t)num_lines_in * in_stride;
  552. uint8_t* const row_out = out + (uint64_t)num_lines_out * out_stride;
  553. const int lines_left = mb_h - num_lines_in;
  554. const int needed_lines = WebPRescaleNeededLines(dec->rescaler, lines_left);
  555. int lines_imported;
  556. assert(needed_lines > 0 && needed_lines <= lines_left);
  557. WebPMultARGBRows(row_in, in_stride,
  558. dec->rescaler->src_width, needed_lines, 0);
  559. lines_imported =
  560. WebPRescalerImport(dec->rescaler, lines_left, row_in, in_stride);
  561. assert(lines_imported == needed_lines);
  562. num_lines_in += lines_imported;
  563. num_lines_out += Export(dec->rescaler, colorspace, out_stride, row_out);
  564. }
  565. return num_lines_out;
  566. }
  567. #endif // WEBP_REDUCE_SIZE
  568. // Emit rows without any scaling.
  569. static int EmitRows(WEBP_CSP_MODE colorspace,
  570. const uint8_t* row_in, int in_stride,
  571. int mb_w, int mb_h,
  572. uint8_t* const out, int out_stride) {
  573. int lines = mb_h;
  574. uint8_t* row_out = out;
  575. while (lines-- > 0) {
  576. VP8LConvertFromBGRA((const uint32_t*)row_in, mb_w, colorspace, row_out);
  577. row_in += in_stride;
  578. row_out += out_stride;
  579. }
  580. return mb_h; // Num rows out == num rows in.
  581. }
  582. //------------------------------------------------------------------------------
  583. // Export to YUVA
  584. static void ConvertToYUVA(const uint32_t* const src, int width, int y_pos,
  585. const WebPDecBuffer* const output) {
  586. const WebPYUVABuffer* const buf = &output->u.YUVA;
  587. // first, the luma plane
  588. WebPConvertARGBToY(src, buf->y + y_pos * buf->y_stride, width);
  589. // then U/V planes
  590. {
  591. uint8_t* const u = buf->u + (y_pos >> 1) * buf->u_stride;
  592. uint8_t* const v = buf->v + (y_pos >> 1) * buf->v_stride;
  593. // even lines: store values
  594. // odd lines: average with previous values
  595. WebPConvertARGBToUV(src, u, v, width, !(y_pos & 1));
  596. }
  597. // Lastly, store alpha if needed.
  598. if (buf->a != NULL) {
  599. uint8_t* const a = buf->a + y_pos * buf->a_stride;
  600. #if defined(WORDS_BIGENDIAN)
  601. WebPExtractAlpha((uint8_t*)src + 0, 0, width, 1, a, 0);
  602. #else
  603. WebPExtractAlpha((uint8_t*)src + 3, 0, width, 1, a, 0);
  604. #endif
  605. }
  606. }
  607. static int ExportYUVA(const VP8LDecoder* const dec, int y_pos) {
  608. WebPRescaler* const rescaler = dec->rescaler;
  609. uint32_t* const src = (uint32_t*)rescaler->dst;
  610. const int dst_width = rescaler->dst_width;
  611. int num_lines_out = 0;
  612. while (WebPRescalerHasPendingOutput(rescaler)) {
  613. WebPRescalerExportRow(rescaler);
  614. WebPMultARGBRow(src, dst_width, 1);
  615. ConvertToYUVA(src, dst_width, y_pos, dec->output_);
  616. ++y_pos;
  617. ++num_lines_out;
  618. }
  619. return num_lines_out;
  620. }
  621. static int EmitRescaledRowsYUVA(const VP8LDecoder* const dec,
  622. uint8_t* in, int in_stride, int mb_h) {
  623. int num_lines_in = 0;
  624. int y_pos = dec->last_out_row_;
  625. while (num_lines_in < mb_h) {
  626. const int lines_left = mb_h - num_lines_in;
  627. const int needed_lines = WebPRescaleNeededLines(dec->rescaler, lines_left);
  628. int lines_imported;
  629. WebPMultARGBRows(in, in_stride, dec->rescaler->src_width, needed_lines, 0);
  630. lines_imported =
  631. WebPRescalerImport(dec->rescaler, lines_left, in, in_stride);
  632. assert(lines_imported == needed_lines);
  633. num_lines_in += lines_imported;
  634. in += needed_lines * in_stride;
  635. y_pos += ExportYUVA(dec, y_pos);
  636. }
  637. return y_pos;
  638. }
  639. static int EmitRowsYUVA(const VP8LDecoder* const dec,
  640. const uint8_t* in, int in_stride,
  641. int mb_w, int num_rows) {
  642. int y_pos = dec->last_out_row_;
  643. while (num_rows-- > 0) {
  644. ConvertToYUVA((const uint32_t*)in, mb_w, y_pos, dec->output_);
  645. in += in_stride;
  646. ++y_pos;
  647. }
  648. return y_pos;
  649. }
  650. //------------------------------------------------------------------------------
  651. // Cropping.
  652. // Sets io->mb_y, io->mb_h & io->mb_w according to start row, end row and
  653. // crop options. Also updates the input data pointer, so that it points to the
  654. // start of the cropped window. Note that pixels are in ARGB format even if
  655. // 'in_data' is uint8_t*.
  656. // Returns true if the crop window is not empty.
  657. static int SetCropWindow(VP8Io* const io, int y_start, int y_end,
  658. uint8_t** const in_data, int pixel_stride) {
  659. assert(y_start < y_end);
  660. assert(io->crop_left < io->crop_right);
  661. if (y_end > io->crop_bottom) {
  662. y_end = io->crop_bottom; // make sure we don't overflow on last row.
  663. }
  664. if (y_start < io->crop_top) {
  665. const int delta = io->crop_top - y_start;
  666. y_start = io->crop_top;
  667. *in_data += delta * pixel_stride;
  668. }
  669. if (y_start >= y_end) return 0; // Crop window is empty.
  670. *in_data += io->crop_left * sizeof(uint32_t);
  671. io->mb_y = y_start - io->crop_top;
  672. io->mb_w = io->crop_right - io->crop_left;
  673. io->mb_h = y_end - y_start;
  674. return 1; // Non-empty crop window.
  675. }
  676. //------------------------------------------------------------------------------
  677. static WEBP_INLINE int GetMetaIndex(
  678. const uint32_t* const image, int xsize, int bits, int x, int y) {
  679. if (bits == 0) return 0;
  680. return image[xsize * (y >> bits) + (x >> bits)];
  681. }
  682. static WEBP_INLINE HTreeGroup* GetHtreeGroupForPos(VP8LMetadata* const hdr,
  683. int x, int y) {
  684. const int meta_index = GetMetaIndex(hdr->huffman_image_, hdr->huffman_xsize_,
  685. hdr->huffman_subsample_bits_, x, y);
  686. assert(meta_index < hdr->num_htree_groups_);
  687. return hdr->htree_groups_ + meta_index;
  688. }
  689. //------------------------------------------------------------------------------
  690. // Main loop, with custom row-processing function
  691. typedef void (*ProcessRowsFunc)(VP8LDecoder* const dec, int row);
  692. static void ApplyInverseTransforms(VP8LDecoder* const dec,
  693. int start_row, int num_rows,
  694. const uint32_t* const rows) {
  695. int n = dec->next_transform_;
  696. const int cache_pixs = dec->width_ * num_rows;
  697. const int end_row = start_row + num_rows;
  698. const uint32_t* rows_in = rows;
  699. uint32_t* const rows_out = dec->argb_cache_;
  700. // Inverse transforms.
  701. while (n-- > 0) {
  702. VP8LTransform* const transform = &dec->transforms_[n];
  703. VP8LInverseTransform(transform, start_row, end_row, rows_in, rows_out);
  704. rows_in = rows_out;
  705. }
  706. if (rows_in != rows_out) {
  707. // No transform called, hence just copy.
  708. memcpy(rows_out, rows_in, cache_pixs * sizeof(*rows_out));
  709. }
  710. }
  711. // Processes (transforms, scales & color-converts) the rows decoded after the
  712. // last call.
  713. static void ProcessRows(VP8LDecoder* const dec, int row) {
  714. const uint32_t* const rows = dec->pixels_ + dec->width_ * dec->last_row_;
  715. const int num_rows = row - dec->last_row_;
  716. assert(row <= dec->io_->crop_bottom);
  717. // We can't process more than NUM_ARGB_CACHE_ROWS at a time (that's the size
  718. // of argb_cache_), but we currently don't need more than that.
  719. assert(num_rows <= NUM_ARGB_CACHE_ROWS);
  720. if (num_rows > 0) { // Emit output.
  721. VP8Io* const io = dec->io_;
  722. uint8_t* rows_data = (uint8_t*)dec->argb_cache_;
  723. const int in_stride = io->width * sizeof(uint32_t); // in unit of RGBA
  724. ApplyInverseTransforms(dec, dec->last_row_, num_rows, rows);
  725. if (!SetCropWindow(io, dec->last_row_, row, &rows_data, in_stride)) {
  726. // Nothing to output (this time).
  727. } else {
  728. const WebPDecBuffer* const output = dec->output_;
  729. if (WebPIsRGBMode(output->colorspace)) { // convert to RGBA
  730. const WebPRGBABuffer* const buf = &output->u.RGBA;
  731. uint8_t* const rgba =
  732. buf->rgba + (int64_t)dec->last_out_row_ * buf->stride;
  733. const int num_rows_out =
  734. #if !defined(WEBP_REDUCE_SIZE)
  735. io->use_scaling ?
  736. EmitRescaledRowsRGBA(dec, rows_data, in_stride, io->mb_h,
  737. rgba, buf->stride) :
  738. #endif // WEBP_REDUCE_SIZE
  739. EmitRows(output->colorspace, rows_data, in_stride,
  740. io->mb_w, io->mb_h, rgba, buf->stride);
  741. // Update 'last_out_row_'.
  742. dec->last_out_row_ += num_rows_out;
  743. } else { // convert to YUVA
  744. dec->last_out_row_ = io->use_scaling ?
  745. EmitRescaledRowsYUVA(dec, rows_data, in_stride, io->mb_h) :
  746. EmitRowsYUVA(dec, rows_data, in_stride, io->mb_w, io->mb_h);
  747. }
  748. assert(dec->last_out_row_ <= output->height);
  749. }
  750. }
  751. // Update 'last_row_'.
  752. dec->last_row_ = row;
  753. assert(dec->last_row_ <= dec->height_);
  754. }
  755. // Row-processing for the special case when alpha data contains only one
  756. // transform (color indexing), and trivial non-green literals.
  757. static int Is8bOptimizable(const VP8LMetadata* const hdr) {
  758. int i;
  759. if (hdr->color_cache_size_ > 0) return 0;
  760. // When the Huffman tree contains only one symbol, we can skip the
  761. // call to ReadSymbol() for red/blue/alpha channels.
  762. for (i = 0; i < hdr->num_htree_groups_; ++i) {
  763. HuffmanCode** const htrees = hdr->htree_groups_[i].htrees;
  764. if (htrees[RED][0].bits > 0) return 0;
  765. if (htrees[BLUE][0].bits > 0) return 0;
  766. if (htrees[ALPHA][0].bits > 0) return 0;
  767. }
  768. return 1;
  769. }
  770. static void AlphaApplyFilter(ALPHDecoder* const alph_dec,
  771. int first_row, int last_row,
  772. uint8_t* out, int stride) {
  773. if (alph_dec->filter_ != WEBP_FILTER_NONE) {
  774. int y;
  775. const uint8_t* prev_line = alph_dec->prev_line_;
  776. assert(WebPUnfilters[alph_dec->filter_] != NULL);
  777. for (y = first_row; y < last_row; ++y) {
  778. WebPUnfilters[alph_dec->filter_](prev_line, out, out, stride);
  779. prev_line = out;
  780. out += stride;
  781. }
  782. alph_dec->prev_line_ = prev_line;
  783. }
  784. }
  785. static void ExtractPalettedAlphaRows(VP8LDecoder* const dec, int last_row) {
  786. // For vertical and gradient filtering, we need to decode the part above the
  787. // crop_top row, in order to have the correct spatial predictors.
  788. ALPHDecoder* const alph_dec = (ALPHDecoder*)dec->io_->opaque;
  789. const int top_row =
  790. (alph_dec->filter_ == WEBP_FILTER_NONE ||
  791. alph_dec->filter_ == WEBP_FILTER_HORIZONTAL) ? dec->io_->crop_top
  792. : dec->last_row_;
  793. const int first_row = (dec->last_row_ < top_row) ? top_row : dec->last_row_;
  794. assert(last_row <= dec->io_->crop_bottom);
  795. if (last_row > first_row) {
  796. // Special method for paletted alpha data. We only process the cropped area.
  797. const int width = dec->io_->width;
  798. uint8_t* out = alph_dec->output_ + width * first_row;
  799. const uint8_t* const in =
  800. (uint8_t*)dec->pixels_ + dec->width_ * first_row;
  801. VP8LTransform* const transform = &dec->transforms_[0];
  802. assert(dec->next_transform_ == 1);
  803. assert(transform->type_ == COLOR_INDEXING_TRANSFORM);
  804. VP8LColorIndexInverseTransformAlpha(transform, first_row, last_row,
  805. in, out);
  806. AlphaApplyFilter(alph_dec, first_row, last_row, out, width);
  807. }
  808. dec->last_row_ = dec->last_out_row_ = last_row;
  809. }
  810. //------------------------------------------------------------------------------
  811. // Helper functions for fast pattern copy (8b and 32b)
  812. // cyclic rotation of pattern word
  813. static WEBP_INLINE uint32_t Rotate8b(uint32_t V) {
  814. #if defined(WORDS_BIGENDIAN)
  815. return ((V & 0xff000000u) >> 24) | (V << 8);
  816. #else
  817. return ((V & 0xffu) << 24) | (V >> 8);
  818. #endif
  819. }
  820. // copy 1, 2 or 4-bytes pattern
  821. static WEBP_INLINE void CopySmallPattern8b(const uint8_t* src, uint8_t* dst,
  822. int length, uint32_t pattern) {
  823. int i;
  824. // align 'dst' to 4-bytes boundary. Adjust the pattern along the way.
  825. while ((uintptr_t)dst & 3) {
  826. *dst++ = *src++;
  827. pattern = Rotate8b(pattern);
  828. --length;
  829. }
  830. // Copy the pattern 4 bytes at a time.
  831. for (i = 0; i < (length >> 2); ++i) {
  832. ((uint32_t*)dst)[i] = pattern;
  833. }
  834. // Finish with left-overs. 'pattern' is still correctly positioned,
  835. // so no Rotate8b() call is needed.
  836. for (i <<= 2; i < length; ++i) {
  837. dst[i] = src[i];
  838. }
  839. }
  840. static WEBP_INLINE void CopyBlock8b(uint8_t* const dst, int dist, int length) {
  841. const uint8_t* src = dst - dist;
  842. if (length >= 8) {
  843. uint32_t pattern = 0;
  844. switch (dist) {
  845. case 1:
  846. pattern = src[0];
  847. #if defined(__arm__) || defined(_M_ARM) // arm doesn't like multiply that much
  848. pattern |= pattern << 8;
  849. pattern |= pattern << 16;
  850. #elif defined(WEBP_USE_MIPS_DSP_R2)
  851. __asm__ volatile ("replv.qb %0, %0" : "+r"(pattern));
  852. #else
  853. pattern = 0x01010101u * pattern;
  854. #endif
  855. break;
  856. case 2:
  857. #if !defined(WORDS_BIGENDIAN)
  858. memcpy(&pattern, src, sizeof(uint16_t));
  859. #else
  860. pattern = ((uint32_t)src[0] << 8) | src[1];
  861. #endif
  862. #if defined(__arm__) || defined(_M_ARM)
  863. pattern |= pattern << 16;
  864. #elif defined(WEBP_USE_MIPS_DSP_R2)
  865. __asm__ volatile ("replv.ph %0, %0" : "+r"(pattern));
  866. #else
  867. pattern = 0x00010001u * pattern;
  868. #endif
  869. break;
  870. case 4:
  871. memcpy(&pattern, src, sizeof(uint32_t));
  872. break;
  873. default:
  874. goto Copy;
  875. }
  876. CopySmallPattern8b(src, dst, length, pattern);
  877. return;
  878. }
  879. Copy:
  880. if (dist >= length) { // no overlap -> use memcpy()
  881. memcpy(dst, src, length * sizeof(*dst));
  882. } else {
  883. int i;
  884. for (i = 0; i < length; ++i) dst[i] = src[i];
  885. }
  886. }
  887. // copy pattern of 1 or 2 uint32_t's
  888. static WEBP_INLINE void CopySmallPattern32b(const uint32_t* src,
  889. uint32_t* dst,
  890. int length, uint64_t pattern) {
  891. int i;
  892. if ((uintptr_t)dst & 4) { // Align 'dst' to 8-bytes boundary.
  893. *dst++ = *src++;
  894. pattern = (pattern >> 32) | (pattern << 32);
  895. --length;
  896. }
  897. assert(0 == ((uintptr_t)dst & 7));
  898. for (i = 0; i < (length >> 1); ++i) {
  899. ((uint64_t*)dst)[i] = pattern; // Copy the pattern 8 bytes at a time.
  900. }
  901. if (length & 1) { // Finish with left-over.
  902. dst[i << 1] = src[i << 1];
  903. }
  904. }
  905. static WEBP_INLINE void CopyBlock32b(uint32_t* const dst,
  906. int dist, int length) {
  907. const uint32_t* const src = dst - dist;
  908. if (dist <= 2 && length >= 4 && ((uintptr_t)dst & 3) == 0) {
  909. uint64_t pattern;
  910. if (dist == 1) {
  911. pattern = (uint64_t)src[0];
  912. pattern |= pattern << 32;
  913. } else {
  914. memcpy(&pattern, src, sizeof(pattern));
  915. }
  916. CopySmallPattern32b(src, dst, length, pattern);
  917. } else if (dist >= length) { // no overlap
  918. memcpy(dst, src, length * sizeof(*dst));
  919. } else {
  920. int i;
  921. for (i = 0; i < length; ++i) dst[i] = src[i];
  922. }
  923. }
  924. //------------------------------------------------------------------------------
  925. static int DecodeAlphaData(VP8LDecoder* const dec, uint8_t* const data,
  926. int width, int height, int last_row) {
  927. int ok = 1;
  928. int row = dec->last_pixel_ / width;
  929. int col = dec->last_pixel_ % width;
  930. VP8LBitReader* const br = &dec->br_;
  931. VP8LMetadata* const hdr = &dec->hdr_;
  932. int pos = dec->last_pixel_; // current position
  933. const int end = width * height; // End of data
  934. const int last = width * last_row; // Last pixel to decode
  935. const int len_code_limit = NUM_LITERAL_CODES + NUM_LENGTH_CODES;
  936. const int mask = hdr->huffman_mask_;
  937. const HTreeGroup* htree_group =
  938. (pos < last) ? GetHtreeGroupForPos(hdr, col, row) : NULL;
  939. assert(pos <= end);
  940. assert(last_row <= height);
  941. assert(Is8bOptimizable(hdr));
  942. while (!br->eos_ && pos < last) {
  943. int code;
  944. // Only update when changing tile.
  945. if ((col & mask) == 0) {
  946. htree_group = GetHtreeGroupForPos(hdr, col, row);
  947. }
  948. assert(htree_group != NULL);
  949. VP8LFillBitWindow(br);
  950. code = ReadSymbol(htree_group->htrees[GREEN], br);
  951. if (code < NUM_LITERAL_CODES) { // Literal
  952. data[pos] = code;
  953. ++pos;
  954. ++col;
  955. if (col >= width) {
  956. col = 0;
  957. ++row;
  958. if (row <= last_row && (row % NUM_ARGB_CACHE_ROWS == 0)) {
  959. ExtractPalettedAlphaRows(dec, row);
  960. }
  961. }
  962. } else if (code < len_code_limit) { // Backward reference
  963. int dist_code, dist;
  964. const int length_sym = code - NUM_LITERAL_CODES;
  965. const int length = GetCopyLength(length_sym, br);
  966. const int dist_symbol = ReadSymbol(htree_group->htrees[DIST], br);
  967. VP8LFillBitWindow(br);
  968. dist_code = GetCopyDistance(dist_symbol, br);
  969. dist = PlaneCodeToDistance(width, dist_code);
  970. if (pos >= dist && end - pos >= length) {
  971. CopyBlock8b(data + pos, dist, length);
  972. } else {
  973. ok = 0;
  974. goto End;
  975. }
  976. pos += length;
  977. col += length;
  978. while (col >= width) {
  979. col -= width;
  980. ++row;
  981. if (row <= last_row && (row % NUM_ARGB_CACHE_ROWS == 0)) {
  982. ExtractPalettedAlphaRows(dec, row);
  983. }
  984. }
  985. if (pos < last && (col & mask)) {
  986. htree_group = GetHtreeGroupForPos(hdr, col, row);
  987. }
  988. } else { // Not reached
  989. ok = 0;
  990. goto End;
  991. }
  992. br->eos_ = VP8LIsEndOfStream(br);
  993. }
  994. // Process the remaining rows corresponding to last row-block.
  995. ExtractPalettedAlphaRows(dec, row > last_row ? last_row : row);
  996. End:
  997. br->eos_ = VP8LIsEndOfStream(br);
  998. if (!ok || (br->eos_ && pos < end)) {
  999. ok = 0;
  1000. dec->status_ = br->eos_ ? VP8_STATUS_SUSPENDED
  1001. : VP8_STATUS_BITSTREAM_ERROR;
  1002. } else {
  1003. dec->last_pixel_ = pos;
  1004. }
  1005. return ok;
  1006. }
  1007. static void SaveState(VP8LDecoder* const dec, int last_pixel) {
  1008. assert(dec->incremental_);
  1009. dec->saved_br_ = dec->br_;
  1010. dec->saved_last_pixel_ = last_pixel;
  1011. if (dec->hdr_.color_cache_size_ > 0) {
  1012. VP8LColorCacheCopy(&dec->hdr_.color_cache_, &dec->hdr_.saved_color_cache_);
  1013. }
  1014. }
  1015. static void RestoreState(VP8LDecoder* const dec) {
  1016. assert(dec->br_.eos_);
  1017. dec->status_ = VP8_STATUS_SUSPENDED;
  1018. dec->br_ = dec->saved_br_;
  1019. dec->last_pixel_ = dec->saved_last_pixel_;
  1020. if (dec->hdr_.color_cache_size_ > 0) {
  1021. VP8LColorCacheCopy(&dec->hdr_.saved_color_cache_, &dec->hdr_.color_cache_);
  1022. }
  1023. }
  1024. #define SYNC_EVERY_N_ROWS 8 // minimum number of rows between check-points
  1025. static int DecodeImageData(VP8LDecoder* const dec, uint32_t* const data,
  1026. int width, int height, int last_row,
  1027. ProcessRowsFunc process_func) {
  1028. int row = dec->last_pixel_ / width;
  1029. int col = dec->last_pixel_ % width;
  1030. VP8LBitReader* const br = &dec->br_;
  1031. VP8LMetadata* const hdr = &dec->hdr_;
  1032. uint32_t* src = data + dec->last_pixel_;
  1033. uint32_t* last_cached = src;
  1034. uint32_t* const src_end = data + width * height; // End of data
  1035. uint32_t* const src_last = data + width * last_row; // Last pixel to decode
  1036. const int len_code_limit = NUM_LITERAL_CODES + NUM_LENGTH_CODES;
  1037. const int color_cache_limit = len_code_limit + hdr->color_cache_size_;
  1038. int next_sync_row = dec->incremental_ ? row : 1 << 24;
  1039. VP8LColorCache* const color_cache =
  1040. (hdr->color_cache_size_ > 0) ? &hdr->color_cache_ : NULL;
  1041. const int mask = hdr->huffman_mask_;
  1042. const HTreeGroup* htree_group =
  1043. (src < src_last) ? GetHtreeGroupForPos(hdr, col, row) : NULL;
  1044. assert(dec->last_row_ < last_row);
  1045. assert(src_last <= src_end);
  1046. while (src < src_last) {
  1047. int code;
  1048. if (row >= next_sync_row) {
  1049. SaveState(dec, (int)(src - data));
  1050. next_sync_row = row + SYNC_EVERY_N_ROWS;
  1051. }
  1052. // Only update when changing tile. Note we could use this test:
  1053. // if "((((prev_col ^ col) | prev_row ^ row)) > mask)" -> tile changed
  1054. // but that's actually slower and needs storing the previous col/row.
  1055. if ((col & mask) == 0) {
  1056. htree_group = GetHtreeGroupForPos(hdr, col, row);
  1057. }
  1058. assert(htree_group != NULL);
  1059. if (htree_group->is_trivial_code) {
  1060. *src = htree_group->literal_arb;
  1061. goto AdvanceByOne;
  1062. }
  1063. VP8LFillBitWindow(br);
  1064. if (htree_group->use_packed_table) {
  1065. code = ReadPackedSymbols(htree_group, br, src);
  1066. if (VP8LIsEndOfStream(br)) break;
  1067. if (code == PACKED_NON_LITERAL_CODE) goto AdvanceByOne;
  1068. } else {
  1069. code = ReadSymbol(htree_group->htrees[GREEN], br);
  1070. }
  1071. if (VP8LIsEndOfStream(br)) break;
  1072. if (code < NUM_LITERAL_CODES) { // Literal
  1073. if (htree_group->is_trivial_literal) {
  1074. *src = htree_group->literal_arb | (code << 8);
  1075. } else {
  1076. int red, blue, alpha;
  1077. red = ReadSymbol(htree_group->htrees[RED], br);
  1078. VP8LFillBitWindow(br);
  1079. blue = ReadSymbol(htree_group->htrees[BLUE], br);
  1080. alpha = ReadSymbol(htree_group->htrees[ALPHA], br);
  1081. if (VP8LIsEndOfStream(br)) break;
  1082. *src = ((uint32_t)alpha << 24) | (red << 16) | (code << 8) | blue;
  1083. }
  1084. AdvanceByOne:
  1085. ++src;
  1086. ++col;
  1087. if (col >= width) {
  1088. col = 0;
  1089. ++row;
  1090. if (process_func != NULL) {
  1091. if (row <= last_row && (row % NUM_ARGB_CACHE_ROWS == 0)) {
  1092. process_func(dec, row);
  1093. }
  1094. }
  1095. if (color_cache != NULL) {
  1096. while (last_cached < src) {
  1097. VP8LColorCacheInsert(color_cache, *last_cached++);
  1098. }
  1099. }
  1100. }
  1101. } else if (code < len_code_limit) { // Backward reference
  1102. int dist_code, dist;
  1103. const int length_sym = code - NUM_LITERAL_CODES;
  1104. const int length = GetCopyLength(length_sym, br);
  1105. const int dist_symbol = ReadSymbol(htree_group->htrees[DIST], br);
  1106. VP8LFillBitWindow(br);
  1107. dist_code = GetCopyDistance(dist_symbol, br);
  1108. dist = PlaneCodeToDistance(width, dist_code);
  1109. if (VP8LIsEndOfStream(br)) break;
  1110. if (src - data < (ptrdiff_t)dist || src_end - src < (ptrdiff_t)length) {
  1111. goto Error;
  1112. } else {
  1113. CopyBlock32b(src, dist, length);
  1114. }
  1115. src += length;
  1116. col += length;
  1117. while (col >= width) {
  1118. col -= width;
  1119. ++row;
  1120. if (process_func != NULL) {
  1121. if (row <= last_row && (row % NUM_ARGB_CACHE_ROWS == 0)) {
  1122. process_func(dec, row);
  1123. }
  1124. }
  1125. }
  1126. // Because of the check done above (before 'src' was incremented by
  1127. // 'length'), the following holds true.
  1128. assert(src <= src_end);
  1129. if (col & mask) htree_group = GetHtreeGroupForPos(hdr, col, row);
  1130. if (color_cache != NULL) {
  1131. while (last_cached < src) {
  1132. VP8LColorCacheInsert(color_cache, *last_cached++);
  1133. }
  1134. }
  1135. } else if (code < color_cache_limit) { // Color cache
  1136. const int key = code - len_code_limit;
  1137. assert(color_cache != NULL);
  1138. while (last_cached < src) {
  1139. VP8LColorCacheInsert(color_cache, *last_cached++);
  1140. }
  1141. *src = VP8LColorCacheLookup(color_cache, key);
  1142. goto AdvanceByOne;
  1143. } else { // Not reached
  1144. goto Error;
  1145. }
  1146. }
  1147. br->eos_ = VP8LIsEndOfStream(br);
  1148. if (dec->incremental_ && br->eos_ && src < src_end) {
  1149. RestoreState(dec);
  1150. } else if (!br->eos_) {
  1151. // Process the remaining rows corresponding to last row-block.
  1152. if (process_func != NULL) {
  1153. process_func(dec, row > last_row ? last_row : row);
  1154. }
  1155. dec->status_ = VP8_STATUS_OK;
  1156. dec->last_pixel_ = (int)(src - data); // end-of-scan marker
  1157. } else {
  1158. // if not incremental, and we are past the end of buffer (eos_=1), then this
  1159. // is a real bitstream error.
  1160. goto Error;
  1161. }
  1162. return 1;
  1163. Error:
  1164. dec->status_ = VP8_STATUS_BITSTREAM_ERROR;
  1165. return 0;
  1166. }
  1167. // -----------------------------------------------------------------------------
  1168. // VP8LTransform
  1169. static void ClearTransform(VP8LTransform* const transform) {
  1170. WebPSafeFree(transform->data_);
  1171. transform->data_ = NULL;
  1172. }
  1173. // For security reason, we need to remap the color map to span
  1174. // the total possible bundled values, and not just the num_colors.
  1175. static int ExpandColorMap(int num_colors, VP8LTransform* const transform) {
  1176. int i;
  1177. const int final_num_colors = 1 << (8 >> transform->bits_);
  1178. uint32_t* const new_color_map =
  1179. (uint32_t*)WebPSafeMalloc((uint64_t)final_num_colors,
  1180. sizeof(*new_color_map));
  1181. if (new_color_map == NULL) {
  1182. return 0;
  1183. } else {
  1184. uint8_t* const data = (uint8_t*)transform->data_;
  1185. uint8_t* const new_data = (uint8_t*)new_color_map;
  1186. new_color_map[0] = transform->data_[0];
  1187. for (i = 4; i < 4 * num_colors; ++i) {
  1188. // Equivalent to AddPixelEq(), on a byte-basis.
  1189. new_data[i] = (data[i] + new_data[i - 4]) & 0xff;
  1190. }
  1191. for (; i < 4 * final_num_colors; ++i) {
  1192. new_data[i] = 0; // black tail.
  1193. }
  1194. WebPSafeFree(transform->data_);
  1195. transform->data_ = new_color_map;
  1196. }
  1197. return 1;
  1198. }
  1199. static int ReadTransform(int* const xsize, int const* ysize,
  1200. VP8LDecoder* const dec) {
  1201. int ok = 1;
  1202. VP8LBitReader* const br = &dec->br_;
  1203. VP8LTransform* transform = &dec->transforms_[dec->next_transform_];
  1204. const VP8LImageTransformType type =
  1205. (VP8LImageTransformType)VP8LReadBits(br, 2);
  1206. // Each transform type can only be present once in the stream.
  1207. if (dec->transforms_seen_ & (1U << type)) {
  1208. return 0; // Already there, let's not accept the second same transform.
  1209. }
  1210. dec->transforms_seen_ |= (1U << type);
  1211. transform->type_ = type;
  1212. transform->xsize_ = *xsize;
  1213. transform->ysize_ = *ysize;
  1214. transform->data_ = NULL;
  1215. ++dec->next_transform_;
  1216. assert(dec->next_transform_ <= NUM_TRANSFORMS);
  1217. switch (type) {
  1218. case PREDICTOR_TRANSFORM:
  1219. case CROSS_COLOR_TRANSFORM:
  1220. transform->bits_ = VP8LReadBits(br, 3) + 2;
  1221. ok = DecodeImageStream(VP8LSubSampleSize(transform->xsize_,
  1222. transform->bits_),
  1223. VP8LSubSampleSize(transform->ysize_,
  1224. transform->bits_),
  1225. 0, dec, &transform->data_);
  1226. break;
  1227. case COLOR_INDEXING_TRANSFORM: {
  1228. const int num_colors = VP8LReadBits(br, 8) + 1;
  1229. const int bits = (num_colors > 16) ? 0
  1230. : (num_colors > 4) ? 1
  1231. : (num_colors > 2) ? 2
  1232. : 3;
  1233. *xsize = VP8LSubSampleSize(transform->xsize_, bits);
  1234. transform->bits_ = bits;
  1235. ok = DecodeImageStream(num_colors, 1, 0, dec, &transform->data_);
  1236. ok = ok && ExpandColorMap(num_colors, transform);
  1237. break;
  1238. }
  1239. case SUBTRACT_GREEN:
  1240. break;
  1241. default:
  1242. assert(0); // can't happen
  1243. break;
  1244. }
  1245. return ok;
  1246. }
  1247. // -----------------------------------------------------------------------------
  1248. // VP8LMetadata
  1249. static void InitMetadata(VP8LMetadata* const hdr) {
  1250. assert(hdr != NULL);
  1251. memset(hdr, 0, sizeof(*hdr));
  1252. }
  1253. static void ClearMetadata(VP8LMetadata* const hdr) {
  1254. assert(hdr != NULL);
  1255. WebPSafeFree(hdr->huffman_image_);
  1256. WebPSafeFree(hdr->huffman_tables_);
  1257. VP8LHtreeGroupsFree(hdr->htree_groups_);
  1258. VP8LColorCacheClear(&hdr->color_cache_);
  1259. VP8LColorCacheClear(&hdr->saved_color_cache_);
  1260. InitMetadata(hdr);
  1261. }
  1262. // -----------------------------------------------------------------------------
  1263. // VP8LDecoder
  1264. VP8LDecoder* VP8LNew(void) {
  1265. VP8LDecoder* const dec = (VP8LDecoder*)WebPSafeCalloc(1ULL, sizeof(*dec));
  1266. if (dec == NULL) return NULL;
  1267. dec->status_ = VP8_STATUS_OK;
  1268. dec->state_ = READ_DIM;
  1269. VP8LDspInit(); // Init critical function pointers.
  1270. return dec;
  1271. }
  1272. void VP8LClear(VP8LDecoder* const dec) {
  1273. int i;
  1274. if (dec == NULL) return;
  1275. ClearMetadata(&dec->hdr_);
  1276. WebPSafeFree(dec->pixels_);
  1277. dec->pixels_ = NULL;
  1278. for (i = 0; i < dec->next_transform_; ++i) {
  1279. ClearTransform(&dec->transforms_[i]);
  1280. }
  1281. dec->next_transform_ = 0;
  1282. dec->transforms_seen_ = 0;
  1283. WebPSafeFree(dec->rescaler_memory);
  1284. dec->rescaler_memory = NULL;
  1285. dec->output_ = NULL; // leave no trace behind
  1286. }
  1287. void VP8LDelete(VP8LDecoder* const dec) {
  1288. if (dec != NULL) {
  1289. VP8LClear(dec);
  1290. WebPSafeFree(dec);
  1291. }
  1292. }
  1293. static void UpdateDecoder(VP8LDecoder* const dec, int width, int height) {
  1294. VP8LMetadata* const hdr = &dec->hdr_;
  1295. const int num_bits = hdr->huffman_subsample_bits_;
  1296. dec->width_ = width;
  1297. dec->height_ = height;
  1298. hdr->huffman_xsize_ = VP8LSubSampleSize(width, num_bits);
  1299. hdr->huffman_mask_ = (num_bits == 0) ? ~0 : (1 << num_bits) - 1;
  1300. }
  1301. static int DecodeImageStream(int xsize, int ysize,
  1302. int is_level0,
  1303. VP8LDecoder* const dec,
  1304. uint32_t** const decoded_data) {
  1305. int ok = 1;
  1306. int transform_xsize = xsize;
  1307. int transform_ysize = ysize;
  1308. VP8LBitReader* const br = &dec->br_;
  1309. VP8LMetadata* const hdr = &dec->hdr_;
  1310. uint32_t* data = NULL;
  1311. int color_cache_bits = 0;
  1312. // Read the transforms (may recurse).
  1313. if (is_level0) {
  1314. while (ok && VP8LReadBits(br, 1)) {
  1315. ok = ReadTransform(&transform_xsize, &transform_ysize, dec);
  1316. }
  1317. }
  1318. // Color cache
  1319. if (ok && VP8LReadBits(br, 1)) {
  1320. color_cache_bits = VP8LReadBits(br, 4);
  1321. ok = (color_cache_bits >= 1 && color_cache_bits <= MAX_CACHE_BITS);
  1322. if (!ok) {
  1323. dec->status_ = VP8_STATUS_BITSTREAM_ERROR;
  1324. goto End;
  1325. }
  1326. }
  1327. // Read the Huffman codes (may recurse).
  1328. ok = ok && ReadHuffmanCodes(dec, transform_xsize, transform_ysize,
  1329. color_cache_bits, is_level0);
  1330. if (!ok) {
  1331. dec->status_ = VP8_STATUS_BITSTREAM_ERROR;
  1332. goto End;
  1333. }
  1334. // Finish setting up the color-cache
  1335. if (color_cache_bits > 0) {
  1336. hdr->color_cache_size_ = 1 << color_cache_bits;
  1337. if (!VP8LColorCacheInit(&hdr->color_cache_, color_cache_bits)) {
  1338. dec->status_ = VP8_STATUS_OUT_OF_MEMORY;
  1339. ok = 0;
  1340. goto End;
  1341. }
  1342. } else {
  1343. hdr->color_cache_size_ = 0;
  1344. }
  1345. UpdateDecoder(dec, transform_xsize, transform_ysize);
  1346. if (is_level0) { // level 0 complete
  1347. dec->state_ = READ_HDR;
  1348. goto End;
  1349. }
  1350. {
  1351. const uint64_t total_size = (uint64_t)transform_xsize * transform_ysize;
  1352. data = (uint32_t*)WebPSafeMalloc(total_size, sizeof(*data));
  1353. if (data == NULL) {
  1354. dec->status_ = VP8_STATUS_OUT_OF_MEMORY;
  1355. ok = 0;
  1356. goto End;
  1357. }
  1358. }
  1359. // Use the Huffman trees to decode the LZ77 encoded data.
  1360. ok = DecodeImageData(dec, data, transform_xsize, transform_ysize,
  1361. transform_ysize, NULL);
  1362. ok = ok && !br->eos_;
  1363. End:
  1364. if (!ok) {
  1365. WebPSafeFree(data);
  1366. ClearMetadata(hdr);
  1367. } else {
  1368. if (decoded_data != NULL) {
  1369. *decoded_data = data;
  1370. } else {
  1371. // We allocate image data in this function only for transforms. At level 0
  1372. // (that is: not the transforms), we shouldn't have allocated anything.
  1373. assert(data == NULL);
  1374. assert(is_level0);
  1375. }
  1376. dec->last_pixel_ = 0; // Reset for future DECODE_DATA_FUNC() calls.
  1377. if (!is_level0) ClearMetadata(hdr); // Clean up temporary data behind.
  1378. }
  1379. return ok;
  1380. }
  1381. //------------------------------------------------------------------------------
  1382. // Allocate internal buffers dec->pixels_ and dec->argb_cache_.
  1383. static int AllocateInternalBuffers32b(VP8LDecoder* const dec, int final_width) {
  1384. const uint64_t num_pixels = (uint64_t)dec->width_ * dec->height_;
  1385. // Scratch buffer corresponding to top-prediction row for transforming the
  1386. // first row in the row-blocks. Not needed for paletted alpha.
  1387. const uint64_t cache_top_pixels = (uint16_t)final_width;
  1388. // Scratch buffer for temporary BGRA storage. Not needed for paletted alpha.
  1389. const uint64_t cache_pixels = (uint64_t)final_width * NUM_ARGB_CACHE_ROWS;
  1390. const uint64_t total_num_pixels =
  1391. num_pixels + cache_top_pixels + cache_pixels;
  1392. assert(dec->width_ <= final_width);
  1393. dec->pixels_ = (uint32_t*)WebPSafeMalloc(total_num_pixels, sizeof(uint32_t));
  1394. if (dec->pixels_ == NULL) {
  1395. dec->argb_cache_ = NULL; // for soundness
  1396. dec->status_ = VP8_STATUS_OUT_OF_MEMORY;
  1397. return 0;
  1398. }
  1399. dec->argb_cache_ = dec->pixels_ + num_pixels + cache_top_pixels;
  1400. return 1;
  1401. }
  1402. static int AllocateInternalBuffers8b(VP8LDecoder* const dec) {
  1403. const uint64_t total_num_pixels = (uint64_t)dec->width_ * dec->height_;
  1404. dec->argb_cache_ = NULL; // for soundness
  1405. dec->pixels_ = (uint32_t*)WebPSafeMalloc(total_num_pixels, sizeof(uint8_t));
  1406. if (dec->pixels_ == NULL) {
  1407. dec->status_ = VP8_STATUS_OUT_OF_MEMORY;
  1408. return 0;
  1409. }
  1410. return 1;
  1411. }
  1412. //------------------------------------------------------------------------------
  1413. // Special row-processing that only stores the alpha data.
  1414. static void ExtractAlphaRows(VP8LDecoder* const dec, int last_row) {
  1415. int cur_row = dec->last_row_;
  1416. int num_rows = last_row - cur_row;
  1417. const uint32_t* in = dec->pixels_ + dec->width_ * cur_row;
  1418. assert(last_row <= dec->io_->crop_bottom);
  1419. while (num_rows > 0) {
  1420. const int num_rows_to_process =
  1421. (num_rows > NUM_ARGB_CACHE_ROWS) ? NUM_ARGB_CACHE_ROWS : num_rows;
  1422. // Extract alpha (which is stored in the green plane).
  1423. ALPHDecoder* const alph_dec = (ALPHDecoder*)dec->io_->opaque;
  1424. uint8_t* const output = alph_dec->output_;
  1425. const int width = dec->io_->width; // the final width (!= dec->width_)
  1426. const int cache_pixs = width * num_rows_to_process;
  1427. uint8_t* const dst = output + width * cur_row;
  1428. const uint32_t* const src = dec->argb_cache_;
  1429. ApplyInverseTransforms(dec, cur_row, num_rows_to_process, in);
  1430. WebPExtractGreen(src, dst, cache_pixs);
  1431. AlphaApplyFilter(alph_dec,
  1432. cur_row, cur_row + num_rows_to_process, dst, width);
  1433. num_rows -= num_rows_to_process;
  1434. in += num_rows_to_process * dec->width_;
  1435. cur_row += num_rows_to_process;
  1436. }
  1437. assert(cur_row == last_row);
  1438. dec->last_row_ = dec->last_out_row_ = last_row;
  1439. }
  1440. int VP8LDecodeAlphaHeader(ALPHDecoder* const alph_dec,
  1441. const uint8_t* const data, size_t data_size) {
  1442. int ok = 0;
  1443. VP8LDecoder* dec = VP8LNew();
  1444. if (dec == NULL) return 0;
  1445. assert(alph_dec != NULL);
  1446. dec->width_ = alph_dec->width_;
  1447. dec->height_ = alph_dec->height_;
  1448. dec->io_ = &alph_dec->io_;
  1449. dec->io_->opaque = alph_dec;
  1450. dec->io_->width = alph_dec->width_;
  1451. dec->io_->height = alph_dec->height_;
  1452. dec->status_ = VP8_STATUS_OK;
  1453. VP8LInitBitReader(&dec->br_, data, data_size);
  1454. if (!DecodeImageStream(alph_dec->width_, alph_dec->height_, 1, dec, NULL)) {
  1455. goto Err;
  1456. }
  1457. // Special case: if alpha data uses only the color indexing transform and
  1458. // doesn't use color cache (a frequent case), we will use DecodeAlphaData()
  1459. // method that only needs allocation of 1 byte per pixel (alpha channel).
  1460. if (dec->next_transform_ == 1 &&
  1461. dec->transforms_[0].type_ == COLOR_INDEXING_TRANSFORM &&
  1462. Is8bOptimizable(&dec->hdr_)) {
  1463. alph_dec->use_8b_decode_ = 1;
  1464. ok = AllocateInternalBuffers8b(dec);
  1465. } else {
  1466. // Allocate internal buffers (note that dec->width_ may have changed here).
  1467. alph_dec->use_8b_decode_ = 0;
  1468. ok = AllocateInternalBuffers32b(dec, alph_dec->width_);
  1469. }
  1470. if (!ok) goto Err;
  1471. // Only set here, once we are sure it is valid (to avoid thread races).
  1472. alph_dec->vp8l_dec_ = dec;
  1473. return 1;
  1474. Err:
  1475. VP8LDelete(dec);
  1476. return 0;
  1477. }
  1478. int VP8LDecodeAlphaImageStream(ALPHDecoder* const alph_dec, int last_row) {
  1479. VP8LDecoder* const dec = alph_dec->vp8l_dec_;
  1480. assert(dec != NULL);
  1481. assert(last_row <= dec->height_);
  1482. if (dec->last_row_ >= last_row) {
  1483. return 1; // done
  1484. }
  1485. if (!alph_dec->use_8b_decode_) WebPInitAlphaProcessing();
  1486. // Decode (with special row processing).
  1487. return alph_dec->use_8b_decode_ ?
  1488. DecodeAlphaData(dec, (uint8_t*)dec->pixels_, dec->width_, dec->height_,
  1489. last_row) :
  1490. DecodeImageData(dec, dec->pixels_, dec->width_, dec->height_,
  1491. last_row, ExtractAlphaRows);
  1492. }
  1493. //------------------------------------------------------------------------------
  1494. int VP8LDecodeHeader(VP8LDecoder* const dec, VP8Io* const io) {
  1495. int width, height, has_alpha;
  1496. if (dec == NULL) return 0;
  1497. if (io == NULL) {
  1498. dec->status_ = VP8_STATUS_INVALID_PARAM;
  1499. return 0;
  1500. }
  1501. dec->io_ = io;
  1502. dec->status_ = VP8_STATUS_OK;
  1503. VP8LInitBitReader(&dec->br_, io->data, io->data_size);
  1504. if (!ReadImageInfo(&dec->br_, &width, &height, &has_alpha)) {
  1505. dec->status_ = VP8_STATUS_BITSTREAM_ERROR;
  1506. goto Error;
  1507. }
  1508. dec->state_ = READ_DIM;
  1509. io->width = width;
  1510. io->height = height;
  1511. if (!DecodeImageStream(width, height, 1, dec, NULL)) goto Error;
  1512. return 1;
  1513. Error:
  1514. VP8LClear(dec);
  1515. assert(dec->status_ != VP8_STATUS_OK);
  1516. return 0;
  1517. }
  1518. int VP8LDecodeImage(VP8LDecoder* const dec) {
  1519. VP8Io* io = NULL;
  1520. WebPDecParams* params = NULL;
  1521. if (dec == NULL) return 0;
  1522. assert(dec->hdr_.huffman_tables_ != NULL);
  1523. assert(dec->hdr_.htree_groups_ != NULL);
  1524. assert(dec->hdr_.num_htree_groups_ > 0);
  1525. io = dec->io_;
  1526. assert(io != NULL);
  1527. params = (WebPDecParams*)io->opaque;
  1528. assert(params != NULL);
  1529. // Initialization.
  1530. if (dec->state_ != READ_DATA) {
  1531. dec->output_ = params->output;
  1532. assert(dec->output_ != NULL);
  1533. if (!WebPIoInitFromOptions(params->options, io, MODE_BGRA)) {
  1534. dec->status_ = VP8_STATUS_INVALID_PARAM;
  1535. goto Err;
  1536. }
  1537. if (!AllocateInternalBuffers32b(dec, io->width)) goto Err;
  1538. #if !defined(WEBP_REDUCE_SIZE)
  1539. if (io->use_scaling && !AllocateAndInitRescaler(dec, io)) goto Err;
  1540. #else
  1541. if (io->use_scaling) {
  1542. dec->status_ = VP8_STATUS_INVALID_PARAM;
  1543. goto Err;
  1544. }
  1545. #endif
  1546. if (io->use_scaling || WebPIsPremultipliedMode(dec->output_->colorspace)) {
  1547. // need the alpha-multiply functions for premultiplied output or rescaling
  1548. WebPInitAlphaProcessing();
  1549. }
  1550. if (!WebPIsRGBMode(dec->output_->colorspace)) {
  1551. WebPInitConvertARGBToYUV();
  1552. if (dec->output_->u.YUVA.a != NULL) WebPInitAlphaProcessing();
  1553. }
  1554. if (dec->incremental_) {
  1555. if (dec->hdr_.color_cache_size_ > 0 &&
  1556. dec->hdr_.saved_color_cache_.colors_ == NULL) {
  1557. if (!VP8LColorCacheInit(&dec->hdr_.saved_color_cache_,
  1558. dec->hdr_.color_cache_.hash_bits_)) {
  1559. dec->status_ = VP8_STATUS_OUT_OF_MEMORY;
  1560. goto Err;
  1561. }
  1562. }
  1563. }
  1564. dec->state_ = READ_DATA;
  1565. }
  1566. // Decode.
  1567. if (!DecodeImageData(dec, dec->pixels_, dec->width_, dec->height_,
  1568. io->crop_bottom, ProcessRows)) {
  1569. goto Err;
  1570. }
  1571. params->last_y = dec->last_out_row_;
  1572. return 1;
  1573. Err:
  1574. VP8LClear(dec);
  1575. assert(dec->status_ != VP8_STATUS_OK);
  1576. return 0;
  1577. }
  1578. //------------------------------------------------------------------------------