vp8l.c 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244
  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 lossless encoder.
  11. //
  12. // Author: Vikas Arora (vikaas.arora@gmail.com)
  13. //
  14. #include <assert.h>
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include "./backward_references.h"
  18. #include "./vp8enci.h"
  19. #include "./vp8li.h"
  20. #include "../dsp/lossless.h"
  21. #include "../utils/bit_writer.h"
  22. #include "../utils/huffman_encode.h"
  23. #include "../utils/utils.h"
  24. #include "../webp/format_constants.h"
  25. #define PALETTE_KEY_RIGHT_SHIFT 22 // Key for 1K buffer.
  26. #define MAX_HUFF_IMAGE_SIZE (16 * 1024 * 1024)
  27. #define MAX_COLORS_FOR_GRAPH 64
  28. // -----------------------------------------------------------------------------
  29. // Palette
  30. static int CompareColors(const void* p1, const void* p2) {
  31. const uint32_t a = *(const uint32_t*)p1;
  32. const uint32_t b = *(const uint32_t*)p2;
  33. assert(a != b);
  34. return (a < b) ? -1 : 1;
  35. }
  36. // If number of colors in the image is less than or equal to MAX_PALETTE_SIZE,
  37. // creates a palette and returns true, else returns false.
  38. static int AnalyzeAndCreatePalette(const WebPPicture* const pic,
  39. uint32_t palette[MAX_PALETTE_SIZE],
  40. int* const palette_size) {
  41. int i, x, y, key;
  42. int num_colors = 0;
  43. uint8_t in_use[MAX_PALETTE_SIZE * 4] = { 0 };
  44. uint32_t colors[MAX_PALETTE_SIZE * 4];
  45. static const uint32_t kHashMul = 0x1e35a7bd;
  46. const uint32_t* argb = pic->argb;
  47. const int width = pic->width;
  48. const int height = pic->height;
  49. uint32_t last_pix = ~argb[0]; // so we're sure that last_pix != argb[0]
  50. for (y = 0; y < height; ++y) {
  51. for (x = 0; x < width; ++x) {
  52. if (argb[x] == last_pix) {
  53. continue;
  54. }
  55. last_pix = argb[x];
  56. key = (kHashMul * last_pix) >> PALETTE_KEY_RIGHT_SHIFT;
  57. while (1) {
  58. if (!in_use[key]) {
  59. colors[key] = last_pix;
  60. in_use[key] = 1;
  61. ++num_colors;
  62. if (num_colors > MAX_PALETTE_SIZE) {
  63. return 0;
  64. }
  65. break;
  66. } else if (colors[key] == last_pix) {
  67. // The color is already there.
  68. break;
  69. } else {
  70. // Some other color sits there.
  71. // Do linear conflict resolution.
  72. ++key;
  73. key &= (MAX_PALETTE_SIZE * 4 - 1); // key mask for 1K buffer.
  74. }
  75. }
  76. }
  77. argb += pic->argb_stride;
  78. }
  79. // TODO(skal): could we reuse in_use[] to speed up EncodePalette()?
  80. num_colors = 0;
  81. for (i = 0; i < (int)(sizeof(in_use) / sizeof(in_use[0])); ++i) {
  82. if (in_use[i]) {
  83. palette[num_colors] = colors[i];
  84. ++num_colors;
  85. }
  86. }
  87. qsort(palette, num_colors, sizeof(*palette), CompareColors);
  88. *palette_size = num_colors;
  89. return 1;
  90. }
  91. static int AnalyzeEntropy(const uint32_t* argb,
  92. int width, int height, int argb_stride,
  93. double* const nonpredicted_bits,
  94. double* const predicted_bits) {
  95. int x, y;
  96. const uint32_t* last_line = NULL;
  97. uint32_t last_pix = argb[0]; // so we're sure that pix_diff == 0
  98. VP8LHistogramSet* const histo_set = VP8LAllocateHistogramSet(2, 0);
  99. if (histo_set == NULL) return 0;
  100. for (y = 0; y < height; ++y) {
  101. for (x = 0; x < width; ++x) {
  102. const uint32_t pix = argb[x];
  103. const uint32_t pix_diff = VP8LSubPixels(pix, last_pix);
  104. if (pix_diff == 0) continue;
  105. if (last_line != NULL && pix == last_line[x]) {
  106. continue;
  107. }
  108. last_pix = pix;
  109. {
  110. const PixOrCopy pix_token = PixOrCopyCreateLiteral(pix);
  111. const PixOrCopy pix_diff_token = PixOrCopyCreateLiteral(pix_diff);
  112. VP8LHistogramAddSinglePixOrCopy(histo_set->histograms[0], &pix_token);
  113. VP8LHistogramAddSinglePixOrCopy(histo_set->histograms[1],
  114. &pix_diff_token);
  115. }
  116. }
  117. last_line = argb;
  118. argb += argb_stride;
  119. }
  120. *nonpredicted_bits = VP8LHistogramEstimateBitsBulk(histo_set->histograms[0]);
  121. *predicted_bits = VP8LHistogramEstimateBitsBulk(histo_set->histograms[1]);
  122. VP8LFreeHistogramSet(histo_set);
  123. return 1;
  124. }
  125. static int AnalyzeAndInit(VP8LEncoder* const enc, WebPImageHint image_hint) {
  126. const WebPPicture* const pic = enc->pic_;
  127. const int width = pic->width;
  128. const int height = pic->height;
  129. const int pix_cnt = width * height;
  130. // we round the block size up, so we're guaranteed to have
  131. // at max MAX_REFS_BLOCK_PER_IMAGE blocks used:
  132. int refs_block_size = (pix_cnt - 1) / MAX_REFS_BLOCK_PER_IMAGE + 1;
  133. assert(pic != NULL && pic->argb != NULL);
  134. enc->use_palette_ =
  135. AnalyzeAndCreatePalette(pic, enc->palette_, &enc->palette_size_);
  136. if (image_hint == WEBP_HINT_GRAPH) {
  137. if (enc->use_palette_ && enc->palette_size_ < MAX_COLORS_FOR_GRAPH) {
  138. enc->use_palette_ = 0;
  139. }
  140. }
  141. if (!enc->use_palette_) {
  142. if (image_hint == WEBP_HINT_PHOTO) {
  143. enc->use_predict_ = 1;
  144. enc->use_cross_color_ = 1;
  145. } else {
  146. double non_pred_entropy, pred_entropy;
  147. if (!AnalyzeEntropy(pic->argb, width, height, pic->argb_stride,
  148. &non_pred_entropy, &pred_entropy)) {
  149. return 0;
  150. }
  151. if (pred_entropy < 0.95 * non_pred_entropy) {
  152. enc->use_predict_ = 1;
  153. enc->use_cross_color_ = 1;
  154. }
  155. }
  156. }
  157. if (!VP8LHashChainInit(&enc->hash_chain_, pix_cnt)) return 0;
  158. // palette-friendly input typically uses less literals
  159. // -> reduce block size a bit
  160. if (enc->use_palette_) refs_block_size /= 2;
  161. VP8LBackwardRefsInit(&enc->refs_[0], refs_block_size);
  162. VP8LBackwardRefsInit(&enc->refs_[1], refs_block_size);
  163. return 1;
  164. }
  165. // Returns false in case of memory error.
  166. static int GetHuffBitLengthsAndCodes(
  167. const VP8LHistogramSet* const histogram_image,
  168. HuffmanTreeCode* const huffman_codes) {
  169. int i, k;
  170. int ok = 0;
  171. uint64_t total_length_size = 0;
  172. uint8_t* mem_buf = NULL;
  173. const int histogram_image_size = histogram_image->size;
  174. int max_num_symbols = 0;
  175. uint8_t* buf_rle = NULL;
  176. HuffmanTree* huff_tree = NULL;
  177. // Iterate over all histograms and get the aggregate number of codes used.
  178. for (i = 0; i < histogram_image_size; ++i) {
  179. const VP8LHistogram* const histo = histogram_image->histograms[i];
  180. HuffmanTreeCode* const codes = &huffman_codes[5 * i];
  181. for (k = 0; k < 5; ++k) {
  182. const int num_symbols =
  183. (k == 0) ? VP8LHistogramNumCodes(histo->palette_code_bits_) :
  184. (k == 4) ? NUM_DISTANCE_CODES : 256;
  185. codes[k].num_symbols = num_symbols;
  186. total_length_size += num_symbols;
  187. }
  188. }
  189. // Allocate and Set Huffman codes.
  190. {
  191. uint16_t* codes;
  192. uint8_t* lengths;
  193. mem_buf = (uint8_t*)WebPSafeCalloc(total_length_size,
  194. sizeof(*lengths) + sizeof(*codes));
  195. if (mem_buf == NULL) goto End;
  196. codes = (uint16_t*)mem_buf;
  197. lengths = (uint8_t*)&codes[total_length_size];
  198. for (i = 0; i < 5 * histogram_image_size; ++i) {
  199. const int bit_length = huffman_codes[i].num_symbols;
  200. huffman_codes[i].codes = codes;
  201. huffman_codes[i].code_lengths = lengths;
  202. codes += bit_length;
  203. lengths += bit_length;
  204. if (max_num_symbols < bit_length) {
  205. max_num_symbols = bit_length;
  206. }
  207. }
  208. }
  209. buf_rle = (uint8_t*)WebPSafeMalloc(1ULL, max_num_symbols);
  210. huff_tree = (HuffmanTree*)WebPSafeMalloc(3ULL * max_num_symbols,
  211. sizeof(*huff_tree));
  212. if (buf_rle == NULL || huff_tree == NULL) goto End;
  213. // Create Huffman trees.
  214. for (i = 0; i < histogram_image_size; ++i) {
  215. HuffmanTreeCode* const codes = &huffman_codes[5 * i];
  216. VP8LHistogram* const histo = histogram_image->histograms[i];
  217. VP8LCreateHuffmanTree(histo->literal_, 15, buf_rle, huff_tree, codes + 0);
  218. VP8LCreateHuffmanTree(histo->red_, 15, buf_rle, huff_tree, codes + 1);
  219. VP8LCreateHuffmanTree(histo->blue_, 15, buf_rle, huff_tree, codes + 2);
  220. VP8LCreateHuffmanTree(histo->alpha_, 15, buf_rle, huff_tree, codes + 3);
  221. VP8LCreateHuffmanTree(histo->distance_, 15, buf_rle, huff_tree, codes + 4);
  222. }
  223. ok = 1;
  224. End:
  225. WebPSafeFree(huff_tree);
  226. WebPSafeFree(buf_rle);
  227. if (!ok) {
  228. WebPSafeFree(mem_buf);
  229. memset(huffman_codes, 0, 5 * histogram_image_size * sizeof(*huffman_codes));
  230. }
  231. return ok;
  232. }
  233. static void StoreHuffmanTreeOfHuffmanTreeToBitMask(
  234. VP8LBitWriter* const bw, const uint8_t* code_length_bitdepth) {
  235. // RFC 1951 will calm you down if you are worried about this funny sequence.
  236. // This sequence is tuned from that, but more weighted for lower symbol count,
  237. // and more spiking histograms.
  238. static const uint8_t kStorageOrder[CODE_LENGTH_CODES] = {
  239. 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
  240. };
  241. int i;
  242. // Throw away trailing zeros:
  243. int codes_to_store = CODE_LENGTH_CODES;
  244. for (; codes_to_store > 4; --codes_to_store) {
  245. if (code_length_bitdepth[kStorageOrder[codes_to_store - 1]] != 0) {
  246. break;
  247. }
  248. }
  249. VP8LWriteBits(bw, 4, codes_to_store - 4);
  250. for (i = 0; i < codes_to_store; ++i) {
  251. VP8LWriteBits(bw, 3, code_length_bitdepth[kStorageOrder[i]]);
  252. }
  253. }
  254. static void ClearHuffmanTreeIfOnlyOneSymbol(
  255. HuffmanTreeCode* const huffman_code) {
  256. int k;
  257. int count = 0;
  258. for (k = 0; k < huffman_code->num_symbols; ++k) {
  259. if (huffman_code->code_lengths[k] != 0) {
  260. ++count;
  261. if (count > 1) return;
  262. }
  263. }
  264. for (k = 0; k < huffman_code->num_symbols; ++k) {
  265. huffman_code->code_lengths[k] = 0;
  266. huffman_code->codes[k] = 0;
  267. }
  268. }
  269. static void StoreHuffmanTreeToBitMask(
  270. VP8LBitWriter* const bw,
  271. const HuffmanTreeToken* const tokens, const int num_tokens,
  272. const HuffmanTreeCode* const huffman_code) {
  273. int i;
  274. for (i = 0; i < num_tokens; ++i) {
  275. const int ix = tokens[i].code;
  276. const int extra_bits = tokens[i].extra_bits;
  277. VP8LWriteBits(bw, huffman_code->code_lengths[ix], huffman_code->codes[ix]);
  278. switch (ix) {
  279. case 16:
  280. VP8LWriteBits(bw, 2, extra_bits);
  281. break;
  282. case 17:
  283. VP8LWriteBits(bw, 3, extra_bits);
  284. break;
  285. case 18:
  286. VP8LWriteBits(bw, 7, extra_bits);
  287. break;
  288. }
  289. }
  290. }
  291. // 'huff_tree' and 'tokens' are pre-alloacted buffers.
  292. static void StoreFullHuffmanCode(VP8LBitWriter* const bw,
  293. HuffmanTree* const huff_tree,
  294. HuffmanTreeToken* const tokens,
  295. const HuffmanTreeCode* const tree) {
  296. uint8_t code_length_bitdepth[CODE_LENGTH_CODES] = { 0 };
  297. uint16_t code_length_bitdepth_symbols[CODE_LENGTH_CODES] = { 0 };
  298. const int max_tokens = tree->num_symbols;
  299. int num_tokens;
  300. HuffmanTreeCode huffman_code;
  301. huffman_code.num_symbols = CODE_LENGTH_CODES;
  302. huffman_code.code_lengths = code_length_bitdepth;
  303. huffman_code.codes = code_length_bitdepth_symbols;
  304. VP8LWriteBits(bw, 1, 0);
  305. num_tokens = VP8LCreateCompressedHuffmanTree(tree, tokens, max_tokens);
  306. {
  307. uint32_t histogram[CODE_LENGTH_CODES] = { 0 };
  308. uint8_t buf_rle[CODE_LENGTH_CODES] = { 0 };
  309. int i;
  310. for (i = 0; i < num_tokens; ++i) {
  311. ++histogram[tokens[i].code];
  312. }
  313. VP8LCreateHuffmanTree(histogram, 7, buf_rle, huff_tree, &huffman_code);
  314. }
  315. StoreHuffmanTreeOfHuffmanTreeToBitMask(bw, code_length_bitdepth);
  316. ClearHuffmanTreeIfOnlyOneSymbol(&huffman_code);
  317. {
  318. int trailing_zero_bits = 0;
  319. int trimmed_length = num_tokens;
  320. int write_trimmed_length;
  321. int length;
  322. int i = num_tokens;
  323. while (i-- > 0) {
  324. const int ix = tokens[i].code;
  325. if (ix == 0 || ix == 17 || ix == 18) {
  326. --trimmed_length; // discount trailing zeros
  327. trailing_zero_bits += code_length_bitdepth[ix];
  328. if (ix == 17) {
  329. trailing_zero_bits += 3;
  330. } else if (ix == 18) {
  331. trailing_zero_bits += 7;
  332. }
  333. } else {
  334. break;
  335. }
  336. }
  337. write_trimmed_length = (trimmed_length > 1 && trailing_zero_bits > 12);
  338. length = write_trimmed_length ? trimmed_length : num_tokens;
  339. VP8LWriteBits(bw, 1, write_trimmed_length);
  340. if (write_trimmed_length) {
  341. const int nbits = VP8LBitsLog2Ceiling(trimmed_length - 1);
  342. const int nbitpairs = (nbits == 0) ? 1 : (nbits + 1) / 2;
  343. VP8LWriteBits(bw, 3, nbitpairs - 1);
  344. assert(trimmed_length >= 2);
  345. VP8LWriteBits(bw, nbitpairs * 2, trimmed_length - 2);
  346. }
  347. StoreHuffmanTreeToBitMask(bw, tokens, length, &huffman_code);
  348. }
  349. }
  350. // 'huff_tree' and 'tokens' are pre-alloacted buffers.
  351. static void StoreHuffmanCode(VP8LBitWriter* const bw,
  352. HuffmanTree* const huff_tree,
  353. HuffmanTreeToken* const tokens,
  354. const HuffmanTreeCode* const huffman_code) {
  355. int i;
  356. int count = 0;
  357. int symbols[2] = { 0, 0 };
  358. const int kMaxBits = 8;
  359. const int kMaxSymbol = 1 << kMaxBits;
  360. // Check whether it's a small tree.
  361. for (i = 0; i < huffman_code->num_symbols && count < 3; ++i) {
  362. if (huffman_code->code_lengths[i] != 0) {
  363. if (count < 2) symbols[count] = i;
  364. ++count;
  365. }
  366. }
  367. if (count == 0) { // emit minimal tree for empty cases
  368. // bits: small tree marker: 1, count-1: 0, large 8-bit code: 0, code: 0
  369. VP8LWriteBits(bw, 4, 0x01);
  370. } else if (count <= 2 && symbols[0] < kMaxSymbol && symbols[1] < kMaxSymbol) {
  371. VP8LWriteBits(bw, 1, 1); // Small tree marker to encode 1 or 2 symbols.
  372. VP8LWriteBits(bw, 1, count - 1);
  373. if (symbols[0] <= 1) {
  374. VP8LWriteBits(bw, 1, 0); // Code bit for small (1 bit) symbol value.
  375. VP8LWriteBits(bw, 1, symbols[0]);
  376. } else {
  377. VP8LWriteBits(bw, 1, 1);
  378. VP8LWriteBits(bw, 8, symbols[0]);
  379. }
  380. if (count == 2) {
  381. VP8LWriteBits(bw, 8, symbols[1]);
  382. }
  383. } else {
  384. StoreFullHuffmanCode(bw, huff_tree, tokens, huffman_code);
  385. }
  386. }
  387. static void WriteHuffmanCode(VP8LBitWriter* const bw,
  388. const HuffmanTreeCode* const code,
  389. int code_index) {
  390. const int depth = code->code_lengths[code_index];
  391. const int symbol = code->codes[code_index];
  392. VP8LWriteBits(bw, depth, symbol);
  393. }
  394. static WebPEncodingError StoreImageToBitMask(
  395. VP8LBitWriter* const bw, int width, int histo_bits,
  396. VP8LBackwardRefs* const refs,
  397. const uint16_t* histogram_symbols,
  398. const HuffmanTreeCode* const huffman_codes) {
  399. // x and y trace the position in the image.
  400. int x = 0;
  401. int y = 0;
  402. const int histo_xsize = histo_bits ? VP8LSubSampleSize(width, histo_bits) : 1;
  403. VP8LRefsCursor c = VP8LRefsCursorInit(refs);
  404. while (VP8LRefsCursorOk(&c)) {
  405. const PixOrCopy* const v = c.cur_pos;
  406. const int histogram_ix = histogram_symbols[histo_bits ?
  407. (y >> histo_bits) * histo_xsize +
  408. (x >> histo_bits) : 0];
  409. const HuffmanTreeCode* const codes = huffman_codes + 5 * histogram_ix;
  410. if (PixOrCopyIsCacheIdx(v)) {
  411. const int code = PixOrCopyCacheIdx(v);
  412. const int literal_ix = 256 + NUM_LENGTH_CODES + code;
  413. WriteHuffmanCode(bw, codes, literal_ix);
  414. } else if (PixOrCopyIsLiteral(v)) {
  415. static const int order[] = { 1, 2, 0, 3 };
  416. int k;
  417. for (k = 0; k < 4; ++k) {
  418. const int code = PixOrCopyLiteral(v, order[k]);
  419. WriteHuffmanCode(bw, codes + k, code);
  420. }
  421. } else {
  422. int bits, n_bits;
  423. int code, distance;
  424. VP8LPrefixEncode(v->len, &code, &n_bits, &bits);
  425. WriteHuffmanCode(bw, codes, 256 + code);
  426. VP8LWriteBits(bw, n_bits, bits);
  427. distance = PixOrCopyDistance(v);
  428. VP8LPrefixEncode(distance, &code, &n_bits, &bits);
  429. WriteHuffmanCode(bw, codes + 4, code);
  430. VP8LWriteBits(bw, n_bits, bits);
  431. }
  432. x += PixOrCopyLength(v);
  433. while (x >= width) {
  434. x -= width;
  435. ++y;
  436. }
  437. VP8LRefsCursorNext(&c);
  438. }
  439. return bw->error_ ? VP8_ENC_ERROR_OUT_OF_MEMORY : VP8_ENC_OK;
  440. }
  441. // Special case of EncodeImageInternal() for cache-bits=0, histo_bits=31
  442. static WebPEncodingError EncodeImageNoHuffman(VP8LBitWriter* const bw,
  443. const uint32_t* const argb,
  444. VP8LHashChain* const hash_chain,
  445. VP8LBackwardRefs refs_array[2],
  446. int width, int height,
  447. int quality) {
  448. int i;
  449. int max_tokens = 0;
  450. WebPEncodingError err = VP8_ENC_OK;
  451. VP8LBackwardRefs* refs;
  452. HuffmanTreeToken* tokens = NULL;
  453. HuffmanTreeCode huffman_codes[5] = { { 0, NULL, NULL } };
  454. const uint16_t histogram_symbols[1] = { 0 }; // only one tree, one symbol
  455. VP8LHistogramSet* const histogram_image = VP8LAllocateHistogramSet(1, 0);
  456. HuffmanTree* const huff_tree = (HuffmanTree*)WebPSafeMalloc(
  457. 3ULL * CODE_LENGTH_CODES, sizeof(*huff_tree));
  458. if (histogram_image == NULL || huff_tree == NULL) {
  459. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  460. goto Error;
  461. }
  462. // Calculate backward references from ARGB image.
  463. refs = VP8LGetBackwardReferences(width, height, argb, quality, 0, 1,
  464. hash_chain, refs_array);
  465. if (refs == NULL) {
  466. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  467. goto Error;
  468. }
  469. // Build histogram image and symbols from backward references.
  470. VP8LHistogramStoreRefs(refs, histogram_image->histograms[0]);
  471. // Create Huffman bit lengths and codes for each histogram image.
  472. assert(histogram_image->size == 1);
  473. if (!GetHuffBitLengthsAndCodes(histogram_image, huffman_codes)) {
  474. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  475. goto Error;
  476. }
  477. // No color cache, no Huffman image.
  478. VP8LWriteBits(bw, 1, 0);
  479. // Find maximum number of symbols for the huffman tree-set.
  480. for (i = 0; i < 5; ++i) {
  481. HuffmanTreeCode* const codes = &huffman_codes[i];
  482. if (max_tokens < codes->num_symbols) {
  483. max_tokens = codes->num_symbols;
  484. }
  485. }
  486. tokens = (HuffmanTreeToken*)WebPSafeMalloc(max_tokens, sizeof(*tokens));
  487. if (tokens == NULL) {
  488. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  489. goto Error;
  490. }
  491. // Store Huffman codes.
  492. for (i = 0; i < 5; ++i) {
  493. HuffmanTreeCode* const codes = &huffman_codes[i];
  494. StoreHuffmanCode(bw, huff_tree, tokens, codes);
  495. ClearHuffmanTreeIfOnlyOneSymbol(codes);
  496. }
  497. // Store actual literals.
  498. err = StoreImageToBitMask(bw, width, 0, refs, histogram_symbols,
  499. huffman_codes);
  500. Error:
  501. WebPSafeFree(tokens);
  502. WebPSafeFree(huff_tree);
  503. VP8LFreeHistogramSet(histogram_image);
  504. WebPSafeFree(huffman_codes[0].codes);
  505. return err;
  506. }
  507. static WebPEncodingError EncodeImageInternal(VP8LBitWriter* const bw,
  508. const uint32_t* const argb,
  509. VP8LHashChain* const hash_chain,
  510. VP8LBackwardRefs refs_array[2],
  511. int width, int height, int quality,
  512. int cache_bits,
  513. int histogram_bits) {
  514. WebPEncodingError err = VP8_ENC_OK;
  515. const int use_2d_locality = 1;
  516. const int use_color_cache = (cache_bits > 0);
  517. const uint32_t histogram_image_xysize =
  518. VP8LSubSampleSize(width, histogram_bits) *
  519. VP8LSubSampleSize(height, histogram_bits);
  520. VP8LHistogramSet* histogram_image =
  521. VP8LAllocateHistogramSet(histogram_image_xysize, cache_bits);
  522. int histogram_image_size = 0;
  523. size_t bit_array_size = 0;
  524. HuffmanTree* huff_tree = NULL;
  525. HuffmanTreeToken* tokens = NULL;
  526. HuffmanTreeCode* huffman_codes = NULL;
  527. VP8LBackwardRefs refs;
  528. VP8LBackwardRefs* best_refs;
  529. uint16_t* const histogram_symbols =
  530. (uint16_t*)WebPSafeMalloc(histogram_image_xysize,
  531. sizeof(*histogram_symbols));
  532. assert(histogram_bits >= MIN_HUFFMAN_BITS);
  533. assert(histogram_bits <= MAX_HUFFMAN_BITS);
  534. VP8LBackwardRefsInit(&refs, refs_array[0].block_size_);
  535. if (histogram_image == NULL || histogram_symbols == NULL) {
  536. VP8LFreeHistogramSet(histogram_image);
  537. WebPSafeFree(histogram_symbols);
  538. return 0;
  539. }
  540. // 'best_refs' is the reference to the best backward refs and points to one
  541. // of refs_array[0] or refs_array[1].
  542. // Calculate backward references from ARGB image.
  543. best_refs = VP8LGetBackwardReferences(width, height, argb, quality,
  544. cache_bits, use_2d_locality,
  545. hash_chain, refs_array);
  546. if (best_refs == NULL || !VP8LBackwardRefsCopy(best_refs, &refs)) {
  547. goto Error;
  548. }
  549. // Build histogram image and symbols from backward references.
  550. if (!VP8LGetHistoImageSymbols(width, height, &refs,
  551. quality, histogram_bits, cache_bits,
  552. histogram_image,
  553. histogram_symbols)) {
  554. goto Error;
  555. }
  556. // Create Huffman bit lengths and codes for each histogram image.
  557. histogram_image_size = histogram_image->size;
  558. bit_array_size = 5 * histogram_image_size;
  559. huffman_codes = (HuffmanTreeCode*)WebPSafeCalloc(bit_array_size,
  560. sizeof(*huffman_codes));
  561. if (huffman_codes == NULL ||
  562. !GetHuffBitLengthsAndCodes(histogram_image, huffman_codes)) {
  563. goto Error;
  564. }
  565. // Free combined histograms.
  566. VP8LFreeHistogramSet(histogram_image);
  567. histogram_image = NULL;
  568. // Color Cache parameters.
  569. VP8LWriteBits(bw, 1, use_color_cache);
  570. if (use_color_cache) {
  571. VP8LWriteBits(bw, 4, cache_bits);
  572. }
  573. // Huffman image + meta huffman.
  574. {
  575. const int write_histogram_image = (histogram_image_size > 1);
  576. VP8LWriteBits(bw, 1, write_histogram_image);
  577. if (write_histogram_image) {
  578. uint32_t* const histogram_argb =
  579. (uint32_t*)WebPSafeMalloc(histogram_image_xysize,
  580. sizeof(*histogram_argb));
  581. int max_index = 0;
  582. uint32_t i;
  583. if (histogram_argb == NULL) goto Error;
  584. for (i = 0; i < histogram_image_xysize; ++i) {
  585. const int symbol_index = histogram_symbols[i] & 0xffff;
  586. histogram_argb[i] = 0xff000000 | (symbol_index << 8);
  587. if (symbol_index >= max_index) {
  588. max_index = symbol_index + 1;
  589. }
  590. }
  591. histogram_image_size = max_index;
  592. VP8LWriteBits(bw, 3, histogram_bits - 2);
  593. err = EncodeImageNoHuffman(bw, histogram_argb, hash_chain, refs_array,
  594. VP8LSubSampleSize(width, histogram_bits),
  595. VP8LSubSampleSize(height, histogram_bits),
  596. quality);
  597. WebPSafeFree(histogram_argb);
  598. if (err != VP8_ENC_OK) goto Error;
  599. }
  600. }
  601. // Store Huffman codes.
  602. {
  603. int i;
  604. int max_tokens = 0;
  605. huff_tree = (HuffmanTree*)WebPSafeMalloc(3ULL * CODE_LENGTH_CODES,
  606. sizeof(*huff_tree));
  607. if (huff_tree == NULL) goto Error;
  608. // Find maximum number of symbols for the huffman tree-set.
  609. for (i = 0; i < 5 * histogram_image_size; ++i) {
  610. HuffmanTreeCode* const codes = &huffman_codes[i];
  611. if (max_tokens < codes->num_symbols) {
  612. max_tokens = codes->num_symbols;
  613. }
  614. }
  615. tokens = (HuffmanTreeToken*)WebPSafeMalloc(max_tokens,
  616. sizeof(*tokens));
  617. if (tokens == NULL) goto Error;
  618. for (i = 0; i < 5 * histogram_image_size; ++i) {
  619. HuffmanTreeCode* const codes = &huffman_codes[i];
  620. StoreHuffmanCode(bw, huff_tree, tokens, codes);
  621. ClearHuffmanTreeIfOnlyOneSymbol(codes);
  622. }
  623. }
  624. // Store actual literals.
  625. err = StoreImageToBitMask(bw, width, histogram_bits, &refs,
  626. histogram_symbols, huffman_codes);
  627. Error:
  628. WebPSafeFree(tokens);
  629. WebPSafeFree(huff_tree);
  630. VP8LFreeHistogramSet(histogram_image);
  631. VP8LBackwardRefsClear(&refs);
  632. if (huffman_codes != NULL) {
  633. WebPSafeFree(huffman_codes->codes);
  634. WebPSafeFree(huffman_codes);
  635. }
  636. WebPSafeFree(histogram_symbols);
  637. return err;
  638. }
  639. // -----------------------------------------------------------------------------
  640. // Transforms
  641. // Check if it would be a good idea to subtract green from red and blue. We
  642. // only impact entropy in red/blue components, don't bother to look at others.
  643. static WebPEncodingError EvalAndApplySubtractGreen(VP8LEncoder* const enc,
  644. int width, int height,
  645. VP8LBitWriter* const bw) {
  646. if (!enc->use_palette_) {
  647. int i;
  648. const uint32_t* const argb = enc->argb_;
  649. double bit_cost_before, bit_cost_after;
  650. // Allocate histogram with cache_bits = 1.
  651. VP8LHistogram* const histo = VP8LAllocateHistogram(1);
  652. if (histo == NULL) return VP8_ENC_ERROR_OUT_OF_MEMORY;
  653. for (i = 0; i < width * height; ++i) {
  654. const uint32_t c = argb[i];
  655. ++histo->red_[(c >> 16) & 0xff];
  656. ++histo->blue_[(c >> 0) & 0xff];
  657. }
  658. bit_cost_before = VP8LHistogramEstimateBits(histo);
  659. VP8LHistogramInit(histo, 1);
  660. for (i = 0; i < width * height; ++i) {
  661. const uint32_t c = argb[i];
  662. const int green = (c >> 8) & 0xff;
  663. ++histo->red_[((c >> 16) - green) & 0xff];
  664. ++histo->blue_[((c >> 0) - green) & 0xff];
  665. }
  666. bit_cost_after = VP8LHistogramEstimateBits(histo);
  667. VP8LFreeHistogram(histo);
  668. // Check if subtracting green yields low entropy.
  669. enc->use_subtract_green_ = (bit_cost_after < bit_cost_before);
  670. if (enc->use_subtract_green_) {
  671. VP8LWriteBits(bw, 1, TRANSFORM_PRESENT);
  672. VP8LWriteBits(bw, 2, SUBTRACT_GREEN);
  673. VP8LSubtractGreenFromBlueAndRed(enc->argb_, width * height);
  674. }
  675. }
  676. return VP8_ENC_OK;
  677. }
  678. static WebPEncodingError ApplyPredictFilter(const VP8LEncoder* const enc,
  679. int width, int height, int quality,
  680. VP8LBitWriter* const bw) {
  681. const int pred_bits = enc->transform_bits_;
  682. const int transform_width = VP8LSubSampleSize(width, pred_bits);
  683. const int transform_height = VP8LSubSampleSize(height, pred_bits);
  684. VP8LResidualImage(width, height, pred_bits, enc->argb_, enc->argb_scratch_,
  685. enc->transform_data_);
  686. VP8LWriteBits(bw, 1, TRANSFORM_PRESENT);
  687. VP8LWriteBits(bw, 2, PREDICTOR_TRANSFORM);
  688. assert(pred_bits >= 2);
  689. VP8LWriteBits(bw, 3, pred_bits - 2);
  690. return EncodeImageNoHuffman(bw, enc->transform_data_,
  691. (VP8LHashChain*)&enc->hash_chain_,
  692. (VP8LBackwardRefs*)enc->refs_, // cast const away
  693. transform_width, transform_height,
  694. quality);
  695. }
  696. static WebPEncodingError ApplyCrossColorFilter(const VP8LEncoder* const enc,
  697. int width, int height,
  698. int quality,
  699. VP8LBitWriter* const bw) {
  700. const int ccolor_transform_bits = enc->transform_bits_;
  701. const int transform_width = VP8LSubSampleSize(width, ccolor_transform_bits);
  702. const int transform_height = VP8LSubSampleSize(height, ccolor_transform_bits);
  703. VP8LColorSpaceTransform(width, height, ccolor_transform_bits, quality,
  704. enc->argb_, enc->transform_data_);
  705. VP8LWriteBits(bw, 1, TRANSFORM_PRESENT);
  706. VP8LWriteBits(bw, 2, CROSS_COLOR_TRANSFORM);
  707. assert(ccolor_transform_bits >= 2);
  708. VP8LWriteBits(bw, 3, ccolor_transform_bits - 2);
  709. return EncodeImageNoHuffman(bw, enc->transform_data_,
  710. (VP8LHashChain*)&enc->hash_chain_,
  711. (VP8LBackwardRefs*)enc->refs_, // cast const away
  712. transform_width, transform_height,
  713. quality);
  714. }
  715. // -----------------------------------------------------------------------------
  716. static WebPEncodingError WriteRiffHeader(const WebPPicture* const pic,
  717. size_t riff_size, size_t vp8l_size) {
  718. uint8_t riff[RIFF_HEADER_SIZE + CHUNK_HEADER_SIZE + VP8L_SIGNATURE_SIZE] = {
  719. 'R', 'I', 'F', 'F', 0, 0, 0, 0, 'W', 'E', 'B', 'P',
  720. 'V', 'P', '8', 'L', 0, 0, 0, 0, VP8L_MAGIC_BYTE,
  721. };
  722. PutLE32(riff + TAG_SIZE, (uint32_t)riff_size);
  723. PutLE32(riff + RIFF_HEADER_SIZE + TAG_SIZE, (uint32_t)vp8l_size);
  724. if (!pic->writer(riff, sizeof(riff), pic)) {
  725. return VP8_ENC_ERROR_BAD_WRITE;
  726. }
  727. return VP8_ENC_OK;
  728. }
  729. static int WriteImageSize(const WebPPicture* const pic,
  730. VP8LBitWriter* const bw) {
  731. const int width = pic->width - 1;
  732. const int height = pic->height - 1;
  733. assert(width < WEBP_MAX_DIMENSION && height < WEBP_MAX_DIMENSION);
  734. VP8LWriteBits(bw, VP8L_IMAGE_SIZE_BITS, width);
  735. VP8LWriteBits(bw, VP8L_IMAGE_SIZE_BITS, height);
  736. return !bw->error_;
  737. }
  738. static int WriteRealAlphaAndVersion(VP8LBitWriter* const bw, int has_alpha) {
  739. VP8LWriteBits(bw, 1, has_alpha);
  740. VP8LWriteBits(bw, VP8L_VERSION_BITS, VP8L_VERSION);
  741. return !bw->error_;
  742. }
  743. static WebPEncodingError WriteImage(const WebPPicture* const pic,
  744. VP8LBitWriter* const bw,
  745. size_t* const coded_size) {
  746. WebPEncodingError err = VP8_ENC_OK;
  747. const uint8_t* const webpll_data = VP8LBitWriterFinish(bw);
  748. const size_t webpll_size = VP8LBitWriterNumBytes(bw);
  749. const size_t vp8l_size = VP8L_SIGNATURE_SIZE + webpll_size;
  750. const size_t pad = vp8l_size & 1;
  751. const size_t riff_size = TAG_SIZE + CHUNK_HEADER_SIZE + vp8l_size + pad;
  752. err = WriteRiffHeader(pic, riff_size, vp8l_size);
  753. if (err != VP8_ENC_OK) goto Error;
  754. if (!pic->writer(webpll_data, webpll_size, pic)) {
  755. err = VP8_ENC_ERROR_BAD_WRITE;
  756. goto Error;
  757. }
  758. if (pad) {
  759. const uint8_t pad_byte[1] = { 0 };
  760. if (!pic->writer(pad_byte, 1, pic)) {
  761. err = VP8_ENC_ERROR_BAD_WRITE;
  762. goto Error;
  763. }
  764. }
  765. *coded_size = CHUNK_HEADER_SIZE + riff_size;
  766. return VP8_ENC_OK;
  767. Error:
  768. return err;
  769. }
  770. // -----------------------------------------------------------------------------
  771. // Allocates the memory for argb (W x H) buffer, 2 rows of context for
  772. // prediction and transform data.
  773. static WebPEncodingError AllocateTransformBuffer(VP8LEncoder* const enc,
  774. int width, int height) {
  775. WebPEncodingError err = VP8_ENC_OK;
  776. const int tile_size = 1 << enc->transform_bits_;
  777. const uint64_t image_size = width * height;
  778. const uint64_t argb_scratch_size = tile_size * width + width;
  779. const int transform_data_size =
  780. VP8LSubSampleSize(width, enc->transform_bits_) *
  781. VP8LSubSampleSize(height, enc->transform_bits_);
  782. const uint64_t total_size =
  783. image_size + argb_scratch_size + (uint64_t)transform_data_size;
  784. uint32_t* mem = (uint32_t*)WebPSafeMalloc(total_size, sizeof(*mem));
  785. if (mem == NULL) {
  786. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  787. goto Error;
  788. }
  789. enc->argb_ = mem;
  790. mem += image_size;
  791. enc->argb_scratch_ = mem;
  792. mem += argb_scratch_size;
  793. enc->transform_data_ = mem;
  794. enc->current_width_ = width;
  795. Error:
  796. return err;
  797. }
  798. static void ApplyPalette(uint32_t* src, uint32_t* dst,
  799. uint32_t src_stride, uint32_t dst_stride,
  800. const uint32_t* palette, int palette_size,
  801. int width, int height, int xbits, uint8_t* row) {
  802. int i, x, y;
  803. int use_LUT = 1;
  804. for (i = 0; i < palette_size; ++i) {
  805. if ((palette[i] & 0xffff00ffu) != 0) {
  806. use_LUT = 0;
  807. break;
  808. }
  809. }
  810. if (use_LUT) {
  811. uint8_t inv_palette[MAX_PALETTE_SIZE] = { 0 };
  812. for (i = 0; i < palette_size; ++i) {
  813. const int color = (palette[i] >> 8) & 0xff;
  814. inv_palette[color] = i;
  815. }
  816. for (y = 0; y < height; ++y) {
  817. for (x = 0; x < width; ++x) {
  818. const int color = (src[x] >> 8) & 0xff;
  819. row[x] = inv_palette[color];
  820. }
  821. VP8LBundleColorMap(row, width, xbits, dst);
  822. src += src_stride;
  823. dst += dst_stride;
  824. }
  825. } else {
  826. // Use 1 pixel cache for ARGB pixels.
  827. uint32_t last_pix = palette[0];
  828. int last_idx = 0;
  829. for (y = 0; y < height; ++y) {
  830. for (x = 0; x < width; ++x) {
  831. const uint32_t pix = src[x];
  832. if (pix != last_pix) {
  833. for (i = 0; i < palette_size; ++i) {
  834. if (pix == palette[i]) {
  835. last_idx = i;
  836. last_pix = pix;
  837. break;
  838. }
  839. }
  840. }
  841. row[x] = last_idx;
  842. }
  843. VP8LBundleColorMap(row, width, xbits, dst);
  844. src += src_stride;
  845. dst += dst_stride;
  846. }
  847. }
  848. }
  849. // Note: Expects "enc->palette_" to be set properly.
  850. // Also, "enc->palette_" will be modified after this call and should not be used
  851. // later.
  852. static WebPEncodingError EncodePalette(VP8LBitWriter* const bw,
  853. VP8LEncoder* const enc, int quality) {
  854. WebPEncodingError err = VP8_ENC_OK;
  855. int i;
  856. const WebPPicture* const pic = enc->pic_;
  857. uint32_t* src = pic->argb;
  858. uint32_t* dst;
  859. const int width = pic->width;
  860. const int height = pic->height;
  861. uint32_t* const palette = enc->palette_;
  862. const int palette_size = enc->palette_size_;
  863. uint8_t* row = NULL;
  864. int xbits;
  865. // Replace each input pixel by corresponding palette index.
  866. // This is done line by line.
  867. if (palette_size <= 4) {
  868. xbits = (palette_size <= 2) ? 3 : 2;
  869. } else {
  870. xbits = (palette_size <= 16) ? 1 : 0;
  871. }
  872. err = AllocateTransformBuffer(enc, VP8LSubSampleSize(width, xbits), height);
  873. if (err != VP8_ENC_OK) goto Error;
  874. dst = enc->argb_;
  875. row = (uint8_t*)WebPSafeMalloc(width, sizeof(*row));
  876. if (row == NULL) return VP8_ENC_ERROR_OUT_OF_MEMORY;
  877. ApplyPalette(src, dst, pic->argb_stride, enc->current_width_,
  878. palette, palette_size, width, height, xbits, row);
  879. // Save palette to bitstream.
  880. VP8LWriteBits(bw, 1, TRANSFORM_PRESENT);
  881. VP8LWriteBits(bw, 2, COLOR_INDEXING_TRANSFORM);
  882. assert(palette_size >= 1);
  883. VP8LWriteBits(bw, 8, palette_size - 1);
  884. for (i = palette_size - 1; i >= 1; --i) {
  885. palette[i] = VP8LSubPixels(palette[i], palette[i - 1]);
  886. }
  887. err = EncodeImageNoHuffman(bw, palette, &enc->hash_chain_, enc->refs_,
  888. palette_size, 1, quality);
  889. Error:
  890. WebPSafeFree(row);
  891. return err;
  892. }
  893. // -----------------------------------------------------------------------------
  894. static int GetHistoBits(int method, int use_palette, int width, int height) {
  895. const int hist_size = VP8LGetHistogramSize(MAX_COLOR_CACHE_BITS);
  896. // Make tile size a function of encoding method (Range: 0 to 6).
  897. int histo_bits = (use_palette ? 9 : 7) - method;
  898. while (1) {
  899. const int huff_image_size = VP8LSubSampleSize(width, histo_bits) *
  900. VP8LSubSampleSize(height, histo_bits);
  901. if ((uint64_t)huff_image_size * hist_size <= MAX_HUFF_IMAGE_SIZE) break;
  902. ++histo_bits;
  903. }
  904. return (histo_bits < MIN_HUFFMAN_BITS) ? MIN_HUFFMAN_BITS :
  905. (histo_bits > MAX_HUFFMAN_BITS) ? MAX_HUFFMAN_BITS : histo_bits;
  906. }
  907. static int GetTransformBits(int method, int histo_bits) {
  908. const int max_transform_bits = (method < 4) ? 6 : (method > 4) ? 4 : 5;
  909. return (histo_bits > max_transform_bits) ? max_transform_bits : histo_bits;
  910. }
  911. static int GetCacheBits(float quality) {
  912. return (quality <= 25.f) ? 0 : 7;
  913. }
  914. static void FinishEncParams(VP8LEncoder* const enc) {
  915. const WebPConfig* const config = enc->config_;
  916. const WebPPicture* const pic = enc->pic_;
  917. const int method = config->method;
  918. const float quality = config->quality;
  919. const int use_palette = enc->use_palette_;
  920. enc->histo_bits_ = GetHistoBits(method, use_palette, pic->width, pic->height);
  921. enc->transform_bits_ = GetTransformBits(method, enc->histo_bits_);
  922. enc->cache_bits_ = GetCacheBits(quality);
  923. }
  924. // -----------------------------------------------------------------------------
  925. // VP8LEncoder
  926. static VP8LEncoder* VP8LEncoderNew(const WebPConfig* const config,
  927. const WebPPicture* const picture) {
  928. VP8LEncoder* const enc = (VP8LEncoder*)WebPSafeCalloc(1ULL, sizeof(*enc));
  929. if (enc == NULL) {
  930. WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
  931. return NULL;
  932. }
  933. enc->config_ = config;
  934. enc->pic_ = picture;
  935. VP8LDspInit();
  936. return enc;
  937. }
  938. static void VP8LEncoderDelete(VP8LEncoder* enc) {
  939. if (enc != NULL) {
  940. VP8LHashChainClear(&enc->hash_chain_);
  941. VP8LBackwardRefsClear(&enc->refs_[0]);
  942. VP8LBackwardRefsClear(&enc->refs_[1]);
  943. WebPSafeFree(enc->argb_);
  944. WebPSafeFree(enc);
  945. }
  946. }
  947. // -----------------------------------------------------------------------------
  948. // Main call
  949. WebPEncodingError VP8LEncodeStream(const WebPConfig* const config,
  950. const WebPPicture* const picture,
  951. VP8LBitWriter* const bw) {
  952. WebPEncodingError err = VP8_ENC_OK;
  953. const int quality = (int)config->quality;
  954. const int width = picture->width;
  955. const int height = picture->height;
  956. VP8LEncoder* const enc = VP8LEncoderNew(config, picture);
  957. const size_t byte_position = VP8LBitWriterNumBytes(bw);
  958. if (enc == NULL) {
  959. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  960. goto Error;
  961. }
  962. // ---------------------------------------------------------------------------
  963. // Analyze image (entropy, num_palettes etc)
  964. if (!AnalyzeAndInit(enc, config->image_hint)) {
  965. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  966. goto Error;
  967. }
  968. FinishEncParams(enc);
  969. if (enc->use_palette_) {
  970. err = EncodePalette(bw, enc, quality);
  971. if (err != VP8_ENC_OK) goto Error;
  972. // Color cache is disabled for palette.
  973. enc->cache_bits_ = 0;
  974. }
  975. // In case image is not packed.
  976. if (enc->argb_ == NULL) {
  977. int y;
  978. err = AllocateTransformBuffer(enc, width, height);
  979. if (err != VP8_ENC_OK) goto Error;
  980. for (y = 0; y < height; ++y) {
  981. memcpy(enc->argb_ + y * width,
  982. picture->argb + y * picture->argb_stride,
  983. width * sizeof(*enc->argb_));
  984. }
  985. enc->current_width_ = width;
  986. }
  987. // ---------------------------------------------------------------------------
  988. // Apply transforms and write transform data.
  989. err = EvalAndApplySubtractGreen(enc, enc->current_width_, height, bw);
  990. if (err != VP8_ENC_OK) goto Error;
  991. if (enc->use_predict_) {
  992. err = ApplyPredictFilter(enc, enc->current_width_, height, quality, bw);
  993. if (err != VP8_ENC_OK) goto Error;
  994. }
  995. if (enc->use_cross_color_) {
  996. err = ApplyCrossColorFilter(enc, enc->current_width_, height, quality, bw);
  997. if (err != VP8_ENC_OK) goto Error;
  998. }
  999. VP8LWriteBits(bw, 1, !TRANSFORM_PRESENT); // No more transforms.
  1000. // ---------------------------------------------------------------------------
  1001. // Estimate the color cache size.
  1002. if (enc->cache_bits_ > 0) {
  1003. if (!VP8LCalculateEstimateForCacheSize(enc->argb_, enc->current_width_,
  1004. height, quality, &enc->hash_chain_,
  1005. &enc->refs_[0], &enc->cache_bits_)) {
  1006. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  1007. goto Error;
  1008. }
  1009. }
  1010. // ---------------------------------------------------------------------------
  1011. // Encode and write the transformed image.
  1012. err = EncodeImageInternal(bw, enc->argb_, &enc->hash_chain_, enc->refs_,
  1013. enc->current_width_, height, quality,
  1014. enc->cache_bits_, enc->histo_bits_);
  1015. if (err != VP8_ENC_OK) goto Error;
  1016. if (picture->stats != NULL) {
  1017. WebPAuxStats* const stats = picture->stats;
  1018. stats->lossless_features = 0;
  1019. if (enc->use_predict_) stats->lossless_features |= 1;
  1020. if (enc->use_cross_color_) stats->lossless_features |= 2;
  1021. if (enc->use_subtract_green_) stats->lossless_features |= 4;
  1022. if (enc->use_palette_) stats->lossless_features |= 8;
  1023. stats->histogram_bits = enc->histo_bits_;
  1024. stats->transform_bits = enc->transform_bits_;
  1025. stats->cache_bits = enc->cache_bits_;
  1026. stats->palette_size = enc->palette_size_;
  1027. stats->lossless_size = (int)(VP8LBitWriterNumBytes(bw) - byte_position);
  1028. }
  1029. Error:
  1030. VP8LEncoderDelete(enc);
  1031. return err;
  1032. }
  1033. int VP8LEncodeImage(const WebPConfig* const config,
  1034. const WebPPicture* const picture) {
  1035. int width, height;
  1036. int has_alpha;
  1037. size_t coded_size;
  1038. int percent = 0;
  1039. int initial_size;
  1040. WebPEncodingError err = VP8_ENC_OK;
  1041. VP8LBitWriter bw;
  1042. if (picture == NULL) return 0;
  1043. if (config == NULL || picture->argb == NULL) {
  1044. err = VP8_ENC_ERROR_NULL_PARAMETER;
  1045. WebPEncodingSetError(picture, err);
  1046. return 0;
  1047. }
  1048. width = picture->width;
  1049. height = picture->height;
  1050. // Initialize BitWriter with size corresponding to 16 bpp to photo images and
  1051. // 8 bpp for graphical images.
  1052. initial_size = (config->image_hint == WEBP_HINT_GRAPH) ?
  1053. width * height : width * height * 2;
  1054. if (!VP8LBitWriterInit(&bw, initial_size)) {
  1055. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  1056. goto Error;
  1057. }
  1058. if (!WebPReportProgress(picture, 1, &percent)) {
  1059. UserAbort:
  1060. err = VP8_ENC_ERROR_USER_ABORT;
  1061. goto Error;
  1062. }
  1063. // Reset stats (for pure lossless coding)
  1064. if (picture->stats != NULL) {
  1065. WebPAuxStats* const stats = picture->stats;
  1066. memset(stats, 0, sizeof(*stats));
  1067. stats->PSNR[0] = 99.f;
  1068. stats->PSNR[1] = 99.f;
  1069. stats->PSNR[2] = 99.f;
  1070. stats->PSNR[3] = 99.f;
  1071. stats->PSNR[4] = 99.f;
  1072. }
  1073. // Write image size.
  1074. if (!WriteImageSize(picture, &bw)) {
  1075. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  1076. goto Error;
  1077. }
  1078. has_alpha = WebPPictureHasTransparency(picture);
  1079. // Write the non-trivial Alpha flag and lossless version.
  1080. if (!WriteRealAlphaAndVersion(&bw, has_alpha)) {
  1081. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  1082. goto Error;
  1083. }
  1084. if (!WebPReportProgress(picture, 5, &percent)) goto UserAbort;
  1085. // Encode main image stream.
  1086. err = VP8LEncodeStream(config, picture, &bw);
  1087. if (err != VP8_ENC_OK) goto Error;
  1088. // TODO(skal): have a fine-grained progress report in VP8LEncodeStream().
  1089. if (!WebPReportProgress(picture, 90, &percent)) goto UserAbort;
  1090. // Finish the RIFF chunk.
  1091. err = WriteImage(picture, &bw, &coded_size);
  1092. if (err != VP8_ENC_OK) goto Error;
  1093. if (!WebPReportProgress(picture, 100, &percent)) goto UserAbort;
  1094. // Save size.
  1095. if (picture->stats != NULL) {
  1096. picture->stats->coded_size += (int)coded_size;
  1097. picture->stats->lossless_size = (int)coded_size;
  1098. }
  1099. if (picture->extra_info != NULL) {
  1100. const int mb_w = (width + 15) >> 4;
  1101. const int mb_h = (height + 15) >> 4;
  1102. memset(picture->extra_info, 0, mb_w * mb_h * sizeof(*picture->extra_info));
  1103. }
  1104. Error:
  1105. if (bw.error_) err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  1106. VP8LBitWriterDestroy(&bw);
  1107. if (err != VP8_ENC_OK) {
  1108. WebPEncodingSetError(picture, err);
  1109. return 0;
  1110. }
  1111. return 1;
  1112. }
  1113. //------------------------------------------------------------------------------