From c94ba8b5f63129a6248d421e4d171f96893aaafc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 12 Aug 2026 21:56:12 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(audio):=20convert=20wide=20lay?= =?UTF-8?q?outs=20and=20off-rate=20sources=20at=20import=20instead=20of=20?= =?UTF-8?q?refusing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An 8-channel Opus track came back "IMPORT FAILED: unsupported channel layout: 8 channels (max stereo)" and took the picture with it, and a 48 kHz file "audio 48000 Hz 2 ch does not match the timeline's 44100 Hz 2 ch". Both strings are gone: an import converts. Width: `fold_5_1` becomes `downmix`, a coefficient table per layout from 2.1 to 7.1 (ITU-R BS.775 — front channels keep their side, centre and surrounds join at -3 dB, LFE dropped, both sides normalised by their own coefficient sum so a full-scale source cannot clip). 5.1 comes out of the table bit-identical to what it was. `vorbis_to_film_order` gains the RFC 7845 permutations for 3, 5, 7 and 8 channels beside the 6 it had, so surround Opus at any width reaches the fold in the order the fold reads. The AC-3 decoder's own 2.1 passthrough, which it leaves at 3, folds here too, and a multichannel AAC track in an *mp4* now takes the `rusty_aac` route the Matroska side already had (`aac_decoder`, one call for both). Rate: the segment resampler a speeded clip already goes through takes the source rate over the timeline's into its step, so the two compose into one interpolation and 48 kHz onto a 44.1 kHz timeline keeps its pitch. All of it is convert-on-read — per packet in the decoder, per buffer in `emit`, after the window trim — so there is no upfront pass to show progress for and nothing to cancel. What is still refused is the layout alone: a mono track cannot join a stereo timeline, in the words "audio 1 ch does not match the timeline's 2 ch". The picker's grey-out rule follows the gate rather than leading it. Measured on a 12.9 GB 2160p AV1 remux with a real-library 7.1 Opus track: imports, opens as a timeline, and a ten-second WAV export comes back at RMS 0.0091 left / 0.0085 right. --- crates/app/src/main.rs | 27 +- crates/engine/src/audio.rs | 558 +++++++++++++++-------- crates/engine/src/export.rs | 3 +- crates/engine/src/playback.rs | 29 +- crates/engine/tests/audio_decode.rs | 200 +++++++- crates/engine/tests/audio_files.rs | 69 ++- crates/engine/tests/audio_multi.rs | 11 +- crates/engine/tests/capability_matrix.rs | 3 + crates/engine/tests/playback.rs | 19 +- crates/engine/tests/saveload.rs | 19 +- scripts/gen_fixtures.sh | 14 + 11 files changed, 711 insertions(+), 241 deletions(-) diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 3f44eef..e8ef959 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -11826,11 +11826,14 @@ fn unusable(info: &StreamInfo, timeline_audio: Option<(u32, u16)>) -> Option format!("{codec} is not supported"), }); } - let (rate, channels) = timeline_audio?; - ((info.sample_rate, info.channels) != (rate, channels)).then(|| { + // The **layout** and not the rate, which is what the engine's own gate now + // asks (`PlaybackSession::import`): a stream written at another sample rate + // is resampled onto the timeline's at the decoder's door, so greying its row + // would be this picker refusing what the timeline accepts. + let (_, channels) = timeline_audio?; + (info.channels != channels).then(|| { format!( - "the timeline is {} kHz {}", - f64::from(rate) / 1000., + "the timeline is {}", layout(channels).unwrap_or_else(|| "silent".to_string()) ) }) @@ -14226,7 +14229,7 @@ mod tests { Landing, arrival, launch_queue, read_ahead, scan_plan, seek_line, silence_line, stash_or_write, repeats, resolution_choices, resolution_ladder, span_label, tone_choices, tone_label, - clip_width, trimmed_clip, trims, unscannable, + clip_width, trimmed_clip, trims, unscannable, unusable, visible_slice, }; use super::{ @@ -14447,13 +14450,17 @@ mod tests { assert_eq!(rows[1].name, "movie.mp4 [audio 2]"); assert_eq!(rows[1].detail, "fra 44.1 kHz stereo"); // Placeable: the one already on the timeline, and the one that matches - // it. The 22 kHz mono track cannot join a 44.1 kHz stereo timeline -- - // one device and one copied AAC track for the whole of it -- and the - // codec we cannot read cannot join anything. Both say which. + // it. The mono track cannot join a stereo timeline -- one device and one + // copied AAC track for the whole of it -- and the codec we cannot read + // cannot join anything. Both say which. Its 22 kHz is *not* part of that + // any more: a rate of its own is resampled at the decoder's door, and a + // row greyed for one the engine accepts is this picker telling a lie. assert_eq!((&rows[0].unusable, &rows[1].unusable), (&None, &None)); + assert_eq!(rows[2].unusable.as_deref(), Some("the timeline is stereo")); assert_eq!( - rows[2].unusable.as_deref(), - Some("the timeline is 44.1 kHz stereo") + unusable(&info(9, 48_000, 2, None, true), Some((44_100, 2))), + None, + "48 kHz stereo joins a 44.1 kHz stereo timeline" ); assert_eq!(rows[3].unusable.as_deref(), Some("unsupported codec")); assert_eq!( diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index f94ecb3..e146751 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -133,12 +133,14 @@ pub struct AacPacket { } /// Everything an import check needs from a candidate file's audio track. Two -/// files may share a timeline only when their probes are equal (or both `None`). +/// files may share a timeline when their layouts agree (or both are `None`). /// -/// Rate and layout only: those are what one output device and one exported track -/// can carry, and an mp3 that agrees on both may join a timeline of mp4s even -/// though nothing about it can be *copied* into an export -- that is a separate -/// refusal, at export time, in [`AudioSession::copy_multi_segments`]. +/// Rate and layout, of which only the **layout** is held to the timeline's: one +/// output device and one exported track carry one width, while a rate of its own +/// is resampled at the decoder's door ([`Resample`]). An mp3 that agrees on the +/// layout may join a timeline of mp4s even though nothing about it can be +/// *copied* into an export -- that is a separate refusal, at export time, in +/// [`AudioSession::copy_multi_segments`]. #[derive(Debug, Clone, Copy, PartialEq)] pub struct AudioProbe { pub sample_rate: u32, @@ -167,9 +169,9 @@ pub struct StreamInfo { pub sample_rate: u32, /// ISO-639-2 from the mdhd, `None` for the `und` most muxers write. pub lang: Option, - /// Whether opening this stream would decode: AAC-LC, mono or stereo. The - /// grey-out rule, mirroring the refusals `Track::open` and `Track::channels` - /// make one file at a time. + /// Whether opening this stream would decode -- a codec question only now + /// that no width is refused. The grey-out rule, mirroring what `Track::open` + /// answers one file at a time. pub decodable: bool, } @@ -291,8 +293,9 @@ impl AudioSession { /// /// Only the sources some segment names are opened. `Ok(None)` when `sources` /// is empty or its first entry has no AAC track; a later source that - /// disagrees on rate/layout is an `Err` — import refuses those up front (one - /// timeline, one output device), this is the backstop. + /// disagrees on *layout* is an `Err` — import refuses those up front (one + /// timeline, one output device), this is the backstop. A source at another + /// sample rate is not one of those: it is resampled, per segment. pub fn open_multi_segments( sources: &[PathBuf], segs: &[(Option, f64, f64)], @@ -372,7 +375,7 @@ impl AudioSession { // match it, and the checks below hold them to that. let meta = AudioMeta { sample_rate: first.sample_rate(), - channels: first.channels()?, + channels: first.channels(), total_samples: first.total_samples(), }; // Built here only so an undecodable stream is an `Err` from the opener @@ -407,12 +410,16 @@ impl AudioSession { silent[source] = true; continue; }; - if (track.sample_rate(), track.channels()?) != (meta.sample_rate, meta.channels) { + // The *rate* is no longer held to the timeline's: a source written at + // another one is read through its segment's [`Resample`] below, the + // very interpolator a speeded clip already goes through, so it plays + // at the pitch it was recorded at over the seconds it was placed for. + // The layout still is -- one output device carries one width, and + // everything wider than a pair is already folded to one. + if track.channels() != meta.channels { return Err(format!( - "source {source} is {} Hz {} ch, the timeline is {} Hz {} ch", - track.sample_rate(), - track.channels()?, - meta.sample_rate, + "source {source} is {} ch, the timeline is {} ch", + track.channels(), meta.channels ) .into()); @@ -437,9 +444,15 @@ impl AudioSession { // Chunk numbering is continuous across every join, counted from the first // segment's audible start in its own source (see `open_segments`). let timeline = segments.first().map_or(0, |s| match s.source { - Some(source) => s - .media_target - .saturating_sub(tracks[source].as_ref().expect("opened above").priming()), + Some(source) => { + let track = tracks[source].as_ref().expect("opened above"); + // ...in *timeline* frames, which is not the source's own count + // when it was written at another rate. Integer, so the equal-rate + // case -- every project before this -- is the number it always was. + let at = s.media_target.saturating_sub(track.priming()); + at.saturating_mul(u64::from(meta.sample_rate)) + / u64::from(track.sample_rate().max(1)) + } None => 0, }); @@ -460,20 +473,41 @@ impl AudioSession { }) .collect(); - // One resampler per speeded segment, built where the sample rate is - // known: what the timeline owes it is seconds there and frames here. + // One resampler per segment that needs one, built where the sample rate + // is known: what the timeline owes it is seconds there and frames here. + // + // Two things ask for one and they compose into a single step: the clip's + // own speed, and a source written at a rate other than the timeline's -- + // the ratio of the two rates is exactly a speed, and reading the samples + // at it is what keeps a 48 kHz file's pitch on a 44.1 kHz timeline. A + // segment with neither has no resampler at all and reaches the mixer + // with the decoder's own samples, byte for byte, as it always did. let speeds: Vec> = segments .iter() + .zip(segs) .enumerate() - .map(|(i, _)| { - speeds.get(i).and_then(Option::as_ref).map(|s| { - Resample::new( - s.step, - (s.timeline_secs * f64::from(meta.sample_rate)) - .round() - .max(0.) as u64, - ) - }) + .map(|(i, (seg, &(_, start_secs, end_secs)))| { + let rate = seg + .source + .and_then(|source| tracks[source].as_ref()) + .map_or(meta.sample_rate, Track::sample_rate); + let ratio = f64::from(rate) / f64::from(meta.sample_rate.max(1)); + let stretch = speeds.get(i).and_then(Option::as_ref); + if stretch.is_none() && rate == meta.sample_rate { + return None; + } + // A speeded clip states the timeline it owes; a plain one owes + // the window it was placed for, and an open-ended window owes + // whatever its source has ([`Resample::UNBOUNDED`]). + let secs = stretch.map_or(end_secs - start_secs, |s| s.timeline_secs); + let owed = match (secs * f64::from(meta.sample_rate)).round() { + frames if frames.is_finite() && frames >= 0.0 => { + (frames as u64).min(Resample::UNBOUNDED - 1) + } + frames if frames > 0.0 => Resample::UNBOUNDED, + _ => 0, + }; + Some(Resample::new(stretch.map_or(1.0, |s| s.step) * ratio, owed)) }) .collect(); @@ -741,7 +775,7 @@ impl AudioSession { }; Ok(Some(AudioProbe { sample_rate: track.sample_rate(), - channels: track.channels()?, + channels: track.channels(), })) } @@ -807,8 +841,11 @@ impl AudioSession { ), lang: (entry.language != "und" && !entry.language.is_empty()) .then(|| entry.language.clone()), - decodable: matches!(channels, 1 | 2) - && (ac3.is_some() || sym.is_some_and(|t| t.decoder().is_ok())), + // No width gate any more: `channels` is what reaches the + // timeline, which [`downmix`] makes a pair out of whatever + // the file carries. What greys a row out is a codec nothing + // here decodes, and nothing else. + decodable: ac3.is_some() || sym.is_some_and(|t| t.decoder().is_ok()), }); } return Ok(streams); @@ -823,7 +860,7 @@ impl AudioSession { // Neither the mp3 nor the wav headers carry an ISO-639 tag the // way an mdhd does, and a lone track needs no telling apart. lang: None, - decodable: matches!(track.channels, 1 | 2) && track.decoder().is_ok(), + decodable: track.decoder().is_ok(), }]); } let file = File::open(path)?; @@ -862,13 +899,17 @@ impl AudioSession { |t| t.sample_rate, ), lang: (!lang.is_empty() && lang != "und").then(|| lang.to_string()), - decodable: ac3.as_ref().is_some_and(|t| matches!(t.channels, 1 | 2)) + // The profile still gates -- the writer rebuilds an + // AudioSpecificConfig and calls it LC -- but the layout no + // longer does: a 5.1 or 7.1 AAC track decodes through + // `rusty_aac` and folds to the pair the timeline carries + // ([`aac_decoder`]). + decodable: ac3.is_some() || aac - && matches!(track.audio_profile(), Ok(AudioObjectType::AacLowComplexity)) - && matches!( - track.channel_config(), - Ok(ChannelConfig::Mono | ChannelConfig::Stereo) - ), + && matches!( + track.audio_profile(), + Ok(AudioObjectType::AacLowComplexity) + ), } }) .collect()) @@ -1266,26 +1307,20 @@ impl Track { } } - /// Mono or stereo; anything wider is refused here rather than one packet at - /// a time, because one output device and one copied track is all there is. - fn channels(&self) -> crate::Result { + /// What this track hands the timeline: mono, or stereo for everything else. + /// Nothing is refused for its width any more -- a layout wider than a pair + /// is folded to one at the decoder's door ([`downmix`]), because one output + /// device is all there is, not because the file is unreadable. + fn channels(&self) -> u16 { match self { Self::Aac(t) => t.channels(), - // Already downmixed: `channels` is what comes *out* of the decoder, - // which is 2 for everything from mono to 5.1 (see [`Ac3Track`]). - Self::Ac3(t) => match t.channels { - 1 | 2 => Ok(t.channels), - n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()), - }, + // Already downmixed by the AC-3 decoder itself; `channels` is what + // comes *out* of it, and the 2.1 passthrough it leaves at 3 (see + // [`Ac3Track`]) is folded by [`decode_ac3`] like any other width. + Self::Ac3(t) => t.channels.min(2), // Downmixed by the very same decoder, out of a Matroska file. - Self::Mkv(t) => match t.channels { - 1 | 2 => Ok(t.channels), - n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()), - }, - Self::Sym(t) => match t.channels { - 1 | 2 => Ok(t.channels), - n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()), - }, + Self::Mkv(t) => t.channels.min(2), + Self::Sym(t) => t.channels, } } @@ -1336,7 +1371,7 @@ impl Track { fn check_decoder(&self) -> crate::Result<()> { match self { Self::Aac(t) => { - AacDecoder::try_new(&t.params, &AudioDecoderOptions::default())?; + aac_decoder(&t.params, t.source_channels())?; } Self::Ac3(t) => { ac3_decoder("ac3", t.requested)?; @@ -1363,9 +1398,9 @@ struct SymTrack { path: PathBuf, track_id: u32, sample_rate: u32, - /// What reaches the timeline: the file's own layout, or 2 for a 5.1 track, - /// which is folded down by [`SymDecoder`] exactly as the AC-3 reader's - /// decoder folds its own. + /// What reaches the timeline: the file's own layout, or 2 for anything + /// wider, which is folded down by [`SymDecoder`] exactly as the AC-3 + /// reader's decoder folds its own. channels: u16, /// What the decoder emits, which is what the fold reads. source_channels: u16, @@ -1463,10 +1498,10 @@ impl SymTrack { path: path.to_path_buf(), track_id, sample_rate, - // 5.1 arrives as a stereo source, whatever it was stored as; every - // other layout is passed through and refused above stereo by - // [`Track::channels`], where it always was. - channels: if channels == 6 { 2 } else { channels }, + // Anything wider than a pair arrives as a stereo source, whatever it + // was stored as: 5.1, 7.1 and everything between are folded by + // [`downmix`] at the decoder's door ([`SymDecoder`]). + channels: channels.min(2), source_channels: channels, total_samples: num_frames.map(|n| n.saturating_sub(priming)), priming, @@ -1488,34 +1523,27 @@ impl SymTrack { /// /// Which decoder is not the caller's business, and it is not always /// symphonia's: its AAC decoder refuses anything wider than stereo outright - /// (`aac/mod.rs:93`, "aac: aac too complex"), which is exactly the 5.1 track - /// of a film in an mkv, so that one goes to `rusty_aac` instead, and it has - /// no Opus decoder at all, so that one goes to `ruopus`. + /// (`aac/mod.rs:93`, "aac: aac too complex"), which is exactly the 5.1 and + /// 7.1 tracks of a film, so those go to `rusty_aac` instead + /// ([`aac_decoder`]), and it has no Opus decoder at all, so that one goes to + /// `ruopus`. fn decoder(&self) -> crate::Result { - let fold = self.source_channels != self.channels; + let from = usize::from(self.source_channels); if self.params.codec == CODEC_ID_OPUS { - let channels = usize::from(self.source_channels); let (streams, coupled, mapping) = - opus_layout(self.params.extra_data.as_deref().unwrap_or_default(), channels)?; + opus_layout(self.params.extra_data.as_deref().unwrap_or_default(), from)?; // 48 kHz whatever the container says: that is the only rate Opus // decodes at, and the rate both readers declare for it. let decoder = ruopus::MultistreamDecoder::with_rate(48_000, streams, coupled, &mapping); - return Ok(SymDecoder::Opus(Box::new(decoder), fold)); - } - if self.params.codec == CODEC_ID_AAC && self.source_channels > 2 { - let asc = self - .params - .extra_data - .as_deref() - .ok_or("a multichannel AAC track with no AudioSpecificConfig")?; - let decoder = rusty_aac::AacDecoder::with_config_bytes(asc) - .map_err(|e| format!("multichannel AAC decoder init failed: {e}"))?; - return Ok(SymDecoder::Aac(Box::new(decoder), fold)); + return Ok(SymDecoder::Opus(Box::new(decoder), from)); + } + if self.params.codec == CODEC_ID_AAC { + return aac_decoder(&self.params, from); } Ok(SymDecoder::Sym( symphonia::default::get_codecs() .make_audio_decoder(&self.params, &AudioDecoderOptions::default())?, - fold, + from, )) } @@ -1626,48 +1654,70 @@ fn sym_reader(path: &Path) -> crate::Result> { } /// One packet in, interleaved f32 out — whichever library did the decoding, and -/// already folded to the layout [`SymTrack::channels`] promised. The flag is -/// that fold: `true` for a 5.1 track, and there is nothing else it can be. +/// already folded to the layout [`SymTrack::channels`] promised. The number +/// beside each is the width the decoder itself emits, which is what +/// [`downmix`] folds from; 1 and 2 fold to nothing. enum SymDecoder { - Sym(Box, bool), + Sym(Box, usize), /// Boxed because the decoder carries its own IMDCT tables and this enum is /// moved into the worker. - Aac(Box, bool), - /// Every Opus track, mono to 5.1: one multistream decoder -- the streams of + Aac(Box, usize), + /// Every Opus track, mono to 7.1: one multistream decoder -- the streams of /// a packet, the channel mapping table and the routing between them are all - /// its business -- and the same fold flag. - Opus(Box, bool), + /// its business -- and the same width. + Opus(Box, usize), } impl SymDecoder { fn decode(&mut self, packet: &Packet, out: &mut Vec) -> crate::Result<()> { match self { - Self::Sym(decoder, fold) => { + Self::Sym(decoder, from) => { decoder.decode(packet)?.copy_to_vec_interleaved::(out); - fold_5_1(out, *fold); + downmix(out, *from); } - Self::Aac(decoder, fold) => { + Self::Aac(decoder, from) => { let pcm = decoder .decode(&packet.data, None) .map_err(|e| format!("AAC decode failed: {e}"))?; *out = pcm.samples; - fold_5_1(out, *fold); + downmix(out, *from); } - Self::Opus(decoder, fold) => { + Self::Opus(decoder, from) => { *out = decoder .decode_packet(&packet.data) .map_err(|e| format!("Opus decode failed: {e}"))?; // The encoder delay is not dropped here: it is this track's // priming ([`SymTrack::open_inner`]), which the window rules // subtract once for the whole segment rather than per packet. - vorbis_to_film_order(out, *fold); - fold_5_1(out, *fold); + vorbis_to_film_order(out, *from); + downmix(out, *from); } } Ok(()) } } +/// The decoder an AAC track of `from` channels needs: symphonia's own 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, so those go to +/// `rusty_aac` instead -- the same routing [`SymTrack::decoder`] does for a +/// Matroska file, asked once here so an mp4's multichannel track takes it too. +fn aac_decoder(params: &AudioCodecParameters, from: usize) -> crate::Result { + if from > 2 { + let asc = params + .extra_data + .as_deref() + .ok_or("a multichannel AAC track with no AudioSpecificConfig")?; + let decoder = rusty_aac::AacDecoder::with_config_bytes(asc) + .map_err(|e| format!("multichannel AAC decoder init failed: {e}"))?; + return Ok(SymDecoder::Aac(Box::new(decoder), from)); + } + Ok(SymDecoder::Sym( + Box::new(AacDecoder::try_new(params, &AudioDecoderOptions::default())?), + from, + )) +} + /// The encoder delay of an Opus track, in samples at 48 kHz: bytes 10 and 11 of /// `OpusHead`, little-endian. Zero for a track whose header is missing or too /// short to hold one -- there is nothing to subtract that we can trust. @@ -1730,49 +1780,98 @@ fn opus_layout(head: &[u8], channels: usize) -> crate::Result<(usize, usize, Vec Ok((streams, coupled, mapping)) } -/// Opus 5.1 is stored in Vorbis channel order (FL, FC, FR, BL, BR, LFE) and -/// [`fold_5_1`] reads the film order every other decoder here hands back (FL, FR, -/// FC, LFE, BL, BR). This is that permutation, in place, and only for the 5.1 -/// track the fold is *for*: mono and stereo need none, and every other width is -/// refused by [`Track::channels`] before a packet is ever decoded. -fn vorbis_to_film_order(samples: &mut [f32], fold: bool) { - if !fold { - return; +/// Surround Opus is stored in Vorbis channel order (RFC 7845 §5.1.1.2) and +/// [`downmix`] reads the film order every other decoder here hands back. This is +/// that permutation, in place, per width: each entry says which *source* channel +/// the output slot of that index reads. Mono, stereo and quad agree already, and +/// a width the RFC does not lay out is left alone rather than shuffled by guess. +fn vorbis_to_film_order(samples: &mut [f32], from: usize) { + let order: &[usize] = match from { + 3 => &[0, 2, 1], // FL FC FR + 5 => &[0, 2, 1, 3, 4], // FL FC FR SL SR + 6 => &[0, 2, 1, 5, 3, 4], // FL FC FR SL SR LFE + 7 => &[0, 2, 1, 6, 5, 3, 4], // FL FC FR SL SR BC LFE + 8 => &[0, 2, 1, 7, 5, 6, 3, 4], // FL FC FR SL SR BL BR LFE + _ => return, + }; + let mut frame = [0.0f32; 8]; + for chunk in samples.chunks_exact_mut(from) { + frame[..from].copy_from_slice(chunk); + for (out, &src) in chunk.iter_mut().zip(order) { + *out = frame[src]; + } } - for frame in samples.chunks_exact_mut(6) { - let [fl, fc, fr, bl, br, lfe] = <[f32; 6]>::try_from(&frame[..]).expect("a 5.1 frame"); - frame.copy_from_slice(&[fl, fr, fc, lfe, bl, br]); +} + +/// What each channel of a `from`-wide film-order layout contributes to the left +/// and the right of a stereo fold. ITU-R BS.775: a front channel keeps its own +/// side, the centre and the back centre go to both at -3 dB, a surround joins +/// its own side at -3 dB, and the LFE is dropped -- it carries no programme a +/// stereo pair could put anywhere, and neither ffmpeg's default downmix nor any +/// player's puts it there. +/// +/// The film order is FL, FR, FC, LFE, BL, BR, SL, SR, which is what symphonia's +/// decoders and `rusty_aac` both hand back (the latter reorders AAC's own +/// C, L, R, Ls, Rs, LFE element order into it: `decode.rs:779`) and what the AC-3 +/// decoder's own passthrough uses. +/// +/// ponytail: a width past 7.1 (22.2, ambisonics) keeps its front pair and drops +/// the rest -- no table here places those, and inventing one silently would be +/// worse than a fold that is merely narrow. Upgrade path is one more arm. +fn fold_coeffs(from: usize) -> Vec<(f32, f32)> { + const C: f32 = std::f32::consts::FRAC_1_SQRT_2; + const L: (f32, f32) = (1.0, 0.0); + const R: (f32, f32) = (0.0, 1.0); + const M: (f32, f32) = (C, C); + const SL: (f32, f32) = (C, 0.0); + const SR: (f32, f32) = (0.0, C); + const X: (f32, f32) = (0.0, 0.0); + match from { + 3 => vec![L, R, X], // L R LFE (the 2.1 passthrough) + 4 => vec![L, R, SL, SR], // FL FR BL BR + 5 => vec![L, R, M, SL, SR], // FL FR FC BL BR + 6 => vec![L, R, M, X, SL, SR], // 5.1 + 7 => vec![L, R, M, X, M, SL, SR], // FL FR FC LFE BC SL SR + 8 => vec![L, R, M, X, SL, SR, SL, SR], // 7.1 + n => (0..n).map(|c| [L, R][usize::from(c > 0)]).collect(), } } -/// 5.1 down to stereo, in place. ITU-R BS.775: the centre and the surround of -/// each side join that side at -3 dB, and the LFE is dropped -- it carries no -/// programme a stereo pair could put anywhere. Both outputs are divided by the -/// sum of their own coefficients, so a source at full scale cannot come out -/// clipped; that is what every player does by default. +/// Anything wider than a stereo pair down to one, in place -- `from` is the +/// channel count the decoder actually emitted, and 1 or 2 is not touched at all. +/// This is what makes a 5.1 or 7.1 film an ordinary stereo source on the +/// timeline instead of an import refusal. /// -/// The layout is FL, FR, FC, LFE, BL, BR, which is what symphonia's decoders -/// and `rusty_aac` both hand back (the latter reorders AAC's own C, L, R, Ls, -/// Rs, LFE element order into it: `decode.rs:779`). +/// Both outputs are divided by the sum of their own coefficients +/// ([`fold_coeffs`]), so a source at full scale cannot come out clipped. /// -/// ponytail: that normalisation costs 7.7 dB against what ffmpeg's `-ac 2` hands -/// out, which does not normalise and can overload -- so a film plays quieter -/// here than in a player beside it. It is the loudness the AC-3 5.1 path already -/// has (measured within 1.3 dB), so the two agree; the upgrade path is a -/// limiter on the output, at which point the coefficients can go back to 1.0. -fn fold_5_1(samples: &mut Vec, fold: bool) { - if !fold { +/// ponytail: that normalisation costs 7.7 dB at 5.1 (9.9 at 7.1) against what +/// ffmpeg's `-ac 2` hands out, which does not normalise and can overload -- so a +/// film plays quieter here than in a player beside it. It is the loudness the +/// AC-3 5.1 path already has (measured within 1.3 dB), so the two agree; the +/// upgrade path is a limiter on the output, at which point the coefficients can +/// go back to 1.0. +fn downmix(samples: &mut Vec, from: usize) { + if from < 3 { return; } - const CENTRE: f32 = std::f32::consts::FRAC_1_SQRT_2; - const NORM: f32 = 1.0 / (1.0 + 2.0 * CENTRE); - for frame in 0..samples.len() / 6 { - let [fl, fr, fc, _lfe, bl, br] = <[f32; 6]>::try_from(&samples[frame * 6..frame * 6 + 6]) - .expect("six samples of a 5.1 frame"); - samples[2 * frame] = (fl + CENTRE * (fc + bl)) * NORM; - samples[2 * frame + 1] = (fr + CENTRE * (fc + br)) * NORM; - } - samples.truncate(samples.len() / 6 * 2); + let coeffs = fold_coeffs(from); + let (left, right) = coeffs + .iter() + .fold((0.0f32, 0.0f32), |(l, r), c| (l + c.0, r + c.1)); + // Never a boost: a layout with nothing on one side stays where it is. + let (left, right) = (1.0 / left.max(1.0), 1.0 / right.max(1.0)); + for frame in 0..samples.len() / from { + let (mut l, mut r) = (0.0, 0.0); + for (c, &(cl, cr)) in coeffs.iter().enumerate() { + let sample = samples[frame * from + c]; + l += cl * sample; + r += cr * sample; + } + samples[2 * frame] = l * left; + samples[2 * frame + 1] = r * right; + } + samples.truncate(samples.len() / from * 2); } /// One source's AC-3 track: the same mp4 sample tables the AAC track is read @@ -2142,16 +2241,20 @@ impl AacTrack { Ok(Some(this)) } - /// Channel count. `AacDecoder` only does mono and stereo, so anything else - /// is refused here rather than one packet at a time. - fn channels(&self) -> crate::Result { + /// What reaches the timeline: mono, or the stereo everything wider is folded + /// to by [`downmix`] at the decoder's door. + fn channels(&self) -> u16 { match self.config { - ChannelConfig::Mono => Ok(1), - ChannelConfig::Stereo => Ok(2), - other => Err(format!("unsupported channel layout: {other:?} (max stereo)").into()), + ChannelConfig::Mono => 1, + _ => 2, } } + /// What the decoder emits, which is what the fold reads. + fn source_channels(&self) -> usize { + usize::from(channel_count(self.config).max(1)) + } + fn track_params(&self) -> AacTrackParams { AacTrackParams { freq_index: self.freq_index, @@ -2475,6 +2578,15 @@ impl Segment { /// starts one clean and drops it at the end, which is what makes a seek a reset /// for free -- exactly as the equalizer's state does. /// +/// It is also what makes a file written at another sample rate playable at all: +/// the step is the clip's speed *times* the source rate over the timeline's, so +/// 48 kHz read onto a 44.1 kHz timeline is one resampler, not two, and the pitch +/// is preserved because the frames are read at the ratio of the rates rather +/// than dropped. Linear interpolation is what a speed change already uses here +/// -- for a 48:44.1 ratio its worst-case image lands ~40 dB down and the +/// alternative is a windowed-sinc kernel and a new state machine for a +/// conversion that is not the audible risk in this path. +/// /// `owed` is what the timeline gives the segment, in frames per channel: /// resampling resolves to whole samples and a clip's own window resolves to /// whole *source* frames, so the two miss each other by a sample or two per @@ -2489,11 +2601,18 @@ struct Resample { pos: f64, /// The last frame of the buffer before this one, one sample per channel. tail: Vec, - /// Output frames per channel still to be emitted for this segment. + /// Output frames per channel still to be emitted for this segment, or + /// [`Resample::UNBOUNDED`] for a window with no end of its own -- what + /// [`AudioSession::open_at`] asks for, where the source running out is the + /// end and there is no shortfall to pad. owed: u64, } impl Resample { + /// "As many as the source has": a segment ending at `f64::INFINITY` owes the + /// timeline nothing it did not decode. + const UNBOUNDED: u64 = u64::MAX; + fn new(step: f64, owed: u64) -> Self { Self { step, @@ -2536,7 +2655,9 @@ impl Resample { self.tail.clear(); self.tail.extend_from_slice(&buf[(frames - 1) * channels..]); self.pos -= frames as f64; - self.owed -= (out.len() / channels) as u64; + if self.owed != Self::UNBOUNDED { + self.owed -= (out.len() / channels) as u64; + } *buf = out; } @@ -2544,6 +2665,9 @@ impl Resample { /// timeline did -- a rounding frame or two, or a clip whose file is shorter /// than the edit says. `false` means the consumer went away. fn flush(&mut self, channels: usize, timeline: &mut u64, tx: &SyncSender) -> bool { + if self.owed == Self::UNBOUNDED { + return true; // nothing was promised, so nothing is short + } while self.owed > 0 { let frames = self.owed.min(u64::from(SAMPLES_PER_PACKET)); let chunk = AudioChunk { @@ -2780,8 +2904,7 @@ fn run(mut w: Worker) { } Track::Aac(track) => track, }; - let mut decoder = match AacDecoder::try_new(&track.params, &AudioDecoderOptions::default()) - { + let mut decoder = match aac_decoder(&track.params, track.source_channels()) { Ok(decoder) => decoder, Err(e) => { eprintln!("audio decoder init failed: {e}"); @@ -2808,14 +2931,10 @@ fn run(mut w: Worker) { units::Duration::new(u64::from(sample.duration)), &sample.bytes[..], ); - let buf = match decoder.decode(&packet) { - Ok(buf) => buf, - Err(e) => { - eprintln!("audio decode error at sample {id}: {e}"); - break; - } - }; - buf.copy_to_vec_interleaved::(&mut interleaved); + if let Err(e) = decoder.decode(&packet, &mut interleaved) { + eprintln!("audio decode error at sample {id}: {e}"); + break; + } let next = pos + (interleaved.len() / channels) as u64; if !emit( &mut interleaved, @@ -2956,6 +3075,9 @@ fn run_ac3( return true; } }; + // The library's §7.8 downmix already handles everything but its own 2.1 + // passthrough, which comes out at 3 and is folded here like any width. + downmix(&mut interleaved, usize::from(track.channels)); let next = pos + samples; if !emit( &mut interleaved, @@ -3016,6 +3138,8 @@ fn run_mkv_ac3( return true; } }; + // ...and the 2.1 passthrough folded here, as on the mp4 side. + downmix(&mut interleaved, usize::from(track.channels)); let next = pos + samples; if !emit( &mut interleaved, @@ -3109,42 +3233,110 @@ fn run_sym( #[cfg(test)] mod tests { - use super::{PRE_ROLL, SAMPLES_PER_PACKET, fold_5_1, packet_at, packet_run}; + use super::{PRE_ROLL, SAMPLES_PER_PACKET, downmix, packet_at, packet_run, vorbis_to_film_order}; + + const C: f32 = std::f32::consts::FRAC_1_SQRT_2; + + /// The fold, channel by channel and width by width: each side keeps its own + /// front channel, takes the centre and its own surrounds at -3 dB, drops the + /// LFE, and comes out unable to clip a full-scale source. The channel order + /// is FL, FR, FC, LFE, BL, BR, SL, SR. + #[test] + fn a_surround_frame_folds_to_stereo_without_clipping() { + // Per width: what each channel at full scale, alone, must land as + // *before* the normalisation that width carries. + let layouts: [(usize, &[(f32, f32)]); 6] = [ + (3, &[(1.0, 0.0), (0.0, 1.0), (0.0, 0.0)]), + (4, &[(1.0, 0.0), (0.0, 1.0), (C, 0.0), (0.0, C)]), + (5, &[(1.0, 0.0), (0.0, 1.0), (C, C), (C, 0.0), (0.0, C)]), + ( + 6, + &[(1.0, 0.0), (0.0, 1.0), (C, C), (0.0, 0.0), (C, 0.0), (0.0, C)], + ), + ( + 7, + &[ + (1.0, 0.0), + (0.0, 1.0), + (C, C), + (0.0, 0.0), + (C, C), + (C, 0.0), + (0.0, C), + ], + ), + ( + 8, + &[ + (1.0, 0.0), + (0.0, 1.0), + (C, C), + (0.0, 0.0), + (C, 0.0), + (0.0, C), + (C, 0.0), + (0.0, C), + ], + ), + ]; + for (from, want) in layouts { + let (nl, nr) = want + .iter() + .fold((0.0f32, 0.0f32), |(l, r), c| (l + c.0, r + c.1)); + for (channel, &(left, right)) in want.iter().enumerate() { + let mut frame = vec![0.0f32; from]; + frame[channel] = 1.0; + downmix(&mut frame, from); + assert_eq!(frame.len(), 2, "{from} ch: one frame is one stereo frame"); + assert!( + (frame[0] - left / nl).abs() < 1e-6 && (frame[1] - right / nr).abs() < 1e-6, + "{from} ch{channel}: {frame:?}, want {left}/{nl} {right}/{nr}" + ); + } + // Every channel at once is what a normalised fold exists for. + let mut loud = vec![1.0f32; from * 2]; + downmix(&mut loud, from); + assert_eq!(loud.len(), 4, "{from} ch: two frames out of two"); + assert!( + loud.iter().all(|s| (*s - 1.0).abs() < 1e-6), + "{from} ch: full scale in, full scale out, never past it: {loud:?}" + ); + } + // Mono and stereo are handed over untouched. + for from in [1, 2] { + let mut flat = vec![0.5f32, -0.5]; + downmix(&mut flat, from); + assert_eq!(flat, [0.5, -0.5], "{from} ch is not a fold"); + } + } - /// The 5.1 fold: each side keeps its own front channel, takes the centre - /// and its own surround at -3 dB, drops the LFE, and comes out unable to - /// clip a full-scale source. The channel order is FL, FR, FC, LFE, BL, BR. + /// The Vorbis order an Opus surround stream is stored in, into the film + /// order the fold reads. Each channel is its own index, so a permutation + /// that drifts is the value that comes out in the wrong slot. #[test] - fn five_one_folds_to_stereo_without_clipping() { - // One frame per channel at full scale, one channel at a time. - for (channel, (left, right)) in [ - (0, (1.0, 0.0)), // FL - (1, (0.0, 1.0)), // FR - (2, (std::f32::consts::FRAC_1_SQRT_2, std::f32::consts::FRAC_1_SQRT_2)), // FC - (3, (0.0, 0.0)), // LFE, dropped - (4, (std::f32::consts::FRAC_1_SQRT_2, 0.0)), // BL - (5, (0.0, std::f32::consts::FRAC_1_SQRT_2)), // BR + fn vorbis_order_becomes_film_order() { + // (width, film slot -> the vorbis channel it must hold) + for (from, want) in [ + (3usize, &[0, 2, 1][..]), + (5, &[0, 2, 1, 3, 4]), + (6, &[0, 2, 1, 5, 3, 4]), + (7, &[0, 2, 1, 6, 5, 3, 4]), + (8, &[0, 2, 1, 7, 5, 6, 3, 4]), ] { - let mut frame = vec![0.0f32; 6]; - frame[channel] = 1.0; - fold_5_1(&mut frame, true); - let norm = 1.0 / (1.0 + 2.0 * std::f32::consts::FRAC_1_SQRT_2); - assert_eq!(frame.len(), 2, "one 5.1 frame is one stereo frame"); - assert!((frame[0] - left * norm).abs() < 1e-6, "ch{channel}: {frame:?}"); - assert!((frame[1] - right * norm).abs() < 1e-6, "ch{channel}: {frame:?}"); - } - // Every channel at once is what a normalised fold exists for. - let mut loud = vec![1.0f32; 12]; - fold_5_1(&mut loud, true); - assert_eq!(loud.len(), 4); - assert!( - loud.iter().all(|s| (*s - 1.0).abs() < 1e-6), - "full scale in, full scale out, never past it: {loud:?}" - ); - // A track that is not 5.1 is handed over untouched. - let mut stereo = vec![0.5f32, -0.5]; - fold_5_1(&mut stereo, false); - assert_eq!(stereo, [0.5, -0.5]); + // Two frames, so a permutation that reads across the frame boundary + // shows up as the wrong frame's value. + let mut samples: Vec = (0..from * 2).map(|i| i as f32).collect(); + vorbis_to_film_order(&mut samples, from); + let got: Vec = samples[..from].iter().map(|&s| s as usize).collect(); + assert_eq!(got, want, "{from} ch, first frame"); + let second: Vec = samples[from..].iter().map(|&s| s as usize - from).collect(); + assert_eq!(second, want, "{from} ch, second frame"); + } + // 7.1's LFE is the last vorbis channel and the fourth film one. + let mut lfe = vec![0.0f32; 8]; + lfe[7] = 1.0; + vorbis_to_film_order(&mut lfe, 8); + assert_eq!(lfe[3], 1.0, "the LFE lands where the fold drops it: {lfe:?}"); } /// A real AAC track: one stts entry, N packets of 1024. diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 86370fc..7a73702 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -1271,7 +1271,8 @@ fn encode_audio( params: crate::AacTrackParams { freq_index, // 1 and 2 are the ISO channel configurations for mono and stereo, - // and the opener refuses anything wider than stereo already. + // and what the opener hands the timeline is one of those whatever + // the source carried ([`crate::audio::downmix`]). chan_conf: audio.channels.max(1) as u8, sample_rate: audio.sample_rate, }, diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index ec53d97..2d7fd1d 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -1881,9 +1881,9 @@ impl PlaybackSession { /// Refused, changing nothing, unless that stream can join *this* timeline: /// same audio parameters as the first source, in the same words /// [`import`](Self::import) refuses a file with. One output device and one - /// copied AAC track mean one set of audio parameters for the whole - /// timeline, so a 22 kHz mono track cannot join a 44.1 kHz stereo one -- - /// there is no resampler here to make one rate of two. + /// copied AAC track mean one *layout* for the whole timeline, so a mono + /// track cannot join a stereo one. Its sample rate may be its own: the + /// segment's resampler conforms it at the decoder's door. /// A front-end greys such a row out; this is the backstop that keeps a /// stale one from making the whole timeline silent. /// @@ -2650,16 +2650,18 @@ fn matches_timeline( } /// Whether a candidate's audio may join a timeline whose first source probes as -/// `first`: same rate, same layout -- or no audio of its own at all, which is -/// silence over the clip's span and agrees with everything. One output device -/// and one exported track is all there is, and no resampler. +/// `first`: same layout -- or no audio of its own at all, which is silence over +/// the clip's span and agrees with everything. One output device and one +/// exported track is all there is, so one width; the *rate* is conformed rather +/// than matched ([`crate::audio::Resample`]), which is why it is not asked +/// about here. /// /// The audio half of [`matches_timeline`], which a stream placed on its own /// ([`PlaybackSession::place_stream_at`]) has to pass while the picture it /// comes with is already on the timeline. /// /// The format itself is deliberately *not* part of this: an mp3 that agrees on -/// rate and layout plays alongside a timeline of mp4s perfectly well. What it +/// layout plays alongside a timeline of mp4s perfectly well. What it /// cannot do is be copied into an export, which is a refusal of its own, at /// export time (`AudioSession::copy_multi_streams`). /// What a timeline's audio is held to: the probe of the first source that could @@ -2695,10 +2697,13 @@ fn audio_source_of(sources: &[Source]) -> Option<&Source> { } fn audio_matches(source: &Source, first: &Option) -> crate::Result<()> { - // Whole-probe equality: rate and layout, which the audio worker holds every - // source to anyway. Both silent is a match. + // The layout, which the audio worker holds every source to anyway -- and not + // the rate any more: a file written at another one is resampled to the + // timeline's at the decoder's door ([`crate::audio::Resample`]), exactly as + // a file shot at another frame rate is read through [`Rate`]. Both silent is + // a match. let probe = AudioSession::probe(&source.path, source.audio_stream)?; - if probe == *first { + if probe.map(|p| p.channels) == first.map(|p| p.channels) { return Ok(()); } // ...and a *silent* file joins whatever the timeline is: it contributes @@ -2712,8 +2717,8 @@ fn audio_matches(source: &Source, first: &Option) -> crate::R Err(match first { None => "the file has audio, the timeline is silent".to_string(), Some(b) => format!( - "audio {} Hz {} ch does not match the timeline's {} Hz {} ch", - probe.sample_rate, probe.channels, b.sample_rate, b.channels + "audio {} ch does not match the timeline's {} ch", + probe.channels, b.channels ), } .into()) diff --git a/crates/engine/tests/audio_decode.rs b/crates/engine/tests/audio_decode.rs index 4102aac..13cb843 100644 --- a/crates/engine/tests/audio_decode.rs +++ b/crates/engine/tests/audio_decode.rs @@ -1,5 +1,5 @@ use std::path::PathBuf; -use std::time::Instant; +use std::time::{Duration, Instant}; use engine::audio::AudioSession; use engine::scratch::Scratch; @@ -245,6 +245,204 @@ fn opus_decodes_from_every_container_and_51_comes_down_in_order() { } } +/// The amplitude of an `hz` sine inside `samples`, by Goertzel. The window is a +/// whole second at 48 kHz, so every frequency this asks about is an exact bin +/// and there is no leakage to correct for; a real sine of amplitude A puts +/// `A * N / 2` in its bin. +fn amplitude(samples: &[f32], hz: f64) -> f64 { + let n = samples.len() as f64; + let w = 2.0 * std::f64::consts::PI * hz / 48_000.0; + let coeff = 2.0 * w.cos(); + let (mut s1, mut s2) = (0.0, 0.0); + for &sample in samples { + let s0 = f64::from(sample) + coeff * s1 - s2; + s2 = s1; + s1 = s0; + } + 2.0 * (s1 * s1 + s2 * s2 - coeff * s1 * s2).sqrt() / n +} + +/// **7.1 Opus**, the widest layout the fold has a table for and the one the +/// largest film carries: five Opus streams, three coupled, arriving on the +/// timeline as an ordinary stereo source instead of the import refusal it used +/// to be ("unsupported channel layout: 8 channels (max stereo)"). +/// +/// The fixture puts one frequency in each of four channels and silence in the +/// rest (`gen_fixtures.sh`), so the whole downmix is one measurement: 440 in FL +/// is left only, 880 in FC is both sides at -3 dB, 1320 in the LFE must be gone +/// entirely, and 1760 in SR is right only. Every coefficient and the whole +/// Vorbis-to-film permutation at this width fail visibly here. +#[test] +fn seven_one_opus_folds_to_the_stereo_the_timeline_carries() { + let path = asset("test_opus_71.mka"); + let streams = AudioSession::probe_streams(&path).expect("streams"); + assert_eq!(streams.len(), 1); + assert!(streams[0].decodable, "a 7.1 row is not greyed out any more"); + assert_eq!(streams[0].channels, 2, "what reaches the timeline is a pair"); + + let (meta, rx) = AudioSession::open(&path) + .expect("open") + .expect("7.1 Opus decodes now"); + assert_eq!((meta.sample_rate, meta.channels), (48000, 2)); + let samples: Vec = rx.into_iter().flat_map(|c| c.samples).collect(); + assert!( + samples.iter().all(|s| s.abs() <= 1.0), + "the fold must not leave the device's range" + ); + // One whole second out of the middle, past any codec fade-in. + let second = |channel: usize| -> Vec { + samples[channel..] + .iter() + .step_by(2) + .skip(48_000) + .take(48_000) + .copied() + .collect() + }; + // 1 + 3 * (-3 dB): FL/FR keep their side, FC and both surround pairs are the + // three that join it. Nothing may come out above full scale, which is what + // dividing by the coefficient sum buys. + let norm = 1.0 + 3.0 * f64::from(std::f32::consts::FRAC_1_SQRT_2); + let c = f64::from(std::f32::consts::FRAC_1_SQRT_2); + let (left, right) = (second(0), second(1)); + // FL is the one channel that keeps its side at unity, so what it comes out + // as names the tone the fixture was written with -- `sine` peaks at 0.125 in + // ffmpeg, and reading that off the fold rather than hard-coding it keeps the + // coefficients below the claim instead of the generator's level. A fold that + // lost FL, or scaled the pair, leaves this band. + let source = amplitude(&left, 440.0) * norm; + assert!( + (0.10..0.15).contains(&source), + "FL came out as a {source:.4} tone; the fixture's is 0.125" + ); + for (side, cut, want) in [ + ("left", &left, [(440.0, 1.0), (880.0, c), (1320.0, 0.0), (1760.0, 0.0)]), + ("right", &right, [(440.0, 0.0), (880.0, c), (1320.0, 0.0), (1760.0, c)]), + ] { + for (hz, coeff) in want { + let got = amplitude(cut, hz); + let expect = source * coeff / norm; + match coeff { + // The LFE, and the channels this side has none of: what is left + // is codec noise and bleed, an order below the quietest tone. + 0.0 => assert!( + got < 0.1 * source / norm, + "{side}: {hz} Hz came through at {got:.4}, and nothing there should" + ), + _ => assert!( + (got - expect).abs() < 0.15 * expect, + "{side}: {hz} Hz at {got:.4}, want {expect:.4} +/-15%" + ), + } + } + } +} + +/// A real 7.1 remux, which is the file this whole change exists for: 12.9 GB of +/// 2160p AV1 with an 8-channel Opus track that used to come back "IMPORT FAILED: +/// unsupported channel layout: 8 channels (max stereo)" and take the picture +/// with it. +/// +/// Skipped, not failed, on a machine that does not have the film: a fixture +/// cannot stand in for the claim (the refusal was measured on *this* file) and a +/// test that cannot make it must say nothing rather than something false. +#[test] +fn his_seven_one_remux_imports_and_plays() { + let film = PathBuf::from( + "/path/to/a-real-av1-opus-7.1-film.mkv", + ); + if !film.exists() { + eprintln!("skipped: {} is not on this machine", film.display()); + return; + } + // The import gate itself: this is the call whose `Err` the app printed. + let probe = AudioSession::probe(&film, 0) + .expect("the 7.1 track no longer refuses the import") + .expect("the film has audio"); + assert_eq!( + (probe.sample_rate, probe.channels), + (48_000, 2), + "7.1 reaches the timeline as a pair" + ); + // ...and every one of its three tracks is offered, none greyed out. + let streams = AudioSession::probe_streams(&film).expect("streams"); + assert_eq!(streams.len(), 3, "7.1 plus two 5.1 commentary tracks"); + assert!( + streams.iter().all(|s| s.decodable && s.channels == 2), + "{streams:?}" + ); + + // Ten seconds out of the middle of the film, through the very worker + // playback and a WAV export both feed from -- with sound on *both* sides, + // which a fold that dropped half the layout would not have. + let (meta, rx) = AudioSession::open_segments(&film, &[(600.0, 610.0)]) + .expect("open") + .expect("the film has audio"); + assert_eq!((meta.sample_rate, meta.channels), (48_000, 2)); + let samples: Vec = rx.into_iter().flat_map(|c| c.samples).collect(); + let secs = (samples.len() / 2) as f64 / 48_000.0; + assert!((9.9..10.1).contains(&secs), "{secs:.3} s decoded, want 10"); + assert!( + samples.iter().all(|s| s.abs() <= 1.0), + "the fold must not leave the device's range" + ); + for (side, channel) in [("left", 0), ("right", 1)] { + let one: Vec = samples[channel..].iter().step_by(2).map(|s| f64::from(*s)).collect(); + let rms = (one.iter().map(|s| s * s).sum::() / one.len() as f64).sqrt(); + assert!(rms > 0.001, "{side} came out silent: RMS {rms:.6}"); + eprintln!("{side}: RMS {rms:.6} over {secs:.2}s from 600s"); + } + + // ...and the whole way out: the file on a timeline, trimmed to ten seconds, + // written as a WAV by the export path and read back through this engine's + // own reader. A session open is what the app's Import does, so a picture + // this size failing to open would fail here rather than in use. + let mut session = engine::PlaybackSession::open(&film).expect("the film opens as a timeline"); + assert_eq!( + session.audio_disabled_reason(), + None, + "a track that decodes owes no excuse" + ); + let frames = (10.0 * session.meta().frame_rate).round() as u32; + for lane in session.lanes() { + session.trim_clip(lane, 0, engine::project::Edge::End, frames); + } + let out = Scratch::file("ve_seven_one", "wav"); + let handle = session.export_to_with( + &out, + &engine::export::ExportSettings { + format: engine::export::Format::Wav, + ..Default::default() + }, + ); + let started = Instant::now(); + while !handle.is_finished() { + assert!(started.elapsed() < Duration::from_secs(300), "export hung"); + std::thread::sleep(Duration::from_millis(50)); + } + handle.result().expect("outcome").expect("the WAV is written"); + let (wav, rx) = AudioSession::open(&out) + .expect("the WAV reopens") + .expect("it has sound"); + let written: Vec = rx.into_iter().flat_map(|c| c.samples).collect(); + let channels = usize::from(wav.channels); + assert_eq!(channels, 2, "a stereo WAV out of a 7.1 source"); + for (side, channel) in [("left", 0), ("right", 1)] { + let one: Vec = written[channel..] + .iter() + .step_by(channels) + .map(|s| f64::from(*s)) + .collect(); + let rms = (one.iter().map(|s| s * s).sum::() / one.len() as f64).sqrt(); + assert!(rms > 0.001, "the exported {side} is silent: RMS {rms:.6}"); + eprintln!( + "exported {side}: RMS {rms:.6} over {:.2}s at {} Hz", + one.len() as f64 / f64::from(wav.sample_rate), + wav.sample_rate + ); + } +} + /// The same two ends of the AC-3 path, in **Matroska**: a stereo AC-3 track and /// a 5.1 E-AC-3 one -- the codec a remux carries and the one the "(AAC only)" /// refusal used to fire on -- both come out of the blocks, both arrive as the diff --git a/crates/engine/tests/audio_files.rs b/crates/engine/tests/audio_files.rs index beb27a1..d06364e 100644 --- a/crates/engine/tests/audio_files.rs +++ b/crates/engine/tests/audio_files.rs @@ -172,16 +172,57 @@ fn a_song_joins_a_video_timeline_on_the_audio_lane() { assert!(session.lane_spans_by_source(Lane::A1).len() >= 2); } +/// A rate one output device cannot have two of is **converted**, not refused: +/// the 48 kHz twin of the tone joins a 44.1 kHz timeline, is placed for the +/// seconds it lasts, and comes out at the pitch it was recorded at. +/// +/// The pitch is the whole claim. Reading a 48 kHz file's frames one for one onto +/// a 44.1 kHz timeline plays it 8.8% slow and 440 Hz becomes 404 -- which is +/// what "it imported" would look like from a length check alone. #[test] -fn a_rate_the_device_cannot_mix_is_refused_at_the_door() { +fn a_rate_the_device_cannot_mix_is_converted_at_the_door() { let mut session = open(asset("test_av.mp4")); + let before = session.timeline_duration(); + import_and_place(&mut session, &asset("test_tone_48k.wav")); + assert_eq!(session.sources().len(), 2, "the 48k file is in the library"); + assert_eq!(session.lane_clips(Lane::A1).len(), 2, "and on the lane"); + // 3 s of tone placed after the video, at the timeline's own rate. + assert!( + (session.timeline_duration() - (before + 3.0)).abs() < 0.05, + "{} s of timeline, want {}", + session.timeline_duration(), + before + 3.0 + ); + + // ...and the samples themselves, straight out of the worker the session + // feeds from: one second of the 48k file, resampled onto a 44.1k timeline. + let sources = [(asset("test_av.mp4"), 0), (asset("test_tone_48k.wav"), 0)]; + let (meta, rx) = + AudioSession::open_multi_streams(&sources, &[(Some(1), 0.25, 1.25)]).expect("open").expect("the timeline has sound"); assert_eq!( - refusal(session.import(&asset("test_tone_48k.wav"))), - "audio 48000 Hz 2 ch does not match the timeline's 44100 Hz 2 ch" + (meta.sample_rate, meta.channels), + (44100, 2), + "the timeline's rate, not the file's" ); - // Refused means unchanged: no library row, no clip, no length. - assert_eq!(session.sources().len(), 1); - assert_eq!(session.lane_clips(Lane::A1).len(), 1); + let samples: Vec = rx.into_iter().flat_map(|c| c.samples).collect(); + let frames = samples.len() / 2; + assert!( + (frames as i64 - 44100).abs() < 64, + "one second of timeline is {frames} frames of 44100" + ); + // 440 Hz left, 880 Hz right -- the fixture's own tones, unmoved. Zero + // crossings date them without an FFT: a file read at 1:1 instead of 48:44.1 + // would come out at 404 and 808, an 8% miss this 2% band rejects. + for (name, channel, hz) in [("left", 0, 440.0), ("right", 1, 880.0)] { + let side: Vec = samples[channel..].iter().step_by(2).copied().collect(); + let secs = side.len() as f64 / 44100.0; + let crossings = side.windows(2).filter(|p| (p[0] < 0.0) != (p[1] < 0.0)).count() as f64; + let got = crossings / 2.0 / secs; + assert!( + (got - hz).abs() <= 0.02 * hz, + "{name}: {got:.1} Hz out of a {hz} Hz tone -- the resample moved the pitch" + ); + } } /// A song *is* a timeline: it scaffolds the canvas a video would have defined, @@ -382,15 +423,13 @@ fn a_video_joins_a_timeline_a_song_started() { import_and_place(&mut session, &asset("test_av.mp4")); assert_eq!(session.lane_clips(Lane::V1).len(), 1, "a picture at last"); assert_eq!(session.lane_clips(Lane::A1).len(), 2); - // A sample rate the device cannot have two of is still refused in the - // timeline's own words... - let e = refusal(session.import(&asset("test_tone_48k.wav"))); - assert_eq!( - e, - "audio 48000 Hz 2 ch does not match the timeline's 44100 Hz 2 ch" - ); - assert_eq!(session.sources().len(), 2, "a refusal left a library row"); - // ...but a *frame* rate of its own is not a refusal: the canvas a song + // A sample rate the device cannot have two of is no refusal either: it is + // resampled onto the timeline's, as a frame rate is conformed to the canvas. + session + .import(&asset("test_tone_48k.wav")) + .expect("48 kHz joins a 44.1 kHz timeline"); + assert_eq!(session.sources().len(), 3); + // ...and a *frame* rate of its own is not a refusal either: the canvas a song // scaffolds runs at 30 fps and a 25 fps picture joins it at the length it // lasts in seconds (50 frames of file, 60 of timeline). session diff --git a/crates/engine/tests/audio_multi.rs b/crates/engine/tests/audio_multi.rs index d9dc201..1366d57 100644 --- a/crates/engine/tests/audio_multi.rs +++ b/crates/engine/tests/audio_multi.rs @@ -250,11 +250,12 @@ fn the_join_carries_no_second_priming_packet() { } #[test] -fn a_source_that_disagrees_on_rate_or_layout_is_refused() { - // Import refuses these up front (one output device, one set of parameters); - // the copy and the decode paths refuse them again rather than mislabel one - // esds for two different tracks. Stream 1 of the multi-audio fixture is - // 22.05 kHz mono against the timeline's 44.1 kHz stereo. +fn a_source_that_disagrees_on_layout_is_refused() { + // Import refuses these up front (one output device, one *layout*); the copy + // and the decode paths refuse them again rather than mislabel one esds for + // two different tracks. Stream 1 of the multi-audio fixture is 22.05 kHz + // mono against the timeline's 44.1 kHz stereo -- its rate is conformed at + // the decoder's door now, its layout is what is left to refuse. let mixed = [(asset("test_av.mp4"), 0), (asset("test_multiaudio.mp4"), 1)]; let segs = [(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0)]; // (`.err()`, not `unwrap_err`: neither Ok payload is `Debug`.) diff --git a/crates/engine/tests/capability_matrix.rs b/crates/engine/tests/capability_matrix.rs index d1fa772..a1f71c5 100644 --- a/crates/engine/tests/capability_matrix.rs +++ b/crates/engine/tests/capability_matrix.rs @@ -103,6 +103,9 @@ fn every_audio_codec_the_refusal_names_really_decodes() { ("test_vp9.webm", "opus in a webm", 1), // 5.1 arrives as the stereo fold, exactly as a 5.1 AC-3 track does. ("test_opus_51.mka", "5.1 opus in an mka", 2), + // ...and 7.1, the widest layout the fold has a table for and the one + // a real remux carries. + ("test_opus_71.mka", "7.1 opus in an mka", 2), ("test_tone.opus", "a standalone opus", 2), ] { let probe = AudioSession::probe(asset(file), 0) diff --git a/crates/engine/tests/playback.rs b/crates/engine/tests/playback.rs index f6ada77..e8eb911 100644 --- a/crates/engine/tests/playback.rs +++ b/crates/engine/tests/playback.rs @@ -963,16 +963,23 @@ fn import_refuses_what_does_not_match() { .remove_source(&asset("test_25fps.mp4"), 0) .expect("...and the row it made comes back off"); - // What is still refused, and all that is: one output device means one rate - // and one layout, and there is no resampler to make two into one. + // A sample *rate* of its own is no longer a refusal either: one output + // device means one rate, and the segment's own resampler is what makes two + // into one now ([`engine::audio::Resample`]). + session + .import(&asset("test_tone_48k.wav")) + .expect("48 kHz may join a 44.1 kHz timeline"); + session + .remove_source(&asset("test_tone_48k.wav"), 0) + .expect("...and the row it made comes back off"); + + // What is still refused, and all that is: one output device carries one + // layout, and a mono track is not the stereo pair this timeline plays. let err = session .import(&asset("test_ac3.mp4")) .expect_err("a mono track cannot join a stereo timeline") .to_string(); - assert_eq!( - err, - "audio 44100 Hz 1 ch does not match the timeline's 44100 Hz 2 ch" - ); + assert_eq!(err, "audio 1 ch does not match the timeline's 2 ch"); assert!( session.import(&asset("no_such_file.mp4")).is_err(), diff --git a/crates/engine/tests/saveload.rs b/crates/engine/tests/saveload.rs index 4942563..10d52fd 100644 --- a/crates/engine/tests/saveload.rs +++ b/crates/engine/tests/saveload.rs @@ -79,11 +79,13 @@ fn a_picked_audio_stream_lands_saves_and_comes_back() { let other = copy_in(&dir, "test_multiaudio.mp4"); let mut session = PlaybackSession::open(&other).expect("open the fixture"); session.set_gain(0.0); + // Its rate would be conformed now; its *layout* is what one output device + // cannot have two of, and the refusal says which. let err = session .place_stream_at(0.0, &other, 1, None) - .expect_err("22.05 kHz mono cannot join a 44.1 kHz stereo timeline") + .expect_err("a mono stream cannot join a stereo timeline") .to_string(); - assert!(err.contains("22050"), "unhelpful refusal: {err}"); + assert_eq!(err, "audio 1 ch does not match the timeline's 2 ch"); assert!( session .place_stream_at(0.0, &media, 1, None) @@ -742,15 +744,16 @@ fn a_source_that_no_longer_matches_the_timeline_is_refused_in_import_words() { .expect("a source that stopped matching must not open") .to_string(); // The suffix is `import`'s own refusal, word for word. The substitute is - // mono, which is the shape of what is left: one output device means one - // rate and one layout. A resolution of its own is placed on the project - // canvas, a rate of its own is read through `Rate`, a codec of its own - // opens its own decoder and a file with no sound plays silence -- none of - // those is a refusal any more. + // mono, which is the shape of what is left: one output device carries one + // layout. A resolution of its own is placed on the project canvas, a frame + // rate of its own is read through `Rate`, a *sample* rate of its own is + // resampled at the decoder's door, a codec of its own opens its own decoder + // and a file with no sound plays silence -- none of those is a refusal any + // more. assert_eq!( err, format!( - "source {}: audio 44100 Hz 1 ch does not match the timeline's 44100 Hz 2 ch", + "source {}: audio 1 ch does not match the timeline's 2 ch", dir.join("test_av2.mp4").display() ) ); diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index c8aaac1..11734dd 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -475,6 +475,20 @@ ffmpeg -y -f lavfi -i "sine=frequency=440:duration=3:sample_rate=48000" \ -f lavfi -i "anullsrc=r=48000:cl=quad:d=3" \ -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]" \ -map "[a]" -c:a libopus -b:a 256k assets/test_opus_51.mka +# ...and **7.1 Opus**, which is a large film's soundtrack in miniature: five +# Opus streams, three coupled, and the widest layout the fold has a table for. +# One frequency per channel, four of the eight carrying anything, so the whole +# downmix is checkable by picking those four out of the folded pair +# (`tests/audio_multi.rs`): 440 in FL is left only, 880 in FC is both sides at +# -3 dB, 1320 in the LFE must be *gone*, and 1760 in SR is right only. Get the +# Vorbis-to-film permutation wrong at this width and every one of those moves. +ffmpeg -y -f lavfi -i "sine=frequency=440:duration=3:sample_rate=48000" \ + -f lavfi -i "sine=frequency=880:duration=3:sample_rate=48000" \ + -f lavfi -i "sine=frequency=1320:duration=3:sample_rate=48000" \ + -f lavfi -i "sine=frequency=1760:duration=3:sample_rate=48000" \ + -f lavfi -i "anullsrc=r=48000:cl=quad:d=3" \ + -filter_complex "[0:a][1:a][2:a][3:a][4:a]join=inputs=5:channel_layout=7.1:map=0.0-FL|4.0-FR|1.0-FC|2.0-LFE|4.1-BL|4.2-BR|4.3-SL|3.0-SR[a]" \ + -map "[a]" -c:a libopus -b:a 320k assets/test_opus_71.mka # Still-image fixture: the source with a picture and no timeline in it. Two # bands rather than one colour, so a test can tell top from bottom (a flipped # decode) and red from blue (a swapped channel order); 640x360, which is 16:9