• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* NOLINT(build/header_guard) */
2 /* Copyright 2010 Google Inc. All Rights Reserved.
3 
4    Distributed under MIT license.
5    See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
6 */
7 
8 /* template parameters: FN */
9 
10 /* A (forgetful) hash table to the data seen by the compressor, to
11    help create backward references to previous data.
12 
13    This is a hash map of fixed size (bucket_size_) to a ring buffer of
14    fixed size (block_size_). The ring buffer contains the last block_size_
15    index positions of the given hash key in the compressed data. */
16 
17 #define HashLongestMatch HASHER()
18 
FN(HashTypeLength)19 static BROTLI_INLINE size_t FN(HashTypeLength)(void) { return 4; }
FN(StoreLookahead)20 static BROTLI_INLINE size_t FN(StoreLookahead)(void) { return 4; }
21 
22 /* HashBytes is the function that chooses the bucket to place the address in. */
FN(HashBytes)23 static uint32_t FN(HashBytes)(
24     const uint8_t* BROTLI_RESTRICT data, const int shift) {
25   uint32_t h = BROTLI_UNALIGNED_LOAD32LE(data) * kHashMul32;
26   /* The higher bits contain more mixture from the multiplication,
27      so we take our results from there. */
28   return (uint32_t)(h >> shift);
29 }
30 
31 typedef struct HashLongestMatch {
32   /* Number of hash buckets. */
33   size_t bucket_size_;
34   /* Only block_size_ newest backward references are kept,
35      and the older are forgotten. */
36   size_t block_size_;
37   /* Left-shift for computing hash bucket index from hash value. */
38   int hash_shift_;
39   /* Mask for accessing entries in a block (in a ring-buffer manner). */
40   uint32_t block_mask_;
41 
42   int block_bits_;
43   int num_last_distances_to_check_;
44 
45   /* Shortcuts. */
46   HasherCommon* common_;
47 
48   /* --- Dynamic size members --- */
49 
50   /* Number of entries in a particular bucket. */
51   uint16_t* num_;  /* uint16_t[bucket_size]; */
52 
53   /* Buckets containing block_size_ of backward references. */
54   uint32_t* buckets_;  /* uint32_t[bucket_size * block_size]; */
55 } HashLongestMatch;
56 
FN(Num)57 static BROTLI_INLINE uint16_t* FN(Num)(void* extra) {
58   return (uint16_t*)extra;
59 }
60 
FN(Initialize)61 static void FN(Initialize)(
62     HasherCommon* common, HashLongestMatch* BROTLI_RESTRICT self,
63     const BrotliEncoderParams* params) {
64   self->common_ = common;
65 
66   BROTLI_UNUSED(params);
67   self->hash_shift_ = 32 - common->params.bucket_bits;
68   self->bucket_size_ = (size_t)1 << common->params.bucket_bits;
69   self->block_size_ = (size_t)1 << common->params.block_bits;
70   self->block_mask_ = (uint32_t)(self->block_size_ - 1);
71   self->num_ = (uint16_t*)common->extra;
72   self->buckets_ = (uint32_t*)(&self->num_[self->bucket_size_]);
73   self->block_bits_ = common->params.block_bits;
74   self->num_last_distances_to_check_ =
75       common->params.num_last_distances_to_check;
76 }
77 
FN(Prepare)78 static void FN(Prepare)(
79     HashLongestMatch* BROTLI_RESTRICT self, BROTLI_BOOL one_shot,
80     size_t input_size, const uint8_t* BROTLI_RESTRICT data) {
81   uint16_t* BROTLI_RESTRICT num = self->num_;
82   /* Partial preparation is 100 times slower (per socket). */
83   size_t partial_prepare_threshold = self->bucket_size_ >> 6;
84   if (one_shot && input_size <= partial_prepare_threshold) {
85     size_t i;
86     for (i = 0; i < input_size; ++i) {
87       const uint32_t key = FN(HashBytes)(&data[i], self->hash_shift_);
88       num[key] = 0;
89     }
90   } else {
91     memset(num, 0, self->bucket_size_ * sizeof(num[0]));
92   }
93 }
94 
FN(HashMemAllocInBytes)95 static BROTLI_INLINE size_t FN(HashMemAllocInBytes)(
96     const BrotliEncoderParams* params, BROTLI_BOOL one_shot,
97     size_t input_size) {
98   size_t bucket_size = (size_t)1 << params->hasher.bucket_bits;
99   size_t block_size = (size_t)1 << params->hasher.block_bits;
100   BROTLI_UNUSED(one_shot);
101   BROTLI_UNUSED(input_size);
102   return sizeof(uint16_t) * bucket_size +
103          sizeof(uint32_t) * bucket_size * block_size;
104 }
105 
106 /* Look at 4 bytes at &data[ix & mask].
107    Compute a hash from these, and store the value of ix at that position. */
FN(Store)108 static BROTLI_INLINE void FN(Store)(
109     HashLongestMatch* BROTLI_RESTRICT self, const uint8_t* BROTLI_RESTRICT data,
110     const size_t mask, const size_t ix) {
111   const uint32_t key = FN(HashBytes)(&data[ix & mask], self->hash_shift_);
112   const size_t minor_ix = self->num_[key] & self->block_mask_;
113   const size_t offset = minor_ix + (key << self->block_bits_);
114   self->buckets_[offset] = (uint32_t)ix;
115   ++self->num_[key];
116 }
117 
FN(StoreRange)118 static BROTLI_INLINE void FN(StoreRange)(HashLongestMatch* BROTLI_RESTRICT self,
119     const uint8_t* BROTLI_RESTRICT data, const size_t mask,
120     const size_t ix_start, const size_t ix_end) {
121   size_t i;
122   for (i = ix_start; i < ix_end; ++i) {
123     FN(Store)(self, data, mask, i);
124   }
125 }
126 
FN(StitchToPreviousBlock)127 static BROTLI_INLINE void FN(StitchToPreviousBlock)(
128     HashLongestMatch* BROTLI_RESTRICT self,
129     size_t num_bytes, size_t position, const uint8_t* ringbuffer,
130     size_t ringbuffer_mask) {
131   if (num_bytes >= FN(HashTypeLength)() - 1 && position >= 3) {
132     /* Prepare the hashes for three last bytes of the last write.
133        These could not be calculated before, since they require knowledge
134        of both the previous and the current block. */
135     FN(Store)(self, ringbuffer, ringbuffer_mask, position - 3);
136     FN(Store)(self, ringbuffer, ringbuffer_mask, position - 2);
137     FN(Store)(self, ringbuffer, ringbuffer_mask, position - 1);
138   }
139 }
140 
FN(PrepareDistanceCache)141 static BROTLI_INLINE void FN(PrepareDistanceCache)(
142     HashLongestMatch* BROTLI_RESTRICT self,
143     int* BROTLI_RESTRICT distance_cache) {
144   PrepareDistanceCache(distance_cache, self->num_last_distances_to_check_);
145 }
146 
147 /* Find a longest backward match of &data[cur_ix] up to the length of
148    max_length and stores the position cur_ix in the hash table.
149 
150    REQUIRES: FN(PrepareDistanceCache) must be invoked for current distance cache
151              values; if this method is invoked repeatedly with the same distance
152              cache values, it is enough to invoke FN(PrepareDistanceCache) once.
153 
154    Does not look for matches longer than max_length.
155    Does not look for matches further away than max_backward.
156    Writes the best match into |out|.
157    |out|->score is updated only if a better match is found. */
FN(FindLongestMatch)158 static BROTLI_INLINE void FN(FindLongestMatch)(
159     HashLongestMatch* BROTLI_RESTRICT self,
160     const BrotliEncoderDictionary* dictionary,
161     const uint8_t* BROTLI_RESTRICT data, const size_t ring_buffer_mask,
162     const int* BROTLI_RESTRICT distance_cache, const size_t cur_ix,
163     const size_t max_length, const size_t max_backward,
164     const size_t dictionary_distance, const size_t max_distance,
165     HasherSearchResult* BROTLI_RESTRICT out) {
166   uint16_t* BROTLI_RESTRICT num = self->num_;
167   uint32_t* BROTLI_RESTRICT buckets = self->buckets_;
168   const size_t cur_ix_masked = cur_ix & ring_buffer_mask;
169   /* Don't accept a short copy from far away. */
170   score_t min_score = out->score;
171   score_t best_score = out->score;
172   size_t best_len = out->len;
173   size_t i;
174   out->len = 0;
175   out->len_code_delta = 0;
176   /* Try last distance first. */
177   for (i = 0; i < (size_t)self->num_last_distances_to_check_; ++i) {
178     const size_t backward = (size_t)distance_cache[i];
179     size_t prev_ix = (size_t)(cur_ix - backward);
180     if (prev_ix >= cur_ix) {
181       continue;
182     }
183     if (BROTLI_PREDICT_FALSE(backward > max_backward)) {
184       continue;
185     }
186     prev_ix &= ring_buffer_mask;
187 
188     if (cur_ix_masked + best_len > ring_buffer_mask ||
189         prev_ix + best_len > ring_buffer_mask ||
190         data[cur_ix_masked + best_len] != data[prev_ix + best_len]) {
191       continue;
192     }
193     {
194       const size_t len = FindMatchLengthWithLimit(&data[prev_ix],
195                                                   &data[cur_ix_masked],
196                                                   max_length);
197       if (len >= 3 || (len == 2 && i < 2)) {
198         /* Comparing for >= 2 does not change the semantics, but just saves for
199            a few unnecessary binary logarithms in backward reference score,
200            since we are not interested in such short matches. */
201         score_t score = BackwardReferenceScoreUsingLastDistance(len);
202         if (best_score < score) {
203           if (i != 0) score -= BackwardReferencePenaltyUsingLastDistance(i);
204           if (best_score < score) {
205             best_score = score;
206             best_len = len;
207             out->len = best_len;
208             out->distance = backward;
209             out->score = best_score;
210           }
211         }
212       }
213     }
214   }
215   {
216     const uint32_t key =
217         FN(HashBytes)(&data[cur_ix_masked], self->hash_shift_);
218     uint32_t* BROTLI_RESTRICT bucket = &buckets[key << self->block_bits_];
219     const size_t down =
220         (num[key] > self->block_size_) ? (num[key] - self->block_size_) : 0u;
221     for (i = num[key]; i > down;) {
222       size_t prev_ix = bucket[--i & self->block_mask_];
223       const size_t backward = cur_ix - prev_ix;
224       if (BROTLI_PREDICT_FALSE(backward > max_backward)) {
225         break;
226       }
227       prev_ix &= ring_buffer_mask;
228       if (cur_ix_masked + best_len > ring_buffer_mask ||
229           prev_ix + best_len > ring_buffer_mask ||
230           data[cur_ix_masked + best_len] != data[prev_ix + best_len]) {
231         continue;
232       }
233       {
234         const size_t len = FindMatchLengthWithLimit(&data[prev_ix],
235                                                     &data[cur_ix_masked],
236                                                     max_length);
237         if (len >= 4) {
238           /* Comparing for >= 3 does not change the semantics, but just saves
239              for a few unnecessary binary logarithms in backward reference
240              score, since we are not interested in such short matches. */
241           score_t score = BackwardReferenceScore(len, backward);
242           if (best_score < score) {
243             best_score = score;
244             best_len = len;
245             out->len = best_len;
246             out->distance = backward;
247             out->score = best_score;
248           }
249         }
250       }
251     }
252     bucket[num[key] & self->block_mask_] = (uint32_t)cur_ix;
253     ++num[key];
254   }
255   if (min_score == out->score) {
256     SearchInStaticDictionary(dictionary,
257         self->common_, &data[cur_ix_masked], max_length, dictionary_distance,
258         max_distance, out, BROTLI_FALSE);
259   }
260 }
261 
262 #undef HashLongestMatch
263