diff --git a/shims/symphonia-codec-aac/Cargo.toml b/shims/symphonia-codec-aac/Cargo.toml new file mode 100644 index 00000000..c9a815c1 --- /dev/null +++ b/shims/symphonia-codec-aac/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "symphonia-codec-aac" +description = "Compatibility shim: the symphonia-codec-aac 0.6 surface edith consumes, served by ec-aac." +version = "0.6.0" +edition = "2024" +license = "MIT OR Apache-2.0" +authors = ["Ahmet Kaan Gümüş"] +publish = false + +[dependencies] +ec-aac = { path = "../../crates/ec-aac", version = "0.1.0" } +symphonia-core = { path = "../symphonia-core", version = "0.6.0" } diff --git a/shims/symphonia-codec-aac/src/lib.rs b/shims/symphonia-codec-aac/src/lib.rs new file mode 100644 index 00000000..ae6c58e6 --- /dev/null +++ b/shims/symphonia-codec-aac/src/lib.rs @@ -0,0 +1,81 @@ +//! Compatibility shim: the `symphonia-codec-aac` 0.6 surface edith consumes, +//! served by [`ec_aac`]. +//! +//! One difference from the incumbent, and it is the reason this exists: +//! **multichannel decodes**. The incumbent refuses anything wider than stereo +//! outright (`aac/mod.rs:93`, "aac: aac too complex"), which is exactly the 5.1 +//! and 7.1 tracks of a film — edith routes those to a second AAC crate to get +//! around it. [`ec_aac`] decodes mono through 7.1 in film channel order, so +//! there is nothing to route around. +//! +//! Written from the signatures edith calls (`AacDecoder::try_new`, then the +//! `AudioDecoder` trait) and the crate's published documentation; no symphonia +//! source was read. + +#![forbid(unsafe_code)] + +use symphonia_core::codecs::audio::{ + AudioCodecParameters, AudioDecoder, AudioDecoderOptions, GenericAudioBufferRef, + well_known::CODEC_ID_AAC, +}; +use symphonia_core::packet::Packet; +use symphonia_core::{Error, Result}; + +/// An AAC-LC decoder for one track. +pub struct AacDecoder { + inner: ec_aac::AacDecoder, + params: AudioCodecParameters, + out: Vec, + channels: usize, +} + +impl AacDecoder { + /// A decoder for the track `params` describes. + /// + /// The `extra_data` is the `AudioSpecificConfig`; a track with none (raw + /// ADTS, which states its configuration in every frame) is accepted and + /// configures itself from the first frame. + pub fn try_new( + params: &AudioCodecParameters, + _options: &AudioDecoderOptions, + ) -> Result { + if params.codec != CODEC_ID_AAC { + return Err(Error::Unsupported(format!( + "codec id {} is not AAC", + params.codec.0 + ))); + } + let inner = match params.extra_data.as_deref() { + Some(asc) => ec_aac::AacDecoder::with_config_bytes(asc)?, + None => ec_aac::AacDecoder::new(), + }; + let channels = params.channels.map_or(2, |c| c.count()).max(1) as usize; + Ok(AacDecoder { + inner, + params: params.clone(), + out: Vec::new(), + channels, + }) + } +} + +impl AudioDecoder for AacDecoder { + fn decode(&mut self, packet: &Packet) -> Result> { + let audio = self.inner.decode(&packet.data, Some(packet.pts.value()))?; + self.channels = usize::from(audio.channels).max(1); + self.out.clear(); + self.out.extend_from_slice(&audio.samples); + Ok(GenericAudioBufferRef::new(&self.out, self.channels)) + } + + fn codec_params(&self) -> &AudioCodecParameters { + &self.params + } + + fn reset(&mut self) { + self.inner = match self.params.extra_data.as_deref() { + Some(asc) => ec_aac::AacDecoder::with_config_bytes(asc).unwrap_or_default(), + None => ec_aac::AacDecoder::new(), + }; + } +} diff --git a/shims/symphonia-core/Cargo.toml b/shims/symphonia-core/Cargo.toml new file mode 100644 index 00000000..31a340e3 --- /dev/null +++ b/shims/symphonia-core/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "symphonia-core" +description = "Compatibility shim: the symphonia-core 0.6 surface edith consumes, over ec-core." +version = "0.6.0" +edition = "2024" +license = "MIT OR Apache-2.0" +authors = ["Ahmet Kaan Gümüş"] +publish = false + +[dependencies] +ec-core = { path = "../../crates/ec-core", version = "0.1.0" } diff --git a/shims/symphonia-core/src/codecs.rs b/shims/symphonia-core/src/codecs.rs new file mode 100644 index 00000000..e80dac42 --- /dev/null +++ b/shims/symphonia-core/src/codecs.rs @@ -0,0 +1,373 @@ +//! Codec identities, stream parameters and the decoder trait. + +use crate::Result; +use crate::packet::Packet; + +/// Per-media-type parameters, as a track carries them. +#[derive(Debug, Clone, PartialEq)] +pub enum CodecParameters { + /// An audio track. + Audio(audio::AudioCodecParameters), + /// A video track. Nothing in this family decodes picture through the + /// symphonia surface, so it carries only what a listing needs. + Video(VideoCodecParameters), + /// A subtitle track. + Subtitle(SubtitleCodecParameters), +} + +/// What a video track states about itself. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct VideoCodecParameters { + /// Codec identity, in this shim's own numbering. + pub codec: u32, + /// Coded width. + pub width: Option, + /// Coded height. + pub height: Option, +} + +/// What a subtitle track states about itself. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct SubtitleCodecParameters { + /// Codec identity, in this shim's own numbering. + pub codec: u32, + /// Setup bytes (the ASS header, for instance). + pub extra_data: Option>, +} + +/// A codec's name, as a registry reports it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CodecInfo { + /// Short lowercase name, e.g. `"aac"`. + pub short_name: &'static str, + /// Human-readable name. + pub long_name: &'static str, +} + +/// One entry of a codec registry. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CodecDescriptor { + /// The identity this entry serves. + pub id: audio::AudioCodecId, + /// Its names. + pub info: CodecInfo, +} + +/// A registry's answer for one audio codec. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct AudioDecoderRegistration { + /// The codec this registration decodes. + pub codec: CodecDescriptor, +} + +/// Audio codecs, parameters and decoders. +pub mod audio { + use super::*; + + /// A codec identity. The numbering is this shim's own; only equality + /// against the [`well_known`] constants is meaningful. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] + pub struct AudioCodecId(pub u32); + + /// The identities edith names. + pub mod well_known { + use super::AudioCodecId; + + /// MPEG-4 AAC. + pub const CODEC_ID_AAC: AudioCodecId = AudioCodecId(0x1000); + /// Xiph Opus. + pub const CODEC_ID_OPUS: AudioCodecId = AudioCodecId(0x1001); + /// Xiph Vorbis. + pub const CODEC_ID_VORBIS: AudioCodecId = AudioCodecId(0x1002); + /// Xiph FLAC. + pub const CODEC_ID_FLAC: AudioCodecId = AudioCodecId(0x1003); + /// MPEG-1/2 Layer III. + pub const CODEC_ID_MP3: AudioCodecId = AudioCodecId(0x1004); + /// Apple Lossless. + pub const CODEC_ID_ALAC: AudioCodecId = AudioCodecId(0x1005); + /// Dolby AC-3. + pub const CODEC_ID_AC3: AudioCodecId = AudioCodecId(0x1006); + /// Dolby Digital Plus. + pub const CODEC_ID_EAC3: AudioCodecId = AudioCodecId(0x1007); + /// Dolby TrueHD. No decoder is registered for it, which is how a + /// caller learns the track cannot be played. + pub const CODEC_ID_TRUEHD: AudioCodecId = AudioCodecId(0x1008); + /// DTS and its extensions. No decoder is registered for it either. + pub const CODEC_ID_DTS: AudioCodecId = AudioCodecId(0x1009); + /// Unsigned 8-bit PCM. + pub const CODEC_ID_PCM_U8: AudioCodecId = AudioCodecId(0x1010); + /// Signed 16-bit little-endian PCM. + pub const CODEC_ID_PCM_S16LE: AudioCodecId = AudioCodecId(0x1011); + /// Signed 16-bit big-endian PCM. + pub const CODEC_ID_PCM_S16BE: AudioCodecId = AudioCodecId(0x1012); + /// Signed 24-bit little-endian PCM. + pub const CODEC_ID_PCM_S24LE: AudioCodecId = AudioCodecId(0x1013); + /// Signed 32-bit little-endian PCM. + pub const CODEC_ID_PCM_S32LE: AudioCodecId = AudioCodecId(0x1014); + /// 32-bit float little-endian PCM. + pub const CODEC_ID_PCM_F32LE: AudioCodecId = AudioCodecId(0x1015); + /// Anything with no identity of its own here. + pub const CODEC_ID_NULL: AudioCodecId = AudioCodecId(0); + } + + /// A channel layout, as far as anything here asks: how many there are. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] + pub struct Channels(pub u32); + + impl Channels { + /// Channels in the layout. + pub fn count(&self) -> u32 { + self.0 + } + } + + /// Everything an audio decoder needs before its first packet. + #[derive(Debug, Clone, Default, PartialEq)] + pub struct AudioCodecParameters { + /// Which codec. + pub codec: AudioCodecId, + /// Sample rate in Hz. + pub sample_rate: Option, + /// Channel layout. + pub channels: Option, + /// Coded bit depth, when the container states one. + pub bits_per_sample: Option, + /// Codec setup bytes: the AudioSpecificConfig, `OpusHead`, STREAMINFO. + pub extra_data: Option>, + } + + impl AudioCodecParameters { + /// Empty parameters, filled in by the `with_*` builders. + pub fn new() -> AudioCodecParameters { + AudioCodecParameters::default() + } + + /// Name the codec. + pub fn for_codec(&mut self, codec: AudioCodecId) -> &mut AudioCodecParameters { + self.codec = codec; + self + } + + /// State the sample rate. + pub fn with_sample_rate(&mut self, rate: u32) -> &mut AudioCodecParameters { + self.sample_rate = Some(rate); + self + } + + /// State the channel layout. + pub fn with_channels(&mut self, channels: Channels) -> &mut AudioCodecParameters { + self.channels = Some(channels); + self + } + + /// State the bit depth. + pub fn with_bits_per_sample(&mut self, bits: u32) -> &mut AudioCodecParameters { + self.bits_per_sample = Some(bits); + self + } + + /// State the codec setup bytes. + pub fn with_extra_data(&mut self, data: Box<[u8]>) -> &mut AudioCodecParameters { + self.extra_data = Some(data); + self + } + } + + /// Options a decoder is built with. Nothing here has any, which is what + /// `Default` means for it. + #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] + pub struct AudioDecoderOptions { + /// Verify the decoded audio against a checksum where the format has + /// one. Not implemented by any decoder in this family. + pub verify: bool, + } + + /// A decoded block, borrowed from the decoder until its next call. + #[derive(Debug, Clone, Copy)] + pub struct GenericAudioBufferRef<'a> { + samples: &'a [f32], + channels: usize, + } + + impl<'a> GenericAudioBufferRef<'a> { + /// Wrap interleaved samples. + pub fn new(samples: &'a [f32], channels: usize) -> GenericAudioBufferRef<'a> { + GenericAudioBufferRef { samples, channels } + } + + /// Channels in the block. + pub fn spec_channels(&self) -> usize { + self.channels + } + + /// Sample frames in the block. + pub fn frames(&self) -> usize { + match self.channels { + 0 => 0, + n => self.samples.len() / n, + } + } + + /// Copy the block into `out`, interleaved, replacing what was there. + pub fn copy_to_vec_interleaved(&self, out: &mut Vec) { + out.clear(); + out.extend(self.samples.iter().map(|&s| S::from_sample(s))); + } + } + + /// A sample type [`GenericAudioBufferRef::copy_to_vec_interleaved`] can + /// convert to. + pub trait FromSample { + /// Convert one normalised `f32` sample. + fn from_sample(s: f32) -> Self; + } + + impl FromSample for f32 { + fn from_sample(s: f32) -> f32 { + s + } + } + + impl FromSample for i16 { + fn from_sample(s: f32) -> i16 { + (s.clamp(-1.0, 1.0) * 32767.0) as i16 + } + } + + impl FromSample for i32 { + fn from_sample(s: f32) -> i32 { + (f64::from(s.clamp(-1.0, 1.0)) * 2147483647.0) as i32 + } + } + + /// A decoder: packets in, one block out per packet. + pub trait AudioDecoder: Send { + /// Decode one packet. + fn decode(&mut self, packet: &Packet) -> Result>; + + /// The parameters this decoder was built with. + fn codec_params(&self) -> &AudioCodecParameters; + + /// Drop state left over from before a seek. + fn reset(&mut self); + } +} + +impl CodecParameters { + /// The audio half, when this is an audio track. + pub fn audio(&self) -> Option<&audio::AudioCodecParameters> { + match self { + CodecParameters::Audio(p) => Some(p), + _ => None, + } + } +} + +/// The identity a family [`ec_core::CodecId`] answers to here. +pub fn audio_codec_id(codec: ec_core::CodecId) -> audio::AudioCodecId { + use audio::well_known::*; + use ec_core::CodecId; + match codec { + CodecId::Aac => CODEC_ID_AAC, + CodecId::Opus => CODEC_ID_OPUS, + CodecId::Vorbis => CODEC_ID_VORBIS, + CodecId::Flac => CODEC_ID_FLAC, + CodecId::Mp3 => CODEC_ID_MP3, + CodecId::Alac => CODEC_ID_ALAC, + CodecId::Ac3 => CODEC_ID_AC3, + CodecId::EAc3 => CODEC_ID_EAC3, + CodecId::TrueHd => CODEC_ID_TRUEHD, + CodecId::Dts => CODEC_ID_DTS, + // Each PCM width keeps its own identity: mapping them all to one and + // back would decode a 24-bit WAVE as 16-bit. + CodecId::PcmU8 => CODEC_ID_PCM_U8, + CodecId::PcmS16Le => CODEC_ID_PCM_S16LE, + CodecId::PcmS16Be => CODEC_ID_PCM_S16BE, + CodecId::PcmS24Le => CODEC_ID_PCM_S24LE, + CodecId::PcmS32Le => CODEC_ID_PCM_S32LE, + CodecId::PcmF32Le => CODEC_ID_PCM_F32LE, + _ => CODEC_ID_NULL, + } +} + +/// The family codec an identity names, or [`None`] for one nothing here +/// decodes. +pub fn ec_codec_id(id: audio::AudioCodecId) -> Option { + use audio::well_known::*; + use ec_core::CodecId; + Some(match id { + CODEC_ID_AAC => CodecId::Aac, + CODEC_ID_OPUS => CodecId::Opus, + CODEC_ID_VORBIS => CodecId::Vorbis, + CODEC_ID_FLAC => CodecId::Flac, + CODEC_ID_MP3 => CodecId::Mp3, + CODEC_ID_ALAC => CodecId::Alac, + CODEC_ID_AC3 => CodecId::Ac3, + CODEC_ID_EAC3 => CodecId::EAc3, + CODEC_ID_TRUEHD => CodecId::TrueHd, + CODEC_ID_DTS => CodecId::Dts, + CODEC_ID_PCM_U8 => CodecId::PcmU8, + CODEC_ID_PCM_S16LE => CodecId::PcmS16Le, + CODEC_ID_PCM_S16BE => CodecId::PcmS16Be, + CODEC_ID_PCM_S24LE => CodecId::PcmS24Le, + CODEC_ID_PCM_S32LE => CodecId::PcmS32Le, + CODEC_ID_PCM_F32LE => CodecId::PcmF32Le, + _ => return None, + }) +} + +/// Family parameters for what a track states, for handing to a family decoder. +pub fn ec_parameters( + params: &audio::AudioCodecParameters, +) -> crate::Result { + let codec = ec_codec_id(params.codec).ok_or_else(|| { + crate::Error::Unsupported(format!("no decoder for codec id {}", params.codec.0)) + })?; + let mut out = ec_core::CodecParameters::new(codec); + out.extradata = params + .extra_data + .as_deref() + .map(ec_core::packet::Buf::copy_from_slice); + out.media = ec_core::registry::MediaParameters::Audio(ec_core::registry::AudioParameters { + sample_rate: params.sample_rate.unwrap_or(48_000), + layout: ec_core::ChannelLayout::from_count( + params.channels.map_or(2, |c| c.count()).max(1) as usize + ), + format: None, + bits_per_sample: params.bits_per_sample, + }); + Ok(out) +} + +/// What a track states, from the family's own description of it. +pub fn from_ec_parameters(params: &ec_core::CodecParameters) -> CodecParameters { + match params.audio() { + Some(audio) => { + let mut out = audio::AudioCodecParameters::new(); + out.for_codec(audio_codec_id(params.codec)) + .with_sample_rate(audio.sample_rate) + .with_channels(audio::Channels(audio.layout.channel_count() as u32)); + if let Some(bits) = audio.bits_per_sample { + out.with_bits_per_sample(bits); + } + if let Some(extra) = ¶ms.extradata { + out.with_extra_data(extra.as_ref().to_vec().into_boxed_slice()); + } + CodecParameters::Audio(out) + } + None => match params.video() { + Some(video) => CodecParameters::Video(VideoCodecParameters { + codec: audio_codec_id(params.codec).0, + width: Some(video.width as u16), + height: Some(video.height as u16), + }), + None => CodecParameters::Subtitle(SubtitleCodecParameters { + codec: audio_codec_id(params.codec).0, + extra_data: params + .extradata + .as_ref() + .map(|b| b.as_ref().to_vec().into_boxed_slice()), + }), + }, + } +} diff --git a/shims/symphonia-core/src/formats.rs b/shims/symphonia-core/src/formats.rs new file mode 100644 index 00000000..b2d46e72 --- /dev/null +++ b/shims/symphonia-core/src/formats.rs @@ -0,0 +1,136 @@ +//! Tracks, the reader trait, and seeking. + +use crate::Result; +use crate::codecs::CodecParameters; +use crate::packet::Packet; +use crate::units::{Time, TimeBase, Timestamp}; + +/// What kind of stream a track carries. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum TrackType { + /// Sound. + Audio, + /// Pictures. + Video, + /// Timed text or bitmaps. + Subtitle, +} + +/// One track of a container. +#[derive(Debug, Clone, PartialEq)] +pub struct Track { + /// The container's own id for the track — a Matroska `TrackNumber`, which + /// is what names one language of a dual-audio file. + pub id: u32, + /// Which kind of stream it is. + pub track_type: TrackType, + /// Base of this track's timestamps. + pub time_base: Option, + /// Sample frames the track holds, when the container states one. + pub num_frames: Option, + /// First timestamp. + pub start_ts: u64, + /// Codec and setup data. + pub codec_params: Option, + /// ISO 639 language tag, when the container carries one. + pub language: Option, +} + +/// Options a reader is built with; nothing here has any. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct FormatOptions { + /// Build a seek index even when the container carries none. + pub enable_gapless: bool, +} + +/// How exactly a seek must land. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum SeekMode { + /// The nearest random access point at or before the target, from which a + /// decoder reaches the target exactly by decoding forward. + #[default] + Accurate, + /// Whatever is cheapest. + Coarse, +} + +/// Where to seek to. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum SeekTo { + /// An instant, on `track_id` or on the default track. + Time { + /// The instant. + time: Time, + /// Which track's timeline it is on. + track_id: Option, + }, + /// A timestamp in a track's own base. + TimeStamp { + /// The timestamp. + ts: Timestamp, + /// Which track it belongs to. + track_id: u32, + }, +} + +/// Where a seek actually landed. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SeekedTo { + /// Track the landing is on. + pub track_id: u32, + /// What was asked for. + pub required_ts: Timestamp, + /// What was reached — at or before `required_ts` in [`SeekMode::Accurate`]. + pub actual_ts: Timestamp, +} + +/// A container reader. +pub trait FormatReader: Send { + /// Every track the container declares. + fn tracks(&self) -> &[Track]; + + /// The first track of `kind`. + fn default_track(&self, kind: TrackType) -> Option<&Track>; + + /// Seek, answering where it landed. + fn seek(&mut self, mode: SeekMode, to: SeekTo) -> Result; + + /// The next packet, or `Ok(None)` at the end of the stream. + fn next_packet(&mut self) -> Result>; +} + +/// Format hints from outside the bytes. +pub mod probe { + /// What the caller knows that the content does not say: a file extension, + /// a MIME type. Advisory — every reader in this family sniffs the content + /// first and is free to disagree. + #[derive(Debug, Clone, Default, PartialEq, Eq)] + pub struct Hint { + extension: Option, + mime_type: Option, + } + + impl Hint { + /// A hint that says nothing. + pub fn new() -> Hint { + Hint::default() + } + + /// Name the file extension, without its dot. + pub fn with_extension(&mut self, extension: &str) -> &mut Hint { + self.extension = Some(extension.to_string()); + self + } + + /// Name the MIME type. + pub fn mime_type(&mut self, mime: &str) -> &mut Hint { + self.mime_type = Some(mime.to_string()); + self + } + + /// The extension, if one was given. + pub fn extension(&self) -> Option<&str> { + self.extension.as_deref() + } + } +} diff --git a/shims/symphonia-core/src/io.rs b/shims/symphonia-core/src/io.rs new file mode 100644 index 00000000..129081fc --- /dev/null +++ b/shims/symphonia-core/src/io.rs @@ -0,0 +1,50 @@ +//! The source a reader reads from. + +use std::io::{Read, Seek}; + +/// Anything a reader can be built over: seekable, readable, and movable to the +/// thread that will do the reading. +pub trait MediaSource: Read + Seek + Send {} + +impl MediaSource for T {} + +/// Options a stream is built with; nothing here has any. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct MediaSourceStreamOptions { + /// Buffer size a caller would like. This shim buffers in the demuxers + /// themselves, so it is advisory. + pub buffer_len: usize, +} + +/// A source with a buffer in front of it. +pub struct MediaSourceStream { + inner: Box, +} + +impl MediaSourceStream { + /// Wrap a source. + pub fn new( + source: Box, + _options: MediaSourceStreamOptions, + ) -> MediaSourceStream { + MediaSourceStream { inner: source } + } + + /// Take the source back out, which is how a reader in this family is + /// handed the file it will read. + pub fn into_inner(self) -> Box { + self.inner + } +} + +impl Read for MediaSourceStream { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + self.inner.read(buf) + } +} + +impl Seek for MediaSourceStream { + fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result { + self.inner.seek(pos) + } +} diff --git a/shims/symphonia-core/src/lib.rs b/shims/symphonia-core/src/lib.rs new file mode 100644 index 00000000..825daab8 --- /dev/null +++ b/shims/symphonia-core/src/lib.rs @@ -0,0 +1,77 @@ +//! Compatibility shim: the `symphonia-core` 0.6 surface edith consumes, over +//! [`ec_core`] and (through the `symphonia` shim) [`ec_probe`]. +//! +//! This is the vocabulary half — parameters, packets, units, the reader and +//! decoder traits. The registries that build them live in the `symphonia` +//! shim, and the AAC decoder seat in `symphonia-codec-aac`, exactly as the +//! incumbent splits them. +//! +//! Written from the signatures edith calls (`crates/engine/src/audio.rs` +//! lines 36-53 and their call sites) and the crate's published documentation. +//! No symphonia source was read: the incumbent is MPL-2.0 and this family is +//! MIT OR Apache-2.0. +//! +//! **Not the whole crate.** What edith does not call is not here: metadata +//! revisions, the sample-buffer zoo, `Signal`/`AudioBuffer` generics, the +//! `CodecRegistry` builder API. Each is a small addition when something needs +//! it; none is a silent omission. + +#![forbid(unsafe_code)] + +pub mod codecs; +pub mod formats; +pub mod io; +pub mod meta; +pub mod packet; +pub mod units; + +use std::fmt; + +/// The incumbent's error type, in the shape callers match on. +#[derive(Debug)] +pub enum Error { + /// Underlying I/O failure. + IoError(std::io::Error), + /// The bitstream is malformed. + DecodeError(String), + /// A capability this build does not have, naming what and why. + Unsupported(String), + /// A seek that could not be served. + SeekError(String), + /// End of stream. + ResetRequired, +} + +/// `Result` with this crate's [`Error`]. +pub type Result = std::result::Result; + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::IoError(e) => write!(f, "io error: {e}"), + Error::DecodeError(e) => write!(f, "decode error: {e}"), + Error::Unsupported(e) => write!(f, "unsupported: {e}"), + Error::SeekError(e) => write!(f, "seek error: {e}"), + Error::ResetRequired => write!(f, "decoder reset required"), + } + } +} + +impl std::error::Error for Error {} + +impl From for Error { + fn from(e: std::io::Error) -> Error { + Error::IoError(e) + } +} + +impl From for Error { + fn from(e: ec_core::Error) -> Error { + match e { + ec_core::Error::Io(io) => Error::IoError(io), + ec_core::Error::Eof | ec_core::Error::NeedMore => Error::ResetRequired, + ec_core::Error::Unsupported { .. } => Error::Unsupported(e.to_string()), + ec_core::Error::Corrupt { .. } => Error::DecodeError(e.to_string()), + } + } +} diff --git a/shims/symphonia-core/src/meta.rs b/shims/symphonia-core/src/meta.rs new file mode 100644 index 00000000..d1b4be09 --- /dev/null +++ b/shims/symphonia-core/src/meta.rs @@ -0,0 +1,12 @@ +//! Metadata options. +//! +//! edith passes `MetadataOptions::default()` and never reads a revision back, +//! so the tags a file carries are read by `ec_probe::Tags` and surfaced there +//! rather than through this type. + +/// Options metadata is read with. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct MetadataOptions { + /// Read cover art as well as text. Nothing here does. + pub read_visuals: bool, +} diff --git a/shims/symphonia-core/src/packet.rs b/shims/symphonia-core/src/packet.rs new file mode 100644 index 00000000..99fb4142 --- /dev/null +++ b/shims/symphonia-core/src/packet.rs @@ -0,0 +1,38 @@ +//! One packet of coded bytes. + +use crate::units::{Duration, Timestamp}; + +/// A packet as a reader hands it out. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Packet { + /// Track this packet belongs to. + pub track_id: u32, + /// Presentation timestamp, in the track's own time base. + pub pts: Timestamp, + /// How long it plays for. + pub dur: Duration, + /// The coded bytes. + pub data: Box<[u8]>, +} + +impl Packet { + /// A packet over `data`. + pub fn new(track_id: u32, pts: Timestamp, dur: Duration, data: &[u8]) -> Packet { + Packet { + track_id, + pts, + dur, + data: data.to_vec().into_boxed_slice(), + } + } + + /// The presentation timestamp. + pub fn pts(&self) -> Timestamp { + self.pts + } + + /// The coded bytes. + pub fn buf(&self) -> &[u8] { + &self.data + } +} diff --git a/shims/symphonia-core/src/units.rs b/shims/symphonia-core/src/units.rs new file mode 100644 index 00000000..8e75b14e --- /dev/null +++ b/shims/symphonia-core/src/units.rs @@ -0,0 +1,134 @@ +//! Time, timestamps and the rational base between them. + +/// A media timestamp, in [`TimeBase`] ticks. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)] +pub struct Timestamp(pub i64); + +impl Timestamp { + /// A timestamp of `ticks`. + pub fn new(ticks: i64) -> Timestamp { + Timestamp(ticks) + } + + /// The tick count. + pub fn value(&self) -> i64 { + self.0 + } +} + +/// A duration in [`TimeBase`] ticks. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)] +pub struct Duration(pub u64); + +impl Duration { + /// A duration of `ticks`. + pub fn new(ticks: u64) -> Duration { + Duration(ticks) + } + + /// The tick count. + pub fn value(&self) -> u64 { + self.0 + } +} + +/// Wall-clock time, split so that no fraction is lost to a float. +#[derive(Debug, Clone, Copy, PartialEq, Default)] +pub struct Time { + /// Whole seconds. + pub seconds: u64, + /// Fraction of a second, 0.0..1.0. + pub frac: f64, +} + +impl Time { + /// A time from whole seconds and a fraction. + pub fn new(seconds: u64, frac: f64) -> Time { + Time { seconds, frac } + } + + /// A time from seconds, or [`None`] for a negative or non-finite input — + /// which is what makes a caller check before seeking to it. + pub fn try_from_secs_f64(secs: f64) -> Option