forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

multistream_enc.rs215 lines, 7.9 KiBHistoryRawDownload
1//! Multichannel Opus encoding: several elementary streams in one packet.
2//!
3//! The exact mirror of [`crate::MultistreamDecoder`]: the first `coupled`
4//! streams are stereo, the rest mono, all but the last written in the
5//! self-delimited framing of RFC 6716 Appendix B. `mapping[c]` names the
6//! coded channel that input channel `c` feeds — the same table, in the same
7//! direction, that the decoder uses to route its output, so input channel
8//! *order is the mapping's*: RFC 7845 family 1 (what a 5.1 film track uses)
9//! is Vorbis order — left, centre, right, back left, back right, LFE.
10//!
11//! An input channel mapped to 255 is discarded; a coded channel no input
12//! names is encoded as silence.
13
14use ec_core::{Error, Result};
15
16use crate::encoder::{Application, Encoder};
17
18/// A multichannel Opus encoder, mono through 255 channels.
19#[derive(Debug)]
20pub struct MultistreamEncoder {
21 streams: Vec<Encoder>,
22 coupled: usize,
23 mapping: Vec<u8>,
24 channels: usize,
25 /// Scratch for one stream's deinterleaved input.
26 buf: Vec<f32>,
27}
28
29impl MultistreamEncoder {
30 /// The encoder delay each stream carries for a `frame_size` frame — the
31 /// per-stream [`Encoder::look_ahead`], which every stream shares, and so
32 /// the Ogg-Opus pre-skip a multistream file must carry.
33 pub fn look_ahead(&self, frame_size: usize) -> usize {
34 self.streams[0].look_ahead(frame_size)
35 }
36
37 /// An encoder for `streams` elementary streams of which the first
38 /// `coupled` are stereo, with `mapping` naming the coded channel each
39 /// input channel feeds. Layout rules are the decoder's, checked the same
40 /// way.
41 pub fn new(
42 sample_rate: u32,
43 streams: usize,
44 coupled: usize,
45 mapping: &[u8],
46 application: Application,
47 ) -> Result<MultistreamEncoder> {
48 if streams == 0 || streams > 255 || coupled > streams {
49 return Err(Error::corrupt(format!(
50 "opus multistream: {streams} streams of which {coupled} coupled"
51 )));
52 }
53 let coded = coupled + streams;
54 if mapping.is_empty() || mapping.len() > 255 {
55 return Err(Error::corrupt(format!(
56 "opus multistream: {} input channels",
57 mapping.len()
58 )));
59 }
60 if let Some(&bad) = mapping.iter().find(|&&m| m != 255 && m as usize >= coded) {
61 return Err(Error::corrupt(format!(
62 "opus multistream: mapping entry {bad} names a channel of {coded}"
63 )));
64 }
65 let mut encoders = Vec::with_capacity(streams);
66 for s in 0..streams {
67 let ch = if s < coupled { 2 } else { 1 };
68 encoders.push(Encoder::new(sample_rate, ch, application)?);
69 }
70 Ok(MultistreamEncoder {
71 streams: encoders,
72 coupled,
73 mapping: mapping.to_vec(),
74 channels: mapping.len(),
75 buf: vec![0.0; 2 * 2880],
76 })
77 }
78
79 /// The RFC 7845 Section 5.1.1.2 default layout for `channels` channels
80 /// (1 to 8), which for 5.1 is four streams, two coupled, in Vorbis channel
81 /// order (FL, FC, FR, BL, BR, LFE) — see [`crate::ogg::default_mapping`]
82 /// for the permutation a film-order caller applies on the way in.
83 pub fn surround(
84 sample_rate: u32,
85 channels: usize,
86 application: Application,
87 ) -> Result<MultistreamEncoder> {
88 let (_family, streams, coupled, table) =
89 crate::ogg::default_mapping(channels).ok_or_else(|| {
90 Error::unsupported(
91 format!("{channels}-channel Opus stream"),
92 "RFC 7845 maps 1 to 8 channels",
93 )
94 })?;
95 MultistreamEncoder::new(
96 sample_rate,
97 streams as usize,
98 coupled as usize,
99 &table,
100 application,
101 )
102 }
103
104 /// The RFC 7845 mapping-family-1 layout for 5.1: four streams, two
105 /// coupled, Vorbis channel order (FL, FC, FR, BL, BR, LFE).
106 pub fn surround_5_1(sample_rate: u32) -> Result<MultistreamEncoder> {
107 MultistreamEncoder::surround(sample_rate, 6, Application::Audio)
108 }
109
110 /// Input channels per frame.
111 pub fn channels(&self) -> usize {
112 self.channels
113 }
114
115 /// The `(streams, coupled, mapping)` triple a RFC 7845 `OpusHead` needs.
116 pub fn layout(&self) -> (usize, usize, &[u8]) {
117 (self.streams.len(), self.coupled, &self.mapping)
118 }
119
120 /// Total target bitrate in bits per second, split over the streams with
121 /// a coupled stream weighing twice a mono one.
122 pub fn set_bitrate(&mut self, total_bps: u32) {
123 let mono = self.streams.len() - self.coupled;
124 let shares = (2 * self.coupled + mono) as u32;
125 let share = total_bps / shares.max(1);
126 for (s, enc) in self.streams.iter_mut().enumerate() {
127 let w = if s < self.coupled { 2 } else { 1 };
128 enc.set_bitrate(share * w);
129 }
130 }
131
132 /// CBR (default) or constrained VBR, applied to every stream.
133 pub fn set_vbr_constrained(&mut self, vbr: bool) {
134 for enc in self.streams.iter_mut() {
135 enc.set_vbr_constrained(vbr);
136 }
137 }
138
139 /// OPUS_SET_INBAND_FEC on every stream.
140 pub fn set_inband_fec(&mut self, on: bool) {
141 for enc in self.streams.iter_mut() {
142 enc.set_inband_fec(on);
143 }
144 }
145
146 /// OPUS_SET_PACKET_LOSS_PERC on every stream.
147 pub fn set_packet_loss_perc(&mut self, perc: u8) {
148 for enc in self.streams.iter_mut() {
149 enc.set_packet_loss_perc(perc);
150 }
151 }
152
153 /// Drops all inter-frame state in every stream.
154 pub fn reset(&mut self) {
155 for enc in self.streams.iter_mut() {
156 enc.reset();
157 }
158 }
159
160 /// The range coder states of all streams, combined the way RFC 6716
161 /// Section 6 combines them for conformance checking.
162 pub fn final_range(&self) -> u32 {
163 self.streams.iter().fold(0, |acc, s| acc ^ s.final_range())
164 }
165
166 /// Encodes one frame — `frame_size` samples per channel of interleaved
167 /// `f32` in the mapping's channel order — as one multistream Opus packet
168 /// in `out`, returning the packet length.
169 pub fn encode_float(
170 &mut self,
171 pcm: &[f32],
172 frame_size: usize,
173 out: &mut [u8],
174 ) -> Result<usize> {
175 if pcm.len() < frame_size * self.channels {
176 return Err(Error::corrupt(format!(
177 "opus multistream encode: {} samples for {} channels of {frame_size}",
178 pcm.len(),
179 self.channels
180 )));
181 }
182 let nb_streams = self.streams.len();
183 let mut pos = 0usize;
184 for s in 0..nb_streams {
185 let stream_channels = if s < self.coupled { 2 } else { 1 };
186 // Gather this stream's channels; a coded channel nobody feeds is
187 // silence.
188 self.buf[..frame_size * stream_channels].fill(0.0);
189 for off in 0..stream_channels {
190 let coded = if s < self.coupled {
191 2 * s + off
192 } else {
193 self.coupled + s
194 };
195 if let Some(c) = self.mapping.iter().position(|&m| m as usize == coded) {
196 for i in 0..frame_size {
197 self.buf[i * stream_channels + off] = pcm[i * self.channels + c];
198 }
199 }
200 }
201 let last = s == nb_streams - 1;
202 let (head, buf) = (&mut out[pos..], &self.buf[..frame_size * stream_channels]);
203 // The borrow checker cannot see that `buf` and the encoder are
204 // disjoint fields through `&mut self`; a split borrow does.
205 let enc = &mut self.streams[s];
206 let n = if last {
207 enc.encode_float(buf, frame_size, head)?
208 } else {
209 enc.encode_self_delimited(buf, frame_size, head)?
210 };
211 pos += n;
212 }
213 Ok(pos)
214 }
215}