histogram.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  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.h"
  17. #include "./histogram.h"
  18. #include "../dsp/lossless.h"
  19. #include "../utils/utils.h"
  20. #define MAX_COST 1.e38
  21. // Number of partitions for the three dominant (literal, red and blue) symbol
  22. // costs.
  23. #define NUM_PARTITIONS 4
  24. // The size of the bin-hash corresponding to the three dominant costs.
  25. #define BIN_SIZE (NUM_PARTITIONS * NUM_PARTITIONS * NUM_PARTITIONS)
  26. static void HistogramClear(VP8LHistogram* const p) {
  27. uint32_t* const literal = p->literal_;
  28. const int cache_bits = p->palette_code_bits_;
  29. const int histo_size = VP8LGetHistogramSize(cache_bits);
  30. memset(p, 0, histo_size);
  31. p->palette_code_bits_ = cache_bits;
  32. p->literal_ = literal;
  33. }
  34. static void HistogramCopy(const VP8LHistogram* const src,
  35. VP8LHistogram* const dst) {
  36. uint32_t* const dst_literal = dst->literal_;
  37. const int dst_cache_bits = dst->palette_code_bits_;
  38. const int histo_size = VP8LGetHistogramSize(dst_cache_bits);
  39. assert(src->palette_code_bits_ == dst_cache_bits);
  40. memcpy(dst, src, histo_size);
  41. dst->literal_ = dst_literal;
  42. }
  43. int VP8LGetHistogramSize(int cache_bits) {
  44. const int literal_size = VP8LHistogramNumCodes(cache_bits);
  45. const size_t total_size = sizeof(VP8LHistogram) + sizeof(int) * literal_size;
  46. assert(total_size <= (size_t)0x7fffffff);
  47. return (int)total_size;
  48. }
  49. void VP8LFreeHistogram(VP8LHistogram* const histo) {
  50. WebPSafeFree(histo);
  51. }
  52. void VP8LFreeHistogramSet(VP8LHistogramSet* const histo) {
  53. WebPSafeFree(histo);
  54. }
  55. void VP8LHistogramStoreRefs(const VP8LBackwardRefs* const refs,
  56. VP8LHistogram* const histo) {
  57. VP8LRefsCursor c = VP8LRefsCursorInit(refs);
  58. while (VP8LRefsCursorOk(&c)) {
  59. VP8LHistogramAddSinglePixOrCopy(histo, c.cur_pos);
  60. VP8LRefsCursorNext(&c);
  61. }
  62. }
  63. void VP8LHistogramCreate(VP8LHistogram* const p,
  64. const VP8LBackwardRefs* const refs,
  65. int palette_code_bits) {
  66. if (palette_code_bits >= 0) {
  67. p->palette_code_bits_ = palette_code_bits;
  68. }
  69. HistogramClear(p);
  70. VP8LHistogramStoreRefs(refs, p);
  71. }
  72. void VP8LHistogramInit(VP8LHistogram* const p, int palette_code_bits) {
  73. p->palette_code_bits_ = palette_code_bits;
  74. HistogramClear(p);
  75. }
  76. VP8LHistogram* VP8LAllocateHistogram(int cache_bits) {
  77. VP8LHistogram* histo = NULL;
  78. const int total_size = VP8LGetHistogramSize(cache_bits);
  79. uint8_t* const memory = (uint8_t*)WebPSafeMalloc(total_size, sizeof(*memory));
  80. if (memory == NULL) return NULL;
  81. histo = (VP8LHistogram*)memory;
  82. // literal_ won't necessary be aligned.
  83. histo->literal_ = (uint32_t*)(memory + sizeof(VP8LHistogram));
  84. VP8LHistogramInit(histo, cache_bits);
  85. return histo;
  86. }
  87. VP8LHistogramSet* VP8LAllocateHistogramSet(int size, int cache_bits) {
  88. int i;
  89. VP8LHistogramSet* set;
  90. const size_t total_size = sizeof(*set)
  91. + sizeof(*set->histograms) * size
  92. + (size_t)VP8LGetHistogramSize(cache_bits) * size;
  93. uint8_t* memory = (uint8_t*)WebPSafeMalloc(total_size, sizeof(*memory));
  94. if (memory == NULL) return NULL;
  95. set = (VP8LHistogramSet*)memory;
  96. memory += sizeof(*set);
  97. set->histograms = (VP8LHistogram**)memory;
  98. memory += size * sizeof(*set->histograms);
  99. set->max_size = size;
  100. set->size = size;
  101. for (i = 0; i < size; ++i) {
  102. set->histograms[i] = (VP8LHistogram*)memory;
  103. // literal_ won't necessary be aligned.
  104. set->histograms[i]->literal_ = (uint32_t*)(memory + sizeof(VP8LHistogram));
  105. VP8LHistogramInit(set->histograms[i], cache_bits);
  106. // There's no padding/alignment between successive histograms.
  107. memory += VP8LGetHistogramSize(cache_bits);
  108. }
  109. return set;
  110. }
  111. // -----------------------------------------------------------------------------
  112. void VP8LHistogramAddSinglePixOrCopy(VP8LHistogram* const histo,
  113. const PixOrCopy* const v) {
  114. if (PixOrCopyIsLiteral(v)) {
  115. ++histo->alpha_[PixOrCopyLiteral(v, 3)];
  116. ++histo->red_[PixOrCopyLiteral(v, 2)];
  117. ++histo->literal_[PixOrCopyLiteral(v, 1)];
  118. ++histo->blue_[PixOrCopyLiteral(v, 0)];
  119. } else if (PixOrCopyIsCacheIdx(v)) {
  120. const int literal_ix =
  121. NUM_LITERAL_CODES + NUM_LENGTH_CODES + PixOrCopyCacheIdx(v);
  122. ++histo->literal_[literal_ix];
  123. } else {
  124. int code, extra_bits;
  125. VP8LPrefixEncodeBits(PixOrCopyLength(v), &code, &extra_bits);
  126. ++histo->literal_[NUM_LITERAL_CODES + code];
  127. VP8LPrefixEncodeBits(PixOrCopyDistance(v), &code, &extra_bits);
  128. ++histo->distance_[code];
  129. }
  130. }
  131. static WEBP_INLINE double BitsEntropyRefine(int nonzeros, int sum, int max_val,
  132. double retval) {
  133. double mix;
  134. if (nonzeros < 5) {
  135. if (nonzeros <= 1) {
  136. return 0;
  137. }
  138. // Two symbols, they will be 0 and 1 in a Huffman code.
  139. // Let's mix in a bit of entropy to favor good clustering when
  140. // distributions of these are combined.
  141. if (nonzeros == 2) {
  142. return 0.99 * sum + 0.01 * retval;
  143. }
  144. // No matter what the entropy says, we cannot be better than min_limit
  145. // with Huffman coding. I am mixing a bit of entropy into the
  146. // min_limit since it produces much better (~0.5 %) compression results
  147. // perhaps because of better entropy clustering.
  148. if (nonzeros == 3) {
  149. mix = 0.95;
  150. } else {
  151. mix = 0.7; // nonzeros == 4.
  152. }
  153. } else {
  154. mix = 0.627;
  155. }
  156. {
  157. double min_limit = 2 * sum - max_val;
  158. min_limit = mix * min_limit + (1.0 - mix) * retval;
  159. return (retval < min_limit) ? min_limit : retval;
  160. }
  161. }
  162. static double BitsEntropy(const uint32_t* const array, int n) {
  163. double retval = 0.;
  164. uint32_t sum = 0;
  165. int nonzeros = 0;
  166. uint32_t max_val = 0;
  167. int i;
  168. for (i = 0; i < n; ++i) {
  169. if (array[i] != 0) {
  170. sum += array[i];
  171. ++nonzeros;
  172. retval -= VP8LFastSLog2(array[i]);
  173. if (max_val < array[i]) {
  174. max_val = array[i];
  175. }
  176. }
  177. }
  178. retval += VP8LFastSLog2(sum);
  179. return BitsEntropyRefine(nonzeros, sum, max_val, retval);
  180. }
  181. static double BitsEntropyCombined(const uint32_t* const X,
  182. const uint32_t* const Y, int n) {
  183. double retval = 0.;
  184. int sum = 0;
  185. int nonzeros = 0;
  186. int max_val = 0;
  187. int i;
  188. for (i = 0; i < n; ++i) {
  189. const int xy = X[i] + Y[i];
  190. if (xy != 0) {
  191. sum += xy;
  192. ++nonzeros;
  193. retval -= VP8LFastSLog2(xy);
  194. if (max_val < xy) {
  195. max_val = xy;
  196. }
  197. }
  198. }
  199. retval += VP8LFastSLog2(sum);
  200. return BitsEntropyRefine(nonzeros, sum, max_val, retval);
  201. }
  202. static double InitialHuffmanCost(void) {
  203. // Small bias because Huffman code length is typically not stored in
  204. // full length.
  205. static const int kHuffmanCodeOfHuffmanCodeSize = CODE_LENGTH_CODES * 3;
  206. static const double kSmallBias = 9.1;
  207. return kHuffmanCodeOfHuffmanCodeSize - kSmallBias;
  208. }
  209. // Finalize the Huffman cost based on streak numbers and length type (<3 or >=3)
  210. static double FinalHuffmanCost(const VP8LStreaks* const stats) {
  211. double retval = InitialHuffmanCost();
  212. retval += stats->counts[0] * 1.5625 + 0.234375 * stats->streaks[0][1];
  213. retval += stats->counts[1] * 2.578125 + 0.703125 * stats->streaks[1][1];
  214. retval += 1.796875 * stats->streaks[0][0];
  215. retval += 3.28125 * stats->streaks[1][0];
  216. return retval;
  217. }
  218. // Trampolines
  219. static double HuffmanCost(const uint32_t* const population, int length) {
  220. const VP8LStreaks stats = VP8LHuffmanCostCount(population, length);
  221. return FinalHuffmanCost(&stats);
  222. }
  223. static double HuffmanCostCombined(const uint32_t* const X,
  224. const uint32_t* const Y, int length) {
  225. const VP8LStreaks stats = VP8LHuffmanCostCombinedCount(X, Y, length);
  226. return FinalHuffmanCost(&stats);
  227. }
  228. // Aggregated costs
  229. static double PopulationCost(const uint32_t* const population, int length) {
  230. return BitsEntropy(population, length) + HuffmanCost(population, length);
  231. }
  232. static double GetCombinedEntropy(const uint32_t* const X,
  233. const uint32_t* const Y, int length) {
  234. return BitsEntropyCombined(X, Y, length) + HuffmanCostCombined(X, Y, length);
  235. }
  236. // Estimates the Entropy + Huffman + other block overhead size cost.
  237. double VP8LHistogramEstimateBits(const VP8LHistogram* const p) {
  238. return
  239. PopulationCost(p->literal_, VP8LHistogramNumCodes(p->palette_code_bits_))
  240. + PopulationCost(p->red_, NUM_LITERAL_CODES)
  241. + PopulationCost(p->blue_, NUM_LITERAL_CODES)
  242. + PopulationCost(p->alpha_, NUM_LITERAL_CODES)
  243. + PopulationCost(p->distance_, NUM_DISTANCE_CODES)
  244. + VP8LExtraCost(p->literal_ + NUM_LITERAL_CODES, NUM_LENGTH_CODES)
  245. + VP8LExtraCost(p->distance_, NUM_DISTANCE_CODES);
  246. }
  247. double VP8LHistogramEstimateBitsBulk(const VP8LHistogram* const p) {
  248. return
  249. BitsEntropy(p->literal_, VP8LHistogramNumCodes(p->palette_code_bits_))
  250. + BitsEntropy(p->red_, NUM_LITERAL_CODES)
  251. + BitsEntropy(p->blue_, NUM_LITERAL_CODES)
  252. + BitsEntropy(p->alpha_, NUM_LITERAL_CODES)
  253. + BitsEntropy(p->distance_, NUM_DISTANCE_CODES)
  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. assert(a->palette_code_bits_ == b->palette_code_bits_);
  265. *cost += GetCombinedEntropy(a->literal_, b->literal_,
  266. VP8LHistogramNumCodes(palette_code_bits));
  267. *cost += VP8LExtraCostCombined(a->literal_ + NUM_LITERAL_CODES,
  268. b->literal_ + NUM_LITERAL_CODES,
  269. NUM_LENGTH_CODES);
  270. if (*cost > cost_threshold) return 0;
  271. *cost += GetCombinedEntropy(a->red_, b->red_, NUM_LITERAL_CODES);
  272. if (*cost > cost_threshold) return 0;
  273. *cost += GetCombinedEntropy(a->blue_, b->blue_, NUM_LITERAL_CODES);
  274. if (*cost > cost_threshold) return 0;
  275. *cost += GetCombinedEntropy(a->alpha_, b->alpha_, NUM_LITERAL_CODES);
  276. if (*cost > cost_threshold) return 0;
  277. *cost += GetCombinedEntropy(a->distance_, b->distance_, NUM_DISTANCE_CODES);
  278. *cost += VP8LExtraCostCombined(a->distance_, b->distance_,
  279. NUM_DISTANCE_CODES);
  280. if (*cost > cost_threshold) return 0;
  281. return 1;
  282. }
  283. // Performs out = a + b, computing the cost C(a+b) - C(a) - C(b) while comparing
  284. // to the threshold value 'cost_threshold'. The score returned is
  285. // Score = C(a+b) - C(a) - C(b), where C(a) + C(b) is known and fixed.
  286. // Since the previous score passed is 'cost_threshold', we only need to compare
  287. // the partial cost against 'cost_threshold + C(a) + C(b)' to possibly bail-out
  288. // early.
  289. static double HistogramAddEval(const VP8LHistogram* const a,
  290. const VP8LHistogram* const b,
  291. VP8LHistogram* const out,
  292. double cost_threshold) {
  293. double cost = 0;
  294. const double sum_cost = a->bit_cost_ + b->bit_cost_;
  295. cost_threshold += sum_cost;
  296. if (GetCombinedHistogramEntropy(a, b, cost_threshold, &cost)) {
  297. VP8LHistogramAdd(a, b, out);
  298. out->bit_cost_ = cost;
  299. out->palette_code_bits_ = a->palette_code_bits_;
  300. }
  301. return cost - sum_cost;
  302. }
  303. // Same as HistogramAddEval(), except that the resulting histogram
  304. // is not stored. Only the cost C(a+b) - C(a) is evaluated. We omit
  305. // the term C(b) which is constant over all the evaluations.
  306. static double HistogramAddThresh(const VP8LHistogram* const a,
  307. const VP8LHistogram* const b,
  308. double cost_threshold) {
  309. double cost = -a->bit_cost_;
  310. GetCombinedHistogramEntropy(a, b, cost_threshold, &cost);
  311. return cost;
  312. }
  313. // -----------------------------------------------------------------------------
  314. // The structure to keep track of cost range for the three dominant entropy
  315. // symbols.
  316. // TODO(skal): Evaluate if float can be used here instead of double for
  317. // representing the entropy costs.
  318. typedef struct {
  319. double literal_max_;
  320. double literal_min_;
  321. double red_max_;
  322. double red_min_;
  323. double blue_max_;
  324. double blue_min_;
  325. } DominantCostRange;
  326. static void DominantCostRangeInit(DominantCostRange* const c) {
  327. c->literal_max_ = 0.;
  328. c->literal_min_ = MAX_COST;
  329. c->red_max_ = 0.;
  330. c->red_min_ = MAX_COST;
  331. c->blue_max_ = 0.;
  332. c->blue_min_ = MAX_COST;
  333. }
  334. static void UpdateDominantCostRange(
  335. const VP8LHistogram* const h, DominantCostRange* const c) {
  336. if (c->literal_max_ < h->literal_cost_) c->literal_max_ = h->literal_cost_;
  337. if (c->literal_min_ > h->literal_cost_) c->literal_min_ = h->literal_cost_;
  338. if (c->red_max_ < h->red_cost_) c->red_max_ = h->red_cost_;
  339. if (c->red_min_ > h->red_cost_) c->red_min_ = h->red_cost_;
  340. if (c->blue_max_ < h->blue_cost_) c->blue_max_ = h->blue_cost_;
  341. if (c->blue_min_ > h->blue_cost_) c->blue_min_ = h->blue_cost_;
  342. }
  343. static void UpdateHistogramCost(VP8LHistogram* const h) {
  344. const double alpha_cost = PopulationCost(h->alpha_, NUM_LITERAL_CODES);
  345. const double distance_cost =
  346. PopulationCost(h->distance_, NUM_DISTANCE_CODES) +
  347. VP8LExtraCost(h->distance_, NUM_DISTANCE_CODES);
  348. const int num_codes = VP8LHistogramNumCodes(h->palette_code_bits_);
  349. h->literal_cost_ = PopulationCost(h->literal_, num_codes) +
  350. VP8LExtraCost(h->literal_ + NUM_LITERAL_CODES,
  351. NUM_LENGTH_CODES);
  352. h->red_cost_ = PopulationCost(h->red_, NUM_LITERAL_CODES);
  353. h->blue_cost_ = PopulationCost(h->blue_, NUM_LITERAL_CODES);
  354. h->bit_cost_ = h->literal_cost_ + h->red_cost_ + h->blue_cost_ +
  355. alpha_cost + distance_cost;
  356. }
  357. static int GetBinIdForEntropy(double min, double max, double val) {
  358. const double range = max - min + 1e-6;
  359. const double delta = val - min;
  360. return (int)(NUM_PARTITIONS * delta / range);
  361. }
  362. // TODO(vikasa): Evaluate, if there's any correlation between red & blue.
  363. static int GetHistoBinIndex(
  364. const VP8LHistogram* const h, const DominantCostRange* const c) {
  365. const int bin_id =
  366. GetBinIdForEntropy(c->blue_min_, c->blue_max_, h->blue_cost_) +
  367. NUM_PARTITIONS * GetBinIdForEntropy(c->red_min_, c->red_max_,
  368. h->red_cost_) +
  369. NUM_PARTITIONS * NUM_PARTITIONS * GetBinIdForEntropy(c->literal_min_,
  370. c->literal_max_,
  371. h->literal_cost_);
  372. assert(bin_id < BIN_SIZE);
  373. return bin_id;
  374. }
  375. // Construct the histograms from backward references.
  376. static void HistogramBuild(
  377. int xsize, int histo_bits, const VP8LBackwardRefs* const backward_refs,
  378. VP8LHistogramSet* const image_histo) {
  379. int x = 0, y = 0;
  380. const int histo_xsize = VP8LSubSampleSize(xsize, histo_bits);
  381. VP8LHistogram** const histograms = image_histo->histograms;
  382. VP8LRefsCursor c = VP8LRefsCursorInit(backward_refs);
  383. assert(histo_bits > 0);
  384. // Construct the Histo from a given backward references.
  385. while (VP8LRefsCursorOk(&c)) {
  386. const PixOrCopy* const v = c.cur_pos;
  387. const int ix = (y >> histo_bits) * histo_xsize + (x >> histo_bits);
  388. VP8LHistogramAddSinglePixOrCopy(histograms[ix], v);
  389. x += PixOrCopyLength(v);
  390. while (x >= xsize) {
  391. x -= xsize;
  392. ++y;
  393. }
  394. VP8LRefsCursorNext(&c);
  395. }
  396. }
  397. // Copies the histograms and computes its bit_cost.
  398. static void HistogramCopyAndAnalyze(
  399. VP8LHistogramSet* const orig_histo, VP8LHistogramSet* const image_histo) {
  400. int i;
  401. const int histo_size = orig_histo->size;
  402. VP8LHistogram** const orig_histograms = orig_histo->histograms;
  403. VP8LHistogram** const histograms = image_histo->histograms;
  404. for (i = 0; i < histo_size; ++i) {
  405. VP8LHistogram* const histo = orig_histograms[i];
  406. UpdateHistogramCost(histo);
  407. // Copy histograms from orig_histo[] to image_histo[].
  408. HistogramCopy(histo, histograms[i]);
  409. }
  410. }
  411. // Partition histograms to different entropy bins for three dominant (literal,
  412. // red and blue) symbol costs and compute the histogram aggregate bit_cost.
  413. static void HistogramAnalyzeEntropyBin(
  414. VP8LHistogramSet* const image_histo, int16_t* const bin_map) {
  415. int i;
  416. VP8LHistogram** const histograms = image_histo->histograms;
  417. const int histo_size = image_histo->size;
  418. const int bin_depth = histo_size + 1;
  419. DominantCostRange cost_range;
  420. DominantCostRangeInit(&cost_range);
  421. // Analyze the dominant (literal, red and blue) entropy costs.
  422. for (i = 0; i < histo_size; ++i) {
  423. VP8LHistogram* const histo = histograms[i];
  424. UpdateDominantCostRange(histo, &cost_range);
  425. }
  426. // bin-hash histograms on three of the dominant (literal, red and blue)
  427. // symbol costs.
  428. for (i = 0; i < histo_size; ++i) {
  429. int num_histos;
  430. VP8LHistogram* const histo = histograms[i];
  431. const int16_t bin_id = (int16_t)GetHistoBinIndex(histo, &cost_range);
  432. const int bin_offset = bin_id * bin_depth;
  433. // bin_map[n][0] for every bin 'n' maintains the counter for the number of
  434. // histograms in that bin.
  435. // Get and increment the num_histos in that bin.
  436. num_histos = ++bin_map[bin_offset];
  437. assert(bin_offset + num_histos < bin_depth * BIN_SIZE);
  438. // Add histogram i'th index at num_histos (last) position in the bin_map.
  439. bin_map[bin_offset + num_histos] = i;
  440. }
  441. }
  442. // Compact the histogram set by moving the valid one left in the set to the
  443. // head and moving the ones that have been merged to other histograms towards
  444. // the end.
  445. // TODO(vikasa): Evaluate if this method can be avoided by altering the code
  446. // logic of HistogramCombineEntropyBin main loop.
  447. static void HistogramCompactBins(VP8LHistogramSet* const image_histo) {
  448. int start = 0;
  449. int end = image_histo->size - 1;
  450. VP8LHistogram** const histograms = image_histo->histograms;
  451. while (start < end) {
  452. while (start <= end && histograms[start] != NULL &&
  453. histograms[start]->bit_cost_ != 0.) {
  454. ++start;
  455. }
  456. while (start <= end && histograms[end]->bit_cost_ == 0.) {
  457. histograms[end] = NULL;
  458. --end;
  459. }
  460. if (start < end) {
  461. assert(histograms[start] != NULL);
  462. assert(histograms[end] != NULL);
  463. HistogramCopy(histograms[end], histograms[start]);
  464. histograms[end] = NULL;
  465. --end;
  466. }
  467. }
  468. image_histo->size = end + 1;
  469. }
  470. static void HistogramCombineEntropyBin(VP8LHistogramSet* const image_histo,
  471. VP8LHistogram* const histos,
  472. int16_t* const bin_map, int bin_depth,
  473. double combine_cost_factor) {
  474. int bin_id;
  475. VP8LHistogram* cur_combo = histos;
  476. VP8LHistogram** const histograms = image_histo->histograms;
  477. for (bin_id = 0; bin_id < BIN_SIZE; ++bin_id) {
  478. const int bin_offset = bin_id * bin_depth;
  479. const int num_histos = bin_map[bin_offset];
  480. const int idx1 = bin_map[bin_offset + 1];
  481. int n;
  482. for (n = 2; n <= num_histos; ++n) {
  483. const int idx2 = bin_map[bin_offset + n];
  484. const double bit_cost_idx2 = histograms[idx2]->bit_cost_;
  485. if (bit_cost_idx2 > 0.) {
  486. const double bit_cost_thresh = -bit_cost_idx2 * combine_cost_factor;
  487. const double curr_cost_diff =
  488. HistogramAddEval(histograms[idx1], histograms[idx2],
  489. cur_combo, bit_cost_thresh);
  490. if (curr_cost_diff < bit_cost_thresh) {
  491. HistogramCopy(cur_combo, histograms[idx1]);
  492. histograms[idx2]->bit_cost_ = 0.;
  493. }
  494. }
  495. }
  496. }
  497. HistogramCompactBins(image_histo);
  498. }
  499. static uint32_t MyRand(uint32_t *seed) {
  500. *seed *= 16807U;
  501. if (*seed == 0) {
  502. *seed = 1;
  503. }
  504. return *seed;
  505. }
  506. static void HistogramCombine(VP8LHistogramSet* const image_histo,
  507. VP8LHistogramSet* const histos, int quality) {
  508. int iter;
  509. uint32_t seed = 0;
  510. int tries_with_no_success = 0;
  511. int image_histo_size = image_histo->size;
  512. const int iter_mult = (quality < 25) ? 2 : 2 + (quality - 25) / 8;
  513. const int outer_iters = image_histo_size * iter_mult;
  514. const int num_pairs = image_histo_size / 2;
  515. const int num_tries_no_success = outer_iters / 2;
  516. const int min_cluster_size = 2;
  517. VP8LHistogram** const histograms = image_histo->histograms;
  518. VP8LHistogram* cur_combo = histos->histograms[0]; // trial histogram
  519. VP8LHistogram* best_combo = histos->histograms[1]; // best histogram so far
  520. // Collapse similar histograms in 'image_histo'.
  521. for (iter = 0;
  522. iter < outer_iters && image_histo_size >= min_cluster_size;
  523. ++iter) {
  524. double best_cost_diff = 0.;
  525. int best_idx1 = -1, best_idx2 = 1;
  526. int j;
  527. const int num_tries =
  528. (num_pairs < image_histo_size) ? num_pairs : image_histo_size;
  529. seed += iter;
  530. for (j = 0; j < num_tries; ++j) {
  531. double curr_cost_diff;
  532. // Choose two histograms at random and try to combine them.
  533. const uint32_t idx1 = MyRand(&seed) % image_histo_size;
  534. const uint32_t tmp = (j & 7) + 1;
  535. const uint32_t diff =
  536. (tmp < 3) ? tmp : MyRand(&seed) % (image_histo_size - 1);
  537. const uint32_t idx2 = (idx1 + diff + 1) % image_histo_size;
  538. if (idx1 == idx2) {
  539. continue;
  540. }
  541. // Calculate cost reduction on combining.
  542. curr_cost_diff = HistogramAddEval(histograms[idx1], histograms[idx2],
  543. cur_combo, best_cost_diff);
  544. if (curr_cost_diff < best_cost_diff) { // found a better pair?
  545. { // swap cur/best combo histograms
  546. VP8LHistogram* const tmp_histo = cur_combo;
  547. cur_combo = best_combo;
  548. best_combo = tmp_histo;
  549. }
  550. best_cost_diff = curr_cost_diff;
  551. best_idx1 = idx1;
  552. best_idx2 = idx2;
  553. }
  554. }
  555. if (best_idx1 >= 0) {
  556. HistogramCopy(best_combo, histograms[best_idx1]);
  557. // swap best_idx2 slot with last one (which is now unused)
  558. --image_histo_size;
  559. if (best_idx2 != image_histo_size) {
  560. HistogramCopy(histograms[image_histo_size], histograms[best_idx2]);
  561. histograms[image_histo_size] = NULL;
  562. }
  563. tries_with_no_success = 0;
  564. }
  565. if (++tries_with_no_success >= num_tries_no_success) {
  566. break;
  567. }
  568. }
  569. image_histo->size = image_histo_size;
  570. }
  571. // -----------------------------------------------------------------------------
  572. // Histogram refinement
  573. // Find the best 'out' histogram for each of the 'in' histograms.
  574. // Note: we assume that out[]->bit_cost_ is already up-to-date.
  575. static void HistogramRemap(const VP8LHistogramSet* const orig_histo,
  576. const VP8LHistogramSet* const image_histo,
  577. uint16_t* const symbols) {
  578. int i;
  579. VP8LHistogram** const orig_histograms = orig_histo->histograms;
  580. VP8LHistogram** const histograms = image_histo->histograms;
  581. for (i = 0; i < orig_histo->size; ++i) {
  582. int best_out = 0;
  583. double best_bits =
  584. HistogramAddThresh(histograms[0], orig_histograms[i], MAX_COST);
  585. int k;
  586. for (k = 1; k < image_histo->size; ++k) {
  587. const double cur_bits =
  588. HistogramAddThresh(histograms[k], orig_histograms[i], best_bits);
  589. if (cur_bits < best_bits) {
  590. best_bits = cur_bits;
  591. best_out = k;
  592. }
  593. }
  594. symbols[i] = best_out;
  595. }
  596. // Recompute each out based on raw and symbols.
  597. for (i = 0; i < image_histo->size; ++i) {
  598. HistogramClear(histograms[i]);
  599. }
  600. for (i = 0; i < orig_histo->size; ++i) {
  601. const int idx = symbols[i];
  602. VP8LHistogramAdd(orig_histograms[i], histograms[idx], histograms[idx]);
  603. }
  604. }
  605. static double GetCombineCostFactor(int histo_size, int quality) {
  606. double combine_cost_factor = 0.16;
  607. if (histo_size > 256) combine_cost_factor /= 2.;
  608. if (histo_size > 512) combine_cost_factor /= 2.;
  609. if (histo_size > 1024) combine_cost_factor /= 2.;
  610. if (quality <= 50) combine_cost_factor /= 2.;
  611. return combine_cost_factor;
  612. }
  613. int VP8LGetHistoImageSymbols(int xsize, int ysize,
  614. const VP8LBackwardRefs* const refs,
  615. int quality, int histo_bits, int cache_bits,
  616. VP8LHistogramSet* const image_histo,
  617. uint16_t* const histogram_symbols) {
  618. int ok = 0;
  619. const int histo_xsize = histo_bits ? VP8LSubSampleSize(xsize, histo_bits) : 1;
  620. const int histo_ysize = histo_bits ? VP8LSubSampleSize(ysize, histo_bits) : 1;
  621. const int image_histo_raw_size = histo_xsize * histo_ysize;
  622. // The bin_map for every bin follows following semantics:
  623. // bin_map[n][0] = num_histo; // The number of histograms in that bin.
  624. // bin_map[n][1] = index of first histogram in that bin;
  625. // bin_map[n][num_histo] = index of last histogram in that bin;
  626. // bin_map[n][num_histo + 1] ... bin_map[n][bin_depth - 1] = un-used indices.
  627. const int bin_depth = image_histo_raw_size + 1;
  628. int16_t* bin_map = NULL;
  629. VP8LHistogramSet* const histos = VP8LAllocateHistogramSet(2, cache_bits);
  630. VP8LHistogramSet* const orig_histo =
  631. VP8LAllocateHistogramSet(image_histo_raw_size, cache_bits);
  632. if (orig_histo == NULL || histos == NULL) {
  633. goto Error;
  634. }
  635. // Don't attempt linear bin-partition heuristic for:
  636. // histograms of small sizes, as bin_map will be very sparse and;
  637. // Higher qualities (> 90), to preserve the compression gains at those
  638. // quality settings.
  639. if (orig_histo->size > 2 * BIN_SIZE && quality < 90) {
  640. const int bin_map_size = bin_depth * BIN_SIZE;
  641. bin_map = (int16_t*)WebPSafeCalloc(bin_map_size, sizeof(*bin_map));
  642. if (bin_map == NULL) goto Error;
  643. }
  644. // Construct the histograms from backward references.
  645. HistogramBuild(xsize, histo_bits, refs, orig_histo);
  646. // Copies the histograms and computes its bit_cost.
  647. HistogramCopyAndAnalyze(orig_histo, image_histo);
  648. if (bin_map != NULL) {
  649. const double combine_cost_factor =
  650. GetCombineCostFactor(image_histo_raw_size, quality);
  651. HistogramAnalyzeEntropyBin(orig_histo, bin_map);
  652. // Collapse histograms with similar entropy.
  653. HistogramCombineEntropyBin(image_histo, histos->histograms[0],
  654. bin_map, bin_depth, combine_cost_factor);
  655. }
  656. // Collapse similar histograms by random histogram-pair compares.
  657. HistogramCombine(image_histo, histos, quality);
  658. // Find the optimal map from original histograms to the final ones.
  659. HistogramRemap(orig_histo, image_histo, histogram_symbols);
  660. ok = 1;
  661. Error:
  662. WebPSafeFree(bin_map);
  663. VP8LFreeHistogramSet(orig_histo);
  664. VP8LFreeHistogramSet(histos);
  665. return ok;
  666. }