Sound Byte Libs 0.5.1-121-g3358a44
C++ firmware library for audio applications on 32-bit ARM Cortex-M processors
Loading...
Searching...
No Matches
bit_reducer.hpp
Go to the documentation of this file.
1// sbl/dsp/primitives/bit_reducer.hpp — Amplitude bit-depth reduction
2//
3// Uniform quantization to N levels. Reduces the effective bit depth of a
4// signal by snapping sample values to a grid. Fractional bit depths produce
5// intermediate step counts for smooth knob sweeps.
6//
7// Domain: waveshape. Quantization changes the instantaneous input-output
8// relationship — it's a staircase transfer function. Harmonically, it adds
9// quantization noise whose character depends on the step count.
10//
11// Usage:
12// sbl::dsp::primitives::BitReducer br;
13// br.set_bits(8.0f); // 256 levels
14// float y = br.process(x); // per-sample
15// br.process(buf, frames); // block in-place
16
17#ifndef SBL_DSP_PRIMITIVES_BIT_REDUCER_HPP_
18#define SBL_DSP_PRIMITIVES_BIT_REDUCER_HPP_
19
20#include <cmath>
21#include <cstdint>
22
23namespace sbl::dsp::primitives {
24
26public:
27 /// Set quantization depth in bits. Fractional values allowed.
28 /// Caches the level count internally.
29 void set_bits(float bits) {
30 bits_ = bits;
31 levels_ = exp2f(bits);
32 inv_levels_ = 1.0f / levels_;
33 }
34
35 float bits() const { return bits_; }
36
37 /// Process a single sample.
38 float process(float x) const {
39 return roundf(x * levels_) * inv_levels_;
40 }
41
42 /// Process a block of samples in-place.
43 void process(float* buf, uint16_t n) const {
44 for (uint16_t i = 0; i < n; ++i) {
45 buf[i] = process(buf[i]);
46 }
47 }
48
49private:
50 float bits_ = 16.0f;
51 float levels_ = 65536.0f;
52 float inv_levels_ = 1.0f / 65536.0f;
53};
54
55} // namespace sbl::dsp::primitives
56
57#endif // SBL_DSP_PRIMITIVES_BIT_REDUCER_HPP_
float process(float x) const
Process a single sample.
void process(float *buf, uint16_t n) const
Process a block of samples in-place.
Stateful, single-concern building blocks.