Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

Opus reads back off the Mac's own reader (#242): the software backend's decoders are made from Symphonia's registry with a libopus decoder added (io/soft/src/opusdec.rs). Symphonia's MP4 reader found an Opus track and had no decoder for it, so the MP4s raea writes itself on Windows and Linux (H.264 + Opus) read as silent: raea media probe listed no audio and raea media share wrote a copy without its sound

shinyobjectz1926af81a5a3
diff --git a/io/soft/src/audio.rs b/io/soft/src/audio.rs
index 83f7022c..c2ec8cca 100644
--- a/io/soft/src/audio.rs
+++ b/io/soft/src/audio.rs
@@ -35,7 +35,7 @@ pub fn decode_audio_symphonia(path: &Path) -> R<Audio> {
.find(|t| t.codec_params.sample_rate.is_some())
.ok_or("no audio track")?
.clone();
- let mut dec = symphonia::default::get_codecs()
+ let mut dec = crate::opusdec::codecs()
.make(&track.codec_params, &DecoderOptions::default())
.map_err(|e| format!("symphonia: {e}"))?;
let mut rate = track.codec_params.sample_rate.unwrap_or(0);
@@ -129,7 +129,7 @@ pub fn decode_audio_window_symphonia(path: &Path, start: f64, secs: f64) -> R<Au
.map_err(|e| format!("symphonia: {e}"))?;
let mut format = probed.format;
let track = format.tracks().iter().find(|t| t.codec_params.sample_rate.is_some()).ok_or("no audio track")?.clone();
- let mut dec = symphonia::default::get_codecs().make(&track.codec_params, &DecoderOptions::default()).map_err(|e| format!("symphonia: {e}"))?;
+ let mut dec = crate::opusdec::codecs().make(&track.codec_params, &DecoderOptions::default()).map_err(|e| format!("symphonia: {e}"))?;
let rate = track.codec_params.sample_rate.unwrap_or(0);
if rate == 0 {
return Err(format!("{}: the sound track has no sample rate", path.display()));
@@ -356,3 +356,34 @@ mod window_tests {
}
}
}
+
+#[cfg(test)]
+mod opus_tests {
+ use raea_io_codec::Audio;
+
+ /// Opus packets as this backend writes them decode back here (#242: no decoder took them, so raea's own MP4s read
+ /// as silent off the Mac): a 440 Hz tone, mono and stereo, comes back at its length and its level.
+ #[test]
+ fn opus_written_here_reads_back() {
+ for channels in [1usize, 2] {
+ let tone: Vec<f32> = (0..48_000).map(|i| 0.5 * (i as f32 * 440.0 * std::f32::consts::TAU / 48_000.0).sin()).collect();
+ let a = Audio { rate: 48_000, channels: vec![tone; channels] };
+ let packets = super::opus_packets(&a).unwrap();
+ let mut dec = crate::packets::AudioPacketDecoder::new("opus", None, 48_000, channels as u32).unwrap();
+ let mut out = vec![Vec::new(); channels];
+ for (_, p) in &packets {
+ let (rate, planes) = dec.decode(p).unwrap();
+ assert_eq!(rate, 48_000);
+ assert_eq!(planes.len(), channels);
+ for (o, p) in out.iter_mut().zip(&planes) {
+ o.extend_from_slice(p);
+ }
+ }
+ let n = out[0].len();
+ assert!((47_000..=49_500).contains(&n), "{channels} channel(s): {n} samples back from 48000");
+ // past the coder's start, the tone's level (0.5 peak is 0.354 RMS)
+ let rms = (out[0][4800..n - 4800].iter().map(|v| v * v).sum::<f32>() / (n - 9600) as f32).sqrt();
+ assert!((rms - 0.354).abs() < 0.03, "{channels} channel(s): RMS {rms}");
+ }
+ }
+}
diff --git a/io/soft/src/lib.rs b/io/soft/src/lib.rs
index 4ab1fbb9..09a06933 100644
--- a/io/soft/src/lib.rs
+++ b/io/soft/src/lib.rs
@@ -12,6 +12,8 @@
mod audio;
#[cfg(feature = "h264")]
mod h264;
+/// Opus read back (libopus) as a Symphonia decoder, and the registry every decoder here is made from
+mod opusdec;
/// packet-level audio decoding (Symphonia), for coders handed packets
pub mod packets;
mod probe;
diff --git a/io/soft/src/opusdec.rs b/io/soft/src/opusdec.rs
new file mode 100644
index 00000000..f45c5a93
--- /dev/null
+++ b/io/soft/src/opusdec.rs
@@ -0,0 +1,103 @@
+//! Opus read back (libopus), as a Symphonia decoder: Symphonia's MP4 reader finds an Opus track and has no decoder for
+//! it, so the MP4s this backend writes itself (H.264 + Opus) came back without their sound wherever no platform reader
+//! stood in front (raea #242: on Windows `raea media probe` listed no audio and `raea media share` wrote a silent copy).
+//! `codecs()` is Symphonia's registry with this one added; every decoder here is made from it.
+
+use std::sync::{Mutex, OnceLock};
+
+use symphonia::core::audio::{AsAudioBufferRef, AudioBuffer, AudioBufferRef, Channels, Signal, SignalSpec};
+use symphonia::core::codecs::{CODEC_TYPE_OPUS, CodecDescriptor, CodecParameters, CodecRegistry, Decoder, DecoderOptions, FinalizeResult};
+use symphonia::core::errors::{Result, decode_error, unsupported_error};
+use symphonia::core::formats::Packet;
+use symphonia::core::support_codec;
+
+/// Opus always decodes at 48 kHz, and a packet holds at most 120 ms of it
+const RATE: u32 = 48_000;
+const MAX_FRAMES: usize = 5760;
+
+pub struct OpusDecoder {
+ params: CodecParameters,
+ /// (behind a lock only because a Symphonia decoder must be Sync, which libopus's state isn't: one caller at a time)
+ dec: Mutex<opus::Decoder>,
+ channels: usize,
+ pcm: Vec<f32>,
+ buf: AudioBuffer<f32>,
+}
+
+/// Symphonia's own codecs and Opus.
+pub fn codecs() -> &'static CodecRegistry {
+ static ALL: OnceLock<CodecRegistry> = OnceLock::new();
+ ALL.get_or_init(|| {
+ let mut r = CodecRegistry::new();
+ symphonia::default::register_enabled_codecs(&mut r);
+ r.register_all::<OpusDecoder>();
+ r
+ })
+}
+
+/// How many channels an Opus track has: its identification header's count (OpusHead, as an MP4's dOps box and an Ogg
+/// stream's first packet both carry it: 8 bytes of magic, a version, the count), else what the container said.
+fn channel_count(p: &CodecParameters) -> usize {
+ let head = p.extra_data.as_deref().filter(|d| d.len() > 9 && d.starts_with(b"OpusHead")).map(|d| d[9] as usize);
+ let said = p.channels.map(|c| c.count()).or(p.channel_layout.map(|l| l.into_channels().count()));
+ head.or(said).unwrap_or(2)
+}
+
+impl Decoder for OpusDecoder {
+ fn try_new(params: &CodecParameters, _: &DecoderOptions) -> Result<Self> {
+ if params.codec != CODEC_TYPE_OPUS {
+ return unsupported_error("opus: not an Opus track");
+ }
+ // mono and stereo (what raea writes, and nearly every Opus file): a surround stream is several coupled streams
+ // under a mapping, which this isn't
+ let (channels, layout, how) = match channel_count(params) {
+ 1 => (1, Channels::FRONT_LEFT, opus::Channels::Mono),
+ 2 => (2, Channels::FRONT_LEFT | Channels::FRONT_RIGHT, opus::Channels::Stereo),
+ _ => return unsupported_error("opus: more than two channels"),
+ };
+ let dec = match opus::Decoder::new(RATE, how) {
+ Ok(d) => d,
+ Err(_) => return unsupported_error("opus: the decoder didn't start"),
+ };
+ let mut params = params.clone();
+ params.with_sample_rate(RATE).with_channels(layout);
+ Ok(OpusDecoder { params, dec: Mutex::new(dec), channels, pcm: vec![0.0; MAX_FRAMES * channels], buf: AudioBuffer::new(MAX_FRAMES as u64, SignalSpec::new(RATE, layout)) })
+ }
+
+ fn supported_codecs() -> &'static [CodecDescriptor] {
+ &[support_codec!(CODEC_TYPE_OPUS, "opus", "Opus")]
+ }
+
+ fn reset(&mut self) {
+ if let Ok(d) = self.dec.get_mut() {
+ let _ = d.reset_state();
+ }
+ }
+
+ fn codec_params(&self) -> &CodecParameters {
+ &self.params
+ }
+
+ fn decode(&mut self, packet: &Packet) -> Result<AudioBufferRef<'_>> {
+ self.buf.clear();
+ let n = match self.dec.get_mut().map(|d| d.decode_float(packet.buf(), &mut self.pcm, false)) {
+ Ok(Ok(n)) => n,
+ _ => return decode_error("opus: a packet didn't decode"),
+ };
+ self.buf.render_reserved(Some(n));
+ for c in 0..self.channels {
+ for (o, i) in self.buf.chan_mut(c).iter_mut().zip(self.pcm.iter().skip(c).step_by(self.channels)) {
+ *o = *i;
+ }
+ }
+ Ok(self.buf.as_audio_buffer_ref())
+ }
+
+ fn finalize(&mut self) -> FinalizeResult {
+ FinalizeResult::default()
+ }
+
+ fn last_decoded(&self) -> AudioBufferRef<'_> {
+ self.buf.as_audio_buffer_ref()
+ }
+}
diff --git a/io/soft/src/packets.rs b/io/soft/src/packets.rs
index eddb31e7..7634b8f5 100644
--- a/io/soft/src/packets.rs
+++ b/io/soft/src/packets.rs
@@ -1,5 +1,5 @@
//! Packet-level audio decoding (Symphonia), for coders handed compressed packets one at a time: AAC (with its
-//! AudioSpecificConfig), MP3, FLAC, PCM, as Symphonia reads them. Planar f32 out.
+//! AudioSpecificConfig), MP3, FLAC, PCM, as Symphonia reads them, and Opus (opusdec.rs). Planar f32 out.
use symphonia::core::audio::{AudioBufferRef, Signal};
use symphonia::core::codecs::{CodecParameters, Decoder, DecoderOptions};
@@ -19,7 +19,8 @@ fn codec_type(codec: &str) -> R<symphonia::core::codecs::CodecType> {
"mp4a" | "aac" => CODEC_TYPE_AAC,
"mp3" => CODEC_TYPE_MP3,
"flac" => CODEC_TYPE_FLAC,
- o => return Err(format!("{o}: audio decodes here as aac, mp3 or flac")),
+ "opus" => CODEC_TYPE_OPUS,
+ o => return Err(format!("{o}: audio decodes here as aac, mp3, flac or opus")),
})
}
@@ -37,7 +38,7 @@ impl AudioPacketDecoder {
} {
p.with_channel_layout(layout);
}
- let dec = symphonia::default::get_codecs().make(&p, &DecoderOptions::default()).map_err(|e| format!("symphonia: {e}"))?;
+ let dec = crate::opusdec::codecs().make(&p, &DecoderOptions::default()).map_err(|e| format!("symphonia: {e}"))?;
Ok(AudioPacketDecoder { dec, ts: 0 })
}