hash.h 15 KB

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