vp8l_enc.c 67 KB

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