forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBbcb4dc5Tahinli21 days ago1034 commits

opus_write.rs222 lines, 9.3 KiBHistoryRawDownload
1//! Writes interleaved PCM as a standalone `.opus` file: Opus in Ogg, RFC 7845.
2//! `ec-opus` encodes, `ec-ogg` pages.
3//!
4//! What the file states, and why each number is what it is:
5//!
6//! - **`OpusHead`**: the channel count; the pre-skip (the encoder's look-ahead
7//! plus one warm-up frame, see [`write`]); the input rate; mapping family 0
8//! for mono and stereo, family 1 (Vorbis channel order, with the stream and
9//! coupled counts and the table) for 3 to 8 channels.
10//! - **`OpusTags`**: the vendor, an `ENCODER` tag, the language where the mix
11//! has one, and the chapters as the `CHAPTERxxx` / `CHAPTERxxxNAME` comments
12//! ffmpeg writes and reads.
13//! - **Granule positions** at 48 kHz with the pre-skip counted, the last one
14//! trimming the final frame's padding, so the duration is exactly the
15//! samples handed in.
16
17use std::fs::File;
18use std::io::BufWriter;
19use std::path::Path;
20
21use ec_core::registry::{AudioParameters, CodecId, CodecParameters, MediaParameters, StreamInfo};
22use ec_core::{ChannelLayout, Muxer as _, Packet, TimeBase};
23
24/// The only clock an Opus stream has (RFC 7845 §4).
25pub const RATE: u32 = 48_000;
26
27/// 20 ms at [`RATE`]: the frame every packet codes.
28const FRAME: usize = 960;
29
30/// The rates RFC 6716 gives an Opus stream, in kbps, that a file is clamped into.
31pub const MIN_KBPS: u32 = 6;
32pub const MAX_KBPS: u32 = 510;
33
34/// What a file with no rate asked for is coded at: transparent for stereo
35/// music, and half the AAC default, because Opus is that much better at it.
36pub const DEFAULT_KBPS: u32 = 128;
37
38/// The vendor string in `OpusTags`.
39const VENDOR: &str = "ec-opus";
40
41/// What travels in `OpusTags` beside the vendor.
42#[derive(Debug, Clone, Default)]
43pub struct Tags<'a> {
44 /// A language code for the `LANGUAGE` comment.
45 pub language: Option<&'a str>,
46 /// `(start in ns, title)`, sorted by start: `CHAPTERxxx` comments.
47 pub chapters: &'a [(u64, String)],
48}
49
50/// Where WAV/film channel `c` sits in Vorbis order, per channel count: the
51/// order family 1 codes in (RFC 7845 §5.1.1.2). `vorbis[i] = wav[ORDER[i]]`.
52fn wav_to_vorbis(channels: usize) -> &'static [usize] {
53 match channels {
54 1 => &[0],
55 2 => &[0, 1],
56 3 => &[0, 2, 1],
57 4 => &[0, 1, 2, 3],
58 5 => &[0, 2, 1, 3, 4],
59 6 => &[0, 2, 1, 4, 5, 3],
60 7 => &[0, 2, 1, 5, 6, 4, 3],
61 _ => &[0, 2, 1, 6, 7, 4, 5, 3],
62 }
63}
64
65/// `OpusTags` with the vendor, `ENCODER`, `LANGUAGE` and the chapters.
66fn opus_tags(tags: &Tags) -> Vec<u8> {
67 let mut comments = vec![format!("ENCODER=edith ({VENDOR})")];
68 if let Some(lang) = tags.language.filter(|l| !l.is_empty()) {
69 comments.push(format!("LANGUAGE={lang}"));
70 }
71 for (i, (ns, title)) in tags.chapters.iter().enumerate() {
72 let ms = ns / 1_000_000;
73 let (h, m, s, ms) = (ms / 3_600_000, ms / 60_000 % 60, ms / 1000 % 60, ms % 1000);
74 comments.push(format!("CHAPTER{i:03}={h:02}:{m:02}:{s:02}.{ms:03}"));
75 comments.push(format!("CHAPTER{i:03}NAME={title}"));
76 }
77 let mut out = Vec::from(*b"OpusTags");
78 out.extend_from_slice(&(VENDOR.len() as u32).to_le_bytes());
79 out.extend_from_slice(VENDOR.as_bytes());
80 out.extend_from_slice(&(comments.len() as u32).to_le_bytes());
81 for c in &comments {
82 out.extend_from_slice(&(c.len() as u32).to_le_bytes());
83 out.extend_from_slice(c.as_bytes());
84 }
85 out
86}
87
88/// Encode `pcm` (interleaved, `channels` wide in WAV/film order, at [`RATE`])
89/// at `kbps` total and write the file to `out`. `input_rate` is what the
90/// header reports as the rate the sound arrived at. `tick` runs once per
91/// packet with the fraction done, and an `Err` from it stops the write (the
92/// export's cancel).
93///
94/// Every stream is pinned to CELT: its look-ahead is one fixed number, so the
95/// pre-skip holds for the whole file and every stream of a surround one lines
96/// up with the others. The first frame is coded twice -- once to warm the
97/// encoder, which has no history behind it and rings, and once for real --
98/// and the warm-up is inside the pre-skip, exactly what pre-skip is for.
99pub fn write(
100 out: &Path,
101 pcm: &[f32],
102 channels: usize,
103 input_rate: u32,
104 kbps: u32,
105 tags: &Tags,
106 tick: &mut dyn FnMut(f32) -> crate::Result<()>,
107) -> crate::Result<()> {
108 let (family, n_streams, coupled, table) = ec_opus::ogg::default_mapping(channels)
109 .ok_or_else(|| format!("Opus maps 1 to 8 channels, and this mix has {channels}"))?;
110 let (n_streams, coupled) = (usize::from(n_streams), usize::from(coupled));
111 let frames = pcm.len() / channels;
112 if frames == 0 {
113 return Err("opus encode: no samples is not a stream".into());
114 }
115 let order = wav_to_vorbis(channels);
116
117 let total = kbps.clamp(MIN_KBPS, MAX_KBPS) * 1000;
118 let share = total / (2 * coupled + (n_streams - coupled)) as u32;
119 let mut encoders = Vec::with_capacity(n_streams);
120 for s in 0..n_streams {
121 let width = if s < coupled { 2 } else { 1 };
122 let mut enc = ec_opus::Encoder::new(RATE, width, ec_opus::Application::Audio)
123 .map_err(|e| format!("the Opus encoder refused {width} channels: {e}"))?;
124 enc.set_mode(Some(ec_opus::Mode::Celt));
125 enc.set_bitrate(share * width as u32);
126 encoders.push(enc);
127 }
128 let pre_skip = encoders[0].look_ahead(FRAME) + FRAME;
129 let pre_skip16 = u16::try_from(pre_skip).map_err(|_| "opus encode: pre-skip over 65535")?;
130 // Exactly as many packets as the pre-skip plus the samples need: the last
131 // one carries the tail and its granule trims the padding after it.
132 let count = (pre_skip + frames).div_ceil(FRAME);
133
134 let head = ec_opus::ogg::opus_head(
135 channels as u8,
136 pre_skip16,
137 input_rate,
138 0,
139 (family != 0).then_some((family, n_streams as u8, coupled as u8, table.as_slice())),
140 );
141 let time_base = TimeBase::try_new(1, i64::from(RATE)).map_err(|e| format!("ogg mux: {e}"))?;
142 let mut params = CodecParameters::new(CodecId::Opus);
143 params.media = MediaParameters::Audio(AudioParameters {
144 sample_rate: RATE,
145 layout: match channels {
146 1 => ChannelLayout::Mono,
147 _ => ChannelLayout::Stereo,
148 },
149 ..AudioParameters::default()
150 });
151 let mut stream = StreamInfo::new(0, time_base, params);
152 stream.duration = Some(frames as i64);
153 stream.start_time = Some(0);
154 let mut muxer = ec_ogg::OggMuxer::new(BufWriter::new(File::create(out)?));
155 muxer.set_page_target_bytes(Some(4096));
156 muxer.add_stream(stream).map_err(|e| format!("ogg mux: {e}"))?;
157 for header in [head, opus_tags(tags)] {
158 let mut packet = Packet::new(0, time_base, header);
159 packet.flags.header = true;
160 muxer.write_packet(&packet).map_err(|e| format!("ogg mux: {e}"))?;
161 }
162
163 let mut frame = vec![0f32; FRAME * channels];
164 let mut stream_buf = vec![0f32; FRAME * 2];
165 let mut bytes = vec![0u8; 1500 * n_streams];
166 for p in 0..count {
167 tick(p as f32 / count as f32)?;
168 // Packet 0 is the warm-up: the first frame, coded again as packet 1.
169 let from = p.saturating_sub(1) * FRAME;
170 let block = &pcm[(from * channels).min(pcm.len())..((from + FRAME) * channels).min(pcm.len())];
171 frame[..block.len()].copy_from_slice(block);
172 frame[block.len()..].fill(0.0);
173 let mut len = 0;
174 for (s, enc) in encoders.iter_mut().enumerate() {
175 let width = if s < coupled { 2 } else { 1 };
176 for off in 0..width {
177 let coded = if s < coupled { 2 * s + off } else { coupled + s };
178 // The Vorbis-order channel that feeds this coded one.
179 let vorbis = table.iter().position(|&m| usize::from(m) == coded);
180 for i in 0..FRAME {
181 stream_buf[i * width + off] =
182 vorbis.map_or(0.0, |v| frame[i * channels + order[v]]);
183 }
184 }
185 let input = &stream_buf[..FRAME * width];
186 let n = if s + 1 == n_streams {
187 enc.encode_float(input, FRAME, &mut bytes[len..])
188 } else {
189 enc.encode_self_delimited(input, FRAME, &mut bytes[len..])
190 }
191 .map_err(|e| format!("Opus encode failed: {e}"))?;
192 len += n;
193 }
194 let granule = match p + 1 == count {
195 true => pre_skip + frames,
196 false => (p + 1) * FRAME,
197 };
198 let mut packet =
199 Packet::new(0, time_base, bytes[..len].to_vec()).with_duration(FRAME as i64);
200 packet.side_data.push(ec_ogg::granule_side_data(granule as i64));
201 muxer.write_packet(&packet).map_err(|e| format!("ogg mux: {e}"))?;
202 }
203 muxer.finish().map_err(|e| format!("ogg mux: {e}"))?;
204 Ok(())
205}
206
207#[cfg(test)]
208mod tests {
209 use super::*;
210
211 #[test]
212 fn the_tags_carry_the_chapters_the_way_ffmpeg_writes_them() {
213 let chapters = vec![(0, "Intro".to_string()), (61_500_000_000, "Two".to_string())];
214 let tags = opus_tags(&Tags { language: Some("eng"), chapters: &chapters });
215 let text = String::from_utf8_lossy(&tags);
216 for want in ["ENCODER=edith", "LANGUAGE=eng", "CHAPTER000=00:00:00.000", "CHAPTER000NAME=Intro",
217 "CHAPTER001=00:01:01.500", "CHAPTER001NAME=Two"] {
218 assert!(text.contains(want), "{want} in {text}");
219 }
220 assert_eq!(u32::from_le_bytes(tags[19..23].try_into().unwrap()), 6, "comment count");
221 }
222}