diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index bbba1be..7ed6df1 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -1548,6 +1548,11 @@ impl Player { match session.cut_regions(®ions, &lanes) { Ok(()) => { self.close_silence(); + // Every hole closed moves the clips after it up a place, so the + // selection now names a different clip than the one that is + // highlighted -- dropped here as after every other edit that + // moves indexes (a delete, a paste, an undo). + self.selected = None; self.reset_after_reseek(); self.notice = Some( format!( @@ -1582,6 +1587,10 @@ impl Player { match session.speed_regions(®ions, rate, &lanes) { Ok(()) => { self.close_silence(); + // Splitting each silence out and closing the room it no longer + // needs moves indexes exactly as the cut does: the selection + // goes with them. + self.selected = None; self.reset_after_reseek(); self.notice = Some( format!( @@ -2332,20 +2341,43 @@ impl Player { .as_mut() .map(|session| session.remove_source(path, stream)); let text = match removed { - Some(Ok(())) => { + Some(Ok(idx)) => { // The picked row may be the one that just went, and the engine // reseeks, so this owes the flag reset like every other edit. if self.selected_asset.as_ref() == Some(&(path.to_path_buf(), stream)) { self.selected_asset = None; } + // A copied clip names its source by *index*, and every index + // past the one that went has just moved down: without this the + // next paste puts some other file on the timeline. + self.clipboard = clipboard_after_remove(self.clipboard, idx); self.reset_after_reseek(); - // The undo stack goes with it (`Project::remove_source`): said - // here, because a `z` that does nothing afterwards would - // otherwise read as a bug. - format!( - "REMOVED {} — there is nothing left to undo", - file_name(path) - ) + // The last row leaves a session naming no file: nothing to + // play, nothing to save and nothing to show, which is the empty + // window the editor launches as. The next import scaffolds a + // fresh timeline from whatever file it is, at that file's own + // rate -- which is why the session goes rather than lingering + // on with the gone file's parameters. + match self + .session + .as_ref() + .is_some_and(|s| s.sources().is_empty()) + { + true => { + self.close_session(); + format!( + "REMOVED {} — the library is empty; import a file to start again", + file_name(path) + ) + } + // The undo stack goes with it (`Project::remove_source`): + // said here, because a `z` that does nothing afterwards + // would otherwise read as a bug. + false => format!( + "REMOVED {} — there is nothing left to undo", + file_name(path) + ), + } } Some(Err(e)) => format!("NOT REMOVED — {e}"), None => "NO TIMELINE — open a file first".to_string(), @@ -2354,6 +2386,64 @@ impl Player { cx.notify(); } + /// Back to the window the editor launches as: no timeline, no library, no + /// picture -- and the hint that says to open a file. What removing the last + /// library row leaves, since a session whose library is empty has nothing + /// left to be ([`Player::remove_source`]). + /// + /// Everything a *loaded project* resets goes here for its reasons (an index + /// into a timeline that is gone names nothing), plus the three per-file + /// caches: they are keyed by path, and the next file to arrive fills them + /// again. + fn close_session(&mut self) { + self.session = None; + // The picture goes with it, or the empty window would keep showing the + // last frame of a timeline that no longer exists. + // + // ponytail: its atlas tile is not released -- `window.drop_image` wants + // a `&mut Window` this door has no other reason to take. One tile per + // emptied library, against one per displayed frame in `pump`; the + // upgrade path is threading the window through `act_on_row`. + self.image = None; + self.clipboard = None; + self.selected = None; + self.selected_asset = None; + self.context_menu = None; + self.library_menu = None; + self.eq_open = None; + self.color_open = None; + self.speed_open = None; + self.close_silence(); + self.waves.clear(); + self.streams.clear(); + self.sizes.clear(); + // Scanned off a source that is not in the library any more. + self.silence_levels = None; + // Every gesture in flight, dropped for `reset_after_reseek`'s reason + // (it drops the trim below): a drag holds a bar, a clip or a band of a + // timeline that has just stopped existing. + self.scrubbing = false; + self.volume_dragging = false; + self.eq_dragging = false; + self.speed_dragging = false; + self.color_dragging = false; + self.displayed = 0; + self.dropped = 0; + self.started = None; + // The empty window's own: no name in the titlebar, nowhere chosen to + // export or save to yet, and a rate that only keeps the timecode + // reading in frames until a file brings its own (`main`). + self.name = NO_FILE.into(); + self.export_path = PathBuf::new(); + self.project_path = PathBuf::new(); + self.fps = 30.; + // No decoder to wait for a frame from: the hint is what shows. + self.reset_after_reseek(); + self.pending_seek = false; + self.eos = false; + self.done = false; + } + /// One item of a library row's menu, done. Every one of them closes the /// menu first -- the list under it is about to be rebuilt -- except the one /// that turns the card over. @@ -2387,11 +2477,22 @@ impl Player { cx.notify(); } - /// The rate and layout the whole timeline's audio is, taken from source 0's - /// own stream: what a library row has to match to be placeable. `None` - /// until that file has been probed, and then nothing is greyed for it. + /// The rate and layout the whole timeline's audio is, taken from the stream + /// of the first source that could have one: what a library row has to match + /// to be placeable. `None` until that file has been probed, and then nothing + /// is greyed for it. + /// + /// The first source that is *not a still*, which is the rule the engine + /// holds every import to (`playback::audio_source_of`) -- a picture at the + /// head of the list (a removal moves indexes) has no stream to describe + /// anything with. fn timeline_audio(&self) -> Option<(u32, u16)> { - let first = self.session.as_ref()?.sources().first()?; + let first = self + .session + .as_ref()? + .sources() + .iter() + .find(|s| !engine::is_image(&s.path))?; let info = self .streams .get(&first.path)? @@ -6301,6 +6402,28 @@ fn can_add(picked: Option<&(PathBuf, usize)>, timeline: bool, exporting: bool) - picked.is_some() && timeline && !exporting } +/// What is left on the clipboard after the library row at `removed` was taken +/// out. A copied clip names its file by *index* into the source list +/// (`engine::Clip::source`) and a removal renumbers that list +/// (`engine::Project::remove_source`), so a clipboard kept as it was would paste +/// **a different file** -- the next one along -- over the range it was copied +/// from. +/// +/// The clip's own file gone means there is nothing to paste: `None`, and the +/// next paste says the clipboard is empty rather than putting some other take +/// down. Every index past it moves down by one, exactly as the lanes' clips do. +fn clipboard_after_remove(clip: Option, removed: usize) -> Option { + let mut clip = clip?; + match clip.source.cmp(&removed) { + std::cmp::Ordering::Equal => None, + std::cmp::Ordering::Greater => { + clip.source -= 1; + Some(clip) + } + std::cmp::Ordering::Less => Some(clip), + } +} + /// One library row: a file and one of its audio streams. Plain data, planned /// before anything is drawn -- which rows exist at all is the branchy part. #[derive(Debug, PartialEq)] @@ -7715,12 +7838,12 @@ mod tests { MENU_PAD, MENU_ROW_H, MENU_ROWS_H, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS, SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo, VOLUME_W, Volume, WAVE_BPS, WAVE_COL, Wave, applicable, band_label, - can_add, cancels_export, color_snap, envelope, eq_spectrum, eq_x, eq_y, export_path, - export_settings, format_key, format_line, format_refusal, frac_along, frac_down, frame_at, - histogram, is_bare_modifier, is_project, keymap, lanes_h, marked, menu_at, normalise, - nothing_to_play, panel_h, project_path, push_digit, retarget, scrub_due, show_label, - silence_rate, source_tint, span_partner, speed_at, timecode, unseen_paths, unseen_sources, - whole_take, width_frac, window_title, + can_add, cancels_export, clipboard_after_remove, color_snap, envelope, eq_spectrum, eq_x, + eq_y, export_path, export_settings, format_key, format_line, format_refusal, frac_along, + frac_down, frame_at, histogram, is_bare_modifier, is_project, keymap, lanes_h, marked, + menu_at, normalise, nothing_to_play, panel_h, project_path, push_digit, retarget, + scrub_due, show_label, silence_rate, source_tint, span_partner, speed_at, timecode, + unseen_paths, unseen_sources, whole_take, width_frac, window_title, }; use super::{ LaneKind, Repeat, View, ZOOM_MIN_FRAMES, ZOOM_STEP, file_name, file_uri, library_rows, @@ -8400,17 +8523,71 @@ mod tests { .expect("nothing plays av2 any more"); assert_eq!(rows(&session), 1, "the row went with it"); assert_eq!(session.sources().len(), 1); - // The one file left cannot go: a project that names none is not one - // that reopens. + // The one file left is held to the same rule and no other: its own take + // is still on the lanes, so it stays... + let first = session.sources()[0].path.clone(); let refusal = session - .remove_source(&session.sources()[0].path.clone(), 0) - .expect_err("the last file stays") + .remove_source(&first, 0) + .expect_err("its take is still on the timeline") .to_string(); - assert!(refusal.contains("only file"), "{refusal}"); + assert!(refusal.contains("still plays"), "{refusal}"); + // ...and once nothing plays it, the *last* row goes too. What is left + // is the empty library `Player::close_session` turns back into the + // window the editor launches as -- the user-reported bug was that this + // very removal was refused, leaving a row that could never be taken + // out. + assert!(session.delete_clip(Lane::V1, 0)); + session + .remove_source(&first, 0) + .expect("the only row goes like any other"); + assert_eq!(rows(&session), 0, "an empty library"); + assert!(session.sources().is_empty()); + // And it is still a session: silent, empty, and asked for its length + // rather than panicking on a source list that is not there. + assert_eq!(session.timeline_duration(), 0.0); + assert!( + session.save_project(&asset("nothing.edith")).is_err(), + "a project naming no file could never be opened again, so it is not written" + ); // A row this timeline never had is refused, not panicked on. assert!(session.remove_source(&second, 0).is_err()); } + /// The clipboard after a library removal. A copied clip names its file by + /// index and a removal renumbers the list, so this is the difference + /// between pasting the take that was copied and pasting **another file** + /// over the same range ([`clipboard_after_remove`], called by + /// [`Player::remove_source`]). + #[test] + fn a_copied_clip_is_renumbered_or_dropped_when_a_row_leaves_the_library() { + let clip = |source: usize| Clip { + start: 0, + in_frame: 0, + out_frame: 30, + source, + link: None, + eq: None, + color: None, + fit: Default::default(), + speed: Default::default(), + }; + // Copied from source 2, source 0 removed: the same file is source 1 now. + assert_eq!( + clipboard_after_remove(Some(clip(2)), 0).map(|c| c.source), + Some(1), + "the clipboard follows its file down the list" + ); + // Copied from a source *before* the one that went: untouched. + assert_eq!( + clipboard_after_remove(Some(clip(0)), 2).map(|c| c.source), + Some(0) + ); + // Copied from the row that was just removed: there is nothing left to + // paste, and pasting the next file along would be a lie. + assert!(clipboard_after_remove(Some(clip(1)), 1).is_none()); + assert!(clipboard_after_remove(None, 0).is_none()); + } + /// The trim-a-clip path through the doors the edge drag uses: /// [`Player::trim_to`] clamps the pointer with `trim_room` and /// [`Player::commit_trim`] writes it with `trim_clip`. The clip plays less diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index 34e097f..49114e1 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -268,14 +268,23 @@ impl AudioSession { eqs: &[Option], speeds: &[Option], ) -> crate::Result)>> { - let Some((path, stream)) = sources.first() else { + // The first source that could have a track, which is not always index 0: + // a still image has none, and one at the front of the list (a save + // renumbers, a library removal moves indexes) would be opened as a + // broken audio file and take the whole timeline's sound down with it. + // The same rule `PlaybackSession` probes by (`audio_source_of`). + let Some((at, (path, stream))) = sources + .iter() + .enumerate() + .find(|(_, (path, _))| !crate::is_image(path)) + else { return Ok(None); }; let Some(first) = Track::open(path, *stream)? else { return Ok(None); }; - // The timeline's meta is the first source's: policy makes every other - // source match it, and the checks below hold them to that. + // The timeline's meta is that source's: policy makes every other source + // match it, and the checks below hold them to that. let meta = AudioMeta { sample_rate: first.sample_rate(), channels: first.channels()?, @@ -286,7 +295,7 @@ impl AudioSession { first.check_decoder()?; let mut tracks: Vec> = sources.iter().map(|_| None).collect(); - tracks[0] = Some(first); + tracks[at] = Some(first); for &(source, ..) in segs { let Some(source) = source else { continue; // a gap opens no file @@ -459,8 +468,9 @@ impl AudioSession { let mut meta = None; let mut rxs = Vec::with_capacity(lanes.len()); for (i, segs) in lanes.iter().enumerate() { - // Every lane probes the same source 0, so the metas agree by - // construction; `None` from any of them is a silent timeline. + // Every lane takes its meta from the same source, so the metas + // agree by construction; `None` from any of them is a silent + // timeline. let flat = Vec::new(); let plain = Vec::new(); let Some((lane_meta, rx)) = Self::open_multi_streams_speed( diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 13cd7e2..cc58c39 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -442,10 +442,12 @@ impl PlaybackSession { /// /// A *new* session rather than a reload of this one, so a load that fails /// leaves the caller's current session untouched -- atomic by - /// construction. Every named file is opened and checked here: source 0 - /// defines the timeline exactly as `open` does, every other source has to - /// match it the way [`import`](Self::import) demands, and every clip has to - /// still be inside the file it plays from. A source that vanished or + /// construction. Every named file is opened and checked here: the + /// *scaffolding* source -- the first that is not a still, since a picture + /// carries no rate -- defines the timeline exactly as `open` does, every + /// other source has to match it the way [`import`](Self::import) demands + /// (a save renumbers, so which index that is says nothing), and every clip + /// has to still be inside the file it plays from. A source that vanished or /// shrank since the save is a refusal naming it, not a silently shorter /// timeline -- the disappearing-file tolerance elsewhere in this type /// applies only *after* a project has loaded. @@ -453,15 +455,35 @@ impl PlaybackSession { /// The undo history is not saved: `undo` is `false` on a fresh load. pub fn open_project(path: &Path) -> crate::Result { let doc = crate::edith::load(path)?; + // *Which* source scaffolds it: the first that is not a still, and index + // 0 only when there is no other. A still defines no frame rate -- it is + // given [`IMAGE_ONLY_RATE`] -- so scaffolding a timeline of 24 fps + // footage off a PNG that a save happened to renumber to index 0 + // (`Project::without_orphan_sources` numbers by first use, and a + // library removal moves indexes too) reads the timeline as 30 fps and + // then refuses every file on it for not matching. The rule this and + // [`audio_source_of`] share: nothing may assume what source 0 *is*. + // + // ponytail: a timeline of nothing but stills, or of stills and songs, + // still comes back at the rate its scaffold implies rather than the one + // it was cut at -- the rate is written nowhere in the file. The upgrade + // path is a dialect that writes it (`crate::edith`), which is also what + // a project naming no file at all would need. + let scaffold = doc + .sources + .iter() + .position(|s| !crate::is_image(&s.path)) + .unwrap_or(0); // Owned: the sources move into the `Project` below, and the device is // opened after that (see the comment there). let first = doc .sources - .first() + .get(scaffold) .cloned() .ok_or("the project names no sources")?; - // Source 0 both scaffolds the session and defines the timeline, so it - // is opened for playback rather than merely probed. + // The scaffolding source both defines the timeline and is what the + // playhead's first picture comes from, so it is opened for playback + // rather than merely probed. // One value, not two locals: everything below this line can refuse, and // locals drop in reverse declaration order -- a bare worker would join // its decode thread while the receiver next to it was still holding @@ -528,8 +550,15 @@ impl PlaybackSession { } let first_audio = first_audio_of(&doc.sources)?; - let mut counts = vec![meta.frame_count]; - for source in &doc.sources[1..] { + // In source order, with the scaffold's own count in its own slot: the + // clip check below indexes this list by source, so it must line up with + // `doc.sources` whichever entry the scaffolding came from. + let mut counts = Vec::with_capacity(doc.sources.len()); + for (i, source) in doc.sources.iter().enumerate() { + if i == scaffold { + counts.push(meta.frame_count); + continue; + } // A still has neither a rate to match nor a track to match with: // its length is the one it is held to, recomputed exactly as the // import that first noted it did ([`image_frames`]), which is what @@ -604,7 +633,15 @@ impl PlaybackSession { // only a session's `drop` retires it, so a refusal above this line would // leave a PipeWire stream and a thread behind for a project that never // opened. Nothing before it needs the device. - let (audio, audio_disabled) = open_audio(&first.path, first.audio_stream); + // + // On the source the timeline's *sound* is defined by, which is the + // scaffold unless that one is a still ([`audio_source_of`]): opening a + // PNG as the device is a session with no audio at all, however many + // clips with sound are on its lanes. + let (audio, audio_disabled) = match audio_source_of(project.sources()) { + Some(source) => open_audio(&source.path, source.audio_stream), + None => (None, None), + }; let mut session = Self { meta, native, @@ -652,7 +689,16 @@ impl PlaybackSession { /// Writes the timeline to `path` as a `.edith`, atomically (see /// [`crate::edith`]). Sources no clip plays from are left out, and the /// playhead is saved with it so a reopened project resumes where it stood. + /// + /// Refused, writing nothing, for a session whose library is empty (every + /// row removed, [`Project::remove_source`]): a file naming no source has no + /// timeline in it and [`open_project`](Self::open_project) could only + /// refuse it, so the refusal belongs here, where nothing has been + /// overwritten yet. pub fn save_project(&self, path: &Path) -> crate::Result<()> { + if self.project.sources().is_empty() { + return Err("this project names no file: there is nothing to save".into()); + } let (sources, lanes, eq, color) = self.project.without_orphan_sources(); let playhead = secs_to_frame(self.now(), self.meta.frame_rate) .min(self.project.timeline_frames().saturating_sub(1)); @@ -1318,7 +1364,14 @@ impl PlaybackSession { /// Reseeks like an edit even though nothing playable changed: the clip /// indexes into the source list have just moved, and the running workers /// were opened against the old numbering. - pub fn remove_source(&mut self, path: &Path, stream: usize) -> crate::Result<()> { + /// + /// The index that went, because everything past it moved down: a caller + /// holding a source index of its own (a clipboard) has to fix it up or drop + /// it, or it names a different file afterwards. The **last** row goes like + /// any other and leaves a session with an empty library -- silent, empty of + /// clips, and unsaveable ([`save_project`](Self::save_project)); a + /// front-end showing one is showing an empty window. + pub fn remove_source(&mut self, path: &Path, stream: usize) -> crate::Result { let wanted = Source::new(path, stream); let idx = self .project @@ -1337,11 +1390,12 @@ impl PlaybackSession { } let now = self.now(); self.seek(now); - Ok(()) + Ok(idx) } - /// What the timeline's audio *is*: source 0's chosen stream, probed. Every - /// other source is held to it. + /// What the timeline's audio *is*: the chosen stream of the first source + /// that could have any ([`audio_source_of`]), probed. Every other source is + /// held to it. fn first_audio(&self) -> crate::Result> { first_audio_of(self.project.sources()) } @@ -1779,12 +1833,26 @@ fn matches_timeline( /// source 0 has always given. This function widens which source is asked, not /// what the answer means. fn first_audio_of(sources: &[Source]) -> crate::Result> { - match sources.iter().find(|s| !crate::is_image(&s.path)) { + match audio_source_of(sources) { Some(first) => AudioSession::probe(&first.path, first.audio_stream), None => Ok(None), } } +/// *Which* source that is: the first one that is not a still. The single answer +/// to "what does this timeline's sound come from", so that probing it +/// ([`first_audio_of`]) and opening the device on it +/// ([`PlaybackSession::open_project`]) can never disagree -- source 0 is only +/// the scaffolding file until a save renumbers it or a library removal takes it +/// away ([`crate::Project::remove_source`]), and a PNG at index 0 opened as the +/// device is a timeline that plays silent although every clip on it has sound. +/// +/// `None` for a library of nothing but stills, and for one with no file at all: +/// both are silent timelines. +fn audio_source_of(sources: &[Source]) -> Option<&Source> { + sources.iter().find(|s| !crate::is_image(&s.path)) +} + fn audio_matches(source: &Source, first: &Option) -> crate::Result<()> { // Whole-probe equality: rate and layout, which the audio worker holds every // source to anyway. Both silent is a match. @@ -1937,7 +2005,7 @@ fn secs_to_frame(secs: f64, fps: f64) -> u32 { #[cfg(test)] mod tests { - use super::{Edge, Lane, PlaybackSession, secs_to_frame}; + use super::{Edge, Lane, PlaybackSession, Source, audio_source_of, secs_to_frame}; use std::path::PathBuf; fn asset(name: &str) -> PathBuf { @@ -1946,6 +2014,27 @@ mod tests { .join(name) } + /// Which source the timeline's sound is opened on -- the one rule + /// [`open_project`](PlaybackSession::open_project), the probe every import + /// is held to and the audio worker all read through. A still at index 0 is + /// a picture, not a silent timeline: opening the device on it is a project + /// that plays silent although every clip on it has sound. + #[test] + fn the_audio_reference_is_never_a_still() { + let (video, still) = (asset("test_av.mp4"), asset("test_still.png")); + let sources = [Source::new(&still, 0), Source::new(&video, 3)]; + assert_eq!( + audio_source_of(&sources).map(|s| (&s.path, s.audio_stream)), + Some((&sources[1].path, 3)), + "the first source that could have a track, with its own stream" + ); + assert!( + audio_source_of(&sources[..1]).is_none(), + "nothing but stills" + ); + assert!(audio_source_of(&[]).is_none(), "and no file at all"); + } + /// The seam between the two lists a source index reaches: dropping a file /// from the library shortens `sources`, and `counts` -- the frame length /// per source, which is what a trim is walled by -- has to lose the same diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 1620522..7c7fe1e 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -809,10 +809,20 @@ impl Project { /// /// Refused, changing nothing, while any clip still plays from it: the /// refusal names the lanes and how many clips each holds, so a caller can - /// say what has to be deleted first. Refused too for the last entry left, - /// because a project that names no file cannot be reopened - /// (`PlaybackSession::open_project`) and the timeline's audio parameters - /// are read off source 0. + /// say what has to be deleted first. The *last* entry goes like any other + /// -- a project may name no file at all, which is an empty library over an + /// empty timeline (nothing can play, since a clip would have refused the + /// removal). What a front-end does with that is its own decision: `edith`'s + /// window goes back to the empty state it launches in, and + /// [`PlaybackSession::save_project`](crate::PlaybackSession::save_project) + /// refuses to write a project that names nothing, because no such file + /// could be opened again. + /// + /// Every index past `idx` moves down by one, so a caller holding a *raw* + /// source index of its own -- a clipboard, which is the one thing outside + /// this type that does -- has to fix it up or drop it, or a paste plays a + /// different file. [`PlaybackSession::remove_source`] hands back the index + /// that went for exactly that. /// /// ponytail: this retires the undo stack. `history` holds lanes alone, so a /// snapshot older than the removal can name the very source being removed @@ -827,12 +837,6 @@ impl Project { return Err(format!("there is no source {idx} to remove").into()); }; let name = source.path.display().to_string(); - // Asked before the clips are counted: with one file left the answer is - // the same whatever plays, and "the only file" is the more useful half - // of it. - if self.sources.len() == 1 { - return Err(format!("{name} is the only file this project names").into()); - } let used: Vec = handles(&self.lanes) .into_iter() .zip(&self.lanes) @@ -876,9 +880,16 @@ impl Project { /// only the ones a clip names. /// /// One exception, and it is the emptied timeline's: a project no clip plays - /// from still keeps source 0. It is the file a session is scaffolded from -- - /// its frame rate is the timeline's and is written nowhere else -- so a save - /// that pruned it would write a project that cannot be loaded back at all. + /// from still keeps its first source, if it has one. A file is what a + /// reopened project scaffolds itself from -- the frame rate is written + /// nowhere else -- so a save that pruned the last of them would write a + /// project that cannot be loaded back at all. + /// + /// What comes out is *not* ordered by anything a reader may assume: first + /// use, lane by lane, means the entry at index 0 can be a still or a song + /// whatever the session was scaffolded from. `PlaybackSession::open_project` + /// picks its rate and its audio reference by what a source *is*, never by + /// where it sits. pub fn without_orphan_sources(&self) -> Parts { let mut moved = vec![None; self.sources.len()]; let mut sources = Vec::new(); @@ -3931,10 +3942,10 @@ mod tests { } /// The two edges of a removal: it retires the undo stack (the ponytail on - /// [`Project::remove_source`]), and the last entry standing cannot go -- - /// source 0 is where a reopened project reads its frame rate. + /// [`Project::remove_source`]), and the last entry goes like any other + /// once nothing plays it -- a project may name no file at all. #[test] - fn remove_source_retires_undo_and_keeps_the_last_file() { + fn remove_source_retires_undo_and_empties_the_library() { let mut p = two_sources(); assert!(p.delete_in(Lane::V1, 3), "FILE2's take goes first"); assert!(!p.history.is_empty(), "there is something to undo"); @@ -3945,18 +3956,25 @@ mod tests { ); assert!(!p.undo(), "and so there is nothing left to undo"); - // The last file standing stays, whatever plays from it: - // `PlaybackSession::open_project` refuses a project that names no - // sources at all, and the timeline's frame rate lives in source 0. + // The last file standing is held to the one rule every row is -- what + // plays cannot go -- and to no other. assert_eq!(p.sources().len(), 1); let refusal = p .remove_source(0) - .expect_err("the only source must stay") + .expect_err("its clips are still on the lanes") .to_string(); - assert!(refusal.contains("only file"), "{refusal}"); - assert_eq!(p.sources().len(), 1); + assert!(refusal.contains("still plays"), "{refusal}"); + assert_eq!(p.sources().len(), 1, "a refusal changes nothing"); + while p.delete_in(Lane::V1, 0) {} + p.remove_source(0) + .expect("the last row goes like any other"); + assert!( + p.sources().is_empty(), + "a project may name no file at all: an empty library over an empty timeline" + ); + assert_eq!(p.timeline_frames(), 0); assert!( - p.remove_source(1).is_err(), + p.remove_source(0).is_err(), "and an index that is not there is refused, not panicked on" ); } diff --git a/crates/engine/tests/images.rs b/crates/engine/tests/images.rs index ba0d666..18de6d7 100644 --- a/crates/engine/tests/images.rs +++ b/crates/engine/tests/images.rs @@ -360,6 +360,95 @@ fn a_still_survives_the_project_round_trip() { let _ = std::fs::remove_dir_all(&dir); } +/// The save renumbers sources by first use, so a still at the head of `V1` +/// comes back as **source 0** however the session was scaffolded -- and source +/// 0 is what everything used to read the timeline off. A picture defines no +/// frame rate and has no sound, so the reload used to read this project as 30 +/// fps (refusing the 25 fps footage still on `A1` by name) and open the output +/// device on a PNG (a timeline that plays silent although its clips have +/// sound). Nothing may assume what source 0 *is*: the rate comes from the first +/// source that has one, and the sound from the first that could have any. +#[test] +fn a_still_at_saved_source_zero_keeps_the_rate_and_the_sound() { + pin_software(); + let dir = std::env::temp_dir().join(format!("ve_still_first_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("scratch dir"); + let media = dir.join("test_25fps.mp4"); + let still = dir.join("test_still.png"); + std::fs::copy(asset("test_25fps.mp4"), &media).expect("copy the video"); + std::fs::copy(asset("test_still.png"), &still).expect("copy the still"); + + // 25 fps, which no still is ever given: the rate alone says which source + // the reload scaffolded from. + let mut session = PlaybackSession::open(&media).expect("open the fixture"); + session.set_gain(0.0); + assert!((session.meta().frame_rate - 25.0).abs() < 0.01); + session.import(&still).expect("a picture"); + // Over the head of V1, where it takes the whole take's picture: the sound + // stays on A1, so the still is the first clip in save order and the video + // is a source only the audio lane names. + assert!( + session + .place_stream_at(0.0, &still, 0, Some(Lane::V1)) + .expect("a still joins any timeline") + ); + assert!(session.lane_clips(Lane::V1).len() == 1 && session.lane_clips(Lane::A1).len() == 1); + + let project = dir.join("still_first.edith"); + session.save_project(&project).expect("save"); + let text = std::fs::read_to_string(&project).expect("read the project"); + let source_0 = text + .lines() + .find(|l| l.starts_with("source ")) + .expect("a source line"); + assert!( + source_0.contains("test_still.png"), + "the premise: the save put the still at index 0 -- {source_0}" + ); + + let reopened = PlaybackSession::open_project(&project).expect("a saved project always reopens"); + assert!( + (reopened.meta().frame_rate - 25.0).abs() < 0.01, + "the footage's rate, not the still's 30: {}", + reopened.meta().frame_rate + ); + // The same sound, at the same place, playing the same file -- by a *new* + // index, which is the renumbering this whole test is about. + let (sound, was) = ( + reopened.lane_clips(Lane::A1)[0], + session.lane_clips(Lane::A1)[0], + ); + assert_eq!( + (sound.start, sound.in_frame, sound.out_frame), + (was.start, was.in_frame, was.out_frame) + ); + assert!( + reopened.sources()[sound.source] + .path + .ends_with("test_25fps.mp4"), + "the take's sound still names the video" + ); + assert!( + reopened.audio_disabled_reason().is_none(), + "a still is not a reason a timeline is silent: {:?}", + reopened.audio_disabled_reason() + ); + // And the sound itself, through the very opener a seek builds its worker + // with: source 0 is the PNG here, and one opened unconditionally is an + // error that takes every lane's audio down with it. + let sources: Vec<_> = reopened + .sources() + .iter() + .map(|s| (s.path.clone(), s.audio_stream)) + .collect(); + let (meta, _rx) = engine::AudioSession::open_multi_streams(&sources, &[(Some(1), 0.0, 1.0)]) + .expect("the worker opens over a still at index 0") + .expect("the take on A1 has sound"); + assert_eq!(meta.sample_rate, 44_100, "the take's own rate"); + let _ = std::fs::remove_dir_all(&dir); +} + /// The export is what was watched: a timeline of video then still comes back /// out of the mp4 as video then still, with the still's own colours in it. #[test]