forge
Explore
Log in

Don't you dare go Hollow

🔀 merge(T6): zero-source survival + boundary-cardinality class fixes

Browse files at this commit

5ef278333d1aa56ef69059cc56a250a60c86dbd2Ahmet Kaan GümüşParent: c97244f7e4ead7
crates/app/src/main.rsmodified+200 -23
@@ -1548,6 +1548,11 @@ impl Player {
1548 match session.cut_regions(&regions, &lanes) {1548 match session.cut_regions(&regions, &lanes) {
1549 Ok(()) => {1549 Ok(()) => {
1550 self.close_silence();1550 self.close_silence();
1551+ // Every hole closed moves the clips after it up a place, so the
1552+ // selection now names a different clip than the one that is
1553+ // highlighted -- dropped here as after every other edit that
1554+ // moves indexes (a delete, a paste, an undo).
1555+ self.selected = None;
1551 self.reset_after_reseek();1556 self.reset_after_reseek();
1552 self.notice = Some(1557 self.notice = Some(
1553 format!(1558 format!(
@@ -1582,6 +1587,10 @@ impl Player {
1582 match session.speed_regions(&regions, rate, &lanes) {1587 match session.speed_regions(&regions, rate, &lanes) {
1583 Ok(()) => {1588 Ok(()) => {
1584 self.close_silence();1589 self.close_silence();
1590+ // Splitting each silence out and closing the room it no longer
1591+ // needs moves indexes exactly as the cut does: the selection
1592+ // goes with them.
1593+ self.selected = None;
1585 self.reset_after_reseek();1594 self.reset_after_reseek();
1586 self.notice = Some(1595 self.notice = Some(
1587 format!(1596 format!(
@@ -2332,20 +2341,43 @@ impl Player {
2332 .as_mut()2341 .as_mut()
2333 .map(|session| session.remove_source(path, stream));2342 .map(|session| session.remove_source(path, stream));
2334 let text = match removed {2343 let text = match removed {
2335- Some(Ok(())) => {2344+ Some(Ok(idx)) => {
2336 // The picked row may be the one that just went, and the engine2345 // The picked row may be the one that just went, and the engine
2337 // reseeks, so this owes the flag reset like every other edit.2346 // reseeks, so this owes the flag reset like every other edit.
2338 if self.selected_asset.as_ref() == Some(&(path.to_path_buf(), stream)) {2347 if self.selected_asset.as_ref() == Some(&(path.to_path_buf(), stream)) {
2339 self.selected_asset = None;2348 self.selected_asset = None;
2340 }2349 }
2350+ // A copied clip names its source by *index*, and every index
2351+ // past the one that went has just moved down: without this the
2352+ // next paste puts some other file on the timeline.
2353+ self.clipboard = clipboard_after_remove(self.clipboard, idx);
2341 self.reset_after_reseek();2354 self.reset_after_reseek();
2342- // The undo stack goes with it (`Project::remove_source`): said2355+ // The last row leaves a session naming no file: nothing to
2343- // here, because a `z` that does nothing afterwards would2356+ // play, nothing to save and nothing to show, which is the empty
2344- // otherwise read as a bug.2357+ // window the editor launches as. The next import scaffolds a
2345- format!(2358+ // fresh timeline from whatever file it is, at that file's own
2346- "REMOVED {} — there is nothing left to undo",2359+ // rate -- which is why the session goes rather than lingering
2347- file_name(path)2360+ // on with the gone file's parameters.
2348- )2361+ match self
2362+ .session
2363+ .as_ref()
2364+ .is_some_and(|s| s.sources().is_empty())
2365+ {
2366+ true => {
2367+ self.close_session();
2368+ format!(
2369+ "REMOVED {} — the library is empty; import a file to start again",
2370+ file_name(path)
2371+ )
2372+ }
2373+ // The undo stack goes with it (`Project::remove_source`):
2374+ // said here, because a `z` that does nothing afterwards
2375+ // would otherwise read as a bug.
2376+ false => format!(
2377+ "REMOVED {} — there is nothing left to undo",
2378+ file_name(path)
2379+ ),
2380+ }
2349 }2381 }
2350 Some(Err(e)) => format!("NOT REMOVED — {e}"),2382 Some(Err(e)) => format!("NOT REMOVED — {e}"),
2351 None => "NO TIMELINE — open a file first".to_string(),2383 None => "NO TIMELINE — open a file first".to_string(),
@@ -2354,6 +2386,64 @@ impl Player {
2354 cx.notify();2386 cx.notify();
2355 }2387 }
2356 2388
2389+ /// Back to the window the editor launches as: no timeline, no library, no
2390+ /// picture -- and the hint that says to open a file. What removing the last
2391+ /// library row leaves, since a session whose library is empty has nothing
2392+ /// left to be ([`Player::remove_source`]).
2393+ ///
2394+ /// Everything a *loaded project* resets goes here for its reasons (an index
2395+ /// into a timeline that is gone names nothing), plus the three per-file
2396+ /// caches: they are keyed by path, and the next file to arrive fills them
2397+ /// again.
2398+ fn close_session(&mut self) {
2399+ self.session = None;
2400+ // The picture goes with it, or the empty window would keep showing the
2401+ // last frame of a timeline that no longer exists.
2402+ //
2403+ // ponytail: its atlas tile is not released -- `window.drop_image` wants
2404+ // a `&mut Window` this door has no other reason to take. One tile per
2405+ // emptied library, against one per displayed frame in `pump`; the
2406+ // upgrade path is threading the window through `act_on_row`.
2407+ self.image = None;
2408+ self.clipboard = None;
2409+ self.selected = None;
2410+ self.selected_asset = None;
2411+ self.context_menu = None;
2412+ self.library_menu = None;
2413+ self.eq_open = None;
2414+ self.color_open = None;
2415+ self.speed_open = None;
2416+ self.close_silence();
2417+ self.waves.clear();
2418+ self.streams.clear();
2419+ self.sizes.clear();
2420+ // Scanned off a source that is not in the library any more.
2421+ self.silence_levels = None;
2422+ // Every gesture in flight, dropped for `reset_after_reseek`'s reason
2423+ // (it drops the trim below): a drag holds a bar, a clip or a band of a
2424+ // timeline that has just stopped existing.
2425+ self.scrubbing = false;
2426+ self.volume_dragging = false;
2427+ self.eq_dragging = false;
2428+ self.speed_dragging = false;
2429+ self.color_dragging = false;
2430+ self.displayed = 0;
2431+ self.dropped = 0;
2432+ self.started = None;
2433+ // The empty window's own: no name in the titlebar, nowhere chosen to
2434+ // export or save to yet, and a rate that only keeps the timecode
2435+ // reading in frames until a file brings its own (`main`).
2436+ self.name = NO_FILE.into();
2437+ self.export_path = PathBuf::new();
2438+ self.project_path = PathBuf::new();
2439+ self.fps = 30.;
2440+ // No decoder to wait for a frame from: the hint is what shows.
2441+ self.reset_after_reseek();
2442+ self.pending_seek = false;
2443+ self.eos = false;
2444+ self.done = false;
2445+ }
2446+
2357 /// One item of a library row's menu, done. Every one of them closes the2447 /// One item of a library row's menu, done. Every one of them closes the
2358 /// menu first -- the list under it is about to be rebuilt -- except the one2448 /// menu first -- the list under it is about to be rebuilt -- except the one
2359 /// that turns the card over.2449 /// that turns the card over.
@@ -2387,11 +2477,22 @@ impl Player {
2387 cx.notify();2477 cx.notify();
2388 }2478 }
2389 2479
2390- /// The rate and layout the whole timeline's audio is, taken from source 0's2480+ /// The rate and layout the whole timeline's audio is, taken from the stream
2391- /// own stream: what a library row has to match to be placeable. `None`2481+ /// of the first source that could have one: what a library row has to match
2392- /// until that file has been probed, and then nothing is greyed for it.2482+ /// to be placeable. `None` until that file has been probed, and then nothing
2483+ /// is greyed for it.
2484+ ///
2485+ /// The first source that is *not a still*, which is the rule the engine
2486+ /// holds every import to (`playback::audio_source_of`) -- a picture at the
2487+ /// head of the list (a removal moves indexes) has no stream to describe
2488+ /// anything with.
2393 fn timeline_audio(&self) -> Option<(u32, u16)> {2489 fn timeline_audio(&self) -> Option<(u32, u16)> {
2394- let first = self.session.as_ref()?.sources().first()?;2490+ let first = self
2491+ .session
2492+ .as_ref()?
2493+ .sources()
2494+ .iter()
2495+ .find(|s| !engine::is_image(&s.path))?;
2395 let info = self2496 let info = self
2396 .streams2497 .streams
2397 .get(&first.path)?2498 .get(&first.path)?
@@ -6301,6 +6402,28 @@ fn can_add(picked: Option<&(PathBuf, usize)>, timeline: bool, exporting: bool) -
6301 picked.is_some() && timeline && !exporting6402 picked.is_some() && timeline && !exporting
6302 }6403 }
6303 6404
6405+/// What is left on the clipboard after the library row at `removed` was taken
6406+/// out. A copied clip names its file by *index* into the source list
6407+/// (`engine::Clip::source`) and a removal renumbers that list
6408+/// (`engine::Project::remove_source`), so a clipboard kept as it was would paste
6409+/// **a different file** -- the next one along -- over the range it was copied
6410+/// from.
6411+///
6412+/// The clip's own file gone means there is nothing to paste: `None`, and the
6413+/// next paste says the clipboard is empty rather than putting some other take
6414+/// down. Every index past it moves down by one, exactly as the lanes' clips do.
6415+fn clipboard_after_remove(clip: Option<Clip>, removed: usize) -> Option<Clip> {
6416+ let mut clip = clip?;
6417+ match clip.source.cmp(&removed) {
6418+ std::cmp::Ordering::Equal => None,
6419+ std::cmp::Ordering::Greater => {
6420+ clip.source -= 1;
6421+ Some(clip)
6422+ }
6423+ std::cmp::Ordering::Less => Some(clip),
6424+ }
6425+}
6426+
6304 /// One library row: a file and one of its audio streams. Plain data, planned6427 /// One library row: a file and one of its audio streams. Plain data, planned
6305 /// before anything is drawn -- which rows exist at all is the branchy part.6428 /// before anything is drawn -- which rows exist at all is the branchy part.
6306 #[derive(Debug, PartialEq)]6429 #[derive(Debug, PartialEq)]
@@ -7715,12 +7838,12 @@ mod tests {
7715 MENU_PAD, MENU_ROW_H, MENU_ROWS_H, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H,7838 MENU_PAD, MENU_ROW_H, MENU_ROWS_H, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H,
7716 SELECTED, SILENCE_ROWS, SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, SURFACE, SWATCH_W, Source,7839 SELECTED, SILENCE_ROWS, SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, SURFACE, SWATCH_W, Source,
7717 Speed, StreamInfo, VOLUME_W, Volume, WAVE_BPS, WAVE_COL, Wave, applicable, band_label,7840 Speed, StreamInfo, VOLUME_W, Volume, WAVE_BPS, WAVE_COL, Wave, applicable, band_label,
7718- can_add, cancels_export, color_snap, envelope, eq_spectrum, eq_x, eq_y, export_path,7841+ can_add, cancels_export, clipboard_after_remove, color_snap, envelope, eq_spectrum, eq_x,
7719- export_settings, format_key, format_line, format_refusal, frac_along, frac_down, frame_at,7842+ eq_y, export_path, export_settings, format_key, format_line, format_refusal, frac_along,
7720- histogram, is_bare_modifier, is_project, keymap, lanes_h, marked, menu_at, normalise,7843+ frac_down, frame_at, histogram, is_bare_modifier, is_project, keymap, lanes_h, marked,
7721- nothing_to_play, panel_h, project_path, push_digit, retarget, scrub_due, show_label,7844+ menu_at, normalise, nothing_to_play, panel_h, project_path, push_digit, retarget,
7722- silence_rate, source_tint, span_partner, speed_at, timecode, unseen_paths, unseen_sources,7845+ scrub_due, show_label, silence_rate, source_tint, span_partner, speed_at, timecode,
7723- whole_take, width_frac, window_title,7846+ unseen_paths, unseen_sources, whole_take, width_frac, window_title,
7724 };7847 };
7725 use super::{7848 use super::{
7726 LaneKind, Repeat, View, ZOOM_MIN_FRAMES, ZOOM_STEP, file_name, file_uri, library_rows,7849 LaneKind, Repeat, View, ZOOM_MIN_FRAMES, ZOOM_STEP, file_name, file_uri, library_rows,
@@ -8400,17 +8523,71 @@ mod tests {
8400 .expect("nothing plays av2 any more");8523 .expect("nothing plays av2 any more");
8401 assert_eq!(rows(&session), 1, "the row went with it");8524 assert_eq!(rows(&session), 1, "the row went with it");
8402 assert_eq!(session.sources().len(), 1);8525 assert_eq!(session.sources().len(), 1);
8403- // The one file left cannot go: a project that names none is not one8526+ // The one file left is held to the same rule and no other: its own take
8404- // that reopens.8527+ // is still on the lanes, so it stays...
8528+ let first = session.sources()[0].path.clone();
8405 let refusal = session8529 let refusal = session
8406- .remove_source(&session.sources()[0].path.clone(), 0)8530+ .remove_source(&first, 0)
8407- .expect_err("the last file stays")8531+ .expect_err("its take is still on the timeline")
8408 .to_string();8532 .to_string();
8409- assert!(refusal.contains("only file"), "{refusal}");8533+ assert!(refusal.contains("still plays"), "{refusal}");
8534+ // ...and once nothing plays it, the *last* row goes too. What is left
8535+ // is the empty library `Player::close_session` turns back into the
8536+ // window the editor launches as -- the user-reported bug was that this
8537+ // very removal was refused, leaving a row that could never be taken
8538+ // out.
8539+ assert!(session.delete_clip(Lane::V1, 0));
8540+ session
8541+ .remove_source(&first, 0)
8542+ .expect("the only row goes like any other");
8543+ assert_eq!(rows(&session), 0, "an empty library");
8544+ assert!(session.sources().is_empty());
8545+ // And it is still a session: silent, empty, and asked for its length
8546+ // rather than panicking on a source list that is not there.
8547+ assert_eq!(session.timeline_duration(), 0.0);
8548+ assert!(
8549+ session.save_project(&asset("nothing.edith")).is_err(),
8550+ "a project naming no file could never be opened again, so it is not written"
8551+ );
8410 // A row this timeline never had is refused, not panicked on.8552 // A row this timeline never had is refused, not panicked on.
8411 assert!(session.remove_source(&second, 0).is_err());8553 assert!(session.remove_source(&second, 0).is_err());
8412 }8554 }
8413 8555
8556+ /// The clipboard after a library removal. A copied clip names its file by
8557+ /// index and a removal renumbers the list, so this is the difference
8558+ /// between pasting the take that was copied and pasting **another file**
8559+ /// over the same range ([`clipboard_after_remove`], called by
8560+ /// [`Player::remove_source`]).
8561+ #[test]
8562+ fn a_copied_clip_is_renumbered_or_dropped_when_a_row_leaves_the_library() {
8563+ let clip = |source: usize| Clip {
8564+ start: 0,
8565+ in_frame: 0,
8566+ out_frame: 30,
8567+ source,
8568+ link: None,
8569+ eq: None,
8570+ color: None,
8571+ fit: Default::default(),
8572+ speed: Default::default(),
8573+ };
8574+ // Copied from source 2, source 0 removed: the same file is source 1 now.
8575+ assert_eq!(
8576+ clipboard_after_remove(Some(clip(2)), 0).map(|c| c.source),
8577+ Some(1),
8578+ "the clipboard follows its file down the list"
8579+ );
8580+ // Copied from a source *before* the one that went: untouched.
8581+ assert_eq!(
8582+ clipboard_after_remove(Some(clip(0)), 2).map(|c| c.source),
8583+ Some(0)
8584+ );
8585+ // Copied from the row that was just removed: there is nothing left to
8586+ // paste, and pasting the next file along would be a lie.
8587+ assert!(clipboard_after_remove(Some(clip(1)), 1).is_none());
8588+ assert!(clipboard_after_remove(None, 0).is_none());
8589+ }
8590+
8414 /// The trim-a-clip path through the doors the edge drag uses:8591 /// The trim-a-clip path through the doors the edge drag uses:
8415 /// [`Player::trim_to`] clamps the pointer with `trim_room` and8592 /// [`Player::trim_to`] clamps the pointer with `trim_room` and
8416 /// [`Player::commit_trim`] writes it with `trim_clip`. The clip plays less8593 /// [`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
@@ -442,10 +442,12 @@ impl PlaybackSession {
442 ///442 ///
443 /// A *new* session rather than a reload of this one, so a load that fails443 /// A *new* session rather than a reload of this one, so a load that fails
444 /// leaves the caller's current session untouched -- atomic by444 /// leaves the caller's current session untouched -- atomic by
445- /// construction. Every named file is opened and checked here: source 0445+ /// construction. Every named file is opened and checked here: the
446- /// defines the timeline exactly as `open` does, every other source has to446+ /// *scaffolding* source -- the first that is not a still, since a picture
447- /// match it the way [`import`](Self::import) demands, and every clip has to447+ /// carries no rate -- defines the timeline exactly as `open` does, every
448- /// still be inside the file it plays from. A source that vanished or448+ /// other source has to match it the way [`import`](Self::import) demands
449+ /// (a save renumbers, so which index that is says nothing), and every clip
450+ /// has to still be inside the file it plays from. A source that vanished or
449 /// shrank since the save is a refusal naming it, not a silently shorter451 /// shrank since the save is a refusal naming it, not a silently shorter
450 /// timeline -- the disappearing-file tolerance elsewhere in this type452 /// timeline -- the disappearing-file tolerance elsewhere in this type
451 /// applies only *after* a project has loaded.453 /// applies only *after* a project has loaded.
@@ -453,15 +455,35 @@ impl PlaybackSession {
453 /// The undo history is not saved: `undo` is `false` on a fresh load.455 /// The undo history is not saved: `undo` is `false` on a fresh load.
454 pub fn open_project(path: &Path) -> crate::Result<Self> {456 pub fn open_project(path: &Path) -> crate::Result<Self> {
455 let doc = crate::edith::load(path)?;457 let doc = crate::edith::load(path)?;
458+ // *Which* source scaffolds it: the first that is not a still, and index
459+ // 0 only when there is no other. A still defines no frame rate -- it is
460+ // given [`IMAGE_ONLY_RATE`] -- so scaffolding a timeline of 24 fps
461+ // footage off a PNG that a save happened to renumber to index 0
462+ // (`Project::without_orphan_sources` numbers by first use, and a
463+ // library removal moves indexes too) reads the timeline as 30 fps and
464+ // then refuses every file on it for not matching. The rule this and
465+ // [`audio_source_of`] share: nothing may assume what source 0 *is*.
466+ //
467+ // ponytail: a timeline of nothing but stills, or of stills and songs,
468+ // still comes back at the rate its scaffold implies rather than the one
469+ // it was cut at -- the rate is written nowhere in the file. The upgrade
470+ // path is a dialect that writes it (`crate::edith`), which is also what
471+ // a project naming no file at all would need.
472+ let scaffold = doc
473+ .sources
474+ .iter()
475+ .position(|s| !crate::is_image(&s.path))
476+ .unwrap_or(0);
456 // Owned: the sources move into the `Project` below, and the device is477 // Owned: the sources move into the `Project` below, and the device is
457 // opened after that (see the comment there).478 // opened after that (see the comment there).
458 let first = doc479 let first = doc
459 .sources480 .sources
460- .first()481+ .get(scaffold)
461 .cloned()482 .cloned()
462 .ok_or("the project names no sources")?;483 .ok_or("the project names no sources")?;
463- // Source 0 both scaffolds the session and defines the timeline, so it484+ // The scaffolding source both defines the timeline and is what the
464- // is opened for playback rather than merely probed.485+ // playhead's first picture comes from, so it is opened for playback
486+ // rather than merely probed.
465 // One value, not two locals: everything below this line can refuse, and487 // One value, not two locals: everything below this line can refuse, and
466 // locals drop in reverse declaration order -- a bare worker would join488 // locals drop in reverse declaration order -- a bare worker would join
467 // its decode thread while the receiver next to it was still holding489 // its decode thread while the receiver next to it was still holding
@@ -528,8 +550,15 @@ impl PlaybackSession {
528 }550 }
529 let first_audio = first_audio_of(&doc.sources)?;551 let first_audio = first_audio_of(&doc.sources)?;
530 552
531- let mut counts = vec![meta.frame_count];553+ // In source order, with the scaffold's own count in its own slot: the
532- for source in &doc.sources[1..] {554+ // clip check below indexes this list by source, so it must line up with
555+ // `doc.sources` whichever entry the scaffolding came from.
556+ let mut counts = Vec::with_capacity(doc.sources.len());
557+ for (i, source) in doc.sources.iter().enumerate() {
558+ if i == scaffold {
559+ counts.push(meta.frame_count);
560+ continue;
561+ }
533 // A still has neither a rate to match nor a track to match with:562 // A still has neither a rate to match nor a track to match with:
534 // its length is the one it is held to, recomputed exactly as the563 // its length is the one it is held to, recomputed exactly as the
535 // import that first noted it did ([`image_frames`]), which is what564 // import that first noted it did ([`image_frames`]), which is what
@@ -604,7 +633,15 @@ impl PlaybackSession {
604 // only a session's `drop` retires it, so a refusal above this line would633 // only a session's `drop` retires it, so a refusal above this line would
605 // leave a PipeWire stream and a thread behind for a project that never634 // leave a PipeWire stream and a thread behind for a project that never
606 // opened. Nothing before it needs the device.635 // opened. Nothing before it needs the device.
607- let (audio, audio_disabled) = open_audio(&first.path, first.audio_stream);636+ //
637+ // On the source the timeline's *sound* is defined by, which is the
638+ // scaffold unless that one is a still ([`audio_source_of`]): opening a
639+ // PNG as the device is a session with no audio at all, however many
640+ // clips with sound are on its lanes.
641+ let (audio, audio_disabled) = match audio_source_of(project.sources()) {
642+ Some(source) => open_audio(&source.path, source.audio_stream),
643+ None => (None, None),
644+ };
608 let mut session = Self {645 let mut session = Self {
609 meta,646 meta,
610 native,647 native,
@@ -652,7 +689,16 @@ impl PlaybackSession {
652 /// Writes the timeline to `path` as a `.edith`, atomically (see689 /// Writes the timeline to `path` as a `.edith`, atomically (see
653 /// [`crate::edith`]). Sources no clip plays from are left out, and the690 /// [`crate::edith`]). Sources no clip plays from are left out, and the
654 /// playhead is saved with it so a reopened project resumes where it stood.691 /// playhead is saved with it so a reopened project resumes where it stood.
692+ ///
693+ /// Refused, writing nothing, for a session whose library is empty (every
694+ /// row removed, [`Project::remove_source`]): a file naming no source has no
695+ /// timeline in it and [`open_project`](Self::open_project) could only
696+ /// refuse it, so the refusal belongs here, where nothing has been
697+ /// overwritten yet.
655 pub fn save_project(&self, path: &Path) -> crate::Result<()> {698 pub fn save_project(&self, path: &Path) -> crate::Result<()> {
699+ if self.project.sources().is_empty() {
700+ return Err("this project names no file: there is nothing to save".into());
701+ }
656 let (sources, lanes, eq, color) = self.project.without_orphan_sources();702 let (sources, lanes, eq, color) = self.project.without_orphan_sources();
657 let playhead = secs_to_frame(self.now(), self.meta.frame_rate)703 let playhead = secs_to_frame(self.now(), self.meta.frame_rate)
658 .min(self.project.timeline_frames().saturating_sub(1));704 .min(self.project.timeline_frames().saturating_sub(1));
@@ -1318,7 +1364,14 @@ impl PlaybackSession {
1318 /// Reseeks like an edit even though nothing playable changed: the clip1364 /// Reseeks like an edit even though nothing playable changed: the clip
1319 /// indexes into the source list have just moved, and the running workers1365 /// indexes into the source list have just moved, and the running workers
1320 /// were opened against the old numbering.1366 /// were opened against the old numbering.
1321- pub fn remove_source(&mut self, path: &Path, stream: usize) -> crate::Result<()> {1367+ ///
1368+ /// The index that went, because everything past it moved down: a caller
1369+ /// holding a source index of its own (a clipboard) has to fix it up or drop
1370+ /// it, or it names a different file afterwards. The **last** row goes like
1371+ /// any other and leaves a session with an empty library -- silent, empty of
1372+ /// clips, and unsaveable ([`save_project`](Self::save_project)); a
1373+ /// front-end showing one is showing an empty window.
1374+ pub fn remove_source(&mut self, path: &Path, stream: usize) -> crate::Result<usize> {
1322 let wanted = Source::new(path, stream);1375 let wanted = Source::new(path, stream);
1323 let idx = self1376 let idx = self
1324 .project1377 .project
@@ -1337,11 +1390,12 @@ impl PlaybackSession {
1337 }1390 }
1338 let now = self.now();1391 let now = self.now();
1339 self.seek(now);1392 self.seek(now);
1340- Ok(())1393+ Ok(idx)
1341 }1394 }
1342 1395
1343- /// What the timeline's audio *is*: source 0's chosen stream, probed. Every1396+ /// What the timeline's audio *is*: the chosen stream of the first source
1344- /// other source is held to it.1397+ /// that could have any ([`audio_source_of`]), probed. Every other source is
1398+ /// held to it.
1345 fn first_audio(&self) -> crate::Result<Option<crate::AudioProbe>> {1399 fn first_audio(&self) -> crate::Result<Option<crate::AudioProbe>> {
1346 first_audio_of(self.project.sources())1400 first_audio_of(self.project.sources())
1347 }1401 }
@@ -1779,12 +1833,26 @@ fn matches_timeline(
1779 /// source 0 has always given. This function widens which source is asked, not1833 /// source 0 has always given. This function widens which source is asked, not
1780 /// what the answer means.1834 /// what the answer means.
1781 fn first_audio_of(sources: &[Source]) -> crate::Result<Option<crate::AudioProbe>> {1835 fn first_audio_of(sources: &[Source]) -> crate::Result<Option<crate::AudioProbe>> {
1782- match sources.iter().find(|s| !crate::is_image(&s.path)) {1836+ match audio_source_of(sources) {
1783 Some(first) => AudioSession::probe(&first.path, first.audio_stream),1837 Some(first) => AudioSession::probe(&first.path, first.audio_stream),
1784 None => Ok(None),1838 None => Ok(None),
1785 }1839 }
1786 }1840 }
1787 1841
1842+/// *Which* source that is: the first one that is not a still. The single answer
1843+/// to "what does this timeline's sound come from", so that probing it
1844+/// ([`first_audio_of`]) and opening the device on it
1845+/// ([`PlaybackSession::open_project`]) can never disagree -- source 0 is only
1846+/// the scaffolding file until a save renumbers it or a library removal takes it
1847+/// away ([`crate::Project::remove_source`]), and a PNG at index 0 opened as the
1848+/// device is a timeline that plays silent although every clip on it has sound.
1849+///
1850+/// `None` for a library of nothing but stills, and for one with no file at all:
1851+/// both are silent timelines.
1852+fn audio_source_of(sources: &[Source]) -> Option<&Source> {
1853+ sources.iter().find(|s| !crate::is_image(&s.path))
1854+}
1855+
1788 fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::Result<()> {1856 fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::Result<()> {
1789 // Whole-probe equality: rate and layout, which the audio worker holds every1857 // Whole-probe equality: rate and layout, which the audio worker holds every
1790 // source to anyway. Both silent is a match.1858 // source to anyway. Both silent is a match.
@@ -1937,7 +2005,7 @@ fn secs_to_frame(secs: f64, fps: f64) -> u32 {
1937 2005
1938 #[cfg(test)]2006 #[cfg(test)]
1939 mod tests {2007 mod tests {
1940- use super::{Edge, Lane, PlaybackSession, secs_to_frame};2008+ use super::{Edge, Lane, PlaybackSession, Source, audio_source_of, secs_to_frame};
1941 use std::path::PathBuf;2009 use std::path::PathBuf;
1942 2010
1943 fn asset(name: &str) -> PathBuf {2011 fn asset(name: &str) -> PathBuf {
@@ -1946,6 +2014,27 @@ mod tests {
1946 .join(name)2014 .join(name)
1947 }2015 }
1948 2016
2017+ /// Which source the timeline's sound is opened on -- the one rule
2018+ /// [`open_project`](PlaybackSession::open_project), the probe every import
2019+ /// is held to and the audio worker all read through. A still at index 0 is
2020+ /// a picture, not a silent timeline: opening the device on it is a project
2021+ /// that plays silent although every clip on it has sound.
2022+ #[test]
2023+ fn the_audio_reference_is_never_a_still() {
2024+ let (video, still) = (asset("test_av.mp4"), asset("test_still.png"));
2025+ let sources = [Source::new(&still, 0), Source::new(&video, 3)];
2026+ assert_eq!(
2027+ audio_source_of(&sources).map(|s| (&s.path, s.audio_stream)),
2028+ Some((&sources[1].path, 3)),
2029+ "the first source that could have a track, with its own stream"
2030+ );
2031+ assert!(
2032+ audio_source_of(&sources[..1]).is_none(),
2033+ "nothing but stills"
2034+ );
2035+ assert!(audio_source_of(&[]).is_none(), "and no file at all");
2036+ }
2037+
1949 /// The seam between the two lists a source index reaches: dropping a file2038 /// The seam between the two lists a source index reaches: dropping a file
1950 /// from the library shortens `sources`, and `counts` -- the frame length2039 /// from the library shortens `sources`, and `counts` -- the frame length
1951 /// per source, which is what a trim is walled by -- has to lose the same2040 /// per source, which is what a trim is walled by -- has to lose the same
crates/engine/src/project.rsmodified+41 -23
@@ -809,10 +809,20 @@ impl Project {
809 ///809 ///
810 /// Refused, changing nothing, while any clip still plays from it: the810 /// Refused, changing nothing, while any clip still plays from it: the
811 /// refusal names the lanes and how many clips each holds, so a caller can811 /// refusal names the lanes and how many clips each holds, so a caller can
812- /// say what has to be deleted first. Refused too for the last entry left,812+ /// say what has to be deleted first. The *last* entry goes like any other
813- /// because a project that names no file cannot be reopened813+ /// -- a project may name no file at all, which is an empty library over an
814- /// (`PlaybackSession::open_project`) and the timeline's audio parameters814+ /// empty timeline (nothing can play, since a clip would have refused the
815- /// are read off source 0.815+ /// removal). What a front-end does with that is its own decision: `edith`'s
816+ /// window goes back to the empty state it launches in, and
817+ /// [`PlaybackSession::save_project`](crate::PlaybackSession::save_project)
818+ /// refuses to write a project that names nothing, because no such file
819+ /// could be opened again.
820+ ///
821+ /// Every index past `idx` moves down by one, so a caller holding a *raw*
822+ /// source index of its own -- a clipboard, which is the one thing outside
823+ /// this type that does -- has to fix it up or drop it, or a paste plays a
824+ /// different file. [`PlaybackSession::remove_source`] hands back the index
825+ /// that went for exactly that.
816 ///826 ///
817 /// ponytail: this retires the undo stack. `history` holds lanes alone, so a827 /// ponytail: this retires the undo stack. `history` holds lanes alone, so a
818 /// snapshot older than the removal can name the very source being removed828 /// snapshot older than the removal can name the very source being removed
@@ -827,12 +837,6 @@ impl Project {
827 return Err(format!("there is no source {idx} to remove").into());837 return Err(format!("there is no source {idx} to remove").into());
828 };838 };
829 let name = source.path.display().to_string();839 let name = source.path.display().to_string();
830- // Asked before the clips are counted: with one file left the answer is
831- // the same whatever plays, and "the only file" is the more useful half
832- // of it.
833- if self.sources.len() == 1 {
834- return Err(format!("{name} is the only file this project names").into());
835- }
836 let used: Vec<String> = handles(&self.lanes)840 let used: Vec<String> = handles(&self.lanes)
837 .into_iter()841 .into_iter()
838 .zip(&self.lanes)842 .zip(&self.lanes)
@@ -876,9 +880,16 @@ impl Project {
876 /// only the ones a clip names.880 /// only the ones a clip names.
877 ///881 ///
878 /// One exception, and it is the emptied timeline's: a project no clip plays882 /// One exception, and it is the emptied timeline's: a project no clip plays
879- /// from still keeps source 0. It is the file a session is scaffolded from --883+ /// from still keeps its first source, if it has one. A file is what a
880- /// its frame rate is the timeline's and is written nowhere else -- so a save884+ /// reopened project scaffolds itself from -- the frame rate is written
881- /// that pruned it would write a project that cannot be loaded back at all.885+ /// nowhere else -- so a save that pruned the last of them would write a
886+ /// project that cannot be loaded back at all.
887+ ///
888+ /// What comes out is *not* ordered by anything a reader may assume: first
889+ /// use, lane by lane, means the entry at index 0 can be a still or a song
890+ /// whatever the session was scaffolded from. `PlaybackSession::open_project`
891+ /// picks its rate and its audio reference by what a source *is*, never by
892+ /// where it sits.
882 pub fn without_orphan_sources(&self) -> Parts {893 pub fn without_orphan_sources(&self) -> Parts {
883 let mut moved = vec![None; self.sources.len()];894 let mut moved = vec![None; self.sources.len()];
884 let mut sources = Vec::new();895 let mut sources = Vec::new();
@@ -3931,10 +3942,10 @@ mod tests {
3931 }3942 }
3932 3943
3933 /// The two edges of a removal: it retires the undo stack (the ponytail on3944 /// The two edges of a removal: it retires the undo stack (the ponytail on
3934- /// [`Project::remove_source`]), and the last entry standing cannot go --3945+ /// [`Project::remove_source`]), and the last entry goes like any other
3935- /// source 0 is where a reopened project reads its frame rate.3946+ /// once nothing plays it -- a project may name no file at all.
3936 #[test]3947 #[test]
3937- fn remove_source_retires_undo_and_keeps_the_last_file() {3948+ fn remove_source_retires_undo_and_empties_the_library() {
3938 let mut p = two_sources();3949 let mut p = two_sources();
3939 assert!(p.delete_in(Lane::V1, 3), "FILE2's take goes first");3950 assert!(p.delete_in(Lane::V1, 3), "FILE2's take goes first");
3940 assert!(!p.history.is_empty(), "there is something to undo");3951 assert!(!p.history.is_empty(), "there is something to undo");
@@ -3945,18 +3956,25 @@ mod tests {
3945 );3956 );
3946 assert!(!p.undo(), "and so there is nothing left to undo");3957 assert!(!p.undo(), "and so there is nothing left to undo");
3947 3958
3948- // The last file standing stays, whatever plays from it:3959+ // The last file standing is held to the one rule every row is -- what
3949- // `PlaybackSession::open_project` refuses a project that names no3960+ // plays cannot go -- and to no other.
3950- // sources at all, and the timeline's frame rate lives in source 0.
3951 assert_eq!(p.sources().len(), 1);3961 assert_eq!(p.sources().len(), 1);
3952 let refusal = p3962 let refusal = p
3953 .remove_source(0)3963 .remove_source(0)
3954- .expect_err("the only source must stay")3964+ .expect_err("its clips are still on the lanes")
3955 .to_string();3965 .to_string();
3956- assert!(refusal.contains("only file"), "{refusal}");3966+ assert!(refusal.contains("still plays"), "{refusal}");
3957- assert_eq!(p.sources().len(), 1);3967+ assert_eq!(p.sources().len(), 1, "a refusal changes nothing");
3968+ while p.delete_in(Lane::V1, 0) {}
3969+ p.remove_source(0)
3970+ .expect("the last row goes like any other");
3971+ assert!(
3972+ p.sources().is_empty(),
3973+ "a project may name no file at all: an empty library over an empty timeline"
3974+ );
3975+ assert_eq!(p.timeline_frames(), 0);
3958 assert!(3976 assert!(
3959- p.remove_source(1).is_err(),3977+ p.remove_source(0).is_err(),
3960 "and an index that is not there is refused, not panicked on"3978 "and an index that is not there is refused, not panicked on"
3961 );3979 );
3962 }3980 }
crates/engine/tests/images.rsmodified+89 -0
@@ -360,6 +360,95 @@ fn a_still_survives_the_project_round_trip() {
360 let _ = std::fs::remove_dir_all(&dir);360 let _ = std::fs::remove_dir_all(&dir);
361 }361 }
362 362
363+/// The save renumbers sources by first use, so a still at the head of `V1`
364+/// comes back as **source 0** however the session was scaffolded -- and source
365+/// 0 is what everything used to read the timeline off. A picture defines no
366+/// frame rate and has no sound, so the reload used to read this project as 30
367+/// fps (refusing the 25 fps footage still on `A1` by name) and open the output
368+/// device on a PNG (a timeline that plays silent although its clips have
369+/// sound). Nothing may assume what source 0 *is*: the rate comes from the first
370+/// source that has one, and the sound from the first that could have any.
371+#[test]
372+fn a_still_at_saved_source_zero_keeps_the_rate_and_the_sound() {
373+ pin_software();
374+ let dir = std::env::temp_dir().join(format!("ve_still_first_{}", std::process::id()));
375+ let _ = std::fs::remove_dir_all(&dir);
376+ std::fs::create_dir_all(&dir).expect("scratch dir");
377+ let media = dir.join("test_25fps.mp4");
378+ let still = dir.join("test_still.png");
379+ std::fs::copy(asset("test_25fps.mp4"), &media).expect("copy the video");
380+ std::fs::copy(asset("test_still.png"), &still).expect("copy the still");
381+
382+ // 25 fps, which no still is ever given: the rate alone says which source
383+ // the reload scaffolded from.
384+ let mut session = PlaybackSession::open(&media).expect("open the fixture");
385+ session.set_gain(0.0);
386+ assert!((session.meta().frame_rate - 25.0).abs() < 0.01);
387+ session.import(&still).expect("a picture");
388+ // Over the head of V1, where it takes the whole take's picture: the sound
389+ // stays on A1, so the still is the first clip in save order and the video
390+ // is a source only the audio lane names.
391+ assert!(
392+ session
393+ .place_stream_at(0.0, &still, 0, Some(Lane::V1))
394+ .expect("a still joins any timeline")
395+ );
396+ assert!(session.lane_clips(Lane::V1).len() == 1 && session.lane_clips(Lane::A1).len() == 1);
397+
398+ let project = dir.join("still_first.edith");
399+ session.save_project(&project).expect("save");
400+ let text = std::fs::read_to_string(&project).expect("read the project");
401+ let source_0 = text
402+ .lines()
403+ .find(|l| l.starts_with("source "))
404+ .expect("a source line");
405+ assert!(
406+ source_0.contains("test_still.png"),
407+ "the premise: the save put the still at index 0 -- {source_0}"
408+ );
409+
410+ let reopened = PlaybackSession::open_project(&project).expect("a saved project always reopens");
411+ assert!(
412+ (reopened.meta().frame_rate - 25.0).abs() < 0.01,
413+ "the footage's rate, not the still's 30: {}",
414+ reopened.meta().frame_rate
415+ );
416+ // The same sound, at the same place, playing the same file -- by a *new*
417+ // index, which is the renumbering this whole test is about.
418+ let (sound, was) = (
419+ reopened.lane_clips(Lane::A1)[0],
420+ session.lane_clips(Lane::A1)[0],
421+ );
422+ assert_eq!(
423+ (sound.start, sound.in_frame, sound.out_frame),
424+ (was.start, was.in_frame, was.out_frame)
425+ );
426+ assert!(
427+ reopened.sources()[sound.source]
428+ .path
429+ .ends_with("test_25fps.mp4"),
430+ "the take's sound still names the video"
431+ );
432+ assert!(
433+ reopened.audio_disabled_reason().is_none(),
434+ "a still is not a reason a timeline is silent: {:?}",
435+ reopened.audio_disabled_reason()
436+ );
437+ // And the sound itself, through the very opener a seek builds its worker
438+ // with: source 0 is the PNG here, and one opened unconditionally is an
439+ // error that takes every lane's audio down with it.
440+ let sources: Vec<_> = reopened
441+ .sources()
442+ .iter()
443+ .map(|s| (s.path.clone(), s.audio_stream))
444+ .collect();
445+ let (meta, _rx) = engine::AudioSession::open_multi_streams(&sources, &[(Some(1), 0.0, 1.0)])
446+ .expect("the worker opens over a still at index 0")
447+ .expect("the take on A1 has sound");
448+ assert_eq!(meta.sample_rate, 44_100, "the take's own rate");
449+ let _ = std::fs::remove_dir_all(&dir);
450+}
451+
363 /// The export is what was watched: a timeline of video then still comes back452 /// The export is what was watched: a timeline of video then still comes back
364 /// out of the mp4 as video then still, with the still's own colours in it.453 /// out of the mp4 as video then still, with the still's own colours in it.
365 #[test]454 #[test]