ADPCM Codecs
Loading...
Searching...
No Matches
BitWriter.h
1/*
2 * Bit writer (little endian bit order by default, or most significant bit
3 * first with setMsbFirst)
4 * Adapted from the FFmpeg put_bits functions:
5 * Copyright (c) 2000, 2001 Fabrice Bellard
6 *
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 */
12
13#pragma once
14
15#include <stdint.h>
16
17#include "config-adpcm.h"
18
19namespace adpcm_ffmpeg {
20
27class BitWriter {
28 public:
30 : buffer_(buffer), buffer_size_(buffer_size < 0 ? 0 : buffer_size) {}
31
33 void setMsbFirst(bool msb) { msb_ = msb; }
34
36 void put(int n, uint32_t value) {
37 if (msb_) {
38 for (int k = n - 1; k >= 0; k--) {
39 acc_ = (acc_ << 1) | ((value >> k) & 1);
40 if (++bits_ == 8) {
41 storeByte((uint8_t)acc_);
42 acc_ = 0;
43 bits_ = 0;
44 }
45 }
46 return;
47 }
48 const uint64_t mask = n >= 32 ? 0xFFFFFFFFull : ((1ull << n) - 1);
49 acc_ |= ((uint64_t)value & mask) << bits_;
50 bits_ += n;
51 while (bits_ >= 8) {
52 storeByte((uint8_t)acc_);
53 acc_ >>= 8;
54 bits_ -= 8;
55 }
56 }
57
59 void putSigned(int n, int32_t value) {
61 }
62
64 void flush() {
65 if (bits_ > 0)
66 storeByte(msb_ ? (uint8_t)(acc_ << (8 - bits_)) : (uint8_t)acc_);
67 acc_ = 0;
68 bits_ = 0;
69 }
70
72 int bytesWritten() const { return pos_; }
73
74 private:
75 uint8_t *buffer_;
76 int buffer_size_;
77 int pos_ = 0;
78 uint64_t acc_ = 0;
79 int bits_ = 0;
80 bool msb_ = false;
81
82 void storeByte(uint8_t v) {
83 if (pos_ < buffer_size_) buffer_[pos_] = v;
84 pos_++;
85 }
86};
87
88} // namespace adpcm_ffmpeg
Vector implementation which provides the most important methods as defined by std::vector....
Definition ADPCMVector.h:16
Writes bits into a buffer. By default the first bit written is the least significant bit of the first...
Definition BitWriter.h:27
void put(int n, uint32_t value)
writes the low n bits of value (0 to 32)
Definition BitWriter.h:36
void setMsbFirst(bool msb)
Selects the bit order used by put(); call before writing.
Definition BitWriter.h:33
void flush()
stores the pending bits as a final, zero padded byte
Definition BitWriter.h:64
int bytesWritten() const
number of bytes stored so far
Definition BitWriter.h:72
void putSigned(int n, int32_t value)
writes the low n bits of a signed value (two's complement, 0 to 31)
Definition BitWriter.h:59