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 +1192 -257

crates/app/src/main.rsmodified+592 -125
@@ -4,13 +4,14 @@ use keymap::{ActionId, Keymap};
4 4
5 use std::cell::Cell;5 use std::cell::Cell;
6 use std::collections::HashMap;6 use std::collections::HashMap;
7-use std::path::PathBuf;7+use std::path::{Path, PathBuf};
8 use std::rc::Rc;8 use std::rc::Rc;
9 use std::sync::Arc;9 use std::sync::Arc;
10 use std::time::{Duration, Instant};10 use std::time::{Duration, Instant};
11 11
12+use engine::audio::StreamInfo;
12 use engine::export::ExportSettings;13 use engine::export::ExportSettings;
13-use engine::project::Lane;14+use engine::project::{Lane, Source};
14 use engine::{Clip, ExportHandle, Frame, PlaybackSession};15 use engine::{Clip, ExportHandle, Frame, PlaybackSession};
15 use gpui::{16 use gpui::{
16 AnyElement, App, Application, Bounds, ClickEvent, Context, FocusHandle, KeyDownEvent,17 AnyElement, App, Application, Bounds, ClickEvent, Context, FocusHandle, KeyDownEvent,
@@ -189,10 +190,10 @@ enum Wave {
189 Peaks(Arc<Vec<(f32, f32)>>),190 Peaks(Arc<Vec<(f32, f32)>>),
190 }191 }
191 192
192-/// A library row being dragged. The source index and nothing else: the row is193+/// A library row being dragged: the file and which of its audio streams that
193-/// only a way of naming a source, and where it lands does not change what is194+/// row is, which is the whole of what a row names. Where it lands does not
194-/// inserted.195+/// change what is inserted.
195-struct AssetDrag(usize);196+struct AssetDrag(PathBuf, usize);
196 197
197 /// An open clip menu: which clip it was opened on, where it hangs, and whether198 /// An open clip menu: which clip it was opened on, where it hangs, and whether
198 /// it has been turned over to show what that clip *is* instead of what can be199 /// it has been turned over to show what that clip *is* instead of what can be
@@ -249,16 +250,21 @@ struct Player {
249 /// `selected` does, so it is closed by anything that can move indices --250 /// `selected` does, so it is closed by anything that can move indices --
250 /// every stroke, and every item of its own.251 /// every stroke, and every item of its own.
251 context_menu: Option<ContextMenu>,252 context_menu: Option<ContextMenu>,
252- /// Which library row is picked, as an index into the session's sources.253+ /// Which library row is picked: the file and the audio stream that row
253- /// Its own selection and not the timeline's: Delete keeps acting on the254+ /// names, which is what an insert needs and what survives a row list being
254- /// clip that was clicked in a lane, whatever the library is showing. Source255+ /// rebuilt. Its own selection and not the timeline's: Delete keeps acting
255- /// indexes are forever (project.rs:264), so this cannot go stale under an256+ /// on the clip that was clicked in a lane, whatever the library is showing.
256- /// edit -- only a new session clears it.257+ selected_asset: Option<(PathBuf, usize)>,
257- selected_asset: Option<usize>,
258 /// What is known about each source's audio, taken once and kept. Keyed on258 /// 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*:259+ /// the path *and stream* -- two streams of one file are two envelopes -- and
260- /// presence means "asked", so a repaint mid-decode cannot ask again.260+ /// the key is inserted the moment the decode is *started*: presence means
261- waves: HashMap<PathBuf, Wave>,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>>,
262 /// The copied clip. Frame ranges only, so it survives the clip it was taken268 /// The copied clip. Frame ranges only, so it survives the clip it was taken
263 /// from being deleted -- and it outlives the selection.269 /// from being deleted -- and it outlives the selection.
264 clipboard: Option<Clip>,270 clipboard: Option<Clip>,
@@ -539,7 +545,8 @@ impl Player {
539 }545 }
540 }546 }
541 547
542- /// Starts a peak decode for every source that has arrived since the last548+ /// Starts a peak decode -- and a stream probe -- for every source that has
549+ /// arrived since the last
543 /// repaint. One call from the render rather than three at the doors,550 /// repaint. One call from the render rather than three at the doors,
544 /// because argv, an import and a project load are all doors and only this551 /// because argv, an import and a project load are all doors and only this
545 /// one is guaranteed to run after each of them.552 /// one is guaranteed to run after each of them.
@@ -550,16 +557,35 @@ impl Player {
550 /// meanwhile and the repaint comes with the peaks. The entry is written557 /// meanwhile and the repaint comes with the peaks. The entry is written
551 /// *before* the spawn, so the sixty repaints that happen while a decode runs558 /// *before* the spawn, so the sixty repaints that happen while a decode runs
552 /// start no further ones.559 /// start no further ones.
553- fn cache_waves(&mut self, cx: &mut Context<Self>) {560+ fn cache_media(&mut self, cx: &mut Context<Self>) {
554 let Some(session) = &self.session else {561 let Some(session) = &self.session else {
555 return;562 return;
556 };563 };
557- for path in unseen_sources(session.sources(), &self.waves) {564+ // Which audio streams each file has, for the library's rows. Header
558- self.waves.insert(path.clone(), Wave::Loading);565+ // only, but a big file's sample tables are not free to parse, so it
559- let decoded = cx.background_executor().spawn({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({
560 let path = path.clone();570 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();
561 async move {587 async move {
562- engine::waveform::peaks(&path, WAVE_BPS)588+ engine::waveform::peaks(&path, stream, WAVE_BPS)
563 .ok()589 .ok()
564 .flatten()590 .flatten()
565 .map(|peaks| Arc::new(normalise(peaks)))591 .map(|peaks| Arc::new(normalise(peaks)))
@@ -569,7 +595,7 @@ impl Player {
569 let decoded = decoded.await;595 let decoded = decoded.await;
570 this.update(cx, |this, cx| {596 this.update(cx, |this, cx| {
571 this.waves.insert(597 this.waves.insert(
572- path,598+ key,
573 match decoded {599 match decoded {
574 Some(peaks) => Wave::Peaks(peaks),600 Some(peaks) => Wave::Peaks(peaks),
575 // Either no audio track or a file we could not read601 // Either no audio track or a file we could not read
@@ -614,38 +640,50 @@ impl Player {
614 /// moves along rather than being painted over. Reseeks like every other640 /// moves along rather than being painted over. Reseeks like every other
615 /// edit, and drops the timeline's selection with it: the insert has just641 /// edit, and drops the timeline's selection with it: the insert has just
616 /// moved the indices it pointed at.642 /// 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>) {
618 if self.exporting().is_some() {644 if self.exporting().is_some() {
619 return;645 return;
620 }646 }
621- let clip = self.session.as_ref().and_then(|session| {647+ let frames = self.session.as_ref().map_or(0, |session| {
622- let frames = source_frames(lane_clips(session), source);648+ source_frames(lane_clips(session), session.sources(), path)
649+ });
623 // Zero means nothing on the timeline plays from that file any more650 // Zero means nothing on the timeline plays from that file any more
624 // -- an undone import leaves the source entry behind (project.rs:264)651 // -- 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.652 // -- so there is no length to insert and no file to ask for one.
626- (frames > 0).then_some(Clip {653+ let placed = match (&mut self.session, frames) {
627- start: 0,654+ (Some(session), 1..) => session.place_stream_at(session.now(), path, stream, frames),
628- in_frame: 0,655+ _ => Ok(false),
629- out_frame: frames,
630- source,
631- link: None,
632- })
633- });
634- let added = match (&mut self.session, clip) {
635- (Some(session), Some(clip)) => session.paste_at(session.now(), clip),
636- _ => false,
637 };656 };
638- if added {657+ match placed {
658+ Ok(true) => {
639 self.selected = None;659 self.selected = None;
640 self.reset_after_reseek();660 self.reset_after_reseek();
641- } else {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) => {
642 self.notice = Some(666 self.notice = Some(
643 "NOTHING ADDED — no clip on the timeline plays from that file any more".into(),667 "NOTHING ADDED — no clip on the timeline plays from that file any more".into(),
644- );668+ )
669+ }
645 }670 }
646 cx.notify();671 cx.notify();
647 }672 }
648 673
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+
649 /// Appends a file to the end of the timeline. A drop is not a key press, so687 /// Appends a file to the end of the timeline. A drop is not a key press, so
650 /// the export guard on the key handler does not cover it and this checks for688 /// the export guard on the key handler does not cover it and this checks for
651 /// itself. The engine reseeks, so like a delete it owes the flag reset; a689 /// itself. The engine reseeks, so like a delete it owes the flag reset; a
@@ -739,7 +777,7 @@ impl Player {
739 let silent = audio_notice(&session);777 let silent = audio_notice(&session);
740 // A project is named after itself but still exports beside its778 // A project is named after itself but still exports beside its
741 // media: that is the only place an export has ever landed.779 // 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);
743 self.session = Some(session);781 self.session = Some(session);
744 self.apply_volume();782 self.apply_volume();
745 self.project_path = path.to_path_buf();783 self.project_path = path.to_path_buf();
@@ -1009,7 +1047,7 @@ impl Render for Player {
1009 // Every way a source can arrive -- argv, an import, a project load --1047 // Every way a source can arrive -- argv, an import, a project load --
1010 // has been through a repaint by the time its clips are drawn, so this1048 // has been through a repaint by the time its clips are drawn, so this
1011 // is the one place that has to notice a new one.1049 // is the one place that has to notice a new one.
1012- self.cache_waves(cx);1050+ self.cache_media(cx);
1013 // What the compositor calls this window. Pushed only when it changes:1051 // What the compositor calls this window. Pushed only when it changes:
1014 // it is a protocol round trip and this runs at vsync.1052 // it is a protocol round trip and this runs at vsync.
1015 let title = window_title(&self.name);1053 let title = window_title(&self.name);
@@ -1277,28 +1315,48 @@ impl Player {
1277 // the door (the import policy, ledger:436), so the session's own meta1315 // the door (the import policy, ledger:436), so the session's own meta
1278 // describes every row and nothing has to be probed to say so.1316 // describes every row and nothing has to be probed to say so.
1279 let meta = self.session.as_ref().map(PlaybackSession::meta);1317 let meta = self.session.as_ref().map(PlaybackSession::meta);
1280- let rows: Vec<_> = sources1318+ let clips: Vec<Clip> = self
1281- .iter()
1282- .enumerate()
1283- .map(|(i, path)| {
1284- let picked = self.selected_asset == Some(i);
1285- let frames = self
1286 .session1319 .session
1287 .as_ref()1320 .as_ref()
1288- .map_or(0, |session| source_frames(lane_clips(session), i));1321+ .map_or_else(Vec::new, |session| lane_clips(session).copied().collect());
1289- let name: SharedString = file_name(path).into();1322+ let rows: Vec<_> = library_rows(sources, &self.streams, self.timeline_audio(), |path| {
1290- let tip: SharedString = match meta {1323+ source_frames(clips.iter(), sources, path)
1291- Some(meta) => format!(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!(
1292 "{} — {}x{} @ {:.2} fps · drag onto a lane, or Add at playhead",1338 "{} — {}x{} @ {:.2} fps · drag onto a lane, or Add at playhead",
1293- path.display(),1339+ row.path.display(),
1294 meta.width,1340 meta.width,
1295 meta.height,1341 meta.height,
1296 meta.frame_rate1342 meta.frame_rate
1297 ),1343 ),
1298- None => path.display().to_string(),1344+ (None, None) => row.path.display().to_string(),
1299 }1345 }
1300 .into();1346 .into();
1301 let ghost = name.clone();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);
1302 div()1360 div()
1303 .id(("asset", i))1361 .id(("asset", i))
1304 .flex_none()1362 .flex_none()
@@ -1308,20 +1366,26 @@ impl Player {
1308 .gap(px(6.))1366 .gap(px(6.))
1309 .pr(px(6.))1367 .pr(px(6.))
1310 .rounded(px(3.))1368 .rounded(px(3.))
1311- .cursor_pointer()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()
1312 .hover(|s| s.bg(rgb(HOVER)))1374 .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| {1375 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
1316- this.selected_asset = Some(i);1376+ this.selected_asset = Some((path.clone(), stream));
1317 cx.notify();1377 cx.notify();
1318 }))1378 }))
1319- // The drag carries the row's source and the row's name: one1379+ // The drag carries the row's file and stream and the
1320- // for the drop to insert, one for the pointer to carry, so1380+ // row's name: one for the drop to insert, one for the
1321- // what is being dragged is legible on the way down.1381+ // pointer to carry, so what is being dragged is legible
1322- .on_drag(AssetDrag(i), move |_, _, _, cx| {1382+ // on the way down.
1383+ .on_drag(AssetDrag(dragged.0, dragged.1), move |_, _, _, cx| {
1323 cx.new(|_| Tip(ghost.clone()))1384 cx.new(|_| Tip(ghost.clone()))
1324 })1385 })
1386+ })
1387+ .when(picked, |d| d.bg(rgb(SELECTED)).border_1())
1388+ .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into())
1325 // Full height and hard against the edge: the tint reads as1389 // Full height and hard against the edge: the tint reads as
1326 // the lane's colour continuing into the list, not as a chip1390 // the lane's colour continuing into the list, not as a chip
1327 // that happens to be near it.1391 // that happens to be near it.
@@ -1331,7 +1395,7 @@ impl Player {
1331 .w(px(SWATCH_W))1395 .w(px(SWATCH_W))
1332 .h_full()1396 .h_full()
1333 .rounded(px(2.))1397 .rounded(px(2.))
1334- .bg(rgb(source_tint(i))),1398+ .bg(rgb(source_tint(row.tint))),
1335 )1399 )
1336 .child(1400 .child(
1337 div()1401 div()
@@ -1345,9 +1409,10 @@ impl Player {
1345 .child(div().truncate().text_size(px(11.)).child(name))1409 .child(div().truncate().text_size(px(11.)).child(name))
1346 .child(1410 .child(
1347 div()1411 div()
1412+ .truncate()
1348 .text_size(px(10.))1413 .text_size(px(10.))
1349 .text_color(rgb(INK_DIM))1414 .text_color(rgb(INK_DIM))
1350- .child(timecode(f64::from(frames) / self.fps, self.fps)),1415+ .child(under),
1351 ),1416 ),
1352 )1417 )
1353 })1418 })
@@ -1414,10 +1479,14 @@ impl Player {
1414 Some(_) => "inserts the picked file at the playhead".to_string(),1479 Some(_) => "inserts the picked file at the playhead".to_string(),
1415 None => "click a file above first — or drag one onto a lane".to_string(),1480 None => "click a file above first — or drag one onto a lane".to_string(),
1416 },1481 },
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+ ),
1418 cx.listener(|this, _: &ClickEvent, _, cx| {1487 cx.listener(|this, _: &ClickEvent, _, cx| {
1419- if let Some(source) = this.selected_asset {1488+ if let Some((path, stream)) = this.selected_asset.clone() {
1420- this.insert_source(source, cx);1489+ this.insert_source(&path, stream, cx);
1421 }1490 }
1422 }),1491 }),
1423 ))1492 ))
@@ -1995,7 +2064,7 @@ impl Player {
1995 let session = self.session.as_ref()?;2064 let session = self.session.as_ref()?;
1996 let clip = *session.lane_clips(menu.lane).get(menu.idx)?;2065 let clip = *session.lane_clips(menu.lane).get(menu.idx)?;
1997 let playhead = frame_at(session.now(), self.fps);2066 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()?;
1999 let secs = |frames: u32| timecode(f64::from(frames) / self.fps, self.fps);2068 let secs = |frames: u32| timecode(f64::from(frames) / self.fps, self.fps);
2000 let row = |n: usize| {2069 let row = |n: usize| {
2001 div()2070 div()
@@ -2016,8 +2085,8 @@ impl Player {
2016 // list of things to click. Each value is one truncated line, which2085 // list of things to click. Each value is one truncated line, which
2017 // is what keeps the height below the one the clamp was given.2086 // is what keeps the height below the one the clamp was given.
2018 for (label, value) in [2087 for (label, value) in [
2019- ("File", file_name(&path)),2088+ ("File", file_name(&source.path)),
2020- ("Path", path.display().to_string()),2089+ ("Path", source.path.display().to_string()),
2021 (2090 (
2022 "Source range",2091 "Source range",
2023 format!("{} – {}", secs(clip.in_frame), secs(clip.out_frame)),2092 format!("{} – {}", secs(clip.in_frame), secs(clip.out_frame)),
@@ -2025,7 +2094,11 @@ impl Player {
2025 ("This clip", secs(clip.len())),2094 ("This clip", secs(clip.len())),
2026 (2095 (
2027 "Source duration",2096 "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+ )),
2029 ),2102 ),
2030 ] {2103 ] {
2031 rows.push(2104 rows.push(
@@ -2100,7 +2173,7 @@ impl Player {
2100 viewport,2173 viewport,
2101 MENU_PAD * 2. + rows.len() as f32 * MENU_ROW_H,2174 MENU_PAD * 2. + rows.len() as f32 * MENU_ROW_H,
2102 );2175 );
2103- let full: SharedString = path.display().to_string().into();2176+ let full: SharedString = source.path.display().to_string().into();
2104 Some(2177 Some(
2105 div()2178 div()
2106 .absolute()2179 .absolute()
@@ -2238,9 +2311,9 @@ impl Player {
2238 // Add button makes, through the same call -- at the2311 // Add button makes, through the same call -- at the
2239 // playhead, not at the pointer: clips here are placed end2312 // playhead, not at the pointer: clips here are placed end
2240 // to end, so where along the bed it landed says nothing.2313 // to end, so where along the bed it landed says nothing.
2241- .on_drop(2314+ .on_drop(cx.listener(|this, drag: &AssetDrag, _, cx| {
2242- cx.listener(|this, drag: &AssetDrag, _, cx| this.insert_source(drag.0, cx)),2315+ this.insert_source(&drag.0.clone(), drag.1, cx)
2243- )2316+ }))
2244 .drag_over::<AssetDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))2317 .drag_over::<AssetDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))
2245 .children(clips.iter().enumerate().map(|(i, clip)| {2318 .children(clips.iter().enumerate().map(|(i, clip)| {
2246 let (start, len) = (2319 let (start, len) = (
@@ -2253,12 +2326,20 @@ impl Player {
2253 // as detached before anyone clicks it.2326 // as detached before anyone clicks it.
2254 let grouped =2327 let grouped =
2255 clip.link.is_some() && others.iter().any(|o| o.link == clip.link);2328 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+ );
2257 let width = width_frac(len, duration);2338 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));
2259 let wave = sources2340 let wave = sources
2260 .get(clip.source)2341 .get(clip.source)
2261- .and_then(|path| self.waves.get(path))2342+ .and_then(|s| self.waves.get(&(s.path.clone(), s.audio_stream)))
2262 .cloned();2343 .cloned();
2263 let (from, to) = (2344 let (from, to) = (
2264 f64::from(clip.in_frame) / self.fps,2345 f64::from(clip.in_frame) / self.fps,
@@ -2481,14 +2562,29 @@ fn audio_notice(session: &PlaybackSession) -> Option<String> {
2481 /// The sources a repaint has not asked about yet. A key that is already there2562 /// The sources a repaint has not asked about yet. A key that is already there
2482 /// means "asked", whatever state it is in, which is what stops a decode already2563 /// means "asked", whatever state it is in, which is what stops a decode already
2483 /// running from being started again by the next of sixty repaints a second.2564 /// 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)> {
2485 sources2569 sources
2486 .iter()2570 .iter()
2487- .filter(|path| !waves.contains_key(*path))2571+ .map(|s| (s.path.clone(), s.audio_stream))
2488- .cloned()2572+ .filter(|key| !waves.contains_key(key))
2489 .collect()2573 .collect()
2490 }2574 }
2491 2575
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+
2492 /// Both lanes' clips, which is everything the timeline knows about its sources.2588 /// Both lanes' clips, which is everything the timeline knows about its sources.
2493 fn lane_clips(session: &PlaybackSession) -> impl Iterator<Item = &Clip> {2589 fn lane_clips(session: &PlaybackSession) -> impl Iterator<Item = &Clip> {
2494 session2590 session
@@ -2498,17 +2594,25 @@ fn lane_clips(session: &PlaybackSession) -> impl Iterator<Item = &Clip> {
2498 }2594 }
2499 2595
2500 /// How long a source is, as the timeline knows it: the furthest frame any clip2596 /// 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 is2597+/// plays from *the file*. Exact for a source the timeline still holds whole --
2502-/// every source the moment it is imported -- and never longer than the file,2598+/// which is every source the moment it is imported -- and never longer than the
2503-/// since every clip was checked against it, so a clip built from this can2599+/// file, 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.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.
2505 ///2605 ///
2506 /// ponytail: a source trimmed on the timeline reads as its trimmed length. The2606 /// ponytail: a source trimmed on the timeline reads as its trimmed length. The
2507 /// file's own length would need a `Demuxer::open` probe per source, off the2607 /// file's own length would need a `Demuxer::open` probe per source, off the
2508 /// render path like the peak decode is -- that is the upgrade path.2608 /// 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 {
2510 clips2614 clips
2511- .filter(|clip| clip.source == source)2615+ .filter(|clip| sources.get(clip.source).is_some_and(|s| s.path == path))
2512 .map(|clip| clip.out_frame)2616 .map(|clip| clip.out_frame)
2513 .max()2617 .max()
2514 .unwrap_or(0)2618 .unwrap_or(0)
@@ -2554,10 +2658,165 @@ fn menu_at(at: Point<Pixels>, viewport: Size<Pixels>, height: f32) -> (f32, f32)
2554 /// Whether the Add button does anything: a row picked, a timeline to put it on,2658 /// Whether the Add button does anything: a row picked, a timeline to put it on,
2555 /// and no export reading that timeline. A button that would do nothing is dimmed2659 /// and no export reading that timeline. A button that would do nothing is dimmed
2556 /// and takes no click, like every other one here.2660 /// 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 {
2558 picked.is_some() && timeline && !exporting2662 picked.is_some() && timeline && !exporting
2559 }2663 }
2560 2664
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+
2561 /// What the media list is given of the window. A share of it, so a narrow2820 /// What the media list is given of the window. A share of it, so a narrow
2562 /// window gives the panel less rather than giving the picture nothing, floored2821 /// window gives the panel less rather than giving the picture nothing, floored
2563 /// where a name stops being readable and capped at a third of the window --2822 /// where a name stops being readable and capped at a third of the window --
@@ -2993,12 +3252,13 @@ mod tests {
2993 ACCENT, CONTROL_H, Clip, HEADER_GAP, HEADER_W, HIT_MIN, INK, INK_DIM, KEYS_ROW_H,3252 ACCENT, CONTROL_H, Clip, HEADER_GAP, HEADER_W, HIT_MIN, INK, INK_DIM, KEYS_ROW_H,
2994 KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W,3253 KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W,
2995 Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED,3254 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,3255+ SOURCE_TINTS, SURFACE, SWATCH_W, Source, StreamInfo, Volume, WAVE_BPS, WAVE_COL, Wave,
2997- cancels_export, envelope, export_path, export_settings, frac_along, frame_at,3256+ applicable, can_add, cancels_export, envelope, export_path, export_settings, frac_along,
2998- is_bare_modifier, is_project, keymap, lane_clips, marked, menu_at, normalise, project_path,3257+ frame_at, is_bare_modifier, is_project, keymap, lane_clips, marked, menu_at, normalise,
2999- push_digit, scrub_due, show_label, source_frames, source_tint, start_frac, timecode,3258+ project_path, push_digit, scrub_due, show_label, source_frames, source_tint, start_frac,
3000- unseen_sources, width_frac, window_title,3259+ timecode, unseen_paths, unseen_sources, width_frac, window_title,
3001 };3260 };
3261+ use super::{file_name, library_rows};
3002 use engine::PlaybackSession;3262 use engine::PlaybackSession;
3003 use gpui::{Bounds, Pixels, point, px, size};3263 use gpui::{Bounds, Pixels, point, px, size};
3004 use std::collections::HashMap;3264 use std::collections::HashMap;
@@ -3023,7 +3283,15 @@ mod tests {
3023 }3283 }
3024 }3284 }
3025 3285
3026- /// The whole of the library's row data comes off the clips: which sources3286+ /// 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
3027 /// there are, how long each one is, and therefore which tint each row wears3295 /// there are, how long each one is, and therefore which tint each row wears
3028 /// -- one index into one list, so a swatch cannot name a different file from3296 /// -- one index into one list, so a swatch cannot name a different file from
3029 /// the boxes it is meant to point at.3297 /// the boxes it is meant to point at.
@@ -3032,11 +3300,12 @@ mod tests {
3032 // Source 0 whole, source 1 trimmed to half of what it was, source 2 on3300 // Source 0 whole, source 1 trimmed to half of what it was, source 2 on
3033 // the audio lane only (its picture was lifted), source 3 imported and3301 // the audio lane only (its picture was lifted), source 3 imported and
3034 // then undone -- an entry with nothing playing from it.3302 // 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();
3035 let video = [clip(0, 150), clip(1, 60)];3304 let video = [clip(0, 150), clip(1, 60)];
3036 let audio = [clip(0, 150), clip(1, 30), clip(2, 90)];3305 let audio = [clip(0, 150), clip(1, 30), clip(2, 90)];
3037 for (row, frames) in [(0, 150), (1, 60), (2, 90), (3, 0)] {3306 for (row, frames) in [(0, 150), (1, 60), (2, 90), (3, 0)] {
3038 assert_eq!(3307 assert_eq!(
3039- source_frames(video.iter().chain(&audio), row),3308+ source_frames(video.iter().chain(&audio), &sources, &sources[row].path),
3040 frames,3309 frames,
3041 "row {row}"3310 "row {row}"
3042 );3311 );
@@ -3044,11 +3313,146 @@ mod tests {
3044 // function -- what makes the panel and the lanes one association.3313 // function -- what makes the panel and the lanes one association.
3045 assert_eq!(source_tint(row), SOURCE_TINTS[row % SOURCE_TINTS.len()]);3314 assert_eq!(source_tint(row), SOURCE_TINTS[row % SOURCE_TINTS.len()]);
3046 }3315 }
3047- // The longest clip of a source wins, whichever lane it is in and3316+ // The longest clip of a file wins, whichever lane it is in and
3048 // whatever order the lanes are read in.3317 // whatever order the lanes are read in.
3049- assert_eq!(source_frames([clip(0, 10), clip(0, 90)].iter(), 0), 90);3318+ let one = [source("/m/0.mp4", 0)];
3050- assert_eq!(source_frames([clip(0, 90), clip(0, 10)].iter(), 0), 90);3319+ let path = &one[0].path;
3051- assert_eq!(source_frames([].iter(), 0), 0);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");
3052 }3456 }
3053 3457
3054 /// What the clip menu offers, and where it hangs. The two items that act on3458 /// What the clip menu offers, and where it hangs. The two items that act on
@@ -3128,7 +3532,11 @@ mod tests {
3128 // at 30 fps, exactly what was appended.3532 // at 30 fps, exactly what was appended.
3129 session.import(&asset("test_av2.mp4")).expect("av2 matches");3533 session.import(&asset("test_av2.mp4")).expect("av2 matches");
3130 assert_eq!(session.sources().len(), 2);3534 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+ );
3132 assert_eq!(timecode(120. / 30., 30.), "00:00:04:00");3540 assert_eq!(timecode(120. / 30., 30.), "00:00:04:00");
3133 }3541 }
3134 3542
@@ -3143,17 +3551,15 @@ mod tests {
3143 assert_eq!(session.timeline_duration(), 9.0);3551 assert_eq!(session.timeline_duration(), 9.0);
3144 // Two seconds in, which is inside the first take: the insert splits it.3552 // Two seconds in, which is inside the first take: the insert splits it.
3145 session.seek(2.0);3553 session.seek(2.0);
3146- let frames = source_frames(lane_clips(&session), 1);3554+ let second = session.sources()[1].path.clone();
3147- assert!(session.paste_at(3555+ let frames = source_frames(lane_clips(&session), session.sources(), &second);
3148- 2.0,3556+ // Through the engine door `insert_source` uses, with the row's own
3149- Clip {3557+ // stream: the button, the drop and this are one call.
3150- start: 0,3558+ assert!(
3151- in_frame: 0,3559+ session
3152- out_frame: frames,3560+ .place_stream_at(2.0, &second, 0, frames)
3153- source: 1,3561+ .expect("av2 is already on the timeline")
3154- link: None,3562+ );
3155- }
3156- ));
3157 // The whole of source 1 went in and nothing was painted over: the3563 // The whole of source 1 went in and nothing was painted over: the
3158 // timeline is longer by exactly that file.3564 // timeline is longer by exactly that file.
3159 assert_eq!(session.timeline_duration(), 13.0);3565 assert_eq!(session.timeline_duration(), 13.0);
@@ -3174,32 +3580,89 @@ mod tests {
3174 assert_eq!(at(video).len(), frames);3580 assert_eq!(at(video).len(), frames);
3175 assert!(at(video).link.is_some());3581 assert!(at(video).link.is_some());
3176 assert_eq!(video.len(), audio.len());3582 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+ );
3177 }3606 }
3178 3607
3179 #[test]3608 #[test]
3180 fn a_source_is_only_ever_asked_for_its_peaks_once() {3609 fn a_source_is_only_ever_asked_for_its_peaks_once() {
3181 let (a, b) = (asset("test_av.mp4"), asset("test_av2.mp4"));3610 let (a, b) = (asset("test_av.mp4"), asset("test_av2.mp4"));
3182- let sources = [a.clone(), b.clone()];3611+ // Two files, and two streams of the first: three envelopes, because
3183- let mut waves: HashMap<PathBuf, Wave> = HashMap::new();3612+ // one file's two audio tracks are two different waveforms.
3184- assert_eq!(unseen_sources(&sources, &waves), sources);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));
3185 // The entry goes in when the decode *starts*, so the sixty repaints a3634 // The entry goes in when the decode *starts*, so the sixty repaints a
3186 // second that happen while it runs must not start it again -- which is3635 // second that happen while it runs must not start it again -- which is
3187 // what this asserts about a key whose value is not an answer yet.3636 // what this asserts about a key whose value is not an answer yet.
3188- waves.insert(a, Wave::Loading);3637+ waves.insert((a.clone(), 0), Wave::Loading);
3189- assert_eq!(unseen_sources(&sources, &waves), vec![b.clone()]);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+ );
3190 // A file with no audio is an answer like any other: never re-asked.3643 // 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);
3192 assert!(unseen_sources(&sources, &waves).is_empty());3646 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);
3193 }3655 }
3194 3656
3195 #[test]3657 #[test]
3196 fn the_add_button_is_dead_unless_it_would_do_something() {3658 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));
3198 // Nothing picked, nothing to put it on, or an export reading the very3661 // Nothing picked, nothing to put it on, or an export reading the very
3199 // edit list this would change.3662 // edit list this would change.
3200 assert!(!can_add(None, true, false));3663 assert!(!can_add(None, true, false));
3201- assert!(!can_add(Some(0), false, false));3664+ assert!(!can_add(Some(&picked), false, false));
3202- assert!(!can_add(Some(0), true, true));3665+ assert!(!can_add(Some(&picked), true, true));
3203 }3666 }
3204 3667
3205 #[test]3668 #[test]
@@ -3691,7 +4154,7 @@ mod tests {
3691 .join(name)4154 .join(name)
3692 };4155 };
3693 let peaks = normalise(4156 let peaks = normalise(
3694- engine::waveform::peaks(asset("test_av.mp4"), WAVE_BPS)4157+ engine::waveform::peaks(asset("test_av.mp4"), 0, WAVE_BPS)
3695 .expect("open the fixture")4158 .expect("open the fixture")
3696 .expect("test_av.mp4 has audio"),4159 .expect("test_av.mp4 has audio"),
3697 );4160 );
@@ -3710,7 +4173,7 @@ mod tests {
3710 );4173 );
3711 // A video-only source draws no waveform at all rather than a flat fake.4174 // A video-only source draws no waveform at all rather than a flat fake.
3712 assert!(4175 assert!(
3713- engine::waveform::peaks(asset("test_baseline.mp4"), WAVE_BPS)4176+ engine::waveform::peaks(asset("test_baseline.mp4"), 0, WAVE_BPS)
3714 .expect("open the fixture")4177 .expect("open the fixture")
3715 .is_none()4178 .is_none()
3716 );4179 );
@@ -3807,7 +4270,10 @@ fn main() {
3807 }4270 }
3808 // A file that plays silent is as much news at launch as it is on a drop, and4271 // A file that plays silent is as much news at launch as it is on a drop, and
3809 // behind the keymap notice for the same reason an import refusal is.4272 // 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+ {
3811 let text = format!("NO AUDIO: {reason}");4277 let text = format!("NO AUDIO: {reason}");
3812 eprintln!("{text}");4278 eprintln!("{text}");
3813 notice.get_or_insert(text);4279 notice.get_or_insert(text);
@@ -3815,9 +4281,9 @@ fn main() {
3815 let meta = session.as_ref().map(|session| *session.meta());4281 let meta = session.as_ref().map(|session| *session.meta());
3816 // Beside the media even for a project: an export has never landed anywhere4282 // Beside the media even for a project: an export has never landed anywhere
3817 // but next to the picture it came from.4283 // but next to the picture it came from.
3818- let out = session4284+ let out = session.as_ref().map_or_else(PathBuf::new, |session| {
3819- .as_ref()4285+ export_path(&session.sources()[0].path)
3820- .map_or_else(PathBuf::new, |session| export_path(&session.sources()[0]));4286+ });
3821 let project = match &arg {4287 let project = match &arg {
3822 Some(arg) if is_project(arg) => arg.clone(),4288 Some(arg) if is_project(arg) => arg.clone(),
3823 Some(arg) => project_path(arg),4289 Some(arg) => project_path(arg),
@@ -3884,6 +4350,7 @@ fn main() {
3884 context_menu: None,4350 context_menu: None,
3885 selected_asset: None,4351 selected_asset: None,
3886 waves: HashMap::new(),4352 waves: HashMap::new(),
4353+ streams: HashMap::new(),
3887 clipboard: None,4354 clipboard: None,
3888 scrubbing: false,4355 scrubbing: false,
3889 last_scrub: Instant::now(),4356 last_scrub: Instant::now(),
crates/engine/src/audio.rsmodified+31 -18
@@ -274,16 +274,19 @@ impl AudioSession {
274 .find(|t| matches!(t.track_type(), Ok(TrackType::Audio)))274 .find(|t| matches!(t.track_type(), Ok(TrackType::Audio)))
275 .map(|t| match t.media_type() {275 .map(|t| match t.media_type() {
276 Ok(media) => format!("the {media} audio track cannot be decoded (AAC-LC only)"),276 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+ }
278 }))280 }))
279 }281 }
280 282
281- /// The audio parameters of `path`, for checking an import against the283+ /// The audio parameters of `path`'s `stream`, for checking an import
282- /// timeline's first source: header only, no decoder and no worker.284+ /// against the timeline's first source: header only, no decoder and no
283- /// `Ok(None)` means no AAC track — an audio-less file, which import pairs285+ /// worker. `Ok(None)` means no AAC track — an audio-less file, which import
284- /// only with other audio-less files.286+ /// pairs only with other audio-less files. A *named* stream that is not
285- pub fn probe(path: impl AsRef<Path>) -> crate::Result<Option<AudioProbe>> {287+ /// there or does not decode is an `Err`, as everywhere else.
286- let Some(track) = Track::open(path.as_ref(), 0)? 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 {
287 return Ok(None);290 return Ok(None);
288 };291 };
289 Ok(Some(AudioProbe {292 Ok(Some(AudioProbe {
@@ -375,14 +378,28 @@ impl AudioSession {
375 pub fn copy_multi_segments(378 pub fn copy_multi_segments(
376 sources: &[PathBuf],379 sources: &[PathBuf],
377 segs: &[(Option<usize>, f64, f64)],380 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)],
378 ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> {395 ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> {
379 let Some(&(Some(first), ..)) = segs.iter().find(|s| s.0.is_some()) else {396 let Some(&(Some(first), ..)) = segs.iter().find(|s| s.0.is_some()) else {
380 return Ok(None); // no segments, or nothing but silence397 return Ok(None); // no segments, or nothing but silence
381 };398 };
382- let path = sources399+ let (path, stream) = sources
383 .get(first)400 .get(first)
384 .ok_or_else(|| format!("segment names source {first} of {}", sources.len()))?;401 .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 {
386 return Ok(None); // silent source, silent export403 return Ok(None); // silent source, silent export
387 };404 };
388 let params = track.track_params();405 let params = track.track_params();
@@ -471,24 +488,20 @@ fn silent_packet(chan_conf: u8) -> crate::Result<Vec<u8>> {
471 }488 }
472 }489 }
473 490
474-/// The source at `index`, opened on first use. Sources a segment list never491+/// The source at `index`, on the stream it names, opened on first use. Sources
475-/// names are never touched: a project's list only grows.492+/// a segment list never 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.
481 fn source_at<'a>(493 fn source_at<'a>(
482 tracks: &'a mut [Option<Track>],494 tracks: &'a mut [Option<Track>],
483- sources: &[PathBuf],495+ sources: &[(PathBuf, usize)],
484 index: usize,496 index: usize,
485 ) -> crate::Result<&'a mut Track> {497 ) -> crate::Result<&'a mut Track> {
486 let slot = tracks498 let slot = tracks
487 .get_mut(index)499 .get_mut(index)
488 .ok_or_else(|| format!("segment names source {index} of {}", sources.len()))?;500 .ok_or_else(|| format!("segment names source {index} of {}", sources.len()))?;
489 if slot.is_none() {501 if slot.is_none() {
502+ let (path, stream) = &sources[index];
490 *slot = Some(503 *slot = Some(
491- Track::open(&sources[index], 0)?504+ Track::open(path, *stream)?
492 .ok_or_else(|| format!("source {index} has no audio track"))?,505 .ok_or_else(|| format!("source {index} has no audio track"))?,
493 );506 );
494 }507 }
crates/engine/src/demux.rsmodified+11 -3
@@ -141,7 +141,8 @@ fn frame_rate(track: &Mp4Track) -> f64 {
141 /// to average 3753.75 averages instead of truncating. All of it in `f64`, which141 /// to average 3753.75 averages instead of truncating. All of it in `f64`, which
142 /// is the bug the caller above exists to avoid.142 /// is the bug the caller above exists to avoid.
143 fn fps_from_stts(entries: impl IntoIterator<Item = (u32, u32)>, timescale: u32) -> f64 {143 fn fps_from_stts(entries: impl IntoIterator<Item = (u32, u32)>, timescale: u32) -> f64 {
144- let (samples, ticks) = entries144+ let (samples, ticks) =
145+ entries
145 .into_iter()146 .into_iter()
146 .fold((0u64, 0u64), |(samples, ticks), (count, delta)| {147 .fold((0u64, 0u64), |(samples, ticks), (count, delta)| {
147 (148 (
@@ -261,7 +262,10 @@ mod tests {
261 );262 );
262 // Constant delta stays an exact division, not an average.263 // Constant delta stays an exact division, not an average.
263 assert_eq!(fps_from_stts([(300u32, 3000u32)], 90_000), 30.0);264 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+ );
265 assert_eq!(fps_from_stts([(0u32, 0u32)], 90_000), 0.0, "no timing");269 assert_eq!(fps_from_stts([(0u32, 0u32)], 90_000), 0.0, "no timing");
266 }270 }
267 271
@@ -277,7 +281,11 @@ mod tests {
277 assert_eq!(first_frame_sample(entries, Some(7507 - 7507)), 1);281 assert_eq!(first_frame_sample(entries, Some(7507 - 7507)), 1);
278 // Two frames genuinely cut off the front.282 // Two frames genuinely cut off the front.
279 assert_eq!(first_frame_sample(entries, Some(7507)), 3);283 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+ );
281 assert_eq!(first_frame_sample(entries, Some(0)), 1, "zero is no trim");289 assert_eq!(first_frame_sample(entries, Some(0)), 1, "zero is no trim");
282 }290 }
283 291
crates/engine/src/edith.rsmodified+123 -38
@@ -1,25 +1,33 @@
1 //! The project file: a line of text per thing, and nothing else.1 //! The project file: a line of text per thing, and nothing else.
2 //!2 //!
3 //! ```text3 //! ```text
4-//! edith 24+//! edith 3
5 //! playhead 905 //! playhead 90
6-//! source test_av.mp46+//! source 0 test_av.mp4
7-//! source /elsewhere/test_av2.mp47+//! source 1 /elsewhere/test_av2.mp4
8 //! video 0 0 120 0 08 //! video 0 0 120 0 0
9 //! audio 0 0 120 0 09 //! audio 0 0 120 0 0
10 //! video 120 0 120 1 -10 //! video 120 0 120 1 -
11 //! ```11 //! ```
12 //!12 //!
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+//!
13 //! A lane line is `<lane> <start> <in> <out> <source> <link>`: where the clip19 //! A lane line is `<lane> <start> <in> <out> <source> <link>`: where the clip
14 //! sits on the timeline, the half-open source range it plays, the file it plays20 //! sits on the timeline, the half-open source range it plays, the file it plays
15 //! from, and its group id (`-` for none). Timeline placement is explicit, so a21 //! from, and its group id (`-` for none). Timeline placement is explicit, so a
16 //! *gap* is simply a stretch no line covers -- there is nothing to write for22 //! *gap* is simply a stretch no line covers -- there is nothing to write for
17 //! one, and nothing that can disagree about its length.23 //! one, and nothing that can disagree about its length.
18 //!24 //!
19-//! **Version 1** wrote one lane, queued end to end: `clip <in> <out> <source>`.25+//! **Version 2** wrote `source <path>`, which is this file's stream 0 -- one
20-//! Such a file still loads -- the clips are laid out cumulatively and copied26+//! per file, whichever audio track came first. **Version 1** wrote that and one
21-//! onto both lanes as one group each, which is exactly what a v1 timeline meant27+//! lane, queued end to end: `clip <in> <out> <source>`. Both still load -- a v1
22-//! -- and saving it again writes v2. A v1 reader refuses a v2 file by name.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.
23 //!31 //!
24 //! Text because an edit list is a few integers and a path, and a path is32 //! Text because an edit list is a few integers and a path, and a path is
25 //! *bytes* on this platform -- a JSON string would have to lossily decode one.33 //! *bytes* on this platform -- a JSON string would have to lossily decode one.
@@ -45,19 +53,21 @@ use std::io::Write;
45 use std::os::unix::ffi::{OsStrExt, OsStringExt};53 use std::os::unix::ffi::{OsStrExt, OsStringExt};
46 use std::path::{Path, PathBuf};54 use std::path::{Path, PathBuf};
47 55
48-use crate::project::Clip;56+use crate::project::{Clip, Source};
49 57
50 /// What [`save`] writes. Read support goes back to `edith 1`; see the module58 /// What [`save`] writes. Read support goes back to `edith 1`; see the module
51-/// docs for what that dialect looked like.59+/// docs for what those dialects looked like.
52-const MAGIC: &[u8] = b"edith 2";60+const MAGIC: &[u8] = b"edith 3";
61+const MAGIC_V2: &[u8] = b"edith 2";
53 const MAGIC_V1: &[u8] = b"edith 1";62 const MAGIC_V1: &[u8] = b"edith 1";
54 63
55 /// What a project file says: an edit list plus where the playhead stood.64 /// What a project file says: an edit list plus where the playhead stood.
56 /// Structurally valid by construction -- see [`parse`].65 /// Structurally valid by construction -- see [`parse`].
57 #[derive(Debug)]66 #[derive(Debug)]
58 pub struct Document {67 pub struct Document {
59- /// Absolute, relative entries already joined to the file's own directory.68+ /// Paths absolute, relative entries already joined to the file's own
60- pub sources: Vec<PathBuf>,69+ /// directory.
70+ pub sources: Vec<Source>,
61 pub video: Vec<Clip>,71 pub video: Vec<Clip>,
62 pub audio: Vec<Clip>,72 pub audio: Vec<Clip>,
63 pub playhead: u32,73 pub playhead: u32,
@@ -67,7 +77,7 @@ pub struct Document {
67 /// orphan-free ([`crate::Project::without_orphan_sources`]).77 /// orphan-free ([`crate::Project::without_orphan_sources`]).
68 pub fn save(78 pub fn save(
69 path: &Path,79 path: &Path,
70- sources: &[PathBuf],80+ sources: &[Source],
71 video: &[Clip],81 video: &[Clip],
72 audio: &[Clip],82 audio: &[Clip],
73 playhead: u32,83 playhead: u32,
@@ -112,14 +122,14 @@ fn project_dir(path: &Path) -> PathBuf {
112 dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf())122 dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf())
113 }123 }
114 124
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> {
116 let mut out = Vec::new();126 let mut out = Vec::new();
117 out.extend_from_slice(MAGIC);127 out.extend_from_slice(MAGIC);
118 out.push(b'\n');128 out.push(b'\n');
119 out.extend_from_slice(format!("playhead {playhead}\n").as_bytes());129 out.extend_from_slice(format!("playhead {playhead}\n").as_bytes());
120 for s in sources {130 for s in sources {
121- out.extend_from_slice(b"source ");131+ out.extend_from_slice(format!("source {} ", s.audio_stream).as_bytes());
122- escape(s.strip_prefix(dir).unwrap_or(s), &mut out);132+ escape(s.path.strip_prefix(dir).unwrap_or(&s.path), &mut out);
123 out.push(b'\n');133 out.push(b'\n');
124 }134 }
125 // Lane by lane rather than interleaved by time: a lane reads as a list, and135 // 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> {
146 let mut lines = body.split(|&b| b == b'\n').enumerate();156 let mut lines = body.split(|&b| b == b'\n').enumerate();
147 let (_, first) = lines.next().unwrap_or((0, &[]));157 let (_, first) = lines.next().unwrap_or((0, &[]));
148 let v1 = first == MAGIC_V1;158 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 {
150 return Err(match first.strip_prefix(b"edith ") {163 return Err(match first.strip_prefix(b"edith ") {
151 Some(v) => format!("line 1: unsupported version {}", String::from_utf8_lossy(v)),164 Some(v) => format!("line 1: unsupported version {}", String::from_utf8_lossy(v)),
152 None => "line 1: not a edith file".to_string(),165 None => "line 1: not a edith file".to_string(),
@@ -184,16 +197,33 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
184 if !doc.video.is_empty() || !doc.audio.is_empty() {197 if !doc.video.is_empty() || !doc.audio.is_empty() {
185 return Err(format!("line {n}: source after a clip").into());198 return Err(format!("line {n}: source after a clip").into());
186 }199 }
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+ };
187 if rest.is_empty() {214 if rest.is_empty() {
188 return Err(format!("line {n}: source without a path").into());215 return Err(format!("line {n}: source without a path").into());
189 }216 }
190 let path = unescape(rest, n)?;217 let path = unescape(rest, n)?;
191 // Relative means "next to the project file", which is what218 // Relative means "next to the project file", which is what
192 // makes a whole folder relocatable.219 // makes a whole folder relocatable.
193- doc.sources.push(if path.is_absolute() {220+ doc.sources.push(Source {
221+ path: if path.is_absolute() {
194 path222 path
195 } else {223 } else {
196 dir.join(path)224 dir.join(path)
225+ },
226+ audio_stream,
197 });227 });
198 }228 }
199 // v1: one lane, no placement, no groups. Every clip becomes one229 // v1: one lane, no placement, no groups. Every clip becomes one
@@ -376,13 +406,17 @@ mod tests {
376 /// Two sources, one under the project's own directory and one not, a clip406 /// Two sources, one under the project's own directory and one not, a clip
377 /// from each on the video lane, and an audio lane with a gap in the middle407 /// from each on the video lane, and an audio lane with a gap in the middle
378 /// -- the shape every case below starts from.408 /// -- 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>) {
380 (417 (
381 PathBuf::from("/proj"),418 PathBuf::from("/proj"),
382- vec![419+ vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 2)],
383- PathBuf::from("/proj/a.mp4"),
384- PathBuf::from("/elsewhere/b.mp4"),
385- ],
386 vec![clip(0, 0, 30, 0, Some(0)), clip(30, 10, 20, 1, Some(1))],420 vec![clip(0, 0, 30, 0, Some(0)), clip(30, 10, 20, 1, Some(1))],
387 vec![clip(0, 0, 30, 0, Some(0))],421 vec![clip(0, 0, 30, 0, Some(0))],
388 )422 )
@@ -394,9 +428,10 @@ mod tests {
394 let bytes = emit(&dir, &sources, &video, &audio, 12);428 let bytes = emit(&dir, &sources, &video, &audio, 12);
395 assert_eq!(429 assert_eq!(
396 String::from_utf8_lossy(&bytes),430 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\
398 video 0 0 30 0 0\nvideo 30 10 20 1 1\naudio 0 0 30 0 0\n",432 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"
400 );435 );
401 let back = parse(&bytes, &dir).expect("parse");436 let back = parse(&bytes, &dir).expect("parse");
402 assert_eq!(back.sources, sources, "relative entries rejoin the dir");437 assert_eq!(back.sources, sources, "relative entries rejoin the dir");
@@ -413,8 +448,36 @@ mod tests {
413 );448 );
414 }449 }
415 450
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+
416 /// The compatibility promise: a v1 file is a fully-grouped, gapless pair of479 /// 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.
418 #[test]481 #[test]
419 fn a_v1_file_loads_as_two_grouped_lanes() {482 fn a_v1_file_loads_as_two_grouped_lanes() {
420 let dir = PathBuf::from("/proj");483 let dir = PathBuf::from("/proj");
@@ -427,10 +490,10 @@ mod tests {
427 );490 );
428 assert_eq!(back.audio, back.video, "one take per clip, on both lanes");491 assert_eq!(back.audio, back.video, "one take per clip, on both lanes");
429 assert_eq!(back.playhead, 5);492 assert_eq!(back.playhead, 5);
430- // Saved again it is v2, and that round-trips to the same document.493+ // Saved again it is v3, and that round-trips to the same document.
431- let v2 = emit(&dir, &back.sources, &back.video, &back.audio, back.playhead);494+ let v3 = emit(&dir, &back.sources, &back.video, &back.audio, back.playhead);
432- assert!(v2.starts_with(b"edith 2\n"));495+ assert!(v3.starts_with(b"edith 3\n"));
433- let again = parse(&v2, &dir).expect("v2 parses");496+ let again = parse(&v3, &dir).expect("v3 parses");
434 assert_eq!((again.video, again.audio), (back.video, back.audio));497 assert_eq!((again.video, again.audio), (back.video, back.audio));
435 // A dialect may not be mixed: lane lines under v1, `clip` under v2.498 // A dialect may not be mixed: lane lines under v1, `clip` under v2.
436 for (bytes, want) in [499 for (bytes, want) in [
@@ -514,17 +577,25 @@ mod tests {
514 let path = dir.join("link/p.edith");577 let path = dir.join("link/p.edith");
515 578
516 let one = [clip(0, 0, 30, 0, None)];579 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");
518 let bytes = std::fs::read(&path).expect("read back");585 let bytes = std::fs::read(&path).expect("read back");
519 assert_eq!(586 assert_eq!(
520 String::from_utf8_lossy(&bytes),587 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"
522 );589 );
523 // Loading rejoins the *given* directory, so the file is reached by the590 // 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.
525 assert_eq!(593 assert_eq!(
526 load(&path).expect("load").sources,594 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+ }]
528 );599 );
529 std::fs::remove_dir_all(&dir).expect("cleanup");600 std::fs::remove_dir_all(&dir).expect("cleanup");
530 }601 }
@@ -533,7 +604,10 @@ mod tests {
533 fn escapes_survive_the_bytes_json_would_not() {604 fn escapes_survive_the_bytes_json_would_not() {
534 let dir = PathBuf::from("/proj");605 let dir = PathBuf::from("/proj");
535 // A newline and a percent in a filename, plus a non-UTF-8 byte.606 // 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+ };
537 let bytes = emit(&dir, &[nasty.clone()], &[clip(0, 0, 5, 0, None)], &[], 0);611 let bytes = emit(&dir, &[nasty.clone()], &[clip(0, 0, 5, 0, None)], &[], 0);
538 assert_eq!(612 assert_eq!(
539 bytes.iter().filter(|&&b| b == b'\n').count(),613 bytes.iter().filter(|&&b| b == b'\n').count(),
@@ -541,16 +615,18 @@ mod tests {
541 "the escaped newline must not become a line break"615 "the escaped newline must not become a line break"
542 );616 );
543 let back = parse(&bytes, &dir).expect("parse");617 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.
544 assert_eq!(back.sources, vec![nasty]);620 assert_eq!(back.sources, vec![nasty]);
545 }621 }
546 622
547 #[test]623 #[test]
548 fn a_wrong_first_line_is_refused_by_name() {624 fn a_wrong_first_line_is_refused_by_name() {
549 let dir = PathBuf::from("/proj");625 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)
551 .unwrap_err()627 .unwrap_err()
552 .to_string();628 .to_string();
553- assert_eq!(err, "line 1: unsupported version 3");629+ assert_eq!(err, "line 1: unsupported version 4");
554 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {630 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {
555 assert_eq!(631 assert_eq!(
556 parse(junk, &dir).unwrap_err().to_string(),632 parse(junk, &dir).unwrap_err().to_string(),
@@ -562,7 +638,16 @@ mod tests {
562 #[test]638 #[test]
563 fn malformed_lines_name_their_line_number() {639 fn malformed_lines_name_their_line_number() {
564 let dir = PathBuf::from("/proj");640 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+ ),
566 (651 (
567 b"edith 1\nsource a.mp4\nclip 0 5\n",652 b"edith 1\nsource a.mp4\nclip 0 5\n",
568 "line 3: clip wants 3 fields, found 2",653 "line 3: clip wants 3 fields, found 2",
crates/engine/src/export.rsmodified+10 -4
@@ -159,8 +159,14 @@ fn run(
159 // files stays in sync. A source whose AAC parameters disagree with the159 // files stays in sync. A source whose AAC parameters disagree with the
160 // first one is an `Err` from there -- import refuses those up front, this160 // first one is an `Err` from there -- import refuses those up front, this
161 // is the backstop -- and the caller deletes the `.part`.161 // is the backstop -- and the caller deletes the `.part`.
162- let audio =162+ //
163- AudioSession::copy_multi_segments(sources, &project.segments_from(0, meta.frame_rate))?;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+ )?;
164 let audio_params = audio.as_ref().map(|(track, _)| AudioParams {170 let audio_params = audio.as_ref().map(|(track, _)| AudioParams {
165 freq_index: track.freq_index,171 freq_index: track.freq_index,
166 chan_conf: track.chan_conf,172 chan_conf: track.chan_conf,
@@ -180,10 +186,10 @@ fn run(
180 // file boundaries, which are just cuts that change the path.186 // file boundaries, which are just cuts that change the path.
181 let mut pictures = match span.from {187 let mut pictures = match span.from {
182 Some((source, in_frame)) => {188 Some((source, in_frame)) => {
183- let path = sources189+ let entry = sources
184 .get(source)190 .get(source)
185 .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?;191 .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)?)
187 }193 }
188 None => None,194 None => None,
189 };195 };
crates/engine/src/mux.rsmodified+5 -2
@@ -186,7 +186,8 @@ impl Mp4Muxer {
186 /// export, which is this bug's own truncation reborn at the writing end.186 /// export, which is this bug's own truncation reborn at the writing end.
187 pub(crate) fn frame_timing(fps: f64) -> crate::Result<(u32, u32)> {187 pub(crate) fn frame_timing(fps: f64) -> crate::Result<(u32, u32)> {
188 let ticks = f64::from(VIDEO_TIMESCALE) / fps;188 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+ {
190 return Ok((VIDEO_TIMESCALE, ticks.round() as u32));191 return Ok((VIDEO_TIMESCALE, ticks.round() as u32));
191 }192 }
192 let timescale = (fps * f64::from(NTSC_TICKS)).round();193 let timescale = (fps * f64::from(NTSC_TICKS)).round();
@@ -503,7 +504,9 @@ mod tests {
503 None,504 None,
504 )505 )
505 .unwrap();506 .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();
507 muxer.write_video_au(&au(&[&[0x41, 0x02]])).unwrap();510 muxer.write_video_au(&au(&[&[0x41, 0x02]])).unwrap();
508 muxer.finish().unwrap();511 muxer.finish().unwrap();
509 512
crates/engine/src/playback.rsmodified+90 -23
@@ -11,7 +11,7 @@
11 //! Drift policy stays with the caller -- this type answers "what time is it",11 //! Drift policy stays with the caller -- this type answers "what time is it",
12 //! the renderer decides which frame that means.12 //! the renderer decides which frame that means.
13 13
14-use std::path::{Path, PathBuf};14+use std::path::Path;
15 use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};15 use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
16 use std::sync::mpsc::{Receiver, TryRecvError};16 use std::sync::mpsc::{Receiver, TryRecvError};
17 use std::sync::{Arc, Mutex};17 use std::sync::{Arc, Mutex};
@@ -23,7 +23,7 @@ use crate::audio::{AudioChunk, AudioSession};
23 use crate::clock::{ClockSource, PlaybackClock};23 use crate::clock::{ClockSource, PlaybackClock};
24 use crate::decode::{DecodeSession, Frame, Worker};24 use crate::decode::{DecodeSession, Frame, Worker};
25 use crate::demux::{Demuxer, VideoMeta};25 use crate::demux::{Demuxer, VideoMeta};
26-use crate::project::{Clip, Lane, Project, Span};26+use crate::project::{Clip, Lane, Project, Source, Span};
27 27
28 /// How long the feeder waits out a full ring. The ring holds a second, so this28 /// How long the feeder waits out a full ring. The ring holds a second, so this
29 /// only has to be short next to that; it costs one wakeup per 10 ms of audio.29 /// only has to be short next to that; it costs one wakeup per 10 ms of audio.
@@ -128,7 +128,9 @@ impl PlaybackSession {
128 // `open_worker` rather than `open` purely for the worker handle: the128 // `open_worker` rather than `open` purely for the worker handle: the
129 // field has to exist from the start for the first seek to use it.129 // field has to exist from the start for the first seek to use it.
130 let (meta, stream) = DecodeSession::open_worker(&path, 0, u32::MAX)?;130 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);
132 let source = match audio {134 let source = match audio {
133 Some(_) => ClockSource::Audio,135 Some(_) => ClockSource::Audio,
134 None => ClockSource::Wall,136 None => ClockSource::Wall,
@@ -181,16 +183,16 @@ impl PlaybackSession {
181 // locals drop in reverse declaration order -- a bare worker would join183 // locals drop in reverse declaration order -- a bare worker would join
182 // its decode thread while the receiver next to it was still holding184 // its decode thread while the receiver next to it was still holding
183 // that thread parked in `send`, which is a hang (see [`FrameStream`]).185 // that thread parked in `send`, which is a hang (see [`FrameStream`]).
184- let (meta, stream) = DecodeSession::open_worker(&first, 0, u32::MAX)186+ let (meta, stream) = DecodeSession::open_worker(&first.path, 0, u32::MAX)
185- .map_err(|e| format!("source {}: {e}", first.display()))?;187+ .map_err(|e| format!("source {}: {e}", first.path.display()))?;
186- let first_audio = AudioSession::probe(&first)?;188+ let first_audio = AudioSession::probe(&first.path, first.audio_stream)?;
187 189
188 let mut counts = vec![meta.frame_count];190 let mut counts = vec![meta.frame_count];
189 for source in &doc.sources[1..] {191 for source in &doc.sources[1..] {
190- let (other, _) =192+ let (other, _) = Demuxer::open(&source.path)
191- Demuxer::open(source).map_err(|e| format!("source {}: {e}", source.display()))?;193+ .map_err(|e| format!("source {}: {e}", source.path.display()))?;
192 matches_timeline(source, &other, &meta, &first_audio)194 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()))?;
194 counts.push(other.frame_count);196 counts.push(other.frame_count);
195 }197 }
196 for (i, clip) in doc.video.iter().chain(&doc.audio).enumerate() {198 for (i, clip) in doc.video.iter().chain(&doc.audio).enumerate() {
@@ -198,7 +200,7 @@ impl PlaybackSession {
198 return Err(format!(200 return Err(format!(
199 "clip {i} ends at frame {} but {} has {} frames",201 "clip {i} ends at frame {} but {} has {} frames",
200 clip.out_frame,202 clip.out_frame,
201- doc.sources[clip.source].display(),203+ doc.sources[clip.source].path.display(),
202 counts[clip.source]204 counts[clip.source]
203 )205 )
204 .into());206 .into());
@@ -213,7 +215,7 @@ impl PlaybackSession {
213 // only a session's `drop` retires it, so a refusal above this line would215 // only a session's `drop` retires it, so a refusal above this line would
214 // leave a PipeWire stream and a thread behind for a project that never216 // leave a PipeWire stream and a thread behind for a project that never
215 // opened. Nothing before it needs the device.217 // 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);
217 let mut session = Self {219 let mut session = Self {
218 meta,220 meta,
219 frames: stream.frames,221 frames: stream.frames,
@@ -252,7 +254,7 @@ impl PlaybackSession {
252 254
253 /// The files this timeline plays from, index 0 first -- a caller needs it255 /// The files this timeline plays from, index 0 first -- a caller needs it
254 /// to name an export or a window after the media rather than the project.256 /// 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] {
256 self.project.sources()258 self.project.sources()
257 }259 }
258 260
@@ -344,7 +346,7 @@ impl PlaybackSession {
344 fn start_span(&mut self, span: Span) {346 fn start_span(&mut self, span: Span) {
345 let opened = match span.from {347 let opened = match span.from {
346 Some((source, in_frame)) => DecodeSession::open_worker(348 Some((source, in_frame)) => DecodeSession::open_worker(
347- &self.project.sources()[source],349+ &self.project.sources()[source].path,
348 in_frame,350 in_frame,
349 in_frame + span.len,351 in_frame + span.len,
350 )352 )
@@ -455,6 +457,56 @@ impl PlaybackSession {
455 self.edit(|p| p.paste(at, clip))457 self.edit(|p| p.paste(at, clip))
456 }458 }
457 459
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+
458 /// Removes the video clip at `idx` and everything under it, closing the gap510 /// Removes the video clip at `idx` and everything under it, closing the gap
459 /// on every lane. Unlike a split this *does* move every following frame, so511 /// on every lane. Unlike a split this *does* move every following frame, so
460 /// the session reseeks to wherever the playhead now points.512 /// the session reseeks to wherever the playhead now points.
@@ -479,11 +531,14 @@ impl PlaybackSession {
479 /// a refusal.531 /// a refusal.
480 pub fn import(&mut self, path: &Path) -> crate::Result<()> {532 pub fn import(&mut self, path: &Path) -> crate::Result<()> {
481 let (meta, _) = Demuxer::open(path)?;533 let (meta, _) = Demuxer::open(path)?;
482- let first = AudioSession::probe(&self.project.sources()[0])?;534+ let first = self.first_audio()?;
483- matches_timeline(path, &meta, &self.meta, &first)?;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)?;
484 539
485 let old_end = self.timeline_duration();540 let old_end = self.timeline_duration();
486- let source = self.project.import(path);541+ let source = self.project.import(path, 0);
487 // Refused only for an unknown index, and this one just came from `import`.542 // Refused only for an unknown index, and this one just came from `import`.
488 self.project.append_clip(source, meta.frame_count);543 self.project.append_clip(source, meta.frame_count);
489 // Reseek like any other edit, even though nothing before the playhead544 // Reseek like any other edit, even though nothing before the playhead
@@ -619,7 +674,10 @@ impl PlaybackSession {
619 // ear never hears it -- and a join between two *files* is just674 // ear never hears it -- and a join between two *files* is just
620 // another segment, because every segment names its own source.675 // another segment, because every segment names its own source.
621 let segs = self.project.segments_from(target, fps);676 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) {
623 Ok(Some((_, rx))) => audio.spawn_feeder(rx),681 Ok(Some((_, rx))) => audio.spawn_feeder(rx),
624 _ => false,682 _ => false,
625 };683 };
@@ -726,7 +784,7 @@ impl Drop for PlaybackSession {
726 /// [`PlaybackSession::open_project`] share them so a file refused at import is784 /// [`PlaybackSession::open_project`] share them so a file refused at import is
727 /// refused in the same words at load.785 /// refused in the same words at load.
728 fn matches_timeline(786 fn matches_timeline(
729- path: &Path,787+ source: &Source,
730 meta: &VideoMeta,788 meta: &VideoMeta,
731 timeline: &VideoMeta,789 timeline: &VideoMeta,
732 first: &Option<crate::AudioProbe>,790 first: &Option<crate::AudioProbe>,
@@ -746,9 +804,16 @@ fn matches_timeline(
746 )804 )
747 .into());805 .into());
748 }806 }
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<()> {
749 // Whole-probe equality: rate, layout and the esds fields, which the audio814 // Whole-probe equality: rate, layout and the esds fields, which the audio
750 // worker holds every source to anyway. Both silent is a match.815 // 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)?;
752 if probe != *first {817 if probe != *first {
753 return Err(match (probe, first) {818 return Err(match (probe, first) {
754 (None, _) => "the file is silent, the timeline has audio".to_string(),819 (None, _) => "the file is silent, the timeline has audio".to_string(),
@@ -771,11 +836,13 @@ fn matches_timeline(
771 /// a surprise worth showing (see836 /// a surprise worth showing (see
772 /// [`audio_disabled_reason`](PlaybackSession::audio_disabled_reason)), where a837 /// [`audio_disabled_reason`](PlaybackSession::audio_disabled_reason)), where a
773 /// file with no audio at all and a machine with no output device are not.838 /// 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>) {839+fn open_audio(path: &Path, stream: usize) -> (Option<Audio>, Option<String>) {
775- let (meta, rx) = match AudioSession::open(path) {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)]) {
776 Ok(Some(opened)) => opened,843 Ok(Some(opened)) => opened,
777- // No AAC track: silent by nature, or sound in a codec we do not have --844+ // No AAC track: silent by nature, or sound in a codec we do not
778- // and only the second of those is worth a word.845+ // have -- and only the second of those is worth a word.
779 Ok(None) => {846 Ok(None) => {
780 let reason = AudioSession::unsupported(path).ok().flatten();847 let reason = AudioSession::unsupported(path).ok().flatten();
781 if let Some(reason) = &reason {848 if let Some(reason) = &reason {
crates/engine/src/project.rsmodified+92 -24
@@ -71,6 +71,31 @@ impl Clip {
71 }71 }
72 }72 }
73 73
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+
74 /// Which lane an operation acts on. The lanes are peers: no operation reads one99 /// Which lane an operation acts on. The lanes are peers: no operation reads one
75 /// to decide what to do to the other, except the grouped ones that say so.100 /// to decide what to do to the other, except the grouped ones that say so.
76 #[derive(Clone, Copy, PartialEq, Eq, Debug)]101 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
@@ -112,7 +137,7 @@ impl Span {
112 #[derive(Clone, Debug)]137 #[derive(Clone, Debug)]
113 pub struct Project {138 pub struct Project {
114 /// Append-only: never popped, never reordered. See the module docs.139 /// Append-only: never popped, never reordered. See the module docs.
115- sources: Vec<PathBuf>,140+ sources: Vec<Source>,
116 /// Indexed by [`Lane::index`]. Each lane is sorted by `start` and disjoint.141 /// Indexed by [`Lane::index`]. Each lane is sorted by `start` and disjoint.
117 lanes: [Vec<Clip>; 2],142 lanes: [Vec<Clip>; 2],
118 /// Snapshots pushed *before* each successful edit; `undo` pops one.143 /// Snapshots pushed *before* each successful edit; `undo` pops one.
@@ -136,7 +161,9 @@ impl Project {
136 link: Some(0),161 link: Some(0),
137 };162 };
138 Self {163 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)],
140 lanes: [vec![clip], vec![clip]],167 lanes: [vec![clip], vec![clip]],
141 history: Vec::new(),168 history: Vec::new(),
142 next_link: 1,169 next_link: 1,
@@ -152,7 +179,7 @@ impl Project {
152 /// whose end overflows, a lane that is unsorted or self-overlapping, and179 /// whose end overflows, a lane that is unsorted or self-overlapping, and
153 /// the grouping rules of [`Clip::link`] below.180 /// the grouping rules of [`Clip::link`] below.
154 pub fn from_parts(181 pub fn from_parts(
155- sources: Vec<PathBuf>,182+ sources: Vec<Source>,
156 video: Vec<Clip>,183 video: Vec<Clip>,
157 audio: Vec<Clip>,184 audio: Vec<Clip>,
158 ) -> crate::Result<Self> {185 ) -> crate::Result<Self> {
@@ -200,7 +227,10 @@ impl Project {
200 // ceiling ids stop being fresh, which loses grouping, not memory.227 // ceiling ids stop being fresh, which loses grouping, not memory.
201 .map_or(0, |m| m.saturating_add(1));228 .map_or(0, |m| m.saturating_add(1));
202 Ok(Self {229 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(),
204 lanes,234 lanes,
205 history: Vec::new(),235 history: Vec::new(),
206 next_link,236 next_link,
@@ -219,20 +249,32 @@ impl Project {
219 249
220 /// The files the clips index into, in import order; index 0 is the file the250 /// The files the clips index into, in import order; index 0 is the file the
221 /// project was opened with.251 /// project was opened with.
222- pub fn sources(&self) -> &[PathBuf] {252+ pub fn sources(&self) -> &[Source] {
223 &self.sources253 &self.sources
224 }254 }
225 255
226- /// Index for `path`, appending it if it is new. Deduped by256+ /// The same list in the `(path, stream)` shape the audio engine indexes
227- /// `fs::canonicalize`, so the same file reached by two paths imports once.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.
228 /// The lanes are untouched -- see [`Project::append_clip`] -- so this pushes270 /// The lanes are untouched -- see [`Project::append_clip`] -- so this pushes
229 /// no history: a source entry alone changes nothing playable.271 /// no history: a source entry alone changes nothing playable.
230- pub fn import(&mut self, path: impl AsRef<Path>) -> usize {272+ pub fn import(&mut self, path: impl AsRef<Path>, audio_stream: usize) -> usize {
231- let path = canonical(path.as_ref());273+ let source = Source::new(path, audio_stream);
232- match self.sources.iter().position(|s| *s == path) {274+ match self.sources.iter().position(|s| *s == source) {
233 Some(idx) => idx,275 Some(idx) => idx,
234 None => {276 None => {
235- self.sources.push(path);277+ self.sources.push(source);
236 self.sources.len() - 1278 self.sources.len() - 1
237 }279 }
238 }280 }
@@ -268,7 +310,7 @@ impl Project {
268 /// nothing plays refuse a future load. New indexes are assigned in order of310 /// nothing plays refuse a future load. New indexes are assigned in order of
269 /// first use -- video lane first, then audio -- so the same project always311 /// first use -- video lane first, then audio -- so the same project always
270 /// emits the same bytes.312 /// 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>) {
272 let mut moved = vec![None; self.sources.len()];314 let mut moved = vec![None; self.sources.len()];
273 let mut sources = Vec::new();315 let mut sources = Vec::new();
274 let mut lanes = self.lanes.clone();316 let mut lanes = self.lanes.clone();
@@ -1252,7 +1294,7 @@ mod tests {
1252 /// of source 0 then [0,4) of source 1.1294 /// of source 0 then [0,4) of source 1.
1253 fn two_sources() -> Project {1295 fn two_sources() -> Project {
1254 let mut p = three();1296 let mut p = three();
1255- let s = p.import(FILE2);1297+ let s = p.import(FILE2, 0);
1256 assert_eq!(s, 1);1298 assert_eq!(s, 1);
1257 assert!(p.append_clip(s, 4));1299 assert!(p.append_clip(s, 4));
1258 p1300 p
@@ -1262,11 +1304,18 @@ mod tests {
1262 fn import_dedups_and_appends() {1304 fn import_dedups_and_appends() {
1263 let mut p = Project::single(FILE, 9);1305 let mut p = Project::single(FILE, 9);
1264 assert_eq!(p.sources().len(), 1, "the opened file is source 0");1306 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");1307+ assert_eq!(p.import(FILE, 0), 0, "reimporting the open file reuses 0");
1266- assert_eq!(p.import(FILE2), 1);1308+ assert_eq!(p.import(FILE2, 0), 1);
1267- assert_eq!(p.import(FILE2), 1, "second import of the same path");1309+ assert_eq!(p.import(FILE2, 0), 1, "second import of the same path");
1268- assert_eq!(p.sources().len(), 2);1310+ // ...but the same file on another audio stream is another source: it is
1269- assert!(!p.append_clip(2, 5), "unknown source index");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");
1270 assert_eq!(p.clips().len(), 1, "a refusal changes nothing");1319 assert_eq!(p.clips().len(), 1, "a refusal changes nothing");
1271 1320
1272 // Two spellings of one real file are one source: this is the case the1321 // Two spellings of one real file are one source: this is the case the
@@ -1274,7 +1323,7 @@ mod tests {
1274 let here = concat!(env!("CARGO_MANIFEST_DIR"), "/src/project.rs");1323 let here = concat!(env!("CARGO_MANIFEST_DIR"), "/src/project.rs");
1275 let detour = concat!(env!("CARGO_MANIFEST_DIR"), "/src/../src/project.rs");1324 let detour = concat!(env!("CARGO_MANIFEST_DIR"), "/src/../src/project.rs");
1276 let mut p = Project::single(here, 9);1325 let mut p = Project::single(here, 9);
1277- assert_eq!(p.import(detour), 0);1326+ assert_eq!(p.import(detour, 0), 0);
1278 assert_eq!(p.sources().len(), 1);1327 assert_eq!(p.sources().len(), 1);
1279 }1328 }
1280 1329
@@ -1362,20 +1411,20 @@ mod tests {
1362 let mut p = two_sources();1411 let mut p = two_sources();
1363 assert!(p.undo());1412 assert!(p.undo());
1364 let (sources, video, audio) = p.without_orphan_sources();1413 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");
1366 assert_eq!(video, three().clips(), "the clips are untouched");1415 assert_eq!(video, three().clips(), "the clips are untouched");
1367 assert_eq!(audio, three().lane(Lane::Audio));1416 assert_eq!(audio, three().lane(Lane::Audio));
1368 1417
1369 // Three sources where only the middle one is orphaned: the survivors1418 // Three sources where only the middle one is orphaned: the survivors
1370 // renumber, and the clips follow.1419 // renumber, and the clips follow.
1371 let mut p = Project::single(FILE, 9);1420 let mut p = Project::single(FILE, 9);
1372- assert_eq!(p.import(FILE2), 1);1421+ assert_eq!(p.import(FILE2, 0), 1);
1373- assert_eq!(p.import("/nonexistent/c.mp4"), 2);1422+ assert_eq!(p.import("/nonexistent/c.mp4", 0), 2);
1374 assert!(p.append_clip(2, 4));1423 assert!(p.append_clip(2, 4));
1375 let (sources, video, audio) = p.without_orphan_sources();1424 let (sources, video, audio) = p.without_orphan_sources();
1376 assert_eq!(1425 assert_eq!(
1377 sources,1426 sources,
1378- vec![PathBuf::from(FILE), PathBuf::from("/nonexistent/c.mp4")]1427+ vec![Source::new(FILE, 0), Source::new("/nonexistent/c.mp4", 0)]
1379 );1428 );
1380 assert_eq!(video.iter().map(|c| c.source).collect::<Vec<_>>(), [0, 1]);1429 assert_eq!(video.iter().map(|c| c.source).collect::<Vec<_>>(), [0, 1]);
1381 // ...and what comes out is loadable, with the same timeline.1430 // ...and what comes out is loadable, with the same timeline.
@@ -1423,7 +1472,7 @@ mod tests {
1423 /// because what an edit produces is what a save writes and a load reads.1472 /// because what an edit produces is what a save writes and a load reads.
1424 #[test]1473 #[test]
1425 fn a_link_id_is_never_two_clips_of_one_lane() {1474 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)];
1427 let linked = |start, in_frame, out_frame, link| Clip {1476 let linked = |start, in_frame, out_frame, link| Clip {
1428 start,1477 start,
1429 in_frame,1478 in_frame,
@@ -1509,6 +1558,25 @@ mod tests {
1509 assert!(p.regroup(30), "only the audio lane can rejoin");1558 assert!(p.regroup(30), "only the audio lane can rejoin");
1510 assert!(p.split(60));1559 assert!(p.split(60));
1511 reloads(&p, "lift, regroup one lane, split");1560 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+ );
1512 }1580 }
1513 1581
1514 /// The same claim, swept: random op sequences off the public surface, the1582 /// 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;
6 6
7 use crate::AudioSession;7 use crate::AudioSession;
8 8
9-/// `(min, max)` of every sample in each `1 / buckets_per_sec` window of `path`'s9+/// `(min, max)` of every sample in each `1 / buckets_per_sec` window of
10-/// audio, from media time 0 (priming already trimmed by the decoder). Channels10+/// `stream` of `path`'s audio, from media time 0 (priming already trimmed by
11-/// are folded together: one envelope per clip, not per channel.11+/// the decoder). Channels are folded together: one envelope per clip, not per
12+/// channel.
12 ///13 ///
13 /// `Ok(None)` for a file with no audio track — a silent source is valid, not a14 /// `Ok(None)` for a file with no audio track — a silent source is valid, not a
14 /// failure. Values are clamped to `[-1.0, 1.0]`, and a bucket's pair always15 /// failure. Values are clamped to `[-1.0, 1.0]`, and a bucket's pair always
15 /// straddles zero, so silence draws as a flat line.16 /// straddles zero, so silence draws as a flat line.
16 ///17 ///
17 /// Decoding the whole file runs at ~1700x realtime, but it is still linear in18 /// 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.
19 pub fn peaks(22 pub fn peaks(
20 path: impl AsRef<Path>,23 path: impl AsRef<Path>,
24+ stream: usize,
21 buckets_per_sec: u32,25 buckets_per_sec: u32,
22 ) -> crate::Result<Option<Vec<(f32, f32)>>> {26 ) -> 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 {
24 return Ok(None);31 return Ok(None);
25 };32 };
26 // Kept fractional: 44100 / 30 is not whole, and rounding it would drift a33 // Kept fractional: 44100 / 30 is not whole, and rounding it would drift a
@@ -62,7 +69,7 @@ mod tests {
62 69
63 #[test]70 #[test]
64 fn peaks_follow_the_1hz_volume_pulse() {71 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)
66 .expect("open")73 .expect("open")
67 .expect("test_av.mp4 has an audio track");74 .expect("test_av.mp4 has an audio track");
68 // 5 s of source; the container's tail padding may spill one bucket.75 // 5 s of source; the container's tail padding may spill one bucket.
@@ -112,9 +119,28 @@ mod tests {
112 #[test]119 #[test]
113 fn video_only_source_has_no_peaks() {120 fn video_only_source_has_no_peaks() {
114 assert!(121 assert!(
115- peaks(asset("test_baseline.mp4"), BPS)122+ peaks(asset("test_baseline.mp4"), 0, BPS)
116 .expect("open")123 .expect("open")
117 .is_none()124 .is_none()
118 );125 );
119 }126 }
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+ }
120 }146 }
crates/engine/tests/audio_multi.rsmodified+5 -3
@@ -189,19 +189,21 @@ fn each_source_ends_where_its_own_track_does() {
189 189
190 #[test]190 #[test]
191 fn probe_reads_the_import_policy_fields() {191 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)
193 .expect("probe")193 .expect("probe")
194 .expect("test_av.mp4 has audio");194 .expect("test_av.mp4 has audio");
195 assert_eq!(av.channels, 2);195 assert_eq!(av.channels, 2);
196 assert_eq!(av.params.sample_rate, RATE as u32);196 assert_eq!(av.params.sample_rate, RATE as u32);
197 assert_eq!(197 assert_eq!(
198- AudioSession::probe(asset("test_av2.mp4")).unwrap().unwrap(),198+ AudioSession::probe(asset("test_av2.mp4"), 0)
199+ .unwrap()
200+ .unwrap(),
199 av,201 av,
200 "the fixtures are the matching pair import must accept"202 "the fixtures are the matching pair import must accept"
201 );203 );
202 for silent in ["test_baseline.mp4", "test_mismatch.mp4"] {204 for silent in ["test_baseline.mp4", "test_mismatch.mp4"] {
203 assert!(205 assert!(
204- AudioSession::probe(asset(silent)).unwrap().is_none(),206+ AudioSession::probe(asset(silent), 0).unwrap().is_none(),
205 "{silent} has no audio track"207 "{silent} has no audio track"
206 );208 );
207 }209 }
crates/engine/tests/export.rsmodified+83 -2
@@ -23,6 +23,7 @@ use engine::export::ExportSettings;
23 use engine::hw::HwEncoder;23 use engine::hw::HwEncoder;
24 use engine::mux::{Mp4Muxer, VideoParams, parameter_sets};24 use engine::mux::{Mp4Muxer, VideoParams, parameter_sets};
25 use engine::project::Lane;25 use engine::project::Lane;
26+use engine::project::Source;
26 use engine::{DecodeSession, ExportHandle, PlaybackSession, Project};27 use engine::{DecodeSession, ExportHandle, PlaybackSession, Project};
27 28
28 const FPS: f64 = 30.0;29 const FPS: f64 = 30.0;
@@ -174,6 +175,86 @@ fn exports_an_edited_timeline_in_hardware() {
174 round_trip("hw", Duration::from_secs(60));175 round_trip("hw", Duration::from_secs(60));
175 }176 }
176 177
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+
177 /// `test_av[0,120)` then the whole of `test_av2`: the last second of the first258 /// `test_av[0,120)` then the whole of `test_av2`: the last second of the first
178 /// source is deleted, so timeline frame 120 is both a cut and a file change --259 /// source is deleted, so timeline frame 120 is both a cut and a file change --
179 /// the join the multi-source export exists for.260 /// the join the multi-source export exists for.
@@ -183,7 +264,7 @@ fn two_sources() -> Project {
183 assert_eq!((av.width, av.height), (av2.width, av2.height), "policy a");264 assert_eq!((av.width, av.height), (av2.width, av2.height), "policy a");
184 265
185 let mut project = Project::single(asset("test_av.mp4"), av.frame_count);266 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);
187 assert_eq!(second, 1, "a second file is a second source");268 assert_eq!(second, 1, "a second file is a second source");
188 assert!(project.append_clip(second, av2.frame_count));269 assert!(project.append_clip(second, av2.frame_count));
189 assert!(project.split(120), "cut a second before the end of test_av");270 assert!(project.split(120), "cut a second before the end of test_av");
@@ -323,7 +404,7 @@ fn a_vanished_source_fails_the_export() {
323 let mut project = Project::single(&baseline, meta.frame_count);404 let mut project = Project::single(&baseline, meta.frame_count);
324 assert!(project.split(5));405 assert!(project.split(5));
325 assert!(project.delete(1));406 assert!(project.delete(1));
326- let second = project.import(&doomed);407+ let second = project.import(&doomed, 0);
327 assert!(project.append_clip(second, meta.frame_count));408 assert!(project.append_clip(second, meta.frame_count));
328 assert!(project.split(10));409 assert!(project.split(10));
329 assert!(project.delete(2));410 assert!(project.delete(2));
crates/engine/tests/playback.rsmodified+1 -1
@@ -879,7 +879,7 @@ fn undo_after_import_is_one_step() {
879 // exposes sources through `clip_spans_by_source`, and the undone clip is879 // exposes sources through `clip_spans_by_source`, and the undone clip is
880 // exactly the one that named it.880 // exactly the one that named it.
881 let mut project = engine::Project::single(asset("test_av.mp4"), 150);881 let mut project = engine::Project::single(asset("test_av.mp4"), 150);
882- let source = project.import(&av2);882+ let source = project.import(&av2, 0);
883 assert!(project.append_clip(source, 120));883 assert!(project.append_clip(source, 120));
884 assert!(project.undo());884 assert!(project.undo());
885 assert_eq!(project.clips().len(), 1);885 assert_eq!(project.clips().len(), 1);
crates/engine/tests/saveload.rsmodified+99 -7
@@ -10,6 +10,7 @@
10 use std::path::{Path, PathBuf};10 use std::path::{Path, PathBuf};
11 11
12 use engine::PlaybackSession;12 use engine::PlaybackSession;
13+use engine::project::Source;
13 14
14 fn asset(name: &str) -> PathBuf {15 fn asset(name: &str) -> PathBuf {
15 PathBuf::from(env!("CARGO_MANIFEST_DIR"))16 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
@@ -32,6 +33,73 @@ fn copy_in(dir: &Path, name: &str) -> PathBuf {
32 to33 to
33 }34 }
34 35
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+
35 /// Two files, four clips, one of them deleted, playhead at 3 s -- a timeline103 /// Two files, four clips, one of them deleted, playhead at 3 s -- a timeline
36 /// with something to lose in every field.104 /// with something to lose in every field.
37 fn edited(dir: &Path) -> PlaybackSession {105 fn edited(dir: &Path) -> PlaybackSession {
@@ -48,7 +116,7 @@ fn edited(dir: &Path) -> PlaybackSession {
48 }116 }
49 117
50 /// What has to survive a round trip, all of it public API.118 /// 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) {
52 (120 (
53 session.clip_spans_by_source(),121 session.clip_spans_by_source(),
54 session.sources().to_vec(),122 session.sources().to_vec(),
@@ -58,9 +126,9 @@ fn shape(session: &PlaybackSession) -> (Vec<(f64, f64, usize)>, Vec<PathBuf>, f6
58 126
59 /// The version-1 promise: a file written before the lanes existed still opens,127 /// The version-1 promise: a file written before the lanes existed still opens,
60 /// as one grouped video+audio pair per clip laid end to end, and saving it128 /// 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.
62 #[test]130 #[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() {
64 let dir = scratch("v1");132 let dir = scratch("v1");
65 copy_in(&dir, "test_av.mp4");133 copy_in(&dir, "test_av.mp4");
66 let path = dir.join("old.edith");134 let path = dir.join("old.edith");
@@ -88,11 +156,11 @@ fn a_version_1_project_loads_fully_grouped_and_saves_as_version_2() {
88 "playhead kept"156 "playhead kept"
89 );157 );
90 158
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.
92 let v2 = dir.join("new.edith");160 let v2 = dir.join("new.edith");
93 loaded.save_project(&v2).expect("save");161 loaded.save_project(&v2).expect("save");
94 let text = std::fs::read_to_string(&v2).expect("read back");162 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}");
96 assert_eq!(164 assert_eq!(
97 text.lines().filter(|l| l.starts_with("video ")).count(),165 text.lines().filter(|l| l.starts_with("video ")).count(),
98 2,166 2,
@@ -109,6 +177,25 @@ fn a_version_1_project_loads_fully_grouped_and_saves_as_version_2() {
109 let third = dir.join("third.edith");177 let third = dir.join("third.edith");
110 again.save_project(&third).expect("save");178 again.save_project(&third).expect("save");
111 assert_eq!(std::fs::read(&third).expect("read"), text.as_bytes());179 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+ );
112 }199 }
113 200
114 #[test]201 #[test]
@@ -160,7 +247,7 @@ fn a_folder_of_media_and_its_project_can_be_moved() {
160 let moved = PlaybackSession::open_project(&to.join("edit.edith")).expect("open the copy");247 let moved = PlaybackSession::open_project(&to.join("edit.edith")).expect("open the copy");
161 assert_eq!(moved.timeline_duration(), 6.0);248 assert_eq!(moved.timeline_duration(), 6.0);
162 assert!(249 assert!(
163- moved.sources().iter().all(|s| s.starts_with(&to)),250+ moved.sources().iter().all(|s| s.path.starts_with(&to)),
164 "sources did not follow the folder: {:?}",251 "sources did not follow the folder: {:?}",
165 moved.sources()252 moved.sources()
166 );253 );
@@ -321,7 +408,12 @@ fn malformed_files_are_numbered_errors_and_never_panics() {
321 let good = "edith 1\nplayhead 0\nsource test_av.mp4\nclip 0 30 0\n";408 let good = "edith 1\nplayhead 0\nsource test_av.mp4\nclip 0 30 0\n";
322 409
323 for (text, want) in [410 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"),
325 ("not a project at all\n", "line 1"),417 ("not a project at all\n", "line 1"),
326 // Dialects do not mix: lane lines are v2's, `clip` is v1's.418 // Dialects do not mix: lane lines are v2's, `clip` is v1's.
327 ("edith 2\nsource test_av.mp4\nclip 0 30 0\n", "line 3"),419 ("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 \
48 -f lavfi -i "sine=frequency=440:duration=2" \48 -f lavfi -i "sine=frequency=440:duration=2" \
49 -map 0:v -map 1:a -c:v libx264 -profile:v baseline -pix_fmt yuv420p \49 -map 0:v -map 1:a -c:v libx264 -profile:v baseline -pix_fmt yuv420p \
50 -c:a ac3 -b:a 192k assets/test_ac3.mp450 -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
51 # Mismatch fixture: different resolution and no audio track at all, so import68 # Mismatch fixture: different resolution and no audio track at all, so import
52 # has something concrete to refuse.69 # has something concrete to refuse.
53 ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \70 ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \