entropy_encode.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. /* Copyright 2010 Google Inc. All Rights Reserved.
  2. Distributed under MIT license.
  3. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
  4. */
  5. /* Entropy encoding (Huffman) utilities. */
  6. #include "./entropy_encode.h"
  7. #include <string.h> /* memset */
  8. #include "../common/constants.h"
  9. #include "../common/platform.h"
  10. #include <brotli/types.h>
  11. #if defined(__cplusplus) || defined(c_plusplus)
  12. extern "C" {
  13. #endif
  14. BROTLI_BOOL BrotliSetDepth(
  15. int p0, HuffmanTree* pool, uint8_t* depth, int max_depth) {
  16. int stack[16];
  17. int level = 0;
  18. int p = p0;
  19. BROTLI_DCHECK(max_depth <= 15);
  20. stack[0] = -1;
  21. while (BROTLI_TRUE) {
  22. if (pool[p].index_left_ >= 0) {
  23. level++;
  24. if (level > max_depth) return BROTLI_FALSE;
  25. stack[level] = pool[p].index_right_or_value_;
  26. p = pool[p].index_left_;
  27. continue;
  28. } else {
  29. depth[pool[p].index_right_or_value_] = (uint8_t)level;
  30. }
  31. while (level >= 0 && stack[level] == -1) level--;
  32. if (level < 0) return BROTLI_TRUE;
  33. p = stack[level];
  34. stack[level] = -1;
  35. }
  36. }
  37. /* Sort the root nodes, least popular first. */
  38. static BROTLI_INLINE BROTLI_BOOL SortHuffmanTree(
  39. const HuffmanTree* v0, const HuffmanTree* v1) {
  40. if (v0->total_count_ != v1->total_count_) {
  41. return TO_BROTLI_BOOL(v0->total_count_ < v1->total_count_);
  42. }
  43. return TO_BROTLI_BOOL(v0->index_right_or_value_ > v1->index_right_or_value_);
  44. }
  45. /* This function will create a Huffman tree.
  46. The catch here is that the tree cannot be arbitrarily deep.
  47. Brotli specifies a maximum depth of 15 bits for "code trees"
  48. and 7 bits for "code length code trees."
  49. count_limit is the value that is to be faked as the minimum value
  50. and this minimum value is raised until the tree matches the
  51. maximum length requirement.
  52. This algorithm is not of excellent performance for very long data blocks,
  53. especially when population counts are longer than 2**tree_limit, but
  54. we are not planning to use this with extremely long blocks.
  55. See http://en.wikipedia.org/wiki/Huffman_coding */
  56. void BrotliCreateHuffmanTree(const uint32_t* data,
  57. const size_t length,
  58. const int tree_limit,
  59. HuffmanTree* tree,
  60. uint8_t* depth) {
  61. uint32_t count_limit;
  62. HuffmanTree sentinel;
  63. InitHuffmanTree(&sentinel, BROTLI_UINT32_MAX, -1, -1);
  64. /* For block sizes below 64 kB, we never need to do a second iteration
  65. of this loop. Probably all of our block sizes will be smaller than
  66. that, so this loop is mostly of academic interest. If we actually
  67. would need this, we would be better off with the Katajainen algorithm. */
  68. for (count_limit = 1; ; count_limit *= 2) {
  69. size_t n = 0;
  70. size_t i;
  71. size_t j;
  72. size_t k;
  73. for (i = length; i != 0;) {
  74. --i;
  75. if (data[i]) {
  76. const uint32_t count = BROTLI_MAX(uint32_t, data[i], count_limit);
  77. InitHuffmanTree(&tree[n++], count, -1, (int16_t)i);
  78. }
  79. }
  80. if (n == 1) {
  81. depth[tree[0].index_right_or_value_] = 1; /* Only one element. */
  82. break;
  83. }
  84. SortHuffmanTreeItems(tree, n, SortHuffmanTree);
  85. /* The nodes are:
  86. [0, n): the sorted leaf nodes that we start with.
  87. [n]: we add a sentinel here.
  88. [n + 1, 2n): new parent nodes are added here, starting from
  89. (n+1). These are naturally in ascending order.
  90. [2n]: we add a sentinel at the end as well.
  91. There will be (2n+1) elements at the end. */
  92. tree[n] = sentinel;
  93. tree[n + 1] = sentinel;
  94. i = 0; /* Points to the next leaf node. */
  95. j = n + 1; /* Points to the next non-leaf node. */
  96. for (k = n - 1; k != 0; --k) {
  97. size_t left, right;
  98. if (tree[i].total_count_ <= tree[j].total_count_) {
  99. left = i;
  100. ++i;
  101. } else {
  102. left = j;
  103. ++j;
  104. }
  105. if (tree[i].total_count_ <= tree[j].total_count_) {
  106. right = i;
  107. ++i;
  108. } else {
  109. right = j;
  110. ++j;
  111. }
  112. {
  113. /* The sentinel node becomes the parent node. */
  114. size_t j_end = 2 * n - k;
  115. tree[j_end].total_count_ =
  116. tree[left].total_count_ + tree[right].total_count_;
  117. tree[j_end].index_left_ = (int16_t)left;
  118. tree[j_end].index_right_or_value_ = (int16_t)right;
  119. /* Add back the last sentinel node. */
  120. tree[j_end + 1] = sentinel;
  121. }
  122. }
  123. if (BrotliSetDepth((int)(2 * n - 1), &tree[0], depth, tree_limit)) {
  124. /* We need to pack the Huffman tree in tree_limit bits. If this was not
  125. successful, add fake entities to the lowest values and retry. */
  126. break;
  127. }
  128. }
  129. }
  130. static void Reverse(uint8_t* v, size_t start, size_t end) {
  131. --end;
  132. while (start < end) {
  133. uint8_t tmp = v[start];
  134. v[start] = v[end];
  135. v[end] = tmp;
  136. ++start;
  137. --end;
  138. }
  139. }
  140. static void BrotliWriteHuffmanTreeRepetitions(
  141. const uint8_t previous_value,
  142. const uint8_t value,
  143. size_t repetitions,
  144. size_t* tree_size,
  145. uint8_t* tree,
  146. uint8_t* extra_bits_data) {
  147. BROTLI_DCHECK(repetitions > 0);
  148. if (previous_value != value) {
  149. tree[*tree_size] = value;
  150. extra_bits_data[*tree_size] = 0;
  151. ++(*tree_size);
  152. --repetitions;
  153. }
  154. if (repetitions == 7) {
  155. tree[*tree_size] = value;
  156. extra_bits_data[*tree_size] = 0;
  157. ++(*tree_size);
  158. --repetitions;
  159. }
  160. if (repetitions < 3) {
  161. size_t i;
  162. for (i = 0; i < repetitions; ++i) {
  163. tree[*tree_size] = value;
  164. extra_bits_data[*tree_size] = 0;
  165. ++(*tree_size);
  166. }
  167. } else {
  168. size_t start = *tree_size;
  169. repetitions -= 3;
  170. while (BROTLI_TRUE) {
  171. tree[*tree_size] = BROTLI_REPEAT_PREVIOUS_CODE_LENGTH;
  172. extra_bits_data[*tree_size] = repetitions & 0x3;
  173. ++(*tree_size);
  174. repetitions >>= 2;
  175. if (repetitions == 0) {
  176. break;
  177. }
  178. --repetitions;
  179. }
  180. Reverse(tree, start, *tree_size);
  181. Reverse(extra_bits_data, start, *tree_size);
  182. }
  183. }
  184. static void BrotliWriteHuffmanTreeRepetitionsZeros(
  185. size_t repetitions,
  186. size_t* tree_size,
  187. uint8_t* tree,
  188. uint8_t* extra_bits_data) {
  189. if (repetitions == 11) {
  190. tree[*tree_size] = 0;
  191. extra_bits_data[*tree_size] = 0;
  192. ++(*tree_size);
  193. --repetitions;
  194. }
  195. if (repetitions < 3) {
  196. size_t i;
  197. for (i = 0; i < repetitions; ++i) {
  198. tree[*tree_size] = 0;
  199. extra_bits_data[*tree_size] = 0;
  200. ++(*tree_size);
  201. }
  202. } else {
  203. size_t start = *tree_size;
  204. repetitions -= 3;
  205. while (BROTLI_TRUE) {
  206. tree[*tree_size] = BROTLI_REPEAT_ZERO_CODE_LENGTH;
  207. extra_bits_data[*tree_size] = repetitions & 0x7;
  208. ++(*tree_size);
  209. repetitions >>= 3;
  210. if (repetitions == 0) {
  211. break;
  212. }
  213. --repetitions;
  214. }
  215. Reverse(tree, start, *tree_size);
  216. Reverse(extra_bits_data, start, *tree_size);
  217. }
  218. }
  219. void BrotliOptimizeHuffmanCountsForRle(size_t length, uint32_t* counts,
  220. uint8_t* good_for_rle) {
  221. size_t nonzero_count = 0;
  222. size_t stride;
  223. size_t limit;
  224. size_t sum;
  225. const size_t streak_limit = 1240;
  226. /* Let's make the Huffman code more compatible with RLE encoding. */
  227. size_t i;
  228. for (i = 0; i < length; i++) {
  229. if (counts[i]) {
  230. ++nonzero_count;
  231. }
  232. }
  233. if (nonzero_count < 16) {
  234. return;
  235. }
  236. while (length != 0 && counts[length - 1] == 0) {
  237. --length;
  238. }
  239. if (length == 0) {
  240. return; /* All zeros. */
  241. }
  242. /* Now counts[0..length - 1] does not have trailing zeros. */
  243. {
  244. size_t nonzeros = 0;
  245. uint32_t smallest_nonzero = 1 << 30;
  246. for (i = 0; i < length; ++i) {
  247. if (counts[i] != 0) {
  248. ++nonzeros;
  249. if (smallest_nonzero > counts[i]) {
  250. smallest_nonzero = counts[i];
  251. }
  252. }
  253. }
  254. if (nonzeros < 5) {
  255. /* Small histogram will model it well. */
  256. return;
  257. }
  258. if (smallest_nonzero < 4) {
  259. size_t zeros = length - nonzeros;
  260. if (zeros < 6) {
  261. for (i = 1; i < length - 1; ++i) {
  262. if (counts[i - 1] != 0 && counts[i] == 0 && counts[i + 1] != 0) {
  263. counts[i] = 1;
  264. }
  265. }
  266. }
  267. }
  268. if (nonzeros < 28) {
  269. return;
  270. }
  271. }
  272. /* 2) Let's mark all population counts that already can be encoded
  273. with an RLE code. */
  274. memset(good_for_rle, 0, length);
  275. {
  276. /* Let's not spoil any of the existing good RLE codes.
  277. Mark any seq of 0's that is longer as 5 as a good_for_rle.
  278. Mark any seq of non-0's that is longer as 7 as a good_for_rle. */
  279. uint32_t symbol = counts[0];
  280. size_t step = 0;
  281. for (i = 0; i <= length; ++i) {
  282. if (i == length || counts[i] != symbol) {
  283. if ((symbol == 0 && step >= 5) ||
  284. (symbol != 0 && step >= 7)) {
  285. size_t k;
  286. for (k = 0; k < step; ++k) {
  287. good_for_rle[i - k - 1] = 1;
  288. }
  289. }
  290. step = 1;
  291. if (i != length) {
  292. symbol = counts[i];
  293. }
  294. } else {
  295. ++step;
  296. }
  297. }
  298. }
  299. /* 3) Let's replace those population counts that lead to more RLE codes.
  300. Math here is in 24.8 fixed point representation. */
  301. stride = 0;
  302. limit = 256 * (counts[0] + counts[1] + counts[2]) / 3 + 420;
  303. sum = 0;
  304. for (i = 0; i <= length; ++i) {
  305. if (i == length || good_for_rle[i] ||
  306. (i != 0 && good_for_rle[i - 1]) ||
  307. (256 * counts[i] - limit + streak_limit) >= 2 * streak_limit) {
  308. if (stride >= 4 || (stride >= 3 && sum == 0)) {
  309. size_t k;
  310. /* The stride must end, collapse what we have, if we have enough (4). */
  311. size_t count = (sum + stride / 2) / stride;
  312. if (count == 0) {
  313. count = 1;
  314. }
  315. if (sum == 0) {
  316. /* Don't make an all zeros stride to be upgraded to ones. */
  317. count = 0;
  318. }
  319. for (k = 0; k < stride; ++k) {
  320. /* We don't want to change value at counts[i],
  321. that is already belonging to the next stride. Thus - 1. */
  322. counts[i - k - 1] = (uint32_t)count;
  323. }
  324. }
  325. stride = 0;
  326. sum = 0;
  327. if (i < length - 2) {
  328. /* All interesting strides have a count of at least 4, */
  329. /* at least when non-zeros. */
  330. limit = 256 * (counts[i] + counts[i + 1] + counts[i + 2]) / 3 + 420;
  331. } else if (i < length) {
  332. limit = 256 * counts[i];
  333. } else {
  334. limit = 0;
  335. }
  336. }
  337. ++stride;
  338. if (i != length) {
  339. sum += counts[i];
  340. if (stride >= 4) {
  341. limit = (256 * sum + stride / 2) / stride;
  342. }
  343. if (stride == 4) {
  344. limit += 120;
  345. }
  346. }
  347. }
  348. }
  349. static void DecideOverRleUse(const uint8_t* depth, const size_t length,
  350. BROTLI_BOOL* use_rle_for_non_zero,
  351. BROTLI_BOOL* use_rle_for_zero) {
  352. size_t total_reps_zero = 0;
  353. size_t total_reps_non_zero = 0;
  354. size_t count_reps_zero = 1;
  355. size_t count_reps_non_zero = 1;
  356. size_t i;
  357. for (i = 0; i < length;) {
  358. const uint8_t value = depth[i];
  359. size_t reps = 1;
  360. size_t k;
  361. for (k = i + 1; k < length && depth[k] == value; ++k) {
  362. ++reps;
  363. }
  364. if (reps >= 3 && value == 0) {
  365. total_reps_zero += reps;
  366. ++count_reps_zero;
  367. }
  368. if (reps >= 4 && value != 0) {
  369. total_reps_non_zero += reps;
  370. ++count_reps_non_zero;
  371. }
  372. i += reps;
  373. }
  374. *use_rle_for_non_zero =
  375. TO_BROTLI_BOOL(total_reps_non_zero > count_reps_non_zero * 2);
  376. *use_rle_for_zero = TO_BROTLI_BOOL(total_reps_zero > count_reps_zero * 2);
  377. }
  378. void BrotliWriteHuffmanTree(const uint8_t* depth,
  379. size_t length,
  380. size_t* tree_size,
  381. uint8_t* tree,
  382. uint8_t* extra_bits_data) {
  383. uint8_t previous_value = BROTLI_INITIAL_REPEATED_CODE_LENGTH;
  384. size_t i;
  385. BROTLI_BOOL use_rle_for_non_zero = BROTLI_FALSE;
  386. BROTLI_BOOL use_rle_for_zero = BROTLI_FALSE;
  387. /* Throw away trailing zeros. */
  388. size_t new_length = length;
  389. for (i = 0; i < length; ++i) {
  390. if (depth[length - i - 1] == 0) {
  391. --new_length;
  392. } else {
  393. break;
  394. }
  395. }
  396. /* First gather statistics on if it is a good idea to do RLE. */
  397. if (length > 50) {
  398. /* Find RLE coding for longer codes.
  399. Shorter codes seem not to benefit from RLE. */
  400. DecideOverRleUse(depth, new_length,
  401. &use_rle_for_non_zero, &use_rle_for_zero);
  402. }
  403. /* Actual RLE coding. */
  404. for (i = 0; i < new_length;) {
  405. const uint8_t value = depth[i];
  406. size_t reps = 1;
  407. if ((value != 0 && use_rle_for_non_zero) ||
  408. (value == 0 && use_rle_for_zero)) {
  409. size_t k;
  410. for (k = i + 1; k < new_length && depth[k] == value; ++k) {
  411. ++reps;
  412. }
  413. }
  414. if (value == 0) {
  415. BrotliWriteHuffmanTreeRepetitionsZeros(
  416. reps, tree_size, tree, extra_bits_data);
  417. } else {
  418. BrotliWriteHuffmanTreeRepetitions(previous_value,
  419. value, reps, tree_size,
  420. tree, extra_bits_data);
  421. previous_value = value;
  422. }
  423. i += reps;
  424. }
  425. }
  426. static uint16_t BrotliReverseBits(size_t num_bits, uint16_t bits) {
  427. static const size_t kLut[16] = { /* Pre-reversed 4-bit values. */
  428. 0x00, 0x08, 0x04, 0x0C, 0x02, 0x0A, 0x06, 0x0E,
  429. 0x01, 0x09, 0x05, 0x0D, 0x03, 0x0B, 0x07, 0x0F
  430. };
  431. size_t retval = kLut[bits & 0x0F];
  432. size_t i;
  433. for (i = 4; i < num_bits; i += 4) {
  434. retval <<= 4;
  435. bits = (uint16_t)(bits >> 4);
  436. retval |= kLut[bits & 0x0F];
  437. }
  438. retval >>= ((0 - num_bits) & 0x03);
  439. return (uint16_t)retval;
  440. }
  441. /* 0..15 are values for bits */
  442. #define MAX_HUFFMAN_BITS 16
  443. void BrotliConvertBitDepthsToSymbols(const uint8_t* depth,
  444. size_t len,
  445. uint16_t* bits) {
  446. /* In Brotli, all bit depths are [1..15]
  447. 0 bit depth means that the symbol does not exist. */
  448. uint16_t bl_count[MAX_HUFFMAN_BITS] = { 0 };
  449. uint16_t next_code[MAX_HUFFMAN_BITS];
  450. size_t i;
  451. int code = 0;
  452. for (i = 0; i < len; ++i) {
  453. ++bl_count[depth[i]];
  454. }
  455. bl_count[0] = 0;
  456. next_code[0] = 0;
  457. for (i = 1; i < MAX_HUFFMAN_BITS; ++i) {
  458. code = (code + bl_count[i - 1]) << 1;
  459. next_code[i] = (uint16_t)code;
  460. }
  461. for (i = 0; i < len; ++i) {
  462. if (depth[i]) {
  463. bits[i] = BrotliReverseBits(depth[i], next_code[depth[i]]++);
  464. }
  465. }
  466. }
  467. #if defined(__cplusplus) || defined(c_plusplus)
  468. } /* extern "C" */
  469. #endif