hash_to_binary_tree_inc.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. /* NOLINT(build/header_guard) */
  2. /* Copyright 2016 Google Inc. All Rights Reserved.
  3. Distributed under MIT license.
  4. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
  5. */
  6. /* template parameters: FN, BUCKET_BITS, MAX_TREE_COMP_LENGTH,
  7. MAX_TREE_SEARCH_DEPTH */
  8. /* A (forgetful) hash table where each hash bucket contains a binary tree of
  9. sequences whose first 4 bytes share the same hash code.
  10. Each sequence is MAX_TREE_COMP_LENGTH long and is identified by its starting
  11. position in the input data. The binary tree is sorted by the lexicographic
  12. order of the sequences, and it is also a max-heap with respect to the
  13. starting positions. */
  14. #define HashToBinaryTree HASHER()
  15. #define BUCKET_SIZE (1 << BUCKET_BITS)
  16. static BROTLI_INLINE size_t FN(HashTypeLength)(void) { return 4; }
  17. static BROTLI_INLINE size_t FN(StoreLookahead)(void) {
  18. return MAX_TREE_COMP_LENGTH;
  19. }
  20. static uint32_t FN(HashBytes)(const uint8_t* data) {
  21. uint32_t h = BROTLI_UNALIGNED_LOAD32LE(data) * kHashMul32;
  22. /* The higher bits contain more mixture from the multiplication,
  23. so we take our results from there. */
  24. return h >> (32 - BUCKET_BITS);
  25. }
  26. typedef struct HashToBinaryTree {
  27. /* The window size minus 1 */
  28. size_t window_mask_;
  29. /* Hash table that maps the 4-byte hashes of the sequence to the last
  30. position where this hash was found, which is the root of the binary
  31. tree of sequences that share this hash bucket. */
  32. uint32_t buckets_[BUCKET_SIZE];
  33. /* A position used to mark a non-existent sequence, i.e. a tree is empty if
  34. its root is at invalid_pos_ and a node is a leaf if both its children
  35. are at invalid_pos_. */
  36. uint32_t invalid_pos_;
  37. /* --- Dynamic size members --- */
  38. /* The union of the binary trees of each hash bucket. The root of the tree
  39. corresponding to a hash is a sequence starting at buckets_[hash] and
  40. the left and right children of a sequence starting at pos are
  41. forest_[2 * pos] and forest_[2 * pos + 1]. */
  42. /* uint32_t forest[2 * num_nodes] */
  43. } HashToBinaryTree;
  44. static BROTLI_INLINE HashToBinaryTree* FN(Self)(HasherHandle handle) {
  45. return (HashToBinaryTree*)&(GetHasherCommon(handle)[1]);
  46. }
  47. static BROTLI_INLINE uint32_t* FN(Forest)(HashToBinaryTree* self) {
  48. return (uint32_t*)(&self[1]);
  49. }
  50. static void FN(Initialize)(
  51. HasherHandle handle, const BrotliEncoderParams* params) {
  52. HashToBinaryTree* self = FN(Self)(handle);
  53. self->window_mask_ = (1u << params->lgwin) - 1u;
  54. self->invalid_pos_ = (uint32_t)(0 - self->window_mask_);
  55. }
  56. static void FN(Prepare)(HasherHandle handle, BROTLI_BOOL one_shot,
  57. size_t input_size, const uint8_t* data) {
  58. HashToBinaryTree* self = FN(Self)(handle);
  59. uint32_t invalid_pos = self->invalid_pos_;
  60. uint32_t i;
  61. BROTLI_UNUSED(data);
  62. BROTLI_UNUSED(one_shot);
  63. BROTLI_UNUSED(input_size);
  64. for (i = 0; i < BUCKET_SIZE; i++) {
  65. self->buckets_[i] = invalid_pos;
  66. }
  67. }
  68. static BROTLI_INLINE size_t FN(HashMemAllocInBytes)(
  69. const BrotliEncoderParams* params, BROTLI_BOOL one_shot,
  70. size_t input_size) {
  71. size_t num_nodes = (size_t)1 << params->lgwin;
  72. if (one_shot && input_size < num_nodes) {
  73. num_nodes = input_size;
  74. }
  75. return sizeof(HashToBinaryTree) + 2 * sizeof(uint32_t) * num_nodes;
  76. }
  77. static BROTLI_INLINE size_t FN(LeftChildIndex)(HashToBinaryTree* self,
  78. const size_t pos) {
  79. return 2 * (pos & self->window_mask_);
  80. }
  81. static BROTLI_INLINE size_t FN(RightChildIndex)(HashToBinaryTree* self,
  82. const size_t pos) {
  83. return 2 * (pos & self->window_mask_) + 1;
  84. }
  85. /* Stores the hash of the next 4 bytes and in a single tree-traversal, the
  86. hash bucket's binary tree is searched for matches and is re-rooted at the
  87. current position.
  88. If less than MAX_TREE_COMP_LENGTH data is available, the hash bucket of the
  89. current position is searched for matches, but the state of the hash table
  90. is not changed, since we can not know the final sorting order of the
  91. current (incomplete) sequence.
  92. This function must be called with increasing cur_ix positions. */
  93. static BROTLI_INLINE BackwardMatch* FN(StoreAndFindMatches)(
  94. HashToBinaryTree* self, const uint8_t* const BROTLI_RESTRICT data,
  95. const size_t cur_ix, const size_t ring_buffer_mask, const size_t max_length,
  96. const size_t max_backward, size_t* const BROTLI_RESTRICT best_len,
  97. BackwardMatch* BROTLI_RESTRICT matches) {
  98. const size_t cur_ix_masked = cur_ix & ring_buffer_mask;
  99. const size_t max_comp_len =
  100. BROTLI_MIN(size_t, max_length, MAX_TREE_COMP_LENGTH);
  101. const BROTLI_BOOL should_reroot_tree =
  102. TO_BROTLI_BOOL(max_length >= MAX_TREE_COMP_LENGTH);
  103. const uint32_t key = FN(HashBytes)(&data[cur_ix_masked]);
  104. uint32_t* forest = FN(Forest)(self);
  105. size_t prev_ix = self->buckets_[key];
  106. /* The forest index of the rightmost node of the left subtree of the new
  107. root, updated as we traverse and re-root the tree of the hash bucket. */
  108. size_t node_left = FN(LeftChildIndex)(self, cur_ix);
  109. /* The forest index of the leftmost node of the right subtree of the new
  110. root, updated as we traverse and re-root the tree of the hash bucket. */
  111. size_t node_right = FN(RightChildIndex)(self, cur_ix);
  112. /* The match length of the rightmost node of the left subtree of the new
  113. root, updated as we traverse and re-root the tree of the hash bucket. */
  114. size_t best_len_left = 0;
  115. /* The match length of the leftmost node of the right subtree of the new
  116. root, updated as we traverse and re-root the tree of the hash bucket. */
  117. size_t best_len_right = 0;
  118. size_t depth_remaining;
  119. if (should_reroot_tree) {
  120. self->buckets_[key] = (uint32_t)cur_ix;
  121. }
  122. for (depth_remaining = MAX_TREE_SEARCH_DEPTH; ; --depth_remaining) {
  123. const size_t backward = cur_ix - prev_ix;
  124. const size_t prev_ix_masked = prev_ix & ring_buffer_mask;
  125. if (backward == 0 || backward > max_backward || depth_remaining == 0) {
  126. if (should_reroot_tree) {
  127. forest[node_left] = self->invalid_pos_;
  128. forest[node_right] = self->invalid_pos_;
  129. }
  130. break;
  131. }
  132. {
  133. const size_t cur_len = BROTLI_MIN(size_t, best_len_left, best_len_right);
  134. size_t len;
  135. BROTLI_DCHECK(cur_len <= MAX_TREE_COMP_LENGTH);
  136. len = cur_len +
  137. FindMatchLengthWithLimit(&data[cur_ix_masked + cur_len],
  138. &data[prev_ix_masked + cur_len],
  139. max_length - cur_len);
  140. BROTLI_DCHECK(
  141. 0 == memcmp(&data[cur_ix_masked], &data[prev_ix_masked], len));
  142. if (matches && len > *best_len) {
  143. *best_len = len;
  144. InitBackwardMatch(matches++, backward, len);
  145. }
  146. if (len >= max_comp_len) {
  147. if (should_reroot_tree) {
  148. forest[node_left] = forest[FN(LeftChildIndex)(self, prev_ix)];
  149. forest[node_right] = forest[FN(RightChildIndex)(self, prev_ix)];
  150. }
  151. break;
  152. }
  153. if (data[cur_ix_masked + len] > data[prev_ix_masked + len]) {
  154. best_len_left = len;
  155. if (should_reroot_tree) {
  156. forest[node_left] = (uint32_t)prev_ix;
  157. }
  158. node_left = FN(RightChildIndex)(self, prev_ix);
  159. prev_ix = forest[node_left];
  160. } else {
  161. best_len_right = len;
  162. if (should_reroot_tree) {
  163. forest[node_right] = (uint32_t)prev_ix;
  164. }
  165. node_right = FN(LeftChildIndex)(self, prev_ix);
  166. prev_ix = forest[node_right];
  167. }
  168. }
  169. }
  170. return matches;
  171. }
  172. /* Finds all backward matches of &data[cur_ix & ring_buffer_mask] up to the
  173. length of max_length and stores the position cur_ix in the hash table.
  174. Sets *num_matches to the number of matches found, and stores the found
  175. matches in matches[0] to matches[*num_matches - 1]. The matches will be
  176. sorted by strictly increasing length and (non-strictly) increasing
  177. distance. */
  178. static BROTLI_INLINE size_t FN(FindAllMatches)(HasherHandle handle,
  179. const BrotliEncoderDictionary* dictionary, const uint8_t* data,
  180. const size_t ring_buffer_mask, const size_t cur_ix,
  181. const size_t max_length, const size_t max_backward,
  182. const size_t gap, const BrotliEncoderParams* params,
  183. BackwardMatch* matches) {
  184. BackwardMatch* const orig_matches = matches;
  185. const size_t cur_ix_masked = cur_ix & ring_buffer_mask;
  186. size_t best_len = 1;
  187. const size_t short_match_max_backward =
  188. params->quality != HQ_ZOPFLIFICATION_QUALITY ? 16 : 64;
  189. size_t stop = cur_ix - short_match_max_backward;
  190. uint32_t dict_matches[BROTLI_MAX_STATIC_DICTIONARY_MATCH_LEN + 1];
  191. size_t i;
  192. if (cur_ix < short_match_max_backward) { stop = 0; }
  193. for (i = cur_ix - 1; i > stop && best_len <= 2; --i) {
  194. size_t prev_ix = i;
  195. const size_t backward = cur_ix - prev_ix;
  196. if (BROTLI_PREDICT_FALSE(backward > max_backward)) {
  197. break;
  198. }
  199. prev_ix &= ring_buffer_mask;
  200. if (data[cur_ix_masked] != data[prev_ix] ||
  201. data[cur_ix_masked + 1] != data[prev_ix + 1]) {
  202. continue;
  203. }
  204. {
  205. const size_t len =
  206. FindMatchLengthWithLimit(&data[prev_ix], &data[cur_ix_masked],
  207. max_length);
  208. if (len > best_len) {
  209. best_len = len;
  210. InitBackwardMatch(matches++, backward, len);
  211. }
  212. }
  213. }
  214. if (best_len < max_length) {
  215. matches = FN(StoreAndFindMatches)(FN(Self)(handle), data, cur_ix,
  216. ring_buffer_mask, max_length, max_backward, &best_len, matches);
  217. }
  218. for (i = 0; i <= BROTLI_MAX_STATIC_DICTIONARY_MATCH_LEN; ++i) {
  219. dict_matches[i] = kInvalidMatch;
  220. }
  221. {
  222. size_t minlen = BROTLI_MAX(size_t, 4, best_len + 1);
  223. if (BrotliFindAllStaticDictionaryMatches(dictionary,
  224. &data[cur_ix_masked], minlen, max_length, &dict_matches[0])) {
  225. size_t maxlen = BROTLI_MIN(
  226. size_t, BROTLI_MAX_STATIC_DICTIONARY_MATCH_LEN, max_length);
  227. size_t l;
  228. for (l = minlen; l <= maxlen; ++l) {
  229. uint32_t dict_id = dict_matches[l];
  230. if (dict_id < kInvalidMatch) {
  231. size_t distance = max_backward + gap + (dict_id >> 5) + 1;
  232. if (distance <= params->dist.max_distance) {
  233. InitDictionaryBackwardMatch(matches++, distance, l, dict_id & 31);
  234. }
  235. }
  236. }
  237. }
  238. }
  239. return (size_t)(matches - orig_matches);
  240. }
  241. /* Stores the hash of the next 4 bytes and re-roots the binary tree at the
  242. current sequence, without returning any matches.
  243. REQUIRES: ix + MAX_TREE_COMP_LENGTH <= end-of-current-block */
  244. static BROTLI_INLINE void FN(Store)(HasherHandle handle, const uint8_t* data,
  245. const size_t mask, const size_t ix) {
  246. HashToBinaryTree* self = FN(Self)(handle);
  247. /* Maximum distance is window size - 16, see section 9.1. of the spec. */
  248. const size_t max_backward = self->window_mask_ - BROTLI_WINDOW_GAP + 1;
  249. FN(StoreAndFindMatches)(self, data, ix, mask, MAX_TREE_COMP_LENGTH,
  250. max_backward, NULL, NULL);
  251. }
  252. static BROTLI_INLINE void FN(StoreRange)(HasherHandle handle,
  253. const uint8_t* data, const size_t mask, const size_t ix_start,
  254. const size_t ix_end) {
  255. size_t i = ix_start;
  256. size_t j = ix_start;
  257. if (ix_start + 63 <= ix_end) {
  258. i = ix_end - 63;
  259. }
  260. if (ix_start + 512 <= i) {
  261. for (; j < i; j += 8) {
  262. FN(Store)(handle, data, mask, j);
  263. }
  264. }
  265. for (; i < ix_end; ++i) {
  266. FN(Store)(handle, data, mask, i);
  267. }
  268. }
  269. static BROTLI_INLINE void FN(StitchToPreviousBlock)(HasherHandle handle,
  270. size_t num_bytes, size_t position, const uint8_t* ringbuffer,
  271. size_t ringbuffer_mask) {
  272. HashToBinaryTree* self = FN(Self)(handle);
  273. if (num_bytes >= FN(HashTypeLength)() - 1 &&
  274. position >= MAX_TREE_COMP_LENGTH) {
  275. /* Store the last `MAX_TREE_COMP_LENGTH - 1` positions in the hasher.
  276. These could not be calculated before, since they require knowledge
  277. of both the previous and the current block. */
  278. const size_t i_start = position - MAX_TREE_COMP_LENGTH + 1;
  279. const size_t i_end = BROTLI_MIN(size_t, position, i_start + num_bytes);
  280. size_t i;
  281. for (i = i_start; i < i_end; ++i) {
  282. /* Maximum distance is window size - 16, see section 9.1. of the spec.
  283. Furthermore, we have to make sure that we don't look further back
  284. from the start of the next block than the window size, otherwise we
  285. could access already overwritten areas of the ring-buffer. */
  286. const size_t max_backward =
  287. self->window_mask_ - BROTLI_MAX(size_t,
  288. BROTLI_WINDOW_GAP - 1,
  289. position - i);
  290. /* We know that i + MAX_TREE_COMP_LENGTH <= position + num_bytes, i.e. the
  291. end of the current block and that we have at least
  292. MAX_TREE_COMP_LENGTH tail in the ring-buffer. */
  293. FN(StoreAndFindMatches)(self, ringbuffer, i, ringbuffer_mask,
  294. MAX_TREE_COMP_LENGTH, max_backward, NULL, NULL);
  295. }
  296. }
  297. }
  298. #undef BUCKET_SIZE
  299. #undef HashToBinaryTree