forge
Explore
Log in

Don't you dare go Hollow

Convert wide layouts and off-rate sources at import instead of refusing

Browse files at this commit

c94ba8b5f63129a6248d421e4d171f96893aaafcAhmet Kaan GümüşParent: 76ede8e
  • feat
    • convert wide layouts and off-rate sources at import instead of refusing
Show full message
✨ feat(audio): convert wide layouts and off-rate sources at import instead of refusing

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.rsmodified+17 -10
@@ -11826,11 +11826,14 @@ fn unusable(info: &StreamInfo, timeline_audio: Option<(u32, u16)>) -> Option<Str
11826 codec => format!("{codec} is not supported"),11826 codec => format!("{codec} is not supported"),
11827 });11827 });
11828 }11828 }
11829- let (rate, channels) = timeline_audio?;11829+ // The **layout** and not the rate, which is what the engine's own gate now
11830- ((info.sample_rate, info.channels) != (rate, channels)).then(|| {11830+ // asks (`PlaybackSession::import`): a stream written at another sample rate
11831+ // is resampled onto the timeline's at the decoder's door, so greying its row
11832+ // would be this picker refusing what the timeline accepts.
11833+ let (_, channels) = timeline_audio?;
11834+ (info.channels != channels).then(|| {
11831 format!(11835 format!(
11832- "the timeline is {} kHz {}",11836+ "the timeline is {}",
11833- f64::from(rate) / 1000.,
11834 layout(channels).unwrap_or_else(|| "silent".to_string())11837 layout(channels).unwrap_or_else(|| "silent".to_string())
11835 )11838 )
11836 })11839 })
@@ -14226,7 +14229,7 @@ mod tests {
14226 Landing, arrival, launch_queue,14229 Landing, arrival, launch_queue,
14227 read_ahead, scan_plan, seek_line, silence_line, stash_or_write,14230 read_ahead, scan_plan, seek_line, silence_line, stash_or_write,
14228 repeats, resolution_choices, resolution_ladder, span_label, tone_choices, tone_label,14231 repeats, resolution_choices, resolution_ladder, span_label, tone_choices, tone_label,
14229- clip_width, trimmed_clip, trims, unscannable,14232+ clip_width, trimmed_clip, trims, unscannable, unusable,
14230 visible_slice,14233 visible_slice,
14231 };14234 };
14232 use super::{14235 use super::{
@@ -14447,13 +14450,17 @@ mod tests {
14447 assert_eq!(rows[1].name, "movie.mp4 [audio 2]");14450 assert_eq!(rows[1].name, "movie.mp4 [audio 2]");
14448 assert_eq!(rows[1].detail, "fra 44.1 kHz stereo");14451 assert_eq!(rows[1].detail, "fra 44.1 kHz stereo");
14449 // Placeable: the one already on the timeline, and the one that matches14452 // Placeable: the one already on the timeline, and the one that matches
14450- // it. The 22 kHz mono track cannot join a 44.1 kHz stereo timeline --14453+ // it. The mono track cannot join a stereo timeline -- one device and one
14451- // one device and one copied AAC track for the whole of it -- and the14454+ // copied AAC track for the whole of it -- and the codec we cannot read
14452- // codec we cannot read cannot join anything. Both say which.14455+ // cannot join anything. Both say which. Its 22 kHz is *not* part of that
14456+ // any more: a rate of its own is resampled at the decoder's door, and a
14457+ // row greyed for one the engine accepts is this picker telling a lie.
14453 assert_eq!((&rows[0].unusable, &rows[1].unusable), (&None, &None));14458 assert_eq!((&rows[0].unusable, &rows[1].unusable), (&None, &None));
14459+ assert_eq!(rows[2].unusable.as_deref(), Some("the timeline is stereo"));
14454 assert_eq!(14460 assert_eq!(
14455- rows[2].unusable.as_deref(),14461+ unusable(&info(9, 48_000, 2, None, true), Some((44_100, 2))),
14456- Some("the timeline is 44.1 kHz stereo")14462+ None,
14463+ "48 kHz stereo joins a 44.1 kHz stereo timeline"
14457 );14464 );
14458 assert_eq!(rows[3].unusable.as_deref(), Some("unsupported codec"));14465 assert_eq!(rows[3].unusable.as_deref(), Some("unsupported codec"));
14459 assert_eq!(14466 assert_eq!(
crates/engine/src/audio.rsmodified+375 -183
@@ -133,12 +133,14 @@ pub struct AacPacket {
133 }133 }
134 134
135 /// Everything an import check needs from a candidate file's audio track. Two135 /// Everything an import check needs from a candidate file's audio track. Two
136-/// files may share a timeline only when their probes are equal (or both `None`).136+/// files may share a timeline when their layouts agree (or both are `None`).
137 ///137 ///
138-/// Rate and layout only: those are what one output device and one exported track138+/// Rate and layout, of which only the **layout** is held to the timeline's: one
139-/// can carry, and an mp3 that agrees on both may join a timeline of mp4s even139+/// output device and one exported track carry one width, while a rate of its own
140-/// though nothing about it can be *copied* into an export -- that is a separate140+/// is resampled at the decoder's door ([`Resample`]). An mp3 that agrees on the
141-/// refusal, at export time, in [`AudioSession::copy_multi_segments`].141+/// layout may join a timeline of mp4s even though nothing about it can be
142+/// *copied* into an export -- that is a separate refusal, at export time, in
143+/// [`AudioSession::copy_multi_segments`].
142 #[derive(Debug, Clone, Copy, PartialEq)]144 #[derive(Debug, Clone, Copy, PartialEq)]
143 pub struct AudioProbe {145 pub struct AudioProbe {
144 pub sample_rate: u32,146 pub sample_rate: u32,
@@ -167,9 +169,9 @@ pub struct StreamInfo {
167 pub sample_rate: u32,169 pub sample_rate: u32,
168 /// ISO-639-2 from the mdhd, `None` for the `und` most muxers write.170 /// ISO-639-2 from the mdhd, `None` for the `und` most muxers write.
169 pub lang: Option<String>,171 pub lang: Option<String>,
170- /// Whether opening this stream would decode: AAC-LC, mono or stereo. The172+ /// Whether opening this stream would decode -- a codec question only now
171- /// grey-out rule, mirroring the refusals `Track::open` and `Track::channels`173+ /// that no width is refused. The grey-out rule, mirroring what `Track::open`
172- /// make one file at a time.174+ /// answers one file at a time.
173 pub decodable: bool,175 pub decodable: bool,
174 }176 }
175 177
@@ -291,8 +293,9 @@ impl AudioSession {
291 ///293 ///
292 /// Only the sources some segment names are opened. `Ok(None)` when `sources`294 /// Only the sources some segment names are opened. `Ok(None)` when `sources`
293 /// is empty or its first entry has no AAC track; a later source that295 /// is empty or its first entry has no AAC track; a later source that
294- /// disagrees on rate/layout is an `Err` — import refuses those up front (one296+ /// disagrees on *layout* is an `Err` — import refuses those up front (one
295- /// timeline, one output device), this is the backstop.297+ /// timeline, one output device), this is the backstop. A source at another
298+ /// sample rate is not one of those: it is resampled, per segment.
296 pub fn open_multi_segments(299 pub fn open_multi_segments(
297 sources: &[PathBuf],300 sources: &[PathBuf],
298 segs: &[(Option<usize>, f64, f64)],301 segs: &[(Option<usize>, f64, f64)],
@@ -372,7 +375,7 @@ impl AudioSession {
372 // match it, and the checks below hold them to that.375 // match it, and the checks below hold them to that.
373 let meta = AudioMeta {376 let meta = AudioMeta {
374 sample_rate: first.sample_rate(),377 sample_rate: first.sample_rate(),
375- channels: first.channels()?,378+ channels: first.channels(),
376 total_samples: first.total_samples(),379 total_samples: first.total_samples(),
377 };380 };
378 // Built here only so an undecodable stream is an `Err` from the opener381 // Built here only so an undecodable stream is an `Err` from the opener
@@ -407,12 +410,16 @@ impl AudioSession {
407 silent[source] = true;410 silent[source] = true;
408 continue;411 continue;
409 };412 };
410- if (track.sample_rate(), track.channels()?) != (meta.sample_rate, meta.channels) {413+ // The *rate* is no longer held to the timeline's: a source written at
414+ // another one is read through its segment's [`Resample`] below, the
415+ // very interpolator a speeded clip already goes through, so it plays
416+ // at the pitch it was recorded at over the seconds it was placed for.
417+ // The layout still is -- one output device carries one width, and
418+ // everything wider than a pair is already folded to one.
419+ if track.channels() != meta.channels {
411 return Err(format!(420 return Err(format!(
412- "source {source} is {} Hz {} ch, the timeline is {} Hz {} ch",421+ "source {source} is {} ch, the timeline is {} ch",
413- track.sample_rate(),422+ track.channels(),
414- track.channels()?,
415- meta.sample_rate,
416 meta.channels423 meta.channels
417 )424 )
418 .into());425 .into());
@@ -437,9 +444,15 @@ impl AudioSession {
437 // Chunk numbering is continuous across every join, counted from the first444 // Chunk numbering is continuous across every join, counted from the first
438 // segment's audible start in its own source (see `open_segments`).445 // segment's audible start in its own source (see `open_segments`).
439 let timeline = segments.first().map_or(0, |s| match s.source {446 let timeline = segments.first().map_or(0, |s| match s.source {
440- Some(source) => s447+ Some(source) => {
441- .media_target448+ let track = tracks[source].as_ref().expect("opened above");
442- .saturating_sub(tracks[source].as_ref().expect("opened above").priming()),449+ // ...in *timeline* frames, which is not the source's own count
450+ // when it was written at another rate. Integer, so the equal-rate
451+ // case -- every project before this -- is the number it always was.
452+ let at = s.media_target.saturating_sub(track.priming());
453+ at.saturating_mul(u64::from(meta.sample_rate))
454+ / u64::from(track.sample_rate().max(1))
455+ }
443 None => 0,456 None => 0,
444 });457 });
445 458
@@ -460,20 +473,41 @@ impl AudioSession {
460 })473 })
461 .collect();474 .collect();
462 475
463- // One resampler per speeded segment, built where the sample rate is476+ // One resampler per segment that needs one, built where the sample rate
464- // known: what the timeline owes it is seconds there and frames here.477+ // is known: what the timeline owes it is seconds there and frames here.
478+ //
479+ // Two things ask for one and they compose into a single step: the clip's
480+ // own speed, and a source written at a rate other than the timeline's --
481+ // the ratio of the two rates is exactly a speed, and reading the samples
482+ // at it is what keeps a 48 kHz file's pitch on a 44.1 kHz timeline. A
483+ // segment with neither has no resampler at all and reaches the mixer
484+ // with the decoder's own samples, byte for byte, as it always did.
465 let speeds: Vec<Option<Resample>> = segments485 let speeds: Vec<Option<Resample>> = segments
466 .iter()486 .iter()
487+ .zip(segs)
467 .enumerate()488 .enumerate()
468- .map(|(i, _)| {489+ .map(|(i, (seg, &(_, start_secs, end_secs)))| {
469- speeds.get(i).and_then(Option::as_ref).map(|s| {490+ let rate = seg
470- Resample::new(491+ .source
471- s.step,492+ .and_then(|source| tracks[source].as_ref())
472- (s.timeline_secs * f64::from(meta.sample_rate))493+ .map_or(meta.sample_rate, Track::sample_rate);
473- .round()494+ let ratio = f64::from(rate) / f64::from(meta.sample_rate.max(1));
474- .max(0.) as u64,495+ let stretch = speeds.get(i).and_then(Option::as_ref);
475- )496+ if stretch.is_none() && rate == meta.sample_rate {
476- })497+ return None;
498+ }
499+ // A speeded clip states the timeline it owes; a plain one owes
500+ // the window it was placed for, and an open-ended window owes
501+ // whatever its source has ([`Resample::UNBOUNDED`]).
502+ let secs = stretch.map_or(end_secs - start_secs, |s| s.timeline_secs);
503+ let owed = match (secs * f64::from(meta.sample_rate)).round() {
504+ frames if frames.is_finite() && frames >= 0.0 => {
505+ (frames as u64).min(Resample::UNBOUNDED - 1)
506+ }
507+ frames if frames > 0.0 => Resample::UNBOUNDED,
508+ _ => 0,
509+ };
510+ Some(Resample::new(stretch.map_or(1.0, |s| s.step) * ratio, owed))
477 })511 })
478 .collect();512 .collect();
479 513
@@ -741,7 +775,7 @@ impl AudioSession {
741 };775 };
742 Ok(Some(AudioProbe {776 Ok(Some(AudioProbe {
743 sample_rate: track.sample_rate(),777 sample_rate: track.sample_rate(),
744- channels: track.channels()?,778+ channels: track.channels(),
745 }))779 }))
746 }780 }
747 781
@@ -807,8 +841,11 @@ impl AudioSession {
807 ),841 ),
808 lang: (entry.language != "und" && !entry.language.is_empty())842 lang: (entry.language != "und" && !entry.language.is_empty())
809 .then(|| entry.language.clone()),843 .then(|| entry.language.clone()),
810- decodable: matches!(channels, 1 | 2)844+ // No width gate any more: `channels` is what reaches the
811- && (ac3.is_some() || sym.is_some_and(|t| t.decoder().is_ok())),845+ // timeline, which [`downmix`] makes a pair out of whatever
846+ // the file carries. What greys a row out is a codec nothing
847+ // here decodes, and nothing else.
848+ decodable: ac3.is_some() || sym.is_some_and(|t| t.decoder().is_ok()),
812 });849 });
813 }850 }
814 return Ok(streams);851 return Ok(streams);
@@ -823,7 +860,7 @@ impl AudioSession {
823 // Neither the mp3 nor the wav headers carry an ISO-639 tag the860 // Neither the mp3 nor the wav headers carry an ISO-639 tag the
824 // way an mdhd does, and a lone track needs no telling apart.861 // way an mdhd does, and a lone track needs no telling apart.
825 lang: None,862 lang: None,
826- decodable: matches!(track.channels, 1 | 2) && track.decoder().is_ok(),863+ decodable: track.decoder().is_ok(),
827 }]);864 }]);
828 }865 }
829 let file = File::open(path)?;866 let file = File::open(path)?;
@@ -862,13 +899,17 @@ impl AudioSession {
862 |t| t.sample_rate,899 |t| t.sample_rate,
863 ),900 ),
864 lang: (!lang.is_empty() && lang != "und").then(|| lang.to_string()),901 lang: (!lang.is_empty() && lang != "und").then(|| lang.to_string()),
865- decodable: ac3.as_ref().is_some_and(|t| matches!(t.channels, 1 | 2))902+ // The profile still gates -- the writer rebuilds an
903+ // AudioSpecificConfig and calls it LC -- but the layout no
904+ // longer does: a 5.1 or 7.1 AAC track decodes through
905+ // `rusty_aac` and folds to the pair the timeline carries
906+ // ([`aac_decoder`]).
907+ decodable: ac3.is_some()
866 || aac908 || aac
867- && matches!(track.audio_profile(), Ok(AudioObjectType::AacLowComplexity))909+ && matches!(
868- && matches!(910+ track.audio_profile(),
869- track.channel_config(),911+ Ok(AudioObjectType::AacLowComplexity)
870- Ok(ChannelConfig::Mono | ChannelConfig::Stereo)912+ ),
871- ),
872 }913 }
873 })914 })
874 .collect())915 .collect())
@@ -1266,26 +1307,20 @@ impl Track {
1266 }1307 }
1267 }1308 }
1268 1309
1269- /// Mono or stereo; anything wider is refused here rather than one packet at1310+ /// What this track hands the timeline: mono, or stereo for everything else.
1270- /// a time, because one output device and one copied track is all there is.1311+ /// Nothing is refused for its width any more -- a layout wider than a pair
1271- fn channels(&self) -> crate::Result<u16> {1312+ /// is folded to one at the decoder's door ([`downmix`]), because one output
1313+ /// device is all there is, not because the file is unreadable.
1314+ fn channels(&self) -> u16 {
1272 match self {1315 match self {
1273 Self::Aac(t) => t.channels(),1316 Self::Aac(t) => t.channels(),
1274- // Already downmixed: `channels` is what comes *out* of the decoder,1317+ // Already downmixed by the AC-3 decoder itself; `channels` is what
1275- // which is 2 for everything from mono to 5.1 (see [`Ac3Track`]).1318+ // comes *out* of it, and the 2.1 passthrough it leaves at 3 (see
1276- Self::Ac3(t) => match t.channels {1319+ // [`Ac3Track`]) is folded by [`decode_ac3`] like any other width.
1277- 1 | 2 => Ok(t.channels),1320+ Self::Ac3(t) => t.channels.min(2),
1278- n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()),
1279- },
1280 // Downmixed by the very same decoder, out of a Matroska file.1321 // Downmixed by the very same decoder, out of a Matroska file.
1281- Self::Mkv(t) => match t.channels {1322+ Self::Mkv(t) => t.channels.min(2),
1282- 1 | 2 => Ok(t.channels),1323+ Self::Sym(t) => t.channels,
1283- n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()),
1284- },
1285- Self::Sym(t) => match t.channels {
1286- 1 | 2 => Ok(t.channels),
1287- n => Err(format!("unsupported channel layout: {n} channels (max stereo)").into()),
1288- },
1289 }1324 }
1290 }1325 }
1291 1326
@@ -1336,7 +1371,7 @@ impl Track {
1336 fn check_decoder(&self) -> crate::Result<()> {1371 fn check_decoder(&self) -> crate::Result<()> {
1337 match self {1372 match self {
1338 Self::Aac(t) => {1373 Self::Aac(t) => {
1339- AacDecoder::try_new(&t.params, &AudioDecoderOptions::default())?;1374+ aac_decoder(&t.params, t.source_channels())?;
1340 }1375 }
1341 Self::Ac3(t) => {1376 Self::Ac3(t) => {
1342 ac3_decoder("ac3", t.requested)?;1377 ac3_decoder("ac3", t.requested)?;
@@ -1363,9 +1398,9 @@ struct SymTrack {
1363 path: PathBuf,1398 path: PathBuf,
1364 track_id: u32,1399 track_id: u32,
1365 sample_rate: u32,1400 sample_rate: u32,
1366- /// What reaches the timeline: the file's own layout, or 2 for a 5.1 track,1401+ /// What reaches the timeline: the file's own layout, or 2 for anything
1367- /// which is folded down by [`SymDecoder`] exactly as the AC-3 reader's1402+ /// wider, which is folded down by [`SymDecoder`] exactly as the AC-3
1368- /// decoder folds its own.1403+ /// reader's decoder folds its own.
1369 channels: u16,1404 channels: u16,
1370 /// What the decoder emits, which is what the fold reads.1405 /// What the decoder emits, which is what the fold reads.
1371 source_channels: u16,1406 source_channels: u16,
@@ -1463,10 +1498,10 @@ impl SymTrack {
1463 path: path.to_path_buf(),1498 path: path.to_path_buf(),
1464 track_id,1499 track_id,
1465 sample_rate,1500 sample_rate,
1466- // 5.1 arrives as a stereo source, whatever it was stored as; every1501+ // Anything wider than a pair arrives as a stereo source, whatever it
1467- // other layout is passed through and refused above stereo by1502+ // was stored as: 5.1, 7.1 and everything between are folded by
1468- // [`Track::channels`], where it always was.1503+ // [`downmix`] at the decoder's door ([`SymDecoder`]).
1469- channels: if channels == 6 { 2 } else { channels },1504+ channels: channels.min(2),
1470 source_channels: channels,1505 source_channels: channels,
1471 total_samples: num_frames.map(|n| n.saturating_sub(priming)),1506 total_samples: num_frames.map(|n| n.saturating_sub(priming)),
1472 priming,1507 priming,
@@ -1488,34 +1523,27 @@ impl SymTrack {
1488 ///1523 ///
1489 /// Which decoder is not the caller's business, and it is not always1524 /// Which decoder is not the caller's business, and it is not always
1490 /// symphonia's: its AAC decoder refuses anything wider than stereo outright1525 /// symphonia's: its AAC decoder refuses anything wider than stereo outright
1491- /// (`aac/mod.rs:93`, "aac: aac too complex"), which is exactly the 5.1 track1526+ /// (`aac/mod.rs:93`, "aac: aac too complex"), which is exactly the 5.1 and
1492- /// of a film in an mkv, so that one goes to `rusty_aac` instead, and it has1527+ /// 7.1 tracks of a film, so those go to `rusty_aac` instead
1493- /// no Opus decoder at all, so that one goes to `ruopus`.1528+ /// ([`aac_decoder`]), and it has no Opus decoder at all, so that one goes to
1529+ /// `ruopus`.
1494 fn decoder(&self) -> crate::Result<SymDecoder> {1530 fn decoder(&self) -> crate::Result<SymDecoder> {
1495- let fold = self.source_channels != self.channels;1531+ let from = usize::from(self.source_channels);
1496 if self.params.codec == CODEC_ID_OPUS {1532 if self.params.codec == CODEC_ID_OPUS {
1497- let channels = usize::from(self.source_channels);
1498 let (streams, coupled, mapping) =1533 let (streams, coupled, mapping) =
1499- opus_layout(self.params.extra_data.as_deref().unwrap_or_default(), channels)?;1534+ opus_layout(self.params.extra_data.as_deref().unwrap_or_default(), from)?;
1500 // 48 kHz whatever the container says: that is the only rate Opus1535 // 48 kHz whatever the container says: that is the only rate Opus
1501 // decodes at, and the rate both readers declare for it.1536 // decodes at, and the rate both readers declare for it.
1502 let decoder = ruopus::MultistreamDecoder::with_rate(48_000, streams, coupled, &mapping);1537 let decoder = ruopus::MultistreamDecoder::with_rate(48_000, streams, coupled, &mapping);
1503- return Ok(SymDecoder::Opus(Box::new(decoder), fold));1538+ return Ok(SymDecoder::Opus(Box::new(decoder), from));
1504- }1539+ }
1505- if self.params.codec == CODEC_ID_AAC && self.source_channels > 2 {1540+ if self.params.codec == CODEC_ID_AAC {
1506- let asc = self1541+ return aac_decoder(&self.params, from);
1507- .params
1508- .extra_data
1509- .as_deref()
1510- .ok_or("a multichannel AAC track with no AudioSpecificConfig")?;
1511- let decoder = rusty_aac::AacDecoder::with_config_bytes(asc)
1512- .map_err(|e| format!("multichannel AAC decoder init failed: {e}"))?;
1513- return Ok(SymDecoder::Aac(Box::new(decoder), fold));
1514 }1542 }
1515 Ok(SymDecoder::Sym(1543 Ok(SymDecoder::Sym(
1516 symphonia::default::get_codecs()1544 symphonia::default::get_codecs()
1517 .make_audio_decoder(&self.params, &AudioDecoderOptions::default())?,1545 .make_audio_decoder(&self.params, &AudioDecoderOptions::default())?,
1518- fold,1546+ from,
1519 ))1547 ))
1520 }1548 }
1521 1549
@@ -1626,48 +1654,70 @@ fn sym_reader(path: &Path) -> crate::Result<Box<dyn FormatReader>> {
1626 }1654 }
1627 1655
1628 /// One packet in, interleaved f32 out — whichever library did the decoding, and1656 /// One packet in, interleaved f32 out — whichever library did the decoding, and
1629-/// already folded to the layout [`SymTrack::channels`] promised. The flag is1657+/// already folded to the layout [`SymTrack::channels`] promised. The number
1630-/// that fold: `true` for a 5.1 track, and there is nothing else it can be.1658+/// beside each is the width the decoder itself emits, which is what
1659+/// [`downmix`] folds from; 1 and 2 fold to nothing.
1631 enum SymDecoder {1660 enum SymDecoder {
1632- Sym(Box<dyn AudioDecoder>, bool),1661+ Sym(Box<dyn AudioDecoder>, usize),
1633 /// Boxed because the decoder carries its own IMDCT tables and this enum is1662 /// Boxed because the decoder carries its own IMDCT tables and this enum is
1634 /// moved into the worker.1663 /// moved into the worker.
1635- Aac(Box<rusty_aac::AacDecoder>, bool),1664+ Aac(Box<rusty_aac::AacDecoder>, usize),
1636- /// Every Opus track, mono to 5.1: one multistream decoder -- the streams of1665+ /// Every Opus track, mono to 7.1: one multistream decoder -- the streams of
1637 /// a packet, the channel mapping table and the routing between them are all1666 /// a packet, the channel mapping table and the routing between them are all
1638- /// its business -- and the same fold flag.1667+ /// its business -- and the same width.
1639- Opus(Box<ruopus::MultistreamDecoder>, bool),1668+ Opus(Box<ruopus::MultistreamDecoder>, usize),
1640 }1669 }
1641 1670
1642 impl SymDecoder {1671 impl SymDecoder {
1643 fn decode(&mut self, packet: &Packet, out: &mut Vec<f32>) -> crate::Result<()> {1672 fn decode(&mut self, packet: &Packet, out: &mut Vec<f32>) -> crate::Result<()> {
1644 match self {1673 match self {
1645- Self::Sym(decoder, fold) => {1674+ Self::Sym(decoder, from) => {
1646 decoder.decode(packet)?.copy_to_vec_interleaved::<f32>(out);1675 decoder.decode(packet)?.copy_to_vec_interleaved::<f32>(out);
1647- fold_5_1(out, *fold);1676+ downmix(out, *from);
1648 }1677 }
1649- Self::Aac(decoder, fold) => {1678+ Self::Aac(decoder, from) => {
1650 let pcm = decoder1679 let pcm = decoder
1651 .decode(&packet.data, None)1680 .decode(&packet.data, None)
1652 .map_err(|e| format!("AAC decode failed: {e}"))?;1681 .map_err(|e| format!("AAC decode failed: {e}"))?;
1653 *out = pcm.samples;1682 *out = pcm.samples;
1654- fold_5_1(out, *fold);1683+ downmix(out, *from);
1655 }1684 }
1656- Self::Opus(decoder, fold) => {1685+ Self::Opus(decoder, from) => {
1657 *out = decoder1686 *out = decoder
1658 .decode_packet(&packet.data)1687 .decode_packet(&packet.data)
1659 .map_err(|e| format!("Opus decode failed: {e}"))?;1688 .map_err(|e| format!("Opus decode failed: {e}"))?;
1660 // The encoder delay is not dropped here: it is this track's1689 // The encoder delay is not dropped here: it is this track's
1661 // priming ([`SymTrack::open_inner`]), which the window rules1690 // priming ([`SymTrack::open_inner`]), which the window rules
1662 // subtract once for the whole segment rather than per packet.1691 // subtract once for the whole segment rather than per packet.
1663- vorbis_to_film_order(out, *fold);1692+ vorbis_to_film_order(out, *from);
1664- fold_5_1(out, *fold);1693+ downmix(out, *from);
1665 }1694 }
1666 }1695 }
1667 Ok(())1696 Ok(())
1668 }1697 }
1669 }1698 }
1670 1699
1700+/// The decoder an AAC track of `from` channels needs: symphonia's own refuses
1701+/// anything wider than stereo outright (`aac/mod.rs:93`, "aac: aac too
1702+/// complex"), which is exactly the 5.1 and 7.1 tracks of a film, so those go to
1703+/// `rusty_aac` instead -- the same routing [`SymTrack::decoder`] does for a
1704+/// Matroska file, asked once here so an mp4's multichannel track takes it too.
1705+fn aac_decoder(params: &AudioCodecParameters, from: usize) -> crate::Result<SymDecoder> {
1706+ if from > 2 {
1707+ let asc = params
1708+ .extra_data
1709+ .as_deref()
1710+ .ok_or("a multichannel AAC track with no AudioSpecificConfig")?;
1711+ let decoder = rusty_aac::AacDecoder::with_config_bytes(asc)
1712+ .map_err(|e| format!("multichannel AAC decoder init failed: {e}"))?;
1713+ return Ok(SymDecoder::Aac(Box::new(decoder), from));
1714+ }
1715+ Ok(SymDecoder::Sym(
1716+ Box::new(AacDecoder::try_new(params, &AudioDecoderOptions::default())?),
1717+ from,
1718+ ))
1719+}
1720+
1671 /// The encoder delay of an Opus track, in samples at 48 kHz: bytes 10 and 11 of1721 /// The encoder delay of an Opus track, in samples at 48 kHz: bytes 10 and 11 of
1672 /// `OpusHead`, little-endian. Zero for a track whose header is missing or too1722 /// `OpusHead`, little-endian. Zero for a track whose header is missing or too
1673 /// short to hold one -- there is nothing to subtract that we can trust.1723 /// 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
1730 Ok((streams, coupled, mapping))1780 Ok((streams, coupled, mapping))
1731 }1781 }
1732 1782
1733-/// Opus 5.1 is stored in Vorbis channel order (FL, FC, FR, BL, BR, LFE) and1783+/// Surround Opus is stored in Vorbis channel order (RFC 7845 §5.1.1.2) and
1734-/// [`fold_5_1`] reads the film order every other decoder here hands back (FL, FR,1784+/// [`downmix`] reads the film order every other decoder here hands back. This is
1735-/// FC, LFE, BL, BR). This is that permutation, in place, and only for the 5.11785+/// that permutation, in place, per width: each entry says which *source* channel
1736-/// track the fold is *for*: mono and stereo need none, and every other width is1786+/// the output slot of that index reads. Mono, stereo and quad agree already, and
1737-/// refused by [`Track::channels`] before a packet is ever decoded.1787+/// a width the RFC does not lay out is left alone rather than shuffled by guess.
1738-fn vorbis_to_film_order(samples: &mut [f32], fold: bool) {1788+fn vorbis_to_film_order(samples: &mut [f32], from: usize) {
1739- if !fold {1789+ let order: &[usize] = match from {
1740- return;1790+ 3 => &[0, 2, 1], // FL FC FR
1791+ 5 => &[0, 2, 1, 3, 4], // FL FC FR SL SR
1792+ 6 => &[0, 2, 1, 5, 3, 4], // FL FC FR SL SR LFE
1793+ 7 => &[0, 2, 1, 6, 5, 3, 4], // FL FC FR SL SR BC LFE
1794+ 8 => &[0, 2, 1, 7, 5, 6, 3, 4], // FL FC FR SL SR BL BR LFE
1795+ _ => return,
1796+ };
1797+ let mut frame = [0.0f32; 8];
1798+ for chunk in samples.chunks_exact_mut(from) {
1799+ frame[..from].copy_from_slice(chunk);
1800+ for (out, &src) in chunk.iter_mut().zip(order) {
1801+ *out = frame[src];
1802+ }
1741 }1803 }
1742- for frame in samples.chunks_exact_mut(6) {1804+}
1743- let [fl, fc, fr, bl, br, lfe] = <[f32; 6]>::try_from(&frame[..]).expect("a 5.1 frame");1805+
1744- frame.copy_from_slice(&[fl, fr, fc, lfe, bl, br]);1806+/// What each channel of a `from`-wide film-order layout contributes to the left
1807+/// and the right of a stereo fold. ITU-R BS.775: a front channel keeps its own
1808+/// side, the centre and the back centre go to both at -3 dB, a surround joins
1809+/// its own side at -3 dB, and the LFE is dropped -- it carries no programme a
1810+/// stereo pair could put anywhere, and neither ffmpeg's default downmix nor any
1811+/// player's puts it there.
1812+///
1813+/// The film order is FL, FR, FC, LFE, BL, BR, SL, SR, which is what symphonia's
1814+/// decoders and `rusty_aac` both hand back (the latter reorders AAC's own
1815+/// C, L, R, Ls, Rs, LFE element order into it: `decode.rs:779`) and what the AC-3
1816+/// decoder's own passthrough uses.
1817+///
1818+/// ponytail: a width past 7.1 (22.2, ambisonics) keeps its front pair and drops
1819+/// the rest -- no table here places those, and inventing one silently would be
1820+/// worse than a fold that is merely narrow. Upgrade path is one more arm.
1821+fn fold_coeffs(from: usize) -> Vec<(f32, f32)> {
1822+ const C: f32 = std::f32::consts::FRAC_1_SQRT_2;
1823+ const L: (f32, f32) = (1.0, 0.0);
1824+ const R: (f32, f32) = (0.0, 1.0);
1825+ const M: (f32, f32) = (C, C);
1826+ const SL: (f32, f32) = (C, 0.0);
1827+ const SR: (f32, f32) = (0.0, C);
1828+ const X: (f32, f32) = (0.0, 0.0);
1829+ match from {
1830+ 3 => vec![L, R, X], // L R LFE (the 2.1 passthrough)
1831+ 4 => vec![L, R, SL, SR], // FL FR BL BR
1832+ 5 => vec![L, R, M, SL, SR], // FL FR FC BL BR
1833+ 6 => vec![L, R, M, X, SL, SR], // 5.1
1834+ 7 => vec![L, R, M, X, M, SL, SR], // FL FR FC LFE BC SL SR
1835+ 8 => vec![L, R, M, X, SL, SR, SL, SR], // 7.1
1836+ n => (0..n).map(|c| [L, R][usize::from(c > 0)]).collect(),
1745 }1837 }
1746 }1838 }
1747 1839
1748-/// 5.1 down to stereo, in place. ITU-R BS.775: the centre and the surround of1840+/// Anything wider than a stereo pair down to one, in place -- `from` is the
1749-/// each side join that side at -3 dB, and the LFE is dropped -- it carries no1841+/// channel count the decoder actually emitted, and 1 or 2 is not touched at all.
1750-/// programme a stereo pair could put anywhere. Both outputs are divided by the1842+/// This is what makes a 5.1 or 7.1 film an ordinary stereo source on the
1751-/// sum of their own coefficients, so a source at full scale cannot come out1843+/// timeline instead of an import refusal.
1752-/// clipped; that is what every player does by default.
1753 ///1844 ///
1754-/// The layout is FL, FR, FC, LFE, BL, BR, which is what symphonia's decoders1845+/// Both outputs are divided by the sum of their own coefficients
1755-/// and `rusty_aac` both hand back (the latter reorders AAC's own C, L, R, Ls,1846+/// ([`fold_coeffs`]), so a source at full scale cannot come out clipped.
1756-/// Rs, LFE element order into it: `decode.rs:779`).
1757 ///1847 ///
1758-/// ponytail: that normalisation costs 7.7 dB against what ffmpeg's `-ac 2` hands1848+/// ponytail: that normalisation costs 7.7 dB at 5.1 (9.9 at 7.1) against what
1759-/// out, which does not normalise and can overload -- so a film plays quieter1849+/// ffmpeg's `-ac 2` hands out, which does not normalise and can overload -- so a
1760-/// here than in a player beside it. It is the loudness the AC-3 5.1 path already1850+/// film plays quieter here than in a player beside it. It is the loudness the
1761-/// has (measured within 1.3 dB), so the two agree; the upgrade path is a1851+/// AC-3 5.1 path already has (measured within 1.3 dB), so the two agree; the
1762-/// limiter on the output, at which point the coefficients can go back to 1.0.1852+/// upgrade path is a limiter on the output, at which point the coefficients can
1763-fn fold_5_1(samples: &mut Vec<f32>, fold: bool) {1853+/// go back to 1.0.
1764- if !fold {1854+fn downmix(samples: &mut Vec<f32>, from: usize) {
1855+ if from < 3 {
1765 return;1856 return;
1766 }1857 }
1767- const CENTRE: f32 = std::f32::consts::FRAC_1_SQRT_2;1858+ let coeffs = fold_coeffs(from);
1768- const NORM: f32 = 1.0 / (1.0 + 2.0 * CENTRE);1859+ let (left, right) = coeffs
1769- for frame in 0..samples.len() / 6 {1860+ .iter()
1770- let [fl, fr, fc, _lfe, bl, br] = <[f32; 6]>::try_from(&samples[frame * 6..frame * 6 + 6])1861+ .fold((0.0f32, 0.0f32), |(l, r), c| (l + c.0, r + c.1));
1771- .expect("six samples of a 5.1 frame");1862+ // Never a boost: a layout with nothing on one side stays where it is.
1772- samples[2 * frame] = (fl + CENTRE * (fc + bl)) * NORM;1863+ let (left, right) = (1.0 / left.max(1.0), 1.0 / right.max(1.0));
1773- samples[2 * frame + 1] = (fr + CENTRE * (fc + br)) * NORM;1864+ for frame in 0..samples.len() / from {
1774- }1865+ let (mut l, mut r) = (0.0, 0.0);
1775- samples.truncate(samples.len() / 6 * 2);1866+ for (c, &(cl, cr)) in coeffs.iter().enumerate() {
1867+ let sample = samples[frame * from + c];
1868+ l += cl * sample;
1869+ r += cr * sample;
1870+ }
1871+ samples[2 * frame] = l * left;
1872+ samples[2 * frame + 1] = r * right;
1873+ }
1874+ samples.truncate(samples.len() / from * 2);
1776 }1875 }
1777 1876
1778 /// One source's AC-3 track: the same mp4 sample tables the AAC track is read1877 /// One source's AC-3 track: the same mp4 sample tables the AAC track is read
@@ -2142,16 +2241,20 @@ impl AacTrack {
2142 Ok(Some(this))2241 Ok(Some(this))
2143 }2242 }
2144 2243
2145- /// Channel count. `AacDecoder` only does mono and stereo, so anything else2244+ /// What reaches the timeline: mono, or the stereo everything wider is folded
2146- /// is refused here rather than one packet at a time.2245+ /// to by [`downmix`] at the decoder's door.
2147- fn channels(&self) -> crate::Result<u16> {2246+ fn channels(&self) -> u16 {
2148 match self.config {2247 match self.config {
2149- ChannelConfig::Mono => Ok(1),2248+ ChannelConfig::Mono => 1,
2150- ChannelConfig::Stereo => Ok(2),2249+ _ => 2,
2151- other => Err(format!("unsupported channel layout: {other:?} (max stereo)").into()),
2152 }2250 }
2153 }2251 }
2154 2252
2253+ /// What the decoder emits, which is what the fold reads.
2254+ fn source_channels(&self) -> usize {
2255+ usize::from(channel_count(self.config).max(1))
2256+ }
2257+
2155 fn track_params(&self) -> AacTrackParams {2258 fn track_params(&self) -> AacTrackParams {
2156 AacTrackParams {2259 AacTrackParams {
2157 freq_index: self.freq_index,2260 freq_index: self.freq_index,
@@ -2475,6 +2578,15 @@ impl Segment {
2475 /// starts one clean and drops it at the end, which is what makes a seek a reset2578 /// starts one clean and drops it at the end, which is what makes a seek a reset
2476 /// for free -- exactly as the equalizer's state does.2579 /// for free -- exactly as the equalizer's state does.
2477 ///2580 ///
2581+/// It is also what makes a file written at another sample rate playable at all:
2582+/// the step is the clip's speed *times* the source rate over the timeline's, so
2583+/// 48 kHz read onto a 44.1 kHz timeline is one resampler, not two, and the pitch
2584+/// is preserved because the frames are read at the ratio of the rates rather
2585+/// than dropped. Linear interpolation is what a speed change already uses here
2586+/// -- for a 48:44.1 ratio its worst-case image lands ~40 dB down and the
2587+/// alternative is a windowed-sinc kernel and a new state machine for a
2588+/// conversion that is not the audible risk in this path.
2589+///
2478 /// `owed` is what the timeline gives the segment, in frames per channel:2590 /// `owed` is what the timeline gives the segment, in frames per channel:
2479 /// resampling resolves to whole samples and a clip's own window resolves to2591 /// resampling resolves to whole samples and a clip's own window resolves to
2480 /// whole *source* frames, so the two miss each other by a sample or two per2592 /// whole *source* frames, so the two miss each other by a sample or two per
@@ -2489,11 +2601,18 @@ struct Resample {
2489 pos: f64,2601 pos: f64,
2490 /// The last frame of the buffer before this one, one sample per channel.2602 /// The last frame of the buffer before this one, one sample per channel.
2491 tail: Vec<f32>,2603 tail: Vec<f32>,
2492- /// Output frames per channel still to be emitted for this segment.2604+ /// Output frames per channel still to be emitted for this segment, or
2605+ /// [`Resample::UNBOUNDED`] for a window with no end of its own -- what
2606+ /// [`AudioSession::open_at`] asks for, where the source running out is the
2607+ /// end and there is no shortfall to pad.
2493 owed: u64,2608 owed: u64,
2494 }2609 }
2495 2610
2496 impl Resample {2611 impl Resample {
2612+ /// "As many as the source has": a segment ending at `f64::INFINITY` owes the
2613+ /// timeline nothing it did not decode.
2614+ const UNBOUNDED: u64 = u64::MAX;
2615+
2497 fn new(step: f64, owed: u64) -> Self {2616 fn new(step: f64, owed: u64) -> Self {
2498 Self {2617 Self {
2499 step,2618 step,
@@ -2536,7 +2655,9 @@ impl Resample {
2536 self.tail.clear();2655 self.tail.clear();
2537 self.tail.extend_from_slice(&buf[(frames - 1) * channels..]);2656 self.tail.extend_from_slice(&buf[(frames - 1) * channels..]);
2538 self.pos -= frames as f64;2657 self.pos -= frames as f64;
2539- self.owed -= (out.len() / channels) as u64;2658+ if self.owed != Self::UNBOUNDED {
2659+ self.owed -= (out.len() / channels) as u64;
2660+ }
2540 *buf = out;2661 *buf = out;
2541 }2662 }
2542 2663
@@ -2544,6 +2665,9 @@ impl Resample {
2544 /// timeline did -- a rounding frame or two, or a clip whose file is shorter2665 /// timeline did -- a rounding frame or two, or a clip whose file is shorter
2545 /// than the edit says. `false` means the consumer went away.2666 /// than the edit says. `false` means the consumer went away.
2546 fn flush(&mut self, channels: usize, timeline: &mut u64, tx: &SyncSender<AudioChunk>) -> bool {2667 fn flush(&mut self, channels: usize, timeline: &mut u64, tx: &SyncSender<AudioChunk>) -> bool {
2668+ if self.owed == Self::UNBOUNDED {
2669+ return true; // nothing was promised, so nothing is short
2670+ }
2547 while self.owed > 0 {2671 while self.owed > 0 {
2548 let frames = self.owed.min(u64::from(SAMPLES_PER_PACKET));2672 let frames = self.owed.min(u64::from(SAMPLES_PER_PACKET));
2549 let chunk = AudioChunk {2673 let chunk = AudioChunk {
@@ -2780,8 +2904,7 @@ fn run(mut w: Worker) {
2780 }2904 }
2781 Track::Aac(track) => track,2905 Track::Aac(track) => track,
2782 };2906 };
2783- let mut decoder = match AacDecoder::try_new(&track.params, &AudioDecoderOptions::default())2907+ let mut decoder = match aac_decoder(&track.params, track.source_channels()) {
2784- {
2785 Ok(decoder) => decoder,2908 Ok(decoder) => decoder,
2786 Err(e) => {2909 Err(e) => {
2787 eprintln!("audio decoder init failed: {e}");2910 eprintln!("audio decoder init failed: {e}");
@@ -2808,14 +2931,10 @@ fn run(mut w: Worker) {
2808 units::Duration::new(u64::from(sample.duration)),2931 units::Duration::new(u64::from(sample.duration)),
2809 &sample.bytes[..],2932 &sample.bytes[..],
2810 );2933 );
2811- let buf = match decoder.decode(&packet) {2934+ if let Err(e) = decoder.decode(&packet, &mut interleaved) {
2812- Ok(buf) => buf,2935+ eprintln!("audio decode error at sample {id}: {e}");
2813- Err(e) => {2936+ break;
2814- eprintln!("audio decode error at sample {id}: {e}");2937+ }
2815- break;
2816- }
2817- };
2818- buf.copy_to_vec_interleaved::<f32>(&mut interleaved);
2819 let next = pos + (interleaved.len() / channels) as u64;2938 let next = pos + (interleaved.len() / channels) as u64;
2820 if !emit(2939 if !emit(
2821 &mut interleaved,2940 &mut interleaved,
@@ -2956,6 +3075,9 @@ fn run_ac3(
2956 return true;3075 return true;
2957 }3076 }
2958 };3077 };
3078+ // The library's §7.8 downmix already handles everything but its own 2.1
3079+ // passthrough, which comes out at 3 and is folded here like any width.
3080+ downmix(&mut interleaved, usize::from(track.channels));
2959 let next = pos + samples;3081 let next = pos + samples;
2960 if !emit(3082 if !emit(
2961 &mut interleaved,3083 &mut interleaved,
@@ -3016,6 +3138,8 @@ fn run_mkv_ac3(
3016 return true;3138 return true;
3017 }3139 }
3018 };3140 };
3141+ // ...and the 2.1 passthrough folded here, as on the mp4 side.
3142+ downmix(&mut interleaved, usize::from(track.channels));
3019 let next = pos + samples;3143 let next = pos + samples;
3020 if !emit(3144 if !emit(
3021 &mut interleaved,3145 &mut interleaved,
@@ -3109,42 +3233,110 @@ fn run_sym(
3109 3233
3110 #[cfg(test)]3234 #[cfg(test)]
3111 mod tests {3235 mod tests {
3112- use super::{PRE_ROLL, SAMPLES_PER_PACKET, fold_5_1, packet_at, packet_run};3236+ use super::{PRE_ROLL, SAMPLES_PER_PACKET, downmix, packet_at, packet_run, vorbis_to_film_order};
3237+
3238+ const C: f32 = std::f32::consts::FRAC_1_SQRT_2;
3239+
3240+ /// The fold, channel by channel and width by width: each side keeps its own
3241+ /// front channel, takes the centre and its own surrounds at -3 dB, drops the
3242+ /// LFE, and comes out unable to clip a full-scale source. The channel order
3243+ /// is FL, FR, FC, LFE, BL, BR, SL, SR.
3244+ #[test]
3245+ fn a_surround_frame_folds_to_stereo_without_clipping() {
3246+ // Per width: what each channel at full scale, alone, must land as
3247+ // *before* the normalisation that width carries.
3248+ let layouts: [(usize, &[(f32, f32)]); 6] = [
3249+ (3, &[(1.0, 0.0), (0.0, 1.0), (0.0, 0.0)]),
3250+ (4, &[(1.0, 0.0), (0.0, 1.0), (C, 0.0), (0.0, C)]),
3251+ (5, &[(1.0, 0.0), (0.0, 1.0), (C, C), (C, 0.0), (0.0, C)]),
3252+ (
3253+ 6,
3254+ &[(1.0, 0.0), (0.0, 1.0), (C, C), (0.0, 0.0), (C, 0.0), (0.0, C)],
3255+ ),
3256+ (
3257+ 7,
3258+ &[
3259+ (1.0, 0.0),
3260+ (0.0, 1.0),
3261+ (C, C),
3262+ (0.0, 0.0),
3263+ (C, C),
3264+ (C, 0.0),
3265+ (0.0, C),
3266+ ],
3267+ ),
3268+ (
3269+ 8,
3270+ &[
3271+ (1.0, 0.0),
3272+ (0.0, 1.0),
3273+ (C, C),
3274+ (0.0, 0.0),
3275+ (C, 0.0),
3276+ (0.0, C),
3277+ (C, 0.0),
3278+ (0.0, C),
3279+ ],
3280+ ),
3281+ ];
3282+ for (from, want) in layouts {
3283+ let (nl, nr) = want
3284+ .iter()
3285+ .fold((0.0f32, 0.0f32), |(l, r), c| (l + c.0, r + c.1));
3286+ for (channel, &(left, right)) in want.iter().enumerate() {
3287+ let mut frame = vec![0.0f32; from];
3288+ frame[channel] = 1.0;
3289+ downmix(&mut frame, from);
3290+ assert_eq!(frame.len(), 2, "{from} ch: one frame is one stereo frame");
3291+ assert!(
3292+ (frame[0] - left / nl).abs() < 1e-6 && (frame[1] - right / nr).abs() < 1e-6,
3293+ "{from} ch{channel}: {frame:?}, want {left}/{nl} {right}/{nr}"
3294+ );
3295+ }
3296+ // Every channel at once is what a normalised fold exists for.
3297+ let mut loud = vec![1.0f32; from * 2];
3298+ downmix(&mut loud, from);
3299+ assert_eq!(loud.len(), 4, "{from} ch: two frames out of two");
3300+ assert!(
3301+ loud.iter().all(|s| (*s - 1.0).abs() < 1e-6),
3302+ "{from} ch: full scale in, full scale out, never past it: {loud:?}"
3303+ );
3304+ }
3305+ // Mono and stereo are handed over untouched.
3306+ for from in [1, 2] {
3307+ let mut flat = vec![0.5f32, -0.5];
3308+ downmix(&mut flat, from);
3309+ assert_eq!(flat, [0.5, -0.5], "{from} ch is not a fold");
3310+ }
3311+ }
3113 3312
3114- /// The 5.1 fold: each side keeps its own front channel, takes the centre3313+ /// The Vorbis order an Opus surround stream is stored in, into the film
3115- /// and its own surround at -3 dB, drops the LFE, and comes out unable to3314+ /// order the fold reads. Each channel is its own index, so a permutation
3116- /// clip a full-scale source. The channel order is FL, FR, FC, LFE, BL, BR.3315+ /// that drifts is the value that comes out in the wrong slot.
3117 #[test]3316 #[test]
3118- fn five_one_folds_to_stereo_without_clipping() {3317+ fn vorbis_order_becomes_film_order() {
3119- // One frame per channel at full scale, one channel at a time.3318+ // (width, film slot -> the vorbis channel it must hold)
3120- for (channel, (left, right)) in [3319+ for (from, want) in [
3121- (0, (1.0, 0.0)), // FL3320+ (3usize, &[0, 2, 1][..]),
3122- (1, (0.0, 1.0)), // FR3321+ (5, &[0, 2, 1, 3, 4]),
3123- (2, (std::f32::consts::FRAC_1_SQRT_2, std::f32::consts::FRAC_1_SQRT_2)), // FC3322+ (6, &[0, 2, 1, 5, 3, 4]),
3124- (3, (0.0, 0.0)), // LFE, dropped3323+ (7, &[0, 2, 1, 6, 5, 3, 4]),
3125- (4, (std::f32::consts::FRAC_1_SQRT_2, 0.0)), // BL3324+ (8, &[0, 2, 1, 7, 5, 6, 3, 4]),
3126- (5, (0.0, std::f32::consts::FRAC_1_SQRT_2)), // BR
3127 ] {3325 ] {
3128- let mut frame = vec![0.0f32; 6];3326+ // Two frames, so a permutation that reads across the frame boundary
3129- frame[channel] = 1.0;3327+ // shows up as the wrong frame's value.
3130- fold_5_1(&mut frame, true);3328+ let mut samples: Vec<f32> = (0..from * 2).map(|i| i as f32).collect();
3131- let norm = 1.0 / (1.0 + 2.0 * std::f32::consts::FRAC_1_SQRT_2);3329+ vorbis_to_film_order(&mut samples, from);
3132- assert_eq!(frame.len(), 2, "one 5.1 frame is one stereo frame");3330+ let got: Vec<usize> = samples[..from].iter().map(|&s| s as usize).collect();
3133- assert!((frame[0] - left * norm).abs() < 1e-6, "ch{channel}: {frame:?}");3331+ assert_eq!(got, want, "{from} ch, first frame");
3134- assert!((frame[1] - right * norm).abs() < 1e-6, "ch{channel}: {frame:?}");3332+ let second: Vec<usize> = samples[from..].iter().map(|&s| s as usize - from).collect();
3135- }3333+ assert_eq!(second, want, "{from} ch, second frame");
3136- // Every channel at once is what a normalised fold exists for.3334+ }
3137- let mut loud = vec![1.0f32; 12];3335+ // 7.1's LFE is the last vorbis channel and the fourth film one.
3138- fold_5_1(&mut loud, true);3336+ let mut lfe = vec![0.0f32; 8];
3139- assert_eq!(loud.len(), 4);3337+ lfe[7] = 1.0;
3140- assert!(3338+ vorbis_to_film_order(&mut lfe, 8);
3141- loud.iter().all(|s| (*s - 1.0).abs() < 1e-6),3339+ assert_eq!(lfe[3], 1.0, "the LFE lands where the fold drops it: {lfe:?}");
3142- "full scale in, full scale out, never past it: {loud:?}"
3143- );
3144- // A track that is not 5.1 is handed over untouched.
3145- let mut stereo = vec![0.5f32, -0.5];
3146- fold_5_1(&mut stereo, false);
3147- assert_eq!(stereo, [0.5, -0.5]);
3148 }3340 }
3149 3341
3150 /// A real AAC track: one stts entry, N packets of 1024.3342 /// A real AAC track: one stts entry, N packets of 1024.
crates/engine/src/export.rsmodified+2 -1
@@ -1271,7 +1271,8 @@ fn encode_audio(
1271 params: crate::AacTrackParams {1271 params: crate::AacTrackParams {
1272 freq_index,1272 freq_index,
1273 // 1 and 2 are the ISO channel configurations for mono and stereo,1273 // 1 and 2 are the ISO channel configurations for mono and stereo,
1274- // and the opener refuses anything wider than stereo already.1274+ // and what the opener hands the timeline is one of those whatever
1275+ // the source carried ([`crate::audio::downmix`]).
1275 chan_conf: audio.channels.max(1) as u8,1276 chan_conf: audio.channels.max(1) as u8,
1276 sample_rate: audio.sample_rate,1277 sample_rate: audio.sample_rate,
1277 },1278 },
crates/engine/src/playback.rsmodified+17 -12
@@ -1881,9 +1881,9 @@ impl PlaybackSession {
1881 /// Refused, changing nothing, unless that stream can join *this* timeline:1881 /// Refused, changing nothing, unless that stream can join *this* timeline:
1882 /// same audio parameters as the first source, in the same words1882 /// same audio parameters as the first source, in the same words
1883 /// [`import`](Self::import) refuses a file with. One output device and one1883 /// [`import`](Self::import) refuses a file with. One output device and one
1884- /// copied AAC track mean one set of audio parameters for the whole1884+ /// copied AAC track mean one *layout* for the whole timeline, so a mono
1885- /// timeline, so a 22 kHz mono track cannot join a 44.1 kHz stereo one --1885+ /// track cannot join a stereo one. Its sample rate may be its own: the
1886- /// there is no resampler here to make one rate of two.1886+ /// segment's resampler conforms it at the decoder's door.
1887 /// A front-end greys such a row out; this is the backstop that keeps a1887 /// A front-end greys such a row out; this is the backstop that keeps a
1888 /// stale one from making the whole timeline silent.1888 /// stale one from making the whole timeline silent.
1889 ///1889 ///
@@ -2650,16 +2650,18 @@ fn matches_timeline(
2650 }2650 }
2651 2651
2652 /// Whether a candidate's audio may join a timeline whose first source probes as2652 /// Whether a candidate's audio may join a timeline whose first source probes as
2653-/// `first`: same rate, same layout -- or no audio of its own at all, which is2653+/// `first`: same layout -- or no audio of its own at all, which is silence over
2654-/// silence over the clip's span and agrees with everything. One output device2654+/// the clip's span and agrees with everything. One output device and one
2655-/// and one exported track is all there is, and no resampler.2655+/// exported track is all there is, so one width; the *rate* is conformed rather
2656+/// than matched ([`crate::audio::Resample`]), which is why it is not asked
2657+/// about here.
2656 ///2658 ///
2657 /// The audio half of [`matches_timeline`], which a stream placed on its own2659 /// The audio half of [`matches_timeline`], which a stream placed on its own
2658 /// ([`PlaybackSession::place_stream_at`]) has to pass while the picture it2660 /// ([`PlaybackSession::place_stream_at`]) has to pass while the picture it
2659 /// comes with is already on the timeline.2661 /// comes with is already on the timeline.
2660 ///2662 ///
2661 /// The format itself is deliberately *not* part of this: an mp3 that agrees on2663 /// The format itself is deliberately *not* part of this: an mp3 that agrees on
2662-/// rate and layout plays alongside a timeline of mp4s perfectly well. What it2664+/// layout plays alongside a timeline of mp4s perfectly well. What it
2663 /// cannot do is be copied into an export, which is a refusal of its own, at2665 /// cannot do is be copied into an export, which is a refusal of its own, at
2664 /// export time (`AudioSession::copy_multi_streams`).2666 /// export time (`AudioSession::copy_multi_streams`).
2665 /// What a timeline's audio is held to: the probe of the first source that could2667 /// 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> {
2695 }2697 }
2696 2698
2697 fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::Result<()> {2699 fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::Result<()> {
2698- // Whole-probe equality: rate and layout, which the audio worker holds every2700+ // The layout, which the audio worker holds every source to anyway -- and not
2699- // source to anyway. Both silent is a match.2701+ // the rate any more: a file written at another one is resampled to the
2702+ // timeline's at the decoder's door ([`crate::audio::Resample`]), exactly as
2703+ // a file shot at another frame rate is read through [`Rate`]. Both silent is
2704+ // a match.
2700 let probe = AudioSession::probe(&source.path, source.audio_stream)?;2705 let probe = AudioSession::probe(&source.path, source.audio_stream)?;
2701- if probe == *first {2706+ if probe.map(|p| p.channels) == first.map(|p| p.channels) {
2702 return Ok(());2707 return Ok(());
2703 }2708 }
2704 // ...and a *silent* file joins whatever the timeline is: it contributes2709 // ...and a *silent* file joins whatever the timeline is: it contributes
@@ -2712,8 +2717,8 @@ fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::R
2712 Err(match first {2717 Err(match first {
2713 None => "the file has audio, the timeline is silent".to_string(),2718 None => "the file has audio, the timeline is silent".to_string(),
2714 Some(b) => format!(2719 Some(b) => format!(
2715- "audio {} Hz {} ch does not match the timeline's {} Hz {} ch",2720+ "audio {} ch does not match the timeline's {} ch",
2716- probe.sample_rate, probe.channels, b.sample_rate, b.channels2721+ probe.channels, b.channels
2717 ),2722 ),
2718 }2723 }
2719 .into())2724 .into())
crates/engine/tests/audio_decode.rsmodified+199 -1
@@ -1,5 +1,5 @@
1 use std::path::PathBuf;1 use std::path::PathBuf;
2-use std::time::Instant;2+use std::time::{Duration, Instant};
3 3
4 use engine::audio::AudioSession;4 use engine::audio::AudioSession;
5 use engine::scratch::Scratch;5 use engine::scratch::Scratch;
@@ -245,6 +245,204 @@ fn opus_decodes_from_every_container_and_51_comes_down_in_order() {
245 }245 }
246 }246 }
247 247
248+/// The amplitude of an `hz` sine inside `samples`, by Goertzel. The window is a
249+/// whole second at 48 kHz, so every frequency this asks about is an exact bin
250+/// and there is no leakage to correct for; a real sine of amplitude A puts
251+/// `A * N / 2` in its bin.
252+fn amplitude(samples: &[f32], hz: f64) -> f64 {
253+ let n = samples.len() as f64;
254+ let w = 2.0 * std::f64::consts::PI * hz / 48_000.0;
255+ let coeff = 2.0 * w.cos();
256+ let (mut s1, mut s2) = (0.0, 0.0);
257+ for &sample in samples {
258+ let s0 = f64::from(sample) + coeff * s1 - s2;
259+ s2 = s1;
260+ s1 = s0;
261+ }
262+ 2.0 * (s1 * s1 + s2 * s2 - coeff * s1 * s2).sqrt() / n
263+}
264+
265+/// **7.1 Opus**, the widest layout the fold has a table for and the one the
266+/// largest film carries: five Opus streams, three coupled, arriving on the
267+/// timeline as an ordinary stereo source instead of the import refusal it used
268+/// to be ("unsupported channel layout: 8 channels (max stereo)").
269+///
270+/// The fixture puts one frequency in each of four channels and silence in the
271+/// rest (`gen_fixtures.sh`), so the whole downmix is one measurement: 440 in FL
272+/// is left only, 880 in FC is both sides at -3 dB, 1320 in the LFE must be gone
273+/// entirely, and 1760 in SR is right only. Every coefficient and the whole
274+/// Vorbis-to-film permutation at this width fail visibly here.
275+#[test]
276+fn seven_one_opus_folds_to_the_stereo_the_timeline_carries() {
277+ let path = asset("test_opus_71.mka");
278+ let streams = AudioSession::probe_streams(&path).expect("streams");
279+ assert_eq!(streams.len(), 1);
280+ assert!(streams[0].decodable, "a 7.1 row is not greyed out any more");
281+ assert_eq!(streams[0].channels, 2, "what reaches the timeline is a pair");
282+
283+ let (meta, rx) = AudioSession::open(&path)
284+ .expect("open")
285+ .expect("7.1 Opus decodes now");
286+ assert_eq!((meta.sample_rate, meta.channels), (48000, 2));
287+ let samples: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect();
288+ assert!(
289+ samples.iter().all(|s| s.abs() <= 1.0),
290+ "the fold must not leave the device's range"
291+ );
292+ // One whole second out of the middle, past any codec fade-in.
293+ let second = |channel: usize| -> Vec<f32> {
294+ samples[channel..]
295+ .iter()
296+ .step_by(2)
297+ .skip(48_000)
298+ .take(48_000)
299+ .copied()
300+ .collect()
301+ };
302+ // 1 + 3 * (-3 dB): FL/FR keep their side, FC and both surround pairs are the
303+ // three that join it. Nothing may come out above full scale, which is what
304+ // dividing by the coefficient sum buys.
305+ let norm = 1.0 + 3.0 * f64::from(std::f32::consts::FRAC_1_SQRT_2);
306+ let c = f64::from(std::f32::consts::FRAC_1_SQRT_2);
307+ let (left, right) = (second(0), second(1));
308+ // FL is the one channel that keeps its side at unity, so what it comes out
309+ // as names the tone the fixture was written with -- `sine` peaks at 0.125 in
310+ // ffmpeg, and reading that off the fold rather than hard-coding it keeps the
311+ // coefficients below the claim instead of the generator's level. A fold that
312+ // lost FL, or scaled the pair, leaves this band.
313+ let source = amplitude(&left, 440.0) * norm;
314+ assert!(
315+ (0.10..0.15).contains(&source),
316+ "FL came out as a {source:.4} tone; the fixture's is 0.125"
317+ );
318+ for (side, cut, want) in [
319+ ("left", &left, [(440.0, 1.0), (880.0, c), (1320.0, 0.0), (1760.0, 0.0)]),
320+ ("right", &right, [(440.0, 0.0), (880.0, c), (1320.0, 0.0), (1760.0, c)]),
321+ ] {
322+ for (hz, coeff) in want {
323+ let got = amplitude(cut, hz);
324+ let expect = source * coeff / norm;
325+ match coeff {
326+ // The LFE, and the channels this side has none of: what is left
327+ // is codec noise and bleed, an order below the quietest tone.
328+ 0.0 => assert!(
329+ got < 0.1 * source / norm,
330+ "{side}: {hz} Hz came through at {got:.4}, and nothing there should"
331+ ),
332+ _ => assert!(
333+ (got - expect).abs() < 0.15 * expect,
334+ "{side}: {hz} Hz at {got:.4}, want {expect:.4} +/-15%"
335+ ),
336+ }
337+ }
338+ }
339+}
340+
341+/// A real 7.1 remux, which is the file this whole change exists for: 12.9 GB of
342+/// 2160p AV1 with an 8-channel Opus track that used to come back "IMPORT FAILED:
343+/// unsupported channel layout: 8 channels (max stereo)" and take the picture
344+/// with it.
345+///
346+/// Skipped, not failed, on a machine that does not have the film: a fixture
347+/// cannot stand in for the claim (the refusal was measured on *this* file) and a
348+/// test that cannot make it must say nothing rather than something false.
349+#[test]
350+fn his_seven_one_remux_imports_and_plays() {
351+ let film = PathBuf::from(
352+ "/path/to/a-real-av1-opus-7.1-film.mkv",
353+ );
354+ if !film.exists() {
355+ eprintln!("skipped: {} is not on this machine", film.display());
356+ return;
357+ }
358+ // The import gate itself: this is the call whose `Err` the app printed.
359+ let probe = AudioSession::probe(&film, 0)
360+ .expect("the 7.1 track no longer refuses the import")
361+ .expect("the film has audio");
362+ assert_eq!(
363+ (probe.sample_rate, probe.channels),
364+ (48_000, 2),
365+ "7.1 reaches the timeline as a pair"
366+ );
367+ // ...and every one of its three tracks is offered, none greyed out.
368+ let streams = AudioSession::probe_streams(&film).expect("streams");
369+ assert_eq!(streams.len(), 3, "7.1 plus two 5.1 commentary tracks");
370+ assert!(
371+ streams.iter().all(|s| s.decodable && s.channels == 2),
372+ "{streams:?}"
373+ );
374+
375+ // Ten seconds out of the middle of the film, through the very worker
376+ // playback and a WAV export both feed from -- with sound on *both* sides,
377+ // which a fold that dropped half the layout would not have.
378+ let (meta, rx) = AudioSession::open_segments(&film, &[(600.0, 610.0)])
379+ .expect("open")
380+ .expect("the film has audio");
381+ assert_eq!((meta.sample_rate, meta.channels), (48_000, 2));
382+ let samples: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect();
383+ let secs = (samples.len() / 2) as f64 / 48_000.0;
384+ assert!((9.9..10.1).contains(&secs), "{secs:.3} s decoded, want 10");
385+ assert!(
386+ samples.iter().all(|s| s.abs() <= 1.0),
387+ "the fold must not leave the device's range"
388+ );
389+ for (side, channel) in [("left", 0), ("right", 1)] {
390+ let one: Vec<f64> = samples[channel..].iter().step_by(2).map(|s| f64::from(*s)).collect();
391+ let rms = (one.iter().map(|s| s * s).sum::<f64>() / one.len() as f64).sqrt();
392+ assert!(rms > 0.001, "{side} came out silent: RMS {rms:.6}");
393+ eprintln!("{side}: RMS {rms:.6} over {secs:.2}s from 600s");
394+ }
395+
396+ // ...and the whole way out: the file on a timeline, trimmed to ten seconds,
397+ // written as a WAV by the export path and read back through this engine's
398+ // own reader. A session open is what the app's Import does, so a picture
399+ // this size failing to open would fail here rather than in use.
400+ let mut session = engine::PlaybackSession::open(&film).expect("the film opens as a timeline");
401+ assert_eq!(
402+ session.audio_disabled_reason(),
403+ None,
404+ "a track that decodes owes no excuse"
405+ );
406+ let frames = (10.0 * session.meta().frame_rate).round() as u32;
407+ for lane in session.lanes() {
408+ session.trim_clip(lane, 0, engine::project::Edge::End, frames);
409+ }
410+ let out = Scratch::file("ve_seven_one", "wav");
411+ let handle = session.export_to_with(
412+ &out,
413+ &engine::export::ExportSettings {
414+ format: engine::export::Format::Wav,
415+ ..Default::default()
416+ },
417+ );
418+ let started = Instant::now();
419+ while !handle.is_finished() {
420+ assert!(started.elapsed() < Duration::from_secs(300), "export hung");
421+ std::thread::sleep(Duration::from_millis(50));
422+ }
423+ handle.result().expect("outcome").expect("the WAV is written");
424+ let (wav, rx) = AudioSession::open(&out)
425+ .expect("the WAV reopens")
426+ .expect("it has sound");
427+ let written: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect();
428+ let channels = usize::from(wav.channels);
429+ assert_eq!(channels, 2, "a stereo WAV out of a 7.1 source");
430+ for (side, channel) in [("left", 0), ("right", 1)] {
431+ let one: Vec<f64> = written[channel..]
432+ .iter()
433+ .step_by(channels)
434+ .map(|s| f64::from(*s))
435+ .collect();
436+ let rms = (one.iter().map(|s| s * s).sum::<f64>() / one.len() as f64).sqrt();
437+ assert!(rms > 0.001, "the exported {side} is silent: RMS {rms:.6}");
438+ eprintln!(
439+ "exported {side}: RMS {rms:.6} over {:.2}s at {} Hz",
440+ one.len() as f64 / f64::from(wav.sample_rate),
441+ wav.sample_rate
442+ );
443+ }
444+}
445+
248 /// The same two ends of the AC-3 path, in **Matroska**: a stereo AC-3 track and446 /// The same two ends of the AC-3 path, in **Matroska**: a stereo AC-3 track and
249 /// a 5.1 E-AC-3 one -- the codec a remux carries and the one the "(AAC only)"447 /// a 5.1 E-AC-3 one -- the codec a remux carries and the one the "(AAC only)"
250 /// refusal used to fire on -- both come out of the blocks, both arrive as the448 /// refusal used to fire on -- both come out of the blocks, both arrive as the
crates/engine/tests/audio_files.rsmodified+54 -15
@@ -172,16 +172,57 @@ fn a_song_joins_a_video_timeline_on_the_audio_lane() {
172 assert!(session.lane_spans_by_source(Lane::A1).len() >= 2);172 assert!(session.lane_spans_by_source(Lane::A1).len() >= 2);
173 }173 }
174 174
175+/// A rate one output device cannot have two of is **converted**, not refused:
176+/// the 48 kHz twin of the tone joins a 44.1 kHz timeline, is placed for the
177+/// seconds it lasts, and comes out at the pitch it was recorded at.
178+///
179+/// The pitch is the whole claim. Reading a 48 kHz file's frames one for one onto
180+/// a 44.1 kHz timeline plays it 8.8% slow and 440 Hz becomes 404 -- which is
181+/// what "it imported" would look like from a length check alone.
175 #[test]182 #[test]
176-fn a_rate_the_device_cannot_mix_is_refused_at_the_door() {183+fn a_rate_the_device_cannot_mix_is_converted_at_the_door() {
177 let mut session = open(asset("test_av.mp4"));184 let mut session = open(asset("test_av.mp4"));
185+ let before = session.timeline_duration();
186+ import_and_place(&mut session, &asset("test_tone_48k.wav"));
187+ assert_eq!(session.sources().len(), 2, "the 48k file is in the library");
188+ assert_eq!(session.lane_clips(Lane::A1).len(), 2, "and on the lane");
189+ // 3 s of tone placed after the video, at the timeline's own rate.
190+ assert!(
191+ (session.timeline_duration() - (before + 3.0)).abs() < 0.05,
192+ "{} s of timeline, want {}",
193+ session.timeline_duration(),
194+ before + 3.0
195+ );
196+
197+ // ...and the samples themselves, straight out of the worker the session
198+ // feeds from: one second of the 48k file, resampled onto a 44.1k timeline.
199+ let sources = [(asset("test_av.mp4"), 0), (asset("test_tone_48k.wav"), 0)];
200+ let (meta, rx) =
201+ AudioSession::open_multi_streams(&sources, &[(Some(1), 0.25, 1.25)]).expect("open").expect("the timeline has sound");
178 assert_eq!(202 assert_eq!(
179- refusal(session.import(&asset("test_tone_48k.wav"))),203+ (meta.sample_rate, meta.channels),
180- "audio 48000 Hz 2 ch does not match the timeline's 44100 Hz 2 ch"204+ (44100, 2),
205+ "the timeline's rate, not the file's"
181 );206 );
182- // Refused means unchanged: no library row, no clip, no length.207+ let samples: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect();
183- assert_eq!(session.sources().len(), 1);208+ let frames = samples.len() / 2;
184- assert_eq!(session.lane_clips(Lane::A1).len(), 1);209+ assert!(
210+ (frames as i64 - 44100).abs() < 64,
211+ "one second of timeline is {frames} frames of 44100"
212+ );
213+ // 440 Hz left, 880 Hz right -- the fixture's own tones, unmoved. Zero
214+ // crossings date them without an FFT: a file read at 1:1 instead of 48:44.1
215+ // would come out at 404 and 808, an 8% miss this 2% band rejects.
216+ for (name, channel, hz) in [("left", 0, 440.0), ("right", 1, 880.0)] {
217+ let side: Vec<f32> = samples[channel..].iter().step_by(2).copied().collect();
218+ let secs = side.len() as f64 / 44100.0;
219+ let crossings = side.windows(2).filter(|p| (p[0] < 0.0) != (p[1] < 0.0)).count() as f64;
220+ let got = crossings / 2.0 / secs;
221+ assert!(
222+ (got - hz).abs() <= 0.02 * hz,
223+ "{name}: {got:.1} Hz out of a {hz} Hz tone -- the resample moved the pitch"
224+ );
225+ }
185 }226 }
186 227
187 /// A song *is* a timeline: it scaffolds the canvas a video would have defined,228 /// 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() {
382 import_and_place(&mut session, &asset("test_av.mp4"));423 import_and_place(&mut session, &asset("test_av.mp4"));
383 assert_eq!(session.lane_clips(Lane::V1).len(), 1, "a picture at last");424 assert_eq!(session.lane_clips(Lane::V1).len(), 1, "a picture at last");
384 assert_eq!(session.lane_clips(Lane::A1).len(), 2);425 assert_eq!(session.lane_clips(Lane::A1).len(), 2);
385- // A sample rate the device cannot have two of is still refused in the426+ // A sample rate the device cannot have two of is no refusal either: it is
386- // timeline's own words...427+ // resampled onto the timeline's, as a frame rate is conformed to the canvas.
387- let e = refusal(session.import(&asset("test_tone_48k.wav")));428+ session
388- assert_eq!(429+ .import(&asset("test_tone_48k.wav"))
389- e,430+ .expect("48 kHz joins a 44.1 kHz timeline");
390- "audio 48000 Hz 2 ch does not match the timeline's 44100 Hz 2 ch"431+ assert_eq!(session.sources().len(), 3);
391- );432+ // ...and a *frame* rate of its own is not a refusal either: the canvas a song
392- assert_eq!(session.sources().len(), 2, "a refusal left a library row");
393- // ...but a *frame* rate of its own is not a refusal: the canvas a song
394 // scaffolds runs at 30 fps and a 25 fps picture joins it at the length it433 // scaffolds runs at 30 fps and a 25 fps picture joins it at the length it
395 // lasts in seconds (50 frames of file, 60 of timeline).434 // lasts in seconds (50 frames of file, 60 of timeline).
396 session435 session
crates/engine/tests/audio_multi.rsmodified+6 -5
@@ -250,11 +250,12 @@ fn the_join_carries_no_second_priming_packet() {
250 }250 }
251 251
252 #[test]252 #[test]
253-fn a_source_that_disagrees_on_rate_or_layout_is_refused() {253+fn a_source_that_disagrees_on_layout_is_refused() {
254- // Import refuses these up front (one output device, one set of parameters);254+ // Import refuses these up front (one output device, one *layout*); the copy
255- // the copy and the decode paths refuse them again rather than mislabel one255+ // and the decode paths refuse them again rather than mislabel one esds for
256- // esds for two different tracks. Stream 1 of the multi-audio fixture is256+ // two different tracks. Stream 1 of the multi-audio fixture is 22.05 kHz
257- // 22.05 kHz mono against the timeline's 44.1 kHz stereo.257+ // mono against the timeline's 44.1 kHz stereo -- its rate is conformed at
258+ // the decoder's door now, its layout is what is left to refuse.
258 let mixed = [(asset("test_av.mp4"), 0), (asset("test_multiaudio.mp4"), 1)];259 let mixed = [(asset("test_av.mp4"), 0), (asset("test_multiaudio.mp4"), 1)];
259 let segs = [(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0)];260 let segs = [(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0)];
260 // (`.err()`, not `unwrap_err`: neither Ok payload is `Debug`.)261 // (`.err()`, not `unwrap_err`: neither Ok payload is `Debug`.)
crates/engine/tests/capability_matrix.rsmodified+3 -0
@@ -103,6 +103,9 @@ fn every_audio_codec_the_refusal_names_really_decodes() {
103 ("test_vp9.webm", "opus in a webm", 1),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.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),105 ("test_opus_51.mka", "5.1 opus in an mka", 2),
106+ // ...and 7.1, the widest layout the fold has a table for and the one
107+ // a real remux carries.
108+ ("test_opus_71.mka", "7.1 opus in an mka", 2),
106 ("test_tone.opus", "a standalone opus", 2),109 ("test_tone.opus", "a standalone opus", 2),
107 ] {110 ] {
108 let probe = AudioSession::probe(asset(file), 0)111 let probe = AudioSession::probe(asset(file), 0)
crates/engine/tests/playback.rsmodified+13 -6
@@ -963,16 +963,23 @@ fn import_refuses_what_does_not_match() {
963 .remove_source(&asset("test_25fps.mp4"), 0)963 .remove_source(&asset("test_25fps.mp4"), 0)
964 .expect("...and the row it made comes back off");964 .expect("...and the row it made comes back off");
965 965
966- // What is still refused, and all that is: one output device means one rate966+ // A sample *rate* of its own is no longer a refusal either: one output
967- // and one layout, and there is no resampler to make two into one.967+ // device means one rate, and the segment's own resampler is what makes two
968+ // into one now ([`engine::audio::Resample`]).
969+ session
970+ .import(&asset("test_tone_48k.wav"))
971+ .expect("48 kHz may join a 44.1 kHz timeline");
972+ session
973+ .remove_source(&asset("test_tone_48k.wav"), 0)
974+ .expect("...and the row it made comes back off");
975+
976+ // What is still refused, and all that is: one output device carries one
977+ // layout, and a mono track is not the stereo pair this timeline plays.
968 let err = session978 let err = session
969 .import(&asset("test_ac3.mp4"))979 .import(&asset("test_ac3.mp4"))
970 .expect_err("a mono track cannot join a stereo timeline")980 .expect_err("a mono track cannot join a stereo timeline")
971 .to_string();981 .to_string();
972- assert_eq!(982+ assert_eq!(err, "audio 1 ch does not match the timeline's 2 ch");
973- err,
974- "audio 44100 Hz 1 ch does not match the timeline's 44100 Hz 2 ch"
975- );
976 983
977 assert!(984 assert!(
978 session.import(&asset("no_such_file.mp4")).is_err(),985 session.import(&asset("no_such_file.mp4")).is_err(),
crates/engine/tests/saveload.rsmodified+11 -8
@@ -79,11 +79,13 @@ fn a_picked_audio_stream_lands_saves_and_comes_back() {
79 let other = copy_in(&dir, "test_multiaudio.mp4");79 let other = copy_in(&dir, "test_multiaudio.mp4");
80 let mut session = PlaybackSession::open(&other).expect("open the fixture");80 let mut session = PlaybackSession::open(&other).expect("open the fixture");
81 session.set_gain(0.0);81 session.set_gain(0.0);
82+ // Its rate would be conformed now; its *layout* is what one output device
83+ // cannot have two of, and the refusal says which.
82 let err = session84 let err = session
83 .place_stream_at(0.0, &other, 1, None)85 .place_stream_at(0.0, &other, 1, None)
84- .expect_err("22.05 kHz mono cannot join a 44.1 kHz stereo timeline")86+ .expect_err("a mono stream cannot join a stereo timeline")
85 .to_string();87 .to_string();
86- assert!(err.contains("22050"), "unhelpful refusal: {err}");88+ assert_eq!(err, "audio 1 ch does not match the timeline's 2 ch");
87 assert!(89 assert!(
88 session90 session
89 .place_stream_at(0.0, &media, 1, None)91 .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() {
742 .expect("a source that stopped matching must not open")744 .expect("a source that stopped matching must not open")
743 .to_string();745 .to_string();
744 // The suffix is `import`'s own refusal, word for word. The substitute is746 // The suffix is `import`'s own refusal, word for word. The substitute is
745- // mono, which is the shape of what is left: one output device means one747+ // mono, which is the shape of what is left: one output device carries one
746- // rate and one layout. A resolution of its own is placed on the project748+ // layout. A resolution of its own is placed on the project canvas, a frame
747- // canvas, a rate of its own is read through `Rate`, a codec of its own749+ // rate of its own is read through `Rate`, a *sample* rate of its own is
748- // opens its own decoder and a file with no sound plays silence -- none of750+ // resampled at the decoder's door, a codec of its own opens its own decoder
749- // those is a refusal any more.751+ // and a file with no sound plays silence -- none of those is a refusal any
752+ // more.
750 assert_eq!(753 assert_eq!(
751 err,754 err,
752 format!(755 format!(
753- "source {}: audio 44100 Hz 1 ch does not match the timeline's 44100 Hz 2 ch",756+ "source {}: audio 1 ch does not match the timeline's 2 ch",
754 dir.join("test_av2.mp4").display()757 dir.join("test_av2.mp4").display()
755 )758 )
756 );759 );
scripts/gen_fixtures.shmodified+14 -0
@@ -475,6 +475,20 @@ ffmpeg -y -f lavfi -i "sine=frequency=440:duration=3:sample_rate=48000" \
475 -f lavfi -i "anullsrc=r=48000:cl=quad:d=3" \475 -f lavfi -i "anullsrc=r=48000:cl=quad:d=3" \
476 -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]" \476 -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]" \
477 -map "[a]" -c:a libopus -b:a 256k assets/test_opus_51.mka477 -map "[a]" -c:a libopus -b:a 256k assets/test_opus_51.mka
478+# ...and **7.1 Opus**, which is a large film's soundtrack in miniature: five
479+# Opus streams, three coupled, and the widest layout the fold has a table for.
480+# One frequency per channel, four of the eight carrying anything, so the whole
481+# downmix is checkable by picking those four out of the folded pair
482+# (`tests/audio_multi.rs`): 440 in FL is left only, 880 in FC is both sides at
483+# -3 dB, 1320 in the LFE must be *gone*, and 1760 in SR is right only. Get the
484+# Vorbis-to-film permutation wrong at this width and every one of those moves.
485+ffmpeg -y -f lavfi -i "sine=frequency=440:duration=3:sample_rate=48000" \
486+ -f lavfi -i "sine=frequency=880:duration=3:sample_rate=48000" \
487+ -f lavfi -i "sine=frequency=1320:duration=3:sample_rate=48000" \
488+ -f lavfi -i "sine=frequency=1760:duration=3:sample_rate=48000" \
489+ -f lavfi -i "anullsrc=r=48000:cl=quad:d=3" \
490+ -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]" \
491+ -map "[a]" -c:a libopus -b:a 320k assets/test_opus_71.mka
478 # Still-image fixture: the source with a picture and no timeline in it. Two492 # Still-image fixture: the source with a picture and no timeline in it. Two
479 # bands rather than one colour, so a test can tell top from bottom (a flipped493 # bands rather than one colour, so a test can tell top from bottom (a flipped
480 # decode) and red from blue (a swapped channel order); 640x360, which is 16:9494 # decode) and red from blue (a swapped channel order); 640x360, which is 16:9