hash.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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. /* A (forgetful) hash table to the data seen by the compressor, to
  6. help create backward references to previous data. */
  7. #ifndef BROTLI_ENC_HASH_H_
  8. #define BROTLI_ENC_HASH_H_
  9. #include <string.h> /* memcmp, memset */
  10. #include "../common/constants.h"
  11. #include "../common/dictionary.h"
  12. #include "../common/platform.h"
  13. #include <brotli/types.h>
  14. #include "./encoder_dict.h"
  15. #include "./fast_log.h"
  16. #include "./find_match_length.h"
  17. #include "./memory.h"
  18. #include "./quality.h"
  19. #include "./static_dict.h"
  20. #if defined(__cplusplus) || defined(c_plusplus)
  21. extern "C" {
  22. #endif
  23. typedef struct {
  24. /* Dynamically allocated area; first member for quickest access. */
  25. void* extra;
  26. size_t dict_num_lookups;
  27. size_t dict_num_matches;
  28. BrotliHasherParams params;
  29. /* False if hasher needs to be "prepared" before use. */
  30. BROTLI_BOOL is_prepared_;
  31. } HasherCommon;
  32. #define score_t size_t
  33. static const uint32_t kCutoffTransformsCount = 10;
  34. /* 0, 12, 27, 23, 42, 63, 56, 48, 59, 64 */
  35. /* 0+0, 4+8, 8+19, 12+11, 16+26, 20+43, 24+32, 28+20, 32+27, 36+28 */
  36. static const uint64_t kCutoffTransforms =
  37. BROTLI_MAKE_UINT64_T(0x071B520A, 0xDA2D3200);
  38. typedef struct HasherSearchResult {
  39. size_t len;
  40. size_t distance;
  41. score_t score;
  42. int len_code_delta; /* == len_code - len */
  43. } HasherSearchResult;
  44. /* kHashMul32 multiplier has these properties:
  45. * The multiplier must be odd. Otherwise we may lose the highest bit.
  46. * No long streaks of ones or zeros.
  47. * There is no effort to ensure that it is a prime, the oddity is enough
  48. for this use.
  49. * The number has been tuned heuristically against compression benchmarks. */
  50. static const uint32_t kHashMul32 = 0x1E35A7BD;
  51. static const uint64_t kHashMul64 = BROTLI_MAKE_UINT64_T(0x1E35A7BD, 0x1E35A7BD);
  52. static const uint64_t kHashMul64Long =
  53. BROTLI_MAKE_UINT64_T(0x1FE35A7Bu, 0xD3579BD3u);
  54. static BROTLI_INLINE uint32_t Hash14(const uint8_t* data) {
  55. uint32_t h = BROTLI_UNALIGNED_LOAD32LE(data) * kHashMul32;
  56. /* The higher bits contain more mixture from the multiplication,
  57. so we take our results from there. */
  58. return h >> (32 - 14);
  59. }
  60. static BROTLI_INLINE void PrepareDistanceCache(
  61. int* BROTLI_RESTRICT distance_cache, const int num_distances) {
  62. if (num_distances > 4) {
  63. int last_distance = distance_cache[0];
  64. distance_cache[4] = last_distance - 1;
  65. distance_cache[5] = last_distance + 1;
  66. distance_cache[6] = last_distance - 2;
  67. distance_cache[7] = last_distance + 2;
  68. distance_cache[8] = last_distance - 3;
  69. distance_cache[9] = last_distance + 3;
  70. if (num_distances > 10) {
  71. int next_last_distance = distance_cache[1];
  72. distance_cache[10] = next_last_distance - 1;
  73. distance_cache[11] = next_last_distance + 1;
  74. distance_cache[12] = next_last_distance - 2;
  75. distance_cache[13] = next_last_distance + 2;
  76. distance_cache[14] = next_last_distance - 3;
  77. distance_cache[15] = next_last_distance + 3;
  78. }
  79. }
  80. }
  81. #define BROTLI_LITERAL_BYTE_SCORE 135
  82. #define BROTLI_DISTANCE_BIT_PENALTY 30
  83. /* Score must be positive after applying maximal penalty. */
  84. #define BROTLI_SCORE_BASE (BROTLI_DISTANCE_BIT_PENALTY * 8 * sizeof(size_t))
  85. /* Usually, we always choose the longest backward reference. This function
  86. allows for the exception of that rule.
  87. If we choose a backward reference that is further away, it will
  88. usually be coded with more bits. We approximate this by assuming
  89. log2(distance). If the distance can be expressed in terms of the
  90. last four distances, we use some heuristic constants to estimate
  91. the bits cost. For the first up to four literals we use the bit
  92. cost of the literals from the literal cost model, after that we
  93. use the average bit cost of the cost model.
  94. This function is used to sometimes discard a longer backward reference
  95. when it is not much longer and the bit cost for encoding it is more
  96. than the saved literals.
  97. backward_reference_offset MUST be positive. */
  98. static BROTLI_INLINE score_t BackwardReferenceScore(
  99. size_t copy_length, size_t backward_reference_offset) {
  100. return BROTLI_SCORE_BASE + BROTLI_LITERAL_BYTE_SCORE * (score_t)copy_length -
  101. BROTLI_DISTANCE_BIT_PENALTY * Log2FloorNonZero(backward_reference_offset);
  102. }
  103. static BROTLI_INLINE score_t BackwardReferenceScoreUsingLastDistance(
  104. size_t copy_length) {
  105. return BROTLI_LITERAL_BYTE_SCORE * (score_t)copy_length +
  106. BROTLI_SCORE_BASE + 15;
  107. }
  108. static BROTLI_INLINE score_t BackwardReferencePenaltyUsingLastDistance(
  109. size_t distance_short_code) {
  110. return (score_t)39 + ((0x1CA10 >> (distance_short_code & 0xE)) & 0xE);
  111. }
  112. static BROTLI_INLINE BROTLI_BOOL TestStaticDictionaryItem(
  113. const BrotliEncoderDictionary* dictionary, size_t len, size_t word_idx,
  114. const uint8_t* data, size_t max_length, size_t max_backward,
  115. size_t max_distance, HasherSearchResult* out) {
  116. size_t offset;
  117. size_t matchlen;
  118. size_t backward;
  119. score_t score;
  120. offset = dictionary->words->offsets_by_length[len] + len * word_idx;
  121. if (len > max_length) {
  122. return BROTLI_FALSE;
  123. }
  124. matchlen =
  125. FindMatchLengthWithLimit(data, &dictionary->words->data[offset], len);
  126. if (matchlen + dictionary->cutoffTransformsCount <= len || matchlen == 0) {
  127. return BROTLI_FALSE;
  128. }
  129. {
  130. size_t cut = len - matchlen;
  131. size_t transform_id = (cut << 2) +
  132. (size_t)((dictionary->cutoffTransforms >> (cut * 6)) & 0x3F);
  133. backward = max_backward + 1 + word_idx +
  134. (transform_id << dictionary->words->size_bits_by_length[len]);
  135. }
  136. if (backward > max_distance) {
  137. return BROTLI_FALSE;
  138. }
  139. score = BackwardReferenceScore(matchlen, backward);
  140. if (score < out->score) {
  141. return BROTLI_FALSE;
  142. }
  143. out->len = matchlen;
  144. out->len_code_delta = (int)len - (int)matchlen;
  145. out->distance = backward;
  146. out->score = score;
  147. return BROTLI_TRUE;
  148. }
  149. static BROTLI_INLINE void SearchInStaticDictionary(
  150. const BrotliEncoderDictionary* dictionary,
  151. HasherCommon* common, const uint8_t* data, size_t max_length,
  152. size_t max_backward, size_t max_distance,
  153. HasherSearchResult* out, BROTLI_BOOL shallow) {
  154. size_t key;
  155. size_t i;
  156. if (common->dict_num_matches < (common->dict_num_lookups >> 7)) {
  157. return;
  158. }
  159. key = Hash14(data) << 1;
  160. for (i = 0; i < (shallow ? 1u : 2u); ++i, ++key) {
  161. common->dict_num_lookups++;
  162. if (dictionary->hash_table_lengths[key] != 0) {
  163. BROTLI_BOOL item_matches = TestStaticDictionaryItem(
  164. dictionary, dictionary->hash_table_lengths[key],
  165. dictionary->hash_table_words[key], data,
  166. max_length, max_backward, max_distance, out);
  167. if (item_matches) {
  168. common->dict_num_matches++;
  169. }
  170. }
  171. }
  172. }
  173. typedef struct BackwardMatch {
  174. uint32_t distance;
  175. uint32_t length_and_code;
  176. } BackwardMatch;
  177. static BROTLI_INLINE void InitBackwardMatch(BackwardMatch* self,
  178. size_t dist, size_t len) {
  179. self->distance = (uint32_t)dist;
  180. self->length_and_code = (uint32_t)(len << 5);
  181. }
  182. static BROTLI_INLINE void InitDictionaryBackwardMatch(BackwardMatch* self,
  183. size_t dist, size_t len, size_t len_code) {
  184. self->distance = (uint32_t)dist;
  185. self->length_and_code =
  186. (uint32_t)((len << 5) | (len == len_code ? 0 : len_code));
  187. }
  188. static BROTLI_INLINE size_t BackwardMatchLength(const BackwardMatch* self) {
  189. return self->length_and_code >> 5;
  190. }
  191. static BROTLI_INLINE size_t BackwardMatchLengthCode(const BackwardMatch* self) {
  192. size_t code = self->length_and_code & 31;
  193. return code ? code : BackwardMatchLength(self);
  194. }
  195. #define EXPAND_CAT(a, b) CAT(a, b)
  196. #define CAT(a, b) a ## b
  197. #define FN(X) EXPAND_CAT(X, HASHER())
  198. #define HASHER() H10
  199. #define BUCKET_BITS 17
  200. #define MAX_TREE_SEARCH_DEPTH 64
  201. #define MAX_TREE_COMP_LENGTH 128
  202. #include "./hash_to_binary_tree_inc.h" /* NOLINT(build/include) */
  203. #undef MAX_TREE_SEARCH_DEPTH
  204. #undef MAX_TREE_COMP_LENGTH
  205. #undef BUCKET_BITS
  206. #undef HASHER
  207. /* MAX_NUM_MATCHES == 64 + MAX_TREE_SEARCH_DEPTH */
  208. #define MAX_NUM_MATCHES_H10 128
  209. /* For BUCKET_SWEEP_BITS == 0, enabling the dictionary lookup makes compression
  210. a little faster (0.5% - 1%) and it compresses 0.15% better on small text
  211. and HTML inputs. */
  212. #define HASHER() H2
  213. #define BUCKET_BITS 16
  214. #define BUCKET_SWEEP_BITS 0
  215. #define HASH_LEN 5
  216. #define USE_DICTIONARY 1
  217. #include "./hash_longest_match_quickly_inc.h" /* NOLINT(build/include) */
  218. #undef BUCKET_SWEEP_BITS
  219. #undef USE_DICTIONARY
  220. #undef HASHER
  221. #define HASHER() H3
  222. #define BUCKET_SWEEP_BITS 1
  223. #define USE_DICTIONARY 0
  224. #include "./hash_longest_match_quickly_inc.h" /* NOLINT(build/include) */
  225. #undef USE_DICTIONARY
  226. #undef BUCKET_SWEEP_BITS
  227. #undef BUCKET_BITS
  228. #undef HASHER
  229. #define HASHER() H4
  230. #define BUCKET_BITS 17
  231. #define BUCKET_SWEEP_BITS 2
  232. #define USE_DICTIONARY 1
  233. #include "./hash_longest_match_quickly_inc.h" /* NOLINT(build/include) */
  234. #undef USE_DICTIONARY
  235. #undef HASH_LEN
  236. #undef BUCKET_SWEEP_BITS
  237. #undef BUCKET_BITS
  238. #undef HASHER
  239. #define HASHER() H5
  240. #include "./hash_longest_match_inc.h" /* NOLINT(build/include) */
  241. #undef HASHER
  242. #define HASHER() H6
  243. #include "./hash_longest_match64_inc.h" /* NOLINT(build/include) */
  244. #undef HASHER
  245. #define BUCKET_BITS 15
  246. #define NUM_LAST_DISTANCES_TO_CHECK 4
  247. #define NUM_BANKS 1
  248. #define BANK_BITS 16
  249. #define HASHER() H40
  250. #include "./hash_forgetful_chain_inc.h" /* NOLINT(build/include) */
  251. #undef HASHER
  252. #undef NUM_LAST_DISTANCES_TO_CHECK
  253. #define NUM_LAST_DISTANCES_TO_CHECK 10
  254. #define HASHER() H41
  255. #include "./hash_forgetful_chain_inc.h" /* NOLINT(build/include) */
  256. #undef HASHER
  257. #undef NUM_LAST_DISTANCES_TO_CHECK
  258. #undef NUM_BANKS
  259. #undef BANK_BITS
  260. #define NUM_LAST_DISTANCES_TO_CHECK 16
  261. #define NUM_BANKS 512
  262. #define BANK_BITS 9
  263. #define HASHER() H42
  264. #include "./hash_forgetful_chain_inc.h" /* NOLINT(build/include) */
  265. #undef HASHER
  266. #undef NUM_LAST_DISTANCES_TO_CHECK
  267. #undef NUM_BANKS
  268. #undef BANK_BITS
  269. #undef BUCKET_BITS
  270. #define HASHER() H54
  271. #define BUCKET_BITS 20
  272. #define BUCKET_SWEEP_BITS 2
  273. #define HASH_LEN 7
  274. #define USE_DICTIONARY 0
  275. #include "./hash_longest_match_quickly_inc.h" /* NOLINT(build/include) */
  276. #undef USE_DICTIONARY
  277. #undef HASH_LEN
  278. #undef BUCKET_SWEEP_BITS
  279. #undef BUCKET_BITS
  280. #undef HASHER
  281. /* fast large window hashers */
  282. #define HASHER() HROLLING_FAST
  283. #define CHUNKLEN 32
  284. #define JUMP 4
  285. #define NUMBUCKETS 16777216
  286. #define MASK ((NUMBUCKETS * 64) - 1)
  287. #include "./hash_rolling_inc.h" /* NOLINT(build/include) */
  288. #undef JUMP
  289. #undef HASHER
  290. #define HASHER() HROLLING
  291. #define JUMP 1
  292. #include "./hash_rolling_inc.h" /* NOLINT(build/include) */
  293. #undef MASK
  294. #undef NUMBUCKETS
  295. #undef JUMP
  296. #undef CHUNKLEN
  297. #undef HASHER
  298. #define HASHER() H35
  299. #define HASHER_A H3
  300. #define HASHER_B HROLLING_FAST
  301. #include "./hash_composite_inc.h" /* NOLINT(build/include) */
  302. #undef HASHER_A
  303. #undef HASHER_B
  304. #undef HASHER
  305. #define HASHER() H55
  306. #define HASHER_A H54
  307. #define HASHER_B HROLLING_FAST
  308. #include "./hash_composite_inc.h" /* NOLINT(build/include) */
  309. #undef HASHER_A
  310. #undef HASHER_B
  311. #undef HASHER
  312. #define HASHER() H65
  313. #define HASHER_A H6
  314. #define HASHER_B HROLLING
  315. #include "./hash_composite_inc.h" /* NOLINT(build/include) */
  316. #undef HASHER_A
  317. #undef HASHER_B
  318. #undef HASHER
  319. #undef FN
  320. #undef CAT
  321. #undef EXPAND_CAT
  322. #define FOR_SIMPLE_HASHERS(H) H(2) H(3) H(4) H(5) H(6) H(40) H(41) H(42) H(54)
  323. #define FOR_COMPOSITE_HASHERS(H) H(35) H(55) H(65)
  324. #define FOR_GENERIC_HASHERS(H) FOR_SIMPLE_HASHERS(H) FOR_COMPOSITE_HASHERS(H)
  325. #define FOR_ALL_HASHERS(H) FOR_GENERIC_HASHERS(H) H(10)
  326. typedef struct {
  327. HasherCommon common;
  328. union {
  329. #define MEMBER_(N) \
  330. H ## N _H ## N;
  331. FOR_ALL_HASHERS(MEMBER_)
  332. #undef MEMBER_
  333. } privat;
  334. } Hasher;
  335. /* MUST be invoked before any other method. */
  336. static BROTLI_INLINE void HasherInit(Hasher* hasher) {
  337. hasher->common.extra = NULL;
  338. }
  339. static BROTLI_INLINE void DestroyHasher(MemoryManager* m, Hasher* hasher) {
  340. if (hasher->common.extra == NULL) return;
  341. BROTLI_FREE(m, hasher->common.extra);
  342. }
  343. static BROTLI_INLINE void HasherReset(Hasher* hasher) {
  344. hasher->common.is_prepared_ = BROTLI_FALSE;
  345. }
  346. static BROTLI_INLINE size_t HasherSize(const BrotliEncoderParams* params,
  347. BROTLI_BOOL one_shot, const size_t input_size) {
  348. switch (params->hasher.type) {
  349. #define SIZE_(N) \
  350. case N: \
  351. return HashMemAllocInBytesH ## N(params, one_shot, input_size);
  352. FOR_ALL_HASHERS(SIZE_)
  353. #undef SIZE_
  354. default:
  355. break;
  356. }
  357. return 0; /* Default case. */
  358. }
  359. static BROTLI_INLINE void HasherSetup(MemoryManager* m, Hasher* hasher,
  360. BrotliEncoderParams* params, const uint8_t* data, size_t position,
  361. size_t input_size, BROTLI_BOOL is_last) {
  362. BROTLI_BOOL one_shot = (position == 0 && is_last);
  363. if (hasher->common.extra == NULL) {
  364. size_t alloc_size;
  365. ChooseHasher(params, &params->hasher);
  366. alloc_size = HasherSize(params, one_shot, input_size);
  367. hasher->common.extra = BROTLI_ALLOC(m, uint8_t, alloc_size);
  368. if (BROTLI_IS_OOM(m) || BROTLI_IS_NULL(hasher->common.extra)) return;
  369. hasher->common.params = params->hasher;
  370. switch (hasher->common.params.type) {
  371. #define INITIALIZE_(N) \
  372. case N: \
  373. InitializeH ## N(&hasher->common, \
  374. &hasher->privat._H ## N, params); \
  375. break;
  376. FOR_ALL_HASHERS(INITIALIZE_);
  377. #undef INITIALIZE_
  378. default:
  379. break;
  380. }
  381. HasherReset(hasher);
  382. }
  383. if (!hasher->common.is_prepared_) {
  384. switch (hasher->common.params.type) {
  385. #define PREPARE_(N) \
  386. case N: \
  387. PrepareH ## N( \
  388. &hasher->privat._H ## N, \
  389. one_shot, input_size, data); \
  390. break;
  391. FOR_ALL_HASHERS(PREPARE_)
  392. #undef PREPARE_
  393. default: break;
  394. }
  395. if (position == 0) {
  396. hasher->common.dict_num_lookups = 0;
  397. hasher->common.dict_num_matches = 0;
  398. }
  399. hasher->common.is_prepared_ = BROTLI_TRUE;
  400. }
  401. }
  402. static BROTLI_INLINE void InitOrStitchToPreviousBlock(
  403. MemoryManager* m, Hasher* hasher, const uint8_t* data, size_t mask,
  404. BrotliEncoderParams* params, size_t position, size_t input_size,
  405. BROTLI_BOOL is_last) {
  406. HasherSetup(m, hasher, params, data, position, input_size, is_last);
  407. if (BROTLI_IS_OOM(m)) return;
  408. switch (hasher->common.params.type) {
  409. #define INIT_(N) \
  410. case N: \
  411. StitchToPreviousBlockH ## N( \
  412. &hasher->privat._H ## N, \
  413. input_size, position, data, mask); \
  414. break;
  415. FOR_ALL_HASHERS(INIT_)
  416. #undef INIT_
  417. default: break;
  418. }
  419. }
  420. #if defined(__cplusplus) || defined(c_plusplus)
  421. } /* extern "C" */
  422. #endif
  423. #endif /* BROTLI_ENC_HASH_H_ */