forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

multistream.rs321 lines, 11.9 KiBHistoryRawDownload
1//! Multichannel Opus: several elementary streams in one packet.
2//!
3//! A multistream packet is just the ordinary packets of each stream laid end to
4//! end. All but the last use the self-delimiting framing of RFC 6716
5//! Appendix B, which carries one extra length so the boundary can be found
6//! without a container; the last uses the ordinary framing, so it takes
7//! whatever is left. That is the whole of the format — everything else is the
8//! channel mapping table, which says where each stream's channels land.
9//!
10//! Streams come in two kinds: the first `coupled` streams are stereo, the rest
11//! mono. `mapping[c]` names the coded channel that output channel `c` reads
12//! from: values below `2*coupled` are a coupled stream's left (even) or right
13//! (odd) channel, values above index the mono streams, and 255 means the
14//! channel is silent.
15//!
16//! Channel *order* is the mapping's, not this decoder's: for RFC 7845 mapping
17//! family 1 — what a 5.1 or 7.1 film track uses — that is Vorbis order
18//! (left, centre, right, back left, back right, LFE for 5.1), and a caller that
19//! wants the product's FL/FR/FC/LFE/BL/BR order permutes it.
20
21use ec_core::{Error, Result};
22
23use crate::packet::Packet;
24use crate::Decoder;
25
26/// A decoder for a multichannel Opus stream, mono through 255 channels.
27#[derive(Debug)]
28pub struct MultistreamDecoder {
29 streams: Vec<Decoder>,
30 coupled: usize,
31 mapping: Vec<u8>,
32 channels: usize,
33 sample_rate: u32,
34 /// Scratch for one stream's output.
35 buf: Vec<f32>,
36 /// Scratch for one stream's first frame as a plain packet.
37 fec: Vec<u8>,
38}
39
40impl MultistreamDecoder {
41 /// A decoder for `streams` elementary streams of which the first `coupled`
42 /// are stereo, with `mapping` naming the coded channel each output channel
43 /// comes from.
44 ///
45 /// # Panics
46 /// On a layout that breaks the RFC's limits — more coupled streams than
47 /// streams, a mapping entry naming a channel no stream codes, an
48 /// unsupported rate. The layout comes from a container header, so callers
49 /// that read one from a file should check it (or use
50 /// [`MultistreamDecoder::try_with_rate`]) rather than pass it straight in.
51 pub fn with_rate(
52 sample_rate: u32,
53 streams: usize,
54 coupled: usize,
55 mapping: &[u8],
56 ) -> MultistreamDecoder {
57 match Self::try_with_rate(sample_rate, streams, coupled, mapping) {
58 Ok(d) => d,
59 Err(e) => panic!("invalid Opus multistream layout: {e}"),
60 }
61 }
62
63 /// [`MultistreamDecoder::with_rate`] with the layout checked instead of
64 /// asserted.
65 pub fn try_with_rate(
66 sample_rate: u32,
67 streams: usize,
68 coupled: usize,
69 mapping: &[u8],
70 ) -> Result<MultistreamDecoder> {
71 if streams == 0 || streams > 255 || coupled > streams {
72 return Err(Error::corrupt(format!(
73 "opus multistream: {streams} streams of which {coupled} coupled"
74 )));
75 }
76 let coded = coupled + streams;
77 if mapping.is_empty() || mapping.len() > 255 {
78 return Err(Error::corrupt(format!(
79 "opus multistream: {} output channels",
80 mapping.len()
81 )));
82 }
83 if let Some(&bad) = mapping.iter().find(|&&m| m != 255 && m as usize >= coded) {
84 return Err(Error::corrupt(format!(
85 "opus multistream: mapping entry {bad} names a channel of {coded}"
86 )));
87 }
88 let mut decoders = Vec::with_capacity(streams);
89 for s in 0..streams {
90 let ch = if s < coupled { 2 } else { 1 };
91 decoders.push(Decoder::new(sample_rate, ch)?);
92 }
93 Ok(MultistreamDecoder {
94 streams: decoders,
95 coupled,
96 mapping: mapping.to_vec(),
97 channels: mapping.len(),
98 sample_rate,
99 buf: vec![0.0; 2 * 5760],
100 fec: Vec::with_capacity(1276),
101 })
102 }
103
104 /// Output channels.
105 pub fn channels(&self) -> usize {
106 self.channels
107 }
108
109 /// Output sample rate.
110 pub fn sample_rate(&self) -> u32 {
111 self.sample_rate
112 }
113
114 /// Drops all inter-packet state in every stream; call after a seek.
115 pub fn reset(&mut self) {
116 for s in self.streams.iter_mut() {
117 s.reset();
118 }
119 }
120
121 /// The range coder states of all streams, combined the way RFC 6716
122 /// Section 6 combines them for conformance checking.
123 pub fn final_range(&self) -> u32 {
124 self.streams.iter().fold(0, |acc, s| acc ^ s.final_range())
125 }
126
127 /// Decodes one multistream packet into a fresh interleaved buffer.
128 ///
129 /// This is the shape the product's decoder loop uses; [`decode_float`] is
130 /// the same work without the allocation.
131 ///
132 /// [`decode_float`]: MultistreamDecoder::decode_float
133 pub fn decode_packet(&mut self, data: &[u8]) -> Result<Vec<f32>> {
134 // A packet is at most 120 ms, and the sample rate at most 48 kHz.
135 let mut out = vec![0.0; 5760 * self.channels * self.sample_rate as usize / 48000];
136 let n = self.decode_float(data, &mut out)?;
137 out.truncate(n * self.channels);
138 Ok(out)
139 }
140
141 /// Decodes one multistream packet into `out`, returning samples per
142 /// channel.
143 pub fn decode_float(&mut self, data: &[u8], out: &mut [f32]) -> Result<usize> {
144 // Every stream but the last needs at least a TOC and a length byte.
145 if data.len() < 2 * self.streams.len() - 1 {
146 return Err(Error::corrupt(format!(
147 "opus multistream: {} bytes for {} streams",
148 data.len(),
149 self.streams.len()
150 )));
151 }
152 let mut rest = data;
153 let mut frame_size = 0usize;
154 let nb_streams = self.streams.len();
155 for s in 0..nb_streams {
156 let last = s == nb_streams - 1;
157 let stream_channels = if s < self.coupled { 2 } else { 1 };
158 let need = 5760 * stream_channels;
159 if self.buf.len() < need {
160 self.buf.resize(need, 0.0);
161 }
162 let (n, consumed) = if last {
163 (
164 self.streams[s].decode_float(rest, &mut self.buf)?,
165 rest.len(),
166 )
167 } else {
168 self.streams[s].decode_self_delimited(rest, &mut self.buf)?
169 };
170 rest = &rest[consumed.min(rest.len())..];
171 if s == 0 {
172 frame_size = n;
173 self.check_out(frame_size, out)?;
174 } else if n != frame_size {
175 return Err(Error::corrupt(format!(
176 "opus multistream: stream {s} decoded {n} samples, stream 0 gave {frame_size}"
177 )));
178 }
179 self.route(s, frame_size, out);
180 }
181 self.silence(frame_size, out);
182 Ok(frame_size)
183 }
184
185 /// Conceals `frame_size` lost samples per channel on every stream
186 /// (libopus `opus_multistream_decode(NULL)`), returning samples per
187 /// channel.
188 pub fn conceal(&mut self, frame_size: usize, out: &mut [f32]) -> Result<usize> {
189 self.check_out(frame_size, out)?;
190 for s in 0..self.streams.len() {
191 self.streams[s].conceal(frame_size, &mut self.buf)?;
192 self.route(s, frame_size, out);
193 }
194 self.silence(frame_size, out);
195 Ok(frame_size)
196 }
197
198 /// Recovers a lost multistream packet from the in-band FEC of the packet
199 /// after it (libopus `decode_fec=1`). Each stream's first frame is handed
200 /// to that stream's FEC path; a stream whose bytes cannot be read, and
201 /// every stream after it, is concealed. Returns samples per channel.
202 pub fn decode_fec(
203 &mut self,
204 next_packet: &[u8],
205 frame_size: usize,
206 out: &mut [f32],
207 ) -> Result<usize> {
208 self.check_out(frame_size, out)?;
209 let nb_streams = self.streams.len();
210 let mut rest = next_packet;
211 for s in 0..nb_streams {
212 let last = s == nb_streams - 1;
213 match first_frame(rest, !last, &mut self.fec) {
214 Ok(consumed) => {
215 rest = &rest[consumed.min(rest.len())..];
216 self.streams[s].decode_fec(&self.fec, frame_size, &mut self.buf)?;
217 }
218 Err(_) => {
219 rest = &[];
220 self.streams[s].conceal(frame_size, &mut self.buf)?;
221 }
222 }
223 self.route(s, frame_size, out);
224 }
225 self.silence(frame_size, out);
226 Ok(frame_size)
227 }
228
229 fn check_out(&self, frame_size: usize, out: &[f32]) -> Result<()> {
230 if out.len() < frame_size * self.channels {
231 return Err(Error::corrupt(format!(
232 "opus multistream: output buffer holds {} samples, packet needs {}",
233 out.len(),
234 frame_size * self.channels
235 )));
236 }
237 Ok(())
238 }
239
240 /// Copies stream `s`'s channels from `self.buf` to the output channels
241 /// the mapping names.
242 fn route(&self, s: usize, frame_size: usize, out: &mut [f32]) {
243 let stream_channels = if s < self.coupled { 2 } else { 1 };
244 for (c, &m) in self.mapping.iter().enumerate() {
245 if m == 255 {
246 continue;
247 }
248 let m = m as usize;
249 let src = if s < self.coupled {
250 if m == 2 * s {
251 Some(0)
252 } else if m == 2 * s + 1 {
253 Some(1)
254 } else {
255 None
256 }
257 } else if m == s + self.coupled {
258 Some(0)
259 } else {
260 None
261 };
262 if let Some(off) = src {
263 for i in 0..frame_size {
264 out[self.channels * i + c] = self.buf[stream_channels * i + off];
265 }
266 }
267 }
268 }
269
270 /// Channels the mapping leaves unassigned are silent.
271 fn silence(&self, frame_size: usize, out: &mut [f32]) {
272 for (c, &m) in self.mapping.iter().enumerate() {
273 if m == 255 {
274 for i in 0..frame_size {
275 out[self.channels * i + c] = 0.0;
276 }
277 }
278 }
279 }
280}
281
282/// Reads the first frame of the stream packet at the head of `data` and
283/// rebuilds it as a plain code-0 packet in `scratch`, returning the bytes the
284/// stream packet occupied.
285fn first_frame(data: &[u8], self_delimited: bool, scratch: &mut Vec<u8>) -> Result<usize> {
286 let packet = Packet::parse(data, self_delimited)?;
287 let first: &[u8] = packet.frames.first().copied().unwrap_or(&[]);
288 let toc = packet.toc;
289 scratch.clear();
290 scratch.push((toc.config << 3) | (u8::from(toc.stereo) << 2));
291 scratch.extend_from_slice(first);
292 Ok(packet.consumed)
293}
294
295#[cfg(test)]
296mod tests {
297 use super::*;
298
299 #[test]
300 fn layouts_are_checked() {
301 // RFC 7845 mapping family 1, 5.1: four streams, two of them coupled.
302 assert!(MultistreamDecoder::try_with_rate(48000, 4, 2, &[0, 4, 1, 2, 3, 5]).is_ok());
303 // More coupled streams than streams.
304 assert!(MultistreamDecoder::try_with_rate(48000, 2, 3, &[0, 1]).is_err());
305 // A mapping entry naming a channel no stream codes: 4 streams with 2
306 // coupled code 6 channels, so 6 is out of range.
307 assert!(MultistreamDecoder::try_with_rate(48000, 4, 2, &[0, 6]).is_err());
308 // 255 is the silent channel and is always allowed.
309 assert!(MultistreamDecoder::try_with_rate(48000, 1, 0, &[0, 255]).is_ok());
310 assert!(MultistreamDecoder::try_with_rate(44100, 1, 0, &[0]).is_err());
311 }
312
313 #[test]
314 fn truncated_packets_are_errors_not_panics() {
315 let mut dec = MultistreamDecoder::with_rate(48000, 4, 2, &[0, 4, 1, 2, 3, 5]);
316 for n in 0..40usize {
317 let data: Vec<u8> = (0..n).map(|i| (i * 37 + 11) as u8).collect();
318 let _ = dec.decode_packet(&data);
319 }
320 }
321}