vp8l_enc.c 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138
  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 <stdlib.h>
  16. #include "./backward_references_enc.h"
  17. #include "./histogram_enc.h"
  18. #include "./vp8i_enc.h"
  19. #include "./vp8li_enc.h"
  20. #include "../dsp/lossless.h"
  21. #include "../dsp/lossless_common.h"
  22. #include "../utils/bit_writer_utils.h"
  23. #include "../utils/huffman_encode_utils.h"
  24. #include "../utils/utils.h"
  25. #include "../webp/format_constants.h"
  26. // Maximum number of histogram images (sub-blocks).
  27. #define MAX_HUFF_IMAGE_SIZE 2600
  28. // Palette reordering for smaller sum of deltas (and for smaller storage).
  29. static int PaletteCompareColorsForQsort(const void* p1, const void* p2) {
  30. const uint32_t a = WebPMemToUint32((uint8_t*)p1);
  31. const uint32_t b = WebPMemToUint32((uint8_t*)p2);
  32. assert(a != b);
  33. return (a < b) ? -1 : 1;
  34. }
  35. static WEBP_INLINE uint32_t PaletteComponentDistance(uint32_t v) {
  36. return (v <= 128) ? v : (256 - v);
  37. }
  38. // Computes a value that is related to the entropy created by the
  39. // palette entry diff.
  40. //
  41. // Note that the last & 0xff is a no-operation in the next statement, but
  42. // removed by most compilers and is here only for regularity of the code.
  43. static WEBP_INLINE uint32_t PaletteColorDistance(uint32_t col1, uint32_t col2) {
  44. const uint32_t diff = VP8LSubPixels(col1, col2);
  45. const int kMoreWeightForRGBThanForAlpha = 9;
  46. uint32_t score;
  47. score = PaletteComponentDistance((diff >> 0) & 0xff);
  48. score += PaletteComponentDistance((diff >> 8) & 0xff);
  49. score += PaletteComponentDistance((diff >> 16) & 0xff);
  50. score *= kMoreWeightForRGBThanForAlpha;
  51. score += PaletteComponentDistance((diff >> 24) & 0xff);
  52. return score;
  53. }
  54. static WEBP_INLINE void SwapColor(uint32_t* const col1, uint32_t* const col2) {
  55. const uint32_t tmp = *col1;
  56. *col1 = *col2;
  57. *col2 = tmp;
  58. }
  59. static WEBP_INLINE int SearchColorNoIdx(const uint32_t sorted[], uint32_t color,
  60. int num_colors) {
  61. int low = 0, hi = num_colors;
  62. if (sorted[low] == color) return low; // loop invariant: sorted[low] != color
  63. while (1) {
  64. const int mid = (low + hi) >> 1;
  65. if (sorted[mid] == color) {
  66. return mid;
  67. } else if (sorted[mid] < color) {
  68. low = mid;
  69. } else {
  70. hi = mid;
  71. }
  72. }
  73. assert(0);
  74. return 0;
  75. }
  76. // The palette has been sorted by alpha. This function checks if the other
  77. // components of the palette have a monotonic development with regards to
  78. // position in the palette. If all have monotonic development, there is
  79. // no benefit to re-organize them greedily. A monotonic development
  80. // would be spotted in green-only situations (like lossy alpha) or gray-scale
  81. // images.
  82. static int PaletteHasNonMonotonousDeltas(const uint32_t* const palette,
  83. int num_colors) {
  84. uint32_t predict = 0x000000;
  85. int i;
  86. uint8_t sign_found = 0x00;
  87. for (i = 0; i < num_colors; ++i) {
  88. const uint32_t diff = VP8LSubPixels(palette[i], predict);
  89. const uint8_t rd = (diff >> 16) & 0xff;
  90. const uint8_t gd = (diff >> 8) & 0xff;
  91. const uint8_t bd = (diff >> 0) & 0xff;
  92. if (rd != 0x00) {
  93. sign_found |= (rd < 0x80) ? 1 : 2;
  94. }
  95. if (gd != 0x00) {
  96. sign_found |= (gd < 0x80) ? 8 : 16;
  97. }
  98. if (bd != 0x00) {
  99. sign_found |= (bd < 0x80) ? 64 : 128;
  100. }
  101. predict = palette[i];
  102. }
  103. return (sign_found & (sign_found << 1)) != 0; // two consequent signs.
  104. }
  105. static void PaletteSortMinimizeDeltas(const uint32_t* const palette_sorted,
  106. int num_colors, uint32_t* const palette) {
  107. uint32_t predict = 0x00000000;
  108. int i, k;
  109. memcpy(palette, palette_sorted, num_colors * sizeof(*palette));
  110. if (!PaletteHasNonMonotonousDeltas(palette_sorted, num_colors)) return;
  111. // Find greedily always the closest color of the predicted color to minimize
  112. // deltas in the palette. This reduces storage needs since the
  113. // palette is stored with delta encoding.
  114. for (i = 0; i < num_colors; ++i) {
  115. int best_ix = i;
  116. uint32_t best_score = ~0U;
  117. for (k = i; k < num_colors; ++k) {
  118. const uint32_t cur_score = PaletteColorDistance(palette[k], predict);
  119. if (best_score > cur_score) {
  120. best_score = cur_score;
  121. best_ix = k;
  122. }
  123. }
  124. SwapColor(&palette[best_ix], &palette[i]);
  125. predict = palette[i];
  126. }
  127. }
  128. // Sort palette in increasing order and prepare an inverse mapping array.
  129. static void PrepareMapToPalette(const uint32_t palette[], uint32_t num_colors,
  130. uint32_t sorted[], uint32_t idx_map[]) {
  131. uint32_t i;
  132. memcpy(sorted, palette, num_colors * sizeof(*sorted));
  133. qsort(sorted, num_colors, sizeof(*sorted), PaletteCompareColorsForQsort);
  134. for (i = 0; i < num_colors; ++i) {
  135. idx_map[SearchColorNoIdx(sorted, palette[i], num_colors)] = i;
  136. }
  137. }
  138. // -----------------------------------------------------------------------------
  139. // Modified Zeng method from "A Survey on Palette Reordering
  140. // Methods for Improving the Compression of Color-Indexed Images" by Armando J.
  141. // Pinho and Antonio J. R. Neves.
  142. // Finds the biggest cooccurrence in the matrix.
  143. static void CoOccurrenceFindMax(const uint32_t* const cooccurrence,
  144. uint32_t num_colors, uint8_t* const c1,
  145. uint8_t* const c2) {
  146. // Find the index that is most frequently located adjacent to other
  147. // (different) indexes.
  148. uint32_t best_sum = 0u;
  149. uint32_t i, j, best_cooccurrence;
  150. *c1 = 0u;
  151. for (i = 0; i < num_colors; ++i) {
  152. uint32_t sum = 0;
  153. for (j = 0; j < num_colors; ++j) sum += cooccurrence[i * num_colors + j];
  154. if (sum > best_sum) {
  155. best_sum = sum;
  156. *c1 = i;
  157. }
  158. }
  159. // Find the index that is most frequently found adjacent to *c1.
  160. *c2 = 0u;
  161. best_cooccurrence = 0u;
  162. for (i = 0; i < num_colors; ++i) {
  163. if (cooccurrence[*c1 * num_colors + i] > best_cooccurrence) {
  164. best_cooccurrence = cooccurrence[*c1 * num_colors + i];
  165. *c2 = i;
  166. }
  167. }
  168. assert(*c1 != *c2);
  169. }
  170. // Builds the cooccurrence matrix
  171. static WebPEncodingError CoOccurrenceBuild(const WebPPicture* const pic,
  172. const uint32_t* const palette,
  173. uint32_t num_colors,
  174. uint32_t* cooccurrence) {
  175. uint32_t *lines, *line_top, *line_current, *line_tmp;
  176. int x, y;
  177. const uint32_t* src = pic->argb;
  178. uint32_t prev_pix = ~src[0];
  179. uint32_t prev_idx = 0u;
  180. uint32_t idx_map[MAX_PALETTE_SIZE] = {0};
  181. uint32_t palette_sorted[MAX_PALETTE_SIZE];
  182. lines = (uint32_t*)WebPSafeMalloc(2 * pic->width, sizeof(*lines));
  183. if (lines == NULL) return VP8_ENC_ERROR_OUT_OF_MEMORY;
  184. line_top = &lines[0];
  185. line_current = &lines[pic->width];
  186. PrepareMapToPalette(palette, num_colors, palette_sorted, idx_map);
  187. for (y = 0; y < pic->height; ++y) {
  188. for (x = 0; x < pic->width; ++x) {
  189. const uint32_t pix = src[x];
  190. if (pix != prev_pix) {
  191. prev_idx = idx_map[SearchColorNoIdx(palette_sorted, pix, num_colors)];
  192. prev_pix = pix;
  193. }
  194. line_current[x] = prev_idx;
  195. // 4-connectivity is what works best as mentioned in "On the relation
  196. // between Memon's and the modified Zeng's palette reordering methods".
  197. if (x > 0 && prev_idx != line_current[x - 1]) {
  198. const uint32_t left_idx = line_current[x - 1];
  199. ++cooccurrence[prev_idx * num_colors + left_idx];
  200. ++cooccurrence[left_idx * num_colors + prev_idx];
  201. }
  202. if (y > 0 && prev_idx != line_top[x]) {
  203. const uint32_t top_idx = line_top[x];
  204. ++cooccurrence[prev_idx * num_colors + top_idx];
  205. ++cooccurrence[top_idx * num_colors + prev_idx];
  206. }
  207. }
  208. line_tmp = line_top;
  209. line_top = line_current;
  210. line_current = line_tmp;
  211. src += pic->argb_stride;
  212. }
  213. WebPSafeFree(lines);
  214. return VP8_ENC_OK;
  215. }
  216. struct Sum {
  217. uint8_t index;
  218. uint32_t sum;
  219. };
  220. // Implements the modified Zeng method from "A Survey on Palette Reordering
  221. // Methods for Improving the Compression of Color-Indexed Images" by Armando J.
  222. // Pinho and Antonio J. R. Neves.
  223. static WebPEncodingError PaletteSortModifiedZeng(
  224. const WebPPicture* const pic, const uint32_t* const palette_sorted,
  225. uint32_t num_colors, uint32_t* const palette) {
  226. uint32_t i, j, ind;
  227. uint8_t remapping[MAX_PALETTE_SIZE];
  228. uint32_t* cooccurrence;
  229. struct Sum sums[MAX_PALETTE_SIZE];
  230. uint32_t first, last;
  231. uint32_t num_sums;
  232. // TODO(vrabaud) check whether one color images should use palette or not.
  233. if (num_colors <= 1) return VP8_ENC_OK;
  234. // Build the co-occurrence matrix.
  235. cooccurrence =
  236. (uint32_t*)WebPSafeCalloc(num_colors * num_colors, sizeof(*cooccurrence));
  237. if (cooccurrence == NULL) return VP8_ENC_ERROR_OUT_OF_MEMORY;
  238. if (CoOccurrenceBuild(pic, palette_sorted, num_colors, cooccurrence) !=
  239. VP8_ENC_OK) {
  240. WebPSafeFree(cooccurrence);
  241. return VP8_ENC_ERROR_OUT_OF_MEMORY;
  242. }
  243. // Initialize the mapping list with the two best indices.
  244. CoOccurrenceFindMax(cooccurrence, num_colors, &remapping[0], &remapping[1]);
  245. // We need to append and prepend to the list of remapping. To this end, we
  246. // actually define the next start/end of the list as indices in a vector (with
  247. // a wrap around when the end is reached).
  248. first = 0;
  249. last = 1;
  250. num_sums = num_colors - 2; // -2 because we know the first two values
  251. if (num_sums > 0) {
  252. // Initialize the sums with the first two remappings and find the best one
  253. struct Sum* best_sum = &sums[0];
  254. best_sum->index = 0u;
  255. best_sum->sum = 0u;
  256. for (i = 0, j = 0; i < num_colors; ++i) {
  257. if (i == remapping[0] || i == remapping[1]) continue;
  258. sums[j].index = i;
  259. sums[j].sum = cooccurrence[i * num_colors + remapping[0]] +
  260. cooccurrence[i * num_colors + remapping[1]];
  261. if (sums[j].sum > best_sum->sum) best_sum = &sums[j];
  262. ++j;
  263. }
  264. while (num_sums > 0) {
  265. const uint8_t best_index = best_sum->index;
  266. // Compute delta to know if we need to prepend or append the best index.
  267. int32_t delta = 0;
  268. const int32_t n = num_colors - num_sums;
  269. for (ind = first, j = 0; (ind + j) % num_colors != last + 1; ++j) {
  270. const uint16_t l_j = remapping[(ind + j) % num_colors];
  271. delta += (n - 1 - 2 * (int32_t)j) *
  272. (int32_t)cooccurrence[best_index * num_colors + l_j];
  273. }
  274. if (delta > 0) {
  275. first = (first == 0) ? num_colors - 1 : first - 1;
  276. remapping[first] = best_index;
  277. } else {
  278. ++last;
  279. remapping[last] = best_index;
  280. }
  281. // Remove best_sum from sums.
  282. *best_sum = sums[num_sums - 1];
  283. --num_sums;
  284. // Update all the sums and find the best one.
  285. best_sum = &sums[0];
  286. for (i = 0; i < num_sums; ++i) {
  287. sums[i].sum += cooccurrence[best_index * num_colors + sums[i].index];
  288. if (sums[i].sum > best_sum->sum) best_sum = &sums[i];
  289. }
  290. }
  291. }
  292. assert((last + 1) % num_colors == first);
  293. WebPSafeFree(cooccurrence);
  294. // Re-map the palette.
  295. for (i = 0; i < num_colors; ++i) {
  296. palette[i] = palette_sorted[remapping[(first + i) % num_colors]];
  297. }
  298. return VP8_ENC_OK;
  299. }
  300. // -----------------------------------------------------------------------------
  301. // Palette
  302. // These five modes are evaluated and their respective entropy is computed.
  303. typedef enum {
  304. kDirect = 0,
  305. kSpatial = 1,
  306. kSubGreen = 2,
  307. kSpatialSubGreen = 3,
  308. kPalette = 4,
  309. kPaletteAndSpatial = 5,
  310. kNumEntropyIx = 6
  311. } EntropyIx;
  312. typedef enum {
  313. kSortedDefault = 0,
  314. kMinimizeDelta = 1,
  315. kModifiedZeng = 2,
  316. kUnusedPalette = 3,
  317. } PaletteSorting;
  318. typedef enum {
  319. kHistoAlpha = 0,
  320. kHistoAlphaPred,
  321. kHistoGreen,
  322. kHistoGreenPred,
  323. kHistoRed,
  324. kHistoRedPred,
  325. kHistoBlue,
  326. kHistoBluePred,
  327. kHistoRedSubGreen,
  328. kHistoRedPredSubGreen,
  329. kHistoBlueSubGreen,
  330. kHistoBluePredSubGreen,
  331. kHistoPalette,
  332. kHistoTotal // Must be last.
  333. } HistoIx;
  334. static void AddSingleSubGreen(int p, uint32_t* const r, uint32_t* const b) {
  335. const int green = p >> 8; // The upper bits are masked away later.
  336. ++r[((p >> 16) - green) & 0xff];
  337. ++b[((p >> 0) - green) & 0xff];
  338. }
  339. static void AddSingle(uint32_t p,
  340. uint32_t* const a, uint32_t* const r,
  341. uint32_t* const g, uint32_t* const b) {
  342. ++a[(p >> 24) & 0xff];
  343. ++r[(p >> 16) & 0xff];
  344. ++g[(p >> 8) & 0xff];
  345. ++b[(p >> 0) & 0xff];
  346. }
  347. static WEBP_INLINE uint32_t HashPix(uint32_t pix) {
  348. // Note that masking with 0xffffffffu is for preventing an
  349. // 'unsigned int overflow' warning. Doesn't impact the compiled code.
  350. return ((((uint64_t)pix + (pix >> 19)) * 0x39c5fba7ull) & 0xffffffffu) >> 24;
  351. }
  352. static int AnalyzeEntropy(const uint32_t* argb,
  353. int width, int height, int argb_stride,
  354. int use_palette,
  355. int palette_size, int transform_bits,
  356. EntropyIx* const min_entropy_ix,
  357. int* const red_and_blue_always_zero) {
  358. // Allocate histogram set with cache_bits = 0.
  359. uint32_t* histo;
  360. if (use_palette && palette_size <= 16) {
  361. // In the case of small palettes, we pack 2, 4 or 8 pixels together. In
  362. // practice, small palettes are better than any other transform.
  363. *min_entropy_ix = kPalette;
  364. *red_and_blue_always_zero = 1;
  365. return 1;
  366. }
  367. histo = (uint32_t*)WebPSafeCalloc(kHistoTotal, sizeof(*histo) * 256);
  368. if (histo != NULL) {
  369. int i, x, y;
  370. const uint32_t* prev_row = NULL;
  371. const uint32_t* curr_row = argb;
  372. uint32_t pix_prev = argb[0]; // Skip the first pixel.
  373. for (y = 0; y < height; ++y) {
  374. for (x = 0; x < width; ++x) {
  375. const uint32_t pix = curr_row[x];
  376. const uint32_t pix_diff = VP8LSubPixels(pix, pix_prev);
  377. pix_prev = pix;
  378. if ((pix_diff == 0) || (prev_row != NULL && pix == prev_row[x])) {
  379. continue;
  380. }
  381. AddSingle(pix,
  382. &histo[kHistoAlpha * 256],
  383. &histo[kHistoRed * 256],
  384. &histo[kHistoGreen * 256],
  385. &histo[kHistoBlue * 256]);
  386. AddSingle(pix_diff,
  387. &histo[kHistoAlphaPred * 256],
  388. &histo[kHistoRedPred * 256],
  389. &histo[kHistoGreenPred * 256],
  390. &histo[kHistoBluePred * 256]);
  391. AddSingleSubGreen(pix,
  392. &histo[kHistoRedSubGreen * 256],
  393. &histo[kHistoBlueSubGreen * 256]);
  394. AddSingleSubGreen(pix_diff,
  395. &histo[kHistoRedPredSubGreen * 256],
  396. &histo[kHistoBluePredSubGreen * 256]);
  397. {
  398. // Approximate the palette by the entropy of the multiplicative hash.
  399. const uint32_t hash = HashPix(pix);
  400. ++histo[kHistoPalette * 256 + hash];
  401. }
  402. }
  403. prev_row = curr_row;
  404. curr_row += argb_stride;
  405. }
  406. {
  407. double entropy_comp[kHistoTotal];
  408. double entropy[kNumEntropyIx];
  409. int k;
  410. int last_mode_to_analyze = use_palette ? kPalette : kSpatialSubGreen;
  411. int j;
  412. // Let's add one zero to the predicted histograms. The zeros are removed
  413. // too efficiently by the pix_diff == 0 comparison, at least one of the
  414. // zeros is likely to exist.
  415. ++histo[kHistoRedPredSubGreen * 256];
  416. ++histo[kHistoBluePredSubGreen * 256];
  417. ++histo[kHistoRedPred * 256];
  418. ++histo[kHistoGreenPred * 256];
  419. ++histo[kHistoBluePred * 256];
  420. ++histo[kHistoAlphaPred * 256];
  421. for (j = 0; j < kHistoTotal; ++j) {
  422. entropy_comp[j] = VP8LBitsEntropy(&histo[j * 256], 256);
  423. }
  424. entropy[kDirect] = entropy_comp[kHistoAlpha] +
  425. entropy_comp[kHistoRed] +
  426. entropy_comp[kHistoGreen] +
  427. entropy_comp[kHistoBlue];
  428. entropy[kSpatial] = entropy_comp[kHistoAlphaPred] +
  429. entropy_comp[kHistoRedPred] +
  430. entropy_comp[kHistoGreenPred] +
  431. entropy_comp[kHistoBluePred];
  432. entropy[kSubGreen] = entropy_comp[kHistoAlpha] +
  433. entropy_comp[kHistoRedSubGreen] +
  434. entropy_comp[kHistoGreen] +
  435. entropy_comp[kHistoBlueSubGreen];
  436. entropy[kSpatialSubGreen] = entropy_comp[kHistoAlphaPred] +
  437. entropy_comp[kHistoRedPredSubGreen] +
  438. entropy_comp[kHistoGreenPred] +
  439. entropy_comp[kHistoBluePredSubGreen];
  440. entropy[kPalette] = entropy_comp[kHistoPalette];
  441. // When including transforms, there is an overhead in bits from
  442. // storing them. This overhead is small but matters for small images.
  443. // For spatial, there are 14 transformations.
  444. entropy[kSpatial] += VP8LSubSampleSize(width, transform_bits) *
  445. VP8LSubSampleSize(height, transform_bits) *
  446. VP8LFastLog2(14);
  447. // For color transforms: 24 as only 3 channels are considered in a
  448. // ColorTransformElement.
  449. entropy[kSpatialSubGreen] += VP8LSubSampleSize(width, transform_bits) *
  450. VP8LSubSampleSize(height, transform_bits) *
  451. VP8LFastLog2(24);
  452. // For palettes, add the cost of storing the palette.
  453. // We empirically estimate the cost of a compressed entry as 8 bits.
  454. // The palette is differential-coded when compressed hence a much
  455. // lower cost than sizeof(uint32_t)*8.
  456. entropy[kPalette] += palette_size * 8;
  457. *min_entropy_ix = kDirect;
  458. for (k = kDirect + 1; k <= last_mode_to_analyze; ++k) {
  459. if (entropy[*min_entropy_ix] > entropy[k]) {
  460. *min_entropy_ix = (EntropyIx)k;
  461. }
  462. }
  463. assert((int)*min_entropy_ix <= last_mode_to_analyze);
  464. *red_and_blue_always_zero = 1;
  465. // Let's check if the histogram of the chosen entropy mode has
  466. // non-zero red and blue values. If all are zero, we can later skip
  467. // the cross color optimization.
  468. {
  469. static const uint8_t kHistoPairs[5][2] = {
  470. { kHistoRed, kHistoBlue },
  471. { kHistoRedPred, kHistoBluePred },
  472. { kHistoRedSubGreen, kHistoBlueSubGreen },
  473. { kHistoRedPredSubGreen, kHistoBluePredSubGreen },
  474. { kHistoRed, kHistoBlue }
  475. };
  476. const uint32_t* const red_histo =
  477. &histo[256 * kHistoPairs[*min_entropy_ix][0]];
  478. const uint32_t* const blue_histo =
  479. &histo[256 * kHistoPairs[*min_entropy_ix][1]];
  480. for (i = 1; i < 256; ++i) {
  481. if ((red_histo[i] | blue_histo[i]) != 0) {
  482. *red_and_blue_always_zero = 0;
  483. break;
  484. }
  485. }
  486. }
  487. }
  488. WebPSafeFree(histo);
  489. return 1;
  490. } else {
  491. return 0;
  492. }
  493. }
  494. static int GetHistoBits(int method, int use_palette, int width, int height) {
  495. // Make tile size a function of encoding method (Range: 0 to 6).
  496. int histo_bits = (use_palette ? 9 : 7) - method;
  497. while (1) {
  498. const int huff_image_size = VP8LSubSampleSize(width, histo_bits) *
  499. VP8LSubSampleSize(height, histo_bits);
  500. if (huff_image_size <= MAX_HUFF_IMAGE_SIZE) break;
  501. ++histo_bits;
  502. }
  503. return (histo_bits < MIN_HUFFMAN_BITS) ? MIN_HUFFMAN_BITS :
  504. (histo_bits > MAX_HUFFMAN_BITS) ? MAX_HUFFMAN_BITS : histo_bits;
  505. }
  506. static int GetTransformBits(int method, int histo_bits) {
  507. const int max_transform_bits = (method < 4) ? 6 : (method > 4) ? 4 : 5;
  508. const int res =
  509. (histo_bits > max_transform_bits) ? max_transform_bits : histo_bits;
  510. assert(res <= MAX_TRANSFORM_BITS);
  511. return res;
  512. }
  513. // Set of parameters to be used in each iteration of the cruncher.
  514. #define CRUNCH_SUBCONFIGS_MAX 2
  515. typedef struct {
  516. int lz77_;
  517. int do_no_cache_;
  518. } CrunchSubConfig;
  519. typedef struct {
  520. int entropy_idx_;
  521. PaletteSorting palette_sorting_type_;
  522. CrunchSubConfig sub_configs_[CRUNCH_SUBCONFIGS_MAX];
  523. int sub_configs_size_;
  524. } CrunchConfig;
  525. // +2 because we add a palette sorting configuration for kPalette and
  526. // kPaletteAndSpatial.
  527. #define CRUNCH_CONFIGS_MAX (kNumEntropyIx + 2)
  528. static int EncoderAnalyze(VP8LEncoder* const enc,
  529. CrunchConfig crunch_configs[CRUNCH_CONFIGS_MAX],
  530. int* const crunch_configs_size,
  531. int* const red_and_blue_always_zero) {
  532. const WebPPicture* const pic = enc->pic_;
  533. const int width = pic->width;
  534. const int height = pic->height;
  535. const WebPConfig* const config = enc->config_;
  536. const int method = config->method;
  537. const int low_effort = (config->method == 0);
  538. int i;
  539. int use_palette;
  540. int n_lz77s;
  541. // If set to 0, analyze the cache with the computed cache value. If 1, also
  542. // analyze with no-cache.
  543. int do_no_cache = 0;
  544. assert(pic != NULL && pic->argb != NULL);
  545. // Check whether a palette is possible.
  546. enc->palette_size_ = WebPGetColorPalette(pic, enc->palette_sorted_);
  547. use_palette = (enc->palette_size_ <= MAX_PALETTE_SIZE);
  548. if (!use_palette) {
  549. enc->palette_size_ = 0;
  550. } else {
  551. qsort(enc->palette_sorted_, enc->palette_size_,
  552. sizeof(*enc->palette_sorted_), PaletteCompareColorsForQsort);
  553. }
  554. // Empirical bit sizes.
  555. enc->histo_bits_ = GetHistoBits(method, use_palette,
  556. pic->width, pic->height);
  557. enc->transform_bits_ = GetTransformBits(method, enc->histo_bits_);
  558. if (low_effort) {
  559. // AnalyzeEntropy is somewhat slow.
  560. crunch_configs[0].entropy_idx_ = use_palette ? kPalette : kSpatialSubGreen;
  561. crunch_configs[0].palette_sorting_type_ =
  562. use_palette ? kSortedDefault : kUnusedPalette;
  563. n_lz77s = 1;
  564. *crunch_configs_size = 1;
  565. } else {
  566. EntropyIx min_entropy_ix;
  567. // Try out multiple LZ77 on images with few colors.
  568. n_lz77s = (enc->palette_size_ > 0 && enc->palette_size_ <= 16) ? 2 : 1;
  569. if (!AnalyzeEntropy(pic->argb, width, height, pic->argb_stride, use_palette,
  570. enc->palette_size_, enc->transform_bits_,
  571. &min_entropy_ix, red_and_blue_always_zero)) {
  572. return 0;
  573. }
  574. if (method == 6 && config->quality == 100) {
  575. do_no_cache = 1;
  576. // Go brute force on all transforms.
  577. *crunch_configs_size = 0;
  578. for (i = 0; i < kNumEntropyIx; ++i) {
  579. // We can only apply kPalette or kPaletteAndSpatial if we can indeed use
  580. // a palette.
  581. if ((i != kPalette && i != kPaletteAndSpatial) || use_palette) {
  582. assert(*crunch_configs_size < CRUNCH_CONFIGS_MAX);
  583. crunch_configs[(*crunch_configs_size)].entropy_idx_ = i;
  584. if (use_palette && (i == kPalette || i == kPaletteAndSpatial)) {
  585. crunch_configs[(*crunch_configs_size)].palette_sorting_type_ =
  586. kMinimizeDelta;
  587. ++*crunch_configs_size;
  588. // Also add modified Zeng's method.
  589. crunch_configs[(*crunch_configs_size)].entropy_idx_ = i;
  590. crunch_configs[(*crunch_configs_size)].palette_sorting_type_ =
  591. kModifiedZeng;
  592. } else {
  593. crunch_configs[(*crunch_configs_size)].palette_sorting_type_ =
  594. kUnusedPalette;
  595. }
  596. ++*crunch_configs_size;
  597. }
  598. }
  599. } else {
  600. // Only choose the guessed best transform.
  601. *crunch_configs_size = 1;
  602. crunch_configs[0].entropy_idx_ = min_entropy_ix;
  603. crunch_configs[0].palette_sorting_type_ =
  604. use_palette ? kMinimizeDelta : kUnusedPalette;
  605. if (config->quality >= 75 && method == 5) {
  606. // Test with and without color cache.
  607. do_no_cache = 1;
  608. // If we have a palette, also check in combination with spatial.
  609. if (min_entropy_ix == kPalette) {
  610. *crunch_configs_size = 2;
  611. crunch_configs[1].entropy_idx_ = kPaletteAndSpatial;
  612. crunch_configs[1].palette_sorting_type_ = kMinimizeDelta;
  613. }
  614. }
  615. }
  616. }
  617. // Fill in the different LZ77s.
  618. assert(n_lz77s <= CRUNCH_SUBCONFIGS_MAX);
  619. for (i = 0; i < *crunch_configs_size; ++i) {
  620. int j;
  621. for (j = 0; j < n_lz77s; ++j) {
  622. assert(j < CRUNCH_SUBCONFIGS_MAX);
  623. crunch_configs[i].sub_configs_[j].lz77_ =
  624. (j == 0) ? kLZ77Standard | kLZ77RLE : kLZ77Box;
  625. crunch_configs[i].sub_configs_[j].do_no_cache_ = do_no_cache;
  626. }
  627. crunch_configs[i].sub_configs_size_ = n_lz77s;
  628. }
  629. return 1;
  630. }
  631. static int EncoderInit(VP8LEncoder* const enc) {
  632. const WebPPicture* const pic = enc->pic_;
  633. const int width = pic->width;
  634. const int height = pic->height;
  635. const int pix_cnt = width * height;
  636. // we round the block size up, so we're guaranteed to have
  637. // at most MAX_REFS_BLOCK_PER_IMAGE blocks used:
  638. const int refs_block_size = (pix_cnt - 1) / MAX_REFS_BLOCK_PER_IMAGE + 1;
  639. int i;
  640. if (!VP8LHashChainInit(&enc->hash_chain_, pix_cnt)) return 0;
  641. for (i = 0; i < 4; ++i) VP8LBackwardRefsInit(&enc->refs_[i], refs_block_size);
  642. return 1;
  643. }
  644. // Returns false in case of memory error.
  645. static int GetHuffBitLengthsAndCodes(
  646. const VP8LHistogramSet* const histogram_image,
  647. HuffmanTreeCode* const huffman_codes) {
  648. int i, k;
  649. int ok = 0;
  650. uint64_t total_length_size = 0;
  651. uint8_t* mem_buf = NULL;
  652. const int histogram_image_size = histogram_image->size;
  653. int max_num_symbols = 0;
  654. uint8_t* buf_rle = NULL;
  655. HuffmanTree* huff_tree = NULL;
  656. // Iterate over all histograms and get the aggregate number of codes used.
  657. for (i = 0; i < histogram_image_size; ++i) {
  658. const VP8LHistogram* const histo = histogram_image->histograms[i];
  659. HuffmanTreeCode* const codes = &huffman_codes[5 * i];
  660. assert(histo != NULL);
  661. for (k = 0; k < 5; ++k) {
  662. const int num_symbols =
  663. (k == 0) ? VP8LHistogramNumCodes(histo->palette_code_bits_) :
  664. (k == 4) ? NUM_DISTANCE_CODES : 256;
  665. codes[k].num_symbols = num_symbols;
  666. total_length_size += num_symbols;
  667. }
  668. }
  669. // Allocate and Set Huffman codes.
  670. {
  671. uint16_t* codes;
  672. uint8_t* lengths;
  673. mem_buf = (uint8_t*)WebPSafeCalloc(total_length_size,
  674. sizeof(*lengths) + sizeof(*codes));
  675. if (mem_buf == NULL) goto End;
  676. codes = (uint16_t*)mem_buf;
  677. lengths = (uint8_t*)&codes[total_length_size];
  678. for (i = 0; i < 5 * histogram_image_size; ++i) {
  679. const int bit_length = huffman_codes[i].num_symbols;
  680. huffman_codes[i].codes = codes;
  681. huffman_codes[i].code_lengths = lengths;
  682. codes += bit_length;
  683. lengths += bit_length;
  684. if (max_num_symbols < bit_length) {
  685. max_num_symbols = bit_length;
  686. }
  687. }
  688. }
  689. buf_rle = (uint8_t*)WebPSafeMalloc(1ULL, max_num_symbols);
  690. huff_tree = (HuffmanTree*)WebPSafeMalloc(3ULL * max_num_symbols,
  691. sizeof(*huff_tree));
  692. if (buf_rle == NULL || huff_tree == NULL) goto End;
  693. // Create Huffman trees.
  694. for (i = 0; i < histogram_image_size; ++i) {
  695. HuffmanTreeCode* const codes = &huffman_codes[5 * i];
  696. VP8LHistogram* const histo = histogram_image->histograms[i];
  697. VP8LCreateHuffmanTree(histo->literal_, 15, buf_rle, huff_tree, codes + 0);
  698. VP8LCreateHuffmanTree(histo->red_, 15, buf_rle, huff_tree, codes + 1);
  699. VP8LCreateHuffmanTree(histo->blue_, 15, buf_rle, huff_tree, codes + 2);
  700. VP8LCreateHuffmanTree(histo->alpha_, 15, buf_rle, huff_tree, codes + 3);
  701. VP8LCreateHuffmanTree(histo->distance_, 15, buf_rle, huff_tree, codes + 4);
  702. }
  703. ok = 1;
  704. End:
  705. WebPSafeFree(huff_tree);
  706. WebPSafeFree(buf_rle);
  707. if (!ok) {
  708. WebPSafeFree(mem_buf);
  709. memset(huffman_codes, 0, 5 * histogram_image_size * sizeof(*huffman_codes));
  710. }
  711. return ok;
  712. }
  713. static void StoreHuffmanTreeOfHuffmanTreeToBitMask(
  714. VP8LBitWriter* const bw, const uint8_t* code_length_bitdepth) {
  715. // RFC 1951 will calm you down if you are worried about this funny sequence.
  716. // This sequence is tuned from that, but more weighted for lower symbol count,
  717. // and more spiking histograms.
  718. static const uint8_t kStorageOrder[CODE_LENGTH_CODES] = {
  719. 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
  720. };
  721. int i;
  722. // Throw away trailing zeros:
  723. int codes_to_store = CODE_LENGTH_CODES;
  724. for (; codes_to_store > 4; --codes_to_store) {
  725. if (code_length_bitdepth[kStorageOrder[codes_to_store - 1]] != 0) {
  726. break;
  727. }
  728. }
  729. VP8LPutBits(bw, codes_to_store - 4, 4);
  730. for (i = 0; i < codes_to_store; ++i) {
  731. VP8LPutBits(bw, code_length_bitdepth[kStorageOrder[i]], 3);
  732. }
  733. }
  734. static void ClearHuffmanTreeIfOnlyOneSymbol(
  735. HuffmanTreeCode* const huffman_code) {
  736. int k;
  737. int count = 0;
  738. for (k = 0; k < huffman_code->num_symbols; ++k) {
  739. if (huffman_code->code_lengths[k] != 0) {
  740. ++count;
  741. if (count > 1) return;
  742. }
  743. }
  744. for (k = 0; k < huffman_code->num_symbols; ++k) {
  745. huffman_code->code_lengths[k] = 0;
  746. huffman_code->codes[k] = 0;
  747. }
  748. }
  749. static void StoreHuffmanTreeToBitMask(
  750. VP8LBitWriter* const bw,
  751. const HuffmanTreeToken* const tokens, const int num_tokens,
  752. const HuffmanTreeCode* const huffman_code) {
  753. int i;
  754. for (i = 0; i < num_tokens; ++i) {
  755. const int ix = tokens[i].code;
  756. const int extra_bits = tokens[i].extra_bits;
  757. VP8LPutBits(bw, huffman_code->codes[ix], huffman_code->code_lengths[ix]);
  758. switch (ix) {
  759. case 16:
  760. VP8LPutBits(bw, extra_bits, 2);
  761. break;
  762. case 17:
  763. VP8LPutBits(bw, extra_bits, 3);
  764. break;
  765. case 18:
  766. VP8LPutBits(bw, extra_bits, 7);
  767. break;
  768. }
  769. }
  770. }
  771. // 'huff_tree' and 'tokens' are pre-alloacted buffers.
  772. static void StoreFullHuffmanCode(VP8LBitWriter* const bw,
  773. HuffmanTree* const huff_tree,
  774. HuffmanTreeToken* const tokens,
  775. const HuffmanTreeCode* const tree) {
  776. uint8_t code_length_bitdepth[CODE_LENGTH_CODES] = { 0 };
  777. uint16_t code_length_bitdepth_symbols[CODE_LENGTH_CODES] = { 0 };
  778. const int max_tokens = tree->num_symbols;
  779. int num_tokens;
  780. HuffmanTreeCode huffman_code;
  781. huffman_code.num_symbols = CODE_LENGTH_CODES;
  782. huffman_code.code_lengths = code_length_bitdepth;
  783. huffman_code.codes = code_length_bitdepth_symbols;
  784. VP8LPutBits(bw, 0, 1);
  785. num_tokens = VP8LCreateCompressedHuffmanTree(tree, tokens, max_tokens);
  786. {
  787. uint32_t histogram[CODE_LENGTH_CODES] = { 0 };
  788. uint8_t buf_rle[CODE_LENGTH_CODES] = { 0 };
  789. int i;
  790. for (i = 0; i < num_tokens; ++i) {
  791. ++histogram[tokens[i].code];
  792. }
  793. VP8LCreateHuffmanTree(histogram, 7, buf_rle, huff_tree, &huffman_code);
  794. }
  795. StoreHuffmanTreeOfHuffmanTreeToBitMask(bw, code_length_bitdepth);
  796. ClearHuffmanTreeIfOnlyOneSymbol(&huffman_code);
  797. {
  798. int trailing_zero_bits = 0;
  799. int trimmed_length = num_tokens;
  800. int write_trimmed_length;
  801. int length;
  802. int i = num_tokens;
  803. while (i-- > 0) {
  804. const int ix = tokens[i].code;
  805. if (ix == 0 || ix == 17 || ix == 18) {
  806. --trimmed_length; // discount trailing zeros
  807. trailing_zero_bits += code_length_bitdepth[ix];
  808. if (ix == 17) {
  809. trailing_zero_bits += 3;
  810. } else if (ix == 18) {
  811. trailing_zero_bits += 7;
  812. }
  813. } else {
  814. break;
  815. }
  816. }
  817. write_trimmed_length = (trimmed_length > 1 && trailing_zero_bits > 12);
  818. length = write_trimmed_length ? trimmed_length : num_tokens;
  819. VP8LPutBits(bw, write_trimmed_length, 1);
  820. if (write_trimmed_length) {
  821. if (trimmed_length == 2) {
  822. VP8LPutBits(bw, 0, 3 + 2); // nbitpairs=1, trimmed_length=2
  823. } else {
  824. const int nbits = BitsLog2Floor(trimmed_length - 2);
  825. const int nbitpairs = nbits / 2 + 1;
  826. assert(trimmed_length > 2);
  827. assert(nbitpairs - 1 < 8);
  828. VP8LPutBits(bw, nbitpairs - 1, 3);
  829. VP8LPutBits(bw, trimmed_length - 2, nbitpairs * 2);
  830. }
  831. }
  832. StoreHuffmanTreeToBitMask(bw, tokens, length, &huffman_code);
  833. }
  834. }
  835. // 'huff_tree' and 'tokens' are pre-alloacted buffers.
  836. static void StoreHuffmanCode(VP8LBitWriter* const bw,
  837. HuffmanTree* const huff_tree,
  838. HuffmanTreeToken* const tokens,
  839. const HuffmanTreeCode* const huffman_code) {
  840. int i;
  841. int count = 0;
  842. int symbols[2] = { 0, 0 };
  843. const int kMaxBits = 8;
  844. const int kMaxSymbol = 1 << kMaxBits;
  845. // Check whether it's a small tree.
  846. for (i = 0; i < huffman_code->num_symbols && count < 3; ++i) {
  847. if (huffman_code->code_lengths[i] != 0) {
  848. if (count < 2) symbols[count] = i;
  849. ++count;
  850. }
  851. }
  852. if (count == 0) { // emit minimal tree for empty cases
  853. // bits: small tree marker: 1, count-1: 0, large 8-bit code: 0, code: 0
  854. VP8LPutBits(bw, 0x01, 4);
  855. } else if (count <= 2 && symbols[0] < kMaxSymbol && symbols[1] < kMaxSymbol) {
  856. VP8LPutBits(bw, 1, 1); // Small tree marker to encode 1 or 2 symbols.
  857. VP8LPutBits(bw, count - 1, 1);
  858. if (symbols[0] <= 1) {
  859. VP8LPutBits(bw, 0, 1); // Code bit for small (1 bit) symbol value.
  860. VP8LPutBits(bw, symbols[0], 1);
  861. } else {
  862. VP8LPutBits(bw, 1, 1);
  863. VP8LPutBits(bw, symbols[0], 8);
  864. }
  865. if (count == 2) {
  866. VP8LPutBits(bw, symbols[1], 8);
  867. }
  868. } else {
  869. StoreFullHuffmanCode(bw, huff_tree, tokens, huffman_code);
  870. }
  871. }
  872. static WEBP_INLINE void WriteHuffmanCode(VP8LBitWriter* const bw,
  873. const HuffmanTreeCode* const code,
  874. int code_index) {
  875. const int depth = code->code_lengths[code_index];
  876. const int symbol = code->codes[code_index];
  877. VP8LPutBits(bw, symbol, depth);
  878. }
  879. static WEBP_INLINE void WriteHuffmanCodeWithExtraBits(
  880. VP8LBitWriter* const bw,
  881. const HuffmanTreeCode* const code,
  882. int code_index,
  883. int bits,
  884. int n_bits) {
  885. const int depth = code->code_lengths[code_index];
  886. const int symbol = code->codes[code_index];
  887. VP8LPutBits(bw, (bits << depth) | symbol, depth + n_bits);
  888. }
  889. static WebPEncodingError StoreImageToBitMask(
  890. VP8LBitWriter* const bw, int width, int histo_bits,
  891. const VP8LBackwardRefs* const refs,
  892. const uint16_t* histogram_symbols,
  893. const HuffmanTreeCode* const huffman_codes) {
  894. const int histo_xsize = histo_bits ? VP8LSubSampleSize(width, histo_bits) : 1;
  895. const int tile_mask = (histo_bits == 0) ? 0 : -(1 << histo_bits);
  896. // x and y trace the position in the image.
  897. int x = 0;
  898. int y = 0;
  899. int tile_x = x & tile_mask;
  900. int tile_y = y & tile_mask;
  901. int histogram_ix = histogram_symbols[0];
  902. const HuffmanTreeCode* codes = huffman_codes + 5 * histogram_ix;
  903. VP8LRefsCursor c = VP8LRefsCursorInit(refs);
  904. while (VP8LRefsCursorOk(&c)) {
  905. const PixOrCopy* const v = c.cur_pos;
  906. if ((tile_x != (x & tile_mask)) || (tile_y != (y & tile_mask))) {
  907. tile_x = x & tile_mask;
  908. tile_y = y & tile_mask;
  909. histogram_ix = histogram_symbols[(y >> histo_bits) * histo_xsize +
  910. (x >> histo_bits)];
  911. codes = huffman_codes + 5 * histogram_ix;
  912. }
  913. if (PixOrCopyIsLiteral(v)) {
  914. static const uint8_t order[] = { 1, 2, 0, 3 };
  915. int k;
  916. for (k = 0; k < 4; ++k) {
  917. const int code = PixOrCopyLiteral(v, order[k]);
  918. WriteHuffmanCode(bw, codes + k, code);
  919. }
  920. } else if (PixOrCopyIsCacheIdx(v)) {
  921. const int code = PixOrCopyCacheIdx(v);
  922. const int literal_ix = 256 + NUM_LENGTH_CODES + code;
  923. WriteHuffmanCode(bw, codes, literal_ix);
  924. } else {
  925. int bits, n_bits;
  926. int code;
  927. const int distance = PixOrCopyDistance(v);
  928. VP8LPrefixEncode(v->len, &code, &n_bits, &bits);
  929. WriteHuffmanCodeWithExtraBits(bw, codes, 256 + code, bits, n_bits);
  930. // Don't write the distance with the extra bits code since
  931. // the distance can be up to 18 bits of extra bits, and the prefix
  932. // 15 bits, totaling to 33, and our PutBits only supports up to 32 bits.
  933. VP8LPrefixEncode(distance, &code, &n_bits, &bits);
  934. WriteHuffmanCode(bw, codes + 4, code);
  935. VP8LPutBits(bw, bits, n_bits);
  936. }
  937. x += PixOrCopyLength(v);
  938. while (x >= width) {
  939. x -= width;
  940. ++y;
  941. }
  942. VP8LRefsCursorNext(&c);
  943. }
  944. return bw->error_ ? VP8_ENC_ERROR_OUT_OF_MEMORY : VP8_ENC_OK;
  945. }
  946. // Special case of EncodeImageInternal() for cache-bits=0, histo_bits=31
  947. static WebPEncodingError EncodeImageNoHuffman(
  948. VP8LBitWriter* const bw, const uint32_t* const argb,
  949. VP8LHashChain* const hash_chain, VP8LBackwardRefs* const refs_array,
  950. int width, int height, int quality, int low_effort) {
  951. int i;
  952. int max_tokens = 0;
  953. WebPEncodingError err = VP8_ENC_OK;
  954. VP8LBackwardRefs* refs;
  955. HuffmanTreeToken* tokens = NULL;
  956. HuffmanTreeCode huffman_codes[5] = { { 0, NULL, NULL } };
  957. const uint16_t histogram_symbols[1] = { 0 }; // only one tree, one symbol
  958. int cache_bits = 0;
  959. VP8LHistogramSet* histogram_image = NULL;
  960. HuffmanTree* const huff_tree = (HuffmanTree*)WebPSafeMalloc(
  961. 3ULL * CODE_LENGTH_CODES, sizeof(*huff_tree));
  962. if (huff_tree == NULL) {
  963. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  964. goto Error;
  965. }
  966. // Calculate backward references from ARGB image.
  967. if (!VP8LHashChainFill(hash_chain, quality, argb, width, height,
  968. low_effort)) {
  969. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  970. goto Error;
  971. }
  972. err = VP8LGetBackwardReferences(
  973. width, height, argb, quality, /*low_effort=*/0, kLZ77Standard | kLZ77RLE,
  974. cache_bits, /*do_no_cache=*/0, hash_chain, refs_array, &cache_bits);
  975. if (err != VP8_ENC_OK) goto Error;
  976. refs = &refs_array[0];
  977. histogram_image = VP8LAllocateHistogramSet(1, cache_bits);
  978. if (histogram_image == NULL) {
  979. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  980. goto Error;
  981. }
  982. VP8LHistogramSetClear(histogram_image);
  983. // Build histogram image and symbols from backward references.
  984. VP8LHistogramStoreRefs(refs, histogram_image->histograms[0]);
  985. // Create Huffman bit lengths and codes for each histogram image.
  986. assert(histogram_image->size == 1);
  987. if (!GetHuffBitLengthsAndCodes(histogram_image, huffman_codes)) {
  988. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  989. goto Error;
  990. }
  991. // No color cache, no Huffman image.
  992. VP8LPutBits(bw, 0, 1);
  993. // Find maximum number of symbols for the huffman tree-set.
  994. for (i = 0; i < 5; ++i) {
  995. HuffmanTreeCode* const codes = &huffman_codes[i];
  996. if (max_tokens < codes->num_symbols) {
  997. max_tokens = codes->num_symbols;
  998. }
  999. }
  1000. tokens = (HuffmanTreeToken*)WebPSafeMalloc(max_tokens, sizeof(*tokens));
  1001. if (tokens == NULL) {
  1002. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  1003. goto Error;
  1004. }
  1005. // Store Huffman codes.
  1006. for (i = 0; i < 5; ++i) {
  1007. HuffmanTreeCode* const codes = &huffman_codes[i];
  1008. StoreHuffmanCode(bw, huff_tree, tokens, codes);
  1009. ClearHuffmanTreeIfOnlyOneSymbol(codes);
  1010. }
  1011. // Store actual literals.
  1012. err = StoreImageToBitMask(bw, width, 0, refs, histogram_symbols,
  1013. huffman_codes);
  1014. Error:
  1015. WebPSafeFree(tokens);
  1016. WebPSafeFree(huff_tree);
  1017. VP8LFreeHistogramSet(histogram_image);
  1018. WebPSafeFree(huffman_codes[0].codes);
  1019. return err;
  1020. }
  1021. static WebPEncodingError EncodeImageInternal(
  1022. VP8LBitWriter* const bw, const uint32_t* const argb,
  1023. VP8LHashChain* const hash_chain, VP8LBackwardRefs refs_array[4], int width,
  1024. int height, int quality, int low_effort, int use_cache,
  1025. const CrunchConfig* const config, int* cache_bits, int histogram_bits,
  1026. size_t init_byte_position, int* const hdr_size, int* const data_size) {
  1027. WebPEncodingError err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  1028. const uint32_t histogram_image_xysize =
  1029. VP8LSubSampleSize(width, histogram_bits) *
  1030. VP8LSubSampleSize(height, histogram_bits);
  1031. VP8LHistogramSet* histogram_image = NULL;
  1032. VP8LHistogram* tmp_histo = NULL;
  1033. int histogram_image_size = 0;
  1034. size_t bit_array_size = 0;
  1035. HuffmanTree* const huff_tree = (HuffmanTree*)WebPSafeMalloc(
  1036. 3ULL * CODE_LENGTH_CODES, sizeof(*huff_tree));
  1037. HuffmanTreeToken* tokens = NULL;
  1038. HuffmanTreeCode* huffman_codes = NULL;
  1039. uint16_t* const histogram_symbols =
  1040. (uint16_t*)WebPSafeMalloc(histogram_image_xysize,
  1041. sizeof(*histogram_symbols));
  1042. int sub_configs_idx;
  1043. int cache_bits_init, write_histogram_image;
  1044. VP8LBitWriter bw_init = *bw, bw_best;
  1045. int hdr_size_tmp;
  1046. VP8LHashChain hash_chain_histogram; // histogram image hash chain
  1047. size_t bw_size_best = ~(size_t)0;
  1048. assert(histogram_bits >= MIN_HUFFMAN_BITS);
  1049. assert(histogram_bits <= MAX_HUFFMAN_BITS);
  1050. assert(hdr_size != NULL);
  1051. assert(data_size != NULL);
  1052. // Make sure we can allocate the different objects.
  1053. memset(&hash_chain_histogram, 0, sizeof(hash_chain_histogram));
  1054. if (huff_tree == NULL || histogram_symbols == NULL ||
  1055. !VP8LHashChainInit(&hash_chain_histogram, histogram_image_xysize) ||
  1056. !VP8LHashChainFill(hash_chain, quality, argb, width, height,
  1057. low_effort)) {
  1058. goto Error;
  1059. }
  1060. if (use_cache) {
  1061. // If the value is different from zero, it has been set during the
  1062. // palette analysis.
  1063. cache_bits_init = (*cache_bits == 0) ? MAX_COLOR_CACHE_BITS : *cache_bits;
  1064. } else {
  1065. cache_bits_init = 0;
  1066. }
  1067. // If several iterations will happen, clone into bw_best.
  1068. if (!VP8LBitWriterInit(&bw_best, 0) ||
  1069. ((config->sub_configs_size_ > 1 ||
  1070. config->sub_configs_[0].do_no_cache_) &&
  1071. !VP8LBitWriterClone(bw, &bw_best))) {
  1072. goto Error;
  1073. }
  1074. for (sub_configs_idx = 0; sub_configs_idx < config->sub_configs_size_;
  1075. ++sub_configs_idx) {
  1076. const CrunchSubConfig* const sub_config =
  1077. &config->sub_configs_[sub_configs_idx];
  1078. int cache_bits_best, i_cache;
  1079. err = VP8LGetBackwardReferences(width, height, argb, quality, low_effort,
  1080. sub_config->lz77_, cache_bits_init,
  1081. sub_config->do_no_cache_, hash_chain,
  1082. &refs_array[0], &cache_bits_best);
  1083. if (err != VP8_ENC_OK) goto Error;
  1084. for (i_cache = 0; i_cache < (sub_config->do_no_cache_ ? 2 : 1); ++i_cache) {
  1085. const int cache_bits_tmp = (i_cache == 0) ? cache_bits_best : 0;
  1086. // Speed-up: no need to study the no-cache case if it was already studied
  1087. // in i_cache == 0.
  1088. if (i_cache == 1 && cache_bits_best == 0) break;
  1089. // Reset the bit writer for this iteration.
  1090. VP8LBitWriterReset(&bw_init, bw);
  1091. // Build histogram image and symbols from backward references.
  1092. histogram_image =
  1093. VP8LAllocateHistogramSet(histogram_image_xysize, cache_bits_tmp);
  1094. tmp_histo = VP8LAllocateHistogram(cache_bits_tmp);
  1095. if (histogram_image == NULL || tmp_histo == NULL ||
  1096. !VP8LGetHistoImageSymbols(width, height, &refs_array[i_cache],
  1097. quality, low_effort, histogram_bits,
  1098. cache_bits_tmp, histogram_image, tmp_histo,
  1099. histogram_symbols)) {
  1100. goto Error;
  1101. }
  1102. // Create Huffman bit lengths and codes for each histogram image.
  1103. histogram_image_size = histogram_image->size;
  1104. bit_array_size = 5 * histogram_image_size;
  1105. huffman_codes = (HuffmanTreeCode*)WebPSafeCalloc(bit_array_size,
  1106. sizeof(*huffman_codes));
  1107. // Note: some histogram_image entries may point to tmp_histos[], so the
  1108. // latter need to outlive the following call to
  1109. // GetHuffBitLengthsAndCodes().
  1110. if (huffman_codes == NULL ||
  1111. !GetHuffBitLengthsAndCodes(histogram_image, huffman_codes)) {
  1112. goto Error;
  1113. }
  1114. // Free combined histograms.
  1115. VP8LFreeHistogramSet(histogram_image);
  1116. histogram_image = NULL;
  1117. // Free scratch histograms.
  1118. VP8LFreeHistogram(tmp_histo);
  1119. tmp_histo = NULL;
  1120. // Color Cache parameters.
  1121. if (cache_bits_tmp > 0) {
  1122. VP8LPutBits(bw, 1, 1);
  1123. VP8LPutBits(bw, cache_bits_tmp, 4);
  1124. } else {
  1125. VP8LPutBits(bw, 0, 1);
  1126. }
  1127. // Huffman image + meta huffman.
  1128. write_histogram_image = (histogram_image_size > 1);
  1129. VP8LPutBits(bw, write_histogram_image, 1);
  1130. if (write_histogram_image) {
  1131. uint32_t* const histogram_argb =
  1132. (uint32_t*)WebPSafeMalloc(histogram_image_xysize,
  1133. sizeof(*histogram_argb));
  1134. int max_index = 0;
  1135. uint32_t i;
  1136. if (histogram_argb == NULL) goto Error;
  1137. for (i = 0; i < histogram_image_xysize; ++i) {
  1138. const int symbol_index = histogram_symbols[i] & 0xffff;
  1139. histogram_argb[i] = (symbol_index << 8);
  1140. if (symbol_index >= max_index) {
  1141. max_index = symbol_index + 1;
  1142. }
  1143. }
  1144. histogram_image_size = max_index;
  1145. VP8LPutBits(bw, histogram_bits - 2, 3);
  1146. err = EncodeImageNoHuffman(
  1147. bw, histogram_argb, &hash_chain_histogram, &refs_array[2],
  1148. VP8LSubSampleSize(width, histogram_bits),
  1149. VP8LSubSampleSize(height, histogram_bits), quality, low_effort);
  1150. WebPSafeFree(histogram_argb);
  1151. if (err != VP8_ENC_OK) goto Error;
  1152. }
  1153. // Store Huffman codes.
  1154. {
  1155. int i;
  1156. int max_tokens = 0;
  1157. // Find maximum number of symbols for the huffman tree-set.
  1158. for (i = 0; i < 5 * histogram_image_size; ++i) {
  1159. HuffmanTreeCode* const codes = &huffman_codes[i];
  1160. if (max_tokens < codes->num_symbols) {
  1161. max_tokens = codes->num_symbols;
  1162. }
  1163. }
  1164. tokens = (HuffmanTreeToken*)WebPSafeMalloc(max_tokens, sizeof(*tokens));
  1165. if (tokens == NULL) goto Error;
  1166. for (i = 0; i < 5 * histogram_image_size; ++i) {
  1167. HuffmanTreeCode* const codes = &huffman_codes[i];
  1168. StoreHuffmanCode(bw, huff_tree, tokens, codes);
  1169. ClearHuffmanTreeIfOnlyOneSymbol(codes);
  1170. }
  1171. }
  1172. // Store actual literals.
  1173. hdr_size_tmp = (int)(VP8LBitWriterNumBytes(bw) - init_byte_position);
  1174. err = StoreImageToBitMask(bw, width, histogram_bits, &refs_array[i_cache],
  1175. histogram_symbols, huffman_codes);
  1176. if (err != VP8_ENC_OK) goto Error;
  1177. // Keep track of the smallest image so far.
  1178. if (VP8LBitWriterNumBytes(bw) < bw_size_best) {
  1179. bw_size_best = VP8LBitWriterNumBytes(bw);
  1180. *cache_bits = cache_bits_tmp;
  1181. *hdr_size = hdr_size_tmp;
  1182. *data_size =
  1183. (int)(VP8LBitWriterNumBytes(bw) - init_byte_position - *hdr_size);
  1184. VP8LBitWriterSwap(bw, &bw_best);
  1185. }
  1186. WebPSafeFree(tokens);
  1187. tokens = NULL;
  1188. if (huffman_codes != NULL) {
  1189. WebPSafeFree(huffman_codes->codes);
  1190. WebPSafeFree(huffman_codes);
  1191. huffman_codes = NULL;
  1192. }
  1193. }
  1194. }
  1195. VP8LBitWriterSwap(bw, &bw_best);
  1196. err = VP8_ENC_OK;
  1197. Error:
  1198. WebPSafeFree(tokens);
  1199. WebPSafeFree(huff_tree);
  1200. VP8LFreeHistogramSet(histogram_image);
  1201. VP8LFreeHistogram(tmp_histo);
  1202. VP8LHashChainClear(&hash_chain_histogram);
  1203. if (huffman_codes != NULL) {
  1204. WebPSafeFree(huffman_codes->codes);
  1205. WebPSafeFree(huffman_codes);
  1206. }
  1207. WebPSafeFree(histogram_symbols);
  1208. VP8LBitWriterWipeOut(&bw_best);
  1209. return err;
  1210. }
  1211. // -----------------------------------------------------------------------------
  1212. // Transforms
  1213. static void ApplySubtractGreen(VP8LEncoder* const enc, int width, int height,
  1214. VP8LBitWriter* const bw) {
  1215. VP8LPutBits(bw, TRANSFORM_PRESENT, 1);
  1216. VP8LPutBits(bw, SUBTRACT_GREEN, 2);
  1217. VP8LSubtractGreenFromBlueAndRed(enc->argb_, width * height);
  1218. }
  1219. static WebPEncodingError ApplyPredictFilter(const VP8LEncoder* const enc,
  1220. int width, int height,
  1221. int quality, int low_effort,
  1222. int used_subtract_green,
  1223. VP8LBitWriter* const bw) {
  1224. const int pred_bits = enc->transform_bits_;
  1225. const int transform_width = VP8LSubSampleSize(width, pred_bits);
  1226. const int transform_height = VP8LSubSampleSize(height, pred_bits);
  1227. // we disable near-lossless quantization if palette is used.
  1228. const int near_lossless_strength = enc->use_palette_ ? 100
  1229. : enc->config_->near_lossless;
  1230. VP8LResidualImage(width, height, pred_bits, low_effort, enc->argb_,
  1231. enc->argb_scratch_, enc->transform_data_,
  1232. near_lossless_strength, enc->config_->exact,
  1233. used_subtract_green);
  1234. VP8LPutBits(bw, TRANSFORM_PRESENT, 1);
  1235. VP8LPutBits(bw, PREDICTOR_TRANSFORM, 2);
  1236. assert(pred_bits >= 2);
  1237. VP8LPutBits(bw, pred_bits - 2, 3);
  1238. return EncodeImageNoHuffman(
  1239. bw, enc->transform_data_, (VP8LHashChain*)&enc->hash_chain_,
  1240. (VP8LBackwardRefs*)&enc->refs_[0], transform_width, transform_height,
  1241. quality, low_effort);
  1242. }
  1243. static WebPEncodingError ApplyCrossColorFilter(const VP8LEncoder* const enc,
  1244. int width, int height,
  1245. int quality, int low_effort,
  1246. VP8LBitWriter* const bw) {
  1247. const int ccolor_transform_bits = enc->transform_bits_;
  1248. const int transform_width = VP8LSubSampleSize(width, ccolor_transform_bits);
  1249. const int transform_height = VP8LSubSampleSize(height, ccolor_transform_bits);
  1250. VP8LColorSpaceTransform(width, height, ccolor_transform_bits, quality,
  1251. enc->argb_, enc->transform_data_);
  1252. VP8LPutBits(bw, TRANSFORM_PRESENT, 1);
  1253. VP8LPutBits(bw, CROSS_COLOR_TRANSFORM, 2);
  1254. assert(ccolor_transform_bits >= 2);
  1255. VP8LPutBits(bw, ccolor_transform_bits - 2, 3);
  1256. return EncodeImageNoHuffman(
  1257. bw, enc->transform_data_, (VP8LHashChain*)&enc->hash_chain_,
  1258. (VP8LBackwardRefs*)&enc->refs_[0], transform_width, transform_height,
  1259. quality, low_effort);
  1260. }
  1261. // -----------------------------------------------------------------------------
  1262. static WebPEncodingError WriteRiffHeader(const WebPPicture* const pic,
  1263. size_t riff_size, size_t vp8l_size) {
  1264. uint8_t riff[RIFF_HEADER_SIZE + CHUNK_HEADER_SIZE + VP8L_SIGNATURE_SIZE] = {
  1265. 'R', 'I', 'F', 'F', 0, 0, 0, 0, 'W', 'E', 'B', 'P',
  1266. 'V', 'P', '8', 'L', 0, 0, 0, 0, VP8L_MAGIC_BYTE,
  1267. };
  1268. PutLE32(riff + TAG_SIZE, (uint32_t)riff_size);
  1269. PutLE32(riff + RIFF_HEADER_SIZE + TAG_SIZE, (uint32_t)vp8l_size);
  1270. if (!pic->writer(riff, sizeof(riff), pic)) {
  1271. return VP8_ENC_ERROR_BAD_WRITE;
  1272. }
  1273. return VP8_ENC_OK;
  1274. }
  1275. static int WriteImageSize(const WebPPicture* const pic,
  1276. VP8LBitWriter* const bw) {
  1277. const int width = pic->width - 1;
  1278. const int height = pic->height - 1;
  1279. assert(width < WEBP_MAX_DIMENSION && height < WEBP_MAX_DIMENSION);
  1280. VP8LPutBits(bw, width, VP8L_IMAGE_SIZE_BITS);
  1281. VP8LPutBits(bw, height, VP8L_IMAGE_SIZE_BITS);
  1282. return !bw->error_;
  1283. }
  1284. static int WriteRealAlphaAndVersion(VP8LBitWriter* const bw, int has_alpha) {
  1285. VP8LPutBits(bw, has_alpha, 1);
  1286. VP8LPutBits(bw, VP8L_VERSION, VP8L_VERSION_BITS);
  1287. return !bw->error_;
  1288. }
  1289. static WebPEncodingError WriteImage(const WebPPicture* const pic,
  1290. VP8LBitWriter* const bw,
  1291. size_t* const coded_size) {
  1292. WebPEncodingError err = VP8_ENC_OK;
  1293. const uint8_t* const webpll_data = VP8LBitWriterFinish(bw);
  1294. const size_t webpll_size = VP8LBitWriterNumBytes(bw);
  1295. const size_t vp8l_size = VP8L_SIGNATURE_SIZE + webpll_size;
  1296. const size_t pad = vp8l_size & 1;
  1297. const size_t riff_size = TAG_SIZE + CHUNK_HEADER_SIZE + vp8l_size + pad;
  1298. err = WriteRiffHeader(pic, riff_size, vp8l_size);
  1299. if (err != VP8_ENC_OK) goto Error;
  1300. if (!pic->writer(webpll_data, webpll_size, pic)) {
  1301. err = VP8_ENC_ERROR_BAD_WRITE;
  1302. goto Error;
  1303. }
  1304. if (pad) {
  1305. const uint8_t pad_byte[1] = { 0 };
  1306. if (!pic->writer(pad_byte, 1, pic)) {
  1307. err = VP8_ENC_ERROR_BAD_WRITE;
  1308. goto Error;
  1309. }
  1310. }
  1311. *coded_size = CHUNK_HEADER_SIZE + riff_size;
  1312. return VP8_ENC_OK;
  1313. Error:
  1314. return err;
  1315. }
  1316. // -----------------------------------------------------------------------------
  1317. static void ClearTransformBuffer(VP8LEncoder* const enc) {
  1318. WebPSafeFree(enc->transform_mem_);
  1319. enc->transform_mem_ = NULL;
  1320. enc->transform_mem_size_ = 0;
  1321. }
  1322. // Allocates the memory for argb (W x H) buffer, 2 rows of context for
  1323. // prediction and transform data.
  1324. // Flags influencing the memory allocated:
  1325. // enc->transform_bits_
  1326. // enc->use_predict_, enc->use_cross_color_
  1327. static WebPEncodingError AllocateTransformBuffer(VP8LEncoder* const enc,
  1328. int width, int height) {
  1329. WebPEncodingError err = VP8_ENC_OK;
  1330. const uint64_t image_size = width * height;
  1331. // VP8LResidualImage needs room for 2 scanlines of uint32 pixels with an extra
  1332. // pixel in each, plus 2 regular scanlines of bytes.
  1333. // TODO(skal): Clean up by using arithmetic in bytes instead of words.
  1334. const uint64_t argb_scratch_size =
  1335. enc->use_predict_
  1336. ? (width + 1) * 2 +
  1337. (width * 2 + sizeof(uint32_t) - 1) / sizeof(uint32_t)
  1338. : 0;
  1339. const uint64_t transform_data_size =
  1340. (enc->use_predict_ || enc->use_cross_color_)
  1341. ? VP8LSubSampleSize(width, enc->transform_bits_) *
  1342. VP8LSubSampleSize(height, enc->transform_bits_)
  1343. : 0;
  1344. const uint64_t max_alignment_in_words =
  1345. (WEBP_ALIGN_CST + sizeof(uint32_t) - 1) / sizeof(uint32_t);
  1346. const uint64_t mem_size =
  1347. image_size + max_alignment_in_words +
  1348. argb_scratch_size + max_alignment_in_words +
  1349. transform_data_size;
  1350. uint32_t* mem = enc->transform_mem_;
  1351. if (mem == NULL || mem_size > enc->transform_mem_size_) {
  1352. ClearTransformBuffer(enc);
  1353. mem = (uint32_t*)WebPSafeMalloc(mem_size, sizeof(*mem));
  1354. if (mem == NULL) {
  1355. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  1356. goto Error;
  1357. }
  1358. enc->transform_mem_ = mem;
  1359. enc->transform_mem_size_ = (size_t)mem_size;
  1360. enc->argb_content_ = kEncoderNone;
  1361. }
  1362. enc->argb_ = mem;
  1363. mem = (uint32_t*)WEBP_ALIGN(mem + image_size);
  1364. enc->argb_scratch_ = mem;
  1365. mem = (uint32_t*)WEBP_ALIGN(mem + argb_scratch_size);
  1366. enc->transform_data_ = mem;
  1367. enc->current_width_ = width;
  1368. Error:
  1369. return err;
  1370. }
  1371. static WebPEncodingError MakeInputImageCopy(VP8LEncoder* const enc) {
  1372. WebPEncodingError err = VP8_ENC_OK;
  1373. const WebPPicture* const picture = enc->pic_;
  1374. const int width = picture->width;
  1375. const int height = picture->height;
  1376. err = AllocateTransformBuffer(enc, width, height);
  1377. if (err != VP8_ENC_OK) return err;
  1378. if (enc->argb_content_ == kEncoderARGB) return VP8_ENC_OK;
  1379. {
  1380. uint32_t* dst = enc->argb_;
  1381. const uint32_t* src = picture->argb;
  1382. int y;
  1383. for (y = 0; y < height; ++y) {
  1384. memcpy(dst, src, width * sizeof(*dst));
  1385. dst += width;
  1386. src += picture->argb_stride;
  1387. }
  1388. }
  1389. enc->argb_content_ = kEncoderARGB;
  1390. assert(enc->current_width_ == width);
  1391. return VP8_ENC_OK;
  1392. }
  1393. // -----------------------------------------------------------------------------
  1394. #define APPLY_PALETTE_GREEDY_MAX 4
  1395. static WEBP_INLINE uint32_t SearchColorGreedy(const uint32_t palette[],
  1396. int palette_size,
  1397. uint32_t color) {
  1398. (void)palette_size;
  1399. assert(palette_size < APPLY_PALETTE_GREEDY_MAX);
  1400. assert(3 == APPLY_PALETTE_GREEDY_MAX - 1);
  1401. if (color == palette[0]) return 0;
  1402. if (color == palette[1]) return 1;
  1403. if (color == palette[2]) return 2;
  1404. return 3;
  1405. }
  1406. static WEBP_INLINE uint32_t ApplyPaletteHash0(uint32_t color) {
  1407. // Focus on the green color.
  1408. return (color >> 8) & 0xff;
  1409. }
  1410. #define PALETTE_INV_SIZE_BITS 11
  1411. #define PALETTE_INV_SIZE (1 << PALETTE_INV_SIZE_BITS)
  1412. static WEBP_INLINE uint32_t ApplyPaletteHash1(uint32_t color) {
  1413. // Forget about alpha.
  1414. return ((uint32_t)((color & 0x00ffffffu) * 4222244071ull)) >>
  1415. (32 - PALETTE_INV_SIZE_BITS);
  1416. }
  1417. static WEBP_INLINE uint32_t ApplyPaletteHash2(uint32_t color) {
  1418. // Forget about alpha.
  1419. return ((uint32_t)((color & 0x00ffffffu) * ((1ull << 31) - 1))) >>
  1420. (32 - PALETTE_INV_SIZE_BITS);
  1421. }
  1422. // Use 1 pixel cache for ARGB pixels.
  1423. #define APPLY_PALETTE_FOR(COLOR_INDEX) do { \
  1424. uint32_t prev_pix = palette[0]; \
  1425. uint32_t prev_idx = 0; \
  1426. for (y = 0; y < height; ++y) { \
  1427. for (x = 0; x < width; ++x) { \
  1428. const uint32_t pix = src[x]; \
  1429. if (pix != prev_pix) { \
  1430. prev_idx = COLOR_INDEX; \
  1431. prev_pix = pix; \
  1432. } \
  1433. tmp_row[x] = prev_idx; \
  1434. } \
  1435. VP8LBundleColorMap(tmp_row, width, xbits, dst); \
  1436. src += src_stride; \
  1437. dst += dst_stride; \
  1438. } \
  1439. } while (0)
  1440. // Remap argb values in src[] to packed palettes entries in dst[]
  1441. // using 'row' as a temporary buffer of size 'width'.
  1442. // We assume that all src[] values have a corresponding entry in the palette.
  1443. // Note: src[] can be the same as dst[]
  1444. static WebPEncodingError ApplyPalette(const uint32_t* src, uint32_t src_stride,
  1445. uint32_t* dst, uint32_t dst_stride,
  1446. const uint32_t* palette, int palette_size,
  1447. int width, int height, int xbits) {
  1448. // TODO(skal): this tmp buffer is not needed if VP8LBundleColorMap() can be
  1449. // made to work in-place.
  1450. uint8_t* const tmp_row = (uint8_t*)WebPSafeMalloc(width, sizeof(*tmp_row));
  1451. int x, y;
  1452. if (tmp_row == NULL) return VP8_ENC_ERROR_OUT_OF_MEMORY;
  1453. if (palette_size < APPLY_PALETTE_GREEDY_MAX) {
  1454. APPLY_PALETTE_FOR(SearchColorGreedy(palette, palette_size, pix));
  1455. } else {
  1456. int i, j;
  1457. uint16_t buffer[PALETTE_INV_SIZE];
  1458. uint32_t (*const hash_functions[])(uint32_t) = {
  1459. ApplyPaletteHash0, ApplyPaletteHash1, ApplyPaletteHash2
  1460. };
  1461. // Try to find a perfect hash function able to go from a color to an index
  1462. // within 1 << PALETTE_INV_SIZE_BITS in order to build a hash map to go
  1463. // from color to index in palette.
  1464. for (i = 0; i < 3; ++i) {
  1465. int use_LUT = 1;
  1466. // Set each element in buffer to max uint16_t.
  1467. memset(buffer, 0xff, sizeof(buffer));
  1468. for (j = 0; j < palette_size; ++j) {
  1469. const uint32_t ind = hash_functions[i](palette[j]);
  1470. if (buffer[ind] != 0xffffu) {
  1471. use_LUT = 0;
  1472. break;
  1473. } else {
  1474. buffer[ind] = j;
  1475. }
  1476. }
  1477. if (use_LUT) break;
  1478. }
  1479. if (i == 0) {
  1480. APPLY_PALETTE_FOR(buffer[ApplyPaletteHash0(pix)]);
  1481. } else if (i == 1) {
  1482. APPLY_PALETTE_FOR(buffer[ApplyPaletteHash1(pix)]);
  1483. } else if (i == 2) {
  1484. APPLY_PALETTE_FOR(buffer[ApplyPaletteHash2(pix)]);
  1485. } else {
  1486. uint32_t idx_map[MAX_PALETTE_SIZE];
  1487. uint32_t palette_sorted[MAX_PALETTE_SIZE];
  1488. PrepareMapToPalette(palette, palette_size, palette_sorted, idx_map);
  1489. APPLY_PALETTE_FOR(
  1490. idx_map[SearchColorNoIdx(palette_sorted, pix, palette_size)]);
  1491. }
  1492. }
  1493. WebPSafeFree(tmp_row);
  1494. return VP8_ENC_OK;
  1495. }
  1496. #undef APPLY_PALETTE_FOR
  1497. #undef PALETTE_INV_SIZE_BITS
  1498. #undef PALETTE_INV_SIZE
  1499. #undef APPLY_PALETTE_GREEDY_MAX
  1500. // Note: Expects "enc->palette_" to be set properly.
  1501. static WebPEncodingError MapImageFromPalette(VP8LEncoder* const enc,
  1502. int in_place) {
  1503. WebPEncodingError err = VP8_ENC_OK;
  1504. const WebPPicture* const pic = enc->pic_;
  1505. const int width = pic->width;
  1506. const int height = pic->height;
  1507. const uint32_t* const palette = enc->palette_;
  1508. const uint32_t* src = in_place ? enc->argb_ : pic->argb;
  1509. const int src_stride = in_place ? enc->current_width_ : pic->argb_stride;
  1510. const int palette_size = enc->palette_size_;
  1511. int xbits;
  1512. // Replace each input pixel by corresponding palette index.
  1513. // This is done line by line.
  1514. if (palette_size <= 4) {
  1515. xbits = (palette_size <= 2) ? 3 : 2;
  1516. } else {
  1517. xbits = (palette_size <= 16) ? 1 : 0;
  1518. }
  1519. err = AllocateTransformBuffer(enc, VP8LSubSampleSize(width, xbits), height);
  1520. if (err != VP8_ENC_OK) return err;
  1521. err = ApplyPalette(src, src_stride,
  1522. enc->argb_, enc->current_width_,
  1523. palette, palette_size, width, height, xbits);
  1524. enc->argb_content_ = kEncoderPalette;
  1525. return err;
  1526. }
  1527. // Save palette_[] to bitstream.
  1528. static WebPEncodingError EncodePalette(VP8LBitWriter* const bw, int low_effort,
  1529. VP8LEncoder* const enc) {
  1530. int i;
  1531. uint32_t tmp_palette[MAX_PALETTE_SIZE];
  1532. const int palette_size = enc->palette_size_;
  1533. const uint32_t* const palette = enc->palette_;
  1534. VP8LPutBits(bw, TRANSFORM_PRESENT, 1);
  1535. VP8LPutBits(bw, COLOR_INDEXING_TRANSFORM, 2);
  1536. assert(palette_size >= 1 && palette_size <= MAX_PALETTE_SIZE);
  1537. VP8LPutBits(bw, palette_size - 1, 8);
  1538. for (i = palette_size - 1; i >= 1; --i) {
  1539. tmp_palette[i] = VP8LSubPixels(palette[i], palette[i - 1]);
  1540. }
  1541. tmp_palette[0] = palette[0];
  1542. return EncodeImageNoHuffman(bw, tmp_palette, &enc->hash_chain_,
  1543. &enc->refs_[0], palette_size, 1, /*quality=*/20,
  1544. low_effort);
  1545. }
  1546. // -----------------------------------------------------------------------------
  1547. // VP8LEncoder
  1548. static VP8LEncoder* VP8LEncoderNew(const WebPConfig* const config,
  1549. const WebPPicture* const picture) {
  1550. VP8LEncoder* const enc = (VP8LEncoder*)WebPSafeCalloc(1ULL, sizeof(*enc));
  1551. if (enc == NULL) {
  1552. WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
  1553. return NULL;
  1554. }
  1555. enc->config_ = config;
  1556. enc->pic_ = picture;
  1557. enc->argb_content_ = kEncoderNone;
  1558. VP8LEncDspInit();
  1559. return enc;
  1560. }
  1561. static void VP8LEncoderDelete(VP8LEncoder* enc) {
  1562. if (enc != NULL) {
  1563. int i;
  1564. VP8LHashChainClear(&enc->hash_chain_);
  1565. for (i = 0; i < 4; ++i) VP8LBackwardRefsClear(&enc->refs_[i]);
  1566. ClearTransformBuffer(enc);
  1567. WebPSafeFree(enc);
  1568. }
  1569. }
  1570. // -----------------------------------------------------------------------------
  1571. // Main call
  1572. typedef struct {
  1573. const WebPConfig* config_;
  1574. const WebPPicture* picture_;
  1575. VP8LBitWriter* bw_;
  1576. VP8LEncoder* enc_;
  1577. int use_cache_;
  1578. CrunchConfig crunch_configs_[CRUNCH_CONFIGS_MAX];
  1579. int num_crunch_configs_;
  1580. int red_and_blue_always_zero_;
  1581. WebPEncodingError err_;
  1582. WebPAuxStats* stats_;
  1583. } StreamEncodeContext;
  1584. static int EncodeStreamHook(void* input, void* data2) {
  1585. StreamEncodeContext* const params = (StreamEncodeContext*)input;
  1586. const WebPConfig* const config = params->config_;
  1587. const WebPPicture* const picture = params->picture_;
  1588. VP8LBitWriter* const bw = params->bw_;
  1589. VP8LEncoder* const enc = params->enc_;
  1590. const int use_cache = params->use_cache_;
  1591. const CrunchConfig* const crunch_configs = params->crunch_configs_;
  1592. const int num_crunch_configs = params->num_crunch_configs_;
  1593. const int red_and_blue_always_zero = params->red_and_blue_always_zero_;
  1594. #if !defined(WEBP_DISABLE_STATS)
  1595. WebPAuxStats* const stats = params->stats_;
  1596. #endif
  1597. WebPEncodingError err = VP8_ENC_OK;
  1598. const int quality = (int)config->quality;
  1599. const int low_effort = (config->method == 0);
  1600. #if (WEBP_NEAR_LOSSLESS == 1)
  1601. const int width = picture->width;
  1602. #endif
  1603. const int height = picture->height;
  1604. const size_t byte_position = VP8LBitWriterNumBytes(bw);
  1605. #if (WEBP_NEAR_LOSSLESS == 1)
  1606. int use_near_lossless = 0;
  1607. #endif
  1608. int hdr_size = 0;
  1609. int data_size = 0;
  1610. int use_delta_palette = 0;
  1611. int idx;
  1612. size_t best_size = ~(size_t)0;
  1613. VP8LBitWriter bw_init = *bw, bw_best;
  1614. (void)data2;
  1615. if (!VP8LBitWriterInit(&bw_best, 0) ||
  1616. (num_crunch_configs > 1 && !VP8LBitWriterClone(bw, &bw_best))) {
  1617. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  1618. goto Error;
  1619. }
  1620. for (idx = 0; idx < num_crunch_configs; ++idx) {
  1621. const int entropy_idx = crunch_configs[idx].entropy_idx_;
  1622. enc->use_palette_ =
  1623. (entropy_idx == kPalette) || (entropy_idx == kPaletteAndSpatial);
  1624. enc->use_subtract_green_ =
  1625. (entropy_idx == kSubGreen) || (entropy_idx == kSpatialSubGreen);
  1626. enc->use_predict_ = (entropy_idx == kSpatial) ||
  1627. (entropy_idx == kSpatialSubGreen) ||
  1628. (entropy_idx == kPaletteAndSpatial);
  1629. // When using a palette, R/B==0, hence no need to test for cross-color.
  1630. if (low_effort || enc->use_palette_) {
  1631. enc->use_cross_color_ = 0;
  1632. } else {
  1633. enc->use_cross_color_ = red_and_blue_always_zero ? 0 : enc->use_predict_;
  1634. }
  1635. // Reset any parameter in the encoder that is set in the previous iteration.
  1636. enc->cache_bits_ = 0;
  1637. VP8LBackwardRefsClear(&enc->refs_[0]);
  1638. VP8LBackwardRefsClear(&enc->refs_[1]);
  1639. #if (WEBP_NEAR_LOSSLESS == 1)
  1640. // Apply near-lossless preprocessing.
  1641. use_near_lossless = (config->near_lossless < 100) && !enc->use_palette_ &&
  1642. !enc->use_predict_;
  1643. if (use_near_lossless) {
  1644. err = AllocateTransformBuffer(enc, width, height);
  1645. if (err != VP8_ENC_OK) goto Error;
  1646. if ((enc->argb_content_ != kEncoderNearLossless) &&
  1647. !VP8ApplyNearLossless(picture, config->near_lossless, enc->argb_)) {
  1648. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  1649. goto Error;
  1650. }
  1651. enc->argb_content_ = kEncoderNearLossless;
  1652. } else {
  1653. enc->argb_content_ = kEncoderNone;
  1654. }
  1655. #else
  1656. enc->argb_content_ = kEncoderNone;
  1657. #endif
  1658. // Encode palette
  1659. if (enc->use_palette_) {
  1660. if (crunch_configs[idx].palette_sorting_type_ == kSortedDefault) {
  1661. // Nothing to do, we have already sorted the palette.
  1662. memcpy(enc->palette_, enc->palette_sorted_,
  1663. enc->palette_size_ * sizeof(*enc->palette_));
  1664. } else if (crunch_configs[idx].palette_sorting_type_ == kMinimizeDelta) {
  1665. PaletteSortMinimizeDeltas(enc->palette_sorted_, enc->palette_size_,
  1666. enc->palette_);
  1667. } else {
  1668. assert(crunch_configs[idx].palette_sorting_type_ == kModifiedZeng);
  1669. err = PaletteSortModifiedZeng(enc->pic_, enc->palette_sorted_,
  1670. enc->palette_size_, enc->palette_);
  1671. if (err != VP8_ENC_OK) goto Error;
  1672. }
  1673. err = EncodePalette(bw, low_effort, enc);
  1674. if (err != VP8_ENC_OK) goto Error;
  1675. err = MapImageFromPalette(enc, use_delta_palette);
  1676. if (err != VP8_ENC_OK) goto Error;
  1677. // If using a color cache, do not have it bigger than the number of
  1678. // colors.
  1679. if (use_cache && enc->palette_size_ < (1 << MAX_COLOR_CACHE_BITS)) {
  1680. enc->cache_bits_ = BitsLog2Floor(enc->palette_size_) + 1;
  1681. }
  1682. }
  1683. if (!use_delta_palette) {
  1684. // In case image is not packed.
  1685. if (enc->argb_content_ != kEncoderNearLossless &&
  1686. enc->argb_content_ != kEncoderPalette) {
  1687. err = MakeInputImageCopy(enc);
  1688. if (err != VP8_ENC_OK) goto Error;
  1689. }
  1690. // -----------------------------------------------------------------------
  1691. // Apply transforms and write transform data.
  1692. if (enc->use_subtract_green_) {
  1693. ApplySubtractGreen(enc, enc->current_width_, height, bw);
  1694. }
  1695. if (enc->use_predict_) {
  1696. err = ApplyPredictFilter(enc, enc->current_width_, height, quality,
  1697. low_effort, enc->use_subtract_green_, bw);
  1698. if (err != VP8_ENC_OK) goto Error;
  1699. }
  1700. if (enc->use_cross_color_) {
  1701. err = ApplyCrossColorFilter(enc, enc->current_width_, height, quality,
  1702. low_effort, bw);
  1703. if (err != VP8_ENC_OK) goto Error;
  1704. }
  1705. }
  1706. VP8LPutBits(bw, !TRANSFORM_PRESENT, 1); // No more transforms.
  1707. // -------------------------------------------------------------------------
  1708. // Encode and write the transformed image.
  1709. err = EncodeImageInternal(bw, enc->argb_, &enc->hash_chain_, enc->refs_,
  1710. enc->current_width_, height, quality, low_effort,
  1711. use_cache, &crunch_configs[idx],
  1712. &enc->cache_bits_, enc->histo_bits_,
  1713. byte_position, &hdr_size, &data_size);
  1714. if (err != VP8_ENC_OK) goto Error;
  1715. // If we are better than what we already have.
  1716. if (VP8LBitWriterNumBytes(bw) < best_size) {
  1717. best_size = VP8LBitWriterNumBytes(bw);
  1718. // Store the BitWriter.
  1719. VP8LBitWriterSwap(bw, &bw_best);
  1720. #if !defined(WEBP_DISABLE_STATS)
  1721. // Update the stats.
  1722. if (stats != NULL) {
  1723. stats->lossless_features = 0;
  1724. if (enc->use_predict_) stats->lossless_features |= 1;
  1725. if (enc->use_cross_color_) stats->lossless_features |= 2;
  1726. if (enc->use_subtract_green_) stats->lossless_features |= 4;
  1727. if (enc->use_palette_) stats->lossless_features |= 8;
  1728. stats->histogram_bits = enc->histo_bits_;
  1729. stats->transform_bits = enc->transform_bits_;
  1730. stats->cache_bits = enc->cache_bits_;
  1731. stats->palette_size = enc->palette_size_;
  1732. stats->lossless_size = (int)(best_size - byte_position);
  1733. stats->lossless_hdr_size = hdr_size;
  1734. stats->lossless_data_size = data_size;
  1735. }
  1736. #endif
  1737. }
  1738. // Reset the bit writer for the following iteration if any.
  1739. if (num_crunch_configs > 1) VP8LBitWriterReset(&bw_init, bw);
  1740. }
  1741. VP8LBitWriterSwap(&bw_best, bw);
  1742. Error:
  1743. VP8LBitWriterWipeOut(&bw_best);
  1744. params->err_ = err;
  1745. // The hook should return false in case of error.
  1746. return (err == VP8_ENC_OK);
  1747. }
  1748. WebPEncodingError VP8LEncodeStream(const WebPConfig* const config,
  1749. const WebPPicture* const picture,
  1750. VP8LBitWriter* const bw_main,
  1751. int use_cache) {
  1752. WebPEncodingError err = VP8_ENC_OK;
  1753. VP8LEncoder* const enc_main = VP8LEncoderNew(config, picture);
  1754. VP8LEncoder* enc_side = NULL;
  1755. CrunchConfig crunch_configs[CRUNCH_CONFIGS_MAX];
  1756. int num_crunch_configs_main, num_crunch_configs_side = 0;
  1757. int idx;
  1758. int red_and_blue_always_zero = 0;
  1759. WebPWorker worker_main, worker_side;
  1760. StreamEncodeContext params_main, params_side;
  1761. // The main thread uses picture->stats, the side thread uses stats_side.
  1762. WebPAuxStats stats_side;
  1763. VP8LBitWriter bw_side;
  1764. const WebPWorkerInterface* const worker_interface = WebPGetWorkerInterface();
  1765. int ok_main;
  1766. // Analyze image (entropy, num_palettes etc)
  1767. if (enc_main == NULL ||
  1768. !EncoderAnalyze(enc_main, crunch_configs, &num_crunch_configs_main,
  1769. &red_and_blue_always_zero) ||
  1770. !EncoderInit(enc_main) || !VP8LBitWriterInit(&bw_side, 0)) {
  1771. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  1772. goto Error;
  1773. }
  1774. // Split the configs between the main and side threads (if any).
  1775. if (config->thread_level > 0) {
  1776. num_crunch_configs_side = num_crunch_configs_main / 2;
  1777. for (idx = 0; idx < num_crunch_configs_side; ++idx) {
  1778. params_side.crunch_configs_[idx] =
  1779. crunch_configs[num_crunch_configs_main - num_crunch_configs_side +
  1780. idx];
  1781. }
  1782. params_side.num_crunch_configs_ = num_crunch_configs_side;
  1783. }
  1784. num_crunch_configs_main -= num_crunch_configs_side;
  1785. for (idx = 0; idx < num_crunch_configs_main; ++idx) {
  1786. params_main.crunch_configs_[idx] = crunch_configs[idx];
  1787. }
  1788. params_main.num_crunch_configs_ = num_crunch_configs_main;
  1789. // Fill in the parameters for the thread workers.
  1790. {
  1791. const int params_size = (num_crunch_configs_side > 0) ? 2 : 1;
  1792. for (idx = 0; idx < params_size; ++idx) {
  1793. // Create the parameters for each worker.
  1794. WebPWorker* const worker = (idx == 0) ? &worker_main : &worker_side;
  1795. StreamEncodeContext* const param =
  1796. (idx == 0) ? &params_main : &params_side;
  1797. param->config_ = config;
  1798. param->picture_ = picture;
  1799. param->use_cache_ = use_cache;
  1800. param->red_and_blue_always_zero_ = red_and_blue_always_zero;
  1801. if (idx == 0) {
  1802. param->stats_ = picture->stats;
  1803. param->bw_ = bw_main;
  1804. param->enc_ = enc_main;
  1805. } else {
  1806. param->stats_ = (picture->stats == NULL) ? NULL : &stats_side;
  1807. // Create a side bit writer.
  1808. if (!VP8LBitWriterClone(bw_main, &bw_side)) {
  1809. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  1810. goto Error;
  1811. }
  1812. param->bw_ = &bw_side;
  1813. // Create a side encoder.
  1814. enc_side = VP8LEncoderNew(config, picture);
  1815. if (enc_side == NULL || !EncoderInit(enc_side)) {
  1816. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  1817. goto Error;
  1818. }
  1819. // Copy the values that were computed for the main encoder.
  1820. enc_side->histo_bits_ = enc_main->histo_bits_;
  1821. enc_side->transform_bits_ = enc_main->transform_bits_;
  1822. enc_side->palette_size_ = enc_main->palette_size_;
  1823. memcpy(enc_side->palette_, enc_main->palette_,
  1824. sizeof(enc_main->palette_));
  1825. memcpy(enc_side->palette_sorted_, enc_main->palette_sorted_,
  1826. sizeof(enc_main->palette_sorted_));
  1827. param->enc_ = enc_side;
  1828. }
  1829. // Create the workers.
  1830. worker_interface->Init(worker);
  1831. worker->data1 = param;
  1832. worker->data2 = NULL;
  1833. worker->hook = EncodeStreamHook;
  1834. }
  1835. }
  1836. // Start the second thread if needed.
  1837. if (num_crunch_configs_side != 0) {
  1838. if (!worker_interface->Reset(&worker_side)) {
  1839. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  1840. goto Error;
  1841. }
  1842. #if !defined(WEBP_DISABLE_STATS)
  1843. // This line is here and not in the param initialization above to remove a
  1844. // Clang static analyzer warning.
  1845. if (picture->stats != NULL) {
  1846. memcpy(&stats_side, picture->stats, sizeof(stats_side));
  1847. }
  1848. #endif
  1849. // This line is only useful to remove a Clang static analyzer warning.
  1850. params_side.err_ = VP8_ENC_OK;
  1851. worker_interface->Launch(&worker_side);
  1852. }
  1853. // Execute the main thread.
  1854. worker_interface->Execute(&worker_main);
  1855. ok_main = worker_interface->Sync(&worker_main);
  1856. worker_interface->End(&worker_main);
  1857. if (num_crunch_configs_side != 0) {
  1858. // Wait for the second thread.
  1859. const int ok_side = worker_interface->Sync(&worker_side);
  1860. worker_interface->End(&worker_side);
  1861. if (!ok_main || !ok_side) {
  1862. err = ok_main ? params_side.err_ : params_main.err_;
  1863. goto Error;
  1864. }
  1865. if (VP8LBitWriterNumBytes(&bw_side) < VP8LBitWriterNumBytes(bw_main)) {
  1866. VP8LBitWriterSwap(bw_main, &bw_side);
  1867. #if !defined(WEBP_DISABLE_STATS)
  1868. if (picture->stats != NULL) {
  1869. memcpy(picture->stats, &stats_side, sizeof(*picture->stats));
  1870. }
  1871. #endif
  1872. }
  1873. } else {
  1874. if (!ok_main) {
  1875. err = params_main.err_;
  1876. goto Error;
  1877. }
  1878. }
  1879. Error:
  1880. VP8LBitWriterWipeOut(&bw_side);
  1881. VP8LEncoderDelete(enc_main);
  1882. VP8LEncoderDelete(enc_side);
  1883. return err;
  1884. }
  1885. #undef CRUNCH_CONFIGS_MAX
  1886. #undef CRUNCH_SUBCONFIGS_MAX
  1887. int VP8LEncodeImage(const WebPConfig* const config,
  1888. const WebPPicture* const picture) {
  1889. int width, height;
  1890. int has_alpha;
  1891. size_t coded_size;
  1892. int percent = 0;
  1893. int initial_size;
  1894. WebPEncodingError err = VP8_ENC_OK;
  1895. VP8LBitWriter bw;
  1896. if (picture == NULL) return 0;
  1897. if (config == NULL || picture->argb == NULL) {
  1898. err = VP8_ENC_ERROR_NULL_PARAMETER;
  1899. WebPEncodingSetError(picture, err);
  1900. return 0;
  1901. }
  1902. width = picture->width;
  1903. height = picture->height;
  1904. // Initialize BitWriter with size corresponding to 16 bpp to photo images and
  1905. // 8 bpp for graphical images.
  1906. initial_size = (config->image_hint == WEBP_HINT_GRAPH) ?
  1907. width * height : width * height * 2;
  1908. if (!VP8LBitWriterInit(&bw, initial_size)) {
  1909. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  1910. goto Error;
  1911. }
  1912. if (!WebPReportProgress(picture, 1, &percent)) {
  1913. UserAbort:
  1914. err = VP8_ENC_ERROR_USER_ABORT;
  1915. goto Error;
  1916. }
  1917. // Reset stats (for pure lossless coding)
  1918. if (picture->stats != NULL) {
  1919. WebPAuxStats* const stats = picture->stats;
  1920. memset(stats, 0, sizeof(*stats));
  1921. stats->PSNR[0] = 99.f;
  1922. stats->PSNR[1] = 99.f;
  1923. stats->PSNR[2] = 99.f;
  1924. stats->PSNR[3] = 99.f;
  1925. stats->PSNR[4] = 99.f;
  1926. }
  1927. // Write image size.
  1928. if (!WriteImageSize(picture, &bw)) {
  1929. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  1930. goto Error;
  1931. }
  1932. has_alpha = WebPPictureHasTransparency(picture);
  1933. // Write the non-trivial Alpha flag and lossless version.
  1934. if (!WriteRealAlphaAndVersion(&bw, has_alpha)) {
  1935. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  1936. goto Error;
  1937. }
  1938. if (!WebPReportProgress(picture, 5, &percent)) goto UserAbort;
  1939. // Encode main image stream.
  1940. err = VP8LEncodeStream(config, picture, &bw, 1 /*use_cache*/);
  1941. if (err != VP8_ENC_OK) goto Error;
  1942. if (!WebPReportProgress(picture, 90, &percent)) goto UserAbort;
  1943. // Finish the RIFF chunk.
  1944. err = WriteImage(picture, &bw, &coded_size);
  1945. if (err != VP8_ENC_OK) goto Error;
  1946. if (!WebPReportProgress(picture, 100, &percent)) goto UserAbort;
  1947. #if !defined(WEBP_DISABLE_STATS)
  1948. // Save size.
  1949. if (picture->stats != NULL) {
  1950. picture->stats->coded_size += (int)coded_size;
  1951. picture->stats->lossless_size = (int)coded_size;
  1952. }
  1953. #endif
  1954. if (picture->extra_info != NULL) {
  1955. const int mb_w = (width + 15) >> 4;
  1956. const int mb_h = (height + 15) >> 4;
  1957. memset(picture->extra_info, 0, mb_w * mb_h * sizeof(*picture->extra_info));
  1958. }
  1959. Error:
  1960. if (bw.error_) err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  1961. VP8LBitWriterWipeOut(&bw);
  1962. if (err != VP8_ENC_OK) {
  1963. WebPEncodingSetError(picture, err);
  1964. return 0;
  1965. }
  1966. return 1;
  1967. }
  1968. //------------------------------------------------------------------------------