diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 5f40024..7db1f93 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -10706,11 +10706,12 @@ mod tests { // Silent like the engine suite: this opens the real device. session.set_gain(0.0); assert_eq!(session.sources().len(), 1); - // 640x360 would join now (the project canvas places it); this file is - // also silent, and a silent file cannot join a timeline with sound. + // 640x360 joins now (the project canvas places it), and so does a file + // with no sound (it plays silence over its span). What is left is one + // output device: a mono track cannot join a stereo timeline. let refusal = session - .import(&asset("test_mismatch.mp4")) - .expect_err("a silent file must not join a timeline with audio") + .import(&asset("test_ac3.mp4")) + .expect_err("a mono track must not join a stereo timeline") .to_string(); assert!(refusal.contains("audio"), "refusal must name it: {refusal}"); assert_eq!(session.sources().len(), 1, "a refusal added a row"); diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index c891e19..ab4f99e 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -203,10 +203,14 @@ impl AudioSession { /// pause — the master clock counts what the device has been fed, so a hole /// that fed nothing would stall the whole timeline on it. /// + /// A segment naming a source that has **no track** is the same silence: a + /// clip of a silent file is a hole with a picture over it, and the timeline + /// let it in on exactly that footing ([`crate::PlaybackSession::import`]). + /// /// 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 is - /// missing audio or disagrees on rate/layout is an `Err` — import refuses - /// those up front (one timeline, one output device), this is the backstop. + /// 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. pub fn open_multi_segments( sources: &[PathBuf], segs: &[(Option, f64, f64)], @@ -294,11 +298,18 @@ impl AudioSession { first.check_decoder()?; let mut tracks: Vec> = sources.iter().map(|_| None).collect(); + // ...and which of them turned out to have no track at all, so a silent + // source is opened once like any other rather than once per segment + // naming it. + let mut silent: Vec = sources.iter().map(|_| false).collect(); tracks[at] = Some(first); for &(source, ..) in segs { let Some(source) = source else { continue; // a gap opens no file }; + if silent.get(source) == Some(&true) { + continue; + } let slot = tracks .get_mut(source) .ok_or_else(|| format!("segment names source {source} of {}", sources.len()))?; @@ -306,8 +317,14 @@ impl AudioSession { continue; // already opened, and the checks below already ran } let (path, stream) = &sources[source]; - let track = Track::open(path, *stream)? - .ok_or_else(|| format!("source {source} has no audio track"))?; + // A source with no audio track at all is not a failure: its + // segments are silence, exactly as a gap's are, and the slot stays + // empty to say so. That is what a silent clip on an audio lane + // means -- a picture over a hole. + let Some(track) = Track::open(path, *stream)? else { + silent[source] = true; + continue; + }; if (track.sample_rate(), track.channels()?) != (meta.sample_rate, meta.channels) { return Err(format!( "source {source} is {} Hz {} ch, the timeline is {} Hz {} ch", @@ -324,14 +341,15 @@ impl AudioSession { let segments: Vec = segs .iter() - .map(|&(source, start_secs, end_secs)| match source { - Some(source) => tracks[source] - .as_ref() - .expect("opened above") - .segment(source, start_secs, end_secs), - None => Segment::silence( - ((end_secs - start_secs).max(0.0) * f64::from(meta.sample_rate)) as u64, - ), + // A gap, and a source with no track to decode, are the same stretch + // of nothing: as many frames of silence as the window is long. + .map(|&(source, start_secs, end_secs)| { + match source.and_then(|source| Some((source, tracks[source].as_ref()?))) { + Some((source, track)) => track.segment(source, start_secs, end_secs), + None => Segment::silence( + ((end_secs - start_secs).max(0.0) * f64::from(meta.sample_rate)) as u64, + ), + } }) .collect(); // Chunk numbering is continuous across every join, counted from the first @@ -622,7 +640,11 @@ impl AudioSession { decodable: matches!(track.channels, 1 | 2), }]); } - let Ok(track) = SymTrack::open(path) else { + // No audio track lists as the silent source it is; a track that + // will not open at all is an `Err` here, as it is in + // [`Track::open`] -- a listing that quietly came back empty for a + // broken file is how a lane ends up silent with nothing to go on. + let Some(track) = SymTrack::open(path)? else { return Ok(Vec::new()); }; return Ok(vec![StreamInfo { @@ -635,7 +657,7 @@ impl AudioSession { }]); } if crate::is_audio(path) { - let track = SymTrack::open(path)?; + let track = SymTrack::open_required(path)?; return Ok(vec![StreamInfo { index: 0, codec: track.codec.into(), @@ -762,15 +784,18 @@ impl AudioSession { /// half a packet over the whole list however many files it spans, and the /// extra priming packet is still the very first segment's alone. /// - /// Every source must declare the same [`AacTrackParams`]: the copy becomes - /// one output track with one esds. Import refuses a mismatch up front; the - /// check here is the backstop, as is the missing-track `Err`. + /// Every source that *has* a track must declare the same + /// [`AacTrackParams`]: the copy becomes one output track with one esds. + /// Import refuses a mismatch up front; the check here is the backstop. /// /// A segment naming **no** source is a gap, and is copied as that many /// packets of [`silent_packet`] silence — the rounding debt carried through /// it like any other, so the hole occupies its exact duration and the audio /// after it stays in sync with the picture. A gap the track *opens* on gets - /// one silent packet more, which is the priming a reader drops. + /// one silent packet more, which is the priming a reader drops. A segment + /// naming a *silent* source is written the same way: a clip whose file has + /// no audio track is a hole with a picture over it, and the timeline it + /// joined already said so ([`crate::PlaybackSession::import`]). pub fn copy_multi_segments( sources: &[PathBuf], segs: &[(Option, f64, f64)], @@ -789,24 +814,34 @@ impl AudioSession { sources: &[(PathBuf, usize)], segs: &[(Option, f64, f64)], ) -> crate::Result)>> { - let Some(&(Some(first), ..)) = segs.iter().find(|s| s.0.is_some()) else { + // The output track is declared from the first source that has one -- + // not simply the first one named, which may be a silent clip. Such a + // clip defines no rate and no layout; it is written as silence below + // and the track goes on being the audible sources' track. + let mut tracks: Vec>> = sources.iter().map(|_| None).collect(); + let mut first = None; + for &(source, ..) in segs { + let Some(source) = source else { continue }; + if let Some(track) = source_at(&mut tracks, sources, source)? { + first = Some(track.track_params()); + break; + } + } + let Some(params) = first else { return Ok(None); // no segments, or nothing but silence }; - let (path, stream) = sources - .get(first) - .ok_or_else(|| format!("segment names source {first} of {}", sources.len()))?; - let Some(track) = copy_track(path, *stream)? else { - return Ok(None); // silent source, silent export - }; - let params = track.track_params(); - let mut tracks: Vec> = sources.iter().map(|_| None).collect(); - tracks[first] = Some(track); let sample_rate = params.sample_rate; let mut err = 0i64; let mut packets: Vec = Vec::new(); for &(source, start_secs, end_secs) in segs { - let Some(source) = source else { + // A gap, and a clip whose source carries no track, are the same hole + // to write: silence for as long as the window is. + let named = match source { + Some(source) => source_at(&mut tracks, sources, source)?.map(|t| (source, t)), + None => None, + }; + let Some((source, track)) = named else { let ideal = ((end_secs - start_secs).max(0.0) * f64::from(sample_rate)) as i64; let bytes = silent_packet(params.chan_conf)?; // A reader drops the first packet of an AAC track as the @@ -824,7 +859,6 @@ impl AudioSession { } continue; }; - let track = source_at(&mut tracks, sources, source)?; if track.track_params() != params { return Err(format!( "source {source} audio is {:?}, the timeline's is {params:?}", @@ -885,24 +919,25 @@ fn silent_packet(chan_conf: u8) -> crate::Result> { } } -/// The source at `index`, on the stream it names, opened on first use. Sources -/// a segment list never names are never touched: a project's list only grows. +/// The source at `index`, on the stream it names, opened on first use -- and +/// `None` for a source that has no track at all, which the caller writes as +/// silence exactly as it writes a gap. The outer `Option` is "has it been +/// opened", the inner one "was there anything in it", so a silent source is +/// opened once like any other. Sources a segment list never names are never +/// touched: a project's list only grows. fn source_at<'a>( - tracks: &'a mut [Option], + tracks: &'a mut [Option>], sources: &[(PathBuf, usize)], index: usize, -) -> crate::Result<&'a mut AacTrack> { +) -> crate::Result> { let slot = tracks .get_mut(index) .ok_or_else(|| format!("segment names source {index} of {}", sources.len()))?; if slot.is_none() { let (path, stream) = &sources[index]; - *slot = Some( - copy_track(path, *stream)? - .ok_or_else(|| format!("source {index} has no audio track"))?, - ); + *slot = Some(copy_track(path, *stream)?); } - Ok(slot.as_mut().expect("just opened")) + Ok(slot.as_mut().expect("just opened").as_mut()) } /// A source's track for the *copy* path, which needs raw AAC access units. @@ -994,8 +1029,8 @@ impl Track { // decoder straight out of the blocks ([`MkvAc3Track`]). Sound neither // one can decode (Opus, DTS) leaves the source the silent one it always // was, which `AudioSession::unsupported` puts into words, rather than - // failing the import of a file whose picture is fine -- and so does an - // AC-3 track that will not open, a laced block say. + // failing the import of a file whose picture is fine. A track that will + // not open at all is *not* in that group: see below. if crate::demux::is_matroska(path) { if stream > 0 { return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into()); @@ -1003,24 +1038,27 @@ impl Track { match MkvAc3Track::open(path) { Ok(Some(track)) => return Ok(Some(Self::Mkv(track))), Ok(None) => {} - // Named on the way past for the same reason symphonia's failure - // is, below: an AC-3 track that broke is a bug, not a codec we - // never had. + // Named on the way past rather than returned: symphonia gets the + // same file next and may read the track perfectly well (a laced + // block is [`MkvAc3Track`]'s limitation, not the file's), and + // if it cannot either, *its* `Err` is the one that comes back. Err(e) => eprintln!("matroska audio: {}: {e}", path.display()), } - // Logged on the way past: "silent" here covers both a codec nothing - // decodes and a track that genuinely broke, and only the second is a - // bug -- with no trace at all it reaches the user as a lane that - // drew no waveform and nothing else to go on. - return Ok(SymTrack::open(path) - .inspect_err(|e| eprintln!("matroska audio: {}: {e}", path.display())) - .ok() - .filter(|t| { - t.decoder() - .inspect_err(|e| eprintln!("matroska audio: {}: {e}", path.display())) - .is_ok() - }) - .map(Self::Sym)); + // Two things are silent here and no more: a file with no audio + // track at all, and a track whose codec nothing in this project + // decodes (Opus, DTS -- [`AudioSession::unsupported`] is what puts + // that into words). A track that will not *open* is an `Err`, the + // same answer the mp4 arm gives: turned into silence it would play + // and export as a hole with only an eprintln to say why, which is a + // bug wearing a feature's clothes. + let Some(track) = SymTrack::open(path)? else { + return Ok(None); + }; + if let Err(e) = track.decoder() { + eprintln!("matroska audio: {}: {e}", path.display()); + return Ok(None); + } + return Ok(Some(Self::Sym(track))); } let audio_file = crate::is_audio(path); // Ahead of the AAC reader, because that one answers "not AAC" for a @@ -1041,7 +1079,7 @@ impl Track { if stream > 0 { return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into()); } - SymTrack::open(path).map(|track| Some(Self::Sym(track))) + SymTrack::open_required(path).map(|track| Some(Self::Sym(track))) } fn sample_rate(&self) -> u32 { @@ -1166,7 +1204,13 @@ struct SymTrack { } impl SymTrack { - fn open(path: &Path) -> crate::Result { + /// `Ok(None)` for a container that opened and holds no audio track at all -- + /// a silent source, which is a thing a file is allowed to be. Everything + /// else that goes wrong here is an `Err`: a file that will not open, will + /// not parse, or carries a track it cannot describe is *broken*, and the + /// difference matters because silence is played and exported without a word + /// while an `Err` is shown ([`Track::open`]). + fn open(path: &Path) -> crate::Result> { let mss = MediaSourceStream::new(Box::new(File::open(path)?), Default::default()); // The extension is a hint, not a decision: the probe reads the magic and // is free to disagree, which is what makes a mislabelled file work. @@ -1180,9 +1224,9 @@ impl SymTrack { FormatOptions::default(), MetadataOptions::default(), )?; - let track = reader - .default_track(SymKind::Audio) - .ok_or_else(|| format!("{} has no audio track", path.display()))?; + let Some(track) = reader.default_track(SymKind::Audio) else { + return Ok(None); + }; let (track_id, num_frames, delay) = (track.id, track.num_frames, track.delay); let time_base = track .time_base @@ -1203,7 +1247,7 @@ impl SymTrack { let codec = symphonia::default::get_codecs() .get_audio_decoder(params.codec) .map_or("an unsupported format", |d| d.codec.info.short_name); - Ok(Self { + Ok(Some(Self { reader, track_id, sample_rate, @@ -1217,7 +1261,14 @@ impl SymTrack { time_base, params, codec, - }) + })) + } + + /// [`open`](Self::open) where having no audio track is itself the error: + /// what a standalone audio file is held to, since a song with no sound in + /// it is a broken file and not a silent source. + fn open_required(path: &Path) -> crate::Result { + Self::open(path)?.ok_or_else(|| format!("{} has no audio track", path.display()).into()) } /// A fresh decoder: seeking mid-stream leaves state that belongs to the diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 0fe9192..d6b06cd 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -1659,8 +1659,9 @@ impl PlaybackSession { /// nothing playable, so there is nothing for [`undo`](Self::undo) to take /// back, and nothing reseeks. /// - /// Refused unless it can join the timeline -- same codec, same audio - /// parameters or both silent; the `Err` names the property that disagrees, + /// Refused unless it can join the timeline -- a decoder this machine can + /// open, and audio parameters that agree or none at all; the `Err` names + /// the property that disagrees, /// for a caller to show. Nothing is changed by a refusal. A *resolution* of /// its own is not a refusal: the clip is placed on the project canvas by its /// fit policy ([`PlaybackSession::set_fit`]) -- and neither is a *frame @@ -2018,8 +2019,9 @@ impl Drop for PlaybackSession { } /// Whether `path`, already demuxed to `meta`, may join a timeline whose -/// parameters are `timeline` and whose audio probes as `first`: same codec, -/// same audio parameters or both silent, and a frame rate that can be named +/// parameters are `timeline` and whose audio probes as `first`: a decoder this +/// machine can open, audio parameters that agree (or no audio at all), and a +/// frame rate that can be named /// against the timeline's. The [`Rate`] it will be read at comes back with the /// answer, so the number the check was decided on is the number it plays by. /// @@ -2028,7 +2030,9 @@ impl Drop for PlaybackSession { /// own fit policy, so a 640x360 file joining a 1920x1080 timeline is a /// letterboxed clip rather than a refusal, and so is a frame rate of its own: /// the timeline keeps its own rate and the file is read at [`Rate`] against it -/// ([`PlaybackSession::import`] notes how long it is *here*). +/// ([`PlaybackSession::import`] notes how long it is *here*). Nor the same +/// codec: every clip opens its own decoder, so a mixed-codec timeline is a +/// decoder each rather than a refusal. /// /// The `Err` names the property that disagrees, and those strings are what a /// front-end shows verbatim; [`PlaybackSession::import`] and @@ -2040,18 +2044,22 @@ fn matches_timeline( timeline: &VideoMeta, first: &Option, ) -> crate::Result { - // Codec first: one timeline is one kind of source. Mixing them would decode - // (every clip opens its own decoder) but on a machine without the VA-API - // plugin the VP9 half would be black frames with the refusal only on - // stderr, which is exactly what a front-end cannot show. - if meta.codec != timeline.codec { - return Err(format!( - "{} does not match the timeline's {}", - meta.codec.name(), - timeline.codec.name() - ) - .into()); - } + // The codec is *not* held to the timeline's -- every clip opens its own + // decoder, so an H.264 take and an HEVC one play on one timeline. What the + // codec gate was really protecting against stays, in the one place that can + // actually answer it: on a machine without the VA-API plugin an HEVC or VP9 + // clip would be black frames with the refusal on stderr alone, so the file + // is asked for a decoder *here*, at the door, where the `Err` is still + // something a front-end can show. A zero-length range probes and starts no + // worker, and H.264 costs nothing at all -- [`DecodeSession::open_worker`] + // only enters VA-API off that path. + DecodeSession::open_worker( + &source.path, + 0, + 0, + ColorParams::default(), + Composer::passthrough(), + )?; // The frame rate is *not* a refusal any more: a file shot at another rate is // placed for the seconds it lasts and read through [`Rate`] at the // decoder's door, so it plays at the speed it was shot at on a timeline @@ -2069,8 +2077,9 @@ fn matches_timeline( } /// Whether a candidate's audio may join a timeline whose first source probes as -/// `first`: same rate, same layout, or both silent. One output device and one -/// exported track is all there is, and no resampler. +/// `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. /// /// The audio half of [`matches_timeline`], which a stream placed on its own /// ([`PlaybackSession::place_stream_at`]) has to pass while the picture it @@ -2088,9 +2097,9 @@ fn matches_timeline( /// `Ok(None)` for a timeline whose first such source is silent, and for one of /// nothing but stills. That is a silent timeline, and a file with sound is /// still refused by [`audio_matches`] in the words it always used ("the file -/// has audio, the timeline is silent") -- the same answer a silent *video* as -/// source 0 has always given. This function widens which source is asked, not -/// what the answer means. +/// has audio, the timeline is silent") -- the device was opened on source 0's +/// track and there is none to open. This function widens which source is asked, +/// not what the answer means. fn first_audio_of(sources: &[Source]) -> crate::Result> { match audio_source_of(sources) { Some(first) => AudioSession::probe(&first.path, first.audio_stream), @@ -2119,12 +2128,19 @@ fn audio_matches(source: &Source, first: &Option) -> crate::R if probe == *first { return Ok(()); } - Err(match (probe, first) { - (None, _) => "the file is silent, the timeline has audio".to_string(), - (_, None) => "the file has audio, the timeline is silent".to_string(), - (Some(a), Some(b)) => format!( + // ...and a *silent* file joins whatever the timeline is: it contributes + // silence over its span, which is the very thing both audio paths already + // synthesise for a gap ([`AudioSession::open_multi_streams_speed`] plays + // it, `AudioSession::copy_multi_streams` writes it). There is no rate and + // no layout to disagree about, so there is nothing left to refuse. + let Some(probe) = probe else { + return Ok(()); + }; + 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", - a.sample_rate, a.channels, b.sample_rate, b.channels + probe.sample_rate, probe.channels, b.sample_rate, b.channels ), } .into()) diff --git a/crates/engine/tests/audio_decode.rs b/crates/engine/tests/audio_decode.rs index e02ea9a..80e9199 100644 --- a/crates/engine/tests/audio_decode.rs +++ b/crates/engine/tests/audio_decode.rs @@ -272,3 +272,40 @@ fn an_ac3_source_refuses_an_mp4_audio_copy() { "unhelpful refusal: {err}" ); } + +/// The two things a Matroska file with no *readable* sound can be, told apart: +/// a file with no audio track is the silent source it says it is, and a file +/// whose audio will not open at all is an error. They used to be the same +/// answer -- silence -- so a broken track played and exported as a hole with +/// nothing but an `eprintln` to say why. +#[test] +fn a_matroska_with_no_track_is_silent_and_a_broken_one_is_an_error() { + // No audio track at all: a picture and two subtitle tracks. Silent, and the + // stream picker offers nothing rather than refusing the file. + let subs = asset("test_subs.mkv"); + assert!( + AudioSession::probe(&subs, 0) + .expect("no audio is not an error") + .is_none(), + "an mkv with no audio track is a silent source" + ); + assert!(AudioSession::probe_streams(&subs).expect("list").is_empty()); + assert!( + AudioSession::open(&subs).expect("open").is_none(), + "no sound" + ); + + // ...and a file that will not parse at all, under the same extension: an + // `Err` a front-end can show, not a silent import. + let broken = std::env::temp_dir().join(format!("ve_broken_{}.mkv", std::process::id())); + std::fs::write(&broken, b"\x1a\x45\xdf\xa3not a matroska file at all").expect("write"); + let err = AudioSession::probe(&broken, 0) + .expect_err("a broken file must not pass for a silent one") + .to_string(); + assert!(!err.is_empty(), "the refusal says something"); + assert!( + AudioSession::probe_streams(&broken).is_err(), + "and so does the listing" + ); + std::fs::remove_file(&broken).unwrap(); +} diff --git a/crates/engine/tests/audio_export.rs b/crates/engine/tests/audio_export.rs index 550a80d..6e0a34d 100644 --- a/crates/engine/tests/audio_export.rs +++ b/crates/engine/tests/audio_export.rs @@ -511,6 +511,67 @@ fn a_cancelled_audio_export_leaves_no_file() { assert!(!part_path(&out).exists(), "no half-written .part either"); } +/// The samples a silent take contributes: a clip of a file with no audio track +/// is silence for exactly its span, between two clips that are heard. This is +/// what makes `PlaybackSession::import` letting such a file in honest -- the +/// export reads the same play list playback does, so a hole here is a hole in +/// the ear too. +#[test] +fn a_silent_clip_exports_as_silence_over_its_own_span() { + let clip = |start, source| Clip { + start, + in_frame: 0, + out_frame: 30, + source, + link: None, + eq: None, + color: None, + fit: FitPolicy::default(), + speed: Speed::NORMAL, + }; + let project = Project::from_parts( + vec![ + Source::new(asset("test_av.mp4"), 0), + // Video only, no audio track at all: the silent take. + Source::new(asset("test_mismatch.mp4"), 0), + ], + vec![ + (LaneKind::Video, vec![clip(0, 0), clip(30, 1), clip(60, 0)]), + (LaneKind::Audio, vec![clip(0, 0), clip(30, 1), clip(60, 0)]), + ], + Vec::new(), + Vec::new(), + ) + .expect("a project whose middle take is silent"); + + let out = out_path("silent_clip", "wav"); + let handle = engine::export::start( + project, + meta(), + &out, + &ExportSettings { + format: Format::Wav, + ..Default::default() + }, + ); + wait(&handle, Duration::from_secs(60)).expect("wav export"); + let (audio, samples) = decode(&out); + let channels = usize::from(audio.channels); + assert_eq!( + samples.len(), + (3.0 * f64::from(RATE)) as usize * channels, + "three seconds of timeline, silent take included" + ); + let heard = rms(&samples, channels, 0.05, 0.95); + let quiet = rms(&samples, channels, 1.0, 2.0); + let again = rms(&samples, channels, 2.05, 2.95); + println!("rms: heard {heard:.4} silent take {quiet:.6} heard {again:.4}"); + assert!(heard > 0.01, "the first take is audible"); + assert!(again > 0.01, "the third take is audible"); + assert_eq!(quiet, 0.0, "the silent take is exact silence, not a stall"); + std::fs::remove_file(&out).unwrap(); +} + /// A silent timeline cannot become an audio file, and says so rather than /// writing zero samples that a user would take for a broken microphone. #[test] diff --git a/crates/engine/tests/audio_multi.rs b/crates/engine/tests/audio_multi.rs index 63fd59e..d9dc201 100644 --- a/crates/engine/tests/audio_multi.rs +++ b/crates/engine/tests/audio_multi.rs @@ -250,18 +250,19 @@ fn the_join_carries_no_second_priming_packet() { } #[test] -fn a_source_without_the_timeline_audio_is_refused() { - // Import refuses these up front (same rate, same layout, or both silent); +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. - let mixed = [asset("test_av.mp4"), asset("test_mismatch.mp4")]; + // 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. + 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`.) for e in [ - AudioSession::copy_multi_segments(&mixed, &segs).err(), - AudioSession::open_multi_segments(&mixed, &segs).err(), + AudioSession::copy_multi_streams(&mixed, &segs).err(), + AudioSession::open_multi_streams(&mixed, &segs).err(), ] - .map(|e| e.expect("a source with no audio track must be refused")) + .map(|e| e.expect("a source at another rate must be refused")) { let msg = e.to_string(); assert!(msg.contains("source 1"), "{msg}"); @@ -270,3 +271,62 @@ fn a_source_without_the_timeline_audio_is_refused() { assert!(AudioSession::copy_multi_segments(&sources(), &[(Some(2), 0.0, 1.0)]).is_err()); assert!(AudioSession::open_multi_segments(&sources(), &[(Some(2), 0.0, 1.0)]).is_err()); } + +/// A source with **no** track is not a refusal at all: its segments are the +/// same silence a gap is, in both paths. That is what a silent clip on an audio +/// lane is -- a picture over a hole -- and the timeline lets one in +/// (`PlaybackSession::import`) precisely because these two agree here. +#[test] +fn a_silent_source_is_silence_and_not_a_refusal() { + let mixed = [asset("test_av.mp4"), asset("test_mismatch.mp4")]; + let segs = [ + (Some(0), 0.0, 1.0), + (Some(1), 0.0, 1.0), + (Some(0), 0.0, 1.0), + ]; + + // Decoded: three seconds, the middle one exact zero, and the chunks still + // arrive contiguous (`drain` asserts that), so the clock is fed through it. + let (_, rx) = AudioSession::open_multi_segments(&mixed, &segs) + .expect("a silent source opens") + .expect("the first source has an audio track"); + let (samples, _, _) = drain(rx); + let frames = samples.len() / CHANNELS; + assert!( + (frames as i64 - 3 * RATE as i64).unsigned_abs() < PACKET, + "{frames} frames for three seconds" + ); + let second = |n: usize| { + let at = |s: usize| (s * RATE as usize * CHANNELS).min(samples.len()); + &samples[at(n)..at(n + 1)] + }; + assert!( + second(0).iter().any(|s| *s != 0.0), + "the first second plays" + ); + assert!( + second(1).iter().all(|s| *s == 0.0), + "the silent source is exact silence" + ); + assert!(second(2).iter().any(|s| *s != 0.0), "and it comes back"); + + // Copied: the same shape in packets, so an mp4 export of that timeline is + // as long as the timeline and quiet where the silent clip is. + let (params, packets) = AudioSession::copy_multi_segments(&mixed, &segs) + .expect("a silent source copies") + .expect("the timeline has an audible source"); + let copied = packets.len() as u64 * PACKET; + assert!( + (copied as i64 - 3 * RATE as i64).unsigned_abs() < 2 * PACKET, + "{copied} samples for three seconds, priming included" + ); + assert_eq!( + params.sample_rate, RATE as u32, + "the audible source's track" + ); + let silence: Vec<_> = packets[44..44 + 43].iter().map(|p| &p.bytes).collect(); + assert!( + silence.iter().all(|b| b.len() <= 7), + "the hole is written as the hand-made silent packet, not as audio" + ); +} diff --git a/crates/engine/tests/av1.rs b/crates/engine/tests/av1.rs index bc8ea5c..531bfc6 100644 --- a/crates/engine/tests/av1.rs +++ b/crates/engine/tests/av1.rs @@ -155,17 +155,27 @@ fn the_software_path_refuses_av1_by_name() { assert!(refused.contains("plugin"), "{refused}"); } -/// A timeline is refused a source coded differently, in the same words a -/// resolution mismatch is refused in: a front-end shows the string as it is. +/// A timeline is *not* refused a source coded differently -- every clip opens +/// its own decoder. What survives is the reason the codec gate existed: on a +/// machine that cannot decode AV1 the file is refused at the door, by the +/// decoder's own name, rather than becoming a clip of black frames. #[test] -fn a_timeline_refuses_the_other_codec() { +fn a_timeline_takes_the_other_codec_or_names_the_missing_decoder() { let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4"); + // The no-plugin machine, forced. + // SAFETY: the suite is documented to run with --test-threads=1. + unsafe { std::env::set_var("VE_SW", "1") }; let refused = session .import(&asset("test_av1.mkv")) - .expect_err("AV1 must not join an H.264 timeline") + .expect_err("no AV1 decoder means no AV1 clip") .to_string(); - assert!(refused.contains("AV1"), "{refused}"); - assert!(refused.contains("H.264"), "{refused}"); + unsafe { std::env::remove_var("VE_SW") }; + assert_eq!(refused, Codec::Av1.needs_plugin()); + assert!( + !refused.contains("H.264"), + "the timeline's own codec is no longer a reason: {refused}" + ); + assert_eq!(session.sources().len(), 1, "a refusal left no row"); } /// The end-to-end user path: opening the file yields pictures, all of them, diff --git a/crates/engine/tests/hevc.rs b/crates/engine/tests/hevc.rs index a128ab6..c1576d7 100644 --- a/crates/engine/tests/hevc.rs +++ b/crates/engine/tests/hevc.rs @@ -112,17 +112,35 @@ fn the_software_path_refuses_hevc_by_name() { assert!(h264, "software H.264 decode still opens"); } -/// A timeline is refused a source coded differently, in the same words a -/// resolution mismatch is refused in: a front-end shows the string as it is. +/// A timeline is *not* refused a source coded differently -- every clip opens +/// its own decoder, so H.264 and HEVC share one timeline. What survives is the +/// reason the codec gate existed: on a machine that cannot decode HEVC the file +/// is refused at the door, by the decoder's own name, rather than becoming a +/// clip of black frames with the complaint on stderr. #[test] -fn a_timeline_refuses_the_other_codec() { +fn a_timeline_takes_the_other_codec_or_names_the_missing_decoder() { let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4"); + // The no-plugin machine, forced: the refusal must still arrive, and it must + // be the decoder's words and not the timeline's. + // SAFETY: the suite is documented to run with --test-threads=1. + unsafe { std::env::set_var("VE_SW", "1") }; let refused = session .import(&asset("test_hevc.mp4")) - .expect_err("HEVC must not join an H.264 timeline") + .expect_err("no HEVC decoder means no HEVC clip") .to_string(); - assert!(refused.contains("HEVC"), "{refused}"); - assert!(refused.contains("H.264"), "{refused}"); + unsafe { std::env::remove_var("VE_SW") }; + assert_eq!(refused, Codec::Hevc.needs_plugin()); + assert!( + !refused.contains("H.264"), + "the timeline's own codec is no longer a reason: {refused}" + ); + assert_eq!(session.sources().len(), 1, "a refusal left no row"); + + // ...and where a decoder exists, it simply joins. + match session.import(&asset("test_hevc.mp4")) { + Ok(_) => assert_eq!(session.sources().len(), 2, "HEVC beside H.264"), + Err(e) => assert_eq!(e.to_string(), Codec::Hevc.needs_plugin()), + } } /// The end-to-end user path: opening the file yields pictures, all of them, @@ -155,6 +173,65 @@ fn the_plugin_decodes_every_hevc_frame() { ); } +/// The mixed-codec timeline, end to end: an H.264 take joins an HEVC one, both +/// spans really decode (a decoder each, opened at the span), and the export -- +/// which re-encodes -- writes every frame of both. The refusal that used to +/// stand here would have made this whole timeline impossible. +#[test] +#[ignore = "needs libengine_hw.so and a VA-API driver with HEVC decode"] +fn an_h264_take_plays_and_exports_on_an_hevc_timeline() { + let hevc = asset("test_hevc.mp4"); + let h264 = asset("test_av.mp4"); + let mut session = PlaybackSession::open(&hevc).expect("open test_hevc.mp4"); + session.set_gain(0.0); + session.import(&h264).expect("H.264 joins an HEVC timeline"); + let end = session.timeline_duration(); + assert!( + session + .place_stream_at(end, &h264, 0, None) + .expect("a file just imported is on this timeline"), + "drag it onto the end" + ); + assert_eq!(session.clip_spans().len(), 2, "two takes, two codecs"); + + // One picture out of each span, which is one decoder each: the HEVC clip + // through the plugin, the H.264 one through either backend. + for (at, what) in [(1.0, "the HEVC take"), (end + 1.0, "the H.264 take")] { + session.seek(at); + let deadline = Instant::now() + Duration::from_secs(10); + let frame = loop { + if let Some(frame) = session.try_frame() { + break frame; + } + assert!(Instant::now() < deadline, "no frame from {what}"); + std::thread::sleep(Duration::from_millis(4)); + }; + assert_eq!( + (frame.width, frame.height), + session.resolution(), + "{what} came out at the project size" + ); + } + + // ...and the export -- the one a front-end starts, off the session itself -- + // re-encodes both to one H.264 track. + let frames = + (session.timeline_duration() * f64::from(session.meta().frame_rate as f32)).round() as u32; + let out = std::env::temp_dir().join(format!("ve_export_mixed_{}.mp4", std::process::id())); + let _ = std::fs::remove_file(&out); + let handle = session.export_to_with(&out, &ExportSettings::default()); + let started = Instant::now(); + while !handle.is_finished() { + assert!(started.elapsed() < Duration::from_secs(240), "export hung"); + std::thread::sleep(Duration::from_millis(20)); + } + handle.result().expect("outcome").expect("the mixed export"); + let (written, _) = Demuxer::open(&out).expect("reopen the export"); + assert_eq!(written.codec, Codec::H264, "exports are always H.264"); + assert_eq!(written.frame_count, frames, "both takes were written"); + let _ = std::fs::remove_file(&out); +} + /// Export re-encodes to H.264 whatever the source was coded with: the packet /// copy path is audio-only, so no HEVC byte can reach an `avc1` track. #[test] diff --git a/crates/engine/tests/lanes.rs b/crates/engine/tests/lanes.rs index fe2f5fa..46ccf6f 100644 --- a/crates/engine/tests/lanes.rs +++ b/crates/engine/tests/lanes.rs @@ -52,8 +52,13 @@ fn out_path(name: &str, ext: &str) -> PathBuf { /// A hand-written v4 project: `V1` the whole of `test_av`, `V2` the middle /// third playing `test_av2` from its own frame 0, `A1` the whole of `test_av`. /// Exactly the file a user would write by hand, parsed by the real loader. -fn three_lane_file() -> PathBuf { - let path = out_path("project", "edith"); +/// +/// `name` is the caller's own, because [`out_path`] is unique per *run* and not +/// per test: two tests sharing one name run in parallel over one file, and the +/// first to finish deletes it out from under the second -- which then fails on +/// a file that is simply not there any more. +fn three_lane_file(name: &str) -> PathBuf { + let path = out_path(name, "edith"); // `source