The AC-3/E-AC-3 decode seat is the native ec-ac3
Browse files at this commit9fab7c99c10a52c2649c828ff67a932c864ee8fcParent: 6421f59- feat
- the AC-3/E-AC-3 decode seat is the native ec-ac3
7 changed files +325 -95
- Cargo.lock +9 -10
- crates/engine/Cargo.toml +14 -4
- crates/engine/src/audio.rs +69 -78
- crates/engine/src/caps.rs +2 -2
- crates/engine/src/demux.rs +1 -1
- crates/engine/tests/audio_ac3_film.rs +225 -0
- real_library.toml.example +5 -0
Cargo.lockmodified+9 -10
| @@ -1596,6 +1596,14 @@ dependencies = [ | |||
| 1596 | "ec-dsp", | 1596 | "ec-dsp", |
| 1597 | ] | 1597 | ] |
| 1598 | 1598 | ||
| 1599 | +[[package]] | ||
| 1600 | +name = "ec-ac3" | ||
| 1601 | +version = "0.1.0" | ||
| 1602 | +dependencies = [ | ||
| 1603 | + "ec-core", | ||
| 1604 | + "ec-dsp", | ||
| 1605 | +] | ||
| 1606 | + | ||
| 1599 | [[package]] | 1607 | [[package]] |
| 1600 | name = "ec-av1" | 1608 | name = "ec-av1" |
| 1601 | version = "0.1.0" | 1609 | version = "0.1.0" |
| @@ -1705,6 +1713,7 @@ name = "engine" | |||
| 1705 | version = "0.1.0" | 1713 | version = "0.1.0" |
| 1706 | dependencies = [ | 1714 | dependencies = [ |
| 1707 | "ec-aac", | 1715 | "ec-aac", |
| 1716 | + "ec-ac3", | ||
| 1708 | "ec-av1", | 1717 | "ec-av1", |
| 1709 | "ec-core", | 1718 | "ec-core", |
| 1710 | "ec-h264", | 1719 | "ec-h264", |
| @@ -1716,7 +1725,6 @@ dependencies = [ | |||
| 1716 | "libloading", | 1725 | "libloading", |
| 1717 | "miniz_oxide", | 1726 | "miniz_oxide", |
| 1718 | "mp4", | 1727 | "mp4", |
| 1719 | - "oxideav-ac3", | ||
| 1720 | "oxideav-ass", | 1728 | "oxideav-ass", |
| 1721 | "oxideav-core", | 1729 | "oxideav-core", |
| 1722 | "oxideav-h265", | 1730 | "oxideav-h265", |
| @@ -4015,15 +4023,6 @@ dependencies = [ | |||
| 4015 | "pin-project-lite", | 4023 | "pin-project-lite", |
| 4016 | ] | 4024 | ] |
| 4017 | 4025 | ||
| 4018 | -[[package]] | ||
| 4019 | -name = "oxideav-ac3" | ||
| 4020 | -version = "0.0.10" | ||
| 4021 | -source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4022 | -checksum = "4c60744c9688507efb6849b1bff197fb17e742b56f8a7f914129464bc86197ad" | ||
| 4023 | -dependencies = [ | ||
| 4024 | - "oxideav-core", | ||
| 4025 | -] | ||
| 4026 | - | ||
| 4027 | [[package]] | 4026 | [[package]] |
| 4028 | name = "oxideav-ass" | 4027 | name = "oxideav-ass" |
| 4029 | version = "0.0.9" | 4028 | version = "0.0.9" |
crates/engine/Cargo.tomlmodified+14 -4
| @@ -126,9 +126,20 @@ rusty_vorbis = "0.1.1" | |||
| 126 | # `tests/opus_export.rs` exports and re-reads the files through this project's | 126 | # `tests/opus_export.rs` exports and re-reads the files through this project's |
| 127 | # own decoder door. | 127 | # own decoder door. |
| 128 | ec-opus = { path = "../../../edith_codecs/crates/ec-opus" } | 128 | ec-opus = { path = "../../../edith_codecs/crates/ec-opus" } |
| 129 | +# The AC-3 / E-AC-3 decode seat, the family's own decoder taking the seat the | ||
| 130 | +# registry crate `oxideav-ac3` held. One decoder reads both syntaxes, dispatching | ||
| 131 | +# per packet on `bsid`, and hands back interleaved f32 in the coded layout or -- | ||
| 132 | +# what the seat asks for on anything wider than mono -- its own A/52 §7.8.2 | ||
| 133 | +# stereo fold, per-position coefficients from the frame's own `acmod` and mix | ||
| 134 | +# levels: the same shape and the same loudness the old seat served. One named | ||
| 135 | +# coverage edge, witnessed, not silent: Annex E dependent substreams and | ||
| 136 | +# enhanced coupling (7.1 DD+ assembled as 5.1-plus-dependents) are refused by | ||
| 137 | +# name where `oxideav-ac3` walked them; every single-substream AC-3 and E-AC-3 | ||
| 138 | +# track decodes. | ||
| 139 | +ec-ac3 = { path = "../../../edith_codecs/crates/ec-ac3" } | ||
| 129 | # The Ogg container, and the only new *name* here that is not a new crate tree: | 140 | # The Ogg container, and the only new *name* here that is not a new crate tree: |
| 130 | -# its one dependency is `oxideav-core`, which the AC-3 decoder above already | 141 | +# its one dependency is `oxideav-core`, a direct line below. MIT. Vorbis-aware |
| 131 | -# pulls in. MIT. Vorbis-aware where it counts -- `xiph_lace` builds the | 142 | +# where it counts -- `xiph_lace` builds the |
| 132 | # three-header blob and the muxer pages those ahead of the audio, which is the | 143 | # three-header blob and the muxer pages those ahead of the audio, which is the |
| 133 | # encapsulation order a Vorbis decoder needs and the part that is easy to get | 144 | # encapsulation order a Vorbis decoder needs and the part that is easy to get |
| 134 | # wrong by hand. | 145 | # wrong by hand. |
| @@ -142,7 +153,7 @@ symphonia-codec-aac = "0.6" | |||
| 142 | # `mkv`, which is not an `is_audio` container at all -- it is how the *sound* of | 153 | # `mkv`, which is not an `is_audio` container at all -- it is how the *sound* of |
| 143 | # a Matroska video file is read, the picture having its own demuxer here. | 154 | # a Matroska video file is read, the picture having its own demuxer here. |
| 144 | # There is no opus/ac3/dts feature at any symphonia version: AC-3 comes from | 155 | # There is no opus/ac3/dts feature at any symphonia version: AC-3 comes from |
| 145 | -# `oxideav-ac3` and Opus from `ec-opus` above, both plugged into this crate's | 156 | +# `ec-ac3` and Opus from `ec-opus` above, both plugged into this crate's |
| 146 | # own readers, and DTS is the one that really is refused. | 157 | # own readers, and DTS is the one that really is refused. |
| 147 | symphonia = { version = "0.6", default-features = false, features = [ | 158 | symphonia = { version = "0.6", default-features = false, features = [ |
| 148 | "aac", | 159 | "aac", |
| @@ -158,7 +169,6 @@ symphonia = { version = "0.6", default-features = false, features = [ | |||
| 158 | "vorbis", | 169 | "vorbis", |
| 159 | "wav", | 170 | "wav", |
| 160 | ] } | 171 | ] } |
| 161 | -oxideav-ac3 = "=0.0.10" | ||
| 162 | oxideav-core = "0.1.34" | 172 | oxideav-core = "0.1.34" |
| 163 | # The subtitle parsers: SRT and WebVTT here, ASS/SSA in the sibling crate -- | 173 | # The subtitle parsers: SRT and WebVTT here, ASS/SSA in the sibling crate -- |
| 164 | # `oxideav-subtitle` hosts the shared IR and hands ASS to `oxideav-ass`, which | 174 | # `oxideav-subtitle` hosts the shared IR and hands ASS to `oxideav-ass`, which |
crates/engine/src/audio.rsmodified+69 -78
| @@ -9,7 +9,7 @@ | |||
| 9 | //! symphonia's own format probe, as does the AAC track of a **Matroska** file: | 9 | //! symphonia's own format probe, as does the AAC track of a **Matroska** file: |
| 10 | //! same reader, `mkv` instead of `isomp4`, and a 5.1 film soundtrack folded to | 10 | //! same reader, `mkv` instead of `isomp4`, and a 5.1 film soundtrack folded to |
| 11 | //! stereo on the way out ([`SymDecoder`]). An mp4's **AC-3** track is the third: the same | 11 | //! stereo on the way out ([`SymDecoder`]). An mp4's **AC-3** track is the third: the same |
| 12 | -//! sample tables, decoded by `oxideav-ac3` and downmixed to stereo by the | 12 | +//! sample tables, decoded by `ec-ac3` and downmixed to stereo by the |
| 13 | //! decoder itself, which is what lets a 5.1 BluRay remux play on a stereo | 13 | //! decoder itself, which is what lets a 5.1 BluRay remux play on a stereo |
| 14 | //! timeline. Everything downstream of [`Track`] sees the | 14 | //! timeline. Everything downstream of [`Track`] sees the |
| 15 | //! same samples either way; only the packet copy asks which reader it came from, | 15 | //! same samples either way; only the packet copy asks which reader it came from, |
| @@ -34,7 +34,6 @@ use std::sync::{Arc, Mutex}; | |||
| 34 | use std::thread; | 34 | use std::thread; |
| 35 | 35 | ||
| 36 | use mp4::{AudioObjectType, ChannelConfig, MediaType, Mp4Reader, Mp4Track, TrackType}; | 36 | use mp4::{AudioObjectType, ChannelConfig, MediaType, Mp4Reader, Mp4Track, TrackType}; |
| 37 | -use oxideav_core::{CodecId, CodecParameters, CodecRegistry, Decoder, Frame, Packet as Ac3Packet}; | ||
| 38 | use symphonia_codec_aac::AacDecoder; | 37 | use symphonia_codec_aac::AacDecoder; |
| 39 | use symphonia_core::codecs::audio::{ | 38 | use symphonia_core::codecs::audio::{ |
| 40 | AudioCodecParameters, AudioDecoder, AudioDecoderOptions, | 39 | AudioCodecParameters, AudioDecoder, AudioDecoderOptions, |
| @@ -66,7 +65,7 @@ const EMPTY_EDIT: u64 = u32::MAX as u64; | |||
| 66 | /// What the sound of a *Matroska* file is read with, named for a refusal: | 65 | /// What the sound of a *Matroska* file is read with, named for a refusal: |
| 67 | /// symphonia's registry as this project enables it (see the feature list in | 66 | /// symphonia's registry as this project enables it (see the feature list in |
| 68 | /// `Cargo.toml`) plus the two families no symphonia version carries and this | 67 | /// `Cargo.toml`) plus the two families no symphonia version carries and this |
| 69 | -/// project decodes anyway -- AC-3/E-AC-3 through `oxideav-ac3` ([`MkvAc3Track`]) | 68 | +/// project decodes anyway -- AC-3/E-AC-3 through `ec-ac3` ([`MkvAc3Track`]) |
| 70 | /// and Opus through `ec-opus` ([`SymDecoder::Opus`]). | 69 | /// and Opus through `ec-opus` ([`SymDecoder::Opus`]). |
| 71 | /// | 70 | /// |
| 72 | /// Written down per container because capability is not one set: an mp4 video's | 71 | /// Written down per container because capability is not one set: an mp4 video's |
| @@ -1489,12 +1488,12 @@ impl Track { | |||
| 1489 | fn channels(&self) -> u16 { | 1488 | fn channels(&self) -> u16 { |
| 1490 | match self { | 1489 | match self { |
| 1491 | Self::Aac(t) => t.channels(), | 1490 | Self::Aac(t) => t.channels(), |
| 1492 | - // Already downmixed by the AC-3 decoder itself; `channels` is what | 1491 | + // Downmixed to a pair by the AC-3 decoder itself (§7.8.2); a mono |
| 1493 | - // comes *out* of it, and the 2.1 passthrough it leaves at 3 (see | 1492 | + // track passes through as the one channel it is (see [`ac3_decoder`]), |
| 1494 | - // [`Ac3Track`]) is folded by [`decode_ac3`] like any other width. | 1493 | + // so what `channels` measures is already the timeline width. |
| 1495 | - Self::Ac3(t) => t.channels.min(2), | 1494 | + Self::Ac3(t) => t.channels, |
| 1496 | - // Downmixed by the very same decoder, out of a Matroska file. | 1495 | + // The same decoder, out of a Matroska file. |
| 1497 | - Self::Mkv(t) => t.channels.min(2), | 1496 | + Self::Mkv(t) => t.channels, |
| 1498 | Self::Sym(t) => t.channels, | 1497 | Self::Sym(t) => t.channels, |
| 1499 | } | 1498 | } |
| 1500 | } | 1499 | } |
| @@ -1549,10 +1548,10 @@ impl Track { | |||
| 1549 | aac_decoder(&t.params, t.source_channels())?; | 1548 | aac_decoder(&t.params, t.source_channels())?; |
| 1550 | } | 1549 | } |
| 1551 | Self::Ac3(t) => { | 1550 | Self::Ac3(t) => { |
| 1552 | - ac3_decoder("ac3", t.requested)?; | 1551 | + ac3_decoder(t.requested)?; |
| 1553 | } | 1552 | } |
| 1554 | Self::Mkv(t) => { | 1553 | Self::Mkv(t) => { |
| 1555 | - ac3_decoder(t.mkv.codec, t.requested)?; | 1554 | + ac3_decoder(t.requested)?; |
| 1556 | } | 1555 | } |
| 1557 | Self::Sym(t) => { | 1556 | Self::Sym(t) => { |
| 1558 | t.decoder()?; | 1557 | t.decoder()?; |
| @@ -2068,15 +2067,18 @@ fn widen(samples: &mut Vec<f32>, from: usize, to: usize) { | |||
| 2068 | } | 2067 | } |
| 2069 | 2068 | ||
| 2070 | /// One source's AC-3 track: the same mp4 sample tables the AAC track is read | 2069 | /// One source's AC-3 track: the same mp4 sample tables the AAC track is read |
| 2071 | -/// from, decoded through `oxideav-ac3` and **downmixed to stereo by the decoder | 2070 | +/// from, decoded through `ec-ac3` and **downmixed to stereo by the decoder |
| 2072 | -/// itself** (ATSC A/52 §7.8, `channels: Some(2)`), because one output device and | 2071 | +/// itself** (ATSC A/52 §7.8.2, [`ec_ac3::Downmix::Stereo`]), because one output |
| 2073 | -/// one timeline layout is all there is. A 5.1 BluRay track therefore arrives | 2072 | +/// device and one timeline layout is all there is. A 5.1 BluRay track therefore |
| 2074 | -/// here as an ordinary stereo source, and its rows in the picker say so. | 2073 | +/// arrives here as an ordinary stereo source, and its rows in the picker say so. |
| 2075 | /// | 2074 | /// |
| 2076 | /// `channels` is what the decoder actually emitted for the first frame rather | 2075 | /// `channels` is what the decoder actually emitted for the first frame rather |
| 2077 | -/// than an assumed 2: everything from mono to 5.1 downmixes to stereo, but a 2.1 | 2076 | +/// than an assumed 2: everything from stereo to 5.1 downmixes to stereo and a |
| 2078 | -/// stream is a passthrough the library leaves at 3, and that is refused by name | 2077 | +/// mono track passes through as the one channel it is (`acmod` carries the |
| 2079 | -/// in [`Track::channels`] instead of being mislabelled. | 2078 | +/// programme in the centre; duplicating it is the timeline's business, see |
| 2079 | +/// [`widen`]). The §7.8.2 fold is position-aware — every `acmod` from 1/0 to | ||
| 2080 | +/// 3/2 puts its centre and surrounds where the matrix says — so no width is | ||
| 2081 | +/// refused or mislabelled. | ||
| 2080 | struct Ac3Track { | 2082 | struct Ac3Track { |
| 2081 | reader: Mp4Reader<BufReader<File>>, | 2083 | reader: Mp4Reader<BufReader<File>>, |
| 2082 | track_id: u32, | 2084 | track_id: u32, |
| @@ -2088,8 +2090,9 @@ struct Ac3Track { | |||
| 2088 | total_samples: Option<u64>, | 2090 | total_samples: Option<u64>, |
| 2089 | stts: Vec<(u32, u32)>, | 2091 | stts: Vec<(u32, u32)>, |
| 2090 | /// What the decoder is asked to hand out, from this track's own layout: | 2092 | /// What the decoder is asked to hand out, from this track's own layout: |
| 2091 | - /// `Some(2)` for anything with more than one front channel, `None` — the | 2093 | + /// [`ec_ac3::Downmix::Stereo`] for anything with more than one front |
| 2092 | - /// library's passthrough — for a mono track. See [`ac3_decoder`]. | 2094 | + /// channel, [`ec_ac3::Downmix::Native`] — the coded channels untouched — |
| 2095 | + /// for a mono track. See [`ac3_decoder`]. | ||
| 2093 | requested: Option<u16>, | 2096 | requested: Option<u16>, |
| 2094 | } | 2097 | } |
| 2095 | 2098 | ||
| @@ -2124,14 +2127,14 @@ impl Ac3Track { | |||
| 2124 | let first = reader | 2127 | let first = reader |
| 2125 | .read_sample(track_id, 1)? | 2128 | .read_sample(track_id, 1)? |
| 2126 | .ok_or("the AC-3 track has no samples")?; | 2129 | .ok_or("the AC-3 track has no samples")?; |
| 2127 | - let sample_rate = oxideav_ac3::syncinfo::parse(&first.bytes) | 2130 | + let sample_rate = ec_ac3::syncinfo::parse(&first.bytes) |
| 2128 | .map_err(|e| format!("not a readable AC-3 syncframe: {e:?}"))? | 2131 | .map_err(|e| format!("not a readable AC-3 syncframe: {e:?}"))? |
| 2129 | .sample_rate; | 2132 | .sample_rate; |
| 2130 | - let nfchans = oxideav_ac3::bsi::parse(first.bytes.get(5..).unwrap_or_default()) | 2133 | + let nfchans = ec_ac3::bsi::parse(first.bytes.get(5..).unwrap_or_default()) |
| 2131 | .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))? | 2134 | .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))? |
| 2132 | .nfchans; | 2135 | .nfchans; |
| 2133 | let requested = (nfchans > 1).then_some(2); | 2136 | let requested = (nfchans > 1).then_some(2); |
| 2134 | - let mut decoder = ac3_decoder("ac3", requested)?; | 2137 | + let mut decoder = ac3_decoder(requested)?; |
| 2135 | let channels = decode_ac3(&mut decoder, &first.bytes)? | 2138 | let channels = decode_ac3(&mut decoder, &first.bytes)? |
| 2136 | .map(|(pcm, samples)| (pcm.len() as u64 / samples.max(1)) as u16) | 2139 | .map(|(pcm, samples)| (pcm.len() as u64 / samples.max(1)) as u16) |
| 2137 | .filter(|&c| c > 0) | 2140 | .filter(|&c| c > 0) |
| @@ -2179,10 +2182,10 @@ impl Ac3Track { | |||
| 2179 | } | 2182 | } |
| 2180 | 2183 | ||
| 2181 | /// One source's AC-3 or E-AC-3 track out of a **Matroska** file: the very same | 2184 | /// One source's AC-3 or E-AC-3 track out of a **Matroska** file: the very same |
| 2182 | -/// decoder and the very same §7.8 stereo downmix [`Ac3Track`] runs, fed out of | 2185 | +/// decoder and the very same §7.8.2 stereo downmix [`Ac3Track`] runs, fed out of |
| 2183 | /// the container's blocks instead of an mp4 sample table. A 5.1 E-AC-3 remux | 2186 | /// the container's blocks instead of an mp4 sample table. A 5.1 E-AC-3 remux |
| 2184 | /// therefore arrives on the timeline as an ordinary stereo source, exactly as | 2187 | /// therefore arrives on the timeline as an ordinary stereo source, exactly as |
| 2185 | -/// the mp4 path's does, and the mono passthrough quirk is the same one. | 2188 | +/// the mp4 path's does, and mono passes through exactly the same way. |
| 2186 | /// | 2189 | /// |
| 2187 | /// Matroska indexes no samples, so what an `stts` walk answers on the mp4 side | 2190 | /// Matroska indexes no samples, so what an `stts` walk answers on the mp4 side |
| 2188 | /// is answered here by the blocks' own timestamps ([`crate::demux::MkvAudio`]): | 2191 | /// is answered here by the blocks' own timestamps ([`crate::demux::MkvAudio`]): |
| @@ -2198,7 +2201,7 @@ struct MkvAc3Track { | |||
| 2198 | total_samples: Option<u64>, | 2201 | total_samples: Option<u64>, |
| 2199 | /// What the decoder is asked to hand out, from this track's own layout: | 2202 | /// What the decoder is asked to hand out, from this track's own layout: |
| 2200 | /// `Some(2)` for anything with more than one front channel, `None` for a | 2203 | /// `Some(2)` for anything with more than one front channel, `None` for a |
| 2201 | - /// mono track. The reason is [`ac3_decoder`]'s `corner-cut`, not this file's. | 2204 | + /// mono track. See [`ac3_decoder`]. |
| 2202 | requested: Option<u16>, | 2205 | requested: Option<u16>, |
| 2203 | } | 2206 | } |
| 2204 | 2207 | ||
| @@ -2233,20 +2236,20 @@ impl MkvAc3Track { | |||
| 2233 | // downmix decision wants. | 2236 | // downmix decision wants. |
| 2234 | let (sample_rate, nfchans) = if mkv.codec == "eac3" { | 2237 | let (sample_rate, nfchans) = if mkv.codec == "eac3" { |
| 2235 | // Annex E's BSI starts right after the 16-bit syncword. | 2238 | // Annex E's BSI starts right after the 16-bit syncword. |
| 2236 | - let bsi = oxideav_ac3::eac3::bsi::parse(first.get(2..).unwrap_or_default()) | 2239 | + let bsi = ec_ac3::eac3::parse(first.get(2..).unwrap_or_default()) |
| 2237 | .map_err(|e| format!("not a readable E-AC-3 bit stream information: {e:?}"))?; | 2240 | .map_err(|e| format!("not a readable E-AC-3 bit stream information: {e:?}"))?; |
| 2238 | (bsi.sample_rate, bsi.nfchans) | 2241 | (bsi.sample_rate, bsi.nfchans) |
| 2239 | } else { | 2242 | } else { |
| 2240 | - let sync = oxideav_ac3::syncinfo::parse(&first) | 2243 | + let sync = ec_ac3::syncinfo::parse(&first) |
| 2241 | .map_err(|e| format!("not a readable AC-3 syncframe: {e:?}"))?; | 2244 | .map_err(|e| format!("not a readable AC-3 syncframe: {e:?}"))?; |
| 2242 | - let bsi = oxideav_ac3::bsi::parse(first.get(5..).unwrap_or_default()) | 2245 | + let bsi = ec_ac3::bsi::parse(first.get(5..).unwrap_or_default()) |
| 2243 | .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))?; | 2246 | .map_err(|e| format!("not a readable AC-3 bit stream information: {e:?}"))?; |
| 2244 | (sync.sample_rate, bsi.nfchans) | 2247 | (sync.sample_rate, bsi.nfchans) |
| 2245 | }; | 2248 | }; |
| 2246 | let requested = (nfchans > 1).then_some(2); | 2249 | let requested = (nfchans > 1).then_some(2); |
| 2247 | - let mut decoder = ac3_decoder(mkv.codec, requested)?; | 2250 | + let mut decoder = ac3_decoder(requested)?; |
| 2248 | - let (pcm, samples) = | 2251 | + let (pcm, samples) = decode_ac3(&mut decoder, &first)? |
| 2249 | - decode_ac3(&mut decoder, &first)?.ok_or("the first AC-3 syncframe decoded to nothing")?; | 2252 | + .ok_or("the first AC-3 syncframe decoded to nothing")?; |
| 2250 | let channels = (pcm.len() as u64 / samples.max(1)) as u16; | 2253 | let channels = (pcm.len() as u64 / samples.max(1)) as u16; |
| 2251 | if channels == 0 { | 2254 | if channels == 0 { |
| 2252 | return Err("the first AC-3 syncframe decoded to nothing".into()); | 2255 | return Err("the first AC-3 syncframe decoded to nothing".into()); |
| @@ -2285,60 +2288,50 @@ impl MkvAc3Track { | |||
| 2285 | } | 2288 | } |
| 2286 | } | 2289 | } |
| 2287 | 2290 | ||
| 2288 | -/// A fresh AC-3 decoder handing out `channels`: `Some(2)` is the library's own | 2291 | +/// A fresh AC-3 / E-AC-3 decoder. `requested` is the downmix ask: `Some(2)` |
| 2289 | -/// A/52 §7.8 stereo downmix, which is the whole reason the timeline can carry a | 2292 | +/// hands back the library's own A/52 §7.8.2 stereo fold — per-position |
| 2290 | -/// 5.1 track at all. Fresh per segment for the same reason every other decoder | 2293 | +/// coefficients from the frame's own `acmod` and mix levels, LFE dropped, |
| 2291 | -/// here is: a seek leaves overlap-add state belonging to the frames we skipped. | 2294 | +/// normalised so a full-scale mix cannot clip — which is the whole reason the |
| 2292 | -/// | 2295 | +/// timeline can carry a 5.1 track at all; `None` passes the coded channels |
| 2293 | -/// corner-cut: `Some(2)` on a **mono** (`acmod` 1/0) source decodes to digital | 2296 | +/// through, which is what a mono track asks for (`acmod` 1/0 carries the |
| 2294 | -/// silence in oxideav-ac3 0.0.10 — measured, 5.1 and stereo are correct — so a | 2297 | +/// programme in the centre, and duplicating it is the timeline's business, see |
| 2295 | -/// mono track asks for no downmix at all and stays the mono source it is. The | 2298 | +/// [`widen`]). Fresh per segment for the same reason every other decoder here |
| 2296 | -/// upgrade path is `Some(2)` unconditionally once the library duplicates the | 2299 | +/// is: a seek leaves overlap-add state belonging to the frames we skipped. |
| 2297 | -/// centre channel; the caller ([`Ac3Track::open`]) is the only thing to change. | ||
| 2298 | /// | 2300 | /// |
| 2299 | -/// `codec` is the track's own id — `ac3` or `eac3`, which the library registers | 2301 | +/// The syntax is not an argument: one decoder reads AC-3 and E-AC-3 alike, |
| 2300 | -/// separately (E-AC-3 claims up to 8 channels where AC-3 claims 6). The struct | 2302 | +/// dispatching per packet on `bsid`. |
| 2301 | -/// behind both dispatches per packet on `bsid` in any case, so what this picks | 2303 | +fn ac3_decoder(requested: Option<u16>) -> crate::Result<ec_ac3::Ac3Decoder> { |
| 2302 | -/// is the capability set, not the syntax. | 2304 | + Ok(ec_ac3::Ac3Decoder::with_options(ec_ac3::Options { |
| 2303 | -fn ac3_decoder(codec: &str, channels: Option<u16>) -> crate::Result<Box<dyn Decoder>> { | 2305 | + downmix: requested |
| 2304 | - let mut registry = CodecRegistry::new(); | 2306 | + .map(|_| ec_ac3::Downmix::Stereo) |
| 2305 | - oxideav_ac3::register_codecs(&mut registry); | 2307 | + .unwrap_or(ec_ac3::Downmix::Native), |
| 2306 | - let mut params = CodecParameters::audio(CodecId::new(codec)); | 2308 | + ..ec_ac3::Options::default() |
| 2307 | - params.channels = channels; | 2309 | + })) |
| 2308 | - registry | ||
| 2309 | - .first_decoder(¶ms) | ||
| 2310 | - .map_err(|e| format!("no AC-3 decoder: {e:?}").into()) | ||
| 2311 | } | 2310 | } |
| 2312 | 2311 | ||
| 2313 | /// One syncframe in, one buffer of interleaved f32 out and the frames per | 2312 | /// One syncframe in, one buffer of interleaved f32 out and the frames per |
| 2314 | /// channel it holds. `Ok(None)` when the decoder wants more input before it can | 2313 | /// channel it holds. `Ok(None)` when the decoder wants more input before it can |
| 2315 | -/// hand a frame back, which is not an error. The library speaks S16 | 2314 | +/// hand a frame back, which is not an error. The library speaks interleaved |
| 2316 | -/// little-endian; `/32768` is the whole conversion, and it lands in the | 2315 | +/// little-endian f32 — the same `[-1, 1)` every other reader here emits. |
| 2317 | -/// `[-1, 1)` every other reader here emits. | ||
| 2318 | /// | 2316 | /// |
| 2319 | /// The frame count comes back beside the samples because an E-AC-3 frame is not | 2317 | /// The frame count comes back beside the samples because an E-AC-3 frame is not |
| 2320 | /// the fixed 1536 (6 blocks of 256) an AC-3 one is -- `numblkscod` may say 1, 2 | 2318 | /// the fixed 1536 (6 blocks of 256) an AC-3 one is -- `numblkscod` may say 1, 2 |
| 2321 | /// or 3 blocks instead of 6 -- and dividing by an assumed length would put the | 2319 | /// or 3 blocks instead of 6 -- and dividing by an assumed length would put the |
| 2322 | /// channel count and every media position after it out. | 2320 | /// channel count and every media position after it out. |
| 2323 | fn decode_ac3( | 2321 | fn decode_ac3( |
| 2324 | - decoder: &mut Box<dyn Decoder>, | 2322 | + decoder: &mut ec_ac3::Ac3Decoder, |
| 2325 | bytes: &[u8], | 2323 | bytes: &[u8], |
| 2326 | ) -> crate::Result<Option<(Vec<f32>, u64)>> { | 2324 | ) -> crate::Result<Option<(Vec<f32>, u64)>> { |
| 2327 | - let packet = Ac3Packet::new(0, oxideav_core::TimeBase::new(1, 48_000), bytes.to_vec()); | 2325 | + match decoder.decode_frame(bytes) { |
| 2328 | - decoder | 2326 | + Ok(frame) => Ok(Some(( |
| 2329 | - .send_packet(&packet) | 2327 | + frame.data[0] |
| 2330 | - .map_err(|e| format!("AC-3 decode failed: {e:?}"))?; | 2328 | + .chunks_exact(4) |
| 2331 | - match decoder.receive_frame() { | 2329 | + .map(|s| f32::from_le_bytes([s[0], s[1], s[2], s[3]])) |
| 2332 | - Ok(Frame::Audio(audio)) => Ok(Some(( | ||
| 2333 | - audio.data[0] | ||
| 2334 | - .chunks_exact(2) | ||
| 2335 | - .map(|s| f32::from(i16::from_le_bytes([s[0], s[1]])) / 32768.0) | ||
| 2336 | .collect(), | 2330 | .collect(), |
| 2337 | - u64::from(audio.samples), | 2331 | + frame.samples as u64, |
| 2338 | ))), | 2332 | ))), |
| 2339 | - Ok(other) => Err(format!("AC-3 decoder handed back {other:?}").into()), | 2333 | + Err(ec_ac3::Error::NeedMore) => Ok(None), |
| 2340 | - Err(oxideav_core::Error::NeedMore) => Ok(None), | 2334 | + Err(e) => Err(format!("AC-3 decode failed: {e}").into()), |
| 2341 | - Err(e) => Err(format!("AC-3 decode failed: {e:?}").into()), | ||
| 2342 | } | 2335 | } |
| 2343 | } | 2336 | } |
| 2344 | 2337 | ||
| @@ -3312,7 +3305,7 @@ fn run_ac3( | |||
| 3312 | timeline: &mut u64, | 3305 | timeline: &mut u64, |
| 3313 | tx: &SyncSender<AudioChunk>, | 3306 | tx: &SyncSender<AudioChunk>, |
| 3314 | ) -> bool { | 3307 | ) -> bool { |
| 3315 | - let mut decoder = match ac3_decoder("ac3", track.requested) { | 3308 | + let mut decoder = match ac3_decoder(track.requested) { |
| 3316 | Ok(decoder) => decoder, | 3309 | Ok(decoder) => decoder, |
| 3317 | Err(e) => { | 3310 | Err(e) => { |
| 3318 | eprintln!("audio decoder init failed: {e}"); | 3311 | eprintln!("audio decoder init failed: {e}"); |
| @@ -3340,9 +3333,8 @@ fn run_ac3( | |||
| 3340 | return true; | 3333 | return true; |
| 3341 | } | 3334 | } |
| 3342 | }; | 3335 | }; |
| 3343 | - // The library's §7.8 downmix already handles everything but its own 2.1 | 3336 | + // §7.8.2 has already folded anything wider than a pair; only a mono |
| 3344 | - // passthrough, which comes out at 3 and is folded here like any width. | 3337 | + // track arrives here in its own width, and [`widen`]'s is the last word. |
| 3345 | - downmix(&mut interleaved, usize::from(track.channels)); | ||
| 3346 | widen(&mut interleaved, usize::from(track.channels), channels); | 3338 | widen(&mut interleaved, usize::from(track.channels), channels); |
| 3347 | let next = pos + samples; | 3339 | let next = pos + samples; |
| 3348 | if !emit( | 3340 | if !emit( |
| @@ -3378,7 +3370,7 @@ fn run_mkv_ac3( | |||
| 3378 | timeline: &mut u64, | 3370 | timeline: &mut u64, |
| 3379 | tx: &SyncSender<AudioChunk>, | 3371 | tx: &SyncSender<AudioChunk>, |
| 3380 | ) -> bool { | 3372 | ) -> bool { |
| 3381 | - let mut decoder = match ac3_decoder(track.mkv.codec, track.requested) { | 3373 | + let mut decoder = match ac3_decoder(track.requested) { |
| 3382 | Ok(decoder) => decoder, | 3374 | Ok(decoder) => decoder, |
| 3383 | Err(e) => { | 3375 | Err(e) => { |
| 3384 | eprintln!("audio decoder init failed: {e}"); | 3376 | eprintln!("audio decoder init failed: {e}"); |
| @@ -3406,8 +3398,7 @@ fn run_mkv_ac3( | |||
| 3406 | return true; | 3398 | return true; |
| 3407 | } | 3399 | } |
| 3408 | }; | 3400 | }; |
| 3409 | - // ...and the 2.1 passthrough folded here, as on the mp4 side. | 3401 | + // ...and widened here, as on the mp4 side. |
| 3410 | - downmix(&mut interleaved, usize::from(track.channels)); | ||
| 3411 | widen(&mut interleaved, usize::from(track.channels), channels); | 3402 | widen(&mut interleaved, usize::from(track.channels), channels); |
| 3412 | let next = pos + samples; | 3403 | let next = pos + samples; |
| 3413 | if !emit( | 3404 | if !emit( |
crates/engine/src/caps.rsmodified+2 -2
| @@ -42,7 +42,7 @@ const SW_CODECS: [(&str, &str, bool, bool); 10] = [ | |||
| 42 | ("MP3", "symphonia / rusty_mp3", true, true), | 42 | ("MP3", "symphonia / rusty_mp3", true, true), |
| 43 | ("FLAC", "symphonia / flacenc", true, true), | 43 | ("FLAC", "symphonia / flacenc", true, true), |
| 44 | ("PCM", "symphonia / hound", true, true), | 44 | ("PCM", "symphonia / hound", true, true), |
| 45 | - ("AC-3", "oxideav-ac3", true, false), | 45 | + ("AC-3", "ec-ac3", true, false), |
| 46 | ("Vorbis", "symphonia / rusty_vorbis", true, true), | 46 | ("Vorbis", "symphonia / rusty_vorbis", true, true), |
| 47 | ("ALAC", "symphonia", true, false), | 47 | ("ALAC", "symphonia", true, false), |
| 48 | ]; | 48 | ]; |
| @@ -164,7 +164,7 @@ mod tests { | |||
| 164 | } | 164 | } |
| 165 | // Decode-only crates must not read as encoders, and the seat words are | 165 | // Decode-only crates must not read as encoders, and the seat words are |
| 166 | // the only thing saying which is which. | 166 | // the only thing saying which is which. |
| 167 | - assert!(line.contains("AC-3 dec (oxideav-ac3)")); | 167 | + assert!(line.contains("AC-3 dec (ec-ac3)")); |
| 168 | assert!(line.contains("H.264 dec+enc (ec-h264)")); | 168 | assert!(line.contains("H.264 dec+enc (ec-h264)")); |
| 169 | assert!(line.contains("HEVC enc (oxideav-h265 intra)")); | 169 | assert!(line.contains("HEVC enc (oxideav-h265 intra)")); |
| 170 | } | 170 | } |
crates/engine/src/demux.rsmodified+1 -1
| @@ -1750,7 +1750,7 @@ pub fn matroska_audio_tracks(path: &Path) -> crate::Result<Vec<MkvAudioTrack>> { | |||
| 1750 | pub struct MkvAudio { | 1750 | pub struct MkvAudio { |
| 1751 | file: File, | 1751 | file: File, |
| 1752 | blocks: Vec<Block>, | 1752 | blocks: Vec<Block>, |
| 1753 | - /// The `oxideav-ac3` codec id these blocks are packets of: `ac3` or `eac3`. | 1753 | + /// The Matroska codec id these blocks are packets of: `ac3` or `eac3`. |
| 1754 | pub codec: &'static str, | 1754 | pub codec: &'static str, |
| 1755 | /// Seconds one `TimestampScale` tick is worth, resolved once at open. | 1755 | /// Seconds one `TimestampScale` tick is worth, resolved once at open. |
| 1756 | secs_per_tick: f64, | 1756 | secs_per_tick: f64, |
crates/engine/tests/audio_ac3_film.rsadded+225 -0
| @@ -0,0 +1,225 @@ | |||
| 1 | +//! The AC-3 films: the decode seat exercised on the kind of tracks it exists | ||
| 2 | +//! for -- a BluRay remux's 48 kHz AC-3 5.1 and a web remux's 5.1 E-AC-3 | ||
| 3 | +//! (Dolby Digital Plus) -- decoded, folded to the pair the timeline carries, | ||
| 4 | +//! seeked across each film, and correlated against ffmpeg's own decode of the | ||
| 5 | +//! same windows. A wrong channel order, a wrong rate, or a fold that lost a | ||
| 6 | +//! side all move the correlation; a seat that refuses the track fails the | ||
| 7 | +//! open. | ||
| 8 | +//! | ||
| 9 | +//! Mirrors `audio_seek`'s film witnesses, which make the same claim of the | ||
| 10 | +//! Opus and multichannel AAC seats. Skipped, not failed, where the film or | ||
| 11 | +//! ffmpeg is not -- these are named by the local `real_library.toml`, not | ||
| 12 | +//! fixtures in this repository. | ||
| 13 | + | ||
| 14 | +use engine::audio::AudioSession; | ||
| 15 | + | ||
| 16 | +/// The AC-3 5.1 film: seeked to three seconds spread across the film and | ||
| 17 | +/// correlated against ffmpeg's decode of the same window. The seat's §7.8.2 | ||
| 18 | +/// fold and ffmpeg's `-ac 2` disagree by roughly 7.7 dB of level, which is | ||
| 19 | +/// why the comparison is level-normalised (`best_lag`). | ||
| 20 | +#[test] | ||
| 21 | +fn a_seek_into_real_ac3_film_lands_on_the_second_it_asked_for() { | ||
| 22 | + let Some(film) = engine::real_library::film("ac3_51_film") else { | ||
| 23 | + return; | ||
| 24 | + }; | ||
| 25 | + if no_ffmpeg() { | ||
| 26 | + return; | ||
| 27 | + } | ||
| 28 | + const SEARCH: f64 = 5.0; | ||
| 29 | + for want in [300.0, 600.0, 900.0] { | ||
| 30 | + let (meta, rx) = AudioSession::open_at(&film, want) | ||
| 31 | + .expect("open") | ||
| 32 | + .expect("the film has audio"); | ||
| 33 | + assert_eq!(meta.sample_rate, 48_000); | ||
| 34 | + assert_eq!(meta.channels, 2, "5.1 reaches the timeline as a pair"); | ||
| 35 | + let probe = one_second(&meta, rx); | ||
| 36 | + let from = want - SEARCH; | ||
| 37 | + let reference = ffmpeg_mono(&film, from, 2.0 * SEARCH + 2.0, meta.sample_rate); | ||
| 38 | + let (lag, score) = best_lag(&probe, &reference); | ||
| 39 | + let at = from + lag as f64 / f64::from(meta.sample_rate); | ||
| 40 | + eprintln!("asked {want}s, content at {at:.3}s (correlation {score:.3})"); | ||
| 41 | + assert!( | ||
| 42 | + score > 0.5, | ||
| 43 | + "asked {want}s: nothing in the reference window correlates ({score:.3}) -- \ | ||
| 44 | + the measurement, not the seek, is what failed" | ||
| 45 | + ); | ||
| 46 | + assert!( | ||
| 47 | + (at - want).abs() <= 0.05, | ||
| 48 | + "asked {want}s, heard {at:.3}s -- {:+.3}s of sound against picture", | ||
| 49 | + at - want | ||
| 50 | + ); | ||
| 51 | + } | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +/// The E-AC-3 film: the Dolby Digital Plus class a web remux carries, whose | ||
| 55 | +/// blocks are fixed-laced in Matroska and whose frames are not the fixed | ||
| 56 | +/// 1536-sample AC-3 shape. Same claim, same measurement. | ||
| 57 | +#[test] | ||
| 58 | +fn a_seek_into_real_eac3_film_lands_on_the_second_it_asked_for() { | ||
| 59 | + let Some(film) = engine::real_library::film("hevc_4k_hdr") else { | ||
| 60 | + return; | ||
| 61 | + }; | ||
| 62 | + if no_ffmpeg() { | ||
| 63 | + return; | ||
| 64 | + } | ||
| 65 | + const SEARCH: f64 = 5.0; | ||
| 66 | + for want in [600.0, 1800.0, 3600.0] { | ||
| 67 | + let (meta, rx) = AudioSession::open_at(&film, want) | ||
| 68 | + .expect("open") | ||
| 69 | + .expect("the film has audio"); | ||
| 70 | + assert_eq!(meta.sample_rate, 48_000); | ||
| 71 | + assert_eq!(meta.channels, 2, "5.1 reaches the timeline as a pair"); | ||
| 72 | + let probe = one_second(&meta, rx); | ||
| 73 | + let from = want - SEARCH; | ||
| 74 | + let reference = ffmpeg_mono(&film, from, 2.0 * SEARCH + 2.0, meta.sample_rate); | ||
| 75 | + let (lag, score) = best_lag(&probe, &reference); | ||
| 76 | + let at = from + lag as f64 / f64::from(meta.sample_rate); | ||
| 77 | + eprintln!("asked {want}s, content at {at:.3}s (correlation {score:.3})"); | ||
| 78 | + assert!( | ||
| 79 | + score > 0.5, | ||
| 80 | + "asked {want}s: nothing in the reference window correlates ({score:.3}) -- \ | ||
| 81 | + the measurement, not the seek, is what failed" | ||
| 82 | + ); | ||
| 83 | + assert!( | ||
| 84 | + (at - want).abs() <= 0.05, | ||
| 85 | + "asked {want}s, heard {at:.3}s -- {:+.3}s of sound against picture", | ||
| 86 | + at - want | ||
| 87 | + ); | ||
| 88 | + } | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +/// True, with the skip said, when ffmpeg is not there to decode a reference. | ||
| 92 | +fn no_ffmpeg() -> bool { | ||
| 93 | + let missing = std::process::Command::new("ffmpeg") | ||
| 94 | + .arg("-version") | ||
| 95 | + .stdout(std::process::Stdio::null()) | ||
| 96 | + .stderr(std::process::Stdio::null()) | ||
| 97 | + .status() | ||
| 98 | + .map(|s| !s.success()) | ||
| 99 | + .unwrap_or(true); | ||
| 100 | + if missing { | ||
| 101 | + eprintln!("skipped: no ffmpeg to decode the reference window with"); | ||
| 102 | + } | ||
| 103 | + missing | ||
| 104 | +} | ||
| 105 | + | ||
| 106 | +/// One second of the opened session, summed to mono: the probe `best_lag` | ||
| 107 | +/// locates inside ffmpeg's window. | ||
| 108 | +fn one_second( | ||
| 109 | + meta: &engine::audio::AudioMeta, | ||
| 110 | + rx: std::sync::mpsc::Receiver<engine::audio::AudioChunk>, | ||
| 111 | +) -> Vec<f64> { | ||
| 112 | + let channels = usize::from(meta.channels); | ||
| 113 | + let mut probe: Vec<f64> = Vec::with_capacity(meta.sample_rate as usize); | ||
| 114 | + for chunk in rx { | ||
| 115 | + probe.extend( | ||
| 116 | + chunk | ||
| 117 | + .samples | ||
| 118 | + .chunks_exact(channels) | ||
| 119 | + .map(|f| f.iter().map(|s| f64::from(*s)).sum::<f64>() / channels as f64), | ||
| 120 | + ); | ||
| 121 | + if probe.len() >= meta.sample_rate as usize { | ||
| 122 | + break; | ||
| 123 | + } | ||
| 124 | + } | ||
| 125 | + probe.truncate(meta.sample_rate as usize); | ||
| 126 | + assert_eq!(probe.len(), meta.sample_rate as usize, "a second to locate"); | ||
| 127 | + probe | ||
| 128 | +} | ||
| 129 | + | ||
| 130 | +/// `dur` seconds of `path`'s first audio track from `start`, decoded by ffmpeg, | ||
| 131 | +/// summed to mono at `rate`. The reference this engine's own landing is measured | ||
| 132 | +/// against, because a decoder cannot be its own witness about where it landed. | ||
| 133 | +fn ffmpeg_mono(path: &std::path::Path, start: f64, dur: f64, rate: u32) -> Vec<f64> { | ||
| 134 | + let out = std::process::Command::new("ffmpeg") | ||
| 135 | + .args(["-v", "error", "-ss"]) | ||
| 136 | + .arg(format!("{start}")) | ||
| 137 | + .arg("-t") | ||
| 138 | + .arg(format!("{dur}")) | ||
| 139 | + .arg("-i") | ||
| 140 | + .arg(path) | ||
| 141 | + .args(["-map", "0:a:0", "-ac", "1", "-ar"]) | ||
| 142 | + .arg(rate.to_string()) | ||
| 143 | + .args(["-f", "f32le", "-"]) | ||
| 144 | + .output() | ||
| 145 | + .expect("ffmpeg runs"); | ||
| 146 | + assert!( | ||
| 147 | + out.status.success(), | ||
| 148 | + "ffmpeg: {}", | ||
| 149 | + String::from_utf8_lossy(&out.stderr) | ||
| 150 | + ); | ||
| 151 | + out.stdout | ||
| 152 | + .chunks_exact(4) | ||
| 153 | + .map(|b| f64::from(f32::from_le_bytes([b[0], b[1], b[2], b[3]]))) | ||
| 154 | + .collect() | ||
| 155 | +} | ||
| 156 | + | ||
| 157 | +/// Where in `reference` the `probe` sits, and how well: the offset in samples of | ||
| 158 | +/// the best normalised cross-correlation, which is 1.0 for the same content and | ||
| 159 | +/// falls away fast for anything else. | ||
| 160 | +/// | ||
| 161 | +/// Coarse then fine, because the naive product over a ten-second window at | ||
| 162 | +/// 48 kHz is 3e10 multiplies: both signals are averaged down by [`DECIMATE`] | ||
| 163 | +/// first -- a crude low-pass, and the peak of a correlation is broad -- then the | ||
| 164 | +/// winner is refined at full rate over the one block around it. The normalisation | ||
| 165 | +/// is what makes the two comparable at all, since this fold is 7.7 dB quieter | ||
| 166 | +/// than ffmpeg's. | ||
| 167 | +fn best_lag(probe: &[f64], reference: &[f64]) -> (usize, f64) { | ||
| 168 | + const DECIMATE: usize = 32; | ||
| 169 | + let down = |xs: &[f64]| -> Vec<f64> { | ||
| 170 | + xs.chunks_exact(DECIMATE) | ||
| 171 | + .map(|c| c.iter().sum::<f64>() / DECIMATE as f64) | ||
| 172 | + .collect() | ||
| 173 | + }; | ||
| 174 | + let (coarse, at) = scan(&down(probe), &down(reference), 1); | ||
| 175 | + let from = (at * DECIMATE).saturating_sub(DECIMATE); | ||
| 176 | + let span = 3 * DECIMATE + probe.len(); | ||
| 177 | + // The score reported is the coarse one, over the whole search window: the | ||
| 178 | + // fine pass only sharpens the offset inside a block it has already chosen, | ||
| 179 | + // and a score over a window that short says nothing about the match. | ||
| 180 | + let (_, offset) = scan( | ||
| 181 | + probe, | ||
| 182 | + &reference[from.min(reference.len())..(from + span).min(reference.len())], | ||
| 183 | + 1, | ||
| 184 | + ); | ||
| 185 | + (from + offset, coarse) | ||
| 186 | +} | ||
| 187 | + | ||
| 188 | +/// The best normalised cross-correlation of `probe` over `reference`, at `step` | ||
| 189 | +/// samples: `(score, offset)`. Both are mean-removed; the denominator is each | ||
| 190 | +/// window's own energy, so a level difference between the two decoders cannot | ||
| 191 | +/// move the peak. | ||
| 192 | +fn scan(probe: &[f64], reference: &[f64], step: usize) -> (f64, usize) { | ||
| 193 | + if reference.len() <= probe.len() || probe.is_empty() { | ||
| 194 | + return (0.0, 0); | ||
| 195 | + } | ||
| 196 | + let mean = |xs: &[f64]| xs.iter().sum::<f64>() / xs.len() as f64; | ||
| 197 | + let p: Vec<f64> = { | ||
| 198 | + let m = mean(probe); | ||
| 199 | + probe.iter().map(|s| s - m).collect() | ||
| 200 | + }; | ||
| 201 | + let pe = p.iter().map(|s| s * s).sum::<f64>().sqrt(); | ||
| 202 | + if pe <= 0.0 { | ||
| 203 | + return (0.0, 0); | ||
| 204 | + } | ||
| 205 | + let (mut best, mut at) = (0.0, 0); | ||
| 206 | + for offset in (0..reference.len() - p.len()).step_by(step) { | ||
| 207 | + let window = &reference[offset..offset + p.len()]; | ||
| 208 | + let m = mean(window); | ||
| 209 | + let (mut dot, mut energy) = (0.0, 0.0); | ||
| 210 | + for (a, b) in p.iter().zip(window) { | ||
| 211 | + let b = b - m; | ||
| 212 | + dot += a * b; | ||
| 213 | + energy += b * b; | ||
| 214 | + } | ||
| 215 | + let score = match energy > 0.0 { | ||
| 216 | + true => dot / (pe * energy.sqrt()), | ||
| 217 | + false => 0.0, | ||
| 218 | + }; | ||
| 219 | + if score > best { | ||
| 220 | + best = score; | ||
| 221 | + at = offset; | ||
| 222 | + } | ||
| 223 | + } | ||
| 224 | + (best, at) | ||
| 225 | +} | ||
real_library.toml.examplemodified+5 -0
| @@ -26,3 +26,8 @@ av1_opus_71 = "/path/to/a-2160p-av1-opus-7.1-remux.mkv" | |||
| 26 | # A feature-length 1080p AV1 remux with a 5.1 Opus track and a cue table: long | 26 | # A feature-length 1080p AV1 remux with a 5.1 Opus track and a cue table: long |
| 27 | # enough to seek an hour into, which is where a Matroska landing goes wrong. | 27 | # enough to seek an hour into, which is where a Matroska landing goes wrong. |
| 28 | av1_opus_51 = "/path/to/a-1080p-av1-opus-5.1-remux.mkv" | 28 | av1_opus_51 = "/path/to/a-1080p-av1-opus-5.1-remux.mkv" |
| 29 | + | ||
| 30 | +# A feature-length film with a plain AC-3 5.1 track (a BluRay encode or remux): | ||
| 31 | +# the multichannel AC-3 seat's own film witness, seeked and correlated against | ||
| 32 | +# ffmpeg like the Opus and AAC films are. | ||
| 33 | +ac3_51_film = "/path/to/an-ac3-5.1-film.mkv" | ||