forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBeb83b6fTahinli3 months ago495 commits

multistream.rs245 lines, 9.1 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::Decoder;
24
25/// A decoder for a multichannel Opus stream, mono through 255 channels.
26#[derive(Debug)]
27pub struct MultistreamDecoder {
28 streams: Vec<Decoder>,
29 coupled: usize,
30 mapping: Vec<u8>,
31 channels: usize,
32 sample_rate: u32,
33 /// Scratch for one stream's output.
34 buf: Vec<f32>,
35}
36
37impl MultistreamDecoder {
38 /// A decoder for `streams` elementary streams of which the first `coupled`
39 /// are stereo, with `mapping` naming the coded channel each output channel
40 /// comes from.
41 ///
42 /// # Panics
43 /// On a layout that breaks the RFC's limits — more coupled streams than
44 /// streams, a mapping entry naming a channel no stream codes, an
45 /// unsupported rate. The layout comes from a container header, so callers
46 /// that read one from a file should check it (or use
47 /// [`MultistreamDecoder::try_with_rate`]) rather than pass it straight in.
48 pub fn with_rate(
49 sample_rate: u32,
50 streams: usize,
51 coupled: usize,
52 mapping: &[u8],
53 ) -> MultistreamDecoder {
54 match Self::try_with_rate(sample_rate, streams, coupled, mapping) {
55 Ok(d) => d,
56 Err(e) => panic!("invalid Opus multistream layout: {e}"),
57 }
58 }
59
60 /// [`MultistreamDecoder::with_rate`] with the layout checked instead of
61 /// asserted.
62 pub fn try_with_rate(
63 sample_rate: u32,
64 streams: usize,
65 coupled: usize,
66 mapping: &[u8],
67 ) -> Result<MultistreamDecoder> {
68 if streams == 0 || streams > 255 || coupled > streams {
69 return Err(Error::corrupt(format!(
70 "opus multistream: {streams} streams of which {coupled} coupled"
71 )));
72 }
73 let coded = coupled + streams;
74 if mapping.is_empty() || mapping.len() > 255 {
75 return Err(Error::corrupt(format!(
76 "opus multistream: {} output channels",
77 mapping.len()
78 )));
79 }
80 if let Some(&bad) = mapping.iter().find(|&&m| m != 255 && m as usize >= coded) {
81 return Err(Error::corrupt(format!(
82 "opus multistream: mapping entry {bad} names a channel of {coded}"
83 )));
84 }
85 let mut decoders = Vec::with_capacity(streams);
86 for s in 0..streams {
87 let ch = if s < coupled { 2 } else { 1 };
88 decoders.push(Decoder::new(sample_rate, ch)?);
89 }
90 Ok(MultistreamDecoder {
91 streams: decoders,
92 coupled,
93 mapping: mapping.to_vec(),
94 channels: mapping.len(),
95 sample_rate,
96 buf: vec![0.0; 2 * 5760],
97 })
98 }
99
100 /// Output channels.
101 pub fn channels(&self) -> usize {
102 self.channels
103 }
104
105 /// Output sample rate.
106 pub fn sample_rate(&self) -> u32 {
107 self.sample_rate
108 }
109
110 /// Drops all inter-packet state in every stream; call after a seek.
111 pub fn reset(&mut self) {
112 for s in self.streams.iter_mut() {
113 s.reset();
114 }
115 }
116
117 /// The range coder states of all streams, combined the way RFC 6716
118 /// Section 6 combines them for conformance checking.
119 pub fn final_range(&self) -> u32 {
120 self.streams.iter().fold(0, |acc, s| acc ^ s.final_range())
121 }
122
123 /// Decodes one multistream packet into a fresh interleaved buffer.
124 ///
125 /// This is the shape the product's decoder loop uses; [`decode_float`] is
126 /// the same work without the allocation.
127 ///
128 /// [`decode_float`]: MultistreamDecoder::decode_float
129 pub fn decode_packet(&mut self, data: &[u8]) -> Result<Vec<f32>> {
130 // A packet is at most 120 ms, and the sample rate at most 48 kHz.
131 let mut out = vec![0.0; 5760 * self.channels * self.sample_rate as usize / 48000];
132 let n = self.decode_float(data, &mut out)?;
133 out.truncate(n * self.channels);
134 Ok(out)
135 }
136
137 /// Decodes one multistream packet into `out`, returning samples per
138 /// channel.
139 pub fn decode_float(&mut self, data: &[u8], out: &mut [f32]) -> Result<usize> {
140 // Every stream but the last needs at least a TOC and a length byte.
141 if data.len() < 2 * self.streams.len() - 1 {
142 return Err(Error::corrupt(format!(
143 "opus multistream: {} bytes for {} streams",
144 data.len(),
145 self.streams.len()
146 )));
147 }
148 let mut rest = data;
149 let mut frame_size = 0usize;
150 let nb_streams = self.streams.len();
151 for s in 0..nb_streams {
152 let last = s == nb_streams - 1;
153 let stream_channels = if s < self.coupled { 2 } else { 1 };
154 let need = 5760 * stream_channels;
155 if self.buf.len() < need {
156 self.buf.resize(need, 0.0);
157 }
158 let (n, consumed) = if last {
159 (
160 self.streams[s].decode_float(rest, &mut self.buf)?,
161 rest.len(),
162 )
163 } else {
164 self.streams[s].decode_self_delimited(rest, &mut self.buf)?
165 };
166 rest = &rest[consumed.min(rest.len())..];
167 if s == 0 {
168 frame_size = n;
169 if out.len() < n * self.channels {
170 return Err(Error::corrupt(format!(
171 "opus multistream: output buffer holds {} samples, packet needs {}",
172 out.len(),
173 n * self.channels
174 )));
175 }
176 } else if n != frame_size {
177 return Err(Error::corrupt(format!(
178 "opus multistream: stream {s} decoded {n} samples, stream 0 gave {frame_size}"
179 )));
180 }
181 // Route this stream's channels to the outputs that name them.
182 for (c, &m) in self.mapping.iter().enumerate() {
183 if m == 255 {
184 continue;
185 }
186 let m = m as usize;
187 let src = if s < self.coupled {
188 if m == 2 * s {
189 Some(0)
190 } else if m == 2 * s + 1 {
191 Some(1)
192 } else {
193 None
194 }
195 } else if m == s + self.coupled {
196 Some(0)
197 } else {
198 None
199 };
200 if let Some(off) = src {
201 for i in 0..frame_size {
202 out[self.channels * i + c] = self.buf[stream_channels * i + off];
203 }
204 }
205 }
206 }
207 // Channels the mapping leaves unassigned are silent.
208 for (c, &m) in self.mapping.iter().enumerate() {
209 if m == 255 {
210 for i in 0..frame_size {
211 out[self.channels * i + c] = 0.0;
212 }
213 }
214 }
215 Ok(frame_size)
216 }
217}
218
219#[cfg(test)]
220mod tests {
221 use super::*;
222
223 #[test]
224 fn layouts_are_checked() {
225 // RFC 7845 mapping family 1, 5.1: four streams, two of them coupled.
226 assert!(MultistreamDecoder::try_with_rate(48000, 4, 2, &[0, 4, 1, 2, 3, 5]).is_ok());
227 // More coupled streams than streams.
228 assert!(MultistreamDecoder::try_with_rate(48000, 2, 3, &[0, 1]).is_err());
229 // A mapping entry naming a channel no stream codes: 4 streams with 2
230 // coupled code 6 channels, so 6 is out of range.
231 assert!(MultistreamDecoder::try_with_rate(48000, 4, 2, &[0, 6]).is_err());
232 // 255 is the silent channel and is always allowed.
233 assert!(MultistreamDecoder::try_with_rate(48000, 1, 0, &[0, 255]).is_ok());
234 assert!(MultistreamDecoder::try_with_rate(44100, 1, 0, &[0]).is_err());
235 }
236
237 #[test]
238 fn truncated_packets_are_errors_not_panics() {
239 let mut dec = MultistreamDecoder::with_rate(48000, 4, 2, &[0, 4, 1, 2, 3, 5]);
240 for n in 0..40usize {
241 let data: Vec<u8> = (0..n).map(|i| (i * 37 + 11) as u8).collect();
242 let _ = dec.decode_packet(&data);
243 }
244 }
245}