forge
Explore
Log in

Don't you dare go Hollow

Mixed codecs and silent takes join the timeline

Browse files at this commit

9bc3bd4865c71d3648a19a9fcac53b8ab5fc08a2Ahmet Kaan GümüşParent: 88fbed0
  • feat
    • mixed codecs and silent takes join the timeline
Show full message
✨ feat(import): mixed codecs and silent takes join the timeline

The two refusals a user hits for no reason are gone: a file coded
differently opens its own decoder like every clip already does, and a
file with no audio track contributes silence over its span like a gap
already does.

What the codec gate was really protecting against stays, moved to the
one place that can answer it: import asks the file for a decoder, so a
machine without the VA-API plugin refuses an HEVC take by the decoder's
own name rather than playing black frames with the complaint on stderr.
Rate and layout stay refused -- there is no resampler.

Both audio paths now read a source with no track as the silence they
already synthesise for a hole: the worker plays it, the packet copy
writes it, so an mp4 export of a timeline with a silent take is as long
as the timeline and quiet where the take is.
crates/engine/src/audio.rsmodified+66 -35
@@ -204,10 +204,14 @@ impl AudioSession {
204 /// pause — the master clock counts what the device has been fed, so a hole204 /// pause — the master clock counts what the device has been fed, so a hole
205 /// that fed nothing would stall the whole timeline on it.205 /// that fed nothing would stall the whole timeline on it.
206 ///206 ///
207+ /// A segment naming a source that has **no track** is the same silence: a
208+ /// clip of a silent file is a hole with a picture over it, and the timeline
209+ /// let it in on exactly that footing ([`crate::PlaybackSession::import`]).
210+ ///
207 /// Only the sources some segment names are opened. `Ok(None)` when `sources`211 /// Only the sources some segment names are opened. `Ok(None)` when `sources`
208- /// is empty or its first entry has no AAC track; a later source that is212+ /// is empty or its first entry has no AAC track; a later source that
209- /// missing audio or disagrees on rate/layout is an `Err` — import refuses213+ /// disagrees on rate/layout is an `Err` — import refuses those up front (one
210- /// those up front (one timeline, one output device), this is the backstop.214+ /// timeline, one output device), this is the backstop.
211 pub fn open_multi_segments(215 pub fn open_multi_segments(
212 sources: &[PathBuf],216 sources: &[PathBuf],
213 segs: &[(Option<usize>, f64, f64)],217 segs: &[(Option<usize>, f64, f64)],
@@ -286,11 +290,18 @@ impl AudioSession {
286 first.check_decoder()?;290 first.check_decoder()?;
287 291
288 let mut tracks: Vec<Option<Track>> = sources.iter().map(|_| None).collect();292 let mut tracks: Vec<Option<Track>> = sources.iter().map(|_| None).collect();
293+ // ...and which of them turned out to have no track at all, so a silent
294+ // source is opened once like any other rather than once per segment
295+ // naming it.
296+ let mut silent: Vec<bool> = sources.iter().map(|_| false).collect();
289 tracks[0] = Some(first);297 tracks[0] = Some(first);
290 for &(source, ..) in segs {298 for &(source, ..) in segs {
291 let Some(source) = source else {299 let Some(source) = source else {
292 continue; // a gap opens no file300 continue; // a gap opens no file
293 };301 };
302+ if silent.get(source) == Some(&true) {
303+ continue;
304+ }
294 let slot = tracks305 let slot = tracks
295 .get_mut(source)306 .get_mut(source)
296 .ok_or_else(|| format!("segment names source {source} of {}", sources.len()))?;307 .ok_or_else(|| format!("segment names source {source} of {}", sources.len()))?;
@@ -298,8 +309,14 @@ impl AudioSession {
298 continue; // already opened, and the checks below already ran309 continue; // already opened, and the checks below already ran
299 }310 }
300 let (path, stream) = &sources[source];311 let (path, stream) = &sources[source];
301- let track = Track::open(path, *stream)?312+ // A source with no audio track at all is not a failure: its
302- .ok_or_else(|| format!("source {source} has no audio track"))?;313+ // segments are silence, exactly as a gap's are, and the slot stays
314+ // empty to say so. That is what a silent clip on an audio lane
315+ // means -- a picture over a hole.
316+ let Some(track) = Track::open(path, *stream)? else {
317+ silent[source] = true;
318+ continue;
319+ };
303 if (track.sample_rate(), track.channels()?) != (meta.sample_rate, meta.channels) {320 if (track.sample_rate(), track.channels()?) != (meta.sample_rate, meta.channels) {
304 return Err(format!(321 return Err(format!(
305 "source {source} is {} Hz {} ch, the timeline is {} Hz {} ch",322 "source {source} is {} Hz {} ch, the timeline is {} Hz {} ch",
@@ -316,14 +333,15 @@ impl AudioSession {
316 333
317 let segments: Vec<Segment> = segs334 let segments: Vec<Segment> = segs
318 .iter()335 .iter()
319- .map(|&(source, start_secs, end_secs)| match source {336+ // A gap, and a source with no track to decode, are the same stretch
320- Some(source) => tracks[source]337+ // of nothing: as many frames of silence as the window is long.
321- .as_ref()338+ .map(|&(source, start_secs, end_secs)| {
322- .expect("opened above")339+ match source.and_then(|source| Some((source, tracks[source].as_ref()?))) {
323- .segment(source, start_secs, end_secs),340+ Some((source, track)) => track.segment(source, start_secs, end_secs),
324 None => Segment::silence(341 None => Segment::silence(
325 ((end_secs - start_secs).max(0.0) * f64::from(meta.sample_rate)) as u64,342 ((end_secs - start_secs).max(0.0) * f64::from(meta.sample_rate)) as u64,
326 ),343 ),
344+ }
327 })345 })
328 .collect();346 .collect();
329 // Chunk numbering is continuous across every join, counted from the first347 // Chunk numbering is continuous across every join, counted from the first
@@ -679,15 +697,18 @@ impl AudioSession {
679 /// half a packet over the whole list however many files it spans, and the697 /// half a packet over the whole list however many files it spans, and the
680 /// extra priming packet is still the very first segment's alone.698 /// extra priming packet is still the very first segment's alone.
681 ///699 ///
682- /// Every source must declare the same [`AacTrackParams`]: the copy becomes700+ /// Every source that *has* a track must declare the same
683- /// one output track with one esds. Import refuses a mismatch up front; the701+ /// [`AacTrackParams`]: the copy becomes one output track with one esds.
684- /// check here is the backstop, as is the missing-track `Err`.702+ /// Import refuses a mismatch up front; the check here is the backstop.
685 ///703 ///
686 /// A segment naming **no** source is a gap, and is copied as that many704 /// A segment naming **no** source is a gap, and is copied as that many
687 /// packets of [`silent_packet`] silence — the rounding debt carried through705 /// packets of [`silent_packet`] silence — the rounding debt carried through
688 /// it like any other, so the hole occupies its exact duration and the audio706 /// it like any other, so the hole occupies its exact duration and the audio
689 /// after it stays in sync with the picture. A gap the track *opens* on gets707 /// after it stays in sync with the picture. A gap the track *opens* on gets
690- /// one silent packet more, which is the priming a reader drops.708+ /// one silent packet more, which is the priming a reader drops. A segment
709+ /// naming a *silent* source is written the same way: a clip whose file has
710+ /// no audio track is a hole with a picture over it, and the timeline it
711+ /// joined already said so ([`crate::PlaybackSession::import`]).
691 pub fn copy_multi_segments(712 pub fn copy_multi_segments(
692 sources: &[PathBuf],713 sources: &[PathBuf],
693 segs: &[(Option<usize>, f64, f64)],714 segs: &[(Option<usize>, f64, f64)],
@@ -706,24 +727,34 @@ impl AudioSession {
706 sources: &[(PathBuf, usize)],727 sources: &[(PathBuf, usize)],
707 segs: &[(Option<usize>, f64, f64)],728 segs: &[(Option<usize>, f64, f64)],
708 ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> {729 ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> {
709- let Some(&(Some(first), ..)) = segs.iter().find(|s| s.0.is_some()) else {730+ // The output track is declared from the first source that has one --
731+ // not simply the first one named, which may be a silent clip. Such a
732+ // clip defines no rate and no layout; it is written as silence below
733+ // and the track goes on being the audible sources' track.
734+ let mut tracks: Vec<Option<Option<AacTrack>>> = sources.iter().map(|_| None).collect();
735+ let mut first = None;
736+ for &(source, ..) in segs {
737+ let Some(source) = source else { continue };
738+ if let Some(track) = source_at(&mut tracks, sources, source)? {
739+ first = Some(track.track_params());
740+ break;
741+ }
742+ }
743+ let Some(params) = first else {
710 return Ok(None); // no segments, or nothing but silence744 return Ok(None); // no segments, or nothing but silence
711 };745 };
712- let (path, stream) = sources
713- .get(first)
714- .ok_or_else(|| format!("segment names source {first} of {}", sources.len()))?;
715- let Some(track) = copy_track(path, *stream)? else {
716- return Ok(None); // silent source, silent export
717- };
718- let params = track.track_params();
719- let mut tracks: Vec<Option<AacTrack>> = sources.iter().map(|_| None).collect();
720- tracks[first] = Some(track);
721 746
722 let sample_rate = params.sample_rate;747 let sample_rate = params.sample_rate;
723 let mut err = 0i64;748 let mut err = 0i64;
724 let mut packets: Vec<AacPacket> = Vec::new();749 let mut packets: Vec<AacPacket> = Vec::new();
725 for &(source, start_secs, end_secs) in segs {750 for &(source, start_secs, end_secs) in segs {
726- let Some(source) = source else {751+ // A gap, and a clip whose source carries no track, are the same hole
752+ // to write: silence for as long as the window is.
753+ let named = match source {
754+ Some(source) => source_at(&mut tracks, sources, source)?.map(|t| (source, t)),
755+ None => None,
756+ };
757+ let Some((source, track)) = named else {
727 let ideal = ((end_secs - start_secs).max(0.0) * f64::from(sample_rate)) as i64;758 let ideal = ((end_secs - start_secs).max(0.0) * f64::from(sample_rate)) as i64;
728 let bytes = silent_packet(params.chan_conf)?;759 let bytes = silent_packet(params.chan_conf)?;
729 // A reader drops the first packet of an AAC track as the760 // A reader drops the first packet of an AAC track as the
@@ -741,7 +772,6 @@ impl AudioSession {
741 }772 }
742 continue;773 continue;
743 };774 };
744- let track = source_at(&mut tracks, sources, source)?;
745 if track.track_params() != params {775 if track.track_params() != params {
746 return Err(format!(776 return Err(format!(
747 "source {source} audio is {:?}, the timeline's is {params:?}",777 "source {source} audio is {:?}, the timeline's is {params:?}",
@@ -801,24 +831,25 @@ fn silent_packet(chan_conf: u8) -> crate::Result<Vec<u8>> {
801 }831 }
802 }832 }
803 833
804-/// The source at `index`, on the stream it names, opened on first use. Sources834+/// The source at `index`, on the stream it names, opened on first use -- and
805-/// a segment list never names are never touched: a project's list only grows.835+/// `None` for a source that has no track at all, which the caller writes as
836+/// silence exactly as it writes a gap. The outer `Option` is "has it been
837+/// opened", the inner one "was there anything in it", so a silent source is
838+/// opened once like any other. Sources a segment list never names are never
839+/// touched: a project's list only grows.
806 fn source_at<'a>(840 fn source_at<'a>(
807- tracks: &'a mut [Option<AacTrack>],841+ tracks: &'a mut [Option<Option<AacTrack>>],
808 sources: &[(PathBuf, usize)],842 sources: &[(PathBuf, usize)],
809 index: usize,843 index: usize,
810-) -> crate::Result<&'a mut AacTrack> {844+) -> crate::Result<Option<&'a mut AacTrack>> {
811 let slot = tracks845 let slot = tracks
812 .get_mut(index)846 .get_mut(index)
813 .ok_or_else(|| format!("segment names source {index} of {}", sources.len()))?;847 .ok_or_else(|| format!("segment names source {index} of {}", sources.len()))?;
814 if slot.is_none() {848 if slot.is_none() {
815 let (path, stream) = &sources[index];849 let (path, stream) = &sources[index];
816- *slot = Some(850+ *slot = Some(copy_track(path, *stream)?);
817- copy_track(path, *stream)?
818- .ok_or_else(|| format!("source {index} has no audio track"))?,
819- );
820 }851 }
821- Ok(slot.as_mut().expect("just opened"))852+ Ok(slot.as_mut().expect("just opened").as_mut())
822 }853 }
823 854
824 /// A source's track for the *copy* path, which needs raw AAC access units.855 /// A source's track for the *copy* path, which needs raw AAC access units.
crates/engine/src/playback.rsmodified+48 -34
@@ -1355,9 +1355,9 @@ impl PlaybackSession {
1355 /// nothing playable, so there is nothing for [`undo`](Self::undo) to take1355 /// nothing playable, so there is nothing for [`undo`](Self::undo) to take
1356 /// back, and nothing reseeks.1356 /// back, and nothing reseeks.
1357 ///1357 ///
1358- /// Refused unless it can join the timeline -- same codec, same frame rate,1358+ /// Refused unless it can join the timeline -- same frame rate, a decoder
1359- /// same audio parameters or both silent; the `Err` names the property that1359+ /// this machine can open, and audio parameters that agree or none at all;
1360- /// disagrees, for a caller to show. Nothing is changed by a refusal. A1360+ /// the `Err` names the property that disagrees, for a caller to show. Nothing is changed by a refusal. A
1361 /// *resolution* of its own is not a refusal: the clip is placed on the1361 /// *resolution* of its own is not a refusal: the clip is placed on the
1362 /// project canvas by its fit policy ([`PlaybackSession::set_fit`]).1362 /// project canvas by its fit policy ([`PlaybackSession::set_fit`]).
1363 pub fn import(&mut self, path: &Path) -> crate::Result<usize> {1363 pub fn import(&mut self, path: &Path) -> crate::Result<usize> {
@@ -1661,16 +1661,18 @@ impl Drop for PlaybackSession {
1661 }1661 }
1662 1662
1663 /// Whether `path`, already demuxed to `meta`, may join a timeline whose1663 /// Whether `path`, already demuxed to `meta`, may join a timeline whose
1664-/// parameters are `timeline` and whose audio probes as `first`: same codec,1664+/// parameters are `timeline` and whose audio probes as `first`: same frame
1665-/// same frame rate, same audio parameters or both silent.1665+/// rate, a decoder this machine can open, and audio parameters that agree (or
1666+/// no audio at all).
1666 ///1667 ///
1667-/// *Not* the same size any more. A project has its own resolution1668+/// *Not* the same size, and no longer the same codec either. A project has its
1668-/// ([`PlaybackSession::set_resolution`]) and every clip is placed on it by its1669+/// own resolution ([`PlaybackSession::set_resolution`]) and every clip is
1669-/// own fit policy, so a 640x360 file joining a 1920x1080 timeline is a1670+/// placed on it by its own fit policy, so a 640x360 file joining a 1920x1080
1670-/// letterboxed clip rather than a refusal. The frame rate stays refused on1671+/// timeline is a letterboxed clip rather than a refusal; and every clip opens
1671-/// purpose: mixing rates means resampling the *timeline*, which is a different1672+/// its own decoder, so a mixed-codec timeline is a decoder each rather than a
1672-/// problem from resampling a picture, and a refusal is the honest answer until1673+/// refusal. The frame rate stays refused on purpose: mixing rates means
1673-/// it is solved.1674+/// resampling the *timeline*, which is a different problem from resampling a
1675+/// picture, and a refusal is the honest answer until it is solved.
1674 ///1676 ///
1675 /// The `Err` names the property that disagrees, and those strings are what a1677 /// The `Err` names the property that disagrees, and those strings are what a
1676 /// front-end shows verbatim; [`PlaybackSession::import`] and1678 /// front-end shows verbatim; [`PlaybackSession::import`] and
@@ -1682,18 +1684,6 @@ fn matches_timeline(
1682 timeline: &VideoMeta,1684 timeline: &VideoMeta,
1683 first: &Option<crate::AudioProbe>,1685 first: &Option<crate::AudioProbe>,
1684 ) -> crate::Result<()> {1686 ) -> crate::Result<()> {
1685- // Codec first: one timeline is one kind of source. Mixing them would decode
1686- // (every clip opens its own decoder) but on a machine without the VA-API
1687- // plugin the VP9 half would be black frames with the refusal only on
1688- // stderr, which is exactly what a front-end cannot show.
1689- if meta.codec != timeline.codec {
1690- return Err(format!(
1691- "{} does not match the timeline's {}",
1692- meta.codec.name(),
1693- timeline.codec.name()
1694- )
1695- .into());
1696- }
1697 // Container frame rates are computed from timescales, so never `==`.1687 // Container frame rates are computed from timescales, so never `==`.
1698 if (meta.frame_rate - timeline.frame_rate).abs() > 0.01 {1688 if (meta.frame_rate - timeline.frame_rate).abs() > 0.01 {
1699 return Err(format!(1689 return Err(format!(
@@ -1702,12 +1692,29 @@ fn matches_timeline(
1702 )1692 )
1703 .into());1693 .into());
1704 }1694 }
1695+ // The codec itself is *not* held to the timeline's any more -- every clip
1696+ // opens its own decoder, so an H.264 take and an HEVC one play on one
1697+ // timeline. What the codec gate was really protecting against stays, in the
1698+ // one place that can actually answer it: on a machine without the VA-API
1699+ // plugin an HEVC or VP9 clip would be black frames with the refusal on
1700+ // stderr alone, so the file is asked for a decoder *here*, at the door,
1701+ // where the `Err` is still something a front-end can show. A zero-length
1702+ // range probes and starts no worker, and H.264 costs nothing at all --
1703+ // [`DecodeSession::open_worker`] only enters VA-API off that path.
1704+ DecodeSession::open_worker(
1705+ &source.path,
1706+ 0,
1707+ 0,
1708+ ColorParams::default(),
1709+ Composer::passthrough(),
1710+ )?;
1705 audio_matches(source, first)1711 audio_matches(source, first)
1706 }1712 }
1707 1713
1708 /// Whether a candidate's audio may join a timeline whose first source probes as1714 /// Whether a candidate's audio may join a timeline whose first source probes as
1709-/// `first`: same rate, same layout, or both silent. One output device and one1715+/// `first`: same rate, same layout -- or no audio of its own at all, which is
1710-/// exported track is all there is, and no resampler.1716+/// silence over the clip's span and agrees with everything. One output device
1717+/// and one exported track is all there is, and no resampler.
1711 ///1718 ///
1712 /// The audio half of [`matches_timeline`], which a stream placed on its own1719 /// The audio half of [`matches_timeline`], which a stream placed on its own
1713 /// ([`PlaybackSession::place_stream_at`]) has to pass while the picture it1720 /// ([`PlaybackSession::place_stream_at`]) has to pass while the picture it
@@ -1725,9 +1732,9 @@ fn matches_timeline(
1725 /// `Ok(None)` for a timeline whose first such source is silent, and for one of1732 /// `Ok(None)` for a timeline whose first such source is silent, and for one of
1726 /// nothing but stills. That is a silent timeline, and a file with sound is1733 /// nothing but stills. That is a silent timeline, and a file with sound is
1727 /// still refused by [`audio_matches`] in the words it always used ("the file1734 /// still refused by [`audio_matches`] in the words it always used ("the file
1728-/// has audio, the timeline is silent") -- the same answer a silent *video* as1735+/// has audio, the timeline is silent") -- the device was opened on source 0's
1729-/// source 0 has always given. This function widens which source is asked, not1736+/// track and there is none to open. This function widens which source is asked,
1730-/// what the answer means.1737+/// not what the answer means.
1731 fn first_audio_of(sources: &[Source]) -> crate::Result<Option<crate::AudioProbe>> {1738 fn first_audio_of(sources: &[Source]) -> crate::Result<Option<crate::AudioProbe>> {
1732 match sources.iter().find(|s| !crate::is_image(&s.path)) {1739 match sources.iter().find(|s| !crate::is_image(&s.path)) {
1733 Some(first) => AudioSession::probe(&first.path, first.audio_stream),1740 Some(first) => AudioSession::probe(&first.path, first.audio_stream),
@@ -1742,12 +1749,19 @@ fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::R
1742 if probe == *first {1749 if probe == *first {
1743 return Ok(());1750 return Ok(());
1744 }1751 }
1745- Err(match (probe, first) {1752+ // ...and a *silent* file joins whatever the timeline is: it contributes
1746- (None, _) => "the file is silent, the timeline has audio".to_string(),1753+ // silence over its span, which is the very thing both audio paths already
1747- (_, None) => "the file has audio, the timeline is silent".to_string(),1754+ // synthesise for a gap ([`AudioSession::open_multi_streams_speed`] plays
1748- (Some(a), Some(b)) => format!(1755+ // it, `AudioSession::copy_multi_streams` writes it). There is no rate and
1756+ // no layout to disagree about, so there is nothing left to refuse.
1757+ let Some(probe) = probe else {
1758+ return Ok(());
1759+ };
1760+ Err(match first {
1761+ None => "the file has audio, the timeline is silent".to_string(),
1762+ Some(b) => format!(
1749 "audio {} Hz {} ch does not match the timeline's {} Hz {} ch",1763 "audio {} Hz {} ch does not match the timeline's {} Hz {} ch",
1750- a.sample_rate, a.channels, b.sample_rate, b.channels1764+ probe.sample_rate, probe.channels, b.sample_rate, b.channels
1751 ),1765 ),
1752 }1766 }
1753 .into())1767 .into())
crates/engine/tests/audio_export.rsmodified+61 -0
@@ -281,6 +281,67 @@ fn a_cancelled_audio_export_leaves_no_file() {
281 assert!(!part_path(&out).exists(), "no half-written .part either");281 assert!(!part_path(&out).exists(), "no half-written .part either");
282 }282 }
283 283
284+/// The samples a silent take contributes: a clip of a file with no audio track
285+/// is silence for exactly its span, between two clips that are heard. This is
286+/// what makes `PlaybackSession::import` letting such a file in honest -- the
287+/// export reads the same play list playback does, so a hole here is a hole in
288+/// the ear too.
289+#[test]
290+fn a_silent_clip_exports_as_silence_over_its_own_span() {
291+ let clip = |start, source| Clip {
292+ start,
293+ in_frame: 0,
294+ out_frame: 30,
295+ source,
296+ link: None,
297+ eq: None,
298+ color: None,
299+ fit: FitPolicy::default(),
300+ speed: Speed::NORMAL,
301+ };
302+ let project = Project::from_parts(
303+ vec![
304+ Source::new(asset("test_av.mp4"), 0),
305+ // Video only, no audio track at all: the silent take.
306+ Source::new(asset("test_mismatch.mp4"), 0),
307+ ],
308+ vec![
309+ (LaneKind::Video, vec![clip(0, 0), clip(30, 1), clip(60, 0)]),
310+ (LaneKind::Audio, vec![clip(0, 0), clip(30, 1), clip(60, 0)]),
311+ ],
312+ Vec::new(),
313+ Vec::new(),
314+ )
315+ .expect("a project whose middle take is silent");
316+
317+ let out = out_path("silent_clip", "wav");
318+ let handle = engine::export::start(
319+ project,
320+ meta(),
321+ &out,
322+ &ExportSettings {
323+ format: Format::Wav,
324+ ..Default::default()
325+ },
326+ );
327+ wait(&handle, Duration::from_secs(60)).expect("wav export");
328+ let (audio, samples) = decode(&out);
329+ let channels = usize::from(audio.channels);
330+ assert_eq!(
331+ samples.len(),
332+ (3.0 * f64::from(RATE)) as usize * channels,
333+ "three seconds of timeline, silent take included"
334+ );
335+ let heard = rms(&samples, channels, 0.05, 0.95);
336+ let quiet = rms(&samples, channels, 1.0, 2.0);
337+ let again = rms(&samples, channels, 2.05, 2.95);
338+ println!("rms: heard {heard:.4} silent take {quiet:.6} heard {again:.4}");
339+ assert!(heard > 0.01, "the first take is audible");
340+ assert!(again > 0.01, "the third take is audible");
341+ assert_eq!(quiet, 0.0, "the silent take is exact silence, not a stall");
342+ std::fs::remove_file(&out).unwrap();
343+}
344+
284 /// A silent timeline cannot become an audio file, and says so rather than345 /// A silent timeline cannot become an audio file, and says so rather than
285 /// writing zero samples that a user would take for a broken microphone.346 /// writing zero samples that a user would take for a broken microphone.
286 #[test]347 #[test]
crates/engine/tests/audio_multi.rsmodified+60 -7
@@ -250,18 +250,22 @@ fn the_join_carries_no_second_priming_packet() {
250 }250 }
251 251
252 #[test]252 #[test]
253-fn a_source_without_the_timeline_audio_is_refused() {253+fn a_source_that_disagrees_on_rate_or_layout_is_refused() {
254- // Import refuses these up front (same rate, same layout, or both silent);254+ // Import refuses these up front (one output device, one set of parameters);
255 // the copy and the decode paths refuse them again rather than mislabel one255 // the copy and the decode paths refuse them again rather than mislabel one
256- // esds for two different tracks.256+ // esds for two different tracks. Stream 1 of the multi-audio fixture is
257- let mixed = [asset("test_av.mp4"), asset("test_mismatch.mp4")];257+ // 22.05 kHz mono against the timeline's 44.1 kHz stereo.
258+ let mixed = [
259+ (asset("test_av.mp4"), 0),
260+ (asset("test_multiaudio.mp4"), 1),
261+ ];
258 let segs = [(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0)];262 let segs = [(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0)];
259 // (`.err()`, not `unwrap_err`: neither Ok payload is `Debug`.)263 // (`.err()`, not `unwrap_err`: neither Ok payload is `Debug`.)
260 for e in [264 for e in [
261- AudioSession::copy_multi_segments(&mixed, &segs).err(),265+ AudioSession::copy_multi_streams(&mixed, &segs).err(),
262- AudioSession::open_multi_segments(&mixed, &segs).err(),266+ AudioSession::open_multi_streams(&mixed, &segs).err(),
263 ]267 ]
264- .map(|e| e.expect("a source with no audio track must be refused"))268+ .map(|e| e.expect("a source at another rate must be refused"))
265 {269 {
266 let msg = e.to_string();270 let msg = e.to_string();
267 assert!(msg.contains("source 1"), "{msg}");271 assert!(msg.contains("source 1"), "{msg}");
@@ -270,3 +274,52 @@ fn a_source_without_the_timeline_audio_is_refused() {
270 assert!(AudioSession::copy_multi_segments(&sources(), &[(Some(2), 0.0, 1.0)]).is_err());274 assert!(AudioSession::copy_multi_segments(&sources(), &[(Some(2), 0.0, 1.0)]).is_err());
271 assert!(AudioSession::open_multi_segments(&sources(), &[(Some(2), 0.0, 1.0)]).is_err());275 assert!(AudioSession::open_multi_segments(&sources(), &[(Some(2), 0.0, 1.0)]).is_err());
272 }276 }
277+
278+/// A source with **no** track is not a refusal at all: its segments are the
279+/// same silence a gap is, in both paths. That is what a silent clip on an audio
280+/// lane is -- a picture over a hole -- and the timeline lets one in
281+/// (`PlaybackSession::import`) precisely because these two agree here.
282+#[test]
283+fn a_silent_source_is_silence_and_not_a_refusal() {
284+ let mixed = [asset("test_av.mp4"), asset("test_mismatch.mp4")];
285+ let segs = [(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0), (Some(0), 0.0, 1.0)];
286+
287+ // Decoded: three seconds, the middle one exact zero, and the chunks still
288+ // arrive contiguous (`drain` asserts that), so the clock is fed through it.
289+ let (_, rx) = AudioSession::open_multi_segments(&mixed, &segs)
290+ .expect("a silent source opens")
291+ .expect("the first source has an audio track");
292+ let (samples, _, _) = drain(rx);
293+ let frames = samples.len() / CHANNELS;
294+ assert!(
295+ (frames as i64 - 3 * RATE as i64).unsigned_abs() < PACKET,
296+ "{frames} frames for three seconds"
297+ );
298+ let second = |n: usize| {
299+ let at = |s: usize| (s * RATE as usize * CHANNELS).min(samples.len());
300+ &samples[at(n)..at(n + 1)]
301+ };
302+ assert!(second(0).iter().any(|s| *s != 0.0), "the first second plays");
303+ assert!(
304+ second(1).iter().all(|s| *s == 0.0),
305+ "the silent source is exact silence"
306+ );
307+ assert!(second(2).iter().any(|s| *s != 0.0), "and it comes back");
308+
309+ // Copied: the same shape in packets, so an mp4 export of that timeline is
310+ // as long as the timeline and quiet where the silent clip is.
311+ let (params, packets) = AudioSession::copy_multi_segments(&mixed, &segs)
312+ .expect("a silent source copies")
313+ .expect("the timeline has an audible source");
314+ let copied = packets.len() as u64 * PACKET;
315+ assert!(
316+ (copied as i64 - 3 * RATE as i64).unsigned_abs() < 2 * PACKET,
317+ "{copied} samples for three seconds, priming included"
318+ );
319+ assert_eq!(params.sample_rate, RATE as u32, "the audible source's track");
320+ let silence: Vec<_> = packets[44..44 + 43].iter().map(|p| &p.bytes).collect();
321+ assert!(
322+ silence.iter().all(|b| b.len() <= 7),
323+ "the hole is written as the hand-made silent packet, not as audio"
324+ );
325+}
crates/engine/tests/av1.rsmodified+16 -6
@@ -147,17 +147,27 @@ fn the_software_path_refuses_av1_by_name() {
147 assert!(refused.contains("plugin"), "{refused}");147 assert!(refused.contains("plugin"), "{refused}");
148 }148 }
149 149
150-/// A timeline is refused a source coded differently, in the same words a150+/// A timeline is *not* refused a source coded differently -- every clip opens
151-/// resolution mismatch is refused in: a front-end shows the string as it is.151+/// its own decoder. What survives is the reason the codec gate existed: on a
152+/// machine that cannot decode AV1 the file is refused at the door, by the
153+/// decoder's own name, rather than becoming a clip of black frames.
152 #[test]154 #[test]
153-fn a_timeline_refuses_the_other_codec() {155+fn a_timeline_takes_the_other_codec_or_names_the_missing_decoder() {
154 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4");156 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4");
157+ // The no-plugin machine, forced.
158+ // SAFETY: the suite is documented to run with --test-threads=1.
159+ unsafe { std::env::set_var("VE_SW", "1") };
155 let refused = session160 let refused = session
156 .import(&asset("test_av1.mkv"))161 .import(&asset("test_av1.mkv"))
157- .expect_err("AV1 must not join an H.264 timeline")162+ .expect_err("no AV1 decoder means no AV1 clip")
158 .to_string();163 .to_string();
159- assert!(refused.contains("AV1"), "{refused}");164+ unsafe { std::env::remove_var("VE_SW") };
160- assert!(refused.contains("H.264"), "{refused}");165+ assert_eq!(refused, Codec::Av1.needs_plugin());
166+ assert!(
167+ !refused.contains("H.264"),
168+ "the timeline's own codec is no longer a reason: {refused}"
169+ );
170+ assert_eq!(session.sources().len(), 1, "a refusal left no row");
161 }171 }
162 172
163 /// The end-to-end user path: opening the file yields pictures, all of them,173 /// The end-to-end user path: opening the file yields pictures, all of them,
crates/engine/tests/hevc.rsmodified+24 -6
@@ -112,17 +112,35 @@ fn the_software_path_refuses_hevc_by_name() {
112 assert!(h264, "software H.264 decode still opens");112 assert!(h264, "software H.264 decode still opens");
113 }113 }
114 114
115-/// A timeline is refused a source coded differently, in the same words a115+/// A timeline is *not* refused a source coded differently -- every clip opens
116-/// resolution mismatch is refused in: a front-end shows the string as it is.116+/// its own decoder, so H.264 and HEVC share one timeline. What survives is the
117+/// reason the codec gate existed: on a machine that cannot decode HEVC the file
118+/// is refused at the door, by the decoder's own name, rather than becoming a
119+/// clip of black frames with the complaint on stderr.
117 #[test]120 #[test]
118-fn a_timeline_refuses_the_other_codec() {121+fn a_timeline_takes_the_other_codec_or_names_the_missing_decoder() {
119 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4");122 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4");
123+ // The no-plugin machine, forced: the refusal must still arrive, and it must
124+ // be the decoder's words and not the timeline's.
125+ // SAFETY: the suite is documented to run with --test-threads=1.
126+ unsafe { std::env::set_var("VE_SW", "1") };
120 let refused = session127 let refused = session
121 .import(&asset("test_hevc.mp4"))128 .import(&asset("test_hevc.mp4"))
122- .expect_err("HEVC must not join an H.264 timeline")129+ .expect_err("no HEVC decoder means no HEVC clip")
123 .to_string();130 .to_string();
124- assert!(refused.contains("HEVC"), "{refused}");131+ unsafe { std::env::remove_var("VE_SW") };
125- assert!(refused.contains("H.264"), "{refused}");132+ assert_eq!(refused, Codec::Hevc.needs_plugin());
133+ assert!(
134+ !refused.contains("H.264"),
135+ "the timeline's own codec is no longer a reason: {refused}"
136+ );
137+ assert_eq!(session.sources().len(), 1, "a refusal left no row");
138+
139+ // ...and where a decoder exists, it simply joins.
140+ match session.import(&asset("test_hevc.mp4")) {
141+ Ok(_) => assert_eq!(session.sources().len(), 2, "HEVC beside H.264"),
142+ Err(e) => assert_eq!(e.to_string(), Codec::Hevc.needs_plugin()),
143+ }
126 }144 }
127 145
128 /// The end-to-end user path: opening the file yields pictures, all of them,146 /// The end-to-end user path: opening the file yields pictures, all of them,
crates/engine/tests/playback.rsmodified+52 -28
@@ -13,7 +13,7 @@ use std::time::{Duration, Instant};
13 13
14 use engine::export::{ExportSettings, Format};14 use engine::export::{ExportSettings, Format};
15 use engine::project::Lane;15 use engine::project::Lane;
16-use engine::{DecodeSession, Frame, PlaybackSession};16+use engine::{Codec, DecodeSession, Frame, PlaybackSession};
17 17
18 fn asset(name: &str) -> PathBuf {18 fn asset(name: &str) -> PathBuf {
19 PathBuf::from(env!("CARGO_MANIFEST_DIR"))19 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
@@ -788,30 +788,31 @@ fn the_first_import_opens_a_library_over_an_empty_timeline() {
788 assert_eq!(session.sources().len(), 1, "the row survives the undo");788 assert_eq!(session.sources().len(), 1, "the row survives the undo");
789 }789 }
790 790
791-/// One timeline, one set of parameters: everything else is refused by name and791+/// One timeline, one frame rate and one set of audio parameters: what is left
792-/// changes nothing.792+/// is refused by name and changes nothing.
793 #[test]793 #[test]
794 fn import_refuses_what_does_not_match() {794 fn import_refuses_what_does_not_match() {
795 let mut session = open(asset("test_av.mp4"));795 let mut session = open(asset("test_av.mp4"));
796 796
797- // A different *codec* cannot join: one timeline is one kind of source.797+ // A different *codec* is not among them any more -- every clip opens its
798- let err = session798+ // own decoder. The only refusal left on that axis is a decoder this machine
799- .import(&asset("test_vp9.mp4"))799+ // cannot open, and it is the plugin's own words, not the timeline's.
800- .expect_err("VP9 must be refused")800+ match session.import(&asset("test_vp9.mp4")) {
801- .to_string();801+ Ok(_) => assert_eq!(session.sources().len(), 2, "VP9 joined the H.264 timeline"),
802- assert!(err.contains("VP9"), "refusal must name the codec: {err}");802+ Err(e) => assert_eq!(
803+ e.to_string(),
804+ Codec::Vp9.needs_plugin(),
805+ "the only codec refusal left is the missing decoder"
806+ ),
807+ }
808+ let rows = session.sources().len();
803 809
804 // A different resolution is no longer among the refusals -- it is placed on810 // A different resolution is no longer among the refusals -- it is placed on
805- // the project canvas instead -- but this file is also silent, and that is.811+ // the project canvas instead -- and neither is a file with no sound: it
806- let err = session812+ // contributes silence over its span.
813+ session
807 .import(&asset("test_mismatch.mp4"))814 .import(&asset("test_mismatch.mp4"))
808- .expect_err("a silent file must be refused")815+ .expect("a silent 640x360 file joins a timeline with sound");
809- .to_string();
810- assert!(err.contains("audio"), "refusal must name the audio: {err}");
811- assert!(
812- !err.contains("640x360"),
813- "a resolution of its own is not a refusal any more: {err}"
814- );
815 816
816 // Same codec, same audio, 25 fps: the one property left, named with both817 // Same codec, same audio, 25 fps: the one property left, named with both
817 // rates. Mixing rates would mean retiming the timeline itself, and there is818 // rates. Mixing rates would mean retiming the timeline itself, and there is
@@ -822,22 +823,21 @@ fn import_refuses_what_does_not_match() {
822 .to_string();823 .to_string();
823 assert_eq!(err, "25.000 fps does not match the timeline's 30.000 fps");824 assert_eq!(err, "25.000 fps does not match the timeline's 30.000 fps");
824 825
825- // Same size and rate, no audio track: the timeline has one.
826- let err = session
827- .import(&asset("test_baseline.mp4"))
828- .expect_err("a silent file must be refused")
829- .to_string();
830- assert!(err.contains("audio"), "refusal must name the audio: {err}");
831-
832 assert!(826 assert!(
833 session.import(&asset("no_such_file.mp4")).is_err(),827 session.import(&asset("no_such_file.mp4")).is_err(),
834 "a missing file is an error, not a panic"828 "a missing file is an error, not a panic"
835 );829 );
836- assert_eq!(session.clip_spans().len(), 1, "a refusal changes nothing");830+ assert_eq!(session.clip_spans().len(), 1, "an import places nothing");
837- assert_eq!(session.sources().len(), 1, "a refusal left a library row");831+ assert_eq!(
832+ session.sources().len(),
833+ rows + 1,
834+ "only the silent file was taken in"
835+ );
838 assert!((session.timeline_duration() - 5.0).abs() < 1e-9);836 assert!((session.timeline_duration() - 5.0).abs() < 1e-9);
839 837
840- // The mirror: audio into a silent timeline is refused just as loudly.838+ // The mirror is still refused: the device was opened on source 0's track
839+ // and a silent timeline has none to open, so a file with sound cannot be
840+ // heard on one.
841 let mut silent = open(asset("test_baseline.mp4"));841 let mut silent = open(asset("test_baseline.mp4"));
842 let err = silent842 let err = silent
843 .import(&asset("test_av.mp4"))843 .import(&asset("test_av.mp4"))
@@ -846,6 +846,30 @@ fn import_refuses_what_does_not_match() {
846 assert!(err.contains("audio"), "refusal must name the audio: {err}");846 assert!(err.contains("audio"), "refusal must name the audio: {err}");
847 }847 }
848 848
849+/// The user path a silent take goes down: a file with no audio track lands on a
850+/// timeline that has one, is placed as the grouped take every video file is,
851+/// and plays -- pictures over its span, silence under them. The sound itself is
852+/// asserted on the samples in `tests/audio_export.rs`; what is asserted here is
853+/// that nothing about the *timeline* is refused or lost.
854+#[test]
855+fn a_silent_file_joins_a_timeline_with_sound_and_plays() {
856+ let mut session = open(asset("test_av.mp4"));
857+ import_and_place(&mut session, &asset("test_mismatch.mp4"));
858+ // 150 frames of test_av, then 60 of the silent file, at 30 fps.
859+ assert_eq!(session.clip_spans().len(), 2, "the silent take landed");
860+ assert!((session.timeline_duration() - 7.0).abs() < 1e-9);
861+ // Both lanes carry it: a silent file is a normal grouped take, and its
862+ // audio clip is the span the worker fills with silence.
863+ assert_eq!(session.lane_clips(Lane::V1).len(), 2);
864+ assert_eq!(session.lane_clips(Lane::A1).len(), 2);
865+
866+ // ...and it decodes: a picture from inside the silent clip's span, at the
867+ // project's resolution like every other clip.
868+ session.seek(6.0);
869+ let frame = next_frame(&mut session, "the silent clip");
870+ assert_eq!((frame.width, frame.height), session.resolution());
871+}
872+
849 /// The user-facing point of a project resolution: media of two sizes on one873 /// The user-facing point of a project resolution: media of two sizes on one
850 /// timeline, each composed onto the project's own canvas.874 /// timeline, each composed onto the project's own canvas.
851 ///875 ///
crates/engine/tests/saveload.rsmodified+6 -5
@@ -733,7 +733,7 @@ fn malformed_files_are_numbered_errors_and_never_panics() {
733 fn a_source_that_no_longer_matches_the_timeline_is_refused_in_import_words() {733 fn a_source_that_no_longer_matches_the_timeline_is_refused_in_import_words() {
734 let dir = scratch("mismatch");734 let dir = scratch("mismatch");
735 copy_in(&dir, "test_av.mp4");735 copy_in(&dir, "test_av.mp4");
736- std::fs::copy(asset("test_mismatch.mp4"), dir.join("test_av2.mp4")).expect("substitute");736+ std::fs::copy(asset("test_25fps.mp4"), dir.join("test_av2.mp4")).expect("substitute");
737 let path = dir.join("swapped.edith");737 let path = dir.join("swapped.edith");
738 std::fs::write(738 std::fs::write(
739 &path,739 &path,
@@ -744,13 +744,14 @@ fn a_source_that_no_longer_matches_the_timeline_is_refused_in_import_words() {
744 .err()744 .err()
745 .expect("a source that stopped matching must not open")745 .expect("a source that stopped matching must not open")
746 .to_string();746 .to_string();
747- // The suffix is `import`'s own refusal, word for word. The substitute is747+ // The suffix is `import`'s own refusal, word for word. The substitute runs
748- // 640x360 *and* silent; only the second of those is a refusal now -- a748+ // at 25 fps, which is the property left: a resolution of its own is placed
749- // resolution of its own is placed on the project canvas.749+ // on the project canvas, a codec of its own opens its own decoder, and a
750+ // file with no sound plays silence -- none of those is a refusal any more.
750 assert_eq!(751 assert_eq!(
751 err,752 err,
752 format!(753 format!(
753- "source {}: the file is silent, the timeline has audio",754+ "source {}: 25.000 fps does not match the timeline's 30.000 fps",
754 dir.join("test_av2.mp4").display()755 dir.join("test_av2.mp4").display()
755 )756 )
756 );757 );
crates/engine/tests/vp9.rsmodified+22 -6
@@ -76,17 +76,33 @@ fn the_software_path_refuses_vp9_by_name() {
76 assert!(h264, "software H.264 decode still opens");76 assert!(h264, "software H.264 decode still opens");
77 }77 }
78 78
79-/// A VP9 timeline is refused a source coded differently, in the same words a79+/// A timeline is *not* refused a source coded differently -- every clip opens
80-/// resolution mismatch is refused in: a front-end shows the string as it is.80+/// its own decoder. What survives is the reason the codec gate existed: on a
81+/// machine that cannot decode VP9 the file is refused at the door, by the
82+/// decoder's own name, rather than becoming a clip of black frames.
81 #[test]83 #[test]
82-fn a_timeline_refuses_the_other_codec() {84+fn a_timeline_takes_the_other_codec_or_names_the_missing_decoder() {
83 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4");85 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4");
86+ // The no-plugin machine, forced.
87+ // SAFETY: the suite is documented to run with --test-threads=1.
88+ unsafe { std::env::set_var("VE_SW", "1") };
84 let refused = session89 let refused = session
85 .import(&asset("test_vp9.mp4"))90 .import(&asset("test_vp9.mp4"))
86- .expect_err("VP9 must not join an H.264 timeline")91+ .expect_err("no VP9 decoder means no VP9 clip")
87 .to_string();92 .to_string();
88- assert!(refused.contains("VP9"), "{refused}");93+ unsafe { std::env::remove_var("VE_SW") };
89- assert!(refused.contains("H.264"), "{refused}");94+ assert_eq!(refused, Codec::Vp9.needs_plugin());
95+ assert!(
96+ !refused.contains("H.264"),
97+ "the timeline's own codec is no longer a reason: {refused}"
98+ );
99+ assert_eq!(session.sources().len(), 1, "a refusal left no row");
100+
101+ // ...and where a decoder exists, it simply joins.
102+ match session.import(&asset("test_vp9.mp4")) {
103+ Ok(_) => assert_eq!(session.sources().len(), 2, "VP9 beside H.264"),
104+ Err(e) => assert_eq!(e.to_string(), Codec::Vp9.needs_plugin()),
105+ }
90 }106 }
91 107
92 /// The end-to-end user path: opening the file yields pictures, all of them,108 /// The end-to-end user path: opening the file yields pictures, all of them,