An Opus film is heard, not refused
Browse files at this commit699950af73d94cd691df3f0f5a875a38bed7577cParent: 8a2e813- feat
- an Opus film is heard, not refused
7 changed files +335 -29
- Cargo.lock +7 -0
- crates/engine/Cargo.toml +22 -2
- crates/engine/src/audio.rs +138 -11
- crates/engine/src/lib.rs +20 -8
- crates/engine/tests/audio_decode.rs +84 -0
- crates/engine/tests/capability_matrix.rs +32 -6
- scripts/gen_fixtures.sh +32 -2
Cargo.lockmodified+7 -0
| @@ -1650,6 +1650,7 @@ dependencies = [ | |||
| 1650 | "oxideav-sub-image", | 1650 | "oxideav-sub-image", |
| 1651 | "oxideav-subtitle", | 1651 | "oxideav-subtitle", |
| 1652 | "rav1e", | 1652 | "rav1e", |
| 1653 | + "ruopus", | ||
| 1653 | "rusty_aac", | 1654 | "rusty_aac", |
| 1654 | "rusty_h264", | 1655 | "rusty_h264", |
| 1655 | "rusty_mp3", | 1656 | "rusty_mp3", |
| @@ -4856,6 +4857,12 @@ version = "0.20.0" | |||
| 4856 | source = "registry+https://github.com/rust-lang/crates.io-index" | 4857 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 4857 | checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" | 4858 | checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" |
| 4858 | 4859 | ||
| 4860 | +[[package]] | ||
| 4861 | +name = "ruopus" | ||
| 4862 | +version = "0.1.2" | ||
| 4863 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 4864 | +checksum = "fcfcd963c83fc1ada2180ccdac7f1568d87fb0f2ad7236b266fdc9fb9122fbfd" | ||
| 4865 | + | ||
| 4859 | [[package]] | 4866 | [[package]] |
| 4860 | name = "rust-embed" | 4867 | name = "rust-embed" |
| 4861 | version = "8.12.0" | 4868 | version = "8.12.0" |
crates/engine/Cargo.tomlmodified+22 -2
| @@ -56,6 +56,25 @@ rusty_mp3 = "0.6" | |||
| 56 | # packet. This one does the whole pipeline. Its quirks are measured and worked | 56 | # packet. This one does the whole pipeline. Its quirks are measured and worked |
| 57 | # around in [`crate::export::write_ogg`] -- read that before touching this line. | 57 | # around in [`crate::export::write_ogg`] -- read that before touching this line. |
| 58 | rusty_vorbis = "0.1.1" | 58 | rusty_vorbis = "0.1.1" |
| 59 | +# The Opus decoder: pure Rust, MIT, no C and no FFI, and no dependencies at all | ||
| 60 | +# without its default features (`spectrograms` is for its own analysis tools). | ||
| 61 | +# Symphonia has no Opus at any version -- its feature list stops at vorbis and | ||
| 62 | +# there is no `symphonia-codec-opus` crate -- while both of its containers *read* | ||
| 63 | +# the format already: `A_OPUS` and `OpusHead` have always mapped to | ||
| 64 | +# `CODEC_ID_OPUS`. The decoder was the one missing half, and the reason a 5.1 | ||
| 65 | +# Opus film played silent while its picture was fine. | ||
| 66 | +# | ||
| 67 | +# Multistream is what decides which crate: a 5.1 track is four elementary Opus | ||
| 68 | +# streams in one packet, all but the last **self-delimited** (RFC 6716 App. B), | ||
| 69 | +# and this one strips that framing per stream (`multistream.rs:71`). The obvious | ||
| 70 | +# sibling pick, `rusty-opus 0.9.1` -- same family as `rusty_aac`/`rusty_mp3` | ||
| 71 | +# above -- hands each self-delimited slice to a decoder that parses it as an | ||
| 72 | +# ordinary packet, so every stream but the last decodes the length prefix as | ||
| 73 | +# payload: measured on a real 5.1 Opus remux as full-scale noise at -13 dBFS where the | ||
| 74 | +# film is silent. This one matches ffmpeg's own decode of the same file to a | ||
| 75 | +# correlation of 1.0000 on all six channels. Pinned exactly, like `oxideav-ac3` | ||
| 76 | +# below, because a decoder is a bit-exactness dependency. | ||
| 77 | +ruopus = { version = "=0.1.2", default-features = false, features = ["std"] } | ||
| 59 | # The Ogg container, and the only new *name* here that is not a new crate tree: | 78 | # The Ogg container, and the only new *name* here that is not a new crate tree: |
| 60 | # its one dependency is `oxideav-core`, which the AC-3 decoder above already | 79 | # its one dependency is `oxideav-core`, which the AC-3 decoder above already |
| 61 | # pulls in. MIT. Vorbis-aware where it counts -- `xiph_lace` builds the | 80 | # pulls in. MIT. Vorbis-aware where it counts -- `xiph_lace` builds the |
| @@ -71,8 +90,9 @@ symphonia-codec-aac = "0.6" | |||
| 71 | # ape, no adpcm: what is listed here is exactly what `is_audio` admits, plus | 90 | # ape, no adpcm: what is listed here is exactly what `is_audio` admits, plus |
| 72 | # `mkv`, which is not an `is_audio` container at all -- it is how the *sound* of | 91 | # `mkv`, which is not an `is_audio` container at all -- it is how the *sound* of |
| 73 | # a Matroska video file is read, the picture having its own demuxer here. | 92 | # a Matroska video file is read, the picture having its own demuxer here. |
| 74 | -# There is no opus/ac3/dts feature at any symphonia version, which is why those | 93 | +# There is no opus/ac3/dts feature at any symphonia version: AC-3 comes from |
| 75 | -# are refused rather than promised. | 94 | +# `oxideav-ac3` and Opus from `ruopus` above, both plugged into this crate's |
| 95 | +# own readers, and DTS is the one that really is refused. | ||
| 76 | symphonia = { version = "0.6", default-features = false, features = [ | 96 | symphonia = { version = "0.6", default-features = false, features = [ |
| 77 | "aac", | 97 | "aac", |
| 78 | "alac", | 98 | "alac", |
crates/engine/src/audio.rsmodified+138 -11
| @@ -37,7 +37,8 @@ use mp4::{AudioObjectType, ChannelConfig, MediaType, Mp4Reader, Mp4Track, TrackT | |||
| 37 | use oxideav_core::{CodecId, CodecParameters, CodecRegistry, Decoder, Frame, Packet as Ac3Packet}; | 37 | use oxideav_core::{CodecId, CodecParameters, CodecRegistry, Decoder, Frame, Packet as Ac3Packet}; |
| 38 | use symphonia_codec_aac::AacDecoder; | 38 | use symphonia_codec_aac::AacDecoder; |
| 39 | use symphonia_core::codecs::audio::{ | 39 | use symphonia_core::codecs::audio::{ |
| 40 | - AudioCodecParameters, AudioDecoder, AudioDecoderOptions, well_known::CODEC_ID_AAC, | 40 | + AudioCodecParameters, AudioDecoder, AudioDecoderOptions, |
| 41 | + well_known::{CODEC_ID_AAC, CODEC_ID_OPUS}, | ||
| 41 | }; | 42 | }; |
| 42 | use symphonia_core::formats::probe::Hint; | 43 | use symphonia_core::formats::probe::Hint; |
| 43 | // `TrackType` is the name both readers give their track kinds; the mp4 one is | 44 | // `TrackType` is the name both readers give their track kinds; the mp4 one is |
| @@ -63,8 +64,9 @@ const EMPTY_EDIT: u64 = u32::MAX as u64; | |||
| 63 | 64 | ||
| 64 | /// 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: |
| 65 | /// 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 |
| 66 | -/// `Cargo.toml`) plus the AC-3 family, which no symphonia version carries and | 67 | +/// `Cargo.toml`) plus the two families no symphonia version carries and this |
| 67 | -/// `oxideav-ac3` does ([`MkvAc3Track`]). | 68 | +/// project decodes anyway -- AC-3/E-AC-3 through `oxideav-ac3` ([`MkvAc3Track`]) |
| 69 | +/// and Opus through `ruopus` ([`SymDecoder::Opus`]). | ||
| 68 | /// | 70 | /// |
| 69 | /// 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 |
| 70 | /// sound never reaches symphonia ([`Track::open`] answers before it), so it | 72 | /// sound never reaches symphonia ([`Track::open`] answers before it), so it |
| @@ -72,7 +74,7 @@ const EMPTY_EDIT: u64 = u32::MAX as u64; | |||
| 72 | /// long after that stopped being true, which is how a user came to re-encode a | 74 | /// long after that stopped being true, which is how a user came to re-encode a |
| 73 | /// film whose FLAC track already played; `capability_matrix` opens one file per | 75 | /// film whose FLAC track already played; `capability_matrix` opens one file per |
| 74 | /// codec named here. | 76 | /// codec named here. |
| 75 | -const MKV_DECODED: &str = "AAC, AC-3/E-AC-3, ALAC, FLAC, MP3, PCM and Vorbis"; | 77 | +const MKV_DECODED: &str = "AAC, AC-3/E-AC-3, ALAC, FLAC, MP3, Opus, PCM and Vorbis"; |
| 76 | 78 | ||
| 77 | /// ...and the mp4 half: [`AacTrack`] and [`Ac3Track`], which is where a video | 79 | /// ...and the mp4 half: [`AacTrack`] and [`Ac3Track`], which is where a video |
| 78 | /// file's sound is read and where it stops. | 80 | /// file's sound is read and where it stops. |
| @@ -677,10 +679,10 @@ impl AudioSession { | |||
| 677 | pub fn unsupported(path: impl AsRef<Path>) -> crate::Result<Option<String>> { | 679 | pub fn unsupported(path: impl AsRef<Path>) -> crate::Result<Option<String>> { |
| 678 | // Matroska: what symphonia reads out of one ([`Track::open`]) plus the | 680 | // Matroska: what symphonia reads out of one ([`Track::open`]) plus the |
| 679 | // AC-3 and E-AC-3 whose blocks are handed to the Dolby decoder | 681 | // AC-3 and E-AC-3 whose blocks are handed to the Dolby decoder |
| 680 | - // ([`MkvAc3Track`]); everything else -- Opus, DTS, which no decoder here | 682 | + // ([`MkvAc3Track`]) and the Opus its own decoder takes; everything else |
| 681 | - // has at any version -- is named rather than left playing silent with no | 683 | + // -- DTS, and whatever else no decoder here has -- is named rather than |
| 682 | - // reason given. A Matroska file with no audio track at all returns | 684 | + // left playing silent with no reason given. A Matroska file with no |
| 683 | - // `None` here like any other silent file. | 685 | + // audio track at all returns `None` here like any other silent file. |
| 684 | if crate::demux::is_matroska(path.as_ref()) { | 686 | if crate::demux::is_matroska(path.as_ref()) { |
| 685 | let Some(codec) = crate::demux::matroska_audio_codec(path.as_ref())? else { | 687 | let Some(codec) = crate::demux::matroska_audio_codec(path.as_ref())? else { |
| 686 | return Ok(None); | 688 | return Ok(None); |
| @@ -690,6 +692,18 @@ impl AudioSession { | |||
| 690 | // reader's own words are the ones worth showing. | 692 | // reader's own words are the ones worth showing. |
| 691 | return Ok(Some(match MkvAc3Track::open(path.as_ref()) { | 693 | return Ok(Some(match MkvAc3Track::open(path.as_ref()) { |
| 692 | Ok(Some(_)) => return Ok(None), | 694 | Ok(Some(_)) => return Ok(None), |
| 695 | + // ...and the same question asked of the other reader, because a | ||
| 696 | + // refusal is a claim: a track symphonia's side really opens and | ||
| 697 | + // builds a decoder for is not one to tell the user about. This | ||
| 698 | + // is what stopped naming `A_OPUS` the moment Opus decoded. | ||
| 699 | + Ok(None) | Err(_) | ||
| 700 | + if SymTrack::open(path.as_ref()) | ||
| 701 | + .ok() | ||
| 702 | + .flatten() | ||
| 703 | + .is_some_and(|t| t.decoder().is_ok()) => | ||
| 704 | + { | ||
| 705 | + return Ok(None); | ||
| 706 | + } | ||
| 693 | Ok(None) => format!( | 707 | Ok(None) => format!( |
| 694 | "the {codec} track of this Matroska file cannot be decoded — {MKV_DECODED} are" | 708 | "the {codec} track of this Matroska file cannot be decoded — {MKV_DECODED} are" |
| 695 | ), | 709 | ), |
| @@ -1441,6 +1455,18 @@ impl SymTrack { | |||
| 1441 | let codec = symphonia::default::get_codecs() | 1455 | let codec = symphonia::default::get_codecs() |
| 1442 | .get_audio_decoder(params.codec) | 1456 | .get_audio_decoder(params.codec) |
| 1443 | .map_or("an unsupported format", |d| d.codec.info.short_name); | 1457 | .map_or("an unsupported format", |d| d.codec.info.short_name); |
| 1458 | + // The one codec here that *does* owe a priming number: Opus states its | ||
| 1459 | + // encoder delay in the stream itself (`OpusHead`'s pre-skip, 312 samples | ||
| 1460 | + // on a film remux) and neither reader drops it, because symphonia trims | ||
| 1461 | + // for its own decoders and the Opus one is this crate's. Measured against | ||
| 1462 | + // ffmpeg's decode of the same file: 312 samples late in *both* an mkv and | ||
| 1463 | + // an ogg until this is subtracted, sample-exact after (correlation | ||
| 1464 | + // 1.00000). It is priming exactly as an AAC track's is, and it is read | ||
| 1465 | + // off the stream rather than the container for that reason. | ||
| 1466 | + let priming = match params.codec { | ||
| 1467 | + CODEC_ID_OPUS => opus_pre_skip(params.extra_data.as_deref().unwrap_or_default()), | ||
| 1468 | + _ => 0, | ||
| 1469 | + }; | ||
| 1444 | Ok(Some(Self { | 1470 | Ok(Some(Self { |
| 1445 | reader, | 1471 | reader, |
| 1446 | track_id, | 1472 | track_id, |
| @@ -1450,8 +1476,8 @@ impl SymTrack { | |||
| 1450 | // [`Track::channels`], where it always was. | 1476 | // [`Track::channels`], where it always was. |
| 1451 | channels: if channels == 6 { 2 } else { channels }, | 1477 | channels: if channels == 6 { 2 } else { channels }, |
| 1452 | source_channels: channels, | 1478 | source_channels: channels, |
| 1453 | - total_samples: num_frames, | 1479 | + total_samples: num_frames.map(|n| n.saturating_sub(priming)), |
| 1454 | - priming: 0, | 1480 | + priming, |
| 1455 | time_base, | 1481 | time_base, |
| 1456 | params, | 1482 | params, |
| 1457 | codec, | 1483 | codec, |
| @@ -1471,9 +1497,19 @@ impl SymTrack { | |||
| 1471 | /// Which decoder is not the caller's business, and it is not always | 1497 | /// Which decoder is not the caller's business, and it is not always |
| 1472 | /// symphonia's: its AAC decoder refuses anything wider than stereo outright | 1498 | /// symphonia's: its AAC decoder refuses anything wider than stereo outright |
| 1473 | /// (`aac/mod.rs:93`, "aac: aac too complex"), which is exactly the 5.1 track | 1499 | /// (`aac/mod.rs:93`, "aac: aac too complex"), which is exactly the 5.1 track |
| 1474 | - /// of a film in an mkv, so that one goes to `rusty_aac` instead. | 1500 | + /// of a film in an mkv, so that one goes to `rusty_aac` instead, and it has |
| 1501 | + /// no Opus decoder at all, so that one goes to `ruopus`. | ||
| 1475 | fn decoder(&self) -> crate::Result<SymDecoder> { | 1502 | fn decoder(&self) -> crate::Result<SymDecoder> { |
| 1476 | let fold = self.source_channels != self.channels; | 1503 | let fold = self.source_channels != self.channels; |
| 1504 | + if self.params.codec == CODEC_ID_OPUS { | ||
| 1505 | + let channels = usize::from(self.source_channels); | ||
| 1506 | + let (streams, coupled, mapping) = | ||
| 1507 | + opus_layout(self.params.extra_data.as_deref().unwrap_or_default(), channels)?; | ||
| 1508 | + // 48 kHz whatever the container says: that is the only rate Opus | ||
| 1509 | + // decodes at, and the rate both readers declare for it. | ||
| 1510 | + let decoder = ruopus::MultistreamDecoder::with_rate(48_000, streams, coupled, &mapping); | ||
| 1511 | + return Ok(SymDecoder::Opus(Box::new(decoder), fold)); | ||
| 1512 | + } | ||
| 1477 | if self.params.codec == CODEC_ID_AAC && self.source_channels > 2 { | 1513 | if self.params.codec == CODEC_ID_AAC && self.source_channels > 2 { |
| 1478 | let asc = self | 1514 | let asc = self |
| 1479 | .params | 1515 | .params |
| @@ -1512,6 +1548,10 @@ enum SymDecoder { | |||
| 1512 | /// Boxed because the decoder carries its own IMDCT tables and this enum is | 1548 | /// Boxed because the decoder carries its own IMDCT tables and this enum is |
| 1513 | /// moved into the worker. | 1549 | /// moved into the worker. |
| 1514 | Aac(Box<rusty_aac::AacDecoder>, bool), | 1550 | Aac(Box<rusty_aac::AacDecoder>, bool), |
| 1551 | + /// Every Opus track, mono to 5.1: one multistream decoder -- the streams of | ||
| 1552 | + /// a packet, the channel mapping table and the routing between them are all | ||
| 1553 | + /// its business -- and the same fold flag. | ||
| 1554 | + Opus(Box<ruopus::MultistreamDecoder>, bool), | ||
| 1515 | } | 1555 | } |
| 1516 | 1556 | ||
| 1517 | impl SymDecoder { | 1557 | impl SymDecoder { |
| @@ -1528,11 +1568,98 @@ impl SymDecoder { | |||
| 1528 | *out = pcm.samples; | 1568 | *out = pcm.samples; |
| 1529 | fold_5_1(out, *fold); | 1569 | fold_5_1(out, *fold); |
| 1530 | } | 1570 | } |
| 1571 | + Self::Opus(decoder, fold) => { | ||
| 1572 | + *out = decoder | ||
| 1573 | + .decode_packet(&packet.data) | ||
| 1574 | + .map_err(|e| format!("Opus decode failed: {e}"))?; | ||
| 1575 | + // The encoder delay is not dropped here: it is this track's | ||
| 1576 | + // priming ([`SymTrack::open_inner`]), which the window rules | ||
| 1577 | + // subtract once for the whole segment rather than per packet. | ||
| 1578 | + vorbis_to_film_order(out, *fold); | ||
| 1579 | + fold_5_1(out, *fold); | ||
| 1580 | + } | ||
| 1531 | } | 1581 | } |
| 1532 | Ok(()) | 1582 | Ok(()) |
| 1533 | } | 1583 | } |
| 1534 | } | 1584 | } |
| 1535 | 1585 | ||
| 1586 | +/// The encoder delay of an Opus track, in samples at 48 kHz: bytes 10 and 11 of | ||
| 1587 | +/// `OpusHead`, little-endian. Zero for a track whose header is missing or too | ||
| 1588 | +/// short to hold one -- there is nothing to subtract that we can trust. | ||
| 1589 | +fn opus_pre_skip(head: &[u8]) -> u64 { | ||
| 1590 | + match head { | ||
| 1591 | + [b'O', b'p', b'u', b's', b'H', b'e', b'a', b'd', _, _, lo, hi, ..] => { | ||
| 1592 | + u64::from(u16::from_le_bytes([*lo, *hi])) | ||
| 1593 | + } | ||
| 1594 | + _ => 0, | ||
| 1595 | + } | ||
| 1596 | +} | ||
| 1597 | + | ||
| 1598 | +/// The stream layout of an Opus track, off the file's own `OpusHead`: how many | ||
| 1599 | +/// elementary streams one packet carries, how many of those are coupled | ||
| 1600 | +/// (stereo), and which decoded channel each output channel comes from. Both | ||
| 1601 | +/// readers hand the header over as `extra_data` verbatim -- an mkv's | ||
| 1602 | +/// `CodecPrivate`, an ogg's identification packet. | ||
| 1603 | +/// | ||
| 1604 | +/// Mapping family 0 carries no table at all and is mono or stereo by definition; | ||
| 1605 | +/// every other family writes one (RFC 7845 §5.1), and family 1 -- the Vorbis | ||
| 1606 | +/// surround layout a 5.1 film track is written with -- is four streams of which | ||
| 1607 | +/// two are coupled. | ||
| 1608 | +/// | ||
| 1609 | +/// Everything here is checked rather than trusted: `MultistreamDecoder::with_rate` | ||
| 1610 | +/// *panics* on a layout that breaks the RFC's limits, and this header comes | ||
| 1611 | +/// straight out of a file, so a truncated or hostile one has to come back as an | ||
| 1612 | +/// `Err` and be refused like any other undecodable track. | ||
| 1613 | +fn opus_layout(head: &[u8], channels: usize) -> crate::Result<(usize, usize, Vec<u8>)> { | ||
| 1614 | + if !(1..=255).contains(&channels) { | ||
| 1615 | + return Err(format!("an Opus track of {channels} channels").into()); | ||
| 1616 | + } | ||
| 1617 | + let table = match head { | ||
| 1618 | + [b'O', b'p', b'u', b's', b'H', b'e', b'a', b'd', rest @ ..] if rest.len() > 10 => { | ||
| 1619 | + // Byte 18 of the header is the mapping family; the table, when there | ||
| 1620 | + // is one, is the two counts and one byte per output channel after it. | ||
| 1621 | + match rest[10] { | ||
| 1622 | + 0 => None, | ||
| 1623 | + _ => Some(rest.get(11..13 + channels).ok_or("a truncated OpusHead")?), | ||
| 1624 | + } | ||
| 1625 | + } | ||
| 1626 | + // No header at all: the container declared the channel count and nothing | ||
| 1627 | + // else, which only family 0 can honestly be. | ||
| 1628 | + _ => None, | ||
| 1629 | + }; | ||
| 1630 | + let Some(table) = table else { | ||
| 1631 | + if channels > 2 { | ||
| 1632 | + return Err(format!("an Opus track of {channels} channels with no mapping").into()); | ||
| 1633 | + } | ||
| 1634 | + return Ok((1, channels - 1, (0..channels as u8).collect())); | ||
| 1635 | + }; | ||
| 1636 | + let (streams, coupled) = (usize::from(table[0]), usize::from(table[1])); | ||
| 1637 | + let mapping = table[2..].to_vec(); | ||
| 1638 | + let decoded = streams + coupled; | ||
| 1639 | + if streams < 1 || coupled > streams || decoded > 255 { | ||
| 1640 | + return Err(format!("an Opus track of {streams} streams, {coupled} coupled").into()); | ||
| 1641 | + } | ||
| 1642 | + if !mapping.iter().all(|&m| m == 255 || usize::from(m) < decoded) { | ||
| 1643 | + return Err(format!("an Opus channel mapping outside its {decoded} streams").into()); | ||
| 1644 | + } | ||
| 1645 | + Ok((streams, coupled, mapping)) | ||
| 1646 | +} | ||
| 1647 | + | ||
| 1648 | +/// Opus 5.1 is stored in Vorbis channel order (FL, FC, FR, BL, BR, LFE) and | ||
| 1649 | +/// [`fold_5_1`] reads the film order every other decoder here hands back (FL, FR, | ||
| 1650 | +/// FC, LFE, BL, BR). This is that permutation, in place, and only for the 5.1 | ||
| 1651 | +/// track the fold is *for*: mono and stereo need none, and every other width is | ||
| 1652 | +/// refused by [`Track::channels`] before a packet is ever decoded. | ||
| 1653 | +fn vorbis_to_film_order(samples: &mut [f32], fold: bool) { | ||
| 1654 | + if !fold { | ||
| 1655 | + return; | ||
| 1656 | + } | ||
| 1657 | + for frame in samples.chunks_exact_mut(6) { | ||
| 1658 | + let [fl, fc, fr, bl, br, lfe] = <[f32; 6]>::try_from(&frame[..]).expect("a 5.1 frame"); | ||
| 1659 | + frame.copy_from_slice(&[fl, fr, fc, lfe, bl, br]); | ||
| 1660 | + } | ||
| 1661 | +} | ||
| 1662 | + | ||
| 1536 | /// 5.1 down to stereo, in place. ITU-R BS.775: the centre and the surround of | 1663 | /// 5.1 down to stereo, in place. ITU-R BS.775: the centre and the surround of |
| 1537 | /// each side join that side at -3 dB, and the LFE is dropped -- it carries no | 1664 | /// each side join that side at -3 dB, and the LFE is dropped -- it carries no |
| 1538 | /// programme a stereo pair could put anywhere. Both outputs are divided by the | 1665 | /// programme a stereo pair could put anywhere. Both outputs are divided by the |
crates/engine/src/lib.rsmodified+20 -8
| @@ -41,14 +41,17 @@ pub use project::{Clip, Project, Rate, Speed}; | |||
| 41 | /// dropped file may land on *before* anything is opened, and so does | 41 | /// dropped file may land on *before* anything is opened, and so does |
| 42 | /// [`PlaybackSession::import`](playback::PlaybackSession::import). | 42 | /// [`PlaybackSession::import`](playback::PlaybackSession::import). |
| 43 | /// | 43 | /// |
| 44 | -/// Exactly the containers the engine's audio path reads (`audio::AudioSession`): | 44 | +/// Exactly the containers the engine's audio path reads (`audio::AudioSession`), |
| 45 | -/// no opus, ac3 or dts, for which no pure-Rust decoder exists -- those are | 45 | +/// Opus included: `.opus` is an Ogg file symphonia's probe already reads and |
| 46 | -/// refused by the same door that refuses a `.txt`, which is the honest answer. | 46 | +/// `ruopus` now decodes, and `.mka` is the Matroska whose sound is all it |
| 47 | +/// has. A `.dts` or a bare `.ac3` is refused by the same door that refuses a | ||
| 48 | +/// `.txt` -- there is no reader here that opens an elementary stream -- which is | ||
| 49 | +/// the honest answer. | ||
| 47 | pub fn is_audio(path: &std::path::Path) -> bool { | 50 | pub fn is_audio(path: &std::path::Path) -> bool { |
| 48 | path.extension().and_then(|e| e.to_str()).is_some_and(|e| { | 51 | path.extension().and_then(|e| e.to_str()).is_some_and(|e| { |
| 49 | matches!( | 52 | matches!( |
| 50 | e.to_ascii_lowercase().as_str(), | 53 | e.to_ascii_lowercase().as_str(), |
| 51 | - "mp3" | "wav" | "flac" | "ogg" | "oga" | "m4a" | "aac" | 54 | + "mp3" | "wav" | "flac" | "ogg" | "oga" | "opus" | "mka" | "m4a" | "aac" |
| 52 | ) | 55 | ) |
| 53 | }) | 56 | }) |
| 54 | } | 57 | } |
| @@ -96,18 +99,27 @@ mod tests { | |||
| 96 | #[test] | 99 | #[test] |
| 97 | fn is_audio_admits_the_containers_the_decoder_reads() { | 100 | fn is_audio_admits_the_containers_the_decoder_reads() { |
| 98 | for name in [ | 101 | for name in [ |
| 99 | - "song.mp3", "a.WAV", "b.flac", "c.ogg", "d.oga", "e.m4a", "f.aac", | 102 | + "song.mp3", |
| 103 | + "a.WAV", | ||
| 104 | + "b.flac", | ||
| 105 | + "c.ogg", | ||
| 106 | + "d.oga", | ||
| 107 | + "e.m4a", | ||
| 108 | + "f.aac", | ||
| 109 | + "g.opus", | ||
| 110 | + "h.OPUS", | ||
| 111 | + "i.mka", | ||
| 100 | ] { | 112 | ] { |
| 101 | assert!(super::is_audio(Path::new(name)), "{name}"); | 113 | assert!(super::is_audio(Path::new(name)), "{name}"); |
| 102 | } | 114 | } |
| 103 | - // Video, projects, the formats with no pure-Rust decoder, and a file | 115 | + // Video, projects, the elementary streams no reader here opens, and a |
| 104 | - // with no extension at all: all of them go elsewhere. | 116 | + // file with no extension at all: all of them go elsewhere. |
| 105 | for name in [ | 117 | for name in [ |
| 106 | "clip.mp4", | 118 | "clip.mp4", |
| 107 | "take.MP4", | 119 | "take.MP4", |
| 108 | "cut.edith", | 120 | "cut.edith", |
| 109 | - "x.opus", | ||
| 110 | "y.ac3", | 121 | "y.ac3", |
| 122 | + "z.dts", | ||
| 111 | "notes", | 123 | "notes", |
| 112 | "mp3", | 124 | "mp3", |
| 113 | ] { | 125 | ] { |
crates/engine/tests/audio_decode.rsmodified+84 -0
| @@ -161,6 +161,90 @@ fn an_ac3_track_decodes_and_51_comes_down_to_stereo() { | |||
| 161 | } | 161 | } |
| 162 | } | 162 | } |
| 163 | 163 | ||
| 164 | +/// Opus, which used to be the codec the refusal string was *for*: a standalone | ||
| 165 | +/// `.opus`, the `.webm` sound off the web, and the 5.1 in an `.mka` that a film | ||
| 166 | +/// soundtrack is -- four Opus streams with a channel mapping table, decoded by | ||
| 167 | +/// `ruopus` and folded to stereo by the same fold the AC-3 and AAC paths use. | ||
| 168 | +/// | ||
| 169 | +/// The 5.1 fixture is the channel-order check as well: its tone is in FL and BR | ||
| 170 | +/// and silent in between, so both output channels carry sound only if the | ||
| 171 | +/// decoder's Vorbis order (FL, FC, FR, BL, BR, LFE) was put into the film order | ||
| 172 | +/// the fold reads (FL, FR, FC, LFE, BL, BR). Skipping that permutation folds BR | ||
| 173 | +/// as if it were BL and the right channel comes out silent. | ||
| 174 | +#[test] | ||
| 175 | +fn opus_decodes_from_every_container_and_51_comes_down_in_order() { | ||
| 176 | + for (name, secs, channels) in [("test_tone.opus", 3.0, 2), ("test_vp9.webm", 2.0, 1)] { | ||
| 177 | + let path = asset(name); | ||
| 178 | + let (meta, rx) = AudioSession::open(&path) | ||
| 179 | + .expect("open") | ||
| 180 | + .expect("Opus decodes now"); | ||
| 181 | + assert_eq!((meta.sample_rate, meta.channels), (48000, channels), "{name}"); | ||
| 182 | + let samples: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect(); | ||
| 183 | + let decoded = (samples.len() / channels as usize) as f64 / 48000.0; | ||
| 184 | + assert!( | ||
| 185 | + (secs - decoded).abs() < 0.1, | ||
| 186 | + "{name} is {secs}s, decoded {decoded:.3}s" | ||
| 187 | + ); | ||
| 188 | + let rms = (samples.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::<f64>() | ||
| 189 | + / samples.len() as f64) | ||
| 190 | + .sqrt(); | ||
| 191 | + assert!( | ||
| 192 | + (0.005..0.75).contains(&rms), | ||
| 193 | + "{name}: RMS {rms:.6} is not a sine at a sane level" | ||
| 194 | + ); | ||
| 195 | + assert!( | ||
| 196 | + samples.iter().all(|s| s.abs() <= 1.0), | ||
| 197 | + "{name}: the decode must not leave the device's range" | ||
| 198 | + ); | ||
| 199 | + // ...and the same file as a session, where the picture allows it: the | ||
| 200 | + // webm's is VP9, which is the VA-API plugin's and not this test's. | ||
| 201 | + if !name.ends_with(".webm") { | ||
| 202 | + let session = engine::PlaybackSession::open(&path).expect("open for playback"); | ||
| 203 | + assert_eq!( | ||
| 204 | + session.audio_disabled_reason(), | ||
| 205 | + None, | ||
| 206 | + "{name}: a track that decodes owes no excuse" | ||
| 207 | + ); | ||
| 208 | + } | ||
| 209 | + } | ||
| 210 | + | ||
| 211 | + let path = asset("test_opus_51.mka"); | ||
| 212 | + let (meta, rx) = AudioSession::open(&path) | ||
| 213 | + .expect("open") | ||
| 214 | + .expect("5.1 Opus decodes now"); | ||
| 215 | + assert_eq!((meta.sample_rate, meta.channels), (48000, 2)); | ||
| 216 | + let samples: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect(); | ||
| 217 | + let rms = |channel: usize| { | ||
| 218 | + let side: Vec<f64> = samples[channel..] | ||
| 219 | + .iter() | ||
| 220 | + .step_by(2) | ||
| 221 | + .map(|s| f64::from(*s) * f64::from(*s)) | ||
| 222 | + .collect(); | ||
| 223 | + (side.iter().sum::<f64>() / side.len() as f64).sqrt() | ||
| 224 | + }; | ||
| 225 | + let (left, right) = (rms(0), rms(1)); | ||
| 226 | + assert!(left > 0.02, "the 5.1 fold came out silent on the left: {left}"); | ||
| 227 | + assert!( | ||
| 228 | + right > 0.3 * left, | ||
| 229 | + "BR was folded as if it were BL: left {left:.4}, right {right:.4}" | ||
| 230 | + ); | ||
| 231 | + // ...and it is the *tone* on each side, not noise at the right level. This is | ||
| 232 | + // the assert that bites: a multistream decoder that mis-slices the packet | ||
| 233 | + // (all but the last stream of an Opus 5.1 packet are self-delimited) hands | ||
| 234 | + // back full-scale hash whose RMS passes every level check above -- measured | ||
| 235 | + // -13 dBFS of it on a film, where the film is silent. | ||
| 236 | + let secs = (samples.len() / 2) as f64 / 48000.0; | ||
| 237 | + for (name, channel, hz) in [("left", 0, 440.0), ("right", 1, 880.0)] { | ||
| 238 | + let side: Vec<f32> = samples[channel..].iter().step_by(2).copied().collect(); | ||
| 239 | + let want = 2.0 * hz * secs; | ||
| 240 | + let got = zero_crossings(&side) as f64; | ||
| 241 | + assert!( | ||
| 242 | + (got - want).abs() <= 0.05 * want, | ||
| 243 | + "{name}: {got} zero crossings, want {want} +/-5% -- a decode this far off is noise" | ||
| 244 | + ); | ||
| 245 | + } | ||
| 246 | +} | ||
| 247 | + | ||
| 164 | /// The same two ends of the AC-3 path, in **Matroska**: a stereo AC-3 track and | 248 | /// The same two ends of the AC-3 path, in **Matroska**: a stereo AC-3 track and |
| 165 | /// a 5.1 E-AC-3 one -- the codec a remux carries and the one the "(AAC only)" | 249 | /// a 5.1 E-AC-3 one -- the codec a remux carries and the one the "(AAC only)" |
| 166 | /// refusal used to fire on -- both come out of the blocks, both arrive as the | 250 | /// refusal used to fire on -- both come out of the blocks, both arrive as the |
crates/engine/tests/capability_matrix.rsmodified+32 -6
| @@ -94,6 +94,23 @@ fn every_audio_codec_the_refusal_names_really_decodes() { | |||
| 94 | .unwrap_or_else(|| panic!("{codec} in a Matroska file came back silent")); | 94 | .unwrap_or_else(|| panic!("{codec} in a Matroska file came back silent")); |
| 95 | assert_eq!(probe.sample_rate, 44_100, "{codec}"); | 95 | assert_eq!(probe.sample_rate, 44_100, "{codec}"); |
| 96 | } | 96 | } |
| 97 | + // Opus, every container it arrives in: a `.webm` off the web, the `.mka` a | ||
| 98 | + // 5.1 film soundtrack is remuxed into, and the standalone `.opus`. It was | ||
| 99 | + // the last codec the notice named as absent while both readers here already | ||
| 100 | + // *parsed* it -- `A_OPUS` and `OpusHead` have always mapped to symphonia's | ||
| 101 | + // `CODEC_ID_OPUS`; only the decoder was missing, and it is `ruopus` now. | ||
| 102 | + for (file, what, channels) in [ | ||
| 103 | + ("test_vp9.webm", "opus in a webm", 1), | ||
| 104 | + // 5.1 arrives as the stereo fold, exactly as a 5.1 AC-3 track does. | ||
| 105 | + ("test_opus_51.mka", "5.1 opus in an mka", 2), | ||
| 106 | + ("test_tone.opus", "a standalone opus", 2), | ||
| 107 | + ] { | ||
| 108 | + let probe = AudioSession::probe(asset(file), 0) | ||
| 109 | + .unwrap_or_else(|e| panic!("{what}: {e}")) | ||
| 110 | + .unwrap_or_else(|| panic!("{what} came back silent")); | ||
| 111 | + assert_eq!(probe.sample_rate, 48_000, "{what}"); | ||
| 112 | + assert_eq!(probe.channels, channels, "{what}"); | ||
| 113 | + } | ||
| 97 | for (file, codec) in [("test_av1.mkv", "aac"), ("test_ac3.mkv", "ac-3")] { | 114 | for (file, codec) in [("test_av1.mkv", "aac"), ("test_ac3.mkv", "ac-3")] { |
| 98 | assert!( | 115 | assert!( |
| 99 | AudioSession::probe(asset(file), 0).expect(codec).is_some(), | 116 | AudioSession::probe(asset(file), 0).expect(codec).is_some(), |
| @@ -107,18 +124,27 @@ fn every_audio_codec_the_refusal_names_really_decodes() { | |||
| 107 | ); | 124 | ); |
| 108 | } | 125 | } |
| 109 | 126 | ||
| 110 | - // ...and the gap the refusal is *for*: Opus has no decoder here at any | 127 | + // ...and the gap the refusal is really *for*, which is DTS and no longer |
| 111 | - // version, so the notice names the track and then names what would work. | 128 | + // Opus: no decoder in this tree has it, so the notice names the track and |
| 112 | - let refused = AudioSession::unsupported(asset("test_vp9.webm")) | 129 | + // then names what would have worked -- Opus among them, or the refusal is |
| 130 | + // back to underselling the engine. | ||
| 131 | + let refused = AudioSession::unsupported(asset("test_dts.mkv")) | ||
| 113 | .expect("read the header") | 132 | .expect("read the header") |
| 114 | - .expect("an Opus track is a reason, not silence"); | 133 | + .expect("a DTS track is a reason, not silence"); |
| 115 | - assert!(refused.contains("A_OPUS"), "{refused}"); | 134 | + assert!(refused.contains("A_DTS"), "{refused}"); |
| 116 | - for named in ["FLAC", "MP3", "Vorbis"] { | 135 | + for named in ["FLAC", "MP3", "Opus", "Vorbis"] { |
| 117 | assert!( | 136 | assert!( |
| 118 | refused.contains(named), | 137 | refused.contains(named), |
| 119 | "the refusal hides a codec that decodes ({named}): {refused}" | 138 | "the refusal hides a codec that decodes ({named}): {refused}" |
| 120 | ); | 139 | ); |
| 121 | } | 140 | } |
| 141 | + // The other half of that claim, and the one a stale refusal string cannot | ||
| 142 | + // fake: a file whose track really does decode has nothing to excuse. | ||
| 143 | + assert_eq!( | ||
| 144 | + AudioSession::unsupported(asset("test_vp9.webm")).expect("read the header"), | ||
| 145 | + None, | ||
| 146 | + "an Opus track that decodes is not a refusal" | ||
| 147 | + ); | ||
| 122 | } | 148 | } |
| 123 | 149 | ||
| 124 | /// Which of two video tracks an mp4 opens on may not depend on hash order: it is | 150 | /// Which of two video tracks an mp4 opens on may not depend on hash order: it is |
scripts/gen_fixtures.shmodified+32 -2
| @@ -84,8 +84,8 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ | |||
| 84 | # The same VP9 stream in Matroska, which is where a yt-dlp download and every | 84 | # The same VP9 stream in Matroska, which is where a yt-dlp download and every |
| 85 | # other VP9 file in the wild actually arrives: `V_VP9` used to fall through the | 85 | # other VP9 file in the wild actually arrives: `V_VP9` used to fall through the |
| 86 | # mkv track dispatch and be refused by name while the mp4 twin above decoded. | 86 | # mkv track dispatch and be refused by name while the mp4 twin above decoded. |
| 87 | -# Opus audio because that is what a .webm carries; the sound is a separate | 87 | +# Opus audio because that is what a .webm carries -- the sound decodes here now |
| 88 | -# refusal (no Opus decoder here) and the picture must not depend on it. | 88 | +# (`ruopus`), and this is the webm cell of the Opus row in `capability_matrix`. |
| 89 | ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ | 89 | ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ |
| 90 | -f lavfi -i "sine=frequency=440:duration=2" \ | 90 | -f lavfi -i "sine=frequency=440:duration=2" \ |
| 91 | -c:v libvpx-vp9 -b:v 2M -g 30 -pix_fmt yuv420p \ | 91 | -c:v libvpx-vp9 -b:v 2M -g 30 -pix_fmt yuv420p \ |
| @@ -108,6 +108,14 @@ ffmpeg -y -f lavfi -i testsrc2=size=320x240:rate=30:duration=2 \ | |||
| 108 | -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ | 108 | -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ |
| 109 | -c:a:0 flac -c:a:1 libmp3lame -c:a:2 libvorbis -c:a:3 alac -c:a:4 pcm_s16le \ | 109 | -c:a:0 flac -c:a:1 libmp3lame -c:a:2 libvorbis -c:a:3 alac -c:a:4 pcm_s16le \ |
| 110 | assets/test_mkv_audio.mkv | 110 | assets/test_mkv_audio.mkv |
| 111 | +# ...and the codec that really is refused, so the other half of the refusal is | ||
| 112 | +# testable too: DTS, which no decoder in this tree has (symphonia has none at any | ||
| 113 | +# version and there is no pure-Rust one to reach for, unlike AC-3 and Opus). The | ||
| 114 | +# notice must name *this* track and go on naming what would have worked. | ||
| 115 | +ffmpeg -y -f lavfi -i testsrc2=size=320x240:rate=30:duration=2 \ | ||
| 116 | + -f lavfi -i "sine=frequency=440:duration=2:sample_rate=48000" \ | ||
| 117 | + -map 0:v -map 1:a -c:v libx264 -profile:v baseline -pix_fmt yuv420p \ | ||
| 118 | + -c:a dca -strict -2 -ac 2 assets/test_dts.mkv | ||
| 111 | # Two video tracks in one mp4, at different sizes so a test can tell which one | 119 | # Two video tracks in one mp4, at different sizes so a test can tell which one |
| 112 | # the demuxer picked. `Mp4Reader::tracks()` is a HashMap and iterating it made | 120 | # the demuxer picked. `Mp4Reader::tracks()` is a HashMap and iterating it made |
| 113 | # "the video track" a different one from one run to the next; the pick comes out | 121 | # "the video track" a different one from one run to the next; the pick comes out |
| @@ -418,6 +426,28 @@ for fmt in mp3 wav flac ogg m4a aac; do | |||
| 418 | -filter_complex "$tone" -map "[a]" -ar 44100 "${codec[@]}" \ | 426 | -filter_complex "$tone" -map "[a]" -ar 44100 "${codec[@]}" \ |
| 419 | "assets/test_tone.$fmt" | 427 | "assets/test_tone.$fmt" |
| 420 | done | 428 | done |
| 429 | +# The two Opus fixtures, which cannot join the loop above: Opus decodes at 48 kHz | ||
| 430 | +# and nothing else, so these are the 48k twins of the tone rather than 44.1k ones. | ||
| 431 | +# First the standalone `.opus`, an Ogg file `crate::is_audio` now admits. | ||
| 432 | +ffmpeg -y -f lavfi -i "sine=frequency=440:duration=3:sample_rate=48000" \ | ||
| 433 | + -f lavfi -i "sine=frequency=880:duration=3:sample_rate=48000" \ | ||
| 434 | + -filter_complex "$tone" -map "[a]" -c:a libopus -b:a 96k \ | ||
| 435 | + assets/test_tone.opus | ||
| 436 | +# ...and 5.1 Opus in an `.mka`, which is the shape a film soundtrack has: four | ||
| 437 | +# Opus streams with the Vorbis channel mapping, folded to stereo on the way to | ||
| 438 | +# the timeline. The tone sits in **FL and BR only**, both silent in between, so | ||
| 439 | +# the fold's channel order is checkable without an FFT: done right, 440 Hz comes | ||
| 440 | +# out left and 880 Hz right; read in the decoder's own Vorbis order (FL, FC, FR, | ||
| 441 | +# BL, BR, LFE) instead of the film order the fold wants (FL, FR, FC, LFE, BL, BR), | ||
| 442 | +# BR lands on the left with FL and the right channel comes out silent. | ||
| 443 | +# `join` needs every output channel mapped and assigns them by *name*, not by | ||
| 444 | +# input order: without the explicit `map=` the two tones land in FC and BR | ||
| 445 | +# instead, and the fixture stops testing what its comment says. | ||
| 446 | +ffmpeg -y -f lavfi -i "sine=frequency=440:duration=3:sample_rate=48000" \ | ||
| 447 | + -f lavfi -i "sine=frequency=880:duration=3:sample_rate=48000" \ | ||
| 448 | + -f lavfi -i "anullsrc=r=48000:cl=quad:d=3" \ | ||
| 449 | + -filter_complex "[0:a][1:a][2:a]join=inputs=3:channel_layout=5.1:map=0.0-FL|2.0-FR|2.1-FC|2.2-LFE|2.3-BL|1.0-BR[a]" \ | ||
| 450 | + -map "[a]" -c:a libopus -b:a 256k assets/test_opus_51.mka | ||
| 421 | # Still-image fixture: the source with a picture and no timeline in it. Two | 451 | # Still-image fixture: the source with a picture and no timeline in it. Two |
| 422 | # bands rather than one colour, so a test can tell top from bottom (a flipped | 452 | # bands rather than one colour, so a test can tell top from bottom (a flipped |
| 423 | # decode) and red from blue (a swapped channel order); 640x360, which is 16:9 | 453 | # decode) and red from blue (a swapped channel order); 640x360, which is 16:9 |