forge
Explore
Log in

Don't you dare go Hollow

The last media leaves and nothing assumes it stayed

Browse files at this commit

96c9fbe1cc8e84cfce6a4ba5fc222546f3d06a65Ahmet Kaan GümüşParent: 88fbed0
  • fix
    • the last media leaves and nothing assumes it stayed
Show full message
🐛 fix(library): the last media leaves and nothing assumes it stayed
crates/app/src/main.rsmodified+190 -23
@@ -1408,6 +1408,11 @@ impl Player {
1408 match session.cut_regions(&regions, &lanes) {1408 match session.cut_regions(&regions, &lanes) {
1409 Ok(()) => {1409 Ok(()) => {
1410 self.close_silence();1410 self.close_silence();
1411+ // Every hole closed moves the clips after it up a place, so the
1412+ // selection now names a different clip than the one that is
1413+ // highlighted -- dropped here as after every other edit that
1414+ // moves indexes (a delete, a paste, an undo).
1415+ self.selected = None;
1411 self.reset_after_reseek();1416 self.reset_after_reseek();
1412 self.notice = Some(1417 self.notice = Some(
1413 format!(1418 format!(
@@ -1442,6 +1447,10 @@ impl Player {
1442 match session.speed_regions(&regions, rate, &lanes) {1447 match session.speed_regions(&regions, rate, &lanes) {
1443 Ok(()) => {1448 Ok(()) => {
1444 self.close_silence();1449 self.close_silence();
1450+ // Splitting each silence out and closing the room it no longer
1451+ // needs moves indexes exactly as the cut does: the selection
1452+ // goes with them.
1453+ self.selected = None;
1445 self.reset_after_reseek();1454 self.reset_after_reseek();
1446 self.notice = Some(1455 self.notice = Some(
1447 format!(1456 format!(
@@ -2133,20 +2142,43 @@ impl Player {
2133 .as_mut()2142 .as_mut()
2134 .map(|session| session.remove_source(path, stream));2143 .map(|session| session.remove_source(path, stream));
2135 let text = match removed {2144 let text = match removed {
2136- Some(Ok(())) => {2145+ Some(Ok(idx)) => {
2137 // The picked row may be the one that just went, and the engine2146 // The picked row may be the one that just went, and the engine
2138 // reseeks, so this owes the flag reset like every other edit.2147 // reseeks, so this owes the flag reset like every other edit.
2139 if self.selected_asset.as_ref() == Some(&(path.to_path_buf(), stream)) {2148 if self.selected_asset.as_ref() == Some(&(path.to_path_buf(), stream)) {
2140 self.selected_asset = None;2149 self.selected_asset = None;
2141 }2150 }
2151+ // A copied clip names its source by *index*, and every index
2152+ // past the one that went has just moved down: without this the
2153+ // next paste puts some other file on the timeline.
2154+ self.clipboard = clipboard_after_remove(self.clipboard, idx);
2142 self.reset_after_reseek();2155 self.reset_after_reseek();
2143- // The undo stack goes with it (`Project::remove_source`): said2156+ // The last row leaves a session naming no file: nothing to
2144- // here, because a `z` that does nothing afterwards would2157+ // play, nothing to save and nothing to show, which is the empty
2145- // otherwise read as a bug.2158+ // window the editor launches as. The next import scaffolds a
2146- format!(2159+ // fresh timeline from whatever file it is, at that file's own
2147- "REMOVED {} — there is nothing left to undo",2160+ // rate -- which is why the session goes rather than lingering
2148- file_name(path)2161+ // on with the gone file's parameters.
2149- )2162+ match self
2163+ .session
2164+ .as_ref()
2165+ .is_some_and(|s| s.sources().is_empty())
2166+ {
2167+ true => {
2168+ self.close_session();
2169+ format!(
2170+ "REMOVED {} — the library is empty; import a file to start again",
2171+ file_name(path)
2172+ )
2173+ }
2174+ // The undo stack goes with it (`Project::remove_source`):
2175+ // said here, because a `z` that does nothing afterwards
2176+ // would otherwise read as a bug.
2177+ false => format!(
2178+ "REMOVED {} — there is nothing left to undo",
2179+ file_name(path)
2180+ ),
2181+ }
2150 }2182 }
2151 Some(Err(e)) => format!("NOT REMOVED — {e}"),2183 Some(Err(e)) => format!("NOT REMOVED — {e}"),
2152 None => "NO TIMELINE — open a file first".to_string(),2184 None => "NO TIMELINE — open a file first".to_string(),
@@ -2155,6 +2187,54 @@ impl Player {
2155 cx.notify();2187 cx.notify();
2156 }2188 }
2157 2189
2190+ /// Back to the window the editor launches as: no timeline, no library, no
2191+ /// picture -- and the hint that says to open a file. What removing the last
2192+ /// library row leaves, since a session whose library is empty has nothing
2193+ /// left to be ([`Player::remove_source`]).
2194+ ///
2195+ /// Everything a *loaded project* resets goes here for its reasons (an index
2196+ /// into a timeline that is gone names nothing), plus the three per-file
2197+ /// caches: they are keyed by path, and the next file to arrive fills them
2198+ /// again.
2199+ fn close_session(&mut self) {
2200+ self.session = None;
2201+ // The picture goes with it, or the empty window would keep showing the
2202+ // last frame of a timeline that no longer exists.
2203+ //
2204+ // ponytail: its atlas tile is not released -- `window.drop_image` wants
2205+ // a `&mut Window` this door has no other reason to take. One tile per
2206+ // emptied library, against one per displayed frame in `pump`; the
2207+ // upgrade path is threading the window through `act_on_row`.
2208+ self.image = None;
2209+ self.clipboard = None;
2210+ self.selected = None;
2211+ self.selected_asset = None;
2212+ self.context_menu = None;
2213+ self.library_menu = None;
2214+ self.eq_open = None;
2215+ self.color_open = None;
2216+ self.speed_open = None;
2217+ self.close_silence();
2218+ self.waves.clear();
2219+ self.streams.clear();
2220+ self.sizes.clear();
2221+ self.displayed = 0;
2222+ self.dropped = 0;
2223+ self.started = None;
2224+ // The empty window's own: no name in the titlebar, nowhere chosen to
2225+ // export or save to yet, and a rate that only keeps the timecode
2226+ // reading in frames until a file brings its own (`main`).
2227+ self.name = NO_FILE.into();
2228+ self.export_path = PathBuf::new();
2229+ self.project_path = PathBuf::new();
2230+ self.fps = 30.;
2231+ // No decoder to wait for a frame from: the hint is what shows.
2232+ self.reset_after_reseek();
2233+ self.pending_seek = false;
2234+ self.eos = false;
2235+ self.done = false;
2236+ }
2237+
2158 /// One item of a library row's menu, done. Every one of them closes the2238 /// One item of a library row's menu, done. Every one of them closes the
2159 /// menu first -- the list under it is about to be rebuilt -- except the one2239 /// menu first -- the list under it is about to be rebuilt -- except the one
2160 /// that turns the card over.2240 /// that turns the card over.
@@ -2188,11 +2268,22 @@ impl Player {
2188 cx.notify();2268 cx.notify();
2189 }2269 }
2190 2270
2191- /// The rate and layout the whole timeline's audio is, taken from source 0's2271+ /// The rate and layout the whole timeline's audio is, taken from the stream
2192- /// own stream: what a library row has to match to be placeable. `None`2272+ /// of the first source that could have one: what a library row has to match
2193- /// until that file has been probed, and then nothing is greyed for it.2273+ /// to be placeable. `None` until that file has been probed, and then nothing
2274+ /// is greyed for it.
2275+ ///
2276+ /// The first source that is *not a still*, which is the rule the engine
2277+ /// holds every import to (`playback::audio_source_of`) -- a picture at the
2278+ /// head of the list (a removal moves indexes) has no stream to describe
2279+ /// anything with.
2194 fn timeline_audio(&self) -> Option<(u32, u16)> {2280 fn timeline_audio(&self) -> Option<(u32, u16)> {
2195- let first = self.session.as_ref()?.sources().first()?;2281+ let first = self
2282+ .session
2283+ .as_ref()?
2284+ .sources()
2285+ .iter()
2286+ .find(|s| !engine::is_image(&s.path))?;
2196 let info = self2287 let info = self
2197 .streams2288 .streams
2198 .get(&first.path)?2289 .get(&first.path)?
@@ -5650,6 +5741,28 @@ fn can_add(picked: Option<&(PathBuf, usize)>, timeline: bool, exporting: bool) -
5650 picked.is_some() && timeline && !exporting5741 picked.is_some() && timeline && !exporting
5651 }5742 }
5652 5743
5744+/// What is left on the clipboard after the library row at `removed` was taken
5745+/// out. A copied clip names its file by *index* into the source list
5746+/// (`engine::Clip::source`) and a removal renumbers that list
5747+/// (`engine::Project::remove_source`), so a clipboard kept as it was would paste
5748+/// **a different file** -- the next one along -- over the range it was copied
5749+/// from.
5750+///
5751+/// The clip's own file gone means there is nothing to paste: `None`, and the
5752+/// next paste says the clipboard is empty rather than putting some other take
5753+/// down. Every index past it moves down by one, exactly as the lanes' clips do.
5754+fn clipboard_after_remove(clip: Option<Clip>, removed: usize) -> Option<Clip> {
5755+ let mut clip = clip?;
5756+ match clip.source.cmp(&removed) {
5757+ std::cmp::Ordering::Equal => None,
5758+ std::cmp::Ordering::Greater => {
5759+ clip.source -= 1;
5760+ Some(clip)
5761+ }
5762+ std::cmp::Ordering::Less => Some(clip),
5763+ }
5764+}
5765+
5653 /// One library row: a file and one of its audio streams. Plain data, planned5766 /// One library row: a file and one of its audio streams. Plain data, planned
5654 /// before anything is drawn -- which rows exist at all is the branchy part.5767 /// before anything is drawn -- which rows exist at all is the branchy part.
5655 #[derive(Debug, PartialEq)]5768 #[derive(Debug, PartialEq)]
@@ -6711,12 +6824,12 @@ mod tests {
6711 LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H,6824 LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H,
6712 Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS, SOURCE_TINTS, SPEED_PRESETS,6825 Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS, SOURCE_TINTS, SPEED_PRESETS,
6713 SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo, Volume, WAVE_BPS, WAVE_COL, Wave,6826 SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo, Volume, WAVE_BPS, WAVE_COL, Wave,
6714- applicable, band_label, can_add, cancels_export, color_snap, envelope, eq_x, eq_y,6827+ applicable, band_label, can_add, cancels_export, clipboard_after_remove, color_snap,
6715- export_path, export_settings, format_key, format_line, format_refusal, frac_along,6828+ envelope, eq_x, eq_y, export_path, export_settings, format_key, format_line,
6716- frac_down, frame_at, histogram, is_bare_modifier, is_project, keymap, lanes_h, marked,6829+ format_refusal, frac_along, frac_down, frame_at, histogram, is_bare_modifier, is_project,
6717- menu_at, normalise, panel_h, project_path, push_digit, retarget, scrub_due, show_label,6830+ keymap, lanes_h, marked, menu_at, normalise, panel_h, project_path, push_digit, retarget,
6718- silence_rate, source_tint, span_partner, speed_at, start_frac, timecode, unseen_paths,6831+ scrub_due, show_label, silence_rate, source_tint, span_partner, speed_at, start_frac,
6719- unseen_sources, whole_take, width_frac, window_title,6832+ timecode, unseen_paths, unseen_sources, whole_take, width_frac, window_title,
6720 };6833 };
6721 use super::{LaneKind, file_name, file_uri, library_rows, unscannable};6834 use super::{LaneKind, file_name, file_uri, library_rows, unscannable};
6722 6835
@@ -7306,17 +7419,71 @@ mod tests {
7306 .expect("nothing plays av2 any more");7419 .expect("nothing plays av2 any more");
7307 assert_eq!(rows(&session), 1, "the row went with it");7420 assert_eq!(rows(&session), 1, "the row went with it");
7308 assert_eq!(session.sources().len(), 1);7421 assert_eq!(session.sources().len(), 1);
7309- // The one file left cannot go: a project that names none is not one7422+ // The one file left is held to the same rule and no other: its own take
7310- // that reopens.7423+ // is still on the lanes, so it stays...
7424+ let first = session.sources()[0].path.clone();
7311 let refusal = session7425 let refusal = session
7312- .remove_source(&session.sources()[0].path.clone(), 0)7426+ .remove_source(&first, 0)
7313- .expect_err("the last file stays")7427+ .expect_err("its take is still on the timeline")
7314 .to_string();7428 .to_string();
7315- assert!(refusal.contains("only file"), "{refusal}");7429+ assert!(refusal.contains("still plays"), "{refusal}");
7430+ // ...and once nothing plays it, the *last* row goes too. What is left
7431+ // is the empty library `Player::close_session` turns back into the
7432+ // window the editor launches as -- the user-reported bug was that this
7433+ // very removal was refused, leaving a row that could never be taken
7434+ // out.
7435+ assert!(session.delete_clip(Lane::V1, 0));
7436+ session
7437+ .remove_source(&first, 0)
7438+ .expect("the only row goes like any other");
7439+ assert_eq!(rows(&session), 0, "an empty library");
7440+ assert!(session.sources().is_empty());
7441+ // And it is still a session: silent, empty, and asked for its length
7442+ // rather than panicking on a source list that is not there.
7443+ assert_eq!(session.timeline_duration(), 0.0);
7444+ assert!(
7445+ session.save_project(&asset("nothing.edith")).is_err(),
7446+ "a project naming no file could never be opened again, so it is not written"
7447+ );
7316 // A row this timeline never had is refused, not panicked on.7448 // A row this timeline never had is refused, not panicked on.
7317 assert!(session.remove_source(&second, 0).is_err());7449 assert!(session.remove_source(&second, 0).is_err());
7318 }7450 }
7319 7451
7452+ /// The clipboard after a library removal. A copied clip names its file by
7453+ /// index and a removal renumbers the list, so this is the difference
7454+ /// between pasting the take that was copied and pasting **another file**
7455+ /// over the same range ([`clipboard_after_remove`], called by
7456+ /// [`Player::remove_source`]).
7457+ #[test]
7458+ fn a_copied_clip_is_renumbered_or_dropped_when_a_row_leaves_the_library() {
7459+ let clip = |source: usize| Clip {
7460+ start: 0,
7461+ in_frame: 0,
7462+ out_frame: 30,
7463+ source,
7464+ link: None,
7465+ eq: None,
7466+ color: None,
7467+ fit: Default::default(),
7468+ speed: Default::default(),
7469+ };
7470+ // Copied from source 2, source 0 removed: the same file is source 1 now.
7471+ assert_eq!(
7472+ clipboard_after_remove(Some(clip(2)), 0).map(|c| c.source),
7473+ Some(1),
7474+ "the clipboard follows its file down the list"
7475+ );
7476+ // Copied from a source *before* the one that went: untouched.
7477+ assert_eq!(
7478+ clipboard_after_remove(Some(clip(0)), 2).map(|c| c.source),
7479+ Some(0)
7480+ );
7481+ // Copied from the row that was just removed: there is nothing left to
7482+ // paste, and pasting the next file along would be a lie.
7483+ assert!(clipboard_after_remove(Some(clip(1)), 1).is_none());
7484+ assert!(clipboard_after_remove(None, 0).is_none());
7485+ }
7486+
7320 /// The trim-a-clip path through the doors the edge drag uses:7487 /// The trim-a-clip path through the doors the edge drag uses:
7321 /// [`Player::trim_to`] clamps the pointer with `trim_room` and7488 /// [`Player::trim_to`] clamps the pointer with `trim_room` and
7322 /// [`Player::commit_trim`] writes it with `trim_clip`. The clip plays less7489 /// [`Player::commit_trim`] writes it with `trim_clip`. The clip plays less
crates/engine/src/audio.rsmodified+16 -6
@@ -268,14 +268,23 @@ impl AudioSession {
268 eqs: &[Option<EqParams>],268 eqs: &[Option<EqParams>],
269 speeds: &[Option<crate::project::Stretch>],269 speeds: &[Option<crate::project::Stretch>],
270 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {270 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
271- let Some((path, stream)) = sources.first() else {271+ // The first source that could have a track, which is not always index 0:
272+ // a still image has none, and one at the front of the list (a save
273+ // renumbers, a library removal moves indexes) would be opened as a
274+ // broken audio file and take the whole timeline's sound down with it.
275+ // The same rule `PlaybackSession` probes by (`audio_source_of`).
276+ let Some((at, (path, stream))) = sources
277+ .iter()
278+ .enumerate()
279+ .find(|(_, (path, _))| !crate::is_image(path))
280+ else {
272 return Ok(None);281 return Ok(None);
273 };282 };
274 let Some(first) = Track::open(path, *stream)? else {283 let Some(first) = Track::open(path, *stream)? else {
275 return Ok(None);284 return Ok(None);
276 };285 };
277- // The timeline's meta is the first source's: policy makes every other286+ // The timeline's meta is that source's: policy makes every other source
278- // source match it, and the checks below hold them to that.287+ // match it, and the checks below hold them to that.
279 let meta = AudioMeta {288 let meta = AudioMeta {
280 sample_rate: first.sample_rate(),289 sample_rate: first.sample_rate(),
281 channels: first.channels()?,290 channels: first.channels()?,
@@ -286,7 +295,7 @@ impl AudioSession {
286 first.check_decoder()?;295 first.check_decoder()?;
287 296
288 let mut tracks: Vec<Option<Track>> = sources.iter().map(|_| None).collect();297 let mut tracks: Vec<Option<Track>> = sources.iter().map(|_| None).collect();
289- tracks[0] = Some(first);298+ tracks[at] = Some(first);
290 for &(source, ..) in segs {299 for &(source, ..) in segs {
291 let Some(source) = source else {300 let Some(source) = source else {
292 continue; // a gap opens no file301 continue; // a gap opens no file
@@ -459,8 +468,9 @@ impl AudioSession {
459 let mut meta = None;468 let mut meta = None;
460 let mut rxs = Vec::with_capacity(lanes.len());469 let mut rxs = Vec::with_capacity(lanes.len());
461 for (i, segs) in lanes.iter().enumerate() {470 for (i, segs) in lanes.iter().enumerate() {
462- // Every lane probes the same source 0, so the metas agree by471+ // Every lane takes its meta from the same source, so the metas
463- // construction; `None` from any of them is a silent timeline.472+ // agree by construction; `None` from any of them is a silent
473+ // timeline.
464 let flat = Vec::new();474 let flat = Vec::new();
465 let plain = Vec::new();475 let plain = Vec::new();
466 let Some((lane_meta, rx)) = Self::open_multi_streams_speed(476 let Some((lane_meta, rx)) = Self::open_multi_streams_speed(
crates/engine/src/playback.rsmodified+105 -16
@@ -417,10 +417,12 @@ impl PlaybackSession {
417 ///417 ///
418 /// A *new* session rather than a reload of this one, so a load that fails418 /// A *new* session rather than a reload of this one, so a load that fails
419 /// leaves the caller's current session untouched -- atomic by419 /// leaves the caller's current session untouched -- atomic by
420- /// construction. Every named file is opened and checked here: source 0420+ /// construction. Every named file is opened and checked here: the
421- /// defines the timeline exactly as `open` does, every other source has to421+ /// *scaffolding* source -- the first that is not a still, since a picture
422- /// match it the way [`import`](Self::import) demands, and every clip has to422+ /// carries no rate -- defines the timeline exactly as `open` does, every
423- /// still be inside the file it plays from. A source that vanished or423+ /// other source has to match it the way [`import`](Self::import) demands
424+ /// (a save renumbers, so which index that is says nothing), and every clip
425+ /// has to still be inside the file it plays from. A source that vanished or
424 /// shrank since the save is a refusal naming it, not a silently shorter426 /// shrank since the save is a refusal naming it, not a silently shorter
425 /// timeline -- the disappearing-file tolerance elsewhere in this type427 /// timeline -- the disappearing-file tolerance elsewhere in this type
426 /// applies only *after* a project has loaded.428 /// applies only *after* a project has loaded.
@@ -428,15 +430,35 @@ impl PlaybackSession {
428 /// The undo history is not saved: `undo` is `false` on a fresh load.430 /// The undo history is not saved: `undo` is `false` on a fresh load.
429 pub fn open_project(path: &Path) -> crate::Result<Self> {431 pub fn open_project(path: &Path) -> crate::Result<Self> {
430 let doc = crate::edith::load(path)?;432 let doc = crate::edith::load(path)?;
433+ // *Which* source scaffolds it: the first that is not a still, and index
434+ // 0 only when there is no other. A still defines no frame rate -- it is
435+ // given [`IMAGE_ONLY_RATE`] -- so scaffolding a timeline of 24 fps
436+ // footage off a PNG that a save happened to renumber to index 0
437+ // (`Project::without_orphan_sources` numbers by first use, and a
438+ // library removal moves indexes too) reads the timeline as 30 fps and
439+ // then refuses every file on it for not matching. The rule this and
440+ // [`audio_source_of`] share: nothing may assume what source 0 *is*.
441+ //
442+ // ponytail: a timeline of nothing but stills, or of stills and songs,
443+ // still comes back at the rate its scaffold implies rather than the one
444+ // it was cut at -- the rate is written nowhere in the file. The upgrade
445+ // path is a dialect that writes it (`crate::edith`), which is also what
446+ // a project naming no file at all would need.
447+ let scaffold = doc
448+ .sources
449+ .iter()
450+ .position(|s| !crate::is_image(&s.path))
451+ .unwrap_or(0);
431 // Owned: the sources move into the `Project` below, and the device is452 // Owned: the sources move into the `Project` below, and the device is
432 // opened after that (see the comment there).453 // opened after that (see the comment there).
433 let first = doc454 let first = doc
434 .sources455 .sources
435- .first()456+ .get(scaffold)
436 .cloned()457 .cloned()
437 .ok_or("the project names no sources")?;458 .ok_or("the project names no sources")?;
438- // Source 0 both scaffolds the session and defines the timeline, so it459+ // The scaffolding source both defines the timeline and is what the
439- // is opened for playback rather than merely probed.460+ // playhead's first picture comes from, so it is opened for playback
461+ // rather than merely probed.
440 // One value, not two locals: everything below this line can refuse, and462 // One value, not two locals: everything below this line can refuse, and
441 // locals drop in reverse declaration order -- a bare worker would join463 // locals drop in reverse declaration order -- a bare worker would join
442 // its decode thread while the receiver next to it was still holding464 // its decode thread while the receiver next to it was still holding
@@ -503,8 +525,15 @@ impl PlaybackSession {
503 }525 }
504 let first_audio = first_audio_of(&doc.sources)?;526 let first_audio = first_audio_of(&doc.sources)?;
505 527
506- let mut counts = vec![meta.frame_count];528+ // In source order, with the scaffold's own count in its own slot: the
507- for source in &doc.sources[1..] {529+ // clip check below indexes this list by source, so it must line up with
530+ // `doc.sources` whichever entry the scaffolding came from.
531+ let mut counts = Vec::with_capacity(doc.sources.len());
532+ for (i, source) in doc.sources.iter().enumerate() {
533+ if i == scaffold {
534+ counts.push(meta.frame_count);
535+ continue;
536+ }
508 // A still has neither a rate to match nor a track to match with:537 // A still has neither a rate to match nor a track to match with:
509 // its length is the one it is held to, recomputed exactly as the538 // its length is the one it is held to, recomputed exactly as the
510 // import that first noted it did ([`image_frames`]), which is what539 // import that first noted it did ([`image_frames`]), which is what
@@ -579,7 +608,15 @@ impl PlaybackSession {
579 // only a session's `drop` retires it, so a refusal above this line would608 // only a session's `drop` retires it, so a refusal above this line would
580 // leave a PipeWire stream and a thread behind for a project that never609 // leave a PipeWire stream and a thread behind for a project that never
581 // opened. Nothing before it needs the device.610 // opened. Nothing before it needs the device.
582- let (audio, audio_disabled) = open_audio(&first.path, first.audio_stream);611+ //
612+ // On the source the timeline's *sound* is defined by, which is the
613+ // scaffold unless that one is a still ([`audio_source_of`]): opening a
614+ // PNG as the device is a session with no audio at all, however many
615+ // clips with sound are on its lanes.
616+ let (audio, audio_disabled) = match audio_source_of(project.sources()) {
617+ Some(source) => open_audio(&source.path, source.audio_stream),
618+ None => (None, None),
619+ };
583 let mut session = Self {620 let mut session = Self {
584 meta,621 meta,
585 native,622 native,
@@ -627,7 +664,16 @@ impl PlaybackSession {
627 /// Writes the timeline to `path` as a `.edith`, atomically (see664 /// Writes the timeline to `path` as a `.edith`, atomically (see
628 /// [`crate::edith`]). Sources no clip plays from are left out, and the665 /// [`crate::edith`]). Sources no clip plays from are left out, and the
629 /// playhead is saved with it so a reopened project resumes where it stood.666 /// playhead is saved with it so a reopened project resumes where it stood.
667+ ///
668+ /// Refused, writing nothing, for a session whose library is empty (every
669+ /// row removed, [`Project::remove_source`]): a file naming no source has no
670+ /// timeline in it and [`open_project`](Self::open_project) could only
671+ /// refuse it, so the refusal belongs here, where nothing has been
672+ /// overwritten yet.
630 pub fn save_project(&self, path: &Path) -> crate::Result<()> {673 pub fn save_project(&self, path: &Path) -> crate::Result<()> {
674+ if self.project.sources().is_empty() {
675+ return Err("this project names no file: there is nothing to save".into());
676+ }
631 let (sources, lanes, eq, color) = self.project.without_orphan_sources();677 let (sources, lanes, eq, color) = self.project.without_orphan_sources();
632 let playhead = secs_to_frame(self.now(), self.meta.frame_rate)678 let playhead = secs_to_frame(self.now(), self.meta.frame_rate)
633 .min(self.project.timeline_frames().saturating_sub(1));679 .min(self.project.timeline_frames().saturating_sub(1));
@@ -1286,7 +1332,14 @@ impl PlaybackSession {
1286 /// Reseeks like an edit even though nothing playable changed: the clip1332 /// Reseeks like an edit even though nothing playable changed: the clip
1287 /// indexes into the source list have just moved, and the running workers1333 /// indexes into the source list have just moved, and the running workers
1288 /// were opened against the old numbering.1334 /// were opened against the old numbering.
1289- pub fn remove_source(&mut self, path: &Path, stream: usize) -> crate::Result<()> {1335+ ///
1336+ /// The index that went, because everything past it moved down: a caller
1337+ /// holding a source index of its own (a clipboard) has to fix it up or drop
1338+ /// it, or it names a different file afterwards. The **last** row goes like
1339+ /// any other and leaves a session with an empty library -- silent, empty of
1340+ /// clips, and unsaveable ([`save_project`](Self::save_project)); a
1341+ /// front-end showing one is showing an empty window.
1342+ pub fn remove_source(&mut self, path: &Path, stream: usize) -> crate::Result<usize> {
1290 let wanted = Source::new(path, stream);1343 let wanted = Source::new(path, stream);
1291 let idx = self1344 let idx = self
1292 .project1345 .project
@@ -1305,11 +1358,12 @@ impl PlaybackSession {
1305 }1358 }
1306 let now = self.now();1359 let now = self.now();
1307 self.seek(now);1360 self.seek(now);
1308- Ok(())1361+ Ok(idx)
1309 }1362 }
1310 1363
1311- /// What the timeline's audio *is*: source 0's chosen stream, probed. Every1364+ /// What the timeline's audio *is*: the chosen stream of the first source
1312- /// other source is held to it.1365+ /// that could have any ([`audio_source_of`]), probed. Every other source is
1366+ /// held to it.
1313 fn first_audio(&self) -> crate::Result<Option<crate::AudioProbe>> {1367 fn first_audio(&self) -> crate::Result<Option<crate::AudioProbe>> {
1314 first_audio_of(self.project.sources())1368 first_audio_of(self.project.sources())
1315 }1369 }
@@ -1729,12 +1783,26 @@ fn matches_timeline(
1729 /// source 0 has always given. This function widens which source is asked, not1783 /// source 0 has always given. This function widens which source is asked, not
1730 /// what the answer means.1784 /// what the answer means.
1731 fn first_audio_of(sources: &[Source]) -> crate::Result<Option<crate::AudioProbe>> {1785 fn first_audio_of(sources: &[Source]) -> crate::Result<Option<crate::AudioProbe>> {
1732- match sources.iter().find(|s| !crate::is_image(&s.path)) {1786+ match audio_source_of(sources) {
1733 Some(first) => AudioSession::probe(&first.path, first.audio_stream),1787 Some(first) => AudioSession::probe(&first.path, first.audio_stream),
1734 None => Ok(None),1788 None => Ok(None),
1735 }1789 }
1736 }1790 }
1737 1791
1792+/// *Which* source that is: the first one that is not a still. The single answer
1793+/// to "what does this timeline's sound come from", so that probing it
1794+/// ([`first_audio_of`]) and opening the device on it
1795+/// ([`PlaybackSession::open_project`]) can never disagree -- source 0 is only
1796+/// the scaffolding file until a save renumbers it or a library removal takes it
1797+/// away ([`crate::Project::remove_source`]), and a PNG at index 0 opened as the
1798+/// device is a timeline that plays silent although every clip on it has sound.
1799+///
1800+/// `None` for a library of nothing but stills, and for one with no file at all:
1801+/// both are silent timelines.
1802+fn audio_source_of(sources: &[Source]) -> Option<&Source> {
1803+ sources.iter().find(|s| !crate::is_image(&s.path))
1804+}
1805+
1738 fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::Result<()> {1806 fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::Result<()> {
1739 // Whole-probe equality: rate and layout, which the audio worker holds every1807 // Whole-probe equality: rate and layout, which the audio worker holds every
1740 // source to anyway. Both silent is a match.1808 // source to anyway. Both silent is a match.
@@ -1885,7 +1953,7 @@ fn secs_to_frame(secs: f64, fps: f64) -> u32 {
1885 1953
1886 #[cfg(test)]1954 #[cfg(test)]
1887 mod tests {1955 mod tests {
1888- use super::{Edge, Lane, PlaybackSession, secs_to_frame};1956+ use super::{Edge, Lane, PlaybackSession, Source, audio_source_of, secs_to_frame};
1889 use std::path::PathBuf;1957 use std::path::PathBuf;
1890 1958
1891 fn asset(name: &str) -> PathBuf {1959 fn asset(name: &str) -> PathBuf {
@@ -1894,6 +1962,27 @@ mod tests {
1894 .join(name)1962 .join(name)
1895 }1963 }
1896 1964
1965+ /// Which source the timeline's sound is opened on -- the one rule
1966+ /// [`open_project`](PlaybackSession::open_project), the probe every import
1967+ /// is held to and the audio worker all read through. A still at index 0 is
1968+ /// a picture, not a silent timeline: opening the device on it is a project
1969+ /// that plays silent although every clip on it has sound.
1970+ #[test]
1971+ fn the_audio_reference_is_never_a_still() {
1972+ let (video, still) = (asset("test_av.mp4"), asset("test_still.png"));
1973+ let sources = [Source::new(&still, 0), Source::new(&video, 3)];
1974+ assert_eq!(
1975+ audio_source_of(&sources).map(|s| (&s.path, s.audio_stream)),
1976+ Some((&sources[1].path, 3)),
1977+ "the first source that could have a track, with its own stream"
1978+ );
1979+ assert!(
1980+ audio_source_of(&sources[..1]).is_none(),
1981+ "nothing but stills"
1982+ );
1983+ assert!(audio_source_of(&[]).is_none(), "and no file at all");
1984+ }
1985+
1897 /// The seam between the two lists a source index reaches: dropping a file1986 /// The seam between the two lists a source index reaches: dropping a file
1898 /// from the library shortens `sources`, and `counts` -- the frame length1987 /// from the library shortens `sources`, and `counts` -- the frame length
1899 /// per source, which is what a trim is walled by -- has to lose the same1988 /// per source, which is what a trim is walled by -- has to lose the same
crates/engine/src/project.rsmodified+41 -23
@@ -748,10 +748,20 @@ impl Project {
748 ///748 ///
749 /// Refused, changing nothing, while any clip still plays from it: the749 /// Refused, changing nothing, while any clip still plays from it: the
750 /// refusal names the lanes and how many clips each holds, so a caller can750 /// refusal names the lanes and how many clips each holds, so a caller can
751- /// say what has to be deleted first. Refused too for the last entry left,751+ /// say what has to be deleted first. The *last* entry goes like any other
752- /// because a project that names no file cannot be reopened752+ /// -- a project may name no file at all, which is an empty library over an
753- /// (`PlaybackSession::open_project`) and the timeline's audio parameters753+ /// empty timeline (nothing can play, since a clip would have refused the
754- /// are read off source 0.754+ /// removal). What a front-end does with that is its own decision: `edith`'s
755+ /// window goes back to the empty state it launches in, and
756+ /// [`PlaybackSession::save_project`](crate::PlaybackSession::save_project)
757+ /// refuses to write a project that names nothing, because no such file
758+ /// could be opened again.
759+ ///
760+ /// Every index past `idx` moves down by one, so a caller holding a *raw*
761+ /// source index of its own -- a clipboard, which is the one thing outside
762+ /// this type that does -- has to fix it up or drop it, or a paste plays a
763+ /// different file. [`PlaybackSession::remove_source`] hands back the index
764+ /// that went for exactly that.
755 ///765 ///
756 /// ponytail: this retires the undo stack. `history` holds lanes alone, so a766 /// ponytail: this retires the undo stack. `history` holds lanes alone, so a
757 /// snapshot older than the removal can name the very source being removed767 /// snapshot older than the removal can name the very source being removed
@@ -766,12 +776,6 @@ impl Project {
766 return Err(format!("there is no source {idx} to remove").into());776 return Err(format!("there is no source {idx} to remove").into());
767 };777 };
768 let name = source.path.display().to_string();778 let name = source.path.display().to_string();
769- // Asked before the clips are counted: with one file left the answer is
770- // the same whatever plays, and "the only file" is the more useful half
771- // of it.
772- if self.sources.len() == 1 {
773- return Err(format!("{name} is the only file this project names").into());
774- }
775 let used: Vec<String> = handles(&self.lanes)779 let used: Vec<String> = handles(&self.lanes)
776 .into_iter()780 .into_iter()
777 .zip(&self.lanes)781 .zip(&self.lanes)
@@ -815,9 +819,16 @@ impl Project {
815 /// only the ones a clip names.819 /// only the ones a clip names.
816 ///820 ///
817 /// One exception, and it is the emptied timeline's: a project no clip plays821 /// One exception, and it is the emptied timeline's: a project no clip plays
818- /// from still keeps source 0. It is the file a session is scaffolded from --822+ /// from still keeps its first source, if it has one. A file is what a
819- /// its frame rate is the timeline's and is written nowhere else -- so a save823+ /// reopened project scaffolds itself from -- the frame rate is written
820- /// that pruned it would write a project that cannot be loaded back at all.824+ /// nowhere else -- so a save that pruned the last of them would write a
825+ /// project that cannot be loaded back at all.
826+ ///
827+ /// What comes out is *not* ordered by anything a reader may assume: first
828+ /// use, lane by lane, means the entry at index 0 can be a still or a song
829+ /// whatever the session was scaffolded from. `PlaybackSession::open_project`
830+ /// picks its rate and its audio reference by what a source *is*, never by
831+ /// where it sits.
821 pub fn without_orphan_sources(&self) -> Parts {832 pub fn without_orphan_sources(&self) -> Parts {
822 let mut moved = vec![None; self.sources.len()];833 let mut moved = vec![None; self.sources.len()];
823 let mut sources = Vec::new();834 let mut sources = Vec::new();
@@ -3784,10 +3795,10 @@ mod tests {
3784 }3795 }
3785 3796
3786 /// The two edges of a removal: it retires the undo stack (the ponytail on3797 /// The two edges of a removal: it retires the undo stack (the ponytail on
3787- /// [`Project::remove_source`]), and the last entry standing cannot go --3798+ /// [`Project::remove_source`]), and the last entry goes like any other
3788- /// source 0 is where a reopened project reads its frame rate.3799+ /// once nothing plays it -- a project may name no file at all.
3789 #[test]3800 #[test]
3790- fn remove_source_retires_undo_and_keeps_the_last_file() {3801+ fn remove_source_retires_undo_and_empties_the_library() {
3791 let mut p = two_sources();3802 let mut p = two_sources();
3792 assert!(p.delete_in(Lane::V1, 3), "FILE2's take goes first");3803 assert!(p.delete_in(Lane::V1, 3), "FILE2's take goes first");
3793 assert!(!p.history.is_empty(), "there is something to undo");3804 assert!(!p.history.is_empty(), "there is something to undo");
@@ -3798,18 +3809,25 @@ mod tests {
3798 );3809 );
3799 assert!(!p.undo(), "and so there is nothing left to undo");3810 assert!(!p.undo(), "and so there is nothing left to undo");
3800 3811
3801- // The last file standing stays, whatever plays from it:3812+ // The last file standing is held to the one rule every row is -- what
3802- // `PlaybackSession::open_project` refuses a project that names no3813+ // plays cannot go -- and to no other.
3803- // sources at all, and the timeline's frame rate lives in source 0.
3804 assert_eq!(p.sources().len(), 1);3814 assert_eq!(p.sources().len(), 1);
3805 let refusal = p3815 let refusal = p
3806 .remove_source(0)3816 .remove_source(0)
3807- .expect_err("the only source must stay")3817+ .expect_err("its clips are still on the lanes")
3808 .to_string();3818 .to_string();
3809- assert!(refusal.contains("only file"), "{refusal}");3819+ assert!(refusal.contains("still plays"), "{refusal}");
3810- assert_eq!(p.sources().len(), 1);3820+ assert_eq!(p.sources().len(), 1, "a refusal changes nothing");
3821+ while p.delete_in(Lane::V1, 0) {}
3822+ p.remove_source(0)
3823+ .expect("the last row goes like any other");
3824+ assert!(
3825+ p.sources().is_empty(),
3826+ "a project may name no file at all: an empty library over an empty timeline"
3827+ );
3828+ assert_eq!(p.timeline_frames(), 0);
3811 assert!(3829 assert!(
3812- p.remove_source(1).is_err(),3830+ p.remove_source(0).is_err(),
3813 "and an index that is not there is refused, not panicked on"3831 "and an index that is not there is refused, not panicked on"
3814 );3832 );
3815 }3833 }
crates/engine/tests/images.rsmodified+89 -0
@@ -341,6 +341,95 @@ fn a_still_survives_the_project_round_trip() {
341 let _ = std::fs::remove_dir_all(&dir);341 let _ = std::fs::remove_dir_all(&dir);
342 }342 }
343 343
344+/// The save renumbers sources by first use, so a still at the head of `V1`
345+/// comes back as **source 0** however the session was scaffolded -- and source
346+/// 0 is what everything used to read the timeline off. A picture defines no
347+/// frame rate and has no sound, so the reload used to read this project as 30
348+/// fps (refusing the 25 fps footage still on `A1` by name) and open the output
349+/// device on a PNG (a timeline that plays silent although its clips have
350+/// sound). Nothing may assume what source 0 *is*: the rate comes from the first
351+/// source that has one, and the sound from the first that could have any.
352+#[test]
353+fn a_still_at_saved_source_zero_keeps_the_rate_and_the_sound() {
354+ pin_software();
355+ let dir = std::env::temp_dir().join(format!("ve_still_first_{}", std::process::id()));
356+ let _ = std::fs::remove_dir_all(&dir);
357+ std::fs::create_dir_all(&dir).expect("scratch dir");
358+ let media = dir.join("test_25fps.mp4");
359+ let still = dir.join("test_still.png");
360+ std::fs::copy(asset("test_25fps.mp4"), &media).expect("copy the video");
361+ std::fs::copy(asset("test_still.png"), &still).expect("copy the still");
362+
363+ // 25 fps, which no still is ever given: the rate alone says which source
364+ // the reload scaffolded from.
365+ let mut session = PlaybackSession::open(&media).expect("open the fixture");
366+ session.set_gain(0.0);
367+ assert!((session.meta().frame_rate - 25.0).abs() < 0.01);
368+ session.import(&still).expect("a picture");
369+ // Over the head of V1, where it takes the whole take's picture: the sound
370+ // stays on A1, so the still is the first clip in save order and the video
371+ // is a source only the audio lane names.
372+ assert!(
373+ session
374+ .place_stream_at(0.0, &still, 0, Some(Lane::V1))
375+ .expect("a still joins any timeline")
376+ );
377+ assert!(session.lane_clips(Lane::V1).len() == 1 && session.lane_clips(Lane::A1).len() == 1);
378+
379+ let project = dir.join("still_first.edith");
380+ session.save_project(&project).expect("save");
381+ let text = std::fs::read_to_string(&project).expect("read the project");
382+ let source_0 = text
383+ .lines()
384+ .find(|l| l.starts_with("source "))
385+ .expect("a source line");
386+ assert!(
387+ source_0.contains("test_still.png"),
388+ "the premise: the save put the still at index 0 -- {source_0}"
389+ );
390+
391+ let reopened = PlaybackSession::open_project(&project).expect("a saved project always reopens");
392+ assert!(
393+ (reopened.meta().frame_rate - 25.0).abs() < 0.01,
394+ "the footage's rate, not the still's 30: {}",
395+ reopened.meta().frame_rate
396+ );
397+ // The same sound, at the same place, playing the same file -- by a *new*
398+ // index, which is the renumbering this whole test is about.
399+ let (sound, was) = (
400+ reopened.lane_clips(Lane::A1)[0],
401+ session.lane_clips(Lane::A1)[0],
402+ );
403+ assert_eq!(
404+ (sound.start, sound.in_frame, sound.out_frame),
405+ (was.start, was.in_frame, was.out_frame)
406+ );
407+ assert!(
408+ reopened.sources()[sound.source]
409+ .path
410+ .ends_with("test_25fps.mp4"),
411+ "the take's sound still names the video"
412+ );
413+ assert!(
414+ reopened.audio_disabled_reason().is_none(),
415+ "a still is not a reason a timeline is silent: {:?}",
416+ reopened.audio_disabled_reason()
417+ );
418+ // And the sound itself, through the very opener a seek builds its worker
419+ // with: source 0 is the PNG here, and one opened unconditionally is an
420+ // error that takes every lane's audio down with it.
421+ let sources: Vec<_> = reopened
422+ .sources()
423+ .iter()
424+ .map(|s| (s.path.clone(), s.audio_stream))
425+ .collect();
426+ let (meta, _rx) = engine::AudioSession::open_multi_streams(&sources, &[(Some(1), 0.0, 1.0)])
427+ .expect("the worker opens over a still at index 0")
428+ .expect("the take on A1 has sound");
429+ assert_eq!(meta.sample_rate, 44_100, "the take's own rate");
430+ let _ = std::fs::remove_dir_all(&dir);
431+}
432+
344 /// The export is what was watched: a timeline of video then still comes back433 /// The export is what was watched: a timeline of video then still comes back
345 /// out of the mp4 as video then still, with the still's own colours in it.434 /// out of the mp4 as video then still, with the still's own colours in it.
346 #[test]435 #[test]