Coverage Report

Created: 2026-12-01 06:52

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libheif/libheif/bitstream.cc
Line
Count
Source
1
/*
2
 * HEIF codec.
3
 * Copyright (c) 2017 Dirk Farin <dirk.farin@gmail.com>
4
 *
5
 * This file is part of libheif.
6
 *
7
 * libheif is free software: you can redistribute it and/or modify
8
 * it under the terms of the GNU Lesser General Public License as
9
 * published by the Free Software Foundation, either version 3 of
10
 * the License, or (at your option) any later version.
11
 *
12
 * libheif is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU Lesser General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Lesser General Public License
18
 * along with libheif.  If not, see <http://www.gnu.org/licenses/>.
19
 */
20
21
#include "bitstream.h"
22
23
#include <utility>
24
#include <cstring>
25
#include <cassert>
26
27
#include "common_utils.h"
28
29
#if !defined(HAVE_BIT)
30
#include <type_traits>
31
#else
32
#include <bit>
33
#endif
34
35
1.22M
#define MAX_UVLC_LEADING_ZEROS 20
36
37
38
StreamReader_istream::StreamReader_istream(std::unique_ptr<std::istream>&& istr)
39
0
    : m_istr(std::move(istr))
40
0
{
41
0
  m_istr->seekg(0, std::ios_base::end);
42
0
  m_length = m_istr->tellg();
43
0
  m_istr->seekg(0, std::ios_base::beg);
44
0
}
45
46
uint64_t StreamReader_istream::get_position() const
47
0
{
48
0
  return m_istr->tellg();
49
0
}
50
51
StreamReader::grow_status StreamReader_istream::wait_for_file_size(uint64_t target_size)
52
0
{
53
0
  return (target_size > m_length) ? grow_status::size_beyond_eof : grow_status::size_reached;
54
0
}
55
56
bool StreamReader_istream::read(void* data, size_t size)
57
0
{
58
0
  uint64_t end_pos = get_position() + size;
59
0
  if (end_pos > m_length) {
60
0
    return false;
61
0
  }
62
63
0
  m_istr->read((char*) data, size);
64
0
  return true;
65
0
}
66
67
bool StreamReader_istream::seek(uint64_t position)
68
0
{
69
0
  if (position > m_length)
70
0
    return false;
71
72
0
  m_istr->seekg(position, std::ios_base::beg);
73
0
  return true;
74
0
}
75
76
77
StreamReader_memory::StreamReader_memory(const uint8_t* data, size_t size, bool copy)
78
187k
    : m_length(size)
79
187k
{
80
187k
  if (copy) {
81
127k
    m_owned_data = new uint8_t[m_length];
82
127k
    if (size > 0) { // memcpy() from a NULL pointer is UB even for size 0 (until C2y/N3322), see read()
83
127k
      memcpy(m_owned_data, data, size);
84
127k
    }
85
86
127k
    m_data = m_owned_data;
87
127k
  }
88
59.9k
  else {
89
59.9k
    m_data = data;
90
59.9k
  }
91
187k
}
92
93
StreamReader_memory::~StreamReader_memory()
94
187k
{
95
187k
  if (m_owned_data) {
96
127k
    delete[] m_owned_data;
97
127k
  }
98
187k
}
99
100
uint64_t StreamReader_memory::get_position() const
101
5.28M
{
102
5.28M
  return m_position;
103
5.28M
}
104
105
StreamReader::grow_status StreamReader_memory::wait_for_file_size(uint64_t target_size)
106
5.10M
{
107
5.10M
  return (target_size > m_length) ? grow_status::size_beyond_eof : grow_status::size_reached;
108
5.10M
}
109
110
bool StreamReader_memory::read(void* data, size_t size)
111
53.2M
{
112
53.2M
  uint64_t end_pos = m_position + size;
113
53.2M
  if (end_pos > m_length) {
114
0
    return false;
115
0
  }
116
117
  // Do not call memcpy() with a NULL pointer, even when size == 0. 'data' is NULL when the
118
  // caller reads into an empty std::vector (e.g. a box with an empty payload), and passing
119
  // NULL to memcpy() is undefined behaviour in C17 and C++. It trips UBSan's nonnull-attribute
120
  // check on glibc's memcpy() declaration. C2y (WG14 N3322) makes zero-length operations on
121
  // NULL pointers well-defined, but we cannot rely on that for many years.
122
53.2M
  if (size > 0) {
123
53.1M
    memcpy(data, &m_data[m_position], size);
124
53.1M
  }
125
53.2M
  m_position += size;
126
127
53.2M
  return true;
128
53.2M
}
129
130
bool StreamReader_memory::seek(uint64_t position)
131
1.61M
{
132
1.61M
  if (position > m_length)
133
0
    return false;
134
135
1.61M
  m_position = position;
136
1.61M
  return true;
137
1.61M
}
138
139
140
StreamReader_CApi::StreamReader_CApi(const heif_reader* func_table, void* userdata)
141
0
    : m_func_table(func_table), m_userdata(userdata)
142
0
{
143
0
}
144
145
StreamReader::grow_status StreamReader_CApi::wait_for_file_size(uint64_t target_size)
146
0
{
147
0
  heif_reader_grow_status status = m_func_table->wait_for_file_size(target_size, m_userdata);
148
0
  switch (status) {
149
0
    case heif_reader_grow_status_size_reached:
150
0
      return grow_status::size_reached;
151
0
    case heif_reader_grow_status_timeout:
152
0
      return grow_status::timeout;
153
0
    case heif_reader_grow_status_size_beyond_eof:
154
0
      return grow_status::size_beyond_eof;
155
0
    default:
156
0
      assert(0);
157
0
      return grow_status::size_beyond_eof;
158
0
  }
159
0
}
160
161
162
BitstreamRange::BitstreamRange(std::shared_ptr<StreamReader> istr,
163
                               size_t length,
164
                               BitstreamRange* parent)
165
2.29M
    : m_istr(std::move(istr)), m_parent_range(parent), m_remaining(length)
166
2.29M
{
167
2.29M
  if (parent) {
168
2.11M
    m_nesting_level = parent->m_nesting_level + 1;
169
2.11M
  }
170
2.29M
}
171
172
173
BitstreamRange::BitstreamRange(std::shared_ptr<StreamReader> istr,
174
                               size_t start,
175
                               size_t end) // one past end
176
707k
  : m_istr(std::move(istr)), m_remaining(end - start)
177
707k
{
178
707k
  assert(end >= start);
179
180
707k
  bool success = m_istr->seek(start);
181
707k
  assert(success);
182
707k
  (void)success; // TODO
183
707k
}
184
185
186
StreamReader::grow_status BitstreamRange::wait_until_range_is_available()
187
0
{
188
0
  return m_istr->wait_for_file_size(m_istr->get_position() + m_remaining);
189
0
}
190
191
192
uint8_t BitstreamRange::read8()
193
13.8M
{
194
13.8M
  if (!prepare_read(1)) {
195
740k
    return 0;
196
740k
  }
197
198
13.1M
  uint8_t buf;
199
200
13.1M
  auto istr = get_istream();
201
13.1M
  bool success = istr->read((char*) &buf, 1);
202
203
13.1M
  if (!success) {
204
0
    set_eof_while_reading();
205
0
    return 0;
206
0
  }
207
208
13.1M
  return buf;
209
13.1M
}
210
211
212
uint16_t BitstreamRange::read16()
213
5.98M
{
214
5.98M
  if (!prepare_read(2)) {
215
67.3k
    return 0;
216
67.3k
  }
217
218
5.91M
  uint8_t buf[2];
219
220
5.91M
  auto istr = get_istream();
221
5.91M
  bool success = istr->read((char*) buf, 2);
222
223
5.91M
  if (!success) {
224
0
    set_eof_while_reading();
225
0
    return 0;
226
0
  }
227
228
5.91M
  return static_cast<uint16_t>((buf[0] << 8) | (buf[1]));
229
5.91M
}
230
231
232
int16_t BitstreamRange::read16s()
233
480k
{
234
480k
  uint16_t v = read16();
235
236
480k
  if (v & 0x8000) {
237
39.4k
    auto val = static_cast<int16_t>((~v) & 0x7fff);
238
39.4k
    return static_cast<int16_t>(-val - 1);
239
39.4k
  }
240
440k
  else {
241
440k
    return static_cast<int16_t>(v);
242
440k
  }
243
480k
}
244
245
246
uint32_t BitstreamRange::read24()
247
14.2k
{
248
14.2k
  if (!prepare_read(3)) {
249
0
    return 0;
250
0
  }
251
252
14.2k
  uint8_t buf[3];
253
254
14.2k
  auto istr = get_istream();
255
14.2k
  bool success = istr->read((char*) buf, 3);
256
257
14.2k
  if (!success) {
258
0
    set_eof_while_reading();
259
0
    return 0;
260
0
  }
261
262
14.2k
  return (uint32_t) ((buf[0] << 16) |
263
14.2k
                     (buf[1] << 8) |
264
14.2k
                     (buf[2]));
265
14.2k
}
266
267
uint32_t BitstreamRange::read32()
268
2.58G
{
269
2.58G
  if (!prepare_read(4)) {
270
2.57G
    return 0;
271
2.57G
  }
272
273
13.9M
  uint8_t buf[4];
274
275
13.9M
  auto istr = get_istream();
276
13.9M
  bool success = istr->read((char*) buf, 4);
277
278
13.9M
  if (!success) {
279
0
    set_eof_while_reading();
280
0
    return 0;
281
0
  }
282
283
13.9M
  return four_bytes_to_uint32(buf[0], buf[1], buf[2], buf[3]);
284
13.9M
}
285
286
287
uint64_t BitstreamRange::read_uint(int len)
288
1.25M
{
289
1.25M
  switch (len)
290
1.25M
  {
291
621k
    case 8:
292
621k
      return read8();
293
581k
    case 16:
294
581k
      return read16();
295
14.2k
    case 24:
296
14.2k
      return read24();
297
28.4k
    case 32:
298
28.4k
      return read32();
299
11.1k
    case 64:
300
11.1k
      return read64();
301
0
    default:
302
0
      assert(false);
303
0
      return 0;
304
1.25M
  }
305
1.25M
}
306
307
308
int32_t BitstreamRange::read32s()
309
269k
{
310
269k
  uint32_t v = read32();
311
312
269k
  if (v & 0x80000000) {
313
25.7k
    return -static_cast<int32_t>((~v) & 0x7fffffff) -1;
314
25.7k
  }
315
243k
  else {
316
243k
    return static_cast<int32_t>(v);
317
243k
  }
318
269k
}
319
320
321
uint64_t BitstreamRange::read64()
322
20.5k
{
323
20.5k
  if (!prepare_read(8)) {
324
292
    return 0;
325
292
  }
326
327
20.2k
  uint8_t buf[8];
328
329
20.2k
  auto istr = get_istream();
330
20.2k
  bool success = istr->read((char*) buf, 8);
331
332
20.2k
  if (!success) {
333
0
    set_eof_while_reading();
334
0
    return 0;
335
0
  }
336
337
20.2k
  return ((static_cast<uint64_t>(buf[0]) << 56) |
338
20.2k
          (static_cast<uint64_t>(buf[1]) << 48) |
339
20.2k
          (static_cast<uint64_t>(buf[2]) << 40) |
340
20.2k
          (static_cast<uint64_t>(buf[3]) << 32) |
341
20.2k
          (static_cast<uint64_t>(buf[4]) << 24) |
342
20.2k
          (static_cast<uint64_t>(buf[5]) << 16) |
343
20.2k
          (static_cast<uint64_t>(buf[6]) << 8) |
344
20.2k
          (static_cast<uint64_t>(buf[7])));
345
20.2k
}
346
347
348
int64_t BitstreamRange::read64s()
349
1.12k
{
350
1.12k
  uint64_t v = read64();
351
352
1.12k
  if (v & 0x8000000000000000) {
353
241
    return -static_cast<int64_t >((~v) & 0x7fffffffffffffff) -1;
354
241
  }
355
886
  else {
356
886
    return static_cast<int64_t >(v);
357
886
  }
358
1.12k
}
359
360
361
float BitstreamRange::read_float32()
362
2.57G
{
363
2.57G
#if __cpp_lib_bit_cast >= 201806L
364
2.57G
  uint32_t i = read32();
365
2.57G
  return std::bit_cast<float>(i); // this works directly on the value layout, thus we do not have to worry about memory layout
366
#else
367
  // compiler too old to support bit_cast
368
369
  // TODO: I am not sure this works everywhere as there seem to be systems where
370
  //       the float byte order is different from the integer endianness
371
  //       https://en.wikipedia.org/wiki/Endianness#Floating_point
372
  uint32_t i = read32();
373
  float f;
374
  memcpy(&f, &i, sizeof(float));
375
  return f;
376
#endif
377
2.57G
}
378
379
380
void StreamWriter::write_float32(float v)
381
0
{
382
0
#if __cpp_lib_bit_cast >= 201806L
383
0
  write32(std::bit_cast<uint32_t>(v)); // this works directly on the value layout, thus we do not have to worry about memory layout
384
#else
385
  // compiler too old to support bit_cast
386
387
  // TODO: I am not sure this works everywhere as there seem to be systems where
388
  //       the float byte order is different from the integer endianness
389
  //       https://en.wikipedia.org/wiki/Endianness#Floating_point
390
  uint32_t i;
391
  memcpy(&i, &v, sizeof(float));
392
  write32(i);
393
#endif
394
0
}
395
396
397
std::string BitstreamRange::read_string()
398
372k
{
399
372k
  std::string str;
400
401
  // Reading a string when no more data is available, returns an empty string.
402
  // Such a case happens, for example, when reading a 'url' box without content.
403
372k
  if (eof()) {
404
20.1k
    return std::string();
405
20.1k
  }
406
407
352k
  auto istr = get_istream();
408
409
14.5M
  for (;;) {
410
14.5M
    if (!prepare_read(1)) {
411
0
      return std::string();
412
0
    }
413
414
14.5M
    char c;
415
14.5M
    bool success = istr->read(&c, 1);
416
417
14.5M
    if (!success) {
418
0
      set_eof_while_reading();
419
0
      return std::string();
420
0
    }
421
422
14.5M
    if (c == 0 || m_remaining==0) {
423
352k
      break;
424
352k
    }
425
14.2M
    else {
426
14.2M
      str += (char) c;
427
14.2M
    }
428
14.5M
  }
429
430
352k
  return str;
431
352k
}
432
433
434
std::string BitstreamRange::read_fixed_string(int len)
435
17.9k
{
436
17.9k
  std::string str;
437
438
17.9k
  if (!prepare_read(len)) {
439
201
    return std::string();
440
201
  }
441
442
17.7k
  auto istr = get_istream();
443
444
17.7k
  uint8_t n;
445
17.7k
  bool success = istr->read(&n, 1);
446
17.7k
  if (!success || n > len - 1) {
447
1.58k
    return {};
448
1.58k
  }
449
450
82.1k
  for (int i = 0; i < n; i++) {
451
66.0k
    char c;
452
66.0k
    success = istr->read(&c, 1);
453
454
66.0k
    if (!success) {
455
0
      set_eof_while_reading();
456
0
      return std::string();
457
0
    }
458
459
66.0k
    str += (char) c;
460
66.0k
  }
461
462
16.1k
  istr->seek_cur(len-n-1);
463
464
16.1k
  return str;
465
16.1k
}
466
467
468
std::string BitstreamRange::read_string_until_eof()
469
2.01k
{
470
2.01k
  size_t n = get_remaining_bytes();
471
472
2.01k
  [[maybe_unused]] bool success = prepare_read(n);
473
2.01k
  assert(success); // we are reading exactly the rest of the box
474
475
2.01k
  std::string str;
476
2.01k
  str.resize(n);
477
2.01k
  get_istream()->read(str.data(), n);
478
479
2.01k
  return str;
480
2.01k
}
481
482
483
bool BitstreamRange::read(uint8_t* data, size_t n)
484
482k
{
485
482k
  if (!prepare_read(n)) {
486
347
    return false;
487
347
  }
488
489
482k
  auto istr = get_istream();
490
482k
  bool success = istr->read(data, n);
491
492
482k
  if (!success) {
493
0
    set_eof_while_reading();
494
0
  }
495
496
482k
  return success;
497
482k
}
498
499
500
bool BitstreamRange::prepare_read(size_t nBytes)
501
2.77G
{
502
  // Note: we do not test for negative nBytes anymore because we now use the unsigned size_t
503
504
2.77G
  if (m_remaining < nBytes) {
505
    // --- not enough data left in box -> move to end of box and set error flag
506
507
2.57G
    skip_to_end_of_box();
508
509
2.57G
    m_error = true;
510
2.57G
    return false;
511
2.57G
  }
512
197M
  else {
513
    // --- this is the normal case (m_remaining >= nBytes)
514
515
197M
    if (m_parent_range) {
516
148M
      if (!m_parent_range->prepare_read(nBytes)) {
517
0
        return false;
518
0
      }
519
148M
    }
520
521
197M
    m_remaining -= nBytes;
522
523
197M
    return true;
524
197M
  }
525
2.77G
}
526
527
528
StreamReader::grow_status BitstreamRange::wait_for_available_bytes(size_t nBytes)
529
4.63M
{
530
4.63M
  int64_t target_size = m_istr->get_position() + nBytes;
531
532
4.63M
  return m_istr->wait_for_file_size(target_size);
533
4.63M
}
534
535
536
void BitstreamRange::skip_without_advancing_file_pos(size_t n)
537
1.73M
{
538
1.73M
  assert(n <= m_remaining);
539
540
1.73M
  m_remaining -= n;
541
542
1.73M
  if (m_parent_range) {
543
1.21M
    m_parent_range->skip_without_advancing_file_pos(n);
544
1.21M
  }
545
1.73M
}
546
547
548
BitReader::BitReader(const uint8_t* buffer, size_t len)
549
844k
  : data_start(buffer),
550
844k
    data_length(len)
551
844k
{
552
844k
  data = buffer;
553
844k
  bytes_remaining = len;
554
555
844k
  nextbits = 0;
556
844k
  nextbits_cnt = 0;
557
558
844k
  refill();
559
844k
}
560
561
562
void BitReader::reset()
563
0
{
564
0
  data = data_start;
565
0
  bytes_remaining = data_length;
566
567
0
  nextbits = 0;
568
0
  nextbits_cnt = 0;
569
570
0
  refill();
571
0
}
572
573
574
uint32_t BitReader::get_bits(int n)
575
16.9M
{
576
16.9M
  assert(n <= 32);
577
578
16.9M
  if (nextbits_cnt < n) {
579
820k
    refill();
580
820k
  }
581
582
16.9M
  uint64_t val = nextbits;
583
16.9M
  val >>= 64 - n;
584
585
16.9M
#if AVOID_FUZZER_FALSE_POSITIVE
586
  // Shifting an unsigned integer left such that some MSBs fall out is well defined in C++ despite the fuzzer claiming otherwise.
587
16.9M
  nextbits &= (0xffffffffffffffffULL >> n);
588
16.9M
#endif
589
590
16.9M
  nextbits <<= n;
591
16.9M
  nextbits_cnt -= n;
592
593
16.9M
  return static_cast<uint32_t>(val);
594
16.9M
}
595
596
597
uint8_t BitReader::get_bits8(int n)
598
2.15M
{
599
2.15M
  assert(n>0 && n <= 8);
600
2.15M
  return static_cast<uint8_t>(get_bits(n));
601
2.15M
}
602
603
uint16_t BitReader::get_bits16(int n)
604
149k
{
605
149k
  assert(n>0 && n <= 16);
606
149k
  return static_cast<uint16_t>(get_bits(n));
607
149k
}
608
609
uint32_t BitReader::get_bits32(int n)
610
844k
{
611
844k
  assert(n>0 && n <= 32);
612
844k
  return static_cast<uint32_t>(get_bits(n));
613
844k
}
614
615
int32_t BitReader::get_bits32s()
616
65.7k
{
617
65.7k
  uint32_t bits = get_bits(32);
618
65.7k
  return static_cast<int32_t>(bits);
619
65.7k
}
620
621
622
bool BitReader::get_flag()
623
2.30M
{
624
2.30M
  return (get_bits(1) == 0x01);
625
2.30M
}
626
627
std::vector<uint8_t> BitReader::read_bytes(uint32_t n)
628
87.1k
{
629
  // TODO: this implementation isn't very efficient
630
87.1k
  std::vector<uint8_t> bytes;
631
1.38M
  for (uint32_t i = 0; i < n; i++) {
632
1.30M
    bytes.push_back(get_bits8(8));
633
1.30M
  }
634
87.1k
  return bytes;
635
87.1k
}
636
637
int BitReader::get_bits_fast(int n)
638
0
{
639
0
  assert(nextbits_cnt >= n);
640
641
0
  uint64_t val = nextbits;
642
0
  val >>= 64 - n;
643
644
0
  nextbits <<= n;
645
0
  nextbits_cnt -= n;
646
647
0
  return (int) val;
648
0
}
649
650
int BitReader::peek_bits(int n)
651
0
{
652
0
  if (nextbits_cnt < n) {
653
0
    refill();
654
0
  }
655
656
0
  uint64_t val = nextbits;
657
0
  val >>= 64 - n;
658
659
0
  return (int) val;
660
0
}
661
662
void BitReader::skip_bytes(uint32_t nBytes)
663
1.04M
{
664
  // This has to run in constant time. The number of bytes to skip is taken directly
665
  // from 32-bit file fields (e.g. the 'uncC' row/tile alignment), so a byte-at-a-time
666
  // loop spins for billions of iterations when a malformed file asks to skip far
667
  // beyond the end of the data. MinimizedImageBox::parse() guards against the same
668
  // failure mode by validating its declared chunk sizes up front.
669
670
1.04M
  uint64_t nBits = uint64_t{nBytes} * 8;
671
672
  // --- consume the bits that are already buffered in 'nextbits'
673
674
1.04M
  if (nextbits_cnt > 0) {
675
998k
    uint64_t from_buffer = std::min(nBits, static_cast<uint64_t>(nextbits_cnt));
676
677
998k
    if (from_buffer >= 64) {
678
2.03k
      nextbits = 0;
679
2.03k
    }
680
996k
    else {
681
996k
#if AVOID_FUZZER_FALSE_POSITIVE
682
996k
      nextbits &= (0xffffffffffffffffULL >> from_buffer);
683
996k
#endif
684
996k
      nextbits <<= from_buffer;
685
996k
    }
686
687
998k
    nextbits_cnt -= static_cast<int64_t>(from_buffer);
688
998k
    nBits -= from_buffer;
689
998k
  }
690
691
1.04M
  if (nBits == 0) {
692
257k
    return;
693
257k
  }
694
695
  // --- skip whole bytes directly in the input buffer, without pushing them
696
  //     through the bit buffer
697
698
786k
  uint64_t whole_bytes = nBits / 8;
699
786k
  int residual_bits = static_cast<int>(nBits % 8);
700
701
786k
  if (whole_bytes >= bytes_remaining) {
702
    // Skipping past the end of the data. Record the overshoot in 'nextbits_cnt' (which
703
    // thereby goes negative) so that get_current_byte_index() keeps advancing exactly
704
    // as it did with the previous bit-by-bit implementation.
705
406k
    uint64_t overshoot_bits = (whole_bytes - bytes_remaining) * 8 + static_cast<uint64_t>(residual_bits);
706
707
406k
    data += bytes_remaining;
708
406k
    bytes_remaining = 0;
709
406k
    nextbits = 0;
710
406k
    nextbits_cnt -= static_cast<int64_t>(overshoot_bits);
711
406k
    return;
712
406k
  }
713
714
379k
  data += static_cast<size_t>(whole_bytes);
715
379k
  bytes_remaining -= static_cast<size_t>(whole_bytes);
716
379k
  nextbits = 0;
717
379k
  nextbits_cnt = 0;
718
719
379k
  refill();
720
721
379k
  if (residual_bits > 0) {
722
20.4k
    skip_bits(residual_bits);
723
20.4k
  }
724
379k
}
725
726
void BitReader::skip_bits(int n)
727
2.61M
{
728
2.61M
  if (nextbits_cnt < n) {
729
94.9k
    refill();
730
94.9k
  }
731
732
2.61M
#if AVOID_FUZZER_FALSE_POSITIVE
733
2.61M
  nextbits &= (0xffffffffffffffffULL >> n);
734
2.61M
#endif
735
736
2.61M
  nextbits <<= n;
737
2.61M
  nextbits_cnt -= n;
738
2.61M
}
739
740
void BitReader::skip_bits_fast(int n)
741
0
{
742
0
#if AVOID_FUZZER_FALSE_POSITIVE
743
0
  nextbits &= (0xffffffffffffffffULL >> n);
744
0
#endif
745
746
0
  nextbits <<= n;
747
0
  nextbits_cnt -= n;
748
0
}
749
750
void BitReader::skip_to_byte_boundary()
751
2.10M
{
752
2.10M
  int nskip = static_cast<int>(nextbits_cnt & 7);
753
754
2.10M
#if AVOID_FUZZER_FALSE_POSITIVE
755
2.10M
  nextbits &= (0xffffffffffffffffULL >> nskip);
756
2.10M
#endif
757
758
2.10M
  nextbits <<= nskip;
759
2.10M
  nextbits_cnt -= nskip;
760
2.10M
}
761
762
bool BitReader::get_uvlc(uint32_t* value)
763
559k
{
764
559k
  int num_zeros = 0;
765
766
1.78M
  while (get_bits(1) == 0) {
767
1.22M
    num_zeros++;
768
769
1.22M
    if (num_zeros > MAX_UVLC_LEADING_ZEROS) { return false; }
770
1.22M
  }
771
772
556k
  if (num_zeros != 0) {
773
279k
    uint32_t offset = get_bits(num_zeros);
774
279k
    *value = offset + (1u << num_zeros) - 1u;
775
279k
    assert(*value > 0);
776
279k
    return true;
777
279k
  }
778
276k
  else {
779
276k
    *value = 0;
780
276k
    return true;
781
276k
  }
782
556k
}
783
784
bool BitReader::get_svlc(int32_t* value)
785
93.5k
{
786
93.5k
  uint32_t v;
787
93.5k
  if (!get_uvlc(&v)) {
788
115
    return false;
789
115
  }
790
93.4k
  else if (v == 0) {
791
67.7k
    *value = 0;
792
67.7k
    return true;
793
67.7k
  }
794
795
25.6k
  bool negative = ((v & 1u) == 0);
796
25.6k
  *value = negative ? -static_cast<int32_t>(v / 2) : static_cast<int32_t>((v + 1) / 2);
797
25.6k
  return true;
798
93.5k
}
799
800
void BitReader::refill()
801
2.13M
{
802
#if 0
803
  // TODO: activate me once I'm sure this works
804
  while (nextbits_cnt <= 64-8 && bytes_remaining) {
805
    uint64_t newval = *data++;
806
    bytes_remaining--;
807
808
    nextbits_cnt += 8;
809
    newval <<= 64-nextbits_cnt;
810
    nextbits |= newval;
811
  }
812
#else
813
2.13M
  if (bytes_remaining == 0) {
814
    // Nothing to refill. Returning early also keeps the shift below out of range
815
    // when nextbits_cnt is far negative after skipping past the end of the data.
816
72.8k
    return;
817
72.8k
  }
818
819
2.06M
  int64_t shift = 64 - nextbits_cnt;
820
821
17.1M
  while (shift >= 8 && bytes_remaining) {
822
15.0M
    uint64_t newval = *data++;
823
15.0M
    bytes_remaining--;
824
825
15.0M
    shift -= 8;
826
15.0M
    newval <<= shift;
827
15.0M
    nextbits |= newval;
828
15.0M
  }
829
830
2.06M
  nextbits_cnt = 64 - shift;
831
2.06M
#endif
832
2.06M
}
833
834
835
// --- BitWriter ---
836
837
void BitWriter::write_bits(uint32_t value, int n)
838
0
{
839
0
  assert(n >= 0 && n <= 32);
840
841
0
  for (int i = n - 1; i >= 0; i--) {
842
0
    uint8_t bit = (value >> i) & 1;
843
0
    m_current_byte |= (bit << (7 - m_bits_in_current_byte));
844
0
    m_bits_in_current_byte++;
845
846
0
    if (m_bits_in_current_byte == 8) {
847
0
      m_data.push_back(m_current_byte);
848
0
      m_current_byte = 0;
849
0
      m_bits_in_current_byte = 0;
850
0
    }
851
0
  }
852
0
}
853
854
void BitWriter::write_bytes(const std::vector<uint8_t>& data)
855
0
{
856
0
  write_bytes(data.data(), data.size());
857
0
}
858
859
void BitWriter::write_bytes(const uint8_t* data, size_t len)
860
0
{
861
0
  assert(m_bits_in_current_byte == 0);
862
0
  m_data.insert(m_data.end(), data, data + len);
863
0
}
864
865
void BitWriter::skip_to_byte_boundary()
866
0
{
867
0
  if (m_bits_in_current_byte > 0) {
868
0
    m_data.push_back(m_current_byte);
869
0
    m_current_byte = 0;
870
0
    m_bits_in_current_byte = 0;
871
0
  }
872
0
}
873
874
std::vector<uint8_t> BitWriter::get_data() const
875
0
{
876
0
  std::vector<uint8_t> result = m_data;
877
0
  if (m_bits_in_current_byte > 0) {
878
0
    result.push_back(m_current_byte);
879
0
  }
880
0
  return result;
881
0
}
882
883
884
// --- StreamWriter ---
885
886
void StreamWriter::write8(uint8_t v)
887
96.7k
{
888
96.7k
  if (m_position == m_data.size()) {
889
78.4k
    m_data.push_back(v);
890
78.4k
    m_position++;
891
78.4k
  }
892
18.2k
  else {
893
18.2k
    m_data[m_position++] = v;
894
18.2k
  }
895
96.7k
}
896
897
898
void StreamWriter::write16(uint16_t v)
899
81.8k
{
900
81.8k
  size_t required_size = m_position + 2;
901
902
81.8k
  if (required_size > m_data.size()) {
903
45.3k
    m_data.resize(required_size);
904
45.3k
  }
905
906
81.8k
  m_data[m_position++] = uint8_t((v >> 8) & 0xFF);
907
81.8k
  m_data[m_position++] = uint8_t(v & 0xFF);
908
81.8k
}
909
910
911
void StreamWriter::write16s(int16_t v16s)
912
0
{
913
0
  uint16_t v;
914
0
  if (v16s >= 0) {
915
0
    v = static_cast<uint16_t>(v16s);
916
0
  }
917
0
  else {
918
0
    auto val = static_cast<uint16_t>((-v16s-1));
919
0
    v = static_cast<uint16_t>(~val);
920
0
  }
921
922
0
  write16(v);
923
0
}
924
925
926
void StreamWriter::write24(uint32_t v)
927
0
{
928
0
  size_t required_size = m_position + 3;
929
930
0
  if (required_size > m_data.size()) {
931
0
    m_data.resize(required_size);
932
0
  }
933
934
0
  m_data[m_position++] = uint8_t((v >> 16) & 0xFF);
935
0
  m_data[m_position++] = uint8_t((v >> 8) & 0xFF);
936
0
  m_data[m_position++] = uint8_t(v & 0xFF);
937
0
}
938
939
940
void StreamWriter::write32(uint32_t v)
941
287k
{
942
287k
  size_t required_size = m_position + 4;
943
944
287k
  if (required_size > m_data.size()) {
945
88.7k
    m_data.resize(required_size);
946
88.7k
  }
947
948
287k
  m_data[m_position++] = uint8_t((v >> 24) & 0xFF);
949
287k
  m_data[m_position++] = uint8_t((v >> 16) & 0xFF);
950
287k
  m_data[m_position++] = uint8_t((v >> 8) & 0xFF);
951
287k
  m_data[m_position++] = uint8_t(v & 0xFF);
952
287k
}
953
954
955
void StreamWriter::write32s(int32_t v32s)
956
4.17k
{
957
4.17k
  uint32_t v;
958
4.17k
  if (v32s >= 0) {
959
838
    v = static_cast<uint32_t>(v32s);
960
838
  }
961
3.33k
  else {
962
3.33k
    v = ~static_cast<uint32_t>((-v32s-1));
963
3.33k
  }
964
965
4.17k
  write32(v);
966
4.17k
}
967
968
969
void StreamWriter::write64(uint64_t v)
970
0
{
971
0
  size_t required_size = m_position + 8;
972
973
0
  if (required_size > m_data.size()) {
974
0
    m_data.resize(required_size);
975
0
  }
976
977
0
  m_data[m_position++] = uint8_t((v >> 56) & 0xFF);
978
0
  m_data[m_position++] = uint8_t((v >> 48) & 0xFF);
979
0
  m_data[m_position++] = uint8_t((v >> 40) & 0xFF);
980
0
  m_data[m_position++] = uint8_t((v >> 32) & 0xFF);
981
0
  m_data[m_position++] = uint8_t((v >> 24) & 0xFF);
982
0
  m_data[m_position++] = uint8_t((v >> 16) & 0xFF);
983
0
  m_data[m_position++] = uint8_t((v >> 8) & 0xFF);
984
0
  m_data[m_position++] = uint8_t(v & 0xFF);
985
0
}
986
987
988
void StreamWriter::write64s(int64_t v)
989
0
{
990
0
  write64(reinterpret_cast<uint64_t&>(v));
991
0
}
992
993
994
void StreamWriter::write(int size, uint64_t value)
995
31.8k
{
996
31.8k
  if (size == 1) {
997
0
    assert(value <= 0xFF);
998
0
    write8((uint8_t) value);
999
0
  }
1000
31.8k
  else if (size == 2) {
1001
4.55k
    assert(value <= 0xFFFF);
1002
4.55k
    write16((uint16_t) value);
1003
4.55k
  }
1004
27.3k
  else if (size == 4) {
1005
27.3k
    assert(value <= 0xFFFFFFFF);
1006
27.3k
    write32((uint32_t) value);
1007
27.3k
  }
1008
0
  else if (size == 8) {
1009
0
    write64((uint64_t) value);
1010
0
  }
1011
0
  else {
1012
0
    assert(false); // unimplemented size
1013
0
  }
1014
31.8k
}
1015
1016
1017
void StreamWriter::write(const std::string& str, bool end_with_null)
1018
9.11k
{
1019
9.11k
  size_t required_size = m_position + str.size() + (end_with_null ? 1 : 0);
1020
1021
9.11k
  if (required_size > m_data.size()) {
1022
9.11k
    m_data.resize(required_size);
1023
9.11k
  }
1024
1025
9.11k
  for (size_t i = 0; i < str.size(); i++) {
1026
0
    m_data[m_position++] = str[i];
1027
0
  }
1028
1029
9.11k
  if (end_with_null) {
1030
9.11k
    m_data[m_position++] = 0;
1031
9.11k
  }
1032
9.11k
}
1033
1034
1035
void StreamWriter::write_fixed_string(std::string s, size_t len)
1036
0
{
1037
0
  size_t required_size = m_position + len;
1038
1039
0
  if (required_size > m_data.size()) {
1040
0
    m_data.resize(required_size);
1041
0
  }
1042
1043
0
  size_t n_chars = std::min(s.length(), len - 1);
1044
0
  assert(n_chars <= 255);
1045
0
  m_data[m_position++] = static_cast<uint8_t>(n_chars);
1046
1047
0
  for (size_t i = 0; i < s.size() && i < len - 1; i++) {
1048
0
    m_data[m_position++] = s[i];
1049
0
  }
1050
1051
0
  for (size_t i = s.size(); i < len - 1; i++) {
1052
0
    m_data[m_position++] = 0;
1053
0
  }
1054
0
}
1055
1056
1057
void StreamWriter::write(const std::vector<uint8_t>& vec)
1058
9.93k
{
1059
9.93k
  size_t required_size = m_position + vec.size();
1060
1061
9.93k
  if (required_size > m_data.size()) {
1062
9.93k
    m_data.resize(required_size);
1063
9.93k
  }
1064
1065
9.93k
  if (!vec.empty()) { // memcpy() with a NULL pointer is UB even for size 0 (until C2y/N3322), see StreamReader_memory::read()
1066
9.93k
    memcpy(m_data.data() + m_position, vec.data(), vec.size());
1067
9.93k
  }
1068
9.93k
  m_position += vec.size();
1069
9.93k
}
1070
1071
1072
void StreamWriter::write(const StreamWriter& writer)
1073
0
{
1074
0
  size_t required_size = m_position + writer.get_data().size();
1075
1076
0
  if (required_size > m_data.size()) {
1077
0
    m_data.resize(required_size);
1078
0
  }
1079
1080
0
  const auto& data = writer.get_data();
1081
1082
0
  if (!data.empty()) { // memcpy() with a NULL pointer is UB even for size 0 (until C2y/N3322), see StreamReader_memory::read()
1083
0
    memcpy(m_data.data() + m_position, data.data(), data.size());
1084
0
  }
1085
1086
0
  m_position += data.size();
1087
0
}
1088
1089
1090
void StreamWriter::skip(int n)
1091
111k
{
1092
111k
  assert(m_position == m_data.size());
1093
111k
  m_data.resize(m_data.size() + n);
1094
111k
  m_position += n;
1095
111k
}
1096
1097
1098
void StreamWriter::insert(int nBytes)
1099
0
{
1100
0
  assert(nBytes >= 0);
1101
1102
0
  if (nBytes == 0) {
1103
0
    return;
1104
0
  }
1105
1106
0
  m_data.resize(m_data.size() + nBytes);
1107
1108
0
  if (m_position < m_data.size() - nBytes) {
1109
0
    memmove(m_data.data() + m_position + nBytes,
1110
0
            m_data.data() + m_position,
1111
0
            m_data.size() - nBytes - m_position);
1112
0
  }
1113
0
}