forge
Explore
Log in

Don't you dare go Hollow

Every audio stream is a row, and the picked one plays and exports

Browse files at this commit

ecb5e06fad9ec596270bafa0c4f376daacc008b9Ahmet Kaan GümüşParent: 92d90b1
  • feat
    • every audio stream is a row, and the picked one plays and exports
Show full message
✨ feat(library): every audio stream is a row, and the picked one plays and exports

A file with one audio track per language is one row per track now, not one row
per file. The engine carries the pick end to end: a source is a (file, audio
stream) pair, .edith v3 writes the stream on the source line, playback opens it
and — the trap this closes — the export copies *that* stream's packets rather
than always stream 0.

Streams that cannot go on the timeline are listed greyed with the reason
instead of hidden: a codec we cannot read, or a rate/layout that cannot share
one output device and one copied AAC track with the rest of the timeline (there
is no resampler here and no AAC encoder to write a join with). place_stream_at
is the one door a row goes through, and it refuses those in the engine's own
words.

- v2 and v1 files still load: no stream field means stream 0, which is all
  those dialects could play; saving either writes v3.
- Waveform peaks are keyed by file *and* stream, so two tracks of one file
  cannot draw each other's envelope.
- Library swatches and clip tints follow the *file*, so a file's streams share
  one colour in the panel and on the lanes.
- assets/test_multilang.mp4: two AAC 44.1k stereo streams (und, fra), the shape
  real multi-language media has and the one where a second stream is placeable.

12 changed files +1227 -311

crates/app/src/main.rsmodified+638 -177
@@ -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,
@@ -183,10 +184,10 @@ enum Wave {
183 Peaks(Arc<Vec<(f32, f32)>>),184 Peaks(Arc<Vec<(f32, f32)>>),
184 }185 }
185 186
186-/// A library row being dragged. The source index and nothing else: the row is187+/// A library row being dragged: the file and which of its audio streams that
187-/// only a way of naming a source, and where it lands does not change what is188+/// row is, which is the whole of what a row names. Where it lands does not
188-/// inserted.189+/// change what is inserted.
189-struct AssetDrag(usize);190+struct AssetDrag(PathBuf, usize);
190 191
191 struct Player {192 struct Player {
192 /// The timeline, once there is one. A run with no file opens without it and193 /// The timeline, once there is one. A run with no file opens without it and
@@ -215,16 +216,21 @@ struct Player {
215 /// screen, but Lift has to know which half it was aimed at. Indices move216 /// screen, but Lift has to know which half it was aimed at. Indices move
216 /// under every edit, so this is cleared by all of them.217 /// under every edit, so this is cleared by all of them.
217 selected: Option<(Lane, usize)>,218 selected: Option<(Lane, usize)>,
218- /// Which library row is picked, as an index into the session's sources.219+ /// Which library row is picked: the file and the audio stream that row
219- /// Its own selection and not the timeline's: Delete keeps acting on the220+ /// names, which is what an insert needs and what survives a row list being
220- /// clip that was clicked in a lane, whatever the library is showing. Source221+ /// rebuilt. Its own selection and not the timeline's: Delete keeps acting
221- /// indexes are forever (project.rs:264), so this cannot go stale under an222+ /// on the clip that was clicked in a lane, whatever the library is showing.
222- /// edit -- only a new session clears it.223+ selected_asset: Option<(PathBuf, usize)>,
223- selected_asset: Option<usize>,
224 /// What is known about each source's audio, taken once and kept. Keyed on224 /// What is known about each source's audio, taken once and kept. Keyed on
225- /// the path, and the key is inserted the moment the decode is *started*:225+ /// the path *and stream* -- two streams of one file are two envelopes -- and
226- /// presence means "asked", so a repaint mid-decode cannot ask again.226+ /// the key is inserted the moment the decode is *started*: presence means
227- waves: HashMap<PathBuf, Wave>,227+ /// "asked", so a repaint mid-decode cannot ask again.
228+ waves: HashMap<(PathBuf, usize), Wave>,
229+ /// Which audio streams each imported file has, as its header describes
230+ /// them: one library row per entry. Keyed and filled like `waves` --
231+ /// presence means "asked" -- and an empty list is a silent file, which is
232+ /// exactly one row and no stream tags.
233+ streams: HashMap<PathBuf, Vec<StreamInfo>>,
228 /// The copied clip. Frame ranges only, so it survives the clip it was taken234 /// The copied clip. Frame ranges only, so it survives the clip it was taken
229 /// from being deleted -- and it outlives the selection.235 /// from being deleted -- and it outlives the selection.
230 clipboard: Option<Clip>,236 clipboard: Option<Clip>,
@@ -474,7 +480,8 @@ impl Player {
474 }480 }
475 }481 }
476 482
477- /// Starts a peak decode for every source that has arrived since the last483+ /// Starts a peak decode -- and a stream probe -- for every source that has
484+ /// arrived since the last
478 /// repaint. One call from the render rather than three at the doors,485 /// repaint. One call from the render rather than three at the doors,
479 /// because argv, an import and a project load are all doors and only this486 /// because argv, an import and a project load are all doors and only this
480 /// one is guaranteed to run after each of them.487 /// one is guaranteed to run after each of them.
@@ -485,16 +492,35 @@ impl Player {
485 /// meanwhile and the repaint comes with the peaks. The entry is written492 /// meanwhile and the repaint comes with the peaks. The entry is written
486 /// *before* the spawn, so the sixty repaints that happen while a decode runs493 /// *before* the spawn, so the sixty repaints that happen while a decode runs
487 /// start no further ones.494 /// start no further ones.
488- fn cache_waves(&mut self, cx: &mut Context<Self>) {495+ fn cache_media(&mut self, cx: &mut Context<Self>) {
489 let Some(session) = &self.session else {496 let Some(session) = &self.session else {
490 return;497 return;
491 };498 };
492- for path in unseen_sources(session.sources(), &self.waves) {499+ // Which audio streams each file has, for the library's rows. Header
493- self.waves.insert(path.clone(), Wave::Loading);500+ // only, but a big file's sample tables are not free to parse, so it
494- let decoded = cx.background_executor().spawn({501+ // goes off the render thread like the peaks do.
502+ for path in unseen_paths(session.sources(), &self.streams) {
503+ self.streams.insert(path.clone(), Vec::new());
504+ let probed = cx.background_executor().spawn({
495 let path = path.clone();505 let path = path.clone();
506+ async move { engine::AudioSession::probe_streams(&path).unwrap_or_default() }
507+ });
508+ cx.spawn(async move |this, cx| {
509+ let probed = probed.await;
510+ this.update(cx, |this, cx| {
511+ this.streams.insert(path, probed);
512+ cx.notify();
513+ })
514+ .ok();
515+ })
516+ .detach();
517+ }
518+ for key in unseen_sources(session.sources(), &self.waves) {
519+ self.waves.insert(key.clone(), Wave::Loading);
520+ let decoded = cx.background_executor().spawn({
521+ let (path, stream) = key.clone();
496 async move {522 async move {
497- engine::waveform::peaks(&path, WAVE_BPS)523+ engine::waveform::peaks(&path, stream, WAVE_BPS)
498 .ok()524 .ok()
499 .flatten()525 .flatten()
500 .map(|peaks| Arc::new(normalise(peaks)))526 .map(|peaks| Arc::new(normalise(peaks)))
@@ -504,7 +530,7 @@ impl Player {
504 let decoded = decoded.await;530 let decoded = decoded.await;
505 this.update(cx, |this, cx| {531 this.update(cx, |this, cx| {
506 this.waves.insert(532 this.waves.insert(
507- path,533+ key,
508 match decoded {534 match decoded {
509 Some(peaks) => Wave::Peaks(peaks),535 Some(peaks) => Wave::Peaks(peaks),
510 // Either no audio track or a file we could not read536 // Either no audio track or a file we could not read
@@ -549,38 +575,50 @@ impl Player {
549 /// moves along rather than being painted over. Reseeks like every other575 /// moves along rather than being painted over. Reseeks like every other
550 /// edit, and drops the timeline's selection with it: the insert has just576 /// edit, and drops the timeline's selection with it: the insert has just
551 /// moved the indices it pointed at.577 /// moved the indices it pointed at.
552- fn insert_source(&mut self, source: usize, cx: &mut Context<Self>) {578+ fn insert_source(&mut self, path: &Path, stream: usize, cx: &mut Context<Self>) {
553 if self.exporting().is_some() {579 if self.exporting().is_some() {
554 return;580 return;
555 }581 }
556- let clip = self.session.as_ref().and_then(|session| {582+ let frames = self.session.as_ref().map_or(0, |session| {
557- let frames = source_frames(lane_clips(session), source);583+ source_frames(lane_clips(session), session.sources(), path)
558- // Zero means nothing on the timeline plays from that file any more
559- // -- an undone import leaves the source entry behind (project.rs:264)
560- // -- so there is no length to insert and no file to ask for one.
561- (frames > 0).then_some(Clip {
562- start: 0,
563- in_frame: 0,
564- out_frame: frames,
565- source,
566- link: None,
567- })
568 });584 });
569- let added = match (&mut self.session, clip) {585+ // Zero means nothing on the timeline plays from that file any more
570- (Some(session), Some(clip)) => session.paste_at(session.now(), clip),586+ // -- an undone import leaves the source entry behind (project.rs:264)
571- _ => false,587+ // -- so there is no length to insert and no file to ask for one.
588+ let placed = match (&mut self.session, frames) {
589+ (Some(session), 1..) => session.place_stream_at(session.now(), path, stream, frames),
590+ _ => Ok(false),
572 };591 };
573- if added {592+ match placed {
574- self.selected = None;593+ Ok(true) => {
575- self.reset_after_reseek();594+ self.selected = None;
576- } else {595+ self.reset_after_reseek();
577- self.notice = Some(596+ }
578- "NOTHING ADDED — no clip on the timeline plays from that file any more".into(),597+ // The engine's own words: a stream that cannot join this timeline
579- );598+ // says which property disagrees, exactly as a refused import does.
599+ Err(e) => self.notice = Some(format!("NOTHING ADDED — {e}").into()),
600+ Ok(false) => {
601+ self.notice = Some(
602+ "NOTHING ADDED — no clip on the timeline plays from that file any more".into(),
603+ )
604+ }
580 }605 }
581 cx.notify();606 cx.notify();
582 }607 }
583 608
609+ /// The rate and layout the whole timeline's audio is, taken from source 0's
610+ /// own stream: what a library row has to match to be placeable. `None`
611+ /// until that file has been probed, and then nothing is greyed for it.
612+ fn timeline_audio(&self) -> Option<(u32, u16)> {
613+ let first = self.session.as_ref()?.sources().first()?;
614+ let info = self
615+ .streams
616+ .get(&first.path)?
617+ .iter()
618+ .find(|s| s.index == first.audio_stream)?;
619+ Some((info.sample_rate, info.channels))
620+ }
621+
584 /// Appends a file to the end of the timeline. A drop is not a key press, so622 /// Appends a file to the end of the timeline. A drop is not a key press, so
585 /// the export guard on the key handler does not cover it and this checks for623 /// the export guard on the key handler does not cover it and this checks for
586 /// itself. The engine reseeks, so like a delete it owes the flag reset; a624 /// itself. The engine reseeks, so like a delete it owes the flag reset; a
@@ -670,7 +708,7 @@ impl Player {
670 self.fps = session.meta().frame_rate;708 self.fps = session.meta().frame_rate;
671 // A project is named after itself but still exports beside its709 // A project is named after itself but still exports beside its
672 // media: that is the only place an export has ever landed.710 // media: that is the only place an export has ever landed.
673- self.export_path = export_path(&session.sources()[0]);711+ self.export_path = export_path(&session.sources()[0].path);
674 self.session = Some(session);712 self.session = Some(session);
675 self.apply_volume();713 self.apply_volume();
676 self.project_path = path.to_path_buf();714 self.project_path = path.to_path_buf();
@@ -936,7 +974,7 @@ impl Render for Player {
936 // Every way a source can arrive -- argv, an import, a project load --974 // Every way a source can arrive -- argv, an import, a project load --
937 // has been through a repaint by the time its clips are drawn, so this975 // has been through a repaint by the time its clips are drawn, so this
938 // is the one place that has to notice a new one.976 // is the one place that has to notice a new one.
939- self.cache_waves(cx);977+ self.cache_media(cx);
940 // What the compositor calls this window. Pushed only when it changes:978 // What the compositor calls this window. Pushed only when it changes:
941 // it is a protocol round trip and this runs at vsync.979 // it is a protocol round trip and this runs at vsync.
942 let title = window_title(&self.name);980 let title = window_title(&self.name);
@@ -1207,81 +1245,108 @@ impl Player {
1207 // the door (the import policy, ledger:436), so the session's own meta1245 // the door (the import policy, ledger:436), so the session's own meta
1208 // describes every row and nothing has to be probed to say so.1246 // describes every row and nothing has to be probed to say so.
1209 let meta = self.session.as_ref().map(PlaybackSession::meta);1247 let meta = self.session.as_ref().map(PlaybackSession::meta);
1210- let rows: Vec<_> = sources1248+ let clips: Vec<Clip> = self
1211- .iter()1249+ .session
1212- .enumerate()1250+ .as_ref()
1213- .map(|(i, path)| {1251+ .map_or_else(Vec::new, |session| lane_clips(session).copied().collect());
1214- let picked = self.selected_asset == Some(i);1252+ let rows: Vec<_> = library_rows(sources, &self.streams, self.timeline_audio(), |path| {
1215- let frames = self1253+ source_frames(clips.iter(), sources, path)
1216- .session1254+ })
1217- .as_ref()1255+ .into_iter()
1218- .map_or(0, |session| source_frames(lane_clips(session), i));1256+ .enumerate()
1219- let name: SharedString = file_name(path).into();1257+ .map(|(i, row)| {
1220- let tip: SharedString = match meta {1258+ let picked = self
1221- Some(meta) => format!(1259+ .selected_asset
1222- "{} — {}x{} @ {:.2} fps · drag onto a lane, or Add at playhead",1260+ .as_ref()
1223- path.display(),1261+ .is_some_and(|p| *p == (row.path.clone(), row.stream));
1224- meta.width,1262+ let name: SharedString = row.name.clone().into();
1225- meta.height,1263+ let tip: SharedString = match (&row.unusable, meta) {
1226- meta.frame_rate1264+ // A greyed row says why in full, where its length would be:
1227- ),1265+ // the list is the one place the file's own tracks are named.
1228- None => path.display().to_string(),1266+ (Some(why), _) => format!("{} — {why}", row.path.display()),
1229- }1267+ (None, Some(meta)) => format!(
1230- .into();1268+ "{} — {}x{} @ {:.2} fps · drag onto a lane, or Add at playhead",
1231- let ghost = name.clone();1269+ row.path.display(),
1232- div()1270+ meta.width,
1233- .id(("asset", i))1271+ meta.height,
1234- .flex_none()1272+ meta.frame_rate
1235- .h(px(ROW_H))1273+ ),
1236- .flex()1274+ (None, None) => row.path.display().to_string(),
1237- .items_center()1275+ }
1238- .gap(px(6.))1276+ .into();
1239- .pr(px(6.))1277+ let ghost = name.clone();
1240- .rounded(px(3.))1278+ // What the second line says: the stream, then either its length or
1241- .cursor_pointer()1279+ // the reason it cannot be used.
1242- .hover(|s| s.bg(rgb(HOVER)))1280+ let under = match &row.unusable {
1243- .when(picked, |d| d.bg(rgb(SELECTED)).border_1())1281+ Some(why) => join_detail(&row.detail, why),
1244- .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into())1282+ None => join_detail(
1245- .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {1283+ &row.detail,
1246- this.selected_asset = Some(i);1284+ &timecode(f64::from(row.frames) / self.fps, self.fps),
1247- cx.notify();1285+ ),
1248- }))1286+ };
1249- // The drag carries the row's source and the row's name: one1287+ let usable = row.unusable.is_none();
1250- // for the drop to insert, one for the pointer to carry, so1288+ let (path, stream) = (row.path.clone(), row.stream);
1251- // what is being dragged is legible on the way down.1289+ let dragged = (path.clone(), stream);
1252- .on_drag(AssetDrag(i), move |_, _, _, cx| {1290+ div()
1253- cx.new(|_| Tip(ghost.clone()))1291+ .id(("asset", i))
1254- })1292+ .flex_none()
1255- // Full height and hard against the edge: the tint reads as1293+ .h(px(ROW_H))
1256- // the lane's colour continuing into the list, not as a chip1294+ .flex()
1257- // that happens to be near it.1295+ .items_center()
1258- .child(1296+ .gap(px(6.))
1259- div()1297+ .pr(px(6.))
1260- .flex_none()1298+ .rounded(px(3.))
1261- .w(px(SWATCH_W))1299+ // A row that cannot be placed takes no click and no drag, and
1262- .h_full()1300+ // reads as unavailable rather than merely unlucky.
1263- .rounded(px(2.))1301+ .when(!usable, |d| d.text_color(rgb(INK_DIM)).opacity(0.55))
1264- .bg(rgb(source_tint(i))),1302+ .when(usable, |d| {
1265- )1303+ d.cursor_pointer()
1266- .child(1304+ .hover(|s| s.bg(rgb(HOVER)))
1267- div()1305+ .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
1268- .flex_1()1306+ this.selected_asset = Some((path.clone(), stream));
1269- .min_w(px(0.))1307+ cx.notify();
1270- .flex()1308+ }))
1271- .flex_col()1309+ // The drag carries the row's file and stream and the
1272- // Two lines rather than two columns: at the width1310+ // row's name: one for the drop to insert, one for the
1273- // this panel yields to, a name and a timecode side1311+ // pointer to carry, so what is being dragged is legible
1274- // by side leave room for neither.1312+ // on the way down.
1275- .child(div().truncate().text_size(px(11.)).child(name))1313+ .on_drag(AssetDrag(dragged.0, dragged.1), move |_, _, _, cx| {
1276- .child(1314+ cx.new(|_| Tip(ghost.clone()))
1277- div()1315+ })
1278- .text_size(px(10.))1316+ })
1279- .text_color(rgb(INK_DIM))1317+ .when(picked, |d| d.bg(rgb(SELECTED)).border_1())
1280- .child(timecode(f64::from(frames) / self.fps, self.fps)),1318+ .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into())
1281- ),1319+ // Full height and hard against the edge: the tint reads as
1282- )1320+ // the lane's colour continuing into the list, not as a chip
1283- })1321+ // that happens to be near it.
1284- .collect();1322+ .child(
1323+ div()
1324+ .flex_none()
1325+ .w(px(SWATCH_W))
1326+ .h_full()
1327+ .rounded(px(2.))
1328+ .bg(rgb(source_tint(row.tint))),
1329+ )
1330+ .child(
1331+ div()
1332+ .flex_1()
1333+ .min_w(px(0.))
1334+ .flex()
1335+ .flex_col()
1336+ // Two lines rather than two columns: at the width
1337+ // this panel yields to, a name and a timecode side
1338+ // by side leave room for neither.
1339+ .child(div().truncate().text_size(px(11.)).child(name))
1340+ .child(
1341+ div()
1342+ .truncate()
1343+ .text_size(px(10.))
1344+ .text_color(rgb(INK_DIM))
1345+ .child(under),
1346+ ),
1347+ )
1348+ })
1349+ .collect();
1285 div()1350 div()
1286 .flex_none()1351 .flex_none()
1287 .w(px(width))1352 .w(px(width))
@@ -1344,10 +1409,14 @@ impl Player {
1344 Some(_) => "inserts the picked file at the playhead".to_string(),1409 Some(_) => "inserts the picked file at the playhead".to_string(),
1345 None => "click a file above first — or drag one onto a lane".to_string(),1410 None => "click a file above first — or drag one onto a lane".to_string(),
1346 },1411 },
1347- can_add(self.selected_asset, self.session.is_some(), exporting),1412+ can_add(
1413+ self.selected_asset.as_ref(),
1414+ self.session.is_some(),
1415+ exporting,
1416+ ),
1348 cx.listener(|this, _: &ClickEvent, _, cx| {1417 cx.listener(|this, _: &ClickEvent, _, cx| {
1349- if let Some(source) = this.selected_asset {1418+ if let Some((path, stream)) = this.selected_asset.clone() {
1350- this.insert_source(source, cx);1419+ this.insert_source(&path, stream, cx);
1351 }1420 }
1352 }),1421 }),
1353 ))1422 ))
@@ -1986,9 +2055,9 @@ impl Player {
1986 // Add button makes, through the same call -- at the2055 // Add button makes, through the same call -- at the
1987 // playhead, not at the pointer: clips here are placed end2056 // playhead, not at the pointer: clips here are placed end
1988 // to end, so where along the bed it landed says nothing.2057 // to end, so where along the bed it landed says nothing.
1989- .on_drop(2058+ .on_drop(cx.listener(|this, drag: &AssetDrag, _, cx| {
1990- cx.listener(|this, drag: &AssetDrag, _, cx| this.insert_source(drag.0, cx)),2059+ this.insert_source(&drag.0.clone(), drag.1, cx)
1991- )2060+ }))
1992 .drag_over::<AssetDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))2061 .drag_over::<AssetDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))
1993 .children(clips.iter().enumerate().map(|(i, clip)| {2062 .children(clips.iter().enumerate().map(|(i, clip)| {
1994 let (start, len) = (2063 let (start, len) = (
@@ -2001,12 +2070,20 @@ impl Player {
2001 // as detached before anyone clicks it.2070 // as detached before anyone clicks it.
2002 let grouped =2071 let grouped =
2003 clip.link.is_some() && others.iter().any(|o| o.link == clip.link);2072 clip.link.is_some() && others.iter().any(|o| o.link == clip.link);
2004- let tint = source_tint(clip.source);2073+ // Tinted by *file*, not by source entry: two audio
2074+ // streams of one file are two sources, and the library
2075+ // gives them one swatch because they are one file.
2076+ let tint = source_tint(
2077+ sources
2078+ .get(clip.source)
2079+ .and_then(|s| sources.iter().position(|o| o.path == s.path))
2080+ .unwrap_or(clip.source),
2081+ );
2005 let width = width_frac(len, duration);2082 let width = width_frac(len, duration);
2006- let label = sources.get(clip.source).map(|path| file_name(path));2083+ let label = sources.get(clip.source).map(|s| file_name(&s.path));
2007 let wave = sources2084 let wave = sources
2008 .get(clip.source)2085 .get(clip.source)
2009- .and_then(|path| self.waves.get(path))2086+ .and_then(|s| self.waves.get(&(s.path.clone(), s.audio_stream)))
2010 .cloned();2087 .cloned();
2011 let (from, to) = (2088 let (from, to) = (
2012 f64::from(clip.in_frame) / self.fps,2089 f64::from(clip.in_frame) / self.fps,
@@ -2200,14 +2277,29 @@ fn file_name(path: &std::path::Path) -> String {
2200 /// The sources a repaint has not asked about yet. A key that is already there2277 /// The sources a repaint has not asked about yet. A key that is already there
2201 /// means "asked", whatever state it is in, which is what stops a decode already2278 /// means "asked", whatever state it is in, which is what stops a decode already
2202 /// running from being started again by the next of sixty repaints a second.2279 /// running from being started again by the next of sixty repaints a second.
2203-fn unseen_sources(sources: &[PathBuf], waves: &HashMap<PathBuf, Wave>) -> Vec<PathBuf> {2280+fn unseen_sources(
2281+ sources: &[Source],
2282+ waves: &HashMap<(PathBuf, usize), Wave>,
2283+) -> Vec<(PathBuf, usize)> {
2204 sources2284 sources
2205 .iter()2285 .iter()
2206- .filter(|path| !waves.contains_key(*path))2286+ .map(|s| (s.path.clone(), s.audio_stream))
2207- .cloned()2287+ .filter(|key| !waves.contains_key(key))
2208 .collect()2288 .collect()
2209 }2289 }
2210 2290
2291+/// The same, for the per-file stream probe: one entry per *file*, however many
2292+/// of its streams the timeline plays.
2293+fn unseen_paths(sources: &[Source], streams: &HashMap<PathBuf, Vec<StreamInfo>>) -> Vec<PathBuf> {
2294+ let mut out: Vec<PathBuf> = Vec::new();
2295+ for s in sources {
2296+ if !streams.contains_key(&s.path) && !out.contains(&s.path) {
2297+ out.push(s.path.clone());
2298+ }
2299+ }
2300+ out
2301+}
2302+
2211 /// Both lanes' clips, which is everything the timeline knows about its sources.2303 /// Both lanes' clips, which is everything the timeline knows about its sources.
2212 fn lane_clips(session: &PlaybackSession) -> impl Iterator<Item = &Clip> {2304 fn lane_clips(session: &PlaybackSession) -> impl Iterator<Item = &Clip> {
2213 session2305 session
@@ -2217,17 +2309,25 @@ fn lane_clips(session: &PlaybackSession) -> impl Iterator<Item = &Clip> {
2217 }2309 }
2218 2310
2219 /// How long a source is, as the timeline knows it: the furthest frame any clip2311 /// How long a source is, as the timeline knows it: the furthest frame any clip
2220-/// plays from it. Exact for a source the timeline still holds whole -- which is2312+/// plays from *the file*. Exact for a source the timeline still holds whole --
2221-/// every source the moment it is imported -- and never longer than the file,2313+/// which is every source the moment it is imported -- and never longer than the
2222-/// since every clip was checked against it, so a clip built from this can2314+/// file, since every clip was checked against it, so a clip built from this can
2223-/// always be played. Zero for a source nothing plays from any more.2315+/// always be played. Zero for a file nothing plays from any more.
2316+///
2317+/// By file rather than by source entry, because a second audio stream of a file
2318+/// already on the timeline is a row that has no clips of its own yet, and every
2319+/// stream of a file is the same length -- the picture is what the length is.
2224 ///2320 ///
2225 /// ponytail: a source trimmed on the timeline reads as its trimmed length. The2321 /// ponytail: a source trimmed on the timeline reads as its trimmed length. The
2226 /// file's own length would need a `Demuxer::open` probe per source, off the2322 /// file's own length would need a `Demuxer::open` probe per source, off the
2227 /// render path like the peak decode is -- that is the upgrade path.2323 /// render path like the peak decode is -- that is the upgrade path.
2228-fn source_frames<'a>(clips: impl Iterator<Item = &'a Clip>, source: usize) -> u32 {2324+fn source_frames<'a>(
2325+ clips: impl Iterator<Item = &'a Clip>,
2326+ sources: &[Source],
2327+ path: &Path,
2328+) -> u32 {
2229 clips2329 clips
2230- .filter(|clip| clip.source == source)2330+ .filter(|clip| sources.get(clip.source).is_some_and(|s| s.path == path))
2231 .map(|clip| clip.out_frame)2331 .map(|clip| clip.out_frame)
2232 .max()2332 .max()
2233 .unwrap_or(0)2333 .unwrap_or(0)
@@ -2236,10 +2336,165 @@ fn source_frames<'a>(clips: impl Iterator<Item = &'a Clip>, source: usize) -> u3
2236 /// Whether the Add button does anything: a row picked, a timeline to put it on,2336 /// Whether the Add button does anything: a row picked, a timeline to put it on,
2237 /// and no export reading that timeline. A button that would do nothing is dimmed2337 /// and no export reading that timeline. A button that would do nothing is dimmed
2238 /// and takes no click, like every other one here.2338 /// and takes no click, like every other one here.
2239-fn can_add(picked: Option<usize>, timeline: bool, exporting: bool) -> bool {2339+fn can_add(picked: Option<&(PathBuf, usize)>, timeline: bool, exporting: bool) -> bool {
2240 picked.is_some() && timeline && !exporting2340 picked.is_some() && timeline && !exporting
2241 }2341 }
2242 2342
2343+/// One library row: a file and one of its audio streams. Plain data, planned
2344+/// before anything is drawn -- which rows exist at all is the branchy part.
2345+#[derive(Debug, PartialEq)]
2346+struct Row {
2347+ path: PathBuf,
2348+ stream: usize,
2349+ /// The file, plus which stream this is when the file has several.
2350+ name: String,
2351+ /// What the stream is, or blank for a file with a single one.
2352+ detail: String,
2353+ /// Why it cannot be put on this timeline, for a row that cannot: shown in
2354+ /// place of the length and the only thing that greys a row out.
2355+ unusable: Option<String>,
2356+ /// Frames of the *file*, for the length line.
2357+ frames: u32,
2358+ /// Index into `SOURCE_TINTS`, shared by every stream of one file: the
2359+ /// swatch says which file, and the lanes tint their clips the same way.
2360+ tint: usize,
2361+}
2362+
2363+/// Every row the library shows: one per source entry, plus one for each further
2364+/// audio stream those files have that no clip plays yet -- a remux with a track
2365+/// per language lists them all, the ones this engine cannot use greyed out
2366+/// rather than hidden. Streams a file has not been probed for yet simply are
2367+/// not there; the row for what *is* on the timeline is always there.
2368+///
2369+/// `timeline_audio` is the rate and layout of source 0's stream, which every
2370+/// other source must match: one output device and one copied AAC track for the
2371+/// whole timeline (`PlaybackSession::place_stream_at`). `None` while unknown,
2372+/// and then nothing is greyed for it -- the engine still refuses.
2373+fn library_rows(
2374+ sources: &[Source],
2375+ streams: &HashMap<PathBuf, Vec<StreamInfo>>,
2376+ timeline_audio: Option<(u32, u16)>,
2377+ frames: impl Fn(&Path) -> u32,
2378+) -> Vec<Row> {
2379+ let mut rows = Vec::new();
2380+ for (i, source) in sources.iter().enumerate() {
2381+ let of_file = streams.get(&source.path).map_or(&[][..], Vec::as_slice);
2382+ let info = of_file.iter().find(|s| s.index == source.audio_stream);
2383+ let tint = sources
2384+ .iter()
2385+ .position(|s| s.path == source.path)
2386+ .expect("a source finds itself");
2387+ rows.push(Row {
2388+ path: source.path.clone(),
2389+ stream: source.audio_stream,
2390+ name: row_name(&source.path, source.audio_stream, of_file.len() > 1),
2391+ // Only where there is a choice to describe: a file with one audio
2392+ // track is the row it has always been, name and length, and the
2393+ // length is what would be squeezed out at the panel's least width.
2394+ detail: info
2395+ .filter(|_| of_file.len() > 1)
2396+ .map_or_else(String::new, stream_detail),
2397+ // A stream already on the timeline is playing: whatever a probe
2398+ // would say about it now, it is usable by demonstration.
2399+ unusable: None,
2400+ frames: frames(&source.path),
2401+ tint,
2402+ });
2403+ // The file's other streams, listed once, right after the last entry
2404+ // that names the file -- so a file's rows sit together.
2405+ if sources[i + 1..].iter().any(|s| s.path == source.path) {
2406+ continue;
2407+ }
2408+ for info in of_file {
2409+ if sources
2410+ .iter()
2411+ .any(|s| s.path == source.path && s.audio_stream == info.index)
2412+ {
2413+ continue; // it has a row of its own above
2414+ }
2415+ rows.push(Row {
2416+ path: source.path.clone(),
2417+ stream: info.index,
2418+ name: row_name(&source.path, info.index, true),
2419+ detail: stream_detail(info),
2420+ unusable: unusable(info, timeline_audio),
2421+ frames: frames(&source.path),
2422+ tint,
2423+ });
2424+ }
2425+ }
2426+ rows
2427+}
2428+
2429+/// The row's second line: what the stream is and then either how long it is or
2430+/// why it cannot be used, with the separator only where both halves exist (a
2431+/// single-stream file says nothing about its stream).
2432+fn join_detail(detail: &str, tail: &str) -> String {
2433+ match detail.is_empty() {
2434+ true => tail.to_string(),
2435+ false => format!("{detail} · {tail}"),
2436+ }
2437+}
2438+
2439+/// How a row names its file: the file alone when it has one audio stream or
2440+/// none, and the file plus which stream this row is when it has several --
2441+/// counted from 1, the way a player numbers tracks.
2442+fn row_name(path: &Path, stream: usize, several: bool) -> String {
2443+ match several {
2444+ false => file_name(path),
2445+ true => format!("{} [audio {}]", file_name(path), stream + 1),
2446+ }
2447+}
2448+
2449+/// What a stream is, for the row's second line: the language if the file says
2450+/// one, then rate and layout. A field the header does not give is left out
2451+/// rather than shown as a zero -- a stream we cannot parse says nothing about
2452+/// itself, and saying "0 Hz" would be saying something.
2453+fn stream_detail(info: &StreamInfo) -> String {
2454+ let mut parts: Vec<String> = Vec::new();
2455+ if let Some(lang) = &info.lang {
2456+ parts.push(lang.clone());
2457+ }
2458+ if info.sample_rate > 0 {
2459+ parts.push(format!("{} kHz", f64::from(info.sample_rate) / 1000.));
2460+ }
2461+ parts.extend(layout(info.channels));
2462+ parts.join(" ")
2463+}
2464+
2465+fn layout(channels: u16) -> Option<String> {
2466+ match channels {
2467+ 0 => None,
2468+ 1 => Some("mono".to_string()),
2469+ 2 => Some("stereo".to_string()),
2470+ n => Some(format!("{n} ch")),
2471+ }
2472+}
2473+
2474+/// Why a stream cannot go on this timeline, or `None` if it can. Both answers
2475+/// are shown: a stream nothing can be done with is listed greyed with the
2476+/// reason, never dropped from the list -- a file has the tracks it has, and a
2477+/// picker that hides them is a picker that lies.
2478+fn unusable(info: &StreamInfo, timeline_audio: Option<(u32, u16)>) -> Option<String> {
2479+ if !info.decodable {
2480+ // ponytail: mp4 0.14 keeps no fourcc for a sample entry it does not
2481+ // parse (`StreamInfo::codec`), so an AC-3 track can only be named as
2482+ // unsupported, not as AC-3. Upgrade path is reading the stsd ourselves.
2483+ return Some(match info.codec.as_str() {
2484+ "unknown" => "unsupported codec".to_string(),
2485+ codec => format!("{codec} is not supported"),
2486+ });
2487+ }
2488+ let (rate, channels) = timeline_audio?;
2489+ ((info.sample_rate, info.channels) != (rate, channels)).then(|| {
2490+ format!(
2491+ "the timeline is {} kHz {}",
2492+ f64::from(rate) / 1000.,
2493+ layout(channels).unwrap_or_else(|| "silent".to_string())
2494+ )
2495+ })
2496+}
2497+
2243 /// What the media list is given of the window. A share of it, so a narrow2498 /// What the media list is given of the window. A share of it, so a narrow
2244 /// window gives the panel less rather than giving the picture nothing, floored2499 /// window gives the panel less rather than giving the picture nothing, floored
2245 /// where a name stops being readable and capped at a third of the window --2500 /// where a name stops being readable and capped at a third of the window --
@@ -2675,11 +2930,13 @@ mod tests {
2675 ACCENT, CONTROL_H, Clip, HEADER_GAP, HEADER_W, HIT_MIN, INK, INK_DIM, KEYS_ROW_H,2930 ACCENT, CONTROL_H, Clip, HEADER_GAP, HEADER_W, HIT_MIN, INK, INK_DIM, KEYS_ROW_H,
2676 KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W,2931 KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W,
2677 Lane, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SOURCE_TINTS, SURFACE,2932 Lane, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SOURCE_TINTS, SURFACE,
2678- SWATCH_W, Volume, WAVE_BPS, WAVE_COL, Wave, can_add, cancels_export, envelope, export_path,2933+ SWATCH_W, Source, StreamInfo, Volume, WAVE_BPS, WAVE_COL, Wave, can_add, cancels_export,
2679- export_settings, frac_along, is_bare_modifier, is_project, keymap, lane_clips, marked,2934+ envelope, export_path, export_settings, frac_along, is_bare_modifier, is_project, keymap,
2680- normalise, project_path, push_digit, scrub_due, show_label, source_frames, source_tint,2935+ lane_clips, marked, normalise, project_path, push_digit, scrub_due, show_label,
2681- start_frac, timecode, unseen_sources, width_frac, window_title,2936+ source_frames, source_tint, start_frac, timecode, unseen_paths, unseen_sources, width_frac,
2937+ window_title,
2682 };2938 };
2939+ use super::{file_name, library_rows};
2683 use engine::PlaybackSession;2940 use engine::PlaybackSession;
2684 use gpui::{Bounds, Pixels, point, px, size};2941 use gpui::{Bounds, Pixels, point, px, size};
2685 use std::collections::HashMap;2942 use std::collections::HashMap;
@@ -2704,7 +2961,15 @@ mod tests {
2704 }2961 }
2705 }2962 }
2706 2963
2707- /// The whole of the library's row data comes off the clips: which sources2964+ /// A source entry for `path` on `stream`, as the project keeps them.
2965+ fn source(path: &str, stream: usize) -> Source {
2966+ Source {
2967+ path: PathBuf::from(path),
2968+ audio_stream: stream,
2969+ }
2970+ }
2971+
2972+ /// The whole of the library's row data comes off the clips: which files
2708 /// there are, how long each one is, and therefore which tint each row wears2973 /// there are, how long each one is, and therefore which tint each row wears
2709 /// -- one index into one list, so a swatch cannot name a different file from2974 /// -- one index into one list, so a swatch cannot name a different file from
2710 /// the boxes it is meant to point at.2975 /// the boxes it is meant to point at.
@@ -2713,11 +2978,12 @@ mod tests {
2713 // Source 0 whole, source 1 trimmed to half of what it was, source 2 on2978 // Source 0 whole, source 1 trimmed to half of what it was, source 2 on
2714 // the audio lane only (its picture was lifted), source 3 imported and2979 // the audio lane only (its picture was lifted), source 3 imported and
2715 // then undone -- an entry with nothing playing from it.2980 // then undone -- an entry with nothing playing from it.
2981+ let sources: Vec<Source> = (0..4).map(|i| source(&format!("/m/{i}.mp4"), 0)).collect();
2716 let video = [clip(0, 150), clip(1, 60)];2982 let video = [clip(0, 150), clip(1, 60)];
2717 let audio = [clip(0, 150), clip(1, 30), clip(2, 90)];2983 let audio = [clip(0, 150), clip(1, 30), clip(2, 90)];
2718 for (row, frames) in [(0, 150), (1, 60), (2, 90), (3, 0)] {2984 for (row, frames) in [(0, 150), (1, 60), (2, 90), (3, 0)] {
2719 assert_eq!(2985 assert_eq!(
2720- source_frames(video.iter().chain(&audio), row),2986+ source_frames(video.iter().chain(&audio), &sources, &sources[row].path),
2721 frames,2987 frames,
2722 "row {row}"2988 "row {row}"
2723 );2989 );
@@ -2725,11 +2991,146 @@ mod tests {
2725 // function -- what makes the panel and the lanes one association.2991 // function -- what makes the panel and the lanes one association.
2726 assert_eq!(source_tint(row), SOURCE_TINTS[row % SOURCE_TINTS.len()]);2992 assert_eq!(source_tint(row), SOURCE_TINTS[row % SOURCE_TINTS.len()]);
2727 }2993 }
2728- // The longest clip of a source wins, whichever lane it is in and2994+ // The longest clip of a file wins, whichever lane it is in and
2729 // whatever order the lanes are read in.2995 // whatever order the lanes are read in.
2730- assert_eq!(source_frames([clip(0, 10), clip(0, 90)].iter(), 0), 90);2996+ let one = [source("/m/0.mp4", 0)];
2731- assert_eq!(source_frames([clip(0, 90), clip(0, 10)].iter(), 0), 90);2997+ let path = &one[0].path;
2732- assert_eq!(source_frames([].iter(), 0), 0);2998+ assert_eq!(
2999+ source_frames([clip(0, 10), clip(0, 90)].iter(), &one, path),
3000+ 90
3001+ );
3002+ assert_eq!(
3003+ source_frames([clip(0, 90), clip(0, 10)].iter(), &one, path),
3004+ 90
3005+ );
3006+ assert_eq!(source_frames([].iter(), &one, path), 0);
3007+ // Two audio streams of one file are two source entries and one length:
3008+ // the second stream's row is placeable the moment the file is there,
3009+ // before any clip names that entry.
3010+ let two = [source("/m/0.mp4", 0), source("/m/0.mp4", 1)];
3011+ assert_eq!(source_frames([clip(0, 90)].iter(), &two, &two[1].path), 90);
3012+ }
3013+
3014+ fn info(
3015+ index: usize,
3016+ rate: u32,
3017+ channels: u16,
3018+ lang: Option<&str>,
3019+ decodable: bool,
3020+ ) -> StreamInfo {
3021+ StreamInfo {
3022+ index,
3023+ codec: if decodable { "aac" } else { "unknown" }.into(),
3024+ channels,
3025+ sample_rate: rate,
3026+ lang: lang.map(str::to_string),
3027+ decodable,
3028+ }
3029+ }
3030+
3031+ /// A file's every audio track gets a row: the ones the timeline can take
3032+ /// are placeable, the ones it cannot are listed greyed with the reason.
3033+ /// Which rows exist at all is the branchy part of the panel, so it is
3034+ /// planned as data and checked here rather than through the pointer.
3035+ #[test]
3036+ fn every_audio_stream_of_a_file_is_a_row_usable_or_not() {
3037+ let multi = PathBuf::from("/m/movie.mp4");
3038+ let sources = [source("/m/movie.mp4", 0)];
3039+ let mut streams = HashMap::new();
3040+ streams.insert(
3041+ multi.clone(),
3042+ vec![
3043+ info(0, 44_100, 2, None, true),
3044+ info(1, 44_100, 2, Some("fra"), true),
3045+ info(2, 22_050, 1, Some("deu"), true),
3046+ info(3, 0, 0, None, false),
3047+ ],
3048+ );
3049+ let rows = library_rows(&sources, &streams, Some((44_100, 2)), |_| 90);
3050+ assert_eq!(
3051+ rows.iter().map(|r| r.stream).collect::<Vec<_>>(),
3052+ [0, 1, 2, 3],
3053+ "one row per audio stream, in file order"
3054+ );
3055+ assert!(
3056+ rows.iter().all(|r| r.path == multi && r.tint == 0),
3057+ "every stream of one file wears the file's own tint"
3058+ );
3059+ assert_eq!(rows[0].name, "movie.mp4 [audio 1]");
3060+ assert_eq!(rows[1].name, "movie.mp4 [audio 2]");
3061+ assert_eq!(rows[1].detail, "fra 44.1 kHz stereo");
3062+ // Placeable: the one already on the timeline, and the one that matches
3063+ // it. The 22 kHz mono track cannot join a 44.1 kHz stereo timeline --
3064+ // one device and one copied AAC track for the whole of it -- and the
3065+ // codec we cannot read cannot join anything. Both say which.
3066+ assert_eq!((&rows[0].unusable, &rows[1].unusable), (&None, &None));
3067+ assert_eq!(
3068+ rows[2].unusable.as_deref(),
3069+ Some("the timeline is 44.1 kHz stereo")
3070+ );
3071+ assert_eq!(rows[3].unusable.as_deref(), Some("unsupported codec"));
3072+ assert_eq!(
3073+ rows[3].detail, "",
3074+ "a stream we cannot parse claims nothing"
3075+ );
3076+ // Every row is the same file, so every row is that file's length.
3077+ assert!(rows.iter().all(|r| r.frames == 90));
3078+
3079+ // The single-stream case is exactly one row and no stream tag: no
3080+ // regression for the media everything else in the world is.
3081+ let plain = [source("/m/plain.mp4", 0)];
3082+ let mut one = HashMap::new();
3083+ one.insert(
3084+ PathBuf::from("/m/plain.mp4"),
3085+ vec![info(0, 44_100, 2, None, true)],
3086+ );
3087+ let rows = library_rows(&plain, &one, Some((44_100, 2)), |_| 90);
3088+ assert_eq!(rows.len(), 1);
3089+ assert_eq!(rows[0].name, "plain.mp4");
3090+ assert_eq!(
3091+ rows[0].detail, "",
3092+ "one audio track is the row it has always been: name and length"
3093+ );
3094+ // ...as is a silent file, and a file not probed yet.
3095+ let mut silent = HashMap::new();
3096+ silent.insert(PathBuf::from("/m/plain.mp4"), Vec::new());
3097+ for probe in [silent, HashMap::new()] {
3098+ let rows = library_rows(&plain, &probe, None, |_| 90);
3099+ assert_eq!(rows.len(), 1);
3100+ assert_eq!(rows[0].name, "plain.mp4");
3101+ assert_eq!(rows[0].detail, "");
3102+ }
3103+
3104+ // A second stream *placed* on the timeline is a source entry of its
3105+ // own: it keeps its row, no duplicate appears for it, and the rows of
3106+ // one file stay together whatever order the entries came in.
3107+ let placed = [
3108+ source("/m/movie.mp4", 0),
3109+ source("/m/other.mp4", 0),
3110+ source("/m/movie.mp4", 2),
3111+ ];
3112+ streams.insert(
3113+ PathBuf::from("/m/other.mp4"),
3114+ vec![info(0, 44_100, 2, None, true)],
3115+ );
3116+ let rows = library_rows(&placed, &streams, Some((44_100, 2)), |_| 90);
3117+ assert_eq!(
3118+ rows.iter()
3119+ .map(|r| (file_name(&r.path), r.stream))
3120+ .collect::<Vec<_>>(),
3121+ [
3122+ ("movie.mp4".to_string(), 0),
3123+ ("other.mp4".to_string(), 0),
3124+ ("movie.mp4".to_string(), 2),
3125+ ("movie.mp4".to_string(), 1),
3126+ ("movie.mp4".to_string(), 3),
3127+ ]
3128+ );
3129+ assert!(
3130+ rows[2].unusable.is_none(),
3131+ "a stream already on the timeline is playing, whatever a probe says"
3132+ );
3133+ assert_eq!(rows[1].tint, 1, "the other file is the other tint");
2733 }3134 }
2734 3135
2735 /// The refusal path, end to end against the real files: an incompatible3136 /// The refusal path, end to end against the real files: an incompatible
@@ -2751,7 +3152,11 @@ mod tests {
2751 // at 30 fps, exactly what was appended.3152 // at 30 fps, exactly what was appended.
2752 session.import(&asset("test_av2.mp4")).expect("av2 matches");3153 session.import(&asset("test_av2.mp4")).expect("av2 matches");
2753 assert_eq!(session.sources().len(), 2);3154 assert_eq!(session.sources().len(), 2);
2754- assert_eq!(source_frames(lane_clips(&session), 1), 120);3155+ let second = session.sources()[1].path.clone();
3156+ assert_eq!(
3157+ source_frames(lane_clips(&session), session.sources(), &second),
3158+ 120
3159+ );
2755 assert_eq!(timecode(120. / 30., 30.), "00:00:04:00");3160 assert_eq!(timecode(120. / 30., 30.), "00:00:04:00");
2756 }3161 }
2757 3162
@@ -2766,17 +3171,15 @@ mod tests {
2766 assert_eq!(session.timeline_duration(), 9.0);3171 assert_eq!(session.timeline_duration(), 9.0);
2767 // Two seconds in, which is inside the first take: the insert splits it.3172 // Two seconds in, which is inside the first take: the insert splits it.
2768 session.seek(2.0);3173 session.seek(2.0);
2769- let frames = source_frames(lane_clips(&session), 1);3174+ let second = session.sources()[1].path.clone();
2770- assert!(session.paste_at(3175+ let frames = source_frames(lane_clips(&session), session.sources(), &second);
2771- 2.0,3176+ // Through the engine door `insert_source` uses, with the row's own
2772- Clip {3177+ // stream: the button, the drop and this are one call.
2773- start: 0,3178+ assert!(
2774- in_frame: 0,3179+ session
2775- out_frame: frames,3180+ .place_stream_at(2.0, &second, 0, frames)
2776- source: 1,3181+ .expect("av2 is already on the timeline")
2777- link: None,3182+ );
2778- }
2779- ));
2780 // The whole of source 1 went in and nothing was painted over: the3183 // The whole of source 1 went in and nothing was painted over: the
2781 // timeline is longer by exactly that file.3184 // timeline is longer by exactly that file.
2782 assert_eq!(session.timeline_duration(), 13.0);3185 assert_eq!(session.timeline_duration(), 13.0);
@@ -2797,32 +3200,89 @@ mod tests {
2797 assert_eq!(at(video).len(), frames);3200 assert_eq!(at(video).len(), frames);
2798 assert!(at(video).link.is_some());3201 assert!(at(video).link.is_some());
2799 assert_eq!(video.len(), audio.len());3202 assert_eq!(video.len(), audio.len());
3203+
3204+ // The same door with a *second audio stream* of a file already there:
3205+ // a new source entry, the same picture, and the row that was dragged
3206+ // is what plays. This is the whole user-facing point of the slice.
3207+ let mut session =
3208+ PlaybackSession::open(asset("test_multilang.mp4")).expect("open the fixture");
3209+ session.set_gain(0.0);
3210+ let path = session.sources()[0].path.clone();
3211+ let frames = source_frames(lane_clips(&session), session.sources(), &path);
3212+ let end = session.timeline_duration();
3213+ assert!(
3214+ session
3215+ .place_stream_at(end, &path, 1, frames)
3216+ .expect("the French track shares the timeline's parameters")
3217+ );
3218+ assert_eq!(session.sources()[1].audio_stream, 1);
3219+ assert_eq!(session.timeline_duration(), end * 2.0);
3220+ // Both rows are the same file, so both rows are that file's length --
3221+ // the second one before any clip of its own existed.
3222+ assert_eq!(
3223+ source_frames(lane_clips(&session), session.sources(), &path),
3224+ frames
3225+ );
2800 }3226 }
2801 3227
2802 #[test]3228 #[test]
2803 fn a_source_is_only_ever_asked_for_its_peaks_once() {3229 fn a_source_is_only_ever_asked_for_its_peaks_once() {
2804 let (a, b) = (asset("test_av.mp4"), asset("test_av2.mp4"));3230 let (a, b) = (asset("test_av.mp4"), asset("test_av2.mp4"));
2805- let sources = [a.clone(), b.clone()];3231+ // Two files, and two streams of the first: three envelopes, because
2806- let mut waves: HashMap<PathBuf, Wave> = HashMap::new();3232+ // one file's two audio tracks are two different waveforms.
2807- assert_eq!(unseen_sources(&sources, &waves), sources);3233+ let sources = [
3234+ Source {
3235+ path: a.clone(),
3236+ audio_stream: 0,
3237+ },
3238+ Source {
3239+ path: a.clone(),
3240+ audio_stream: 1,
3241+ },
3242+ Source {
3243+ path: b.clone(),
3244+ audio_stream: 0,
3245+ },
3246+ ];
3247+ let keys = |s: &[Source]| {
3248+ s.iter()
3249+ .map(|s| (s.path.clone(), s.audio_stream))
3250+ .collect::<Vec<_>>()
3251+ };
3252+ let mut waves: HashMap<(PathBuf, usize), Wave> = HashMap::new();
3253+ assert_eq!(unseen_sources(&sources, &waves), keys(&sources));
2808 // The entry goes in when the decode *starts*, so the sixty repaints a3254 // The entry goes in when the decode *starts*, so the sixty repaints a
2809 // second that happen while it runs must not start it again -- which is3255 // second that happen while it runs must not start it again -- which is
2810 // what this asserts about a key whose value is not an answer yet.3256 // what this asserts about a key whose value is not an answer yet.
2811- waves.insert(a, Wave::Loading);3257+ waves.insert((a.clone(), 0), Wave::Loading);
2812- assert_eq!(unseen_sources(&sources, &waves), vec![b.clone()]);3258+ assert_eq!(
3259+ unseen_sources(&sources, &waves),
3260+ keys(&sources[1..]),
3261+ "the file's other stream is a key of its own"
3262+ );
2813 // A file with no audio is an answer like any other: never re-asked.3263 // A file with no audio is an answer like any other: never re-asked.
2814- waves.insert(b, Wave::Silent);3264+ waves.insert((a, 1), Wave::Silent);
3265+ waves.insert((b.clone(), 0), Wave::Silent);
2815 assert!(unseen_sources(&sources, &waves).is_empty());3266 assert!(unseen_sources(&sources, &waves).is_empty());
3267+ // The stream probe is per *file*: the two entries of `a` ask once.
3268+ let mut streams: HashMap<PathBuf, Vec<StreamInfo>> = HashMap::new();
3269+ assert_eq!(
3270+ unseen_paths(&sources, &streams),
3271+ vec![asset("test_av.mp4"), b]
3272+ );
3273+ streams.insert(asset("test_av.mp4"), Vec::new());
3274+ assert_eq!(unseen_paths(&sources, &streams).len(), 1);
2816 }3275 }
2817 3276
2818 #[test]3277 #[test]
2819 fn the_add_button_is_dead_unless_it_would_do_something() {3278 fn the_add_button_is_dead_unless_it_would_do_something() {
2820- assert!(can_add(Some(0), true, false));3279+ let picked = (PathBuf::from("/m/0.mp4"), 0);
3280+ assert!(can_add(Some(&picked), true, false));
2821 // Nothing picked, nothing to put it on, or an export reading the very3281 // Nothing picked, nothing to put it on, or an export reading the very
2822 // edit list this would change.3282 // edit list this would change.
2823 assert!(!can_add(None, true, false));3283 assert!(!can_add(None, true, false));
2824- assert!(!can_add(Some(0), false, false));3284+ assert!(!can_add(Some(&picked), false, false));
2825- assert!(!can_add(Some(0), true, true));3285+ assert!(!can_add(Some(&picked), true, true));
2826 }3286 }
2827 3287
2828 #[test]3288 #[test]
@@ -3314,7 +3774,7 @@ mod tests {
3314 .join(name)3774 .join(name)
3315 };3775 };
3316 let peaks = normalise(3776 let peaks = normalise(
3317- engine::waveform::peaks(asset("test_av.mp4"), WAVE_BPS)3777+ engine::waveform::peaks(asset("test_av.mp4"), 0, WAVE_BPS)
3318 .expect("open the fixture")3778 .expect("open the fixture")
3319 .expect("test_av.mp4 has audio"),3779 .expect("test_av.mp4 has audio"),
3320 );3780 );
@@ -3333,7 +3793,7 @@ mod tests {
3333 );3793 );
3334 // A video-only source draws no waveform at all rather than a flat fake.3794 // A video-only source draws no waveform at all rather than a flat fake.
3335 assert!(3795 assert!(
3336- engine::waveform::peaks(asset("test_baseline.mp4"), WAVE_BPS)3796+ engine::waveform::peaks(asset("test_baseline.mp4"), 0, WAVE_BPS)
3337 .expect("open the fixture")3797 .expect("open the fixture")
3338 .is_none()3798 .is_none()
3339 );3799 );
@@ -3431,9 +3891,9 @@ fn main() {
3431 let meta = session.as_ref().map(|session| *session.meta());3891 let meta = session.as_ref().map(|session| *session.meta());
3432 // Beside the media even for a project: an export has never landed anywhere3892 // Beside the media even for a project: an export has never landed anywhere
3433 // but next to the picture it came from.3893 // but next to the picture it came from.
3434- let out = session3894+ let out = session.as_ref().map_or_else(PathBuf::new, |session| {
3435- .as_ref()3895+ export_path(&session.sources()[0].path)
3436- .map_or_else(PathBuf::new, |session| export_path(&session.sources()[0]));3896+ });
3437 let project = match &arg {3897 let project = match &arg {
3438 Some(arg) if is_project(arg) => arg.clone(),3898 Some(arg) if is_project(arg) => arg.clone(),
3439 Some(arg) => project_path(arg),3899 Some(arg) => project_path(arg),
@@ -3499,6 +3959,7 @@ fn main() {
3499 selected: None,3959 selected: None,
3500 selected_asset: None,3960 selected_asset: None,
3501 waves: HashMap::new(),3961 waves: HashMap::new(),
3962+ streams: HashMap::new(),
3502 clipboard: None,3963 clipboard: None,
3503 scrubbing: false,3964 scrubbing: false,
3504 last_scrub: Instant::now(),3965 last_scrub: Instant::now(),
crates/engine/src/audio.rsmodified+28 -17
@@ -259,12 +259,13 @@ impl AudioSession {
259 Ok(Some((meta, rx)))259 Ok(Some((meta, rx)))
260 }260 }
261 261
262- /// The audio parameters of `path`, for checking an import against the262+ /// The audio parameters of `path`'s `stream`, for checking an import
263- /// timeline's first source: header only, no decoder and no worker.263+ /// against the timeline's first source: header only, no decoder and no
264- /// `Ok(None)` means no AAC track — an audio-less file, which import pairs264+ /// worker. `Ok(None)` means no AAC track — an audio-less file, which import
265- /// only with other audio-less files.265+ /// pairs only with other audio-less files. A *named* stream that is not
266- pub fn probe(path: impl AsRef<Path>) -> crate::Result<Option<AudioProbe>> {266+ /// there or does not decode is an `Err`, as everywhere else.
267- let Some(track) = Track::open(path.as_ref(), 0)? else {267+ pub fn probe(path: impl AsRef<Path>, stream: usize) -> crate::Result<Option<AudioProbe>> {
268+ let Some(track) = Track::open(path.as_ref(), stream)? else {
268 return Ok(None);269 return Ok(None);
269 };270 };
270 Ok(Some(AudioProbe {271 Ok(Some(AudioProbe {
@@ -356,14 +357,28 @@ impl AudioSession {
356 pub fn copy_multi_segments(357 pub fn copy_multi_segments(
357 sources: &[PathBuf],358 sources: &[PathBuf],
358 segs: &[(Option<usize>, f64, f64)],359 segs: &[(Option<usize>, f64, f64)],
360+ ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> {
361+ let sources: Vec<_> = sources.iter().map(|p| (p.clone(), 0)).collect();
362+ Self::copy_multi_streams(&sources, segs)
363+ }
364+
365+ /// [`copy_multi_segments`](Self::copy_multi_segments) with each source
366+ /// naming *which* of its audio streams to copy — the same `(path, stream)`
367+ /// list [`open_multi_streams`](Self::open_multi_streams) plays. The two
368+ /// take it in the same shape on purpose: an export that copied a different
369+ /// stream from the one the timeline played would be a file that sounds
370+ /// nothing like what was edited, and nothing would say so.
371+ pub fn copy_multi_streams(
372+ sources: &[(PathBuf, usize)],
373+ segs: &[(Option<usize>, f64, f64)],
359 ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> {374 ) -> crate::Result<Option<(AacTrackParams, Vec<AacPacket>)>> {
360 let Some(&(Some(first), ..)) = segs.iter().find(|s| s.0.is_some()) else {375 let Some(&(Some(first), ..)) = segs.iter().find(|s| s.0.is_some()) else {
361 return Ok(None); // no segments, or nothing but silence376 return Ok(None); // no segments, or nothing but silence
362 };377 };
363- let path = sources378+ let (path, stream) = sources
364 .get(first)379 .get(first)
365 .ok_or_else(|| format!("segment names source {first} of {}", sources.len()))?;380 .ok_or_else(|| format!("segment names source {first} of {}", sources.len()))?;
366- let Some(track) = Track::open(path, 0)? else {381+ let Some(track) = Track::open(path, *stream)? else {
367 return Ok(None); // silent source, silent export382 return Ok(None); // silent source, silent export
368 };383 };
369 let params = track.track_params();384 let params = track.track_params();
@@ -452,24 +467,20 @@ fn silent_packet(chan_conf: u8) -> crate::Result<Vec<u8>> {
452 }467 }
453 }468 }
454 469
455-/// The source at `index`, opened on first use. Sources a segment list never470+/// The source at `index`, on the stream it names, opened on first use. Sources
456-/// names are never touched: a project's list only grows.471+/// a segment list never names are never touched: a project's list only grows.
457-///
458-/// ponytail: the copy path is still stream 0 of every source — an export of a
459-/// timeline playing stream 1 would carry stream 0's audio. Upgrade path is the
460-/// `(PathBuf, usize)` list [`AudioSession::open_multi_streams`] already takes,
461-/// which is S4b's job once a stream can be picked at all.
462 fn source_at<'a>(472 fn source_at<'a>(
463 tracks: &'a mut [Option<Track>],473 tracks: &'a mut [Option<Track>],
464- sources: &[PathBuf],474+ sources: &[(PathBuf, usize)],
465 index: usize,475 index: usize,
466 ) -> crate::Result<&'a mut Track> {476 ) -> crate::Result<&'a mut Track> {
467 let slot = tracks477 let slot = tracks
468 .get_mut(index)478 .get_mut(index)
469 .ok_or_else(|| format!("segment names source {index} of {}", sources.len()))?;479 .ok_or_else(|| format!("segment names source {index} of {}", sources.len()))?;
470 if slot.is_none() {480 if slot.is_none() {
481+ let (path, stream) = &sources[index];
471 *slot = Some(482 *slot = Some(
472- Track::open(&sources[index], 0)?483+ Track::open(path, *stream)?
473 .ok_or_else(|| format!("source {index} has no audio track"))?,484 .ok_or_else(|| format!("source {index} has no audio track"))?,
474 );485 );
475 }486 }
crates/engine/src/edith.rsmodified+126 -41
@@ -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 {
194- path221+ path: if path.is_absolute() {
195- } else {222+ path
196- dir.join(path)223+ } else {
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/playback.rsmodified+95 -28
@@ -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.
@@ -123,7 +123,9 @@ impl PlaybackSession {
123 // `open_worker` rather than `open` purely for the worker handle: the123 // `open_worker` rather than `open` purely for the worker handle: the
124 // field has to exist from the start for the first seek to use it.124 // field has to exist from the start for the first seek to use it.
125 let (meta, stream) = DecodeSession::open_worker(&path, 0, u32::MAX)?;125 let (meta, stream) = DecodeSession::open_worker(&path, 0, u32::MAX)?;
126- let audio = open_audio(&path);126+ // A file is opened on its first audio stream, like `Project::single`
127+ // names it: nothing has picked one yet.
128+ let audio = open_audio(&path, 0);
127 let source = match audio {129 let source = match audio {
128 Some(_) => ClockSource::Audio,130 Some(_) => ClockSource::Audio,
129 None => ClockSource::Wall,131 None => ClockSource::Wall,
@@ -175,16 +177,16 @@ impl PlaybackSession {
175 // locals drop in reverse declaration order -- a bare worker would join177 // locals drop in reverse declaration order -- a bare worker would join
176 // its decode thread while the receiver next to it was still holding178 // its decode thread while the receiver next to it was still holding
177 // that thread parked in `send`, which is a hang (see [`FrameStream`]).179 // that thread parked in `send`, which is a hang (see [`FrameStream`]).
178- let (meta, stream) = DecodeSession::open_worker(&first, 0, u32::MAX)180+ let (meta, stream) = DecodeSession::open_worker(&first.path, 0, u32::MAX)
179- .map_err(|e| format!("source {}: {e}", first.display()))?;181+ .map_err(|e| format!("source {}: {e}", first.path.display()))?;
180- let first_audio = AudioSession::probe(&first)?;182+ let first_audio = AudioSession::probe(&first.path, first.audio_stream)?;
181 183
182 let mut counts = vec![meta.frame_count];184 let mut counts = vec![meta.frame_count];
183 for source in &doc.sources[1..] {185 for source in &doc.sources[1..] {
184- let (other, _) =186+ let (other, _) = Demuxer::open(&source.path)
185- Demuxer::open(source).map_err(|e| format!("source {}: {e}", source.display()))?;187+ .map_err(|e| format!("source {}: {e}", source.path.display()))?;
186 matches_timeline(source, &other, &meta, &first_audio)188 matches_timeline(source, &other, &meta, &first_audio)
187- .map_err(|e| format!("source {}: {e}", source.display()))?;189+ .map_err(|e| format!("source {}: {e}", source.path.display()))?;
188 counts.push(other.frame_count);190 counts.push(other.frame_count);
189 }191 }
190 for (i, clip) in doc.video.iter().chain(&doc.audio).enumerate() {192 for (i, clip) in doc.video.iter().chain(&doc.audio).enumerate() {
@@ -192,7 +194,7 @@ impl PlaybackSession {
192 return Err(format!(194 return Err(format!(
193 "clip {i} ends at frame {} but {} has {} frames",195 "clip {i} ends at frame {} but {} has {} frames",
194 clip.out_frame,196 clip.out_frame,
195- doc.sources[clip.source].display(),197+ doc.sources[clip.source].path.display(),
196 counts[clip.source]198 counts[clip.source]
197 )199 )
198 .into());200 .into());
@@ -207,7 +209,7 @@ impl PlaybackSession {
207 // only a session's `drop` retires it, so a refusal above this line would209 // only a session's `drop` retires it, so a refusal above this line would
208 // leave a PipeWire stream and a thread behind for a project that never210 // leave a PipeWire stream and a thread behind for a project that never
209 // opened. Nothing before it needs the device.211 // opened. Nothing before it needs the device.
210- let audio = open_audio(&first);212+ let audio = open_audio(&first.path, first.audio_stream);
211 let mut session = Self {213 let mut session = Self {
212 meta,214 meta,
213 frames: stream.frames,215 frames: stream.frames,
@@ -237,7 +239,7 @@ impl PlaybackSession {
237 239
238 /// The files this timeline plays from, index 0 first -- a caller needs it240 /// The files this timeline plays from, index 0 first -- a caller needs it
239 /// to name an export or a window after the media rather than the project.241 /// to name an export or a window after the media rather than the project.
240- pub fn sources(&self) -> &[PathBuf] {242+ pub fn sources(&self) -> &[Source] {
241 self.project.sources()243 self.project.sources()
242 }244 }
243 245
@@ -329,7 +331,7 @@ impl PlaybackSession {
329 fn start_span(&mut self, span: Span) {331 fn start_span(&mut self, span: Span) {
330 let opened = match span.from {332 let opened = match span.from {
331 Some((source, in_frame)) => DecodeSession::open_worker(333 Some((source, in_frame)) => DecodeSession::open_worker(
332- &self.project.sources()[source],334+ &self.project.sources()[source].path,
333 in_frame,335 in_frame,
334 in_frame + span.len,336 in_frame + span.len,
335 )337 )
@@ -440,6 +442,56 @@ impl PlaybackSession {
440 self.edit(|p| p.paste(at, clip))442 self.edit(|p| p.paste(at, clip))
441 }443 }
442 444
445+ /// Places `frames` of `path` played on its audio `stream` at
446+ /// `timeline_secs`, the way [`paste_at`](Self::paste_at) places a copy --
447+ /// the door a library row goes through, and the only way a stream other
448+ /// than the one an import brought in reaches the timeline. The `(file,
449+ /// stream)` pair becomes a source if it is not one already.
450+ ///
451+ /// Refused, changing nothing, unless that stream can join *this* timeline:
452+ /// same audio parameters as the first source, in the same words
453+ /// [`import`](Self::import) refuses a file with. One output device and one
454+ /// copied AAC track mean one set of audio parameters for the whole
455+ /// timeline, so a 22 kHz mono track cannot join a 44.1 kHz stereo one --
456+ /// there is no resampler here, and no AAC encoder to write the join with.
457+ /// A front-end greys such a row out; this is the backstop that keeps a
458+ /// stale one from making the whole timeline silent.
459+ pub fn place_stream_at(
460+ &mut self,
461+ timeline_secs: f64,
462+ path: &Path,
463+ stream: usize,
464+ frames: u32,
465+ ) -> crate::Result<bool> {
466+ let wanted = Source::new(path, stream);
467+ // Another stream of a file whose picture is *already* on the timeline:
468+ // that is what a library row is, and it is why nothing here has to
469+ // check dimensions or frame rate -- the file passed that at import.
470+ if !self.project.sources().iter().any(|s| s.path == wanted.path) {
471+ return Err(format!("{} is not on this timeline", path.display()).into());
472+ }
473+ let first = self.first_audio()?;
474+ audio_matches(&wanted, &first)?;
475+ let source = self.project.import(path, stream);
476+ Ok(self.paste_at(
477+ timeline_secs,
478+ Clip {
479+ start: 0,
480+ in_frame: 0,
481+ out_frame: frames.max(1),
482+ source,
483+ link: None,
484+ },
485+ ))
486+ }
487+
488+ /// What the timeline's audio *is*: source 0's chosen stream, probed. Every
489+ /// other source is held to it.
490+ fn first_audio(&self) -> crate::Result<Option<crate::AudioProbe>> {
491+ let first = &self.project.sources()[0];
492+ AudioSession::probe(&first.path, first.audio_stream)
493+ }
494+
443 /// Removes the video clip at `idx` and everything under it, closing the gap495 /// Removes the video clip at `idx` and everything under it, closing the gap
444 /// on every lane. Unlike a split this *does* move every following frame, so496 /// on every lane. Unlike a split this *does* move every following frame, so
445 /// the session reseeks to wherever the playhead now points.497 /// the session reseeks to wherever the playhead now points.
@@ -464,11 +516,14 @@ impl PlaybackSession {
464 /// a refusal.516 /// a refusal.
465 pub fn import(&mut self, path: &Path) -> crate::Result<()> {517 pub fn import(&mut self, path: &Path) -> crate::Result<()> {
466 let (meta, _) = Demuxer::open(path)?;518 let (meta, _) = Demuxer::open(path)?;
467- let first = AudioSession::probe(&self.project.sources()[0])?;519+ let first = self.first_audio()?;
468- matches_timeline(path, &meta, &self.meta, &first)?;520+ // Stream 0: an import brings a file in on its first audio track, and
521+ // [`place_stream_at`](Self::place_stream_at) is how any other one of
522+ // its streams reaches the timeline afterwards.
523+ matches_timeline(&Source::new(path, 0), &meta, &self.meta, &first)?;
469 524
470 let old_end = self.timeline_duration();525 let old_end = self.timeline_duration();
471- let source = self.project.import(path);526+ let source = self.project.import(path, 0);
472 // Refused only for an unknown index, and this one just came from `import`.527 // Refused only for an unknown index, and this one just came from `import`.
473 self.project.append_clip(source, meta.frame_count);528 self.project.append_clip(source, meta.frame_count);
474 // Reseek like any other edit, even though nothing before the playhead529 // Reseek like any other edit, even though nothing before the playhead
@@ -604,7 +659,10 @@ impl PlaybackSession {
604 // ear never hears it -- and a join between two *files* is just659 // ear never hears it -- and a join between two *files* is just
605 // another segment, because every segment names its own source.660 // another segment, because every segment names its own source.
606 let segs = self.project.segments_from(target, fps);661 let segs = self.project.segments_from(target, fps);
607- audio_running = match AudioSession::open_multi_segments(self.project.sources(), &segs) {662+ // Each source on the stream it was placed with: what plays is what
663+ // the library row said, and what an export copies (`export::run`).
664+ let sources = self.project.audio_sources();
665+ audio_running = match AudioSession::open_multi_streams(&sources, &segs) {
608 Ok(Some((_, rx))) => audio.spawn_feeder(rx),666 Ok(Some((_, rx))) => audio.spawn_feeder(rx),
609 _ => false,667 _ => false,
610 };668 };
@@ -711,7 +769,7 @@ impl Drop for PlaybackSession {
711 /// [`PlaybackSession::open_project`] share them so a file refused at import is769 /// [`PlaybackSession::open_project`] share them so a file refused at import is
712 /// refused in the same words at load.770 /// refused in the same words at load.
713 fn matches_timeline(771 fn matches_timeline(
714- path: &Path,772+ source: &Source,
715 meta: &VideoMeta,773 meta: &VideoMeta,
716 timeline: &VideoMeta,774 timeline: &VideoMeta,
717 first: &Option<crate::AudioProbe>,775 first: &Option<crate::AudioProbe>,
@@ -731,9 +789,16 @@ fn matches_timeline(
731 )789 )
732 .into());790 .into());
733 }791 }
792+ audio_matches(source, first)
793+}
794+
795+/// The audio half of [`matches_timeline`], which a stream placed on its own
796+/// ([`PlaybackSession::place_stream_at`]) has to pass while the picture it
797+/// comes with is already on the timeline.
798+fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::Result<()> {
734 // Whole-probe equality: rate, layout and the esds fields, which the audio799 // Whole-probe equality: rate, layout and the esds fields, which the audio
735 // worker holds every source to anyway. Both silent is a match.800 // worker holds every source to anyway. Both silent is a match.
736- let probe = AudioSession::probe(path)?;801+ let probe = AudioSession::probe(&source.path, source.audio_stream)?;
737 if probe != *first {802 if probe != *first {
738 return Err(match (probe, first) {803 return Err(match (probe, first) {
739 (None, _) => "the file is silent, the timeline has audio".to_string(),804 (None, _) => "the file is silent, the timeline has audio".to_string(),
@@ -751,15 +816,17 @@ fn matches_timeline(
751 /// `None` for a silent session -- no audio track, no plugin, no daemon, or a816 /// `None` for a silent session -- no audio track, no plugin, no daemon, or a
752 /// track the decoder refuses. Dropping the receiver on the way out stops the817 /// track the decoder refuses. Dropping the receiver on the way out stops the
753 /// audio decode worker, so a failure here leaves nothing running.818 /// audio decode worker, so a failure here leaves nothing running.
754-fn open_audio(path: &Path) -> Option<Audio> {819+fn open_audio(path: &Path, stream: usize) -> Option<Audio> {
755- let (meta, rx) = match AudioSession::open(path) {820+ let sources = [(path.to_path_buf(), stream)];
756- Ok(Some(opened)) => opened,821+ let (meta, rx) =
757- Ok(None) => return None,822+ match AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)]) {
758- Err(e) => {823+ Ok(Some(opened)) => opened,
759- eprintln!("audio disabled: {e}");824+ Ok(None) => return None,
760- return None;825+ Err(e) => {
761- }826+ eprintln!("audio disabled: {e}");
762- };827+ return None;
828+ }
829+ };
763 let ao = AoSession::open(meta.sample_rate, u32::from(meta.channels))?;830 let ao = AoSession::open(meta.sample_rate, u32::from(meta.channels))?;
764 // The stream comes up streaming; a session starts paused, so silence the831 // The stream comes up streaming; a session starts paused, so silence the
765 // device until `play`. The feeder still fills the ring in the meantime.832 // device until `play`. The feeder still fills the ring in the meantime.
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
@@ -42,6 +42,23 @@ ffmpeg -y -f lavfi -i testsrc2=size=320x240:rate=30:duration=2 \
42 -c:a:1 aac -ar:a:1 22050 -ac:a:1 1 \42 -c:a:1 aac -ar:a:1 22050 -ac:a:1 1 \
43 -c:a:2 ac3 -ar:a:2 44100 -ac:a:2 2 \43 -c:a:2 ac3 -ar:a:2 44100 -ac:a:2 2 \
44 -metadata:s:a:1 language=fra assets/test_multiaudio.mp444 -metadata:s:a:1 language=fra assets/test_multiaudio.mp4
45+# Multi-language fixture: the shape real media has — one video and two AAC
46+# streams that *agree* on rate and layout (44.1k stereo) and differ only in
47+# language and content, 440/880 Hz undefined and 220/330 Hz French. One
48+# timeline means one set of audio parameters, so this is the file where the
49+# second stream can actually be put on the timeline; test_multiaudio.mp4 is the
50+# file where it cannot, and both cases have to be shown.
51+ffmpeg -y -f lavfi -i testsrc2=size=320x240:rate=30:duration=2 \
52+ -f lavfi -i "sine=frequency=440:duration=2" \
53+ -f lavfi -i "sine=frequency=880:duration=2" \
54+ -f lavfi -i "sine=frequency=220:duration=2" \
55+ -f lavfi -i "sine=frequency=330:duration=2" \
56+ -filter_complex "[1:a][2:a]join=inputs=2:channel_layout=stereo[a0];\
57+[3:a][4:a]join=inputs=2:channel_layout=stereo[a1]" \
58+ -map 0:v -map "[a0]" -map "[a1]" \
59+ -c:v libx264 -profile:v baseline -pix_fmt yuv420p \
60+ -c:a aac -ar 44100 -ac 2 \
61+ -metadata:s:a:1 language=fra assets/test_multilang.mp4
45 # Mismatch fixture: different resolution and no audio track at all, so import62 # Mismatch fixture: different resolution and no audio track at all, so import
46 # has something concrete to refuse.63 # has something concrete to refuse.
47 ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \64 ffmpeg -y -f lavfi -i testsrc2=size=640x360:rate=30:duration=2 \