forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'worktree-agent-a695bc1c3e9f35be0'

Browse files at this commit

c0f047417a05ea88d6f77c9e404e384f94ff11cbAhmet Kaan GümüşParent: f52d7f5ecb5e06

14 changed files +1273 -338

crates/app/src/main.rsmodified+651 -184
@@ -4,13 +4,14 @@ use keymap::{ActionId, Keymap};
44
55 use std::cell::Cell;
66 use std::collections::HashMap;
7-use std::path::PathBuf;
7+use std::path::{Path, PathBuf};
88 use std::rc::Rc;
99 use std::sync::Arc;
1010 use std::time::{Duration, Instant};
1111
12+use engine::audio::StreamInfo;
1213 use engine::export::ExportSettings;
13-use engine::project::Lane;
14+use engine::project::{Lane, Source};
1415 use engine::{Clip, ExportHandle, Frame, PlaybackSession};
1516 use gpui::{
1617 AnyElement, App, Application, Bounds, ClickEvent, Context, FocusHandle, KeyDownEvent,
@@ -189,10 +190,10 @@ enum Wave {
189190 Peaks(Arc<Vec<(f32, f32)>>),
190191 }
191192
192-/// A library row being dragged. The source index and nothing else: the row is
193-/// only a way of naming a source, and where it lands does not change what is
194-/// inserted.
195-struct AssetDrag(usize);
193+/// A library row being dragged: the file and which of its audio streams that
194+/// row is, which is the whole of what a row names. Where it lands does not
195+/// change what is inserted.
196+struct AssetDrag(PathBuf, usize);
196197
197198 /// An open clip menu: which clip it was opened on, where it hangs, and whether
198199 /// it has been turned over to show what that clip *is* instead of what can be
@@ -249,16 +250,21 @@ struct Player {
249250 /// `selected` does, so it is closed by anything that can move indices --
250251 /// every stroke, and every item of its own.
251252 context_menu: Option<ContextMenu>,
252- /// Which library row is picked, as an index into the session's sources.
253- /// Its own selection and not the timeline's: Delete keeps acting on the
254- /// clip that was clicked in a lane, whatever the library is showing. Source
255- /// indexes are forever (project.rs:264), so this cannot go stale under an
256- /// edit -- only a new session clears it.
257- selected_asset: Option<usize>,
253+ /// Which library row is picked: the file and the audio stream that row
254+ /// names, which is what an insert needs and what survives a row list being
255+ /// rebuilt. Its own selection and not the timeline's: Delete keeps acting
256+ /// on the clip that was clicked in a lane, whatever the library is showing.
257+ selected_asset: Option<(PathBuf, usize)>,
258258 /// What is known about each source's audio, taken once and kept. Keyed on
259- /// the path, and the key is inserted the moment the decode is *started*:
260- /// presence means "asked", so a repaint mid-decode cannot ask again.
261- waves: HashMap<PathBuf, Wave>,
259+ /// the path *and stream* -- two streams of one file are two envelopes -- and
260+ /// the key is inserted the moment the decode is *started*: presence means
261+ /// "asked", so a repaint mid-decode cannot ask again.
262+ waves: HashMap<(PathBuf, usize), Wave>,
263+ /// Which audio streams each imported file has, as its header describes
264+ /// them: one library row per entry. Keyed and filled like `waves` --
265+ /// presence means "asked" -- and an empty list is a silent file, which is
266+ /// exactly one row and no stream tags.
267+ streams: HashMap<PathBuf, Vec<StreamInfo>>,
262268 /// The copied clip. Frame ranges only, so it survives the clip it was taken
263269 /// from being deleted -- and it outlives the selection.
264270 clipboard: Option<Clip>,
@@ -539,7 +545,8 @@ impl Player {
539545 }
540546 }
541547
542- /// Starts a peak decode for every source that has arrived since the last
548+ /// Starts a peak decode -- and a stream probe -- for every source that has
549+ /// arrived since the last
543550 /// repaint. One call from the render rather than three at the doors,
544551 /// because argv, an import and a project load are all doors and only this
545552 /// one is guaranteed to run after each of them.
@@ -550,16 +557,35 @@ impl Player {
550557 /// meanwhile and the repaint comes with the peaks. The entry is written
551558 /// *before* the spawn, so the sixty repaints that happen while a decode runs
552559 /// start no further ones.
553- fn cache_waves(&mut self, cx: &mut Context<Self>) {
560+ fn cache_media(&mut self, cx: &mut Context<Self>) {
554561 let Some(session) = &self.session else {
555562 return;
556563 };
557- for path in unseen_sources(session.sources(), &self.waves) {
558- self.waves.insert(path.clone(), Wave::Loading);
559- let decoded = cx.background_executor().spawn({
564+ // Which audio streams each file has, for the library's rows. Header
565+ // only, but a big file's sample tables are not free to parse, so it
566+ // goes off the render thread like the peaks do.
567+ for path in unseen_paths(session.sources(), &self.streams) {
568+ self.streams.insert(path.clone(), Vec::new());
569+ let probed = cx.background_executor().spawn({
560570 let path = path.clone();
571+ async move { engine::AudioSession::probe_streams(&path).unwrap_or_default() }
572+ });
573+ cx.spawn(async move |this, cx| {
574+ let probed = probed.await;
575+ this.update(cx, |this, cx| {
576+ this.streams.insert(path, probed);
577+ cx.notify();
578+ })
579+ .ok();
580+ })
581+ .detach();
582+ }
583+ for key in unseen_sources(session.sources(), &self.waves) {
584+ self.waves.insert(key.clone(), Wave::Loading);
585+ let decoded = cx.background_executor().spawn({
586+ let (path, stream) = key.clone();
561587 async move {
562- engine::waveform::peaks(&path, WAVE_BPS)
588+ engine::waveform::peaks(&path, stream, WAVE_BPS)
563589 .ok()
564590 .flatten()
565591 .map(|peaks| Arc::new(normalise(peaks)))
@@ -569,7 +595,7 @@ impl Player {
569595 let decoded = decoded.await;
570596 this.update(cx, |this, cx| {
571597 this.waves.insert(
572- path,
598+ key,
573599 match decoded {
574600 Some(peaks) => Wave::Peaks(peaks),
575601 // Either no audio track or a file we could not read
@@ -614,38 +640,50 @@ impl Player {
614640 /// moves along rather than being painted over. Reseeks like every other
615641 /// edit, and drops the timeline's selection with it: the insert has just
616642 /// moved the indices it pointed at.
617- fn insert_source(&mut self, source: usize, cx: &mut Context<Self>) {
643+ fn insert_source(&mut self, path: &Path, stream: usize, cx: &mut Context<Self>) {
618644 if self.exporting().is_some() {
619645 return;
620646 }
621- let clip = self.session.as_ref().and_then(|session| {
622- let frames = source_frames(lane_clips(session), source);
623- // Zero means nothing on the timeline plays from that file any more
624- // -- an undone import leaves the source entry behind (project.rs:264)
625- // -- so there is no length to insert and no file to ask for one.
626- (frames > 0).then_some(Clip {
627- start: 0,
628- in_frame: 0,
629- out_frame: frames,
630- source,
631- link: None,
632- })
647+ let frames = self.session.as_ref().map_or(0, |session| {
648+ source_frames(lane_clips(session), session.sources(), path)
633649 });
634- let added = match (&mut self.session, clip) {
635- (Some(session), Some(clip)) => session.paste_at(session.now(), clip),
636- _ => false,
650+ // Zero means nothing on the timeline plays from that file any more
651+ // -- an undone import leaves the source entry behind (project.rs:264)
652+ // -- so there is no length to insert and no file to ask for one.
653+ let placed = match (&mut self.session, frames) {
654+ (Some(session), 1..) => session.place_stream_at(session.now(), path, stream, frames),
655+ _ => Ok(false),
637656 };
638- if added {
639- self.selected = None;
640- self.reset_after_reseek();
641- } else {
642- self.notice = Some(
643- "NOTHING ADDED — no clip on the timeline plays from that file any more".into(),
644- );
657+ match placed {
658+ Ok(true) => {
659+ self.selected = None;
660+ self.reset_after_reseek();
661+ }
662+ // The engine's own words: a stream that cannot join this timeline
663+ // says which property disagrees, exactly as a refused import does.
664+ Err(e) => self.notice = Some(format!("NOTHING ADDED — {e}").into()),
665+ Ok(false) => {
666+ self.notice = Some(
667+ "NOTHING ADDED — no clip on the timeline plays from that file any more".into(),
668+ )
669+ }
645670 }
646671 cx.notify();
647672 }
648673
674+ /// The rate and layout the whole timeline's audio is, taken from source 0's
675+ /// own stream: what a library row has to match to be placeable. `None`
676+ /// until that file has been probed, and then nothing is greyed for it.
677+ fn timeline_audio(&self) -> Option<(u32, u16)> {
678+ let first = self.session.as_ref()?.sources().first()?;
679+ let info = self
680+ .streams
681+ .get(&first.path)?
682+ .iter()
683+ .find(|s| s.index == first.audio_stream)?;
684+ Some((info.sample_rate, info.channels))
685+ }
686+
649687 /// Appends a file to the end of the timeline. A drop is not a key press, so
650688 /// the export guard on the key handler does not cover it and this checks for
651689 /// itself. The engine reseeks, so like a delete it owes the flag reset; a
@@ -739,7 +777,7 @@ impl Player {
739777 let silent = audio_notice(&session);
740778 // A project is named after itself but still exports beside its
741779 // media: that is the only place an export has ever landed.
742- self.export_path = export_path(&session.sources()[0]);
780+ self.export_path = export_path(&session.sources()[0].path);
743781 self.session = Some(session);
744782 self.apply_volume();
745783 self.project_path = path.to_path_buf();
@@ -1009,7 +1047,7 @@ impl Render for Player {
10091047 // Every way a source can arrive -- argv, an import, a project load --
10101048 // has been through a repaint by the time its clips are drawn, so this
10111049 // is the one place that has to notice a new one.
1012- self.cache_waves(cx);
1050+ self.cache_media(cx);
10131051 // What the compositor calls this window. Pushed only when it changes:
10141052 // it is a protocol round trip and this runs at vsync.
10151053 let title = window_title(&self.name);
@@ -1277,81 +1315,108 @@ impl Player {
12771315 // the door (the import policy, ledger:436), so the session's own meta
12781316 // describes every row and nothing has to be probed to say so.
12791317 let meta = self.session.as_ref().map(PlaybackSession::meta);
1280- let rows: Vec<_> = sources
1281- .iter()
1282- .enumerate()
1283- .map(|(i, path)| {
1284- let picked = self.selected_asset == Some(i);
1285- let frames = self
1286- .session
1287- .as_ref()
1288- .map_or(0, |session| source_frames(lane_clips(session), i));
1289- let name: SharedString = file_name(path).into();
1290- let tip: SharedString = match meta {
1291- Some(meta) => format!(
1292- "{} — {}x{} @ {:.2} fps · drag onto a lane, or Add at playhead",
1293- path.display(),
1294- meta.width,
1295- meta.height,
1296- meta.frame_rate
1297- ),
1298- None => path.display().to_string(),
1299- }
1300- .into();
1301- let ghost = name.clone();
1302- div()
1303- .id(("asset", i))
1304- .flex_none()
1305- .h(px(ROW_H))
1306- .flex()
1307- .items_center()
1308- .gap(px(6.))
1309- .pr(px(6.))
1310- .rounded(px(3.))
1311- .cursor_pointer()
1312- .hover(|s| s.bg(rgb(HOVER)))
1313- .when(picked, |d| d.bg(rgb(SELECTED)).border_1())
1314- .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into())
1315- .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
1316- this.selected_asset = Some(i);
1317- cx.notify();
1318- }))
1319- // The drag carries the row's source and the row's name: one
1320- // for the drop to insert, one for the pointer to carry, so
1321- // what is being dragged is legible on the way down.
1322- .on_drag(AssetDrag(i), move |_, _, _, cx| {
1323- cx.new(|_| Tip(ghost.clone()))
1324- })
1325- // Full height and hard against the edge: the tint reads as
1326- // the lane's colour continuing into the list, not as a chip
1327- // that happens to be near it.
1328- .child(
1329- div()
1330- .flex_none()
1331- .w(px(SWATCH_W))
1332- .h_full()
1333- .rounded(px(2.))
1334- .bg(rgb(source_tint(i))),
1335- )
1336- .child(
1337- div()
1338- .flex_1()
1339- .min_w(px(0.))
1340- .flex()
1341- .flex_col()
1342- // Two lines rather than two columns: at the width
1343- // this panel yields to, a name and a timecode side
1344- // by side leave room for neither.
1345- .child(div().truncate().text_size(px(11.)).child(name))
1346- .child(
1347- div()
1348- .text_size(px(10.))
1349- .text_color(rgb(INK_DIM))
1350- .child(timecode(f64::from(frames) / self.fps, self.fps)),
1351- ),
1352- )
1353- })
1354- .collect();
1318+ let clips: Vec<Clip> = self
1319+ .session
1320+ .as_ref()
1321+ .map_or_else(Vec::new, |session| lane_clips(session).copied().collect());
1322+ let rows: Vec<_> = library_rows(sources, &self.streams, self.timeline_audio(), |path| {
1323+ source_frames(clips.iter(), sources, path)
1324+ })
1325+ .into_iter()
1326+ .enumerate()
1327+ .map(|(i, row)| {
1328+ let picked = self
1329+ .selected_asset
1330+ .as_ref()
1331+ .is_some_and(|p| *p == (row.path.clone(), row.stream));
1332+ let name: SharedString = row.name.clone().into();
1333+ let tip: SharedString = match (&row.unusable, meta) {
1334+ // A greyed row says why in full, where its length would be:
1335+ // the list is the one place the file's own tracks are named.
1336+ (Some(why), _) => format!("{} — {why}", row.path.display()),
1337+ (None, Some(meta)) => format!(
1338+ "{} — {}x{} @ {:.2} fps · drag onto a lane, or Add at playhead",
1339+ row.path.display(),
1340+ meta.width,
1341+ meta.height,
1342+ meta.frame_rate
1343+ ),
1344+ (None, None) => row.path.display().to_string(),
1345+ }
1346+ .into();
1347+ let ghost = name.clone();
1348+ // What the second line says: the stream, then either its length or
1349+ // the reason it cannot be used.
1350+ let under = match &row.unusable {
1351+ Some(why) => join_detail(&row.detail, why),
1352+ None => join_detail(
1353+ &row.detail,
1354+ &timecode(f64::from(row.frames) / self.fps, self.fps),
1355+ ),
1356+ };
1357+ let usable = row.unusable.is_none();
1358+ let (path, stream) = (row.path.clone(), row.stream);
1359+ let dragged = (path.clone(), stream);
1360+ div()
1361+ .id(("asset", i))
1362+ .flex_none()
1363+ .h(px(ROW_H))
1364+ .flex()
1365+ .items_center()
1366+ .gap(px(6.))
1367+ .pr(px(6.))
1368+ .rounded(px(3.))
1369+ // A row that cannot be placed takes no click and no drag, and
1370+ // reads as unavailable rather than merely unlucky.
1371+ .when(!usable, |d| d.text_color(rgb(INK_DIM)).opacity(0.55))
1372+ .when(usable, |d| {
1373+ d.cursor_pointer()
1374+ .hover(|s| s.bg(rgb(HOVER)))
1375+ .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
1376+ this.selected_asset = Some((path.clone(), stream));
1377+ cx.notify();
1378+ }))
1379+ // The drag carries the row's file and stream and the
1380+ // row's name: one for the drop to insert, one for the
1381+ // pointer to carry, so what is being dragged is legible
1382+ // on the way down.
1383+ .on_drag(AssetDrag(dragged.0, dragged.1), move |_, _, _, cx| {
1384+ cx.new(|_| Tip(ghost.clone()))
1385+ })
1386+ })
1387+ .when(picked, |d| d.bg(rgb(SELECTED)).border_1())
1388+ .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into())
1389+ // Full height and hard against the edge: the tint reads as
1390+ // the lane's colour continuing into the list, not as a chip
1391+ // that happens to be near it.
1392+ .child(
1393+ div()
1394+ .flex_none()
1395+ .w(px(SWATCH_W))
1396+ .h_full()
1397+ .rounded(px(2.))
1398+ .bg(rgb(source_tint(row.tint))),
1399+ )
1400+ .child(
1401+ div()
1402+ .flex_1()
1403+ .min_w(px(0.))
1404+ .flex()
1405+ .flex_col()
1406+ // Two lines rather than two columns: at the width
1407+ // this panel yields to, a name and a timecode side
1408+ // by side leave room for neither.
1409+ .child(div().truncate().text_size(px(11.)).child(name))
1410+ .child(
1411+ div()
1412+ .truncate()
1413+ .text_size(px(10.))
1414+ .text_color(rgb(INK_DIM))
1415+ .child(under),
1416+ ),
1417+ )
1418+ })
1419+ .collect();
13551420 div()
13561421 .flex_none()
13571422 .w(px(width))
@@ -1414,10 +1479,14 @@ impl Player {
14141479 Some(_) => "inserts the picked file at the playhead".to_string(),
14151480 None => "click a file above first — or drag one onto a lane".to_string(),
14161481 },
1417- can_add(self.selected_asset, self.session.is_some(), exporting),
1482+ can_add(
1483+ self.selected_asset.as_ref(),
1484+ self.session.is_some(),
1485+ exporting,
1486+ ),
14181487 cx.listener(|this, _: &ClickEvent, _, cx| {
1419- if let Some(source) = this.selected_asset {
1420- this.insert_source(source, cx);
1488+ if let Some((path, stream)) = this.selected_asset.clone() {
1489+ this.insert_source(&path, stream, cx);
14211490 }
14221491 }),
14231492 ))
@@ -1995,7 +2064,7 @@ impl Player {
19952064 let session = self.session.as_ref()?;
19962065 let clip = *session.lane_clips(menu.lane).get(menu.idx)?;
19972066 let playhead = frame_at(session.now(), self.fps);
1998- let path = session.sources().get(clip.source).cloned()?;
2067+ let source = session.sources().get(clip.source).cloned()?;
19992068 let secs = |frames: u32| timecode(f64::from(frames) / self.fps, self.fps);
20002069 let row = |n: usize| {
20012070 div()
@@ -2016,8 +2085,8 @@ impl Player {
20162085 // list of things to click. Each value is one truncated line, which
20172086 // is what keeps the height below the one the clamp was given.
20182087 for (label, value) in [
2019- ("File", file_name(&path)),
2020- ("Path", path.display().to_string()),
2088+ ("File", file_name(&source.path)),
2089+ ("Path", source.path.display().to_string()),
20212090 (
20222091 "Source range",
20232092 format!("{} – {}", secs(clip.in_frame), secs(clip.out_frame)),
@@ -2025,7 +2094,11 @@ impl Player {
20252094 ("This clip", secs(clip.len())),
20262095 (
20272096 "Source duration",
2028- secs(source_frames(lane_clips(session), clip.source)),
2097+ secs(source_frames(
2098+ lane_clips(session),
2099+ session.sources(),
2100+ &source.path,
2101+ )),
20292102 ),
20302103 ] {
20312104 rows.push(
@@ -2100,7 +2173,7 @@ impl Player {
21002173 viewport,
21012174 MENU_PAD * 2. + rows.len() as f32 * MENU_ROW_H,
21022175 );
2103- let full: SharedString = path.display().to_string().into();
2176+ let full: SharedString = source.path.display().to_string().into();
21042177 Some(
21052178 div()
21062179 .absolute()
@@ -2238,9 +2311,9 @@ impl Player {
22382311 // Add button makes, through the same call -- at the
22392312 // playhead, not at the pointer: clips here are placed end
22402313 // to end, so where along the bed it landed says nothing.
2241- .on_drop(
2242- cx.listener(|this, drag: &AssetDrag, _, cx| this.insert_source(drag.0, cx)),
2243- )
2314+ .on_drop(cx.listener(|this, drag: &AssetDrag, _, cx| {
2315+ this.insert_source(&drag.0.clone(), drag.1, cx)
2316+ }))
22442317 .drag_over::<AssetDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))
22452318 .children(clips.iter().enumerate().map(|(i, clip)| {
22462319 let (start, len) = (
@@ -2253,12 +2326,20 @@ impl Player {
22532326 // as detached before anyone clicks it.
22542327 let grouped =
22552328 clip.link.is_some() && others.iter().any(|o| o.link == clip.link);
2256- let tint = source_tint(clip.source);
2329+ // Tinted by *file*, not by source entry: two audio
2330+ // streams of one file are two sources, and the library
2331+ // gives them one swatch because they are one file.
2332+ let tint = source_tint(
2333+ sources
2334+ .get(clip.source)
2335+ .and_then(|s| sources.iter().position(|o| o.path == s.path))
2336+ .unwrap_or(clip.source),
2337+ );
22572338 let width = width_frac(len, duration);
2258- let label = sources.get(clip.source).map(|path| file_name(path));
2339+ let label = sources.get(clip.source).map(|s| file_name(&s.path));
22592340 let wave = sources
22602341 .get(clip.source)
2261- .and_then(|path| self.waves.get(path))
2342+ .and_then(|s| self.waves.get(&(s.path.clone(), s.audio_stream)))
22622343 .cloned();
22632344 let (from, to) = (
22642345 f64::from(clip.in_frame) / self.fps,
@@ -2481,14 +2562,29 @@ fn audio_notice(session: &PlaybackSession) -> Option<String> {
24812562 /// The sources a repaint has not asked about yet. A key that is already there
24822563 /// means "asked", whatever state it is in, which is what stops a decode already
24832564 /// running from being started again by the next of sixty repaints a second.
2484-fn unseen_sources(sources: &[PathBuf], waves: &HashMap<PathBuf, Wave>) -> Vec<PathBuf> {
2565+fn unseen_sources(
2566+ sources: &[Source],
2567+ waves: &HashMap<(PathBuf, usize), Wave>,
2568+) -> Vec<(PathBuf, usize)> {
24852569 sources
24862570 .iter()
2487- .filter(|path| !waves.contains_key(*path))
2488- .cloned()
2571+ .map(|s| (s.path.clone(), s.audio_stream))
2572+ .filter(|key| !waves.contains_key(key))
24892573 .collect()
24902574 }
24912575
2576+/// The same, for the per-file stream probe: one entry per *file*, however many
2577+/// of its streams the timeline plays.
2578+fn unseen_paths(sources: &[Source], streams: &HashMap<PathBuf, Vec<StreamInfo>>) -> Vec<PathBuf> {
2579+ let mut out: Vec<PathBuf> = Vec::new();
2580+ for s in sources {
2581+ if !streams.contains_key(&s.path) && !out.contains(&s.path) {
2582+ out.push(s.path.clone());
2583+ }
2584+ }
2585+ out
2586+}
2587+
24922588 /// Both lanes' clips, which is everything the timeline knows about its sources.
24932589 fn lane_clips(session: &PlaybackSession) -> impl Iterator<Item = &Clip> {
24942590 session
@@ -2498,17 +2594,25 @@ fn lane_clips(session: &PlaybackSession) -> impl Iterator<Item = &Clip> {
24982594 }
24992595
25002596 /// How long a source is, as the timeline knows it: the furthest frame any clip
2501-/// plays from it. Exact for a source the timeline still holds whole -- which is
2502-/// every source the moment it is imported -- and never longer than the file,
2503-/// since every clip was checked against it, so a clip built from this can
2504-/// always be played. Zero for a source nothing plays from any more.
2597+/// plays from *the file*. Exact for a source the timeline still holds whole --
2598+/// which is every source the moment it is imported -- and never longer than the
2599+/// file, since every clip was checked against it, so a clip built from this can
2600+/// always be played. Zero for a file nothing plays from any more.
2601+///
2602+/// By file rather than by source entry, because a second audio stream of a file
2603+/// already on the timeline is a row that has no clips of its own yet, and every
2604+/// stream of a file is the same length -- the picture is what the length is.
25052605 ///
25062606 /// ponytail: a source trimmed on the timeline reads as its trimmed length. The
25072607 /// file's own length would need a `Demuxer::open` probe per source, off the
25082608 /// render path like the peak decode is -- that is the upgrade path.
2509-fn source_frames<'a>(clips: impl Iterator<Item = &'a Clip>, source: usize) -> u32 {
2609+fn source_frames<'a>(
2610+ clips: impl Iterator<Item = &'a Clip>,
2611+ sources: &[Source],
2612+ path: &Path,
2613+) -> u32 {
25102614 clips
2511- .filter(|clip| clip.source == source)
2615+ .filter(|clip| sources.get(clip.source).is_some_and(|s| s.path == path))
25122616 .map(|clip| clip.out_frame)
25132617 .max()
25142618 .unwrap_or(0)
@@ -2554,10 +2658,165 @@ fn menu_at(at: Point<Pixels>, viewport: Size<Pixels>, height: f32) -> (f32, f32)
25542658 /// Whether the Add button does anything: a row picked, a timeline to put it on,
25552659 /// and no export reading that timeline. A button that would do nothing is dimmed
25562660 /// and takes no click, like every other one here.
2557-fn can_add(picked: Option<usize>, timeline: bool, exporting: bool) -> bool {
2661+fn can_add(picked: Option<&(PathBuf, usize)>, timeline: bool, exporting: bool) -> bool {
25582662 picked.is_some() && timeline && !exporting
25592663 }
25602664
2665+/// One library row: a file and one of its audio streams. Plain data, planned
2666+/// before anything is drawn -- which rows exist at all is the branchy part.
2667+#[derive(Debug, PartialEq)]
2668+struct Row {
2669+ path: PathBuf,
2670+ stream: usize,
2671+ /// The file, plus which stream this is when the file has several.
2672+ name: String,
2673+ /// What the stream is, or blank for a file with a single one.
2674+ detail: String,
2675+ /// Why it cannot be put on this timeline, for a row that cannot: shown in
2676+ /// place of the length and the only thing that greys a row out.
2677+ unusable: Option<String>,
2678+ /// Frames of the *file*, for the length line.
2679+ frames: u32,
2680+ /// Index into `SOURCE_TINTS`, shared by every stream of one file: the
2681+ /// swatch says which file, and the lanes tint their clips the same way.
2682+ tint: usize,
2683+}
2684+
2685+/// Every row the library shows: one per source entry, plus one for each further
2686+/// audio stream those files have that no clip plays yet -- a remux with a track
2687+/// per language lists them all, the ones this engine cannot use greyed out
2688+/// rather than hidden. Streams a file has not been probed for yet simply are
2689+/// not there; the row for what *is* on the timeline is always there.
2690+///
2691+/// `timeline_audio` is the rate and layout of source 0's stream, which every
2692+/// other source must match: one output device and one copied AAC track for the
2693+/// whole timeline (`PlaybackSession::place_stream_at`). `None` while unknown,
2694+/// and then nothing is greyed for it -- the engine still refuses.
2695+fn library_rows(
2696+ sources: &[Source],
2697+ streams: &HashMap<PathBuf, Vec<StreamInfo>>,
2698+ timeline_audio: Option<(u32, u16)>,
2699+ frames: impl Fn(&Path) -> u32,
2700+) -> Vec<Row> {
2701+ let mut rows = Vec::new();
2702+ for (i, source) in sources.iter().enumerate() {
2703+ let of_file = streams.get(&source.path).map_or(&[][..], Vec::as_slice);
2704+ let info = of_file.iter().find(|s| s.index == source.audio_stream);
2705+ let tint = sources
2706+ .iter()
2707+ .position(|s| s.path == source.path)
2708+ .expect("a source finds itself");
2709+ rows.push(Row {
2710+ path: source.path.clone(),
2711+ stream: source.audio_stream,
2712+ name: row_name(&source.path, source.audio_stream, of_file.len() > 1),
2713+ // Only where there is a choice to describe: a file with one audio
2714+ // track is the row it has always been, name and length, and the
2715+ // length is what would be squeezed out at the panel's least width.
2716+ detail: info
2717+ .filter(|_| of_file.len() > 1)
2718+ .map_or_else(String::new, stream_detail),
2719+ // A stream already on the timeline is playing: whatever a probe
2720+ // would say about it now, it is usable by demonstration.
2721+ unusable: None,
2722+ frames: frames(&source.path),
2723+ tint,
2724+ });
2725+ // The file's other streams, listed once, right after the last entry
2726+ // that names the file -- so a file's rows sit together.
2727+ if sources[i + 1..].iter().any(|s| s.path == source.path) {
2728+ continue;
2729+ }
2730+ for info in of_file {
2731+ if sources
2732+ .iter()
2733+ .any(|s| s.path == source.path && s.audio_stream == info.index)
2734+ {
2735+ continue; // it has a row of its own above
2736+ }
2737+ rows.push(Row {
2738+ path: source.path.clone(),
2739+ stream: info.index,
2740+ name: row_name(&source.path, info.index, true),
2741+ detail: stream_detail(info),
2742+ unusable: unusable(info, timeline_audio),
2743+ frames: frames(&source.path),
2744+ tint,
2745+ });
2746+ }
2747+ }
2748+ rows
2749+}
2750+
2751+/// The row's second line: what the stream is and then either how long it is or
2752+/// why it cannot be used, with the separator only where both halves exist (a
2753+/// single-stream file says nothing about its stream).
2754+fn join_detail(detail: &str, tail: &str) -> String {
2755+ match detail.is_empty() {
2756+ true => tail.to_string(),
2757+ false => format!("{detail} · {tail}"),
2758+ }
2759+}
2760+
2761+/// How a row names its file: the file alone when it has one audio stream or
2762+/// none, and the file plus which stream this row is when it has several --
2763+/// counted from 1, the way a player numbers tracks.
2764+fn row_name(path: &Path, stream: usize, several: bool) -> String {
2765+ match several {
2766+ false => file_name(path),
2767+ true => format!("{} [audio {}]", file_name(path), stream + 1),
2768+ }
2769+}
2770+
2771+/// What a stream is, for the row's second line: the language if the file says
2772+/// one, then rate and layout. A field the header does not give is left out
2773+/// rather than shown as a zero -- a stream we cannot parse says nothing about
2774+/// itself, and saying "0 Hz" would be saying something.
2775+fn stream_detail(info: &StreamInfo) -> String {
2776+ let mut parts: Vec<String> = Vec::new();
2777+ if let Some(lang) = &info.lang {
2778+ parts.push(lang.clone());
2779+ }
2780+ if info.sample_rate > 0 {
2781+ parts.push(format!("{} kHz", f64::from(info.sample_rate) / 1000.));
2782+ }
2783+ parts.extend(layout(info.channels));
2784+ parts.join(" ")
2785+}
2786+
2787+fn layout(channels: u16) -> Option<String> {
2788+ match channels {
2789+ 0 => None,
2790+ 1 => Some("mono".to_string()),
2791+ 2 => Some("stereo".to_string()),
2792+ n => Some(format!("{n} ch")),
2793+ }
2794+}
2795+
2796+/// Why a stream cannot go on this timeline, or `None` if it can. Both answers
2797+/// are shown: a stream nothing can be done with is listed greyed with the
2798+/// reason, never dropped from the list -- a file has the tracks it has, and a
2799+/// picker that hides them is a picker that lies.
2800+fn unusable(info: &StreamInfo, timeline_audio: Option<(u32, u16)>) -> Option<String> {
2801+ if !info.decodable {
2802+ // ponytail: mp4 0.14 keeps no fourcc for a sample entry it does not
2803+ // parse (`StreamInfo::codec`), so an AC-3 track can only be named as
2804+ // unsupported, not as AC-3. Upgrade path is reading the stsd ourselves.
2805+ return Some(match info.codec.as_str() {
2806+ "unknown" => "unsupported codec".to_string(),
2807+ codec => format!("{codec} is not supported"),
2808+ });
2809+ }
2810+ let (rate, channels) = timeline_audio?;
2811+ ((info.sample_rate, info.channels) != (rate, channels)).then(|| {
2812+ format!(
2813+ "the timeline is {} kHz {}",
2814+ f64::from(rate) / 1000.,
2815+ layout(channels).unwrap_or_else(|| "silent".to_string())
2816+ )
2817+ })
2818+}
2819+
25612820 /// What the media list is given of the window. A share of it, so a narrow
25622821 /// window gives the panel less rather than giving the picture nothing, floored
25632822 /// where a name stops being readable and capped at a third of the window --
@@ -2993,12 +3252,13 @@ mod tests {
29933252 ACCENT, CONTROL_H, Clip, HEADER_GAP, HEADER_W, HIT_MIN, INK, INK_DIM, KEYS_ROW_H,
29943253 KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W,
29953254 Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED,
2996- SOURCE_TINTS, SURFACE, SWATCH_W, Volume, WAVE_BPS, WAVE_COL, Wave, applicable, can_add,
2997- cancels_export, envelope, export_path, export_settings, frac_along, frame_at,
2998- is_bare_modifier, is_project, keymap, lane_clips, marked, menu_at, normalise, project_path,
2999- push_digit, scrub_due, show_label, source_frames, source_tint, start_frac, timecode,
3000- unseen_sources, width_frac, window_title,
3255+ SOURCE_TINTS, SURFACE, SWATCH_W, Source, StreamInfo, Volume, WAVE_BPS, WAVE_COL, Wave,
3256+ applicable, can_add, cancels_export, envelope, export_path, export_settings, frac_along,
3257+ frame_at, is_bare_modifier, is_project, keymap, lane_clips, marked, menu_at, normalise,
3258+ project_path, push_digit, scrub_due, show_label, source_frames, source_tint, start_frac,
3259+ timecode, unseen_paths, unseen_sources, width_frac, window_title,
30013260 };
3261+ use super::{file_name, library_rows};
30023262 use engine::PlaybackSession;
30033263 use gpui::{Bounds, Pixels, point, px, size};
30043264 use std::collections::HashMap;
@@ -3023,7 +3283,15 @@ mod tests {
30233283 }
30243284 }
30253285
3026- /// The whole of the library's row data comes off the clips: which sources
3286+ /// A source entry for `path` on `stream`, as the project keeps them.
3287+ fn source(path: &str, stream: usize) -> Source {
3288+ Source {
3289+ path: PathBuf::from(path),
3290+ audio_stream: stream,
3291+ }
3292+ }
3293+
3294+ /// The whole of the library's row data comes off the clips: which files
30273295 /// there are, how long each one is, and therefore which tint each row wears
30283296 /// -- one index into one list, so a swatch cannot name a different file from
30293297 /// the boxes it is meant to point at.
@@ -3032,11 +3300,12 @@ mod tests {
30323300 // Source 0 whole, source 1 trimmed to half of what it was, source 2 on
30333301 // the audio lane only (its picture was lifted), source 3 imported and
30343302 // then undone -- an entry with nothing playing from it.
3303+ let sources: Vec<Source> = (0..4).map(|i| source(&format!("/m/{i}.mp4"), 0)).collect();
30353304 let video = [clip(0, 150), clip(1, 60)];
30363305 let audio = [clip(0, 150), clip(1, 30), clip(2, 90)];
30373306 for (row, frames) in [(0, 150), (1, 60), (2, 90), (3, 0)] {
30383307 assert_eq!(
3039- source_frames(video.iter().chain(&audio), row),
3308+ source_frames(video.iter().chain(&audio), &sources, &sources[row].path),
30403309 frames,
30413310 "row {row}"
30423311 );
@@ -3044,11 +3313,146 @@ mod tests {
30443313 // function -- what makes the panel and the lanes one association.
30453314 assert_eq!(source_tint(row), SOURCE_TINTS[row % SOURCE_TINTS.len()]);
30463315 }
3047- // The longest clip of a source wins, whichever lane it is in and
3316+ // The longest clip of a file wins, whichever lane it is in and
30483317 // whatever order the lanes are read in.
3049- assert_eq!(source_frames([clip(0, 10), clip(0, 90)].iter(), 0), 90);
3050- assert_eq!(source_frames([clip(0, 90), clip(0, 10)].iter(), 0), 90);
3051- assert_eq!(source_frames([].iter(), 0), 0);
3318+ let one = [source("/m/0.mp4", 0)];
3319+ let path = &one[0].path;
3320+ assert_eq!(
3321+ source_frames([clip(0, 10), clip(0, 90)].iter(), &one, path),
3322+ 90
3323+ );
3324+ assert_eq!(
3325+ source_frames([clip(0, 90), clip(0, 10)].iter(), &one, path),
3326+ 90
3327+ );
3328+ assert_eq!(source_frames([].iter(), &one, path), 0);
3329+ // Two audio streams of one file are two source entries and one length:
3330+ // the second stream's row is placeable the moment the file is there,
3331+ // before any clip names that entry.
3332+ let two = [source("/m/0.mp4", 0), source("/m/0.mp4", 1)];
3333+ assert_eq!(source_frames([clip(0, 90)].iter(), &two, &two[1].path), 90);
3334+ }
3335+
3336+ fn info(
3337+ index: usize,
3338+ rate: u32,
3339+ channels: u16,
3340+ lang: Option<&str>,
3341+ decodable: bool,
3342+ ) -> StreamInfo {
3343+ StreamInfo {
3344+ index,
3345+ codec: if decodable { "aac" } else { "unknown" }.into(),
3346+ channels,
3347+ sample_rate: rate,
3348+ lang: lang.map(str::to_string),
3349+ decodable,
3350+ }
3351+ }
3352+
3353+ /// A file's every audio track gets a row: the ones the timeline can take
3354+ /// are placeable, the ones it cannot are listed greyed with the reason.
3355+ /// Which rows exist at all is the branchy part of the panel, so it is
3356+ /// planned as data and checked here rather than through the pointer.
3357+ #[test]
3358+ fn every_audio_stream_of_a_file_is_a_row_usable_or_not() {
3359+ let multi = PathBuf::from("/m/movie.mp4");
3360+ let sources = [source("/m/movie.mp4", 0)];
3361+ let mut streams = HashMap::new();
3362+ streams.insert(
3363+ multi.clone(),
3364+ vec![
3365+ info(0, 44_100, 2, None, true),
3366+ info(1, 44_100, 2, Some("fra"), true),
3367+ info(2, 22_050, 1, Some("deu"), true),
3368+ info(3, 0, 0, None, false),
3369+ ],
3370+ );
3371+ let rows = library_rows(&sources, &streams, Some((44_100, 2)), |_| 90);
3372+ assert_eq!(
3373+ rows.iter().map(|r| r.stream).collect::<Vec<_>>(),
3374+ [0, 1, 2, 3],
3375+ "one row per audio stream, in file order"
3376+ );
3377+ assert!(
3378+ rows.iter().all(|r| r.path == multi && r.tint == 0),
3379+ "every stream of one file wears the file's own tint"
3380+ );
3381+ assert_eq!(rows[0].name, "movie.mp4 [audio 1]");
3382+ assert_eq!(rows[1].name, "movie.mp4 [audio 2]");
3383+ assert_eq!(rows[1].detail, "fra 44.1 kHz stereo");
3384+ // Placeable: the one already on the timeline, and the one that matches
3385+ // it. The 22 kHz mono track cannot join a 44.1 kHz stereo timeline --
3386+ // one device and one copied AAC track for the whole of it -- and the
3387+ // codec we cannot read cannot join anything. Both say which.
3388+ assert_eq!((&rows[0].unusable, &rows[1].unusable), (&None, &None));
3389+ assert_eq!(
3390+ rows[2].unusable.as_deref(),
3391+ Some("the timeline is 44.1 kHz stereo")
3392+ );
3393+ assert_eq!(rows[3].unusable.as_deref(), Some("unsupported codec"));
3394+ assert_eq!(
3395+ rows[3].detail, "",
3396+ "a stream we cannot parse claims nothing"
3397+ );
3398+ // Every row is the same file, so every row is that file's length.
3399+ assert!(rows.iter().all(|r| r.frames == 90));
3400+
3401+ // The single-stream case is exactly one row and no stream tag: no
3402+ // regression for the media everything else in the world is.
3403+ let plain = [source("/m/plain.mp4", 0)];
3404+ let mut one = HashMap::new();
3405+ one.insert(
3406+ PathBuf::from("/m/plain.mp4"),
3407+ vec![info(0, 44_100, 2, None, true)],
3408+ );
3409+ let rows = library_rows(&plain, &one, Some((44_100, 2)), |_| 90);
3410+ assert_eq!(rows.len(), 1);
3411+ assert_eq!(rows[0].name, "plain.mp4");
3412+ assert_eq!(
3413+ rows[0].detail, "",
3414+ "one audio track is the row it has always been: name and length"
3415+ );
3416+ // ...as is a silent file, and a file not probed yet.
3417+ let mut silent = HashMap::new();
3418+ silent.insert(PathBuf::from("/m/plain.mp4"), Vec::new());
3419+ for probe in [silent, HashMap::new()] {
3420+ let rows = library_rows(&plain, &probe, None, |_| 90);
3421+ assert_eq!(rows.len(), 1);
3422+ assert_eq!(rows[0].name, "plain.mp4");
3423+ assert_eq!(rows[0].detail, "");
3424+ }
3425+
3426+ // A second stream *placed* on the timeline is a source entry of its
3427+ // own: it keeps its row, no duplicate appears for it, and the rows of
3428+ // one file stay together whatever order the entries came in.
3429+ let placed = [
3430+ source("/m/movie.mp4", 0),
3431+ source("/m/other.mp4", 0),
3432+ source("/m/movie.mp4", 2),
3433+ ];
3434+ streams.insert(
3435+ PathBuf::from("/m/other.mp4"),
3436+ vec![info(0, 44_100, 2, None, true)],
3437+ );
3438+ let rows = library_rows(&placed, &streams, Some((44_100, 2)), |_| 90);
3439+ assert_eq!(
3440+ rows.iter()
3441+ .map(|r| (file_name(&r.path), r.stream))
3442+ .collect::<Vec<_>>(),
3443+ [
3444+ ("movie.mp4".to_string(), 0),
3445+ ("other.mp4".to_string(), 0),
3446+ ("movie.mp4".to_string(), 2),
3447+ ("movie.mp4".to_string(), 1),
3448+ ("movie.mp4".to_string(), 3),
3449+ ]
3450+ );
3451+ assert!(
3452+ rows[2].unusable.is_none(),
3453+ "a stream already on the timeline is playing, whatever a probe says"
3454+ );
3455+ assert_eq!(rows[1].tint, 1, "the other file is the other tint");
30523456 }
30533457
30543458 /// What the clip menu offers, and where it hangs. The two items that act on
@@ -3128,7 +3532,11 @@ mod tests {
31283532 // at 30 fps, exactly what was appended.
31293533 session.import(&asset("test_av2.mp4")).expect("av2 matches");
31303534 assert_eq!(session.sources().len(), 2);
3131- assert_eq!(source_frames(lane_clips(&session), 1), 120);
3535+ let second = session.sources()[1].path.clone();
3536+ assert_eq!(
3537+ source_frames(lane_clips(&session), session.sources(), &second),
3538+ 120
3539+ );
31323540 assert_eq!(timecode(120. / 30., 30.), "00:00:04:00");
31333541 }
31343542
@@ -3143,17 +3551,15 @@ mod tests {
31433551 assert_eq!(session.timeline_duration(), 9.0);
31443552 // Two seconds in, which is inside the first take: the insert splits it.
31453553 session.seek(2.0);
3146- let frames = source_frames(lane_clips(&session), 1);
3147- assert!(session.paste_at(
3148- 2.0,
3149- Clip {
3150- start: 0,
3151- in_frame: 0,
3152- out_frame: frames,
3153- source: 1,
3154- link: None,
3155- }
3156- ));
3554+ let second = session.sources()[1].path.clone();
3555+ let frames = source_frames(lane_clips(&session), session.sources(), &second);
3556+ // Through the engine door `insert_source` uses, with the row's own
3557+ // stream: the button, the drop and this are one call.
3558+ assert!(
3559+ session
3560+ .place_stream_at(2.0, &second, 0, frames)
3561+ .expect("av2 is already on the timeline")
3562+ );
31573563 // The whole of source 1 went in and nothing was painted over: the
31583564 // timeline is longer by exactly that file.
31593565 assert_eq!(session.timeline_duration(), 13.0);
@@ -3174,32 +3580,89 @@ mod tests {
31743580 assert_eq!(at(video).len(), frames);
31753581 assert!(at(video).link.is_some());
31763582 assert_eq!(video.len(), audio.len());
3583+
3584+ // The same door with a *second audio stream* of a file already there:
3585+ // a new source entry, the same picture, and the row that was dragged
3586+ // is what plays. This is the whole user-facing point of the slice.
3587+ let mut session =
3588+ PlaybackSession::open(asset("test_multilang.mp4")).expect("open the fixture");
3589+ session.set_gain(0.0);
3590+ let path = session.sources()[0].path.clone();
3591+ let frames = source_frames(lane_clips(&session), session.sources(), &path);
3592+ let end = session.timeline_duration();
3593+ assert!(
3594+ session
3595+ .place_stream_at(end, &path, 1, frames)
3596+ .expect("the French track shares the timeline's parameters")
3597+ );
3598+ assert_eq!(session.sources()[1].audio_stream, 1);
3599+ assert_eq!(session.timeline_duration(), end * 2.0);
3600+ // Both rows are the same file, so both rows are that file's length --
3601+ // the second one before any clip of its own existed.
3602+ assert_eq!(
3603+ source_frames(lane_clips(&session), session.sources(), &path),
3604+ frames
3605+ );
31773606 }
31783607
31793608 #[test]
31803609 fn a_source_is_only_ever_asked_for_its_peaks_once() {
31813610 let (a, b) = (asset("test_av.mp4"), asset("test_av2.mp4"));
3182- let sources = [a.clone(), b.clone()];
3183- let mut waves: HashMap<PathBuf, Wave> = HashMap::new();
3184- assert_eq!(unseen_sources(&sources, &waves), sources);
3611+ // Two files, and two streams of the first: three envelopes, because
3612+ // one file's two audio tracks are two different waveforms.
3613+ let sources = [
3614+ Source {
3615+ path: a.clone(),
3616+ audio_stream: 0,
3617+ },
3618+ Source {
3619+ path: a.clone(),
3620+ audio_stream: 1,
3621+ },
3622+ Source {
3623+ path: b.clone(),
3624+ audio_stream: 0,
3625+ },
3626+ ];
3627+ let keys = |s: &[Source]| {
3628+ s.iter()
3629+ .map(|s| (s.path.clone(), s.audio_stream))
3630+ .collect::<Vec<_>>()
3631+ };
3632+ let mut waves: HashMap<(PathBuf, usize), Wave> = HashMap::new();
3633+ assert_eq!(unseen_sources(&sources, &waves), keys(&sources));
31853634 // The entry goes in when the decode *starts*, so the sixty repaints a
31863635 // second that happen while it runs must not start it again -- which is
31873636 // what this asserts about a key whose value is not an answer yet.
3188- waves.insert(a, Wave::Loading);
3189- assert_eq!(unseen_sources(&sources, &waves), vec![b.clone()]);
3637+ waves.insert((a.clone(), 0), Wave::Loading);
3638+ assert_eq!(
3639+ unseen_sources(&sources, &waves),
3640+ keys(&sources[1..]),
3641+ "the file's other stream is a key of its own"
3642+ );
31903643 // A file with no audio is an answer like any other: never re-asked.
3191- waves.insert(b, Wave::Silent);
3644+ waves.insert((a, 1), Wave::Silent);
3645+ waves.insert((b.clone(), 0), Wave::Silent);
31923646 assert!(unseen_sources(&sources, &waves).is_empty());
3647+ // The stream probe is per *file*: the two entries of `a` ask once.
3648+ let mut streams: HashMap<PathBuf, Vec<StreamInfo>> = HashMap::new();
3649+ assert_eq!(
3650+ unseen_paths(&sources, &streams),
3651+ vec![asset("test_av.mp4"), b]
3652+ );
3653+ streams.insert(asset("test_av.mp4"), Vec::new());
3654+ assert_eq!(unseen_paths(&sources, &streams).len(), 1);
31933655 }
31943656
31953657 #[test]
31963658 fn the_add_button_is_dead_unless_it_would_do_something() {
3197- assert!(can_add(Some(0), true, false));
3659+ let picked = (PathBuf::from("/m/0.mp4"), 0);
3660+ assert!(can_add(Some(&picked), true, false));
31983661 // Nothing picked, nothing to put it on, or an export reading the very
31993662 // edit list this would change.
32003663 assert!(!can_add(None, true, false));
3201- assert!(!can_add(Some(0), false, false));
3202- assert!(!can_add(Some(0), true, true));
3664+ assert!(!can_add(Some(&picked), false, false));
3665+ assert!(!can_add(Some(&picked), true, true));
32033666 }
32043667
32053668 #[test]
@@ -3691,7 +4154,7 @@ mod tests {
36914154 .join(name)
36924155 };
36934156 let peaks = normalise(
3694- engine::waveform::peaks(asset("test_av.mp4"), WAVE_BPS)
4157+ engine::waveform::peaks(asset("test_av.mp4"), 0, WAVE_BPS)
36954158 .expect("open the fixture")
36964159 .expect("test_av.mp4 has audio"),
36974160 );
@@ -3710,7 +4173,7 @@ mod tests {
37104173 );
37114174 // A video-only source draws no waveform at all rather than a flat fake.
37124175 assert!(
3713- engine::waveform::peaks(asset("test_baseline.mp4"), WAVE_BPS)
4176+ engine::waveform::peaks(asset("test_baseline.mp4"), 0, WAVE_BPS)
37144177 .expect("open the fixture")
37154178 .is_none()
37164179 );
@@ -3807,7 +4270,10 @@ fn main() {
38074270 }
38084271 // A file that plays silent is as much news at launch as it is on a drop, and
38094272 // behind the keymap notice for the same reason an import refusal is.
3810- if let Some(reason) = session.as_ref().and_then(PlaybackSession::audio_disabled_reason) {
4273+ if let Some(reason) = session
4274+ .as_ref()
4275+ .and_then(PlaybackSession::audio_disabled_reason)
4276+ {
38114277 let text = format!("NO AUDIO: {reason}");
38124278 eprintln!("{text}");
38134279 notice.get_or_insert(text);
@@ -3815,9 +4281,9 @@ fn main() {
38154281 let meta = session.as_ref().map(|session| *session.meta());
38164282 // Beside the media even for a project: an export has never landed anywhere
38174283 // but next to the picture it came from.
3818- let out = session
3819- .as_ref()
3820- .map_or_else(PathBuf::new, |session| export_path(&session.sources()[0]));
4284+ let out = session.as_ref().map_or_else(PathBuf::new, |session| {
4285+ export_path(&session.sources()[0].path)
4286+ });
38214287 let project = match &arg {
38224288 Some(arg) if is_project(arg) => arg.clone(),
38234289 Some(arg) => project_path(arg),
@@ -3884,6 +4350,7 @@ fn main() {
38844350 context_menu: None,
38854351 selected_asset: None,
38864352 waves: HashMap::new(),
4353+ streams: HashMap::new(),
38874354 clipboard: None,
38884355 scrubbing: false,
38894356 last_scrub: Instant::now(),
crates/engine/src/audio.rsmodified+31 -18
@@ -274,16 +274,19 @@ impl AudioSession {
274274 .find(|t| matches!(t.track_type(), Ok(TrackType::Audio)))
275275 .map(|t| match t.media_type() {
276276 Ok(media) => format!("the {media} audio track cannot be decoded (AAC-LC only)"),
277- Err(_) => "the audio track is in a codec we cannot decode (AAC-LC only)".to_string(),
277+ Err(_) => {
278+ "the audio track is in a codec we cannot decode (AAC-LC only)".to_string()
279+ }
278280 }))
279281 }
280282
281- /// The audio parameters of `path`, for checking an import against the
282- /// timeline's first source: header only, no decoder and no worker.
283- /// `Ok(None)` means no AAC track — an audio-less file, which import pairs
284- /// only with other audio-less files.
285- pub fn probe(path: impl AsRef<Path>) -> crate::Result<Option<AudioProbe>> {
286- let Some(track) = Track::open(path.as_ref(), 0)? else {
283+ /// The audio parameters of `path`'s `stream`, for checking an import
284+ /// against the timeline's first source: header only, no decoder and no
285+ /// worker. `Ok(None)` means no AAC track — an audio-less file, which import
286+ /// pairs only with other audio-less files. A *named* stream that is not
287+ /// there or does not decode is an `Err`, as everywhere else.
288+ pub fn probe(path: impl AsRef<Path>, stream: usize) -> crate::Result<Option<AudioProbe>> {
289+ let Some(track) = Track::open(path.as_ref(), stream)? else {
287290 return Ok(None);
288291 };
289292 Ok(Some(AudioProbe {
@@ -375,14 +378,28 @@ impl AudioSession {
375378 pub fn copy_multi_segments(
376379 sources: &[PathBuf],
377380 segs: &[(Option<usize>, f64, f64)],
381+ ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> {
382+ let sources: Vec<_> = sources.iter().map(|p| (p.clone(), 0)).collect();
383+ Self::copy_multi_streams(&sources, segs)
384+ }
385+
386+ /// [`copy_multi_segments`](Self::copy_multi_segments) with each source
387+ /// naming *which* of its audio streams to copy — the same `(path, stream)`
388+ /// list [`open_multi_streams`](Self::open_multi_streams) plays. The two
389+ /// take it in the same shape on purpose: an export that copied a different
390+ /// stream from the one the timeline played would be a file that sounds
391+ /// nothing like what was edited, and nothing would say so.
392+ pub fn copy_multi_streams(
393+ sources: &[(PathBuf, usize)],
394+ segs: &[(Option<usize>, f64, f64)],
378395 ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> {
379396 let Some(&(Some(first), ..)) = segs.iter().find(|s| s.0.is_some()) else {
380397 return Ok(None); // no segments, or nothing but silence
381398 };
382- let path = sources
399+ let (path, stream) = sources
383400 .get(first)
384401 .ok_or_else(|| format!("segment names source {first} of {}", sources.len()))?;
385- let Some(track) = Track::open(path, 0)? else {
402+ let Some(track) = Track::open(path, *stream)? else {
386403 return Ok(None); // silent source, silent export
387404 };
388405 let params = track.track_params();
@@ -471,24 +488,20 @@ fn silent_packet(chan_conf: u8) -> crate::Result<Vec<u8>> {
471488 }
472489 }
473490
474-/// The source at `index`, opened on first use. Sources a segment list never
475-/// names are never touched: a project's list only grows.
476-///
477-/// ponytail: the copy path is still stream 0 of every source — an export of a
478-/// timeline playing stream 1 would carry stream 0's audio. Upgrade path is the
479-/// `(PathBuf, usize)` list [`AudioSession::open_multi_streams`] already takes,
480-/// which is S4b's job once a stream can be picked at all.
491+/// The source at `index`, on the stream it names, opened on first use. Sources
492+/// a segment list never names are never touched: a project's list only grows.
481493 fn source_at<'a>(
482494 tracks: &'a mut [Option<Track>],
483- sources: &[PathBuf],
495+ sources: &[(PathBuf, usize)],
484496 index: usize,
485497 ) -> crate::Result<&'a mut Track> {
486498 let slot = tracks
487499 .get_mut(index)
488500 .ok_or_else(|| format!("segment names source {index} of {}", sources.len()))?;
489501 if slot.is_none() {
502+ let (path, stream) = &sources[index];
490503 *slot = Some(
491- Track::open(&sources[index], 0)?
504+ Track::open(path, *stream)?
492505 .ok_or_else(|| format!("source {index} has no audio track"))?,
493506 );
494507 }
crates/engine/src/demux.rsmodified+18 -10
@@ -141,14 +141,15 @@ fn frame_rate(track: &Mp4Track) -> f64 {
141141 /// to average 3753.75 averages instead of truncating. All of it in `f64`, which
142142 /// is the bug the caller above exists to avoid.
143143 fn fps_from_stts(entries: impl IntoIterator<Item = (u32, u32)>, timescale: u32) -> f64 {
144- let (samples, ticks) = entries
145- .into_iter()
146- .fold((0u64, 0u64), |(samples, ticks), (count, delta)| {
147- (
148- samples + u64::from(count),
149- ticks + u64::from(count) * u64::from(delta),
150- )
151- });
144+ let (samples, ticks) =
145+ entries
146+ .into_iter()
147+ .fold((0u64, 0u64), |(samples, ticks), (count, delta)| {
148+ (
149+ samples + u64::from(count),
150+ ticks + u64::from(count) * u64::from(delta),
151+ )
152+ });
152153 match ticks {
153154 // No timing in the header at all; `mp4`'s own answer for that is 0.0 too.
154155 0 => 0.0,
@@ -261,7 +262,10 @@ mod tests {
261262 );
262263 // Constant delta stays an exact division, not an average.
263264 assert_eq!(fps_from_stts([(300u32, 3000u32)], 90_000), 30.0);
264- assert_eq!(fps_from_stts([(120u32, 1001u32)], 30_000), 30_000.0 / 1001.0);
265+ assert_eq!(
266+ fps_from_stts([(120u32, 1001u32)], 30_000),
267+ 30_000.0 / 1001.0
268+ );
265269 assert_eq!(fps_from_stts([(0u32, 0u32)], 90_000), 0.0, "no timing");
266270 }
267271
@@ -277,7 +281,11 @@ mod tests {
277281 assert_eq!(first_frame_sample(entries, Some(7507 - 7507)), 1);
278282 // Two frames genuinely cut off the front.
279283 assert_eq!(first_frame_sample(entries, Some(7507)), 3);
280- assert_eq!(first_frame_sample(entries, None), 1, "no edit list, no trim");
284+ assert_eq!(
285+ first_frame_sample(entries, None),
286+ 1,
287+ "no edit list, no trim"
288+ );
281289 assert_eq!(first_frame_sample(entries, Some(0)), 1, "zero is no trim");
282290 }
283291
crates/engine/src/edith.rsmodified+126 -41
@@ -1,25 +1,33 @@
11 //! The project file: a line of text per thing, and nothing else.
22 //!
33 //! ```text
4-//! edith 2
4+//! edith 3
55 //! playhead 90
6-//! source test_av.mp4
7-//! source /elsewhere/test_av2.mp4
6+//! source 0 test_av.mp4
7+//! source 1 /elsewhere/test_av2.mp4
88 //! video 0 0 120 0 0
99 //! audio 0 0 120 0 0
1010 //! video 120 0 120 1 -
1111 //! ```
1212 //!
13+//! A source line is `source <audio stream> <path>`: which of the file's audio
14+//! tracks that source plays, in the file order
15+//! [`crate::AudioSession::probe_streams`] numbers, and then the path -- the
16+//! stream first because a path runs to the end of the line (it may hold
17+//! spaces) and an optional *trailing* field could not be told from one.
18+//!
1319 //! A lane line is `<lane> <start> <in> <out> <source> <link>`: where the clip
1420 //! sits on the timeline, the half-open source range it plays, the file it plays
1521 //! from, and its group id (`-` for none). Timeline placement is explicit, so a
1622 //! *gap* is simply a stretch no line covers -- there is nothing to write for
1723 //! one, and nothing that can disagree about its length.
1824 //!
19-//! **Version 1** wrote one lane, queued end to end: `clip <in> <out> <source>`.
20-//! Such a file still loads -- the clips are laid out cumulatively and copied
21-//! onto both lanes as one group each, which is exactly what a v1 timeline meant
22-//! -- and saving it again writes v2. A v1 reader refuses a v2 file by name.
25+//! **Version 2** wrote `source <path>`, which is this file's stream 0 -- one
26+//! per file, whichever audio track came first. **Version 1** wrote that and one
27+//! lane, queued end to end: `clip <in> <out> <source>`. Both still load -- a v1
28+//! file's clips are laid out cumulatively and copied onto both lanes as one
29+//! group each, which is exactly what a v1 timeline meant -- and saving either
30+//! again writes v3. An older reader refuses a newer file by name.
2331 //!
2432 //! Text because an edit list is a few integers and a path, and a path is
2533 //! *bytes* on this platform -- a JSON string would have to lossily decode one.
@@ -45,19 +53,21 @@ use std::io::Write;
4553 use std::os::unix::ffi::{OsStrExt, OsStringExt};
4654 use std::path::{Path, PathBuf};
4755
48-use crate::project::Clip;
56+use crate::project::{Clip, Source};
4957
5058 /// What [`save`] writes. Read support goes back to `edith 1`; see the module
51-/// docs for what that dialect looked like.
52-const MAGIC: &[u8] = b"edith 2";
59+/// docs for what those dialects looked like.
60+const MAGIC: &[u8] = b"edith 3";
61+const MAGIC_V2: &[u8] = b"edith 2";
5362 const MAGIC_V1: &[u8] = b"edith 1";
5463
5564 /// What a project file says: an edit list plus where the playhead stood.
5665 /// Structurally valid by construction -- see [`parse`].
5766 #[derive(Debug)]
5867 pub struct Document {
59- /// Absolute, relative entries already joined to the file's own directory.
60- pub sources: Vec<PathBuf>,
68+ /// Paths absolute, relative entries already joined to the file's own
69+ /// directory.
70+ pub sources: Vec<Source>,
6171 pub video: Vec<Clip>,
6272 pub audio: Vec<Clip>,
6373 pub playhead: u32,
@@ -67,7 +77,7 @@ pub struct Document {
6777 /// orphan-free ([`crate::Project::without_orphan_sources`]).
6878 pub fn save(
6979 path: &Path,
70- sources: &[PathBuf],
80+ sources: &[Source],
7181 video: &[Clip],
7282 audio: &[Clip],
7383 playhead: u32,
@@ -112,14 +122,14 @@ fn project_dir(path: &Path) -> PathBuf {
112122 dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf())
113123 }
114124
115-fn emit(dir: &Path, sources: &[PathBuf], video: &[Clip], audio: &[Clip], playhead: u32) -> Vec<u8> {
125+fn emit(dir: &Path, sources: &[Source], video: &[Clip], audio: &[Clip], playhead: u32) -> Vec<u8> {
116126 let mut out = Vec::new();
117127 out.extend_from_slice(MAGIC);
118128 out.push(b'\n');
119129 out.extend_from_slice(format!("playhead {playhead}\n").as_bytes());
120130 for s in sources {
121- out.extend_from_slice(b"source ");
122- escape(s.strip_prefix(dir).unwrap_or(s), &mut out);
131+ out.extend_from_slice(format!("source {} ", s.audio_stream).as_bytes());
132+ escape(s.path.strip_prefix(dir).unwrap_or(&s.path), &mut out);
123133 out.push(b'\n');
124134 }
125135 // Lane by lane rather than interleaved by time: a lane reads as a list, and
@@ -146,7 +156,10 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
146156 let mut lines = body.split(|&b| b == b'\n').enumerate();
147157 let (_, first) = lines.next().unwrap_or((0, &[]));
148158 let v1 = first == MAGIC_V1;
149- if first != MAGIC && !v1 {
159+ // The dialects that wrote a source line without its stream field. Reading
160+ // one is the whole of what "an old project still opens" means here.
161+ let streamless = v1 || first == MAGIC_V2;
162+ if first != MAGIC && !streamless {
150163 return Err(match first.strip_prefix(b"edith ") {
151164 Some(v) => format!("line 1: unsupported version {}", String::from_utf8_lossy(v)),
152165 None => "line 1: not a edith file".to_string(),
@@ -184,16 +197,33 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
184197 if !doc.video.is_empty() || !doc.audio.is_empty() {
185198 return Err(format!("line {n}: source after a clip").into());
186199 }
200+ // The stream comes first and the path is everything after it,
201+ // spaces and all; an older dialect wrote no stream and meant 0.
202+ let (audio_stream, rest) = if streamless {
203+ (0, rest)
204+ } else {
205+ // No space at all still has to reach `number`, so a v2 line
206+ // in a v3 file is refused as the missing field it is rather
207+ // than as a missing path.
208+ let at = rest.iter().position(|&b| b == b' ');
209+ (
210+ number(&rest[..at.unwrap_or(rest.len())], n)? as usize,
211+ &rest[at.map_or(rest.len(), |at| at + 1)..],
212+ )
213+ };
187214 if rest.is_empty() {
188215 return Err(format!("line {n}: source without a path").into());
189216 }
190217 let path = unescape(rest, n)?;
191218 // Relative means "next to the project file", which is what
192219 // makes a whole folder relocatable.
193- doc.sources.push(if path.is_absolute() {
194- path
195- } else {
196- dir.join(path)
220+ doc.sources.push(Source {
221+ path: if path.is_absolute() {
222+ path
223+ } else {
224+ dir.join(path)
225+ },
226+ audio_stream,
197227 });
198228 }
199229 // v1: one lane, no placement, no groups. Every clip becomes one
@@ -376,13 +406,17 @@ mod tests {
376406 /// Two sources, one under the project's own directory and one not, a clip
377407 /// from each on the video lane, and an audio lane with a gap in the middle
378408 /// -- the shape every case below starts from.
379- fn doc() -> (PathBuf, Vec<PathBuf>, Vec<Clip>, Vec<Clip>) {
409+ fn source(path: &str, audio_stream: usize) -> Source {
410+ Source {
411+ path: PathBuf::from(path),
412+ audio_stream,
413+ }
414+ }
415+
416+ fn doc() -> (PathBuf, Vec<Source>, Vec<Clip>, Vec<Clip>) {
380417 (
381418 PathBuf::from("/proj"),
382- vec![
383- PathBuf::from("/proj/a.mp4"),
384- PathBuf::from("/elsewhere/b.mp4"),
385- ],
419+ vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 2)],
386420 vec![clip(0, 0, 30, 0, Some(0)), clip(30, 10, 20, 1, Some(1))],
387421 vec![clip(0, 0, 30, 0, Some(0))],
388422 )
@@ -394,9 +428,10 @@ mod tests {
394428 let bytes = emit(&dir, &sources, &video, &audio, 12);
395429 assert_eq!(
396430 String::from_utf8_lossy(&bytes),
397- "edith 2\nplayhead 12\nsource a.mp4\nsource /elsewhere/b.mp4\n\
431+ "edith 3\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\
398432 video 0 0 30 0 0\nvideo 30 10 20 1 1\naudio 0 0 30 0 0\n",
399- "the file under the project directory is written relative to it"
433+ "the file under the project directory is written relative to it, \
434+ each with the audio stream it plays"
400435 );
401436 let back = parse(&bytes, &dir).expect("parse");
402437 assert_eq!(back.sources, sources, "relative entries rejoin the dir");
@@ -413,8 +448,36 @@ mod tests {
413448 );
414449 }
415450
451+ /// The other half of the compatibility promise: a v2 file names no audio
452+ /// stream and means stream 0 -- what the whole dialect could play -- and
453+ /// saving it again writes v3 saying so, with nothing else changed.
454+ #[test]
455+ fn a_v2_file_loads_as_stream_0() {
456+ let dir = PathBuf::from("/proj");
457+ let v2 = b"edith 2\nplayhead 12\nsource a.mp4\nsource /elsewhere/b.mp4\n\
458+ video 0 0 30 0 0\nvideo 30 10 20 1 1\naudio 0 0 30 0 0\n";
459+ let back = parse(v2, &dir).expect("v2 parses");
460+ assert_eq!(
461+ back.sources,
462+ vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 0)],
463+ );
464+ let (_, _, video, audio) = doc();
465+ assert_eq!((&back.video, &back.audio), (&video, &audio));
466+
467+ let v3 = emit(&dir, &back.sources, &back.video, &back.audio, back.playhead);
468+ assert_eq!(
469+ String::from_utf8_lossy(&v3),
470+ "edith 3\nplayhead 12\nsource 0 a.mp4\nsource 0 /elsewhere/b.mp4\n\
471+ video 0 0 30 0 0\nvideo 30 10 20 1 1\naudio 0 0 30 0 0\n",
472+ "a re-saved v2 project differs only by its version and the streams \
473+ it always meant"
474+ );
475+ let again = parse(&v3, &dir).expect("v3 parses");
476+ assert_eq!(again.sources, back.sources);
477+ }
478+
416479 /// The compatibility promise: a v1 file is a fully-grouped, gapless pair of
417- /// lanes, and saving it again writes v2.
480+ /// lanes, and saving it again writes v3.
418481 #[test]
419482 fn a_v1_file_loads_as_two_grouped_lanes() {
420483 let dir = PathBuf::from("/proj");
@@ -427,10 +490,10 @@ mod tests {
427490 );
428491 assert_eq!(back.audio, back.video, "one take per clip, on both lanes");
429492 assert_eq!(back.playhead, 5);
430- // Saved again it is v2, and that round-trips to the same document.
431- let v2 = emit(&dir, &back.sources, &back.video, &back.audio, back.playhead);
432- assert!(v2.starts_with(b"edith 2\n"));
433- let again = parse(&v2, &dir).expect("v2 parses");
493+ // Saved again it is v3, and that round-trips to the same document.
494+ let v3 = emit(&dir, &back.sources, &back.video, &back.audio, back.playhead);
495+ assert!(v3.starts_with(b"edith 3\n"));
496+ let again = parse(&v3, &dir).expect("v3 parses");
434497 assert_eq!((again.video, again.audio), (back.video, back.audio));
435498 // A dialect may not be mixed: lane lines under v1, `clip` under v2.
436499 for (bytes, want) in [
@@ -514,17 +577,25 @@ mod tests {
514577 let path = dir.join("link/p.edith");
515578
516579 let one = [clip(0, 0, 30, 0, None)];
517- save(&path, &[source], &one, &one, 0).expect("save");
580+ let entry = Source {
581+ path: source,
582+ audio_stream: 1,
583+ };
584+ save(&path, &[entry], &one, &one, 0).expect("save");
518585 let bytes = std::fs::read(&path).expect("read back");
519586 assert_eq!(
520587 String::from_utf8_lossy(&bytes),
521- "edith 2\nplayhead 0\nsource a.mp4\nvideo 0 0 30 0 -\naudio 0 0 30 0 -\n"
588+ "edith 3\nplayhead 0\nsource 1 a.mp4\nvideo 0 0 30 0 -\naudio 0 0 30 0 -\n"
522589 );
523590 // Loading rejoins the *given* directory, so the file is reached by the
524- // way the project was opened -- the same file, through the link.
591+ // way the project was opened -- the same file, through the link, still
592+ // playing the stream it was saved on.
525593 assert_eq!(
526594 load(&path).expect("load").sources,
527- vec![dir.join("link/a.mp4")]
595+ vec![Source {
596+ path: dir.join("link/a.mp4"),
597+ audio_stream: 1,
598+ }]
528599 );
529600 std::fs::remove_dir_all(&dir).expect("cleanup");
530601 }
@@ -533,7 +604,10 @@ mod tests {
533604 fn escapes_survive_the_bytes_json_would_not() {
534605 let dir = PathBuf::from("/proj");
535606 // A newline and a percent in a filename, plus a non-UTF-8 byte.
536- let nasty = PathBuf::from(OsString::from_vec(b"/proj/we\nird 100%\xff.mp4".to_vec()));
607+ let nasty = Source {
608+ path: PathBuf::from(OsString::from_vec(b"/proj/we\nird 100%\xff.mp4".to_vec())),
609+ audio_stream: 0,
610+ };
537611 let bytes = emit(&dir, &[nasty.clone()], &[clip(0, 0, 5, 0, None)], &[], 0);
538612 assert_eq!(
539613 bytes.iter().filter(|&&b| b == b'\n').count(),
@@ -541,16 +615,18 @@ mod tests {
541615 "the escaped newline must not become a line break"
542616 );
543617 let back = parse(&bytes, &dir).expect("parse");
618+ // The spaces in it are the reason the stream field leads rather than
619+ // trails: everything after the first one is path.
544620 assert_eq!(back.sources, vec![nasty]);
545621 }
546622
547623 #[test]
548624 fn a_wrong_first_line_is_refused_by_name() {
549625 let dir = PathBuf::from("/proj");
550- let err = parse(b"edith 3\nsource a.mp4\nvideo 0 0 5 0 -\n", &dir)
626+ let err = parse(b"edith 4\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)
551627 .unwrap_err()
552628 .to_string();
553- assert_eq!(err, "line 1: unsupported version 3");
629+ assert_eq!(err, "line 1: unsupported version 4");
554630 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {
555631 assert_eq!(
556632 parse(junk, &dir).unwrap_err().to_string(),
@@ -562,7 +638,16 @@ mod tests {
562638 #[test]
563639 fn malformed_lines_name_their_line_number() {
564640 let dir = PathBuf::from("/proj");
565- let cases: [(&[u8], &str); 8] = [
641+ let cases: [(&[u8], &str); 10] = [
642+ // v3 wants the stream before the path, and a path after it.
643+ (
644+ b"edith 3\nsource a.mp4\nvideo 0 0 5 0 -\n",
645+ "line 2: \"a.mp4\" is not a number",
646+ ),
647+ (
648+ b"edith 3\nsource 0\nvideo 0 0 5 0 -\n",
649+ "line 2: source without a path",
650+ ),
566651 (
567652 b"edith 1\nsource a.mp4\nclip 0 5\n",
568653 "line 3: clip wants 3 fields, found 2",
crates/engine/src/export.rsmodified+10 -4
@@ -159,8 +159,14 @@ fn run(
159159 // files stays in sync. A source whose AAC parameters disagree with the
160160 // first one is an `Err` from there -- import refuses those up front, this
161161 // is the backstop -- and the caller deletes the `.part`.
162- let audio =
163- AudioSession::copy_multi_segments(sources, &project.segments_from(0, meta.frame_rate))?;
162+ //
163+ // The stream each source is copied from is the one it plays: `audio_sources`
164+ // is the same list `PlaybackSession::seek` hands the decoder, so an export
165+ // of a timeline playing a file's second audio track carries *that* track.
166+ let audio = AudioSession::copy_multi_streams(
167+ &project.audio_sources(),
168+ &project.segments_from(0, meta.frame_rate),
169+ )?;
164170 let audio_params = audio.as_ref().map(|(track, _)| AudioParams {
165171 freq_index: track.freq_index,
166172 chan_conf: track.chan_conf,
@@ -180,10 +186,10 @@ fn run(
180186 // file boundaries, which are just cuts that change the path.
181187 let mut pictures = match span.from {
182188 Some((source, in_frame)) => {
183- let path = sources
189+ let entry = sources
184190 .get(source)
185191 .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?;
186- Some(ClipDecoder::open(path, in_frame)?)
192+ Some(ClipDecoder::open(&entry.path, in_frame)?)
187193 }
188194 None => None,
189195 };
crates/engine/src/mux.rsmodified+5 -2
@@ -186,7 +186,8 @@ impl Mp4Muxer {
186186 /// export, which is this bug's own truncation reborn at the writing end.
187187 pub(crate) fn frame_timing(fps: f64) -> crate::Result<(u32, u32)> {
188188 let ticks = f64::from(VIDEO_TIMESCALE) / fps;
189- if (ticks - ticks.round()).abs() < 1e-9 && (1.0..=f64::from(u32::MAX)).contains(&ticks.round()) {
189+ if (ticks - ticks.round()).abs() < 1e-9 && (1.0..=f64::from(u32::MAX)).contains(&ticks.round())
190+ {
190191 return Ok((VIDEO_TIMESCALE, ticks.round() as u32));
191192 }
192193 let timescale = (fps * f64::from(NTSC_TICKS)).round();
@@ -503,7 +504,9 @@ mod tests {
503504 None,
504505 )
505506 .unwrap();
506- muxer.write_video_au(&au(&[SPS, PPS, &[0x65, 0x01]])).unwrap();
507+ muxer
508+ .write_video_au(&au(&[SPS, PPS, &[0x65, 0x01]]))
509+ .unwrap();
507510 muxer.write_video_au(&au(&[&[0x41, 0x02]])).unwrap();
508511 muxer.finish().unwrap();
509512
crates/engine/src/playback.rsmodified+102 -35
@@ -11,7 +11,7 @@
1111 //! Drift policy stays with the caller -- this type answers "what time is it",
1212 //! the renderer decides which frame that means.
1313
14-use std::path::{Path, PathBuf};
14+use std::path::Path;
1515 use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
1616 use std::sync::mpsc::{Receiver, TryRecvError};
1717 use std::sync::{Arc, Mutex};
@@ -23,7 +23,7 @@ use crate::audio::{AudioChunk, AudioSession};
2323 use crate::clock::{ClockSource, PlaybackClock};
2424 use crate::decode::{DecodeSession, Frame, Worker};
2525 use crate::demux::{Demuxer, VideoMeta};
26-use crate::project::{Clip, Lane, Project, Span};
26+use crate::project::{Clip, Lane, Project, Source, Span};
2727
2828 /// How long the feeder waits out a full ring. The ring holds a second, so this
2929 /// only has to be short next to that; it costs one wakeup per 10 ms of audio.
@@ -128,7 +128,9 @@ impl PlaybackSession {
128128 // `open_worker` rather than `open` purely for the worker handle: the
129129 // field has to exist from the start for the first seek to use it.
130130 let (meta, stream) = DecodeSession::open_worker(&path, 0, u32::MAX)?;
131- let (audio, audio_disabled) = open_audio(&path);
131+ // A file is opened on its first audio stream, like `Project::single`
132+ // names it: nothing has picked one yet.
133+ let (audio, audio_disabled) = open_audio(&path, 0);
132134 let source = match audio {
133135 Some(_) => ClockSource::Audio,
134136 None => ClockSource::Wall,
@@ -181,16 +183,16 @@ impl PlaybackSession {
181183 // locals drop in reverse declaration order -- a bare worker would join
182184 // its decode thread while the receiver next to it was still holding
183185 // that thread parked in `send`, which is a hang (see [`FrameStream`]).
184- let (meta, stream) = DecodeSession::open_worker(&first, 0, u32::MAX)
185- .map_err(|e| format!("source {}: {e}", first.display()))?;
186- let first_audio = AudioSession::probe(&first)?;
186+ let (meta, stream) = DecodeSession::open_worker(&first.path, 0, u32::MAX)
187+ .map_err(|e| format!("source {}: {e}", first.path.display()))?;
188+ let first_audio = AudioSession::probe(&first.path, first.audio_stream)?;
187189
188190 let mut counts = vec![meta.frame_count];
189191 for source in &doc.sources[1..] {
190- let (other, _) =
191- Demuxer::open(source).map_err(|e| format!("source {}: {e}", source.display()))?;
192+ let (other, _) = Demuxer::open(&source.path)
193+ .map_err(|e| format!("source {}: {e}", source.path.display()))?;
192194 matches_timeline(source, &other, &meta, &first_audio)
193- .map_err(|e| format!("source {}: {e}", source.display()))?;
195+ .map_err(|e| format!("source {}: {e}", source.path.display()))?;
194196 counts.push(other.frame_count);
195197 }
196198 for (i, clip) in doc.video.iter().chain(&doc.audio).enumerate() {
@@ -198,7 +200,7 @@ impl PlaybackSession {
198200 return Err(format!(
199201 "clip {i} ends at frame {} but {} has {} frames",
200202 clip.out_frame,
201- doc.sources[clip.source].display(),
203+ doc.sources[clip.source].path.display(),
202204 counts[clip.source]
203205 )
204206 .into());
@@ -213,7 +215,7 @@ impl PlaybackSession {
213215 // only a session's `drop` retires it, so a refusal above this line would
214216 // leave a PipeWire stream and a thread behind for a project that never
215217 // opened. Nothing before it needs the device.
216- let (audio, audio_disabled) = open_audio(&first);
218+ let (audio, audio_disabled) = open_audio(&first.path, first.audio_stream);
217219 let mut session = Self {
218220 meta,
219221 frames: stream.frames,
@@ -252,7 +254,7 @@ impl PlaybackSession {
252254
253255 /// The files this timeline plays from, index 0 first -- a caller needs it
254256 /// to name an export or a window after the media rather than the project.
255- pub fn sources(&self) -> &[PathBuf] {
257+ pub fn sources(&self) -> &[Source] {
256258 self.project.sources()
257259 }
258260
@@ -344,7 +346,7 @@ impl PlaybackSession {
344346 fn start_span(&mut self, span: Span) {
345347 let opened = match span.from {
346348 Some((source, in_frame)) => DecodeSession::open_worker(
347- &self.project.sources()[source],
349+ &self.project.sources()[source].path,
348350 in_frame,
349351 in_frame + span.len,
350352 )
@@ -455,6 +457,56 @@ impl PlaybackSession {
455457 self.edit(|p| p.paste(at, clip))
456458 }
457459
460+ /// Places `frames` of `path` played on its audio `stream` at
461+ /// `timeline_secs`, the way [`paste_at`](Self::paste_at) places a copy --
462+ /// the door a library row goes through, and the only way a stream other
463+ /// than the one an import brought in reaches the timeline. The `(file,
464+ /// stream)` pair becomes a source if it is not one already.
465+ ///
466+ /// Refused, changing nothing, unless that stream can join *this* timeline:
467+ /// same audio parameters as the first source, in the same words
468+ /// [`import`](Self::import) refuses a file with. One output device and one
469+ /// copied AAC track mean one set of audio parameters for the whole
470+ /// timeline, so a 22 kHz mono track cannot join a 44.1 kHz stereo one --
471+ /// there is no resampler here, and no AAC encoder to write the join with.
472+ /// A front-end greys such a row out; this is the backstop that keeps a
473+ /// stale one from making the whole timeline silent.
474+ pub fn place_stream_at(
475+ &mut self,
476+ timeline_secs: f64,
477+ path: &Path,
478+ stream: usize,
479+ frames: u32,
480+ ) -> crate::Result<bool> {
481+ let wanted = Source::new(path, stream);
482+ // Another stream of a file whose picture is *already* on the timeline:
483+ // that is what a library row is, and it is why nothing here has to
484+ // check dimensions or frame rate -- the file passed that at import.
485+ if !self.project.sources().iter().any(|s| s.path == wanted.path) {
486+ return Err(format!("{} is not on this timeline", path.display()).into());
487+ }
488+ let first = self.first_audio()?;
489+ audio_matches(&wanted, &first)?;
490+ let source = self.project.import(path, stream);
491+ Ok(self.paste_at(
492+ timeline_secs,
493+ Clip {
494+ start: 0,
495+ in_frame: 0,
496+ out_frame: frames.max(1),
497+ source,
498+ link: None,
499+ },
500+ ))
501+ }
502+
503+ /// What the timeline's audio *is*: source 0's chosen stream, probed. Every
504+ /// other source is held to it.
505+ fn first_audio(&self) -> crate::Result<Option<crate::AudioProbe>> {
506+ let first = &self.project.sources()[0];
507+ AudioSession::probe(&first.path, first.audio_stream)
508+ }
509+
458510 /// Removes the video clip at `idx` and everything under it, closing the gap
459511 /// on every lane. Unlike a split this *does* move every following frame, so
460512 /// the session reseeks to wherever the playhead now points.
@@ -479,11 +531,14 @@ impl PlaybackSession {
479531 /// a refusal.
480532 pub fn import(&mut self, path: &Path) -> crate::Result<()> {
481533 let (meta, _) = Demuxer::open(path)?;
482- let first = AudioSession::probe(&self.project.sources()[0])?;
483- matches_timeline(path, &meta, &self.meta, &first)?;
534+ let first = self.first_audio()?;
535+ // Stream 0: an import brings a file in on its first audio track, and
536+ // [`place_stream_at`](Self::place_stream_at) is how any other one of
537+ // its streams reaches the timeline afterwards.
538+ matches_timeline(&Source::new(path, 0), &meta, &self.meta, &first)?;
484539
485540 let old_end = self.timeline_duration();
486- let source = self.project.import(path);
541+ let source = self.project.import(path, 0);
487542 // Refused only for an unknown index, and this one just came from `import`.
488543 self.project.append_clip(source, meta.frame_count);
489544 // Reseek like any other edit, even though nothing before the playhead
@@ -619,7 +674,10 @@ impl PlaybackSession {
619674 // ear never hears it -- and a join between two *files* is just
620675 // another segment, because every segment names its own source.
621676 let segs = self.project.segments_from(target, fps);
622- audio_running = match AudioSession::open_multi_segments(self.project.sources(), &segs) {
677+ // Each source on the stream it was placed with: what plays is what
678+ // the library row said, and what an export copies (`export::run`).
679+ let sources = self.project.audio_sources();
680+ audio_running = match AudioSession::open_multi_streams(&sources, &segs) {
623681 Ok(Some((_, rx))) => audio.spawn_feeder(rx),
624682 _ => false,
625683 };
@@ -726,7 +784,7 @@ impl Drop for PlaybackSession {
726784 /// [`PlaybackSession::open_project`] share them so a file refused at import is
727785 /// refused in the same words at load.
728786 fn matches_timeline(
729- path: &Path,
787+ source: &Source,
730788 meta: &VideoMeta,
731789 timeline: &VideoMeta,
732790 first: &Option<crate::AudioProbe>,
@@ -746,9 +804,16 @@ fn matches_timeline(
746804 )
747805 .into());
748806 }
807+ audio_matches(source, first)
808+}
809+
810+/// The audio half of [`matches_timeline`], which a stream placed on its own
811+/// ([`PlaybackSession::place_stream_at`]) has to pass while the picture it
812+/// comes with is already on the timeline.
813+fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::Result<()> {
749814 // Whole-probe equality: rate, layout and the esds fields, which the audio
750815 // worker holds every source to anyway. Both silent is a match.
751- let probe = AudioSession::probe(path)?;
816+ let probe = AudioSession::probe(&source.path, source.audio_stream)?;
752817 if probe != *first {
753818 return Err(match (probe, first) {
754819 (None, _) => "the file is silent, the timeline has audio".to_string(),
@@ -771,23 +836,25 @@ fn matches_timeline(
771836 /// a surprise worth showing (see
772837 /// [`audio_disabled_reason`](PlaybackSession::audio_disabled_reason)), where a
773838 /// file with no audio at all and a machine with no output device are not.
774-fn open_audio(path: &Path) -> (Option<Audio>, Option<String>) {
775- let (meta, rx) = match AudioSession::open(path) {
776- Ok(Some(opened)) => opened,
777- // No AAC track: silent by nature, or sound in a codec we do not have --
778- // and only the second of those is worth a word.
779- Ok(None) => {
780- let reason = AudioSession::unsupported(path).ok().flatten();
781- if let Some(reason) = &reason {
782- eprintln!("audio disabled: {reason}");
839+fn open_audio(path: &Path, stream: usize) -> (Option<Audio>, Option<String>) {
840+ let sources = [(path.to_path_buf(), stream)];
841+ let (meta, rx) =
842+ match AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)]) {
843+ Ok(Some(opened)) => opened,
844+ // No AAC track: silent by nature, or sound in a codec we do not
845+ // have -- and only the second of those is worth a word.
846+ Ok(None) => {
847+ let reason = AudioSession::unsupported(path).ok().flatten();
848+ if let Some(reason) = &reason {
849+ eprintln!("audio disabled: {reason}");
850+ }
851+ return (None, reason);
783852 }
784- return (None, reason);
785- }
786- Err(e) => {
787- eprintln!("audio disabled: {e}");
788- return (None, Some(e.to_string()));
789- }
790- };
853+ Err(e) => {
854+ eprintln!("audio disabled: {e}");
855+ return (None, Some(e.to_string()));
856+ }
857+ };
791858 let Some(ao) = AoSession::open(meta.sample_rate, u32::from(meta.channels)) else {
792859 return (None, None); // no device: the machine's business, not the file's
793860 };
crates/engine/src/project.rsmodified+92 -24
@@ -71,6 +71,31 @@ impl Clip {
7171 }
7272 }
7373
74+/// A file the timeline plays from, and *which* of its audio streams it plays:
75+/// a file carrying one track per language is several sources, one per stream,
76+/// sharing a path. Two entries differing only in the stream are two sources --
77+/// they are what a clip names, and a clip plays exactly one stream.
78+///
79+/// The path is always canonical ([`Source::new`]), so the same file reached by
80+/// two paths is one source.
81+#[derive(Clone, Debug, PartialEq, Eq)]
82+pub struct Source {
83+ pub path: PathBuf,
84+ /// Position among the file's audio tracks in file order, the numbering
85+ /// [`crate::AudioSession::probe_streams`] hands out. `0` for a file with a
86+ /// single track, and for a silent one.
87+ pub audio_stream: usize,
88+}
89+
90+impl Source {
91+ pub fn new(path: impl AsRef<Path>, audio_stream: usize) -> Self {
92+ Self {
93+ path: canonical(path.as_ref()),
94+ audio_stream,
95+ }
96+ }
97+}
98+
7499 /// Which lane an operation acts on. The lanes are peers: no operation reads one
75100 /// to decide what to do to the other, except the grouped ones that say so.
76101 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
@@ -112,7 +137,7 @@ impl Span {
112137 #[derive(Clone, Debug)]
113138 pub struct Project {
114139 /// Append-only: never popped, never reordered. See the module docs.
115- sources: Vec<PathBuf>,
140+ sources: Vec<Source>,
116141 /// Indexed by [`Lane::index`]. Each lane is sorted by `start` and disjoint.
117142 lanes: [Vec<Clip>; 2],
118143 /// Snapshots pushed *before* each successful edit; `undo` pops one.
@@ -136,7 +161,9 @@ impl Project {
136161 link: Some(0),
137162 };
138163 Self {
139- sources: vec![canonical(path.as_ref())],
164+ // A file is opened on its first audio stream: nothing has picked
165+ // one yet, and every file with audio at all has that one.
166+ sources: vec![Source::new(path, 0)],
140167 lanes: [vec![clip], vec![clip]],
141168 history: Vec::new(),
142169 next_link: 1,
@@ -152,7 +179,7 @@ impl Project {
152179 /// whose end overflows, a lane that is unsorted or self-overlapping, and
153180 /// the grouping rules of [`Clip::link`] below.
154181 pub fn from_parts(
155- sources: Vec<PathBuf>,
182+ sources: Vec<Source>,
156183 video: Vec<Clip>,
157184 audio: Vec<Clip>,
158185 ) -> crate::Result<Self> {
@@ -200,7 +227,10 @@ impl Project {
200227 // ceiling ids stop being fresh, which loses grouping, not memory.
201228 .map_or(0, |m| m.saturating_add(1));
202229 Ok(Self {
203- sources: sources.iter().map(|s| canonical(s)).collect(),
230+ sources: sources
231+ .iter()
232+ .map(|s| Source::new(&s.path, s.audio_stream))
233+ .collect(),
204234 lanes,
205235 history: Vec::new(),
206236 next_link,
@@ -219,20 +249,32 @@ impl Project {
219249
220250 /// The files the clips index into, in import order; index 0 is the file the
221251 /// project was opened with.
222- pub fn sources(&self) -> &[PathBuf] {
252+ pub fn sources(&self) -> &[Source] {
223253 &self.sources
224254 }
225255
226- /// Index for `path`, appending it if it is new. Deduped by
227- /// `fs::canonicalize`, so the same file reached by two paths imports once.
256+ /// The same list in the `(path, stream)` shape the audio engine indexes
257+ /// into -- [`crate::AudioSession::open_multi_streams`] and
258+ /// [`crate::AudioSession::copy_multi_streams`] take it, so the stream a clip
259+ /// was placed with is the stream that plays *and* the stream that exports.
260+ pub fn audio_sources(&self) -> Vec<(PathBuf, usize)> {
261+ self.sources
262+ .iter()
263+ .map(|s| (s.path.clone(), s.audio_stream))
264+ .collect()
265+ }
266+
267+ /// Index for `path` played on `audio_stream`, appending it if it is new.
268+ /// Deduped by `fs::canonicalize` *and* by stream, so the same file reached
269+ /// by two paths imports once and two streams of one file are two sources.
228270 /// The lanes are untouched -- see [`Project::append_clip`] -- so this pushes
229271 /// no history: a source entry alone changes nothing playable.
230- pub fn import(&mut self, path: impl AsRef<Path>) -> usize {
231- let path = canonical(path.as_ref());
232- match self.sources.iter().position(|s| *s == path) {
272+ pub fn import(&mut self, path: impl AsRef<Path>, audio_stream: usize) -> usize {
273+ let source = Source::new(path, audio_stream);
274+ match self.sources.iter().position(|s| *s == source) {
233275 Some(idx) => idx,
234276 None => {
235- self.sources.push(path);
277+ self.sources.push(source);
236278 self.sources.len() - 1
237279 }
238280 }
@@ -268,7 +310,7 @@ impl Project {
268310 /// nothing plays refuse a future load. New indexes are assigned in order of
269311 /// first use -- video lane first, then audio -- so the same project always
270312 /// emits the same bytes.
271- pub fn without_orphan_sources(&self) -> (Vec<PathBuf>, Vec<Clip>, Vec<Clip>) {
313+ pub fn without_orphan_sources(&self) -> (Vec<Source>, Vec<Clip>, Vec<Clip>) {
272314 let mut moved = vec![None; self.sources.len()];
273315 let mut sources = Vec::new();
274316 let mut lanes = self.lanes.clone();
@@ -1252,7 +1294,7 @@ mod tests {
12521294 /// of source 0 then [0,4) of source 1.
12531295 fn two_sources() -> Project {
12541296 let mut p = three();
1255- let s = p.import(FILE2);
1297+ let s = p.import(FILE2, 0);
12561298 assert_eq!(s, 1);
12571299 assert!(p.append_clip(s, 4));
12581300 p
@@ -1262,11 +1304,18 @@ mod tests {
12621304 fn import_dedups_and_appends() {
12631305 let mut p = Project::single(FILE, 9);
12641306 assert_eq!(p.sources().len(), 1, "the opened file is source 0");
1265- assert_eq!(p.import(FILE), 0, "reimporting the open file reuses 0");
1266- assert_eq!(p.import(FILE2), 1);
1267- assert_eq!(p.import(FILE2), 1, "second import of the same path");
1268- assert_eq!(p.sources().len(), 2);
1269- assert!(!p.append_clip(2, 5), "unknown source index");
1307+ assert_eq!(p.import(FILE, 0), 0, "reimporting the open file reuses 0");
1308+ assert_eq!(p.import(FILE2, 0), 1);
1309+ assert_eq!(p.import(FILE2, 0), 1, "second import of the same path");
1310+ // ...but the same file on another audio stream is another source: it is
1311+ // what a clip names, and a clip plays exactly one stream.
1312+ assert_eq!(p.import(FILE2, 1), 2, "a second stream is a second source");
1313+ assert_eq!(p.import(FILE2, 1), 2, "and dedups on the pair");
1314+ assert_eq!(p.sources()[2].audio_stream, 1);
1315+ assert!(p.append_clip(2, 4), "a stream entry is placeable");
1316+ assert!(p.undo());
1317+ assert_eq!(p.sources().len(), 3);
1318+ assert!(!p.append_clip(3, 5), "unknown source index");
12701319 assert_eq!(p.clips().len(), 1, "a refusal changes nothing");
12711320
12721321 // Two spellings of one real file are one source: this is the case the
@@ -1274,7 +1323,7 @@ mod tests {
12741323 let here = concat!(env!("CARGO_MANIFEST_DIR"), "/src/project.rs");
12751324 let detour = concat!(env!("CARGO_MANIFEST_DIR"), "/src/../src/project.rs");
12761325 let mut p = Project::single(here, 9);
1277- assert_eq!(p.import(detour), 0);
1326+ assert_eq!(p.import(detour, 0), 0);
12781327 assert_eq!(p.sources().len(), 1);
12791328 }
12801329
@@ -1362,20 +1411,20 @@ mod tests {
13621411 let mut p = two_sources();
13631412 assert!(p.undo());
13641413 let (sources, video, audio) = p.without_orphan_sources();
1365- assert_eq!(sources, vec![PathBuf::from(FILE)], "the orphan is gone");
1414+ assert_eq!(sources, vec![Source::new(FILE, 0)], "the orphan is gone");
13661415 assert_eq!(video, three().clips(), "the clips are untouched");
13671416 assert_eq!(audio, three().lane(Lane::Audio));
13681417
13691418 // Three sources where only the middle one is orphaned: the survivors
13701419 // renumber, and the clips follow.
13711420 let mut p = Project::single(FILE, 9);
1372- assert_eq!(p.import(FILE2), 1);
1373- assert_eq!(p.import("/nonexistent/c.mp4"), 2);
1421+ assert_eq!(p.import(FILE2, 0), 1);
1422+ assert_eq!(p.import("/nonexistent/c.mp4", 0), 2);
13741423 assert!(p.append_clip(2, 4));
13751424 let (sources, video, audio) = p.without_orphan_sources();
13761425 assert_eq!(
13771426 sources,
1378- vec![PathBuf::from(FILE), PathBuf::from("/nonexistent/c.mp4")]
1427+ vec![Source::new(FILE, 0), Source::new("/nonexistent/c.mp4", 0)]
13791428 );
13801429 assert_eq!(video.iter().map(|c| c.source).collect::<Vec<_>>(), [0, 1]);
13811430 // ...and what comes out is loadable, with the same timeline.
@@ -1423,7 +1472,7 @@ mod tests {
14231472 /// because what an edit produces is what a save writes and a load reads.
14241473 #[test]
14251474 fn a_link_id_is_never_two_clips_of_one_lane() {
1426- let sources = vec![PathBuf::from(FILE)];
1475+ let sources = vec![Source::new(FILE, 0)];
14271476 let linked = |start, in_frame, out_frame, link| Clip {
14281477 start,
14291478 in_frame,
@@ -1509,6 +1558,25 @@ mod tests {
15091558 assert!(p.regroup(30), "only the audio lane can rejoin");
15101559 assert!(p.split(60));
15111560 reloads(&p, "lift, regroup one lane, split");
1561+
1562+ // Two audio streams of one file, both placed: two source entries with
1563+ // one path between them, which is the state a stream picked out of the
1564+ // library reaches -- and the state a save has to write and read back.
1565+ let mut p = Project::single(FILE, 150);
1566+ let second = p.import(FILE, 1);
1567+ assert_eq!(second, 1, "the same file on another stream is a new source");
1568+ assert!(p.append_clip(second, 150));
1569+ assert!(p.split(200));
1570+ reloads(
1571+ &p,
1572+ "a second audio stream of the same file, placed and split",
1573+ );
1574+ let (sources, ..) = p.without_orphan_sources();
1575+ assert_eq!(
1576+ sources.iter().map(|s| s.audio_stream).collect::<Vec<_>>(),
1577+ [0, 1],
1578+ "both entries survive the orphan prune: both are played"
1579+ );
15121580 }
15131581
15141582 /// The same claim, swept: random op sequences off the public surface, the
crates/engine/src/waveform.rsmodified+33 -7
@@ -6,21 +6,28 @@ use std::path::Path;
66
77 use crate::AudioSession;
88
9-/// `(min, max)` of every sample in each `1 / buckets_per_sec` window of `path`'s
10-/// audio, from media time 0 (priming already trimmed by the decoder). Channels
11-/// are folded together: one envelope per clip, not per channel.
9+/// `(min, max)` of every sample in each `1 / buckets_per_sec` window of
10+/// `stream` of `path`'s audio, from media time 0 (priming already trimmed by
11+/// the decoder). Channels are folded together: one envelope per clip, not per
12+/// channel.
1213 ///
1314 /// `Ok(None)` for a file with no audio track — a silent source is valid, not a
1415 /// failure. Values are clamped to `[-1.0, 1.0]`, and a bucket's pair always
1516 /// straddles zero, so silence draws as a flat line.
1617 ///
1718 /// Decoding the whole file runs at ~1700x realtime, but it is still linear in
18-/// source length: callers cache the result per source, never per repaint.
19+/// source length: callers cache the result per source *and stream* — two
20+/// streams of one file are two different envelopes, and a cache keyed on the
21+/// path alone would draw the first one under both.
1922 pub fn peaks(
2023 path: impl AsRef<Path>,
24+ stream: usize,
2125 buckets_per_sec: u32,
2226 ) -> crate::Result<Option<Vec<(f32, f32)>>> {
23- let Some((meta, rx)) = AudioSession::open(path)? else {
27+ let sources = [(path.as_ref().to_path_buf(), stream)];
28+ let Some((meta, rx)) =
29+ AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)])?
30+ else {
2431 return Ok(None);
2532 };
2633 // Kept fractional: 44100 / 30 is not whole, and rounding it would drift a
@@ -62,7 +69,7 @@ mod tests {
6269
6370 #[test]
6471 fn peaks_follow_the_1hz_volume_pulse() {
65- let peaks = peaks(asset("test_av.mp4"), BPS)
72+ let peaks = peaks(asset("test_av.mp4"), 0, BPS)
6673 .expect("open")
6774 .expect("test_av.mp4 has an audio track");
6875 // 5 s of source; the container's tail padding may spill one bucket.
@@ -112,9 +119,28 @@ mod tests {
112119 #[test]
113120 fn video_only_source_has_no_peaks() {
114121 assert!(
115- peaks(asset("test_baseline.mp4"), BPS)
122+ peaks(asset("test_baseline.mp4"), 0, BPS)
116123 .expect("open")
117124 .is_none()
118125 );
119126 }
127+
128+ /// Two streams of one file are two envelopes: the lane draws what the clip
129+ /// actually plays, so a cache keyed on the path alone would be a lie the
130+ /// user can see. Stream 1 of the fixture is 2 s of 220 Hz mono against
131+ /// stream 0's 4-second-long pulsed stereo pair.
132+ #[test]
133+ fn each_stream_of_a_file_has_its_own_envelope() {
134+ let multi = asset("test_multiaudio.mp4");
135+ let zero = peaks(&multi, 0, BPS).expect("open").expect("stream 0");
136+ let one = peaks(&multi, 1, BPS).expect("open").expect("stream 1");
137+ assert!(!zero.is_empty() && !one.is_empty());
138+ // Bucket for bucket, not merely somewhere: a cache keyed on the path
139+ // alone would hand the lane the *first* stream's shape for both, and
140+ // that is what this refuses.
141+ assert_ne!(zero, one, "both streams drew the same envelope");
142+ assert_ne!(zero[0], one[0], "...and they differ from the first bucket");
143+ // A stream that does not decode is refused, not drawn as silence.
144+ assert!(peaks(&multi, 2, BPS).is_err(), "AC-3 has no envelope");
145+ }
120146 }
crates/engine/tests/audio_multi.rsmodified+5 -3
@@ -189,19 +189,21 @@ fn each_source_ends_where_its_own_track_does() {
189189
190190 #[test]
191191 fn probe_reads_the_import_policy_fields() {
192- let av = AudioSession::probe(asset("test_av.mp4"))
192+ let av = AudioSession::probe(asset("test_av.mp4"), 0)
193193 .expect("probe")
194194 .expect("test_av.mp4 has audio");
195195 assert_eq!(av.channels, 2);
196196 assert_eq!(av.params.sample_rate, RATE as u32);
197197 assert_eq!(
198- AudioSession::probe(asset("test_av2.mp4")).unwrap().unwrap(),
198+ AudioSession::probe(asset("test_av2.mp4"), 0)
199+ .unwrap()
200+ .unwrap(),
199201 av,
200202 "the fixtures are the matching pair import must accept"
201203 );
202204 for silent in ["test_baseline.mp4", "test_mismatch.mp4"] {
203205 assert!(
204- AudioSession::probe(asset(silent)).unwrap().is_none(),
206+ AudioSession::probe(asset(silent), 0).unwrap().is_none(),
205207 "{silent} has no audio track"
206208 );
207209 }
crates/engine/tests/export.rsmodified+83 -2
@@ -23,6 +23,7 @@ use engine::export::ExportSettings;
2323 use engine::hw::HwEncoder;
2424 use engine::mux::{Mp4Muxer, VideoParams, parameter_sets};
2525 use engine::project::Lane;
26+use engine::project::Source;
2627 use engine::{DecodeSession, ExportHandle, PlaybackSession, Project};
2728
2829 const FPS: f64 = 30.0;
@@ -174,6 +175,86 @@ fn exports_an_edited_timeline_in_hardware() {
174175 round_trip("hw", Duration::from_secs(60));
175176 }
176177
178+/// The trap this slice exists to close: a timeline playing a file's *second*
179+/// audio stream must export that stream's packets. Playing one stream and
180+/// exporting another is a file that sounds nothing like what was edited, and
181+/// nothing in it would say so -- so the check is the copied bytes, not just the
182+/// header. Software only: the picture is beside the point here.
183+#[test]
184+fn exports_the_audio_stream_the_timeline_plays() {
185+ pin_software();
186+ let multi = asset("test_multiaudio.mp4");
187+ let (meta, _) = engine::demux::Demuxer::open(&multi).expect("open the fixture");
188+ let whole = engine::Clip {
189+ start: 0,
190+ in_frame: 0,
191+ out_frame: meta.frame_count,
192+ source: 0,
193+ link: Some(0),
194+ };
195+ // Stream 1 is the 22.05 kHz mono French track; stream 0 is 44.1 kHz
196+ // stereo. A project may only hold streams that agree, so this timeline is
197+ // stream 1 alone -- which is exactly what an export must carry.
198+ let project = Project::from_parts(
199+ vec![Source {
200+ path: multi.clone(),
201+ audio_stream: 1,
202+ }],
203+ vec![whole],
204+ vec![whole],
205+ )
206+ .expect("a one-source project on stream 1");
207+ let out = out_path("stream1");
208+ let handle = engine::export::start(project, meta, &out, &ExportSettings::default());
209+ wait(&handle, Duration::from_secs(120)).expect("export");
210+
211+ let (audio, _) = engine::AudioSession::open(&out)
212+ .expect("reopen export audio")
213+ .expect("the export has audio");
214+ assert_eq!(
215+ (audio.sample_rate, audio.channels),
216+ (22_050, 1),
217+ "the export carries stream 0's parameters, not the stream that played"
218+ );
219+
220+ // Byte for byte: the exported track is the copy of stream 1, and it is not
221+ // the copy of stream 0 -- the second assert is what makes the first one
222+ // mean something.
223+ let segs = [(Some(0), 0.0, f64::from(meta.frame_count) / FPS)];
224+ let copy = |stream| {
225+ engine::AudioSession::copy_multi_streams(&[(multi.clone(), stream)], &segs)
226+ .expect("copy")
227+ .expect("has audio")
228+ .1
229+ .into_iter()
230+ .map(|p| p.bytes)
231+ .collect::<Vec<_>>()
232+ };
233+ let (one, zero) = (copy(1), copy(0));
234+ assert_ne!(one, zero, "the two streams are not the same bytes");
235+
236+ let file = File::open(&out).unwrap();
237+ let size = file.metadata().unwrap().len();
238+ let mut reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap();
239+ let track = *reader
240+ .tracks()
241+ .keys()
242+ .find(|id| reader.sample_count(**id).unwrap_or(0) as usize == one.len())
243+ .unwrap_or(&2);
244+ let written: Vec<Vec<u8>> = (1..=reader.sample_count(track).expect("audio track"))
245+ .map(|id| {
246+ reader
247+ .read_sample(track, id)
248+ .expect("sample")
249+ .expect("present")
250+ .bytes
251+ .to_vec()
252+ })
253+ .collect();
254+ assert_eq!(written, one, "the exported packets are stream 1's");
255+ std::fs::remove_file(&out).unwrap();
256+}
257+
177258 /// `test_av[0,120)` then the whole of `test_av2`: the last second of the first
178259 /// source is deleted, so timeline frame 120 is both a cut and a file change --
179260 /// the join the multi-source export exists for.
@@ -183,7 +264,7 @@ fn two_sources() -> Project {
183264 assert_eq!((av.width, av.height), (av2.width, av2.height), "policy a");
184265
185266 let mut project = Project::single(asset("test_av.mp4"), av.frame_count);
186- let second = project.import(asset("test_av2.mp4"));
267+ let second = project.import(asset("test_av2.mp4"), 0);
187268 assert_eq!(second, 1, "a second file is a second source");
188269 assert!(project.append_clip(second, av2.frame_count));
189270 assert!(project.split(120), "cut a second before the end of test_av");
@@ -323,7 +404,7 @@ fn a_vanished_source_fails_the_export() {
323404 let mut project = Project::single(&baseline, meta.frame_count);
324405 assert!(project.split(5));
325406 assert!(project.delete(1));
326- let second = project.import(&doomed);
407+ let second = project.import(&doomed, 0);
327408 assert!(project.append_clip(second, meta.frame_count));
328409 assert!(project.split(10));
329410 assert!(project.delete(2));
crates/engine/tests/playback.rsmodified+1 -1
@@ -879,7 +879,7 @@ fn undo_after_import_is_one_step() {
879879 // exposes sources through `clip_spans_by_source`, and the undone clip is
880880 // exactly the one that named it.
881881 let mut project = engine::Project::single(asset("test_av.mp4"), 150);
882- let source = project.import(&av2);
882+ let source = project.import(&av2, 0);
883883 assert!(project.append_clip(source, 120));
884884 assert!(project.undo());
885885 assert_eq!(project.clips().len(), 1);
crates/engine/tests/saveload.rsmodified+99 -7
@@ -10,6 +10,7 @@
1010 use std::path::{Path, PathBuf};
1111
1212 use engine::PlaybackSession;
13+use engine::project::Source;
1314
1415 fn asset(name: &str) -> PathBuf {
1516 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
@@ -32,6 +33,73 @@ fn copy_in(dir: &Path, name: &str) -> PathBuf {
3233 to
3334 }
3435
36+/// The whole of what a picked audio stream has to survive: a file's second
37+/// language goes on the timeline beside its first, the project says so on
38+/// disk, and reopening it plays the same two streams. This is the file-level
39+/// half of what a library row does -- `place_stream_at` is the one door that
40+/// row goes through.
41+#[test]
42+fn a_picked_audio_stream_lands_saves_and_comes_back() {
43+ let dir = scratch("streams");
44+ let media = copy_in(&dir, "test_multilang.mp4");
45+ let mut session = PlaybackSession::open(&media).expect("open the fixture");
46+ session.set_gain(0.0); // silent like the rest of the suites
47+ let frames = session.clip_at(0).expect("one clip").out_frame;
48+ let end = session.timeline_duration();
49+
50+ // Stream 1 is the French track, same rate and layout as stream 0, so it
51+ // can join this timeline; it lands as a second source of the same file.
52+ assert!(
53+ session
54+ .place_stream_at(end, &media, 1, frames)
55+ .expect("stream 1 matches the timeline")
56+ );
57+ assert_eq!(
58+ session
59+ .sources()
60+ .iter()
61+ .map(|s| s.audio_stream)
62+ .collect::<Vec<_>>(),
63+ [0, 1],
64+ "the same file twice, on two streams"
65+ );
66+ assert_eq!(session.timeline_duration(), end * 2.0);
67+
68+ let path = dir.join("langs.edith");
69+ session.save_project(&path).expect("save");
70+ let text = std::fs::read_to_string(&path).expect("read back");
71+ assert!(
72+ text.contains("source 0 test_multilang.mp4")
73+ && text.contains("source 1 test_multilang.mp4"),
74+ "the streams did not reach the file:\n{text}"
75+ );
76+
77+ let loaded = PlaybackSession::open_project(&path).expect("reopen the project");
78+ assert_eq!(loaded.sources(), session.sources());
79+ assert_eq!(loaded.timeline_duration(), session.timeline_duration());
80+
81+ // And the refusals, in the engine's own words: a stream that cannot share
82+ // one output device with the timeline, and a file that is not on it.
83+ let other = copy_in(&dir, "test_multiaudio.mp4");
84+ let mut session = PlaybackSession::open(&other).expect("open the fixture");
85+ session.set_gain(0.0);
86+ let frames = session.clip_at(0).expect("one clip").out_frame;
87+ let err = session
88+ .place_stream_at(0.0, &other, 1, frames)
89+ .expect_err("22.05 kHz mono cannot join a 44.1 kHz stereo timeline")
90+ .to_string();
91+ assert!(err.contains("22050"), "unhelpful refusal: {err}");
92+ assert!(
93+ session
94+ .place_stream_at(0.0, &media, 1, frames)
95+ .expect_err("a file that is not a source")
96+ .to_string()
97+ .contains("not on this timeline")
98+ );
99+ assert_eq!(session.sources().len(), 1, "a refusal added a source");
100+ std::fs::remove_dir_all(&dir).expect("cleanup");
101+}
102+
35103 /// Two files, four clips, one of them deleted, playhead at 3 s -- a timeline
36104 /// with something to lose in every field.
37105 fn edited(dir: &Path) -> PlaybackSession {
@@ -48,7 +116,7 @@ fn edited(dir: &Path) -> PlaybackSession {
48116 }
49117
50118 /// What has to survive a round trip, all of it public API.
51-fn shape(session: &PlaybackSession) -> (Vec<(f64, f64, usize)>, Vec<PathBuf>, f64) {
119+fn shape(session: &PlaybackSession) -> (Vec<(f64, f64, usize)>, Vec<Source>, f64) {
52120 (
53121 session.clip_spans_by_source(),
54122 session.sources().to_vec(),
@@ -58,9 +126,9 @@ fn shape(session: &PlaybackSession) -> (Vec<(f64, f64, usize)>, Vec<PathBuf>, f6
58126
59127 /// The version-1 promise: a file written before the lanes existed still opens,
60128 /// as one grouped video+audio pair per clip laid end to end, and saving it
61-/// again writes version 2 -- which reopens as the same timeline.
129+/// again writes version 3 -- which reopens as the same timeline.
62130 #[test]
63-fn a_version_1_project_loads_fully_grouped_and_saves_as_version_2() {
131+fn a_version_1_project_loads_fully_grouped_and_saves_as_version_3() {
64132 let dir = scratch("v1");
65133 copy_in(&dir, "test_av.mp4");
66134 let path = dir.join("old.edith");
@@ -88,11 +156,11 @@ fn a_version_1_project_loads_fully_grouped_and_saves_as_version_2() {
88156 "playhead kept"
89157 );
90158
91- // Saved again it is v2, and v2 round-trips to the same timeline.
159+ // Saved again it is v3, and v3 round-trips to the same timeline.
92160 let v2 = dir.join("new.edith");
93161 loaded.save_project(&v2).expect("save");
94162 let text = std::fs::read_to_string(&v2).expect("read back");
95- assert!(text.starts_with("edith 2\n"), "{text}");
163+ assert!(text.starts_with("edith 3\n"), "{text}");
96164 assert_eq!(
97165 text.lines().filter(|l| l.starts_with("video ")).count(),
98166 2,
@@ -109,6 +177,25 @@ fn a_version_1_project_loads_fully_grouped_and_saves_as_version_2() {
109177 let third = dir.join("third.edith");
110178 again.save_project(&third).expect("save");
111179 assert_eq!(std::fs::read(&third).expect("read"), text.as_bytes());
180+
181+ // And the same promise one version on: a v2 file names no audio stream and
182+ // opens on stream 0, which is the only one that dialect could play.
183+ let v2 = dir.join("v2.edith");
184+ std::fs::write(
185+ &v2,
186+ "edith 2\nplayhead 0\nsource test_av.mp4\nvideo 0 0 30 0 0\naudio 0 0 30 0 0\n",
187+ )
188+ .expect("write a v2 file");
189+ let loaded = PlaybackSession::open_project(&v2).expect("a v2 file still opens");
190+ assert_eq!(loaded.sources().len(), 1);
191+ assert_eq!(loaded.sources()[0].audio_stream, 0);
192+ loaded.save_project(&v2).expect("save");
193+ assert!(
194+ std::fs::read_to_string(&v2)
195+ .expect("read back")
196+ .contains("source 0 test_av.mp4"),
197+ "a re-saved v2 project says the stream it always meant"
198+ );
112199 }
113200
114201 #[test]
@@ -160,7 +247,7 @@ fn a_folder_of_media_and_its_project_can_be_moved() {
160247 let moved = PlaybackSession::open_project(&to.join("edit.edith")).expect("open the copy");
161248 assert_eq!(moved.timeline_duration(), 6.0);
162249 assert!(
163- moved.sources().iter().all(|s| s.starts_with(&to)),
250+ moved.sources().iter().all(|s| s.path.starts_with(&to)),
164251 "sources did not follow the folder: {:?}",
165252 moved.sources()
166253 );
@@ -321,7 +408,12 @@ fn malformed_files_are_numbered_errors_and_never_panics() {
321408 let good = "edith 1\nplayhead 0\nsource test_av.mp4\nclip 0 30 0\n";
322409
323410 for (text, want) in [
324- ("edith 3\nsource test_av.mp4\nvideo 0 0 30 0 -\n", "line 1"),
411+ (
412+ "edith 4\nsource 0 test_av.mp4\nvideo 0 0 30 0 -\n",
413+ "line 1",
414+ ),
415+ // A v2 source line in a v3 file: the stream field is not optional.
416+ ("edith 3\nsource test_av.mp4\nvideo 0 0 30 0 -\n", "line 2"),
325417 ("not a project at all\n", "line 1"),
326418 // Dialects do not mix: lane lines are v2's, `clip` is v1's.
327419 ("edith 2\nsource test_av.mp4\nclip 0 30 0\n", "line 3"),
scripts/gen_fixtures.shmodified+17 -0
@@ -48,6 +48,23 @@ ffmpeg -y -f lavfi -i testsrc2=size=320x180:rate=30:duration=2 \
4848 -f lavfi -i "sine=frequency=440:duration=2" \
4949 -map 0:v -map 1:a -c:v libx264 -profile:v baseline -pix_fmt yuv420p \
5050 -c:a ac3 -b:a 192k assets/test_ac3.mp4
51+# Multi-language fixture: the shape real media has — one video and two AAC
52+# streams that *agree* on rate and layout (44.1k stereo) and differ only in
53+# language and content, 440/880 Hz undefined and 220/330 Hz French. One
54+# timeline means one set of audio parameters, so this is the file where the
55+# second stream can actually be put on the timeline; test_multiaudio.mp4 is the
56+# file where it cannot, and both cases have to be shown.
57+ffmpeg -y -f lavfi -i testsrc2=size=320x240:rate=30:duration=2 \
58+ -f lavfi -i "sine=frequency=440:duration=2" \
59+ -f lavfi -i "sine=frequency=880:duration=2" \
60+ -f lavfi -i "sine=frequency=220:duration=2" \
61+ -f lavfi -i "sine=frequency=330:duration=2" \
62+ -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo[a0];\
63+[3:a][4:a]join=inputs=2:channel_layout=stereo[a1]" \
64+ -map 0:v -map "[a0]" -map "[a1]" \
65+ -c:v libx264 -profile:v baseline -pix_fmt yuv420p \
66+ -c:a aac -ar 44100 -ac 2 \
67+ -metadata:s:a:1 language=fra assets/test_multilang.mp4
5168 # Mismatch fixture: different resolution and no audio track at all, so import
5269 # has something concrete to refuse.
5370 ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \