forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

multistream_enc.rs194 lines, 7.2 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 /// An encoder for `streams` elementary streams of which the first
31 /// `coupled` are stereo, with `mapping` naming the coded channel each
32 /// input channel feeds. Layout rules are the decoder's, checked the same
33 /// way.
34 pub fn new(
35 sample_rate: u32,
36 streams: usize,
37 coupled: usize,
38 mapping: &[u8],
39 application: Application,
40 ) -> Result<MultistreamEncoder> {
41 if streams == 0 || streams > 255 || coupled > streams {
42 return Err(Error::corrupt(format!(
43 "opus multistream: {streams} streams of which {coupled} coupled"
44 )));
45 }
46 let coded = coupled + streams;
47 if mapping.is_empty() || mapping.len() > 255 {
48 return Err(Error::corrupt(format!(
49 "opus multistream: {} input channels",
50 mapping.len()
51 )));
52 }
53 if let Some(&bad) = mapping.iter().find(|&&m| m != 255 && m as usize >= coded) {
54 return Err(Error::corrupt(format!(
55 "opus multistream: mapping entry {bad} names a channel of {coded}"
56 )));
57 }
58 let mut encoders = Vec::with_capacity(streams);
59 for s in 0..streams {
60 let ch = if s < coupled { 2 } else { 1 };
61 encoders.push(Encoder::new(sample_rate, ch, application)?);
62 }
63 Ok(MultistreamEncoder {
64 streams: encoders,
65 coupled,
66 mapping: mapping.to_vec(),
67 channels: mapping.len(),
68 buf: vec![0.0; 2 * 960],
69 })
70 }
71
72 /// The RFC 7845 Section 5.1.1.2 default layout for `channels` channels
73 /// (1 to 8), which for 5.1 is four streams, two coupled, in Vorbis channel
74 /// order (FL, FC, FR, BL, BR, LFE) — see [`crate::ogg::default_mapping`]
75 /// for the permutation a film-order caller applies on the way in.
76 pub fn surround(
77 sample_rate: u32,
78 channels: usize,
79 application: Application,
80 ) -> Result<MultistreamEncoder> {
81 let (_family, streams, coupled, table) =
82 crate::ogg::default_mapping(channels).ok_or_else(|| {
83 Error::unsupported(
84 format!("{channels}-channel Opus stream"),
85 "RFC 7845 maps 1 to 8 channels",
86 )
87 })?;
88 MultistreamEncoder::new(
89 sample_rate,
90 streams as usize,
91 coupled as usize,
92 &table,
93 application,
94 )
95 }
96
97 /// The RFC 7845 mapping-family-1 layout for 5.1: four streams, two
98 /// coupled, Vorbis channel order (FL, FC, FR, BL, BR, LFE).
99 pub fn surround_5_1(sample_rate: u32) -> Result<MultistreamEncoder> {
100 MultistreamEncoder::surround(sample_rate, 6, Application::Audio)
101 }
102
103 /// Input channels per frame.
104 pub fn channels(&self) -> usize {
105 self.channels
106 }
107
108 /// The `(streams, coupled, mapping)` triple a RFC 7845 `OpusHead` needs.
109 pub fn layout(&self) -> (usize, usize, &[u8]) {
110 (self.streams.len(), self.coupled, &self.mapping)
111 }
112
113 /// Total target bitrate in bits per second, split over the streams with
114 /// a coupled stream weighing twice a mono one.
115 pub fn set_bitrate(&mut self, total_bps: u32) {
116 let mono = self.streams.len() - self.coupled;
117 let shares = (2 * self.coupled + mono) as u32;
118 let share = total_bps / shares.max(1);
119 for (s, enc) in self.streams.iter_mut().enumerate() {
120 let w = if s < self.coupled { 2 } else { 1 };
121 enc.set_bitrate(share * w);
122 }
123 }
124
125 /// CBR (default) or constrained VBR, applied to every stream.
126 pub fn set_vbr_constrained(&mut self, vbr: bool) {
127 for enc in self.streams.iter_mut() {
128 enc.set_vbr_constrained(vbr);
129 }
130 }
131
132 /// Drops all inter-frame state in every stream.
133 pub fn reset(&mut self) {
134 for enc in self.streams.iter_mut() {
135 enc.reset();
136 }
137 }
138
139 /// The range coder states of all streams, combined the way RFC 6716
140 /// Section 6 combines them for conformance checking.
141 pub fn final_range(&self) -> u32 {
142 self.streams.iter().fold(0, |acc, s| acc ^ s.final_range())
143 }
144
145 /// Encodes one frame — `frame_size` samples per channel of interleaved
146 /// `f32` in the mapping's channel order — as one multistream Opus packet
147 /// in `out`, returning the packet length.
148 pub fn encode_float(
149 &mut self,
150 pcm: &[f32],
151 frame_size: usize,
152 out: &mut [u8],
153 ) -> Result<usize> {
154 if pcm.len() < frame_size * self.channels {
155 return Err(Error::corrupt(format!(
156 "opus multistream encode: {} samples for {} channels of {frame_size}",
157 pcm.len(),
158 self.channels
159 )));
160 }
161 let nb_streams = self.streams.len();
162 let mut pos = 0usize;
163 for s in 0..nb_streams {
164 let stream_channels = if s < self.coupled { 2 } else { 1 };
165 // Gather this stream's channels; a coded channel nobody feeds is
166 // silence.
167 self.buf[..frame_size * stream_channels].fill(0.0);
168 for off in 0..stream_channels {
169 let coded = if s < self.coupled {
170 2 * s + off
171 } else {
172 self.coupled + s
173 };
174 if let Some(c) = self.mapping.iter().position(|&m| m as usize == coded) {
175 for i in 0..frame_size {
176 self.buf[i * stream_channels + off] = pcm[i * self.channels + c];
177 }
178 }
179 }
180 let last = s == nb_streams - 1;
181 let (head, buf) = (&mut out[pos..], &self.buf[..frame_size * stream_channels]);
182 // The borrow checker cannot see that `buf` and the encoder are
183 // disjoint fields through `&mut self`; a split borrow does.
184 let enc = &mut self.streams[s];
185 let n = if last {
186 enc.encode_float(buf, frame_size, head)?
187 } else {
188 enc.encode_self_delimited(buf, frame_size, head)?
189 };
190 pos += n;
191 }
192 Ok(pos)
193 }
194}