aboutsummaryrefslogtreecommitdiff
path: root/c/dec/bit_reader.h
blob: 3d1024bcf5f4b538c06968513428044f2b00a236 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
/* Copyright 2013 Google Inc. All Rights Reserved.

   Distributed under MIT license.
   See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
*/

/* Bit reading helpers */

#ifndef BROTLI_DEC_BIT_READER_H_
#define BROTLI_DEC_BIT_READER_H_

#include <string.h>  /* memcpy */

#include <brotli/types.h>

#include "../common/constants.h"
#include "../common/platform.h"

#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif

#define BROTLI_SHORT_FILL_BIT_WINDOW_READ (sizeof(brotli_reg_t) >> 1)

/* 162 bits + 7 bytes */
#define BROTLI_FAST_INPUT_SLACK 28

BROTLI_INTERNAL extern const brotli_reg_t kBrotliBitMask[33];

static BROTLI_INLINE brotli_reg_t BitMask(brotli_reg_t n) {
  if (BROTLI_IS_CONSTANT(n) || BROTLI_HAS_UBFX) {
    /* Masking with this expression turns to a single
       "Unsigned Bit Field Extract" UBFX instruction on ARM. */
    return ~(~((brotli_reg_t)0) << n);
  } else {
    return kBrotliBitMask[n];
  }
}

typedef struct {
  brotli_reg_t val_;       /* pre-fetched bits */
  brotli_reg_t bit_pos_;   /* current bit-reading position in val_ */
  const uint8_t* next_in;  /* the byte we're reading from */
  const uint8_t* guard_in; /* position from which "fast-path" is prohibited */
  const uint8_t* last_in;  /* == next_in + avail_in */
} BrotliBitReader;

typedef struct {
  brotli_reg_t val_;
  brotli_reg_t bit_pos_;
  const uint8_t* next_in;
  size_t avail_in;
} BrotliBitReaderState;

/* Initializes the BrotliBitReader fields. */
BROTLI_INTERNAL void BrotliInitBitReader(BrotliBitReader* br);

/* Ensures that accumulator is not empty.
   May consume up to sizeof(brotli_reg_t) - 1 bytes of input.
   Returns BROTLI_FALSE if data is required but there is no input available.
   For !BROTLI_UNALIGNED_READ_FAST this function also prepares bit reader for
   aligned reading. */
BROTLI_INTERNAL BROTLI_BOOL BrotliWarmupBitReader(BrotliBitReader* br);

/* Fallback for BrotliSafeReadBits32. Extracted as noninlined method to unburden
   the main code-path. Never called for RFC brotli streams, required only for
   "large-window" mode and other extensions. */
BROTLI_INTERNAL BROTLI_NOINLINE BROTLI_BOOL BrotliSafeReadBits32Slow(
    BrotliBitReader* br, brotli_reg_t n_bits, brotli_reg_t* val);

static BROTLI_INLINE size_t
BrotliBitReaderGetAvailIn(BrotliBitReader* const br) {
  return (size_t)(br->last_in - br->next_in);
}

static BROTLI_INLINE void BrotliBitReaderSaveState(
    BrotliBitReader* const from, BrotliBitReaderState* to) {
  to->val_ = from->val_;
  to->bit_pos_ = from->bit_pos_;
  to->next_in = from->next_in;
  to->avail_in = BrotliBitReaderGetAvailIn(from);
}

static BROTLI_INLINE void BrotliBitReaderSetInput(
    BrotliBitReader* const br, const uint8_t* next_in, size_t avail_in) {
  br->next_in = next_in;
  br->last_in = (avail_in == 0) ? next_in : (next_in + avail_in);
  if (avail_in + 1 > BROTLI_FAST_INPUT_SLACK) {
    br->guard_in = next_in + (avail_in + 1 - BROTLI_FAST_INPUT_SLACK);
  } else {
    br->guard_in = next_in;
  }
}

static BROTLI_INLINE void BrotliBitReaderRestoreState(
    BrotliBitReader* const to, BrotliBitReaderState* from) {
  to->val_ = from->val_;
  to->bit_pos_ = from->bit_pos_;
  to->next_in = from->next_in;
  BrotliBitReaderSetInput(to, from->next_in, from->avail_in);
}

static BROTLI_INLINE brotli_reg_t BrotliGetAvailableBits(
    const BrotliBitReader* br) {
  return (BROTLI_64_BITS ? 64 : 32) - br->bit_pos_;
}

/* Returns amount of unread bytes the bit reader still has buffered from the
   BrotliInput, including whole bytes in br->val_. Result is capped with
   maximal ring-buffer size (larger number won't be utilized anyway). */
static BROTLI_INLINE size_t BrotliGetRemainingBytes(BrotliBitReader* br) {
  static const size_t kCap = (size_t)1 << BROTLI_LARGE_MAX_WBITS;
  size_t avail_in = BrotliBitReaderGetAvailIn(br);
  if (avail_in > kCap) return kCap;
  return avail_in + (BrotliGetAvailableBits(br) >> 3);
}

/* Checks if there is at least |num| bytes left in the input ring-buffer
   (excluding the bits remaining in br->val_). */
static BROTLI_INLINE BROTLI_BOOL BrotliCheckInputAmount(
    BrotliBitReader* const br) {
  return TO_BROTLI_BOOL(br->next_in < br->guard_in);
}

/* Guarantees that there are at least |n_bits| + 1 bits in accumulator.
   Precondition: accumulator contains at least 1 bit.
   |n_bits| should be in the range [1..24] for regular build. For portable
   non-64-bit little-endian build only 16 bits are safe to request. */
static BROTLI_INLINE void BrotliFillBitWindow(
    BrotliBitReader* const br, brotli_reg_t n_bits) {
#if (BROTLI_64_BITS)
  if (BROTLI_UNALIGNED_READ_FAST && BROTLI_IS_CONSTANT(n_bits) &&
      (n_bits <= 8)) {
    brotli_reg_t bit_pos = br->bit_pos_;
    if (bit_pos >= 56) {
      br->val_ =
          (br->val_ >> 56) | (BROTLI_UNALIGNED_LOAD64LE(br->next_in) << 8);
      br->bit_pos_ =
          bit_pos ^ 56; /* here same as -= 56 because of the if condition */
      br->next_in += 7;
    }
  } else if (BROTLI_UNALIGNED_READ_FAST && BROTLI_IS_CONSTANT(n_bits) &&
             (n_bits <= 16)) {
    brotli_reg_t bit_pos = br->bit_pos_;
    if (bit_pos >= 48) {
      br->val_ =
          (br->val_ >> 48) | (BROTLI_UNALIGNED_LOAD64LE(br->next_in) << 16);
      br->bit_pos_ =
          bit_pos ^ 48; /* here same as -= 48 because of the if condition */
      br->next_in += 6;
    }
  } else {
    brotli_reg_t bit_pos = br->bit_pos_;
    if (bit_pos >= 32) {
      br->val_ = (br->val_ >> 32) |
                 (((uint64_t)BROTLI_UNALIGNED_LOAD32LE(br->next_in)) << 32);
      br->bit_pos_ =
          bit_pos ^ 32; /* here same as -= 32 because of the if condition */
      br->next_in += BROTLI_SHORT_FILL_BIT_WINDOW_READ;
    }
  }
#else
  if (BROTLI_UNALIGNED_READ_FAST && BROTLI_IS_CONSTANT(n_bits) &&
      (n_bits <= 8)) {
    brotli_reg_t bit_pos = br->bit_pos_;
    if (bit_pos >= 24) {
      br->val_ =
          (br->val_ >> 24) | (BROTLI_UNALIGNED_LOAD32LE(br->next_in) << 8);
      br->bit_pos_ =
          bit_pos ^ 24; /* here same as -= 24 because of the if condition */
      br->next_in += 3;
    }
  } else {
    brotli_reg_t bit_pos = br->bit_pos_;
    if (bit_pos >= 16) {
      br->val_ = (br->val_ >> 16) |
                 (((brotli_reg_t)BROTLI_UNALIGNED_LOAD16LE(br->next_in)) << 16);
      br->bit_pos_ =
          bit_pos ^ 16; /* here same as -= 16 because of the if condition */
      br->next_in += BROTLI_SHORT_FILL_BIT_WINDOW_READ;
    }
  }
#endif
}

/* Mostly like BrotliFillBitWindow, but guarantees only 16 bits and reads no
   more than BROTLI_SHORT_FILL_BIT_WINDOW_READ bytes of input. */
static BROTLI_INLINE void BrotliFillBitWindow16(BrotliBitReader* const br) {
  BrotliFillBitWindow(br, 17);
}

/* Tries to pull one byte of input to accumulator.
   Returns BROTLI_FALSE if there is no input available. */
static BROTLI_INLINE BROTLI_BOOL BrotliPullByte(BrotliBitReader* const br) {
  if (br->next_in == br->last_in) {
    return BROTLI_FALSE;
  }
  br->val_ >>= 8;
#if (BROTLI_64_BITS)
  br->val_ |= ((uint64_t)*br->next_in) << 56;
#else
  br->val_ |= ((brotli_reg_t)*br->next_in) << 24;
#endif
  br->bit_pos_ -= 8;
  ++br->next_in;
  return BROTLI_TRUE;
}

/* Returns currently available bits.
   The number of valid bits could be calculated by BrotliGetAvailableBits. */
static BROTLI_INLINE brotli_reg_t BrotliGetBitsUnmasked(
    BrotliBitReader* const br) {
  return br->val_ >> br->bit_pos_;
}

/* Like BrotliGetBits, but does not mask the result.
   The result contains at least 16 valid bits. */
static BROTLI_INLINE brotli_reg_t BrotliGet16BitsUnmasked(
    BrotliBitReader* const br) {
  BrotliFillBitWindow(br, 16);
  return (brotli_reg_t)BrotliGetBitsUnmasked(br);
}

/* Returns the specified number of bits from |br| without advancing bit
   position. */
static BROTLI_INLINE brotli_reg_t BrotliGetBits(
    BrotliBitReader* const br, brotli_reg_t n_bits) {
  BrotliFillBitWindow(br, n_bits);
  return BrotliGetBitsUnmasked(br) & BitMask(n_bits);
}

/* Tries to peek the specified amount of bits. Returns BROTLI_FALSE, if there
   is not enough input. */
static BROTLI_INLINE BROTLI_BOOL BrotliSafeGetBits(
    BrotliBitReader* const br, brotli_reg_t n_bits, brotli_reg_t* val) {
  while (BrotliGetAvailableBits(br) < n_bits) {
    if (!BrotliPullByte(br)) {
      return BROTLI_FALSE;
    }
  }
  *val = BrotliGetBitsUnmasked(br) & BitMask(n_bits);
  return BROTLI_TRUE;
}

/* Advances the bit pos by |n_bits|. */
static BROTLI_INLINE void BrotliDropBits(
    BrotliBitReader* const br, brotli_reg_t n_bits) {
  br->bit_pos_ += n_bits;
}

static BROTLI_INLINE void BrotliBitReaderUnload(BrotliBitReader* br) {
  brotli_reg_t unused_bytes = BrotliGetAvailableBits(br) >> 3;
  brotli_reg_t unused_bits = unused_bytes << 3;
  br->next_in =
      (unused_bytes == 0) ? br->next_in : (br->next_in - unused_bytes);
  if (unused_bits == sizeof(br->val_) << 3) {
    br->val_ = 0;
  } else {
    br->val_ <<= unused_bits;
  }
  br->bit_pos_ += unused_bits;
}

/* Reads the specified number of bits from |br| and advances the bit pos.
   Precondition: accumulator MUST contain at least |n_bits|. */
static BROTLI_INLINE void BrotliTakeBits(BrotliBitReader* const br,
                                         brotli_reg_t n_bits,
                                         brotli_reg_t* val) {
  *val = BrotliGetBitsUnmasked(br) & BitMask(n_bits);
  BROTLI_LOG(("[BrotliTakeBits]  %d %d %d val: %6x\n",
              (int)BrotliBitReaderGetAvailIn(br), (int)br->bit_pos_,
              (int)n_bits, (int)*val));
  BrotliDropBits(br, n_bits);
}

/* Reads the specified number of bits from |br| and advances the bit pos.
   Assumes that there is enough input to perform BrotliFillBitWindow.
   Up to 24 bits are allowed to be requested from this method. */
static BROTLI_INLINE brotli_reg_t BrotliReadBits24(
    BrotliBitReader* const br, brotli_reg_t n_bits) {
  BROTLI_DCHECK(n_bits <= 24);
  if (BROTLI_64_BITS || (n_bits <= 16)) {
    brotli_reg_t val;
    BrotliFillBitWindow(br, n_bits);
    BrotliTakeBits(br, n_bits, &val);
    return val;
  } else {
    brotli_reg_t low_val;
    brotli_reg_t high_val;
    BrotliFillBitWindow(br, 16);
    BrotliTakeBits(br, 16, &low_val);
    BrotliFillBitWindow(br, 8);
    BrotliTakeBits(br, n_bits - 16, &high_val);
    return low_val | (high_val << 16);
  }
}

/* Same as BrotliReadBits24, but allows reading up to 32 bits. */
static BROTLI_INLINE brotli_reg_t BrotliReadBits32(
    BrotliBitReader* const br, brotli_reg_t n_bits) {
  BROTLI_DCHECK(n_bits <= 32);
  if (BROTLI_64_BITS || (n_bits <= 16)) {
    brotli_reg_t val;
    BrotliFillBitWindow(br, n_bits);
    BrotliTakeBits(br, n_bits, &val);
    return val;
  } else {
    brotli_reg_t low_val;
    brotli_reg_t high_val;
    BrotliFillBitWindow(br, 16);
    BrotliTakeBits(br, 16, &low_val);
    BrotliFillBitWindow(br, 16);
    BrotliTakeBits(br, n_bits - 16, &high_val);
    return low_val | (high_val << 16);
  }
}

/* Tries to read the specified amount of bits. Returns BROTLI_FALSE, if there
   is not enough input. |n_bits| MUST be positive.
   Up to 24 bits are allowed to be requested from this method. */
static BROTLI_INLINE BROTLI_BOOL BrotliSafeReadBits(
    BrotliBitReader* const br, brotli_reg_t n_bits, brotli_reg_t* val) {
  BROTLI_DCHECK(n_bits <= 24);
  while (BrotliGetAvailableBits(br) < n_bits) {
    if (!BrotliPullByte(br)) {
      return BROTLI_FALSE;
    }
  }
  BrotliTakeBits(br, n_bits, val);
  return BROTLI_TRUE;
}

/* Same as BrotliSafeReadBits, but allows reading up to 32 bits. */
static BROTLI_INLINE BROTLI_BOOL BrotliSafeReadBits32(
    BrotliBitReader* const br, brotli_reg_t n_bits, brotli_reg_t* val) {
  BROTLI_DCHECK(n_bits <= 32);
  if (BROTLI_64_BITS || (n_bits <= 24)) {
    while (BrotliGetAvailableBits(br) < n_bits) {
      if (!BrotliPullByte(br)) {
        return BROTLI_FALSE;
      }
    }
    BrotliTakeBits(br, n_bits, val);
    return BROTLI_TRUE;
  } else {
    return BrotliSafeReadBits32Slow(br, n_bits, val);
  }
}

/* Advances the bit reader position to the next byte boundary and verifies
   that any skipped bits are set to zero. */
static BROTLI_INLINE BROTLI_BOOL BrotliJumpToByteBoundary(BrotliBitReader* br) {
  brotli_reg_t pad_bits_count = BrotliGetAvailableBits(br) & 0x7;
  brotli_reg_t pad_bits = 0;
  if (pad_bits_count != 0) {
    BrotliTakeBits(br, pad_bits_count, &pad_bits);
  }
  return TO_BROTLI_BOOL(pad_bits == 0);
}

static BROTLI_INLINE void BrotliDropBytes(BrotliBitReader* br, size_t num) {
  br->next_in += num;
}

/* Copies remaining input bytes stored in the bit reader to the output. Value
   |num| may not be larger than BrotliGetRemainingBytes. The bit reader must be
   warmed up again after this. */
static BROTLI_INLINE void BrotliCopyBytes(uint8_t* dest,
                                          BrotliBitReader* br, size_t num) {
  while (BrotliGetAvailableBits(br) >= 8 && num > 0) {
    *dest = (uint8_t)BrotliGetBitsUnmasked(br);
    BrotliDropBits(br, 8);
    ++dest;
    --num;
  }
  if (num > 0) {
    memcpy(dest, br->next_in, num);
    BrotliDropBytes(br, num);
  }
}

BROTLI_UNUSED_FUNCTION void BrotliBitReaderSuppressUnusedFunctions(void) {
  BROTLI_UNUSED(&BrotliBitReaderSuppressUnusedFunctions);

  BROTLI_UNUSED(&BrotliBitReaderGetAvailIn);
  BROTLI_UNUSED(&BrotliBitReaderRestoreState);
  BROTLI_UNUSED(&BrotliBitReaderSaveState);
  BROTLI_UNUSED(&BrotliBitReaderSetInput);
  BROTLI_UNUSED(&BrotliBitReaderUnload);
  BROTLI_UNUSED(&BrotliCheckInputAmount);
  BROTLI_UNUSED(&BrotliCopyBytes);
  BROTLI_UNUSED(&BrotliFillBitWindow16);
  BROTLI_UNUSED(&BrotliGet16BitsUnmasked);
  BROTLI_UNUSED(&BrotliGetBits);
  BROTLI_UNUSED(&BrotliGetRemainingBytes);
  BROTLI_UNUSED(&BrotliJumpToByteBoundary);
  BROTLI_UNUSED(&BrotliReadBits24);
  BROTLI_UNUSED(&BrotliReadBits32);
  BROTLI_UNUSED(&BrotliSafeGetBits);
  BROTLI_UNUSED(&BrotliSafeReadBits);
  BROTLI_UNUSED(&BrotliSafeReadBits32);
}

#if defined(__cplusplus) || defined(c_plusplus)
}  /* extern "C" */
#endif

#endif  /* BROTLI_DEC_BIT_READER_H_ */