forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust379.8 MiB780c4a9Tahinli5 hours ago4220 commits

encode_audio.rs363 lines, 11.5 KiBHistoryRawDownload
1use ec_aac::{AacEncoder, AacEncoderConfig, WindowShape};
2use ec_ac3::{Ac3Encoder, EncoderConfig as Ac3Config};
3use ec_alac::AlacEncoder;
4use ec_core::registry::Encoder as _;
5use ec_core::{AudioFrame, Buf, ChannelLayout, Frame, SampleFormat};
6use ec_flac::EncoderConfig as FlacConfig;
7use ec_mp3::{Mp3Encoder, Mp3EncoderConfig};
8use ec_opus::{Application, Encoder as OpusEncoder, MultistreamEncoder};
9use ec_truehd::TrueHdEncoder;
10use ec_vorbis::{EncoderConfig as VorbisConfig, VorbisEncoder};
11
12const FRAMES: usize = 24_000;
13const SEED: u64 = 0x2545_F491_4F6C_DD1D;
14const PACKET_CAP: usize = 4000;
15
16pub fn run() {
17 aac();
18 mp3();
19 opus();
20 vorbis();
21 flac();
22 alac();
23 ac3();
24 truehd();
25}
26
27fn emit(codec: &str, config: &str, index: usize, encode: impl FnOnce() -> ec_core::Result<Vec<u8>>) {
28 let name = format!("encode_audio/{codec}/{config}/{index}");
29 crate::guard(&name, || match encode() {
30 Ok(bytes) => crate::hash(&name, &bytes),
31 Err(err) => crate::error(&name, err),
32 });
33}
34
35fn sine(turns: f64) -> f64 {
36 let x = (turns - turns.round()) * std::f64::consts::TAU;
37 let mut term = x;
38 let mut sum = x;
39 for k in 1..10 {
40 let n = f64::from(2 * k);
41 term *= -x * x / (n * (n + 1.0));
42 sum += term;
43 }
44 sum
45}
46
47fn synth(channels: usize, rate: u32, frames: usize) -> Vec<f64> {
48 let mut state = SEED;
49 let mut out = Vec::with_capacity(channels * frames);
50 for t in 0..frames {
51 let time = t as f64 / f64::from(rate);
52 let gate = if (t / 6000) % 2 == 0 { 1.0 } else { 0.15 };
53 for c in 0..channels {
54 state = state
55 .wrapping_mul(6_364_136_223_846_793_005)
56 .wrapping_add(1_442_695_040_888_963_407);
57 let noise = (state >> 11) as f64 / (1u64 << 52) as f64 - 1.0;
58 let tone = 0.4 * sine(440.0 * time * (1.0 + 0.25 * c as f64))
59 + 0.2 * sine(1234.5 * time + c as f64 / 8.0);
60 out.push(((tone + 0.05 * noise) * gate).clamp(-1.0, 1.0));
61 }
62 }
63 out
64}
65
66fn to_f32(samples: &[f64]) -> Vec<f32> {
67 samples.iter().map(|s| *s as f32).collect()
68}
69
70fn to_int(samples: &[f64], bits: u32) -> Vec<i32> {
71 let scale = f64::from((1u32 << (bits - 1)) - 1);
72 samples.iter().map(|s| (*s * scale).round() as i32).collect()
73}
74
75fn aac_encode(cfg: AacEncoderConfig, channels: usize, rate: u32) -> ec_core::Result<Vec<u8>> {
76 let pcm = to_f32(&synth(channels, rate, FRAMES));
77 let mut enc = AacEncoder::new(cfg);
78 enc.push_pcm(&pcm, channels as u16, rate)?;
79 enc.finish();
80 let mut out = enc.audio_specific_config();
81 while let Ok(packet) = enc.next_packet() {
82 out.extend_from_slice(&packet.data);
83 }
84 Ok(out)
85}
86
87fn aac() {
88 let rows = [
89 (1, 64_000, WindowShape::Sine, true, true, true),
90 (2, 128_000, WindowShape::Sine, true, true, true),
91 (2, 96_000, WindowShape::Kbd, true, true, true),
92 (2, 128_000, WindowShape::Sine, false, true, true),
93 (2, 128_000, WindowShape::Sine, true, false, true),
94 (2, 128_000, WindowShape::Sine, true, true, false),
95 (6, 384_000, WindowShape::Sine, true, true, true),
96 ];
97 for (index, (channels, bitrate_bps, window_shape, adts, mid_side, window_switching)) in
98 rows.into_iter().enumerate()
99 {
100 let config = format!(
101 "ch{channels}-{bitrate_bps}-{window_shape:?}-adts{adts}-ms{mid_side}-ws{window_switching}"
102 );
103 let cfg = AacEncoderConfig {
104 bitrate_bps,
105 window_shape,
106 adts,
107 mid_side,
108 window_switching,
109 };
110 emit("aac", &config, index, || aac_encode(cfg, channels, 48_000));
111 }
112}
113
114fn mp3_encode(cfg: Mp3EncoderConfig, channels: usize, rate: u32) -> ec_core::Result<Vec<u8>> {
115 let pcm = to_f32(&synth(channels, rate, FRAMES));
116 let mut enc = Mp3Encoder::new(cfg);
117 enc.push_pcm_f32(&pcm, channels as u16, rate)?;
118 enc.finish();
119 let mut out = Vec::new();
120 while let Ok(frame) = enc.next_packet() {
121 out.extend_from_slice(&frame);
122 }
123 Ok(out)
124}
125
126fn mp3() {
127 let rows = [
128 (44_100, 2, 128, None),
129 (44_100, 1, 64, None),
130 (48_000, 2, 320, None),
131 (48_000, 2, 0, Some(0.2)),
132 (44_100, 2, 0, Some(0.5)),
133 (48_000, 1, 0, Some(0.9)),
134 ];
135 for (index, (rate, channels, bitrate_kbps, vbr_quality)) in rows.into_iter().enumerate() {
136 let mode = match vbr_quality {
137 Some(q) => format!("vbr{q}"),
138 None => format!("cbr{bitrate_kbps}"),
139 };
140 let config = format!("r{rate}-ch{channels}-{mode}");
141 let cfg = Mp3EncoderConfig {
142 bitrate_kbps,
143 vbr_quality,
144 };
145 emit("mp3", &config, index, || mp3_encode(cfg, channels, rate));
146 }
147}
148
149fn opus_encode(
150 app: Application,
151 channels: usize,
152 bitrate_bps: u32,
153 vbr: bool,
154 frame: usize,
155) -> ec_core::Result<Vec<u8>> {
156 let pcm = to_f32(&synth(channels, 48_000, FRAMES));
157 let mut enc = OpusEncoder::new(48_000, channels, app)?;
158 enc.set_bitrate(bitrate_bps);
159 enc.set_vbr_constrained(vbr);
160 let mut out = Vec::new();
161 let mut packet = vec![0u8; PACKET_CAP];
162 for chunk in pcm.chunks_exact(frame * channels) {
163 let n = enc.encode_float(chunk, frame, &mut packet)?;
164 out.extend_from_slice(&packet[..n]);
165 }
166 Ok(out)
167}
168
169fn opus_multi(channels: usize, app: Application, bitrate_bps: u32) -> ec_core::Result<Vec<u8>> {
170 let frame = 960;
171 let pcm = to_f32(&synth(channels, 48_000, FRAMES));
172 let mut enc = MultistreamEncoder::surround(48_000, channels, app)?;
173 enc.set_bitrate(bitrate_bps);
174 let mut out = Vec::new();
175 let mut packet = vec![0u8; PACKET_CAP];
176 for chunk in pcm.chunks_exact(frame * channels) {
177 let n = enc.encode_float(chunk, frame, &mut packet)?;
178 out.extend_from_slice(&packet[..n]);
179 }
180 Ok(out)
181}
182
183fn opus() {
184 let singles = [
185 (Application::Audio, 2, 96_000, true, 960),
186 (Application::Audio, 2, 64_000, false, 960),
187 (Application::Voip, 1, 24_000, true, 960),
188 (Application::Voip, 2, 32_000, false, 960),
189 (Application::LowDelay, 2, 128_000, true, 480),
190 (Application::LowDelay, 1, 64_000, false, 240),
191 ];
192 for (index, (app, channels, bitrate_bps, vbr, frame)) in singles.into_iter().enumerate() {
193 let config = format!("{app:?}-ch{channels}-{bitrate_bps}-vbr{vbr}-frame{frame}");
194 emit("opus", &config, index, || {
195 opus_encode(app, channels, bitrate_bps, vbr, frame)
196 });
197 }
198 let multis = [
199 (2, Application::Audio, 128_000),
200 (6, Application::Audio, 384_000),
201 (6, Application::LowDelay, 384_000),
202 ];
203 for (index, (channels, app, bitrate_bps)) in multis.into_iter().enumerate() {
204 let config = format!("multistream-{app:?}-ch{channels}-{bitrate_bps}");
205 emit("opus", &config, singles.len() + index, || {
206 opus_multi(channels, app, bitrate_bps)
207 });
208 }
209}
210
211fn vorbis_encode(cfg: VorbisConfig, pcm: &[f32]) -> ec_core::Result<Vec<u8>> {
212 let mut enc = VorbisEncoder::new(cfg)?;
213 let mut out = Vec::new();
214 for header in enc.headers() {
215 out.extend_from_slice(header);
216 }
217 enc.push_interleaved(pcm)?;
218 enc.finish();
219 while let Ok(packet) = enc.next_packet() {
220 out.extend_from_slice(&packet.data);
221 }
222 Ok(out)
223}
224
225fn vorbis() {
226 let rows = [
227 (48_000, 2, 128_000, 0.5),
228 (44_100, 1, 64_000, 0.3),
229 (48_000, 2, 0, 0.5),
230 (48_000, 2, 0, 0.9),
231 (48_000, 6, 256_000, 0.5),
232 ];
233 for (index, (rate, channels, bitrate_bps, quality)) in rows.into_iter().enumerate() {
234 let config = format!("r{rate}-ch{channels}-bps{bitrate_bps}-q{quality}");
235 emit("vorbis", &config, index, || {
236 let cfg = VorbisConfig {
237 sample_rate: rate,
238 channels: channels as u16,
239 bitrate_bps,
240 quality,
241 };
242 vorbis_encode(cfg, &to_f32(&synth(channels, rate, FRAMES)))
243 });
244 }
245}
246
247fn flac_config(level: u32) -> FlacConfig {
248 let (block_size, max_lpc_order, max_partition_order, stereo_decorrelation) = match level {
249 0 => (1152, 0, 3, false),
250 1 => (1152, 0, 3, true),
251 2 => (1152, 0, 3, true),
252 3 => (4096, 0, 4, true),
253 4 => (4096, 8, 4, true),
254 5 => (4096, 8, 5, true),
255 6 => (4096, 8, 6, true),
256 7 => (4096, 12, 6, true),
257 _ => (4096, 32, 8, true),
258 };
259 FlacConfig {
260 block_size,
261 max_lpc_order,
262 max_partition_order,
263 stereo_decorrelation,
264 ..Default::default()
265 }
266}
267
268fn flac() {
269 for level in 0..=8u32 {
270 for (d, depth) in [8u32, 16, 24].into_iter().enumerate() {
271 let config = format!("level{level}-depth{depth}");
272 let index = level as usize * 3 + d;
273 emit("flac", &config, index, || {
274 let samples = to_int(&synth(2, 48_000, FRAMES), depth);
275 ec_flac::encode(&flac_config(level), &samples, 2, depth, 48_000)
276 });
277 }
278 }
279}
280
281fn alac_encode(channels: u8, bits: u8, frame: u32) -> ec_core::Result<Vec<u8>> {
282 let enc = AlacEncoder::new(48_000, channels, bits, frame)?;
283 let samples = to_int(&synth(usize::from(channels), 48_000, FRAMES), u32::from(bits));
284 let mut out = enc.cookie().to_bytes().to_vec();
285 for chunk in samples.chunks(frame as usize * usize::from(channels)) {
286 out.extend(enc.encode_frame(chunk)?);
287 }
288 Ok(out)
289}
290
291fn alac() {
292 let rows = [
293 (2, 16, 4096),
294 (2, 24, 4096),
295 (1, 16, 4096),
296 (1, 24, 4096),
297 (2, 24, 352),
298 ];
299 for (index, (channels, bits, frame)) in rows.into_iter().enumerate() {
300 let config = format!("ch{channels}-{bits}bit-frame{frame}");
301 emit("alac", &config, index, || alac_encode(channels, bits, frame));
302 }
303}
304
305fn ac3_encode(rate: u32, channels: usize, bitrate_kbps: u32) -> ec_core::Result<Vec<u8>> {
306 let pcm = to_f32(&synth(channels, rate, FRAMES));
307 let mut enc = Ac3Encoder::new(Ac3Config {
308 sample_rate: rate,
309 channels: channels as u16,
310 bitrate_kbps,
311 })?;
312 enc.push_pcm_f32(&pcm)?;
313 enc.finish();
314 let mut out = Vec::new();
315 while let Ok(frame) = enc.next_packet() {
316 out.extend_from_slice(&frame);
317 }
318 Ok(out)
319}
320
321fn ac3() {
322 let rows = [
323 (48_000, 1, 96),
324 (48_000, 2, 192),
325 (44_100, 2, 192),
326 (32_000, 2, 128),
327 (48_000, 6, 448),
328 ];
329 for (index, (rate, channels, bitrate_kbps)) in rows.into_iter().enumerate() {
330 let config = format!("r{rate}-ch{channels}-{bitrate_kbps}k");
331 emit("ac3", &config, index, || {
332 ac3_encode(rate, channels, bitrate_kbps)
333 });
334 }
335}
336
337fn truehd_encode(rate: u32) -> ec_core::Result<Vec<u8>> {
338 let samples = to_int(&synth(2, rate, FRAMES), 24);
339 let bytes: Vec<u8> = samples.iter().flat_map(|s| (s << 8).to_ne_bytes()).collect();
340 let frame = AudioFrame::try_new(
341 SampleFormat::S32,
342 false,
343 ChannelLayout::Stereo,
344 rate,
345 FRAMES,
346 vec![Buf::from_vec(bytes)],
347 )?;
348 let mut enc = TrueHdEncoder::new(rate)?;
349 enc.send_frame(&Frame::Audio(frame))?;
350 enc.flush()?;
351 let mut out = Vec::new();
352 while let Ok(packet) = enc.receive_packet() {
353 out.extend_from_slice(&packet.data);
354 }
355 Ok(out)
356}
357
358fn truehd() {
359 for (index, rate) in [48_000u32, 44_100, 96_000].into_iter().enumerate() {
360 let config = format!("r{rate}-ch2-24bit");
361 emit("truehd", &config, index, || truehd_encode(rate));
362 }
363}