decibri_decode/audio.rs
1//! Decoded audio, and the description that travels with it.
2
3/// The sample rate and channel count of a block of audio.
4///
5/// Rate and layout are one value, not two, so they cannot be passed separately
6/// and cannot drift apart. decibri has been bitten repeatedly by a rate
7/// travelling independently of the samples it describes; the most expensive
8/// instance was the AEC reference path, where a reference at the wrong rate is
9/// accepted without complaint and cancels nothing.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11pub struct AudioSpec {
12 /// Samples per second, per channel.
13 pub sample_rate: u32,
14 /// Number of interleaved channels.
15 pub channels: u16,
16}
17
18impl AudioSpec {
19 /// Describes audio at `sample_rate` with `channels` interleaved channels.
20 pub const fn new(sample_rate: u32, channels: u16) -> Self {
21 Self {
22 sample_rate,
23 channels,
24 }
25 }
26
27 /// Describes single-channel audio at `sample_rate`.
28 ///
29 /// Named because single-channel audio is stated by the caller often enough
30 /// to be worth one call rather than two arguments: a headerless G.711 or
31 /// PCM stream, or a mono file being written. Nothing in the crate produces
32 /// this shape on its own. A decode keeps the source's own channel count,
33 /// and mixing down to one channel is
34 /// [`downmix_to_mono`](crate::downmix_to_mono), called by whoever wants it.
35 pub const fn mono(sample_rate: u32) -> Self {
36 Self::new(sample_rate, 1)
37 }
38
39 /// `true` when this describes single-channel audio.
40 pub const fn is_mono(&self) -> bool {
41 self.channels == 1
42 }
43
44 /// How many whole frames `sample_count` interleaved samples make up.
45 ///
46 /// Returns `0` for a spec with no channels rather than dividing by zero.
47 pub const fn frames(&self, sample_count: usize) -> usize {
48 if self.channels == 0 {
49 0
50 } else {
51 sample_count / self.channels as usize
52 }
53 }
54}
55
56/// Decoded audio together with the [`AudioSpec`] that describes it.
57///
58/// Samples are `f32`, interleaved when there is more than one channel, and are
59/// nominally in `-1.0..=1.0`. Formats whose integer range maps outside that
60/// interval are not clamped by the decoder; clamping is a policy decision for
61/// whoever consumes the audio.
62///
63/// This type is what leaves the crate. A [`Decoder`](crate::Decoder) appends
64/// into a plain `Vec<f32>` because it is the caller's own decoder and its
65/// [`output_spec`](crate::Decoder::output_spec) is authoritative, but at every
66/// boundary where audio travels further than that, it travels as an
67/// `AudioBuffer` so no downstream stage has to infer a rate.
68#[derive(Debug, Clone, PartialEq)]
69pub struct AudioBuffer {
70 spec: AudioSpec,
71 samples: Vec<f32>,
72}
73
74impl AudioBuffer {
75 /// An empty buffer described by `spec`.
76 pub const fn new(spec: AudioSpec) -> Self {
77 Self {
78 spec,
79 samples: Vec::new(),
80 }
81 }
82
83 /// An empty buffer described by `spec`, with room for `capacity` samples.
84 pub fn with_capacity(spec: AudioSpec, capacity: usize) -> Self {
85 Self {
86 spec,
87 samples: Vec::with_capacity(capacity),
88 }
89 }
90
91 /// Binds `samples` to the `spec` that describes them.
92 ///
93 /// The pairing is not checked, because there is nothing to check it
94 /// against: `spec` is the assertion. Use it at the one point where the
95 /// rate is known, immediately after pulling samples from the decoder that
96 /// reported it.
97 pub const fn from_samples(spec: AudioSpec, samples: Vec<f32>) -> Self {
98 Self { spec, samples }
99 }
100
101 /// The rate and layout of the samples held here.
102 pub const fn spec(&self) -> AudioSpec {
103 self.spec
104 }
105
106 /// Samples per second, per channel.
107 pub const fn sample_rate(&self) -> u32 {
108 self.spec.sample_rate
109 }
110
111 /// Number of interleaved channels.
112 pub const fn channels(&self) -> u16 {
113 self.spec.channels
114 }
115
116 /// The interleaved samples.
117 pub fn samples(&self) -> &[f32] {
118 &self.samples
119 }
120
121 /// The interleaved samples, mutably.
122 pub fn samples_mut(&mut self) -> &mut [f32] {
123 &mut self.samples
124 }
125
126 /// The number of whole frames held.
127 pub fn frames(&self) -> usize {
128 self.spec.frames(self.samples.len())
129 }
130
131 /// `true` when no samples are held.
132 pub fn is_empty(&self) -> bool {
133 self.samples.is_empty()
134 }
135
136 /// Appends interleaved samples, which must already be at this buffer's
137 /// rate and layout.
138 pub fn extend_from_slice(&mut self, samples: &[f32]) {
139 self.samples.extend_from_slice(samples);
140 }
141
142 /// Drops the samples, keeping the spec and the allocation.
143 pub fn clear(&mut self) {
144 self.samples.clear();
145 }
146
147 /// Takes the samples out, discarding the description.
148 ///
149 /// Named to be conspicuous at a call site: past this point the rate no
150 /// longer travels with the audio, which is the situation this type exists
151 /// to prevent.
152 pub fn into_samples(self) -> Vec<f32> {
153 self.samples
154 }
155}
156
157#[cfg(test)]
158mod tests {
159 use super::*;
160
161 #[test]
162 fn a_spec_carries_rate_and_layout_together() {
163 let spec = AudioSpec::new(48_000, 2);
164 assert_eq!(spec.sample_rate, 48_000);
165 assert_eq!(spec.channels, 2);
166 assert!(!spec.is_mono());
167 assert!(AudioSpec::mono(16_000).is_mono());
168 }
169
170 #[test]
171 fn frames_divide_by_the_channel_count() {
172 assert_eq!(AudioSpec::new(48_000, 2).frames(1000), 500);
173 // A trailing partial frame is not a frame.
174 assert_eq!(AudioSpec::new(48_000, 2).frames(1001), 500);
175 assert_eq!(AudioSpec::mono(48_000).frames(1000), 1000);
176 }
177
178 #[test]
179 fn a_zero_channel_spec_reports_no_frames_rather_than_dividing_by_zero() {
180 assert_eq!(AudioSpec::new(48_000, 0).frames(1000), 0);
181 let buffer = AudioBuffer::from_samples(AudioSpec::new(48_000, 0), vec![0.0; 8]);
182 assert_eq!(buffer.frames(), 0);
183 }
184
185 #[test]
186 fn a_buffer_keeps_its_spec_through_every_mutation() {
187 let spec = AudioSpec::mono(8_000);
188 let mut buffer = AudioBuffer::with_capacity(spec, 4);
189 assert!(buffer.is_empty());
190
191 buffer.extend_from_slice(&[0.25, -0.25]);
192 assert_eq!(buffer.spec(), spec);
193 assert_eq!(buffer.sample_rate(), 8_000);
194 assert_eq!(buffer.channels(), 1);
195 assert_eq!(buffer.frames(), 2);
196 assert_eq!(buffer.samples(), &[0.25, -0.25]);
197
198 buffer.samples_mut()[0] = 0.5;
199 assert_eq!(buffer.samples(), &[0.5, -0.25]);
200
201 buffer.clear();
202 assert!(buffer.is_empty());
203 assert_eq!(buffer.spec(), spec);
204 }
205
206 #[test]
207 fn samples_can_be_taken_out_and_bound_back_to_a_spec() {
208 let spec = AudioSpec::mono(16_000);
209 let buffer = AudioBuffer::from_samples(spec, vec![1.0, 2.0, 3.0]);
210 let samples = buffer.into_samples();
211 let rebound = AudioBuffer::from_samples(spec, samples);
212 assert_eq!(rebound.samples(), &[1.0, 2.0, 3.0]);
213 assert_eq!(rebound.spec(), spec);
214 }
215
216 #[test]
217 fn an_empty_buffer_still_declares_a_rate() {
218 let buffer = AudioBuffer::new(AudioSpec::mono(44_100));
219 assert!(buffer.is_empty());
220 assert_eq!(buffer.sample_rate(), 44_100);
221 }
222}