histogram_enc.c 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  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. // Author: Jyrki Alakuijala (jyrki@google.com)
  11. //
  12. #ifdef HAVE_CONFIG_H
  13. #include "../webp/config.h"
  14. #endif
  15. #include <math.h>
  16. #include "./backward_references_enc.h"
  17. #include "./histogram_enc.h"
  18. #include "../dsp/lossless.h"
  19. #include "../dsp/lossless_common.h"
  20. #include "../utils/utils.h"
  21. #define MAX_COST 1.e38
  22. // Number of partitions for the three dominant (literal, red and blue) symbol
  23. // costs.
  24. #define NUM_PARTITIONS 4
  25. // The size of the bin-hash corresponding to the three dominant costs.
  26. #define BIN_SIZE (NUM_PARTITIONS * NUM_PARTITIONS * NUM_PARTITIONS)
  27. // Maximum number of histograms allowed in greedy combining algorithm.
  28. #define MAX_HISTO_GREEDY 100
  29. static void HistogramClear(VP8LHistogram* const p) {
  30. uint32_t* const literal = p->literal_;
  31. const int cache_bits = p->palette_code_bits_;
  32. const int histo_size = VP8LGetHistogramSize(cache_bits);
  33. memset(p, 0, histo_size);
  34. p->palette_code_bits_ = cache_bits;
  35. p->literal_ = literal;
  36. }
  37. // Swap two histogram pointers.
  38. static void HistogramSwap(VP8LHistogram** const A, VP8LHistogram** const B) {
  39. VP8LHistogram* const tmp = *A;
  40. *A = *B;
  41. *B = tmp;
  42. }
  43. static void HistogramCopy(const VP8LHistogram* const src,
  44. VP8LHistogram* const dst) {
  45. uint32_t* const dst_literal = dst->literal_;
  46. const int dst_cache_bits = dst->palette_code_bits_;
  47. const int histo_size = VP8LGetHistogramSize(dst_cache_bits);
  48. assert(src->palette_code_bits_ == dst_cache_bits);
  49. memcpy(dst, src, histo_size);
  50. dst->literal_ = dst_literal;
  51. }
  52. int VP8LGetHistogramSize(int cache_bits) {
  53. const int literal_size = VP8LHistogramNumCodes(cache_bits);
  54. const size_t total_size = sizeof(VP8LHistogram) + sizeof(int) * literal_size;
  55. assert(total_size <= (size_t)0x7fffffff);
  56. return (int)total_size;
  57. }
  58. void VP8LFreeHistogram(VP8LHistogram* const histo) {
  59. WebPSafeFree(histo);
  60. }
  61. void VP8LFreeHistogramSet(VP8LHistogramSet* const histo) {
  62. WebPSafeFree(histo);
  63. }
  64. void VP8LHistogramStoreRefs(const VP8LBackwardRefs* const refs,
  65. VP8LHistogram* const histo) {
  66. VP8LRefsCursor c = VP8LRefsCursorInit(refs);
  67. while (VP8LRefsCursorOk(&c)) {
  68. VP8LHistogramAddSinglePixOrCopy(histo, c.cur_pos);
  69. VP8LRefsCursorNext(&c);
  70. }
  71. }
  72. void VP8LHistogramCreate(VP8LHistogram* const p,
  73. const VP8LBackwardRefs* const refs,
  74. int palette_code_bits) {
  75. if (palette_code_bits >= 0) {
  76. p->palette_code_bits_ = palette_code_bits;
  77. }
  78. HistogramClear(p);
  79. VP8LHistogramStoreRefs(refs, p);
  80. }
  81. void VP8LHistogramInit(VP8LHistogram* const p, int palette_code_bits) {
  82. p->palette_code_bits_ = palette_code_bits;
  83. HistogramClear(p);
  84. }
  85. VP8LHistogram* VP8LAllocateHistogram(int cache_bits) {
  86. VP8LHistogram* histo = NULL;
  87. const int total_size = VP8LGetHistogramSize(cache_bits);
  88. uint8_t* const memory = (uint8_t*)WebPSafeMalloc(total_size, sizeof(*memory));
  89. if (memory == NULL) return NULL;
  90. histo = (VP8LHistogram*)memory;
  91. // literal_ won't necessary be aligned.
  92. histo->literal_ = (uint32_t*)(memory + sizeof(VP8LHistogram));
  93. VP8LHistogramInit(histo, cache_bits);
  94. return histo;
  95. }
  96. VP8LHistogramSet* VP8LAllocateHistogramSet(int size, int cache_bits) {
  97. int i;
  98. VP8LHistogramSet* set;
  99. const int histo_size = VP8LGetHistogramSize(cache_bits);
  100. const size_t total_size =
  101. sizeof(*set) + size * (sizeof(*set->histograms) +
  102. histo_size + WEBP_ALIGN_CST);
  103. uint8_t* memory = (uint8_t*)WebPSafeMalloc(total_size, sizeof(*memory));
  104. if (memory == NULL) return NULL;
  105. set = (VP8LHistogramSet*)memory;
  106. memory += sizeof(*set);
  107. set->histograms = (VP8LHistogram**)memory;
  108. memory += size * sizeof(*set->histograms);
  109. set->max_size = size;
  110. set->size = size;
  111. for (i = 0; i < size; ++i) {
  112. memory = (uint8_t*)WEBP_ALIGN(memory);
  113. set->histograms[i] = (VP8LHistogram*)memory;
  114. // literal_ won't necessary be aligned.
  115. set->histograms[i]->literal_ = (uint32_t*)(memory + sizeof(VP8LHistogram));
  116. VP8LHistogramInit(set->histograms[i], cache_bits);
  117. memory += histo_size;
  118. }
  119. return set;
  120. }
  121. // -----------------------------------------------------------------------------
  122. void VP8LHistogramAddSinglePixOrCopy(VP8LHistogram* const histo,
  123. const PixOrCopy* const v) {
  124. if (PixOrCopyIsLiteral(v)) {
  125. ++histo->alpha_[PixOrCopyLiteral(v, 3)];
  126. ++histo->red_[PixOrCopyLiteral(v, 2)];
  127. ++histo->literal_[PixOrCopyLiteral(v, 1)];
  128. ++histo->blue_[PixOrCopyLiteral(v, 0)];
  129. } else if (PixOrCopyIsCacheIdx(v)) {
  130. const int literal_ix =
  131. NUM_LITERAL_CODES + NUM_LENGTH_CODES + PixOrCopyCacheIdx(v);
  132. ++histo->literal_[literal_ix];
  133. } else {
  134. int code, extra_bits;
  135. VP8LPrefixEncodeBits(PixOrCopyLength(v), &code, &extra_bits);
  136. ++histo->literal_[NUM_LITERAL_CODES + code];
  137. VP8LPrefixEncodeBits(PixOrCopyDistance(v), &code, &extra_bits);
  138. ++histo->distance_[code];
  139. }
  140. }
  141. // -----------------------------------------------------------------------------
  142. // Entropy-related functions.
  143. static WEBP_INLINE double BitsEntropyRefine(const VP8LBitEntropy* entropy) {
  144. double mix;
  145. if (entropy->nonzeros < 5) {
  146. if (entropy->nonzeros <= 1) {
  147. return 0;
  148. }
  149. // Two symbols, they will be 0 and 1 in a Huffman code.
  150. // Let's mix in a bit of entropy to favor good clustering when
  151. // distributions of these are combined.
  152. if (entropy->nonzeros == 2) {
  153. return 0.99 * entropy->sum + 0.01 * entropy->entropy;
  154. }
  155. // No matter what the entropy says, we cannot be better than min_limit
  156. // with Huffman coding. I am mixing a bit of entropy into the
  157. // min_limit since it produces much better (~0.5 %) compression results
  158. // perhaps because of better entropy clustering.
  159. if (entropy->nonzeros == 3) {
  160. mix = 0.95;
  161. } else {
  162. mix = 0.7; // nonzeros == 4.
  163. }
  164. } else {
  165. mix = 0.627;
  166. }
  167. {
  168. double min_limit = 2 * entropy->sum - entropy->max_val;
  169. min_limit = mix * min_limit + (1.0 - mix) * entropy->entropy;
  170. return (entropy->entropy < min_limit) ? min_limit : entropy->entropy;
  171. }
  172. }
  173. double VP8LBitsEntropy(const uint32_t* const array, int n,
  174. uint32_t* const trivial_symbol) {
  175. VP8LBitEntropy entropy;
  176. VP8LBitsEntropyUnrefined(array, n, &entropy);
  177. if (trivial_symbol != NULL) {
  178. *trivial_symbol =
  179. (entropy.nonzeros == 1) ? entropy.nonzero_code : VP8L_NON_TRIVIAL_SYM;
  180. }
  181. return BitsEntropyRefine(&entropy);
  182. }
  183. static double InitialHuffmanCost(void) {
  184. // Small bias because Huffman code length is typically not stored in
  185. // full length.
  186. static const int kHuffmanCodeOfHuffmanCodeSize = CODE_LENGTH_CODES * 3;
  187. static const double kSmallBias = 9.1;
  188. return kHuffmanCodeOfHuffmanCodeSize - kSmallBias;
  189. }
  190. // Finalize the Huffman cost based on streak numbers and length type (<3 or >=3)
  191. static double FinalHuffmanCost(const VP8LStreaks* const stats) {
  192. // The constants in this function are experimental and got rounded from
  193. // their original values in 1/8 when switched to 1/1024.
  194. double retval = InitialHuffmanCost();
  195. // Second coefficient: Many zeros in the histogram are covered efficiently
  196. // by a run-length encode. Originally 2/8.
  197. retval += stats->counts[0] * 1.5625 + 0.234375 * stats->streaks[0][1];
  198. // Second coefficient: Constant values are encoded less efficiently, but still
  199. // RLE'ed. Originally 6/8.
  200. retval += stats->counts[1] * 2.578125 + 0.703125 * stats->streaks[1][1];
  201. // 0s are usually encoded more efficiently than non-0s.
  202. // Originally 15/8.
  203. retval += 1.796875 * stats->streaks[0][0];
  204. // Originally 26/8.
  205. retval += 3.28125 * stats->streaks[1][0];
  206. return retval;
  207. }
  208. // Get the symbol entropy for the distribution 'population'.
  209. // Set 'trivial_sym', if there's only one symbol present in the distribution.
  210. static double PopulationCost(const uint32_t* const population, int length,
  211. uint32_t* const trivial_sym) {
  212. VP8LBitEntropy bit_entropy;
  213. VP8LStreaks stats;
  214. VP8LGetEntropyUnrefined(population, length, &bit_entropy, &stats);
  215. if (trivial_sym != NULL) {
  216. *trivial_sym = (bit_entropy.nonzeros == 1) ? bit_entropy.nonzero_code
  217. : VP8L_NON_TRIVIAL_SYM;
  218. }
  219. return BitsEntropyRefine(&bit_entropy) + FinalHuffmanCost(&stats);
  220. }
  221. // trivial_at_end is 1 if the two histograms only have one element that is
  222. // non-zero: both the zero-th one, or both the last one.
  223. static WEBP_INLINE double GetCombinedEntropy(const uint32_t* const X,
  224. const uint32_t* const Y,
  225. int length, int trivial_at_end) {
  226. VP8LStreaks stats;
  227. if (trivial_at_end) {
  228. // This configuration is due to palettization that transforms an indexed
  229. // pixel into 0xff000000 | (pixel << 8) in VP8LBundleColorMap.
  230. // BitsEntropyRefine is 0 for histograms with only one non-zero value.
  231. // Only FinalHuffmanCost needs to be evaluated.
  232. memset(&stats, 0, sizeof(stats));
  233. // Deal with the non-zero value at index 0 or length-1.
  234. stats.streaks[1][0] += 1;
  235. // Deal with the following/previous zero streak.
  236. stats.counts[0] += 1;
  237. stats.streaks[0][1] += length - 1;
  238. return FinalHuffmanCost(&stats);
  239. } else {
  240. VP8LBitEntropy bit_entropy;
  241. VP8LGetCombinedEntropyUnrefined(X, Y, length, &bit_entropy, &stats);
  242. return BitsEntropyRefine(&bit_entropy) + FinalHuffmanCost(&stats);
  243. }
  244. }
  245. // Estimates the Entropy + Huffman + other block overhead size cost.
  246. double VP8LHistogramEstimateBits(const VP8LHistogram* const p) {
  247. return
  248. PopulationCost(
  249. p->literal_, VP8LHistogramNumCodes(p->palette_code_bits_), NULL)
  250. + PopulationCost(p->red_, NUM_LITERAL_CODES, NULL)
  251. + PopulationCost(p->blue_, NUM_LITERAL_CODES, NULL)
  252. + PopulationCost(p->alpha_, NUM_LITERAL_CODES, NULL)
  253. + PopulationCost(p->distance_, NUM_DISTANCE_CODES, NULL)
  254. + VP8LExtraCost(p->literal_ + NUM_LITERAL_CODES, NUM_LENGTH_CODES)
  255. + VP8LExtraCost(p->distance_, NUM_DISTANCE_CODES);
  256. }
  257. // -----------------------------------------------------------------------------
  258. // Various histogram combine/cost-eval functions
  259. static int GetCombinedHistogramEntropy(const VP8LHistogram* const a,
  260. const VP8LHistogram* const b,
  261. double cost_threshold,
  262. double* cost) {
  263. const int palette_code_bits = a->palette_code_bits_;
  264. int trivial_at_end = 0;
  265. assert(a->palette_code_bits_ == b->palette_code_bits_);
  266. *cost += GetCombinedEntropy(a->literal_, b->literal_,
  267. VP8LHistogramNumCodes(palette_code_bits), 0);
  268. *cost += VP8LExtraCostCombined(a->literal_ + NUM_LITERAL_CODES,
  269. b->literal_ + NUM_LITERAL_CODES,
  270. NUM_LENGTH_CODES);
  271. if (*cost > cost_threshold) return 0;
  272. if (a->trivial_symbol_ != VP8L_NON_TRIVIAL_SYM &&
  273. a->trivial_symbol_ == b->trivial_symbol_) {
  274. // A, R and B are all 0 or 0xff.
  275. const uint32_t color_a = (a->trivial_symbol_ >> 24) & 0xff;
  276. const uint32_t color_r = (a->trivial_symbol_ >> 16) & 0xff;
  277. const uint32_t color_b = (a->trivial_symbol_ >> 0) & 0xff;
  278. if ((color_a == 0 || color_a == 0xff) &&
  279. (color_r == 0 || color_r == 0xff) &&
  280. (color_b == 0 || color_b == 0xff)) {
  281. trivial_at_end = 1;
  282. }
  283. }
  284. *cost +=
  285. GetCombinedEntropy(a->red_, b->red_, NUM_LITERAL_CODES, trivial_at_end);
  286. if (*cost > cost_threshold) return 0;
  287. *cost +=
  288. GetCombinedEntropy(a->blue_, b->blue_, NUM_LITERAL_CODES, trivial_at_end);
  289. if (*cost > cost_threshold) return 0;
  290. *cost += GetCombinedEntropy(a->alpha_, b->alpha_, NUM_LITERAL_CODES,
  291. trivial_at_end);
  292. if (*cost > cost_threshold) return 0;
  293. *cost +=
  294. GetCombinedEntropy(a->distance_, b->distance_, NUM_DISTANCE_CODES, 0);
  295. *cost +=
  296. VP8LExtraCostCombined(a->distance_, b->distance_, NUM_DISTANCE_CODES);
  297. if (*cost > cost_threshold) return 0;
  298. return 1;
  299. }
  300. static WEBP_INLINE void HistogramAdd(const VP8LHistogram* const a,
  301. const VP8LHistogram* const b,
  302. VP8LHistogram* const out) {
  303. VP8LHistogramAdd(a, b, out);
  304. out->trivial_symbol_ = (a->trivial_symbol_ == b->trivial_symbol_)
  305. ? a->trivial_symbol_
  306. : VP8L_NON_TRIVIAL_SYM;
  307. }
  308. // Performs out = a + b, computing the cost C(a+b) - C(a) - C(b) while comparing
  309. // to the threshold value 'cost_threshold'. The score returned is
  310. // Score = C(a+b) - C(a) - C(b), where C(a) + C(b) is known and fixed.
  311. // Since the previous score passed is 'cost_threshold', we only need to compare
  312. // the partial cost against 'cost_threshold + C(a) + C(b)' to possibly bail-out
  313. // early.
  314. static double HistogramAddEval(const VP8LHistogram* const a,
  315. const VP8LHistogram* const b,
  316. VP8LHistogram* const out,
  317. double cost_threshold) {
  318. double cost = 0;
  319. const double sum_cost = a->bit_cost_ + b->bit_cost_;
  320. cost_threshold += sum_cost;
  321. if (GetCombinedHistogramEntropy(a, b, cost_threshold, &cost)) {
  322. HistogramAdd(a, b, out);
  323. out->bit_cost_ = cost;
  324. out->palette_code_bits_ = a->palette_code_bits_;
  325. }
  326. return cost - sum_cost;
  327. }
  328. // Same as HistogramAddEval(), except that the resulting histogram
  329. // is not stored. Only the cost C(a+b) - C(a) is evaluated. We omit
  330. // the term C(b) which is constant over all the evaluations.
  331. static double HistogramAddThresh(const VP8LHistogram* const a,
  332. const VP8LHistogram* const b,
  333. double cost_threshold) {
  334. double cost = -a->bit_cost_;
  335. GetCombinedHistogramEntropy(a, b, cost_threshold, &cost);
  336. return cost;
  337. }
  338. // -----------------------------------------------------------------------------
  339. // The structure to keep track of cost range for the three dominant entropy
  340. // symbols.
  341. // TODO(skal): Evaluate if float can be used here instead of double for
  342. // representing the entropy costs.
  343. typedef struct {
  344. double literal_max_;
  345. double literal_min_;
  346. double red_max_;
  347. double red_min_;
  348. double blue_max_;
  349. double blue_min_;
  350. } DominantCostRange;
  351. static void DominantCostRangeInit(DominantCostRange* const c) {
  352. c->literal_max_ = 0.;
  353. c->literal_min_ = MAX_COST;
  354. c->red_max_ = 0.;
  355. c->red_min_ = MAX_COST;
  356. c->blue_max_ = 0.;
  357. c->blue_min_ = MAX_COST;
  358. }
  359. static void UpdateDominantCostRange(
  360. const VP8LHistogram* const h, DominantCostRange* const c) {
  361. if (c->literal_max_ < h->literal_cost_) c->literal_max_ = h->literal_cost_;
  362. if (c->literal_min_ > h->literal_cost_) c->literal_min_ = h->literal_cost_;
  363. if (c->red_max_ < h->red_cost_) c->red_max_ = h->red_cost_;
  364. if (c->red_min_ > h->red_cost_) c->red_min_ = h->red_cost_;
  365. if (c->blue_max_ < h->blue_cost_) c->blue_max_ = h->blue_cost_;
  366. if (c->blue_min_ > h->blue_cost_) c->blue_min_ = h->blue_cost_;
  367. }
  368. static void UpdateHistogramCost(VP8LHistogram* const h) {
  369. uint32_t alpha_sym, red_sym, blue_sym;
  370. const double alpha_cost =
  371. PopulationCost(h->alpha_, NUM_LITERAL_CODES, &alpha_sym);
  372. const double distance_cost =
  373. PopulationCost(h->distance_, NUM_DISTANCE_CODES, NULL) +
  374. VP8LExtraCost(h->distance_, NUM_DISTANCE_CODES);
  375. const int num_codes = VP8LHistogramNumCodes(h->palette_code_bits_);
  376. h->literal_cost_ = PopulationCost(h->literal_, num_codes, NULL) +
  377. VP8LExtraCost(h->literal_ + NUM_LITERAL_CODES,
  378. NUM_LENGTH_CODES);
  379. h->red_cost_ = PopulationCost(h->red_, NUM_LITERAL_CODES, &red_sym);
  380. h->blue_cost_ = PopulationCost(h->blue_, NUM_LITERAL_CODES, &blue_sym);
  381. h->bit_cost_ = h->literal_cost_ + h->red_cost_ + h->blue_cost_ +
  382. alpha_cost + distance_cost;
  383. if ((alpha_sym | red_sym | blue_sym) == VP8L_NON_TRIVIAL_SYM) {
  384. h->trivial_symbol_ = VP8L_NON_TRIVIAL_SYM;
  385. } else {
  386. h->trivial_symbol_ =
  387. ((uint32_t)alpha_sym << 24) | (red_sym << 16) | (blue_sym << 0);
  388. }
  389. }
  390. static int GetBinIdForEntropy(double min, double max, double val) {
  391. const double range = max - min;
  392. if (range > 0.) {
  393. const double delta = val - min;
  394. return (int)((NUM_PARTITIONS - 1e-6) * delta / range);
  395. } else {
  396. return 0;
  397. }
  398. }
  399. static int GetHistoBinIndex(const VP8LHistogram* const h,
  400. const DominantCostRange* const c, int low_effort) {
  401. int bin_id = GetBinIdForEntropy(c->literal_min_, c->literal_max_,
  402. h->literal_cost_);
  403. assert(bin_id < NUM_PARTITIONS);
  404. if (!low_effort) {
  405. bin_id = bin_id * NUM_PARTITIONS
  406. + GetBinIdForEntropy(c->red_min_, c->red_max_, h->red_cost_);
  407. bin_id = bin_id * NUM_PARTITIONS
  408. + GetBinIdForEntropy(c->blue_min_, c->blue_max_, h->blue_cost_);
  409. assert(bin_id < BIN_SIZE);
  410. }
  411. return bin_id;
  412. }
  413. // Construct the histograms from backward references.
  414. static void HistogramBuild(
  415. int xsize, int histo_bits, const VP8LBackwardRefs* const backward_refs,
  416. VP8LHistogramSet* const image_histo) {
  417. int x = 0, y = 0;
  418. const int histo_xsize = VP8LSubSampleSize(xsize, histo_bits);
  419. VP8LHistogram** const histograms = image_histo->histograms;
  420. VP8LRefsCursor c = VP8LRefsCursorInit(backward_refs);
  421. assert(histo_bits > 0);
  422. while (VP8LRefsCursorOk(&c)) {
  423. const PixOrCopy* const v = c.cur_pos;
  424. const int ix = (y >> histo_bits) * histo_xsize + (x >> histo_bits);
  425. VP8LHistogramAddSinglePixOrCopy(histograms[ix], v);
  426. x += PixOrCopyLength(v);
  427. while (x >= xsize) {
  428. x -= xsize;
  429. ++y;
  430. }
  431. VP8LRefsCursorNext(&c);
  432. }
  433. }
  434. // Copies the histograms and computes its bit_cost.
  435. static void HistogramCopyAndAnalyze(
  436. VP8LHistogramSet* const orig_histo, VP8LHistogramSet* const image_histo) {
  437. int i;
  438. const int histo_size = orig_histo->size;
  439. VP8LHistogram** const orig_histograms = orig_histo->histograms;
  440. VP8LHistogram** const histograms = image_histo->histograms;
  441. for (i = 0; i < histo_size; ++i) {
  442. VP8LHistogram* const histo = orig_histograms[i];
  443. UpdateHistogramCost(histo);
  444. // Copy histograms from orig_histo[] to image_histo[].
  445. HistogramCopy(histo, histograms[i]);
  446. }
  447. }
  448. // Partition histograms to different entropy bins for three dominant (literal,
  449. // red and blue) symbol costs and compute the histogram aggregate bit_cost.
  450. static void HistogramAnalyzeEntropyBin(VP8LHistogramSet* const image_histo,
  451. uint16_t* const bin_map,
  452. int low_effort) {
  453. int i;
  454. VP8LHistogram** const histograms = image_histo->histograms;
  455. const int histo_size = image_histo->size;
  456. DominantCostRange cost_range;
  457. DominantCostRangeInit(&cost_range);
  458. // Analyze the dominant (literal, red and blue) entropy costs.
  459. for (i = 0; i < histo_size; ++i) {
  460. UpdateDominantCostRange(histograms[i], &cost_range);
  461. }
  462. // bin-hash histograms on three of the dominant (literal, red and blue)
  463. // symbol costs and store the resulting bin_id for each histogram.
  464. for (i = 0; i < histo_size; ++i) {
  465. bin_map[i] = GetHistoBinIndex(histograms[i], &cost_range, low_effort);
  466. }
  467. }
  468. // Compact image_histo[] by merging some histograms with same bin_id together if
  469. // it's advantageous.
  470. static VP8LHistogram* HistogramCombineEntropyBin(
  471. VP8LHistogramSet* const image_histo,
  472. VP8LHistogram* cur_combo,
  473. const uint16_t* const bin_map, int bin_map_size, int num_bins,
  474. double combine_cost_factor, int low_effort) {
  475. VP8LHistogram** const histograms = image_histo->histograms;
  476. int idx;
  477. // Work in-place: processed histograms are put at the beginning of
  478. // image_histo[]. At the end, we just have to truncate the array.
  479. int size = 0;
  480. struct {
  481. int16_t first; // position of the histogram that accumulates all
  482. // histograms with the same bin_id
  483. uint16_t num_combine_failures; // number of combine failures per bin_id
  484. } bin_info[BIN_SIZE];
  485. assert(num_bins <= BIN_SIZE);
  486. for (idx = 0; idx < num_bins; ++idx) {
  487. bin_info[idx].first = -1;
  488. bin_info[idx].num_combine_failures = 0;
  489. }
  490. for (idx = 0; idx < bin_map_size; ++idx) {
  491. const int bin_id = bin_map[idx];
  492. const int first = bin_info[bin_id].first;
  493. assert(size <= idx);
  494. if (first == -1) {
  495. // just move histogram #idx to its final position
  496. histograms[size] = histograms[idx];
  497. bin_info[bin_id].first = size++;
  498. } else if (low_effort) {
  499. HistogramAdd(histograms[idx], histograms[first], histograms[first]);
  500. } else {
  501. // try to merge #idx into #first (both share the same bin_id)
  502. const double bit_cost = histograms[idx]->bit_cost_;
  503. const double bit_cost_thresh = -bit_cost * combine_cost_factor;
  504. const double curr_cost_diff =
  505. HistogramAddEval(histograms[first], histograms[idx],
  506. cur_combo, bit_cost_thresh);
  507. if (curr_cost_diff < bit_cost_thresh) {
  508. // Try to merge two histograms only if the combo is a trivial one or
  509. // the two candidate histograms are already non-trivial.
  510. // For some images, 'try_combine' turns out to be false for a lot of
  511. // histogram pairs. In that case, we fallback to combining
  512. // histograms as usual to avoid increasing the header size.
  513. const int try_combine =
  514. (cur_combo->trivial_symbol_ != VP8L_NON_TRIVIAL_SYM) ||
  515. ((histograms[idx]->trivial_symbol_ == VP8L_NON_TRIVIAL_SYM) &&
  516. (histograms[first]->trivial_symbol_ == VP8L_NON_TRIVIAL_SYM));
  517. const int max_combine_failures = 32;
  518. if (try_combine ||
  519. bin_info[bin_id].num_combine_failures >= max_combine_failures) {
  520. // move the (better) merged histogram to its final slot
  521. HistogramSwap(&cur_combo, &histograms[first]);
  522. } else {
  523. histograms[size++] = histograms[idx];
  524. ++bin_info[bin_id].num_combine_failures;
  525. }
  526. } else {
  527. histograms[size++] = histograms[idx];
  528. }
  529. }
  530. }
  531. image_histo->size = size;
  532. if (low_effort) {
  533. // for low_effort case, update the final cost when everything is merged
  534. for (idx = 0; idx < size; ++idx) {
  535. UpdateHistogramCost(histograms[idx]);
  536. }
  537. }
  538. return cur_combo;
  539. }
  540. static uint32_t MyRand(uint32_t* const seed) {
  541. *seed = (*seed * 16807ull) & 0xffffffffu;
  542. if (*seed == 0) {
  543. *seed = 1;
  544. }
  545. return *seed;
  546. }
  547. // -----------------------------------------------------------------------------
  548. // Histogram pairs priority queue
  549. // Pair of histograms. Negative idx1 value means that pair is out-of-date.
  550. typedef struct {
  551. int idx1;
  552. int idx2;
  553. double cost_diff;
  554. double cost_combo;
  555. } HistogramPair;
  556. typedef struct {
  557. HistogramPair* queue;
  558. int size;
  559. int max_size;
  560. } HistoQueue;
  561. static int HistoQueueInit(HistoQueue* const histo_queue, const int max_index) {
  562. histo_queue->size = 0;
  563. // max_index^2 for the queue size is safe. If you look at
  564. // HistogramCombineGreedy, and imagine that UpdateQueueFront always pushes
  565. // data to the queue, you insert at most:
  566. // - max_index*(max_index-1)/2 (the first two for loops)
  567. // - max_index - 1 in the last for loop at the first iteration of the while
  568. // loop, max_index - 2 at the second iteration ... therefore
  569. // max_index*(max_index-1)/2 overall too
  570. histo_queue->max_size = max_index * max_index;
  571. // We allocate max_size + 1 because the last element at index "size" is
  572. // used as temporary data (and it could be up to max_size).
  573. histo_queue->queue = (HistogramPair*)WebPSafeMalloc(
  574. histo_queue->max_size + 1, sizeof(*histo_queue->queue));
  575. return histo_queue->queue != NULL;
  576. }
  577. static void HistoQueueClear(HistoQueue* const histo_queue) {
  578. assert(histo_queue != NULL);
  579. WebPSafeFree(histo_queue->queue);
  580. }
  581. static void SwapHistogramPairs(HistogramPair *p1,
  582. HistogramPair *p2) {
  583. const HistogramPair tmp = *p1;
  584. *p1 = *p2;
  585. *p2 = tmp;
  586. }
  587. // Given a valid priority queue in range [0, queue_size) this function checks
  588. // whether histo_queue[queue_size] should be accepted and swaps it with the
  589. // front if it is smaller. Otherwise, it leaves it as is.
  590. static void UpdateQueueFront(HistoQueue* const histo_queue) {
  591. if (histo_queue->queue[histo_queue->size].cost_diff >= 0) return;
  592. if (histo_queue->queue[histo_queue->size].cost_diff <
  593. histo_queue->queue[0].cost_diff) {
  594. SwapHistogramPairs(histo_queue->queue,
  595. histo_queue->queue + histo_queue->size);
  596. }
  597. ++histo_queue->size;
  598. // We cannot add more elements than the capacity.
  599. // The allocation adds an extra element to the official capacity so that
  600. // histo_queue->queue[histo_queue->max_size] is read/written within bound.
  601. assert(histo_queue->size <= histo_queue->max_size);
  602. }
  603. // -----------------------------------------------------------------------------
  604. static void PreparePair(VP8LHistogram** histograms, int idx1, int idx2,
  605. HistogramPair* const pair) {
  606. VP8LHistogram* h1;
  607. VP8LHistogram* h2;
  608. double sum_cost;
  609. if (idx1 > idx2) {
  610. const int tmp = idx2;
  611. idx2 = idx1;
  612. idx1 = tmp;
  613. }
  614. pair->idx1 = idx1;
  615. pair->idx2 = idx2;
  616. h1 = histograms[idx1];
  617. h2 = histograms[idx2];
  618. sum_cost = h1->bit_cost_ + h2->bit_cost_;
  619. pair->cost_combo = 0.;
  620. GetCombinedHistogramEntropy(h1, h2, sum_cost, &pair->cost_combo);
  621. pair->cost_diff = pair->cost_combo - sum_cost;
  622. }
  623. // Combines histograms by continuously choosing the one with the highest cost
  624. // reduction.
  625. static int HistogramCombineGreedy(VP8LHistogramSet* const image_histo) {
  626. int ok = 0;
  627. int image_histo_size = image_histo->size;
  628. int i, j;
  629. VP8LHistogram** const histograms = image_histo->histograms;
  630. // Indexes of remaining histograms.
  631. int* const clusters =
  632. (int*)WebPSafeMalloc(image_histo_size, sizeof(*clusters));
  633. // Priority queue of histogram pairs.
  634. HistoQueue histo_queue;
  635. if (!HistoQueueInit(&histo_queue, image_histo_size) || clusters == NULL) {
  636. goto End;
  637. }
  638. for (i = 0; i < image_histo_size; ++i) {
  639. // Initialize clusters indexes.
  640. clusters[i] = i;
  641. for (j = i + 1; j < image_histo_size; ++j) {
  642. // Initialize positions array.
  643. PreparePair(histograms, i, j, &histo_queue.queue[histo_queue.size]);
  644. UpdateQueueFront(&histo_queue);
  645. }
  646. }
  647. while (image_histo_size > 1 && histo_queue.size > 0) {
  648. HistogramPair* copy_to;
  649. const int idx1 = histo_queue.queue[0].idx1;
  650. const int idx2 = histo_queue.queue[0].idx2;
  651. HistogramAdd(histograms[idx2], histograms[idx1], histograms[idx1]);
  652. histograms[idx1]->bit_cost_ = histo_queue.queue[0].cost_combo;
  653. // Remove merged histogram.
  654. for (i = 0; i + 1 < image_histo_size; ++i) {
  655. if (clusters[i] >= idx2) {
  656. clusters[i] = clusters[i + 1];
  657. }
  658. }
  659. --image_histo_size;
  660. // Remove pairs intersecting the just combined best pair. This will
  661. // therefore pop the head of the queue.
  662. copy_to = histo_queue.queue;
  663. for (i = 0; i < histo_queue.size; ++i) {
  664. HistogramPair* const p = histo_queue.queue + i;
  665. if (p->idx1 == idx1 || p->idx2 == idx1 ||
  666. p->idx1 == idx2 || p->idx2 == idx2) {
  667. // Do not copy the invalid pair.
  668. continue;
  669. }
  670. if (p->cost_diff < histo_queue.queue[0].cost_diff) {
  671. // Replace the top of the queue if we found better.
  672. SwapHistogramPairs(histo_queue.queue, p);
  673. }
  674. SwapHistogramPairs(copy_to, p);
  675. ++copy_to;
  676. }
  677. histo_queue.size = (int)(copy_to - histo_queue.queue);
  678. // Push new pairs formed with combined histogram to the queue.
  679. for (i = 0; i < image_histo_size; ++i) {
  680. if (clusters[i] != idx1) {
  681. PreparePair(histograms, idx1, clusters[i],
  682. &histo_queue.queue[histo_queue.size]);
  683. UpdateQueueFront(&histo_queue);
  684. }
  685. }
  686. }
  687. // Move remaining histograms to the beginning of the array.
  688. for (i = 0; i < image_histo_size; ++i) {
  689. if (i != clusters[i]) { // swap the two histograms
  690. HistogramSwap(&histograms[i], &histograms[clusters[i]]);
  691. }
  692. }
  693. image_histo->size = image_histo_size;
  694. ok = 1;
  695. End:
  696. WebPSafeFree(clusters);
  697. HistoQueueClear(&histo_queue);
  698. return ok;
  699. }
  700. static void HistogramCombineStochastic(VP8LHistogramSet* const image_histo,
  701. VP8LHistogram* tmp_histo,
  702. VP8LHistogram* best_combo,
  703. int quality, int min_cluster_size) {
  704. int iter;
  705. uint32_t seed = 0;
  706. int tries_with_no_success = 0;
  707. int image_histo_size = image_histo->size;
  708. const int iter_mult = (quality < 25) ? 2 : 2 + (quality - 25) / 8;
  709. const int outer_iters = image_histo_size * iter_mult;
  710. const int num_pairs = image_histo_size / 2;
  711. const int num_tries_no_success = outer_iters / 2;
  712. int idx2_max = image_histo_size - 1;
  713. int do_brute_dorce = 0;
  714. VP8LHistogram** const histograms = image_histo->histograms;
  715. // Collapse similar histograms in 'image_histo'.
  716. ++min_cluster_size;
  717. for (iter = 0;
  718. iter < outer_iters && image_histo_size >= min_cluster_size;
  719. ++iter) {
  720. double best_cost_diff = 0.;
  721. int best_idx1 = -1, best_idx2 = 1;
  722. int j;
  723. int num_tries =
  724. (num_pairs < image_histo_size) ? num_pairs : image_histo_size;
  725. // Use a brute force approach if:
  726. // - stochastic has not worked for a while and
  727. // - if the number of iterations for brute force is less than the number of
  728. // iterations if we never find a match ever again stochastically (hence
  729. // num_tries times the number of remaining outer iterations).
  730. do_brute_dorce =
  731. (tries_with_no_success > 10) &&
  732. (idx2_max * (idx2_max + 1) < 2 * num_tries * (outer_iters - iter));
  733. if (do_brute_dorce) num_tries = idx2_max;
  734. seed += iter;
  735. for (j = 0; j < num_tries; ++j) {
  736. double curr_cost_diff;
  737. // Choose two histograms at random and try to combine them.
  738. uint32_t idx1, idx2;
  739. if (do_brute_dorce) {
  740. // Use a brute force approach.
  741. idx1 = (uint32_t)j;
  742. idx2 = (uint32_t)idx2_max;
  743. } else {
  744. const uint32_t tmp = (j & 7) + 1;
  745. const uint32_t diff =
  746. (tmp < 3) ? tmp : MyRand(&seed) % (image_histo_size - 1);
  747. idx1 = MyRand(&seed) % image_histo_size;
  748. idx2 = (idx1 + diff + 1) % image_histo_size;
  749. if (idx1 == idx2) {
  750. continue;
  751. }
  752. }
  753. // Calculate cost reduction on combining.
  754. curr_cost_diff = HistogramAddEval(histograms[idx1], histograms[idx2],
  755. tmp_histo, best_cost_diff);
  756. if (curr_cost_diff < best_cost_diff) { // found a better pair?
  757. HistogramSwap(&best_combo, &tmp_histo);
  758. best_cost_diff = curr_cost_diff;
  759. best_idx1 = idx1;
  760. best_idx2 = idx2;
  761. }
  762. }
  763. if (do_brute_dorce) --idx2_max;
  764. if (best_idx1 >= 0) {
  765. HistogramSwap(&best_combo, &histograms[best_idx1]);
  766. // swap best_idx2 slot with last one (which is now unused)
  767. --image_histo_size;
  768. if (idx2_max >= image_histo_size) idx2_max = image_histo_size - 1;
  769. if (best_idx2 != image_histo_size) {
  770. HistogramSwap(&histograms[image_histo_size], &histograms[best_idx2]);
  771. histograms[image_histo_size] = NULL;
  772. }
  773. tries_with_no_success = 0;
  774. }
  775. if (++tries_with_no_success >= num_tries_no_success || idx2_max == 0) {
  776. break;
  777. }
  778. }
  779. image_histo->size = image_histo_size;
  780. }
  781. // -----------------------------------------------------------------------------
  782. // Histogram refinement
  783. // Find the best 'out' histogram for each of the 'in' histograms.
  784. // Note: we assume that out[]->bit_cost_ is already up-to-date.
  785. static void HistogramRemap(const VP8LHistogramSet* const in,
  786. const VP8LHistogramSet* const out,
  787. uint16_t* const symbols) {
  788. int i;
  789. VP8LHistogram** const in_histo = in->histograms;
  790. VP8LHistogram** const out_histo = out->histograms;
  791. const int in_size = in->size;
  792. const int out_size = out->size;
  793. if (out_size > 1) {
  794. for (i = 0; i < in_size; ++i) {
  795. int best_out = 0;
  796. double best_bits = MAX_COST;
  797. int k;
  798. for (k = 0; k < out_size; ++k) {
  799. const double cur_bits =
  800. HistogramAddThresh(out_histo[k], in_histo[i], best_bits);
  801. if (k == 0 || cur_bits < best_bits) {
  802. best_bits = cur_bits;
  803. best_out = k;
  804. }
  805. }
  806. symbols[i] = best_out;
  807. }
  808. } else {
  809. assert(out_size == 1);
  810. for (i = 0; i < in_size; ++i) {
  811. symbols[i] = 0;
  812. }
  813. }
  814. // Recompute each out based on raw and symbols.
  815. for (i = 0; i < out_size; ++i) {
  816. HistogramClear(out_histo[i]);
  817. }
  818. for (i = 0; i < in_size; ++i) {
  819. const int idx = symbols[i];
  820. HistogramAdd(in_histo[i], out_histo[idx], out_histo[idx]);
  821. }
  822. }
  823. static double GetCombineCostFactor(int histo_size, int quality) {
  824. double combine_cost_factor = 0.16;
  825. if (quality < 90) {
  826. if (histo_size > 256) combine_cost_factor /= 2.;
  827. if (histo_size > 512) combine_cost_factor /= 2.;
  828. if (histo_size > 1024) combine_cost_factor /= 2.;
  829. if (quality <= 50) combine_cost_factor /= 2.;
  830. }
  831. return combine_cost_factor;
  832. }
  833. int VP8LGetHistoImageSymbols(int xsize, int ysize,
  834. const VP8LBackwardRefs* const refs,
  835. int quality, int low_effort,
  836. int histo_bits, int cache_bits,
  837. VP8LHistogramSet* const image_histo,
  838. VP8LHistogramSet* const tmp_histos,
  839. uint16_t* const histogram_symbols) {
  840. int ok = 0;
  841. const int histo_xsize = histo_bits ? VP8LSubSampleSize(xsize, histo_bits) : 1;
  842. const int histo_ysize = histo_bits ? VP8LSubSampleSize(ysize, histo_bits) : 1;
  843. const int image_histo_raw_size = histo_xsize * histo_ysize;
  844. VP8LHistogramSet* const orig_histo =
  845. VP8LAllocateHistogramSet(image_histo_raw_size, cache_bits);
  846. VP8LHistogram* cur_combo;
  847. // Don't attempt linear bin-partition heuristic for
  848. // histograms of small sizes (as bin_map will be very sparse) and
  849. // maximum quality q==100 (to preserve the compression gains at that level).
  850. const int entropy_combine_num_bins = low_effort ? NUM_PARTITIONS : BIN_SIZE;
  851. const int entropy_combine =
  852. (orig_histo->size > entropy_combine_num_bins * 2) && (quality < 100);
  853. if (orig_histo == NULL) goto Error;
  854. // Construct the histograms from backward references.
  855. HistogramBuild(xsize, histo_bits, refs, orig_histo);
  856. // Copies the histograms and computes its bit_cost.
  857. HistogramCopyAndAnalyze(orig_histo, image_histo);
  858. cur_combo = tmp_histos->histograms[1]; // pick up working slot
  859. if (entropy_combine) {
  860. const int bin_map_size = orig_histo->size;
  861. // Reuse histogram_symbols storage. By definition, it's guaranteed to be ok.
  862. uint16_t* const bin_map = histogram_symbols;
  863. const double combine_cost_factor =
  864. GetCombineCostFactor(image_histo_raw_size, quality);
  865. HistogramAnalyzeEntropyBin(orig_histo, bin_map, low_effort);
  866. // Collapse histograms with similar entropy.
  867. cur_combo = HistogramCombineEntropyBin(image_histo, cur_combo,
  868. bin_map, bin_map_size,
  869. entropy_combine_num_bins,
  870. combine_cost_factor, low_effort);
  871. }
  872. // Don't combine the histograms using stochastic and greedy heuristics for
  873. // low-effort compression mode.
  874. if (!low_effort || !entropy_combine) {
  875. const float x = quality / 100.f;
  876. // cubic ramp between 1 and MAX_HISTO_GREEDY:
  877. const int threshold_size = (int)(1 + (x * x * x) * (MAX_HISTO_GREEDY - 1));
  878. HistogramCombineStochastic(image_histo, tmp_histos->histograms[0],
  879. cur_combo, quality, threshold_size);
  880. if ((image_histo->size <= threshold_size) &&
  881. !HistogramCombineGreedy(image_histo)) {
  882. goto Error;
  883. }
  884. }
  885. // TODO(vikasa): Optimize HistogramRemap for low-effort compression mode also.
  886. // Find the optimal map from original histograms to the final ones.
  887. HistogramRemap(orig_histo, image_histo, histogram_symbols);
  888. ok = 1;
  889. Error:
  890. VP8LFreeHistogramSet(orig_histo);
  891. return ok;
  892. }