forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'worktree-agent-adf1db523f92613e0'

Browse files at this commit

f7fc68f38548b9f59463614efcd95b8a0f70b733Ahmet Kaan GümüşParent: 6a64d06000621a
crates/engine/src/audio.rsmodified+118 -0
@@ -10,6 +10,11 @@
10 //! same samples either way; only the packet copy asks which reader it came from,10 //! same samples either way; only the packet copy asks which reader it came from,
11 //! because there is nothing to copy out of an mp3 that an mp4 can hold.11 //! because there is nothing to copy out of an mp3 that an mp4 can hold.
12 //!12 //!
13+//! One output, however many lanes: a timeline's audio lanes are decoded side by
14+//! side and summed ([`AudioSession::open_mixed_streams`]), which is what both
15+//! the device and an audio-only export are handed. One lane skips the mixer
16+//! entirely and is the plain single-stream path it always was.
17+//!
13 //! Both readers are addressed as `(path, stream)`. An mp4 may carry several18 //! Both readers are addressed as `(path, stream)`. An mp4 may carry several
14 //! audio tracks and the caller picks one; a standalone audio file carries19 //! audio tracks and the caller picks one; a standalone audio file carries
15 //! exactly one, so any stream above 0 there is an `Err` rather than a silent20 //! exactly one, so any stream above 0 there is an `Err` rather than a silent
@@ -292,6 +297,53 @@ impl AudioSession {
292 Ok(Some((meta, rx)))297 Ok(Some((meta, rx)))
293 }298 }
294 299
300+ /// Every audio lane of a timeline, summed into one stream: `lanes` is one
301+ /// play list per lane, each in the shape
302+ /// [`open_multi_streams`](Self::open_multi_streams) takes, and what comes
303+ /// out is what the device hears -- the lanes decoded side by side and added
304+ /// sample for sample, clamped to `[-1, 1]` so a loud pair cannot wrap the
305+ /// output.
306+ ///
307+ /// **One lane is not mixed at all**: it is `open_multi_streams` verbatim, so
308+ /// a timeline with a single audio lane decodes exactly the samples it always
309+ /// did, down to the bit and down to the thread count.
310+ ///
311+ /// Lengths need not agree: a lane that has run out contributes silence to
312+ /// what is left, which is what a shorter lane means. Each lane keeps its own
313+ /// gap rule -- a hole in it is real silence from its own worker, not a
314+ /// skipped chunk -- so the sum feeds the master clock a sample per sample of
315+ /// timeline however the lanes are arranged. `start_sample` numbers from the
316+ /// first lane's own start (see [`AudioChunk`]).
317+ pub fn open_mixed_streams(
318+ sources: &[(PathBuf, usize)],
319+ lanes: &[Vec<(Option<usize>, f64, f64)>],
320+ ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
321+ let [first, rest @ ..] = lanes else {
322+ return Ok(None);
323+ };
324+ if rest.is_empty() {
325+ return Self::open_multi_streams(sources, first);
326+ }
327+ let mut meta = None;
328+ let mut rxs = Vec::with_capacity(lanes.len());
329+ for segs in lanes {
330+ // Every lane probes the same source 0, so the metas agree by
331+ // construction; `None` from any of them is a silent timeline.
332+ let Some((lane_meta, rx)) = Self::open_multi_streams(sources, segs)? else {
333+ return Ok(None);
334+ };
335+ meta = Some(lane_meta);
336+ rxs.push(rx);
337+ }
338+ let meta = meta.expect("at least two lanes opened above");
339+ let (tx, rx) = sync_channel(32);
340+ let channels = usize::from(meta.channels);
341+ thread::Builder::new()
342+ .name("audio-mix".into())
343+ .spawn(move || mix(&rxs, channels, &tx))?;
344+ Ok(Some((meta, rx)))
345+ }
346+
295 /// Why [`open`](Self::open) came back silent for a file that *has* sound:347 /// Why [`open`](Self::open) came back silent for a file that *has* sound:
296 /// `Some(reason)` when there is an audio track and it is not the AAC-LC348 /// `Some(reason)` when there is an audio track and it is not the AAC-LC
297 /// this decodes (an AC-3 remux, say). `None` when the file is simply silent349 /// this decodes (an AC-3 remux, say). `None` when the file is simply silent
@@ -1193,6 +1245,72 @@ struct Worker {
1193 tx: SyncSender<AudioChunk>,1245 tx: SyncSender<AudioChunk>,
1194 }1246 }
1195 1247
1248+/// Sums one worker per lane into one stream (see
1249+/// [`AudioSession::open_mixed_streams`]). Every lane starts at the same timeline
1250+/// position and synthesises its own gaps, so the lanes are sample-aligned by
1251+/// construction and a mix is an add: no resampling, no positioning, no drift to
1252+/// correct. What is emitted at each turn is the shortest block every still-live
1253+/// lane can supply, which keeps a slow lane from being outrun and never buffers
1254+/// more than the chunks already in flight.
1255+///
1256+/// A lane whose channel has closed has ended and simply stops being added --
1257+/// that is what "shorter lane" means here. The mix ends when all of them have.
1258+/// The accumulator is reused across turns; the one allocation per chunk is the
1259+/// buffer the channel takes ownership of, and none of this is the RT path (the
1260+/// device callback reads the ring the feeder has already filled).
1261+fn mix(rxs: &[Receiver<AudioChunk>], channels: usize, tx: &SyncSender<AudioChunk>) {
1262+ let mut pending: Vec<Vec<f32>> = rxs.iter().map(|_| Vec::new()).collect();
1263+ let mut live: Vec<bool> = rxs.iter().map(|_| true).collect();
1264+ // Numbering follows lane 0, whose first chunk says where it starts.
1265+ let mut base = 0;
1266+ let mut emitted = 0;
1267+ let mut out: Vec<f32> = Vec::new();
1268+ loop {
1269+ for (i, rx) in rxs.iter().enumerate() {
1270+ while live[i] && pending[i].is_empty() {
1271+ match rx.recv() {
1272+ Ok(chunk) => {
1273+ if i == 0 && emitted == 0 {
1274+ base = chunk.start_sample;
1275+ }
1276+ pending[i] = chunk.samples;
1277+ }
1278+ Err(_) => live[i] = false,
1279+ }
1280+ }
1281+ }
1282+ // The block every lane still playing can cover; `None` once they are all
1283+ // done, which is the only way out of this loop besides a gone consumer.
1284+ let Some(frames) = pending
1285+ .iter()
1286+ .filter(|p| !p.is_empty())
1287+ .map(|p| p.len() / channels)
1288+ .min()
1289+ .filter(|&f| f > 0)
1290+ else {
1291+ return;
1292+ };
1293+ let block = frames * channels;
1294+ out.clear();
1295+ out.resize(block, 0.0);
1296+ for lane in pending.iter_mut().filter(|p| !p.is_empty()) {
1297+ for (sum, sample) in out.iter_mut().zip(lane.drain(..block)) {
1298+ *sum += sample;
1299+ }
1300+ }
1301+ let chunk = AudioChunk {
1302+ start_sample: base + emitted,
1303+ // Clamped, not wrapped: two lanes at full scale are what a mix has
1304+ // to survive, and the device takes `[-1, 1]`.
1305+ samples: out.iter().map(|s| s.clamp(-1.0, 1.0)).collect(),
1306+ };
1307+ if tx.send(chunk).is_err() {
1308+ return; // caller moved on
1309+ }
1310+ emitted += frames as u64;
1311+ }
1312+}
1313+
1196 fn run(mut w: Worker) {1314 fn run(mut w: Worker) {
1197 let mut interleaved = Vec::new();1315 let mut interleaved = Vec::new();
1198 let channels = w.channels;1316 let channels = w.channels;
crates/engine/src/export.rsmodified+43 -18
@@ -31,7 +31,7 @@ use crate::audio::{AudioMeta, AudioSession};
31 use crate::demux::{Demuxer, VideoMeta};31 use crate::demux::{Demuxer, VideoMeta};
32 use crate::hw::{HwEncoder, HwSession};32 use crate::hw::{HwEncoder, HwSession};
33 use crate::mux::{AudioParams, Mp4Muxer, VideoParams};33 use crate::mux::{AudioParams, Mp4Muxer, VideoParams};
34-use crate::project::{Lane, Project};34+use crate::project::Project;
35 35
36 /// Progress is reported in permille: an atomic integer the render loop can read36 /// Progress is reported in permille: an atomic integer the render loop can read
37 /// without a lock, fine enough for any progress bar.37 /// without a lock, fine enough for any progress bar.
@@ -51,7 +51,9 @@ const MAX_BITRATE: u64 = 20_000_000;
51 /// front-end says so rather than hiding the rows.51 /// front-end says so rather than hiding the rows.
52 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]52 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
53 pub enum Format {53 pub enum Format {
54- /// Picture and sound: video re-encoded, AAC copied.54+ /// Picture and sound: video re-encoded, AAC copied. Copied, so it carries
55+ /// **one** audio lane: a timeline whose sound is spread over two is refused
56+ /// by name here and mixed by the other two formats, which decode.
55 #[default]57 #[default]
56 Mp4,58 Mp4,
57 /// The audio lane alone, 16-bit PCM.59 /// The audio lane alone, 16-bit PCM.
@@ -210,10 +212,30 @@ fn run(
210 // The stream each source is copied from is the one it plays: `audio_sources`212 // The stream each source is copied from is the one it plays: `audio_sources`
211 // is the same list `PlaybackSession::seek` hands the decoder, so an export213 // is the same list `PlaybackSession::seek` hands the decoder, so an export
212 // of a timeline playing a file's second audio track carries *that* track.214 // of a timeline playing a file's second audio track carries *that* track.
213- let audio = AudioSession::copy_multi_streams(215+ //
214- &project.audio_sources(),216+ // One lane, because this path *copies* AAC packets and a mix is not a copy:
215- &project.segments_from(0, meta.frame_rate),217+ // summing two lanes means decoding both and encoding the result, and there
216- )?;218+ // is no AAC encoder here to encode it with. Refused by name rather than
219+ // silently exporting the first lane -- a file missing half its sound is the
220+ // one failure a user would not notice.
221+ //
222+ // *Which* lane is the same question `audio_segments_from` answers for
223+ // playback, and it is asked here rather than assumed: the lane that holds
224+ // the sound need not be `A1` (a project may leave `A1` empty and place
225+ // everything on `A2`), and copying `A1`'s list in that case would write a
226+ // file with no audio track at all -- silently, which is the failure this
227+ // whole comment is about.
228+ let lanes = project.audio_segments_from(0, meta.frame_rate);
229+ let [segments] = &lanes[..] else {
230+ return Err(format!(
231+ "this timeline has {} audio lanes and an mp4 export copies one: \
232+ there is no AAC encoder here to mix them with. Export WAV or FLAC, \
233+ which are mixed, or put the sound on one lane",
234+ lanes.len()
235+ )
236+ .into());
237+ };
238+ let audio = AudioSession::copy_multi_streams(&project.audio_sources(), segments)?;
217 let audio_params = audio.as_ref().map(|(track, _)| AudioParams {239 let audio_params = audio.as_ref().map(|(track, _)| AudioParams {
218 freq_index: track.freq_index,240 freq_index: track.freq_index,
219 chan_conf: track.chan_conf,241 chan_conf: track.chan_conf,
@@ -223,10 +245,12 @@ fn run(
223 let mut muxer = None;245 let mut muxer = None;
224 let mut done = 0u32;246 let mut done = 0u32;
225 let black = Black::new(meta);247 let black = Black::new(meta);
226- // Spans, not clips: a gap in the video lane is part of the timeline and248+ // Spans, not clips: a gap in the video is part of the timeline and gets
227- // gets encoded too, as black frames. The picture count is therefore249+ // encoded too, as black frames. The picture count is therefore
228- // `timeline_frames` however the lane is arranged.250+ // `timeline_frames` however the lanes are arranged -- and *which* lane a
229- for span in project.spans_from(Lane::V1, 0) {251+ // span comes from is `composite_spans_from`'s answer, the same one playback
252+ // shows, so an export is what was watched.
253+ for span in project.composite_spans_from(0) {
230 // Every clip reopens its own source file at its own in point; the254 // Every clip reopens its own source file at its own in point; the
231 // encoder is *not* reopened, so the export is one continuous stream255 // encoder is *not* reopened, so the export is one continuous stream
232 // whose GOP boundaries need not line up with the cuts -- nor with the256 // whose GOP boundaries need not line up with the cuts -- nor with the
@@ -279,13 +303,14 @@ fn run(
279 Ok(())303 Ok(())
280 }304 }
281 305
282-/// The audio lane alone, as a WAV or a FLAC.306+/// The audio lanes alone, summed, as a WAV or a FLAC.
283 ///307 ///
284-/// Nothing here re-derives the edit: the play list is308+/// Nothing here re-derives the edit: the play lists are
285-/// [`Project::segments_from`] and it is handed to the very309+/// [`Project::audio_segments_from`] and they are handed to the very
286-/// [`AudioSession::open_multi_streams`] playback feeds from, so what is written310+/// [`AudioSession::open_mixed_streams`] playback feeds from, so what is written
287-/// is what was heard -- gaps included, which arrive as real silence from that311+/// is what was heard -- every lane, mixed the same way, gaps included, which
288-/// choke point rather than as a hole this would have to invent.312+/// arrive as real silence from that choke point rather than as a hole this would
313+/// have to invent.
289 ///314 ///
290 /// The length is the *timeline's*: each segment resolves its window to whole315 /// The length is the *timeline's*: each segment resolves its window to whole
291 /// samples on its own, so the sum can miss the timeline by a sample or two, and316 /// samples on its own, so the sum can miss the timeline by a sample or two, and
@@ -300,8 +325,8 @@ fn run_audio(
300 format: Format,325 format: Format,
301 ) -> crate::Result<()> {326 ) -> crate::Result<()> {
302 let sources = project.audio_sources();327 let sources = project.audio_sources();
303- let segs = project.segments_from(0, meta.frame_rate);328+ let segs = project.audio_segments_from(0, meta.frame_rate);
304- let Some((audio, chunks)) = AudioSession::open_multi_streams(&sources, &segs)? else {329+ let Some((audio, chunks)) = AudioSession::open_mixed_streams(&sources, &segs)? else {
305 return Err("this timeline has no audio to export".into());330 return Err("this timeline has no audio to export".into());
306 };331 };
307 let channels = usize::from(audio.channels);332 let channels = usize::from(audio.channels);
crates/engine/src/playback.rsmodified+9 -6
@@ -149,7 +149,7 @@ impl PlaybackSession {
149 // One clip per lane covering the file, so timeline == source until the149 // One clip per lane covering the file, so timeline == source until the
150 // first edit -- and the range opened above is exactly that clip's.150 // first edit -- and the range opened above is exactly that clip's.
151 let project = Project::single(&path, meta.frame_count);151 let project = Project::single(&path, meta.frame_count);
152- let span = project.span_at(Lane::V1, 0).expect("never empty");152+ let span = project.composite_span_at(0).expect("never empty");
153 Ok(Self {153 Ok(Self {
154 meta,154 meta,
155 frames: stream.frames,155 frames: stream.frames,
@@ -247,7 +247,7 @@ impl PlaybackSession {
247 247
248 let playhead = doc.playhead;248 let playhead = doc.playhead;
249 let project = Project::from_parts(doc.sources, doc.lanes, doc.eq)?;249 let project = Project::from_parts(doc.sources, doc.lanes, doc.eq)?;
250- let span = project.span_at(Lane::V1, 0).expect("never empty");250+ let span = project.composite_span_at(0).expect("never empty");
251 // Last, because it is the one thing here that cannot be taken back: the251 // Last, because it is the one thing here that cannot be taken back: the
252 // feeder thread outlives the `Audio` value (it holds its own clones) and252 // feeder thread outlives the `Audio` value (it holds its own clones) and
253 // only a session's `drop` retires it, so a refusal above this line would253 // only a session's `drop` retires it, so a refusal above this line would
@@ -364,7 +364,7 @@ impl PlaybackSession {
364 /// clip under the running worker and only the mapping stays true.364 /// clip under the running worker and only the mapping stays true.
365 fn next_clip(&mut self) -> bool {365 fn next_clip(&mut self) -> bool {
366 let next = self.span.end();366 let next = self.span.end();
367- let Some(span) = self.project.span_at(Lane::V1, next) else {367+ let Some(span) = self.project.composite_span_at(next) else {
368 return false;368 return false;
369 };369 };
370 // We only get here on a disconnect, so the old worker has already370 // We only get here on a disconnect, so the old worker has already
@@ -759,7 +759,7 @@ impl PlaybackSession {
759 // `target` is inside the timeline (never empty), so this always spans;759 // `target` is inside the timeline (never empty), so this always spans;
760 // the span runs from there to the end of whatever it landed in -- a760 // the span runs from there to the end of whatever it landed in -- a
761 // clip, or a gap, which starts a black-frame worker instead.761 // clip, or a gap, which starts a black-frame worker instead.
762- if let Some(span) = self.project.span_at(Lane::V1, target) {762+ if let Some(span) = self.project.composite_span_at(target) {
763 self.start_span(span);763 self.start_span(span);
764 }764 }
765 self.eos = false;765 self.eos = false;
@@ -777,11 +777,14 @@ impl PlaybackSession {
777 // between clips are gapless: the video reopens at a boundary, the777 // between clips are gapless: the video reopens at a boundary, the
778 // ear never hears it -- and a join between two *files* is just778 // ear never hears it -- and a join between two *files* is just
779 // another segment, because every segment names its own source.779 // another segment, because every segment names its own source.
780- let segs = self.project.segments_from(target, fps);780+ // One play list per audio lane, summed by the mixer: what the ear
781+ // hears is every lane at once, and a lane's own gaps are silence in
782+ // it rather than a hole in the count the master clock keeps.
783+ let segs = self.project.audio_segments_from(target, fps);
781 // Each source on the stream it was placed with: what plays is what784 // Each source on the stream it was placed with: what plays is what
782 // the library row said, and what an export copies (`export::run`).785 // the library row said, and what an export copies (`export::run`).
783 let sources = self.project.audio_sources();786 let sources = self.project.audio_sources();
784- audio_running = match AudioSession::open_multi_streams(&sources, &segs) {787+ audio_running = match AudioSession::open_mixed_streams(&sources, &segs) {
785 Ok(Some((_, rx))) => audio.spawn_feeder(rx),788 Ok(Some((_, rx))) => audio.spawn_feeder(rx),
786 _ => false,789 _ => false,
787 };790 };
crates/engine/src/project.rsmodified+234 -3
@@ -15,8 +15,10 @@
15 //! splice of the list;15 //! splice of the list;
16 //! * the lanes are independent and are peers: deleting audio under a picture is16 //! * the lanes are independent and are peers: deleting audio under a picture is
17 //! one lane's business, and the picture does not shift. No lane is special17 //! one lane's business, and the picture does not shift. No lane is special
18-//! except by what a *caller* reads -- playback and export take `V1`, the audio18+//! except by what a *caller* reads -- and what playback and export read is the
19-//! worker takes `A1`, until a compositing slice teaches them the rest.19+//! whole stack: [`Project::composite_span_at`] resolves the video lanes to the
20+//! one picture that shows, [`Project::audio_segments_from`] hands every audio
21+//! lane over to be summed.
20 //!22 //!
21 //! The price is one invariant this module enforces at every mutation and every23 //! The price is one invariant this module enforces at every mutation and every
22 //! constructor: within a lane, clips are **sorted by `start` and never overlap**24 //! constructor: within a lane, clips are **sorted by `start` and never overlap**
@@ -638,6 +640,80 @@ impl Project {
638 out640 out
639 }641 }
640 642
643+ /// What the *composite* shows from `timeline_frame` on -- the answer
644+ /// [`span_at`](Project::span_at) gives for one lane, resolved across every
645+ /// video lane by one rule: **the topmost lane with a clip there wins**, and
646+ /// topmost is the *last* video lane in display order, so `V2` covers `V1`
647+ /// (the usual overlay convention). A frame no video lane covers is a gap,
648+ /// which is black however many lanes are above or below it.
649+ ///
650+ /// No blending, so exactly one lane is visible at a time and the composite
651+ /// is itself a span list -- which is why one decoder plays it, the same one
652+ /// a single-lane timeline uses, rather than N running at once.
653+ ///
654+ /// The span is cut short wherever a *higher* lane's clip starts, because
655+ /// from that frame on a different lane wins; that is what makes walking
656+ /// [`composite_spans_from`](Project::composite_spans_from) correct.
657+ ///
658+ /// ponytail: alpha, opacity or any blend mode makes this untrue -- two
659+ /// lanes would then be visible in one frame and the caller needs a decoder
660+ /// per lane plus a compositor. Upgrade path is a `Vec<Span>` per frame
661+ /// (this same walk, per lane) feeding N decoders.
662+ pub fn composite_span_at(&self, timeline_frame: u32) -> Option<Span> {
663+ let total = self.timeline_frames();
664+ if timeline_frame >= total {
665+ return None;
666+ }
667+ let video: Vec<Lane> = self
668+ .lanes()
669+ .into_iter()
670+ .filter(|l| l.kind == LaneKind::Video)
671+ .collect();
672+ // The last covering lane is the winner; only the lanes above it can
673+ // interrupt what it shows.
674+ let winner = video
675+ .iter()
676+ .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some());
677+ let (from, until) = match winner {
678+ Some(i) => {
679+ let clips = self.lane(video[i]);
680+ let idx = at(clips, timeline_frame).expect("just found above");
681+ (
682+ Some((
683+ clips[idx].source,
684+ clips[idx].in_frame + (timeline_frame - clips[idx].start),
685+ )),
686+ clips[idx].end(),
687+ )
688+ }
689+ // Nothing covers it: black until something above the floor starts.
690+ None => (None, total),
691+ };
692+ let takeover = video[winner.map_or(0, |i| i + 1)..]
693+ .iter()
694+ .filter_map(|&lane| self.lane(lane).iter().find(|c| c.start > timeline_frame))
695+ .map(|c| c.start)
696+ .min();
697+ Some(Span {
698+ start: timeline_frame,
699+ len: takeover.map_or(until, |t| t.min(until)) - timeline_frame,
700+ from,
701+ })
702+ }
703+
704+ /// [`spans_from`](Project::spans_from) over the composite: every stretch the
705+ /// viewer sees from `timeline_frame` to the end, in order. What an export
706+ /// encodes and what playback walks at a clip boundary.
707+ pub fn composite_spans_from(&self, timeline_frame: u32) -> Vec<Span> {
708+ let mut out = Vec::new();
709+ let mut t = timeline_frame;
710+ while let Some(span) = self.composite_span_at(t) {
711+ t = span.end();
712+ out.push(span);
713+ }
714+ out
715+ }
716+
641 /// Split every lane at `timeline_frame`, so that frame becomes the first717 /// Split every lane at `timeline_frame`, so that frame becomes the first
642 /// frame of a new clip, and hand the two sides two fresh group ids. Refused718 /// frame of a new clip, and hand the two sides two fresh group ids. Refused
643 /// (`false`, no change) when no lane has a clip to split there -- at a719 /// (`false`, no change) when no lane has a clip to split there -- at a
@@ -858,10 +934,20 @@ impl Project {
858 /// The first entry is partial when the position is mid-clip. Empty when the934 /// The first entry is partial when the position is mid-clip. Empty when the
859 /// position is past the end or `fps` is not usable.935 /// position is past the end or `fps` is not usable.
860 pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(Option<usize>, f64, f64)> {936 pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(Option<usize>, f64, f64)> {
937+ self.lane_segments_from(Lane::A1, timeline_frame, fps)
938+ }
939+
940+ /// [`segments_from`](Project::segments_from) for a named lane.
941+ pub fn lane_segments_from(
942+ &self,
943+ lane: Lane,
944+ timeline_frame: u32,
945+ fps: f64,
946+ ) -> Vec<(Option<usize>, f64, f64)> {
861 if !(fps.is_finite() && fps > 0.0) {947 if !(fps.is_finite() && fps > 0.0) {
862 return Vec::new();948 return Vec::new();
863 }949 }
864- self.spans_from(Lane::A1, timeline_frame)950+ self.spans_from(lane, timeline_frame)
865 .iter()951 .iter()
866 .map(|span| match span.from {952 .map(|span| match span.from {
867 // A clip's window is in *source* seconds: where in the file it953 // A clip's window is in *source* seconds: where in the file it
@@ -877,6 +963,32 @@ impl Project {
877 .collect()963 .collect()
878 }964 }
879 965
966+ /// One play list per audio lane that *holds* something, in display order --
967+ /// what the mixer sums ([`crate::AudioSession::open_mixed_streams`]) and
968+ /// what an export asks how many lanes it would have to mix.
969+ ///
970+ /// Never empty: a timeline whose audio lanes are all empty (or which has no
971+ /// audio lane at all) still yields one all-gap list, so it plays silence
972+ /// against a master clock exactly as it did before there were lanes to
973+ /// count. Lanes with nothing on them are left out rather than mixed in as
974+ /// silence: they would cost a decode thread each and add zero.
975+ pub fn audio_segments_from(
976+ &self,
977+ timeline_frame: u32,
978+ fps: f64,
979+ ) -> Vec<Vec<(Option<usize>, f64, f64)>> {
980+ let lists: Vec<_> = self
981+ .lanes()
982+ .into_iter()
983+ .filter(|l| l.kind == LaneKind::Audio && !self.lane(*l).is_empty())
984+ .map(|lane| self.lane_segments_from(lane, timeline_frame, fps))
985+ .collect();
986+ match lists.is_empty() {
987+ true => vec![self.lane_segments_from(Lane::A1, timeline_frame, fps)],
988+ false => lists,
989+ }
990+ }
991+
880 /// Pushes the undo snapshot. Every mutating method calls this once, *after*992 /// Pushes the undo snapshot. Every mutating method calls this once, *after*
881 /// it has decided it will succeed -- a refusal must not cost an undo step.993 /// it has decided it will succeed -- a refusal must not cost an undo step.
882 fn snapshot(&mut self) {994 fn snapshot(&mut self) {
@@ -2416,4 +2528,123 @@ mod tests {
2416 }2528 }
2417 }2529 }
2418 }2530 }
2531+
2532+ /// The compositing rule, in one walk: `V2` covers `V1` while it has a clip
2533+ /// there, `V1` shows again on either side of it, and a frame no video lane
2534+ /// covers is a gap however many lanes there are.
2535+ #[test]
2536+ fn the_composite_is_the_topmost_lane_with_a_clip() {
2537+ let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
2538+ let lanes = vec![
2539+ // V1: the whole 30 frames of source 0.
2540+ (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
2541+ // V2: source 1 over the middle third.
2542+ (LaneKind::Video, vec![clip(10, 5, 15, 1)]),
2543+ (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
2544+ ];
2545+ let p = Project::from_parts(sources, lanes, vec![]).expect("valid parts");
2546+ assert_eq!(
2547+ p.composite_spans_from(0),
2548+ vec![
2549+ Span {
2550+ start: 0,
2551+ len: 10,
2552+ from: Some((0, 0))
2553+ },
2554+ Span {
2555+ start: 10,
2556+ len: 10,
2557+ from: Some((1, 5))
2558+ },
2559+ Span {
2560+ start: 20,
2561+ len: 10,
2562+ from: Some((0, 20))
2563+ },
2564+ ],
2565+ "V2 takes over for its own span and hands V1 back"
2566+ );
2567+ // A mid-span ask resolves the same way, which is what a seek does.
2568+ assert_eq!(
2569+ p.composite_span_at(15),
2570+ Some(Span {
2571+ start: 15,
2572+ len: 5,
2573+ from: Some((1, 10))
2574+ })
2575+ );
2576+ assert_eq!(p.composite_span_at(30), None, "past the end");
2577+
2578+ // A hole in V1 under V2's clip: black between the two, and black after
2579+ // both run out (the audio lane is still holding the timeline open).
2580+ let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
2581+ let holed = vec![
2582+ (LaneKind::Video, vec![clip(0, 0, 5, 0)]),
2583+ (LaneKind::Video, vec![clip(10, 0, 10, 1)]),
2584+ (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
2585+ ];
2586+ let p = Project::from_parts(sources, holed, vec![]).expect("valid parts");
2587+ assert_eq!(
2588+ p.composite_spans_from(0),
2589+ vec![
2590+ Span {
2591+ start: 0,
2592+ len: 5,
2593+ from: Some((0, 0))
2594+ },
2595+ Span {
2596+ start: 5,
2597+ len: 5,
2598+ from: None
2599+ },
2600+ Span {
2601+ start: 10,
2602+ len: 10,
2603+ from: Some((1, 0))
2604+ },
2605+ Span {
2606+ start: 20,
2607+ len: 10,
2608+ from: None
2609+ },
2610+ ]
2611+ );
2612+
2613+ // One video lane: the composite *is* that lane, span for span -- the
2614+ // promise every existing two-lane project rests on.
2615+ let p = Project::single(FILE, 30);
2616+ assert_eq!(p.composite_spans_from(0), p.spans_from(Lane::V1, 0));
2617+ assert_eq!(p.composite_span_at(7), p.span_at(Lane::V1, 7));
2618+ }
2619+
2620+ /// Every audio lane holding something gets a play list, and only those.
2621+ #[test]
2622+ fn audio_segments_cover_every_lane_that_holds_something() {
2623+ let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)];
2624+ let lanes = vec![
2625+ (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
2626+ (LaneKind::Audio, vec![clip(0, 0, 30, 0)]),
2627+ (LaneKind::Audio, vec![clip(15, 0, 15, 1)]),
2628+ (LaneKind::Audio, Vec::new()),
2629+ ];
2630+ let p = Project::from_parts(sources, lanes, vec![]).expect("valid parts");
2631+ let lists = p.audio_segments_from(0, FPS);
2632+ assert_eq!(lists.len(), 2, "the empty lane is not mixed in");
2633+ assert_eq!(lists[0], p.segments_from(0, FPS), "A1 is unchanged");
2634+ // A2 is a gap up to frame 15, then the whole of source 1.
2635+ assert_eq!(lists[1], vec![(None, 0.0, 0.5), (Some(1), 0.0, 0.5)]);
2636+
2637+ // No audio lane holds anything: one all-gap list, so such a timeline
2638+ // still plays silence against a master clock.
2639+ let p = Project::from_parts(
2640+ vec![Source::new(FILE, 0)],
2641+ vec![
2642+ (LaneKind::Video, vec![clip(0, 0, 30, 0)]),
2643+ (LaneKind::Audio, Vec::new()),
2644+ ],
2645+ vec![],
2646+ )
2647+ .expect("valid parts");
2648+ assert_eq!(p.audio_segments_from(0, FPS), vec![vec![(None, 0.0, 1.0)]]);
2649+ }
2419 }2650 }
crates/engine/tests/lanes.rsadded+380 -0
@@ -0,0 +1,380 @@
1+//! N lanes, composited: what a timeline with a `V2` over its `V1` and an `A2`
2+//! over its `A1` plays, and that an export of it is the same thing.
3+//!
4+//! The fixtures are the two video assets, which differ picture for picture, so
5+//! "which lane is showing" is answered by comparing the decoded frame against
6+//! each source rather than by trusting the edit list.
7+//!
8+//! ```text
9+//! cargo test -p engine --release --test lanes -- --nocapture
10+//! ```
11+
12+use std::path::{Path, PathBuf};
13+use std::sync::Once;
14+use std::time::{Duration, Instant};
15+
16+use engine::export::{ExportSettings, Format};
17+use engine::project::{Clip, LaneKind, Source};
18+use engine::{DecodeSession, ExportHandle, PlaybackSession, Project};
19+
20+const FPS: f64 = 30.0;
21+/// `test_av.mp4` is 150 frames, `test_av2.mp4` 120; the top lane covers the
22+/// middle third of the first.
23+const TOTAL: u32 = 150;
24+const TOP_IN: u32 = 50;
25+const TOP_OUT: u32 = 100;
26+
27+fn asset(name: &str) -> PathBuf {
28+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
29+ .join("../../assets")
30+ .join(name)
31+}
32+
33+/// Software on both halves, so this suite proves the composite on any machine
34+/// rather than whatever the local VA-API driver does.
35+fn pin_software() {
36+ static PIN: Once = Once::new();
37+ PIN.call_once(|| unsafe {
38+ std::env::set_var("VE_SW", "1");
39+ std::env::set_var("VE_SW_ENC", "1");
40+ });
41+}
42+
43+/// Per-run unique, like the export suite's: two suites at once must not write
44+/// each other's files.
45+fn out_path(name: &str, ext: &str) -> PathBuf {
46+ let path = std::env::temp_dir().join(format!("ve_lanes_{name}_{}.{ext}", std::process::id()));
47+ let _ = std::fs::remove_file(&path);
48+ path
49+}
50+
51+/// A hand-written v4 project: `V1` the whole of `test_av`, `V2` the middle
52+/// third playing `test_av2` from its own frame 0, `A1` the whole of `test_av`.
53+/// Exactly the file a user would write by hand, parsed by the real loader.
54+fn three_lane_file() -> PathBuf {
55+ let path = out_path("project", "edith");
56+ // `source <audio stream> <path>`: the number is which audio track of the
57+ // file plays, not the source index -- both of these are on their first.
58+ let text = format!(
59+ "edith 4\nplayhead 0\nsource 0 {}\nsource 0 {}\n\
60+ video 1 0 0 {TOTAL} 0 -\naudio 1 0 0 {TOTAL} 0 -\n\
61+ video 2 {TOP_IN} 0 {} 1 -\n",
62+ asset("test_av.mp4").display(),
63+ asset("test_av2.mp4").display(),
64+ TOP_OUT - TOP_IN,
65+ );
66+ std::fs::write(&path, text).expect("write the project file");
67+ path
68+}
69+
70+/// One frame of `path` by absolute index, BGRA.
71+fn frame_at(path: &Path, index: u32) -> Vec<u8> {
72+ let (_, frames, _) = DecodeSession::open_at(path, index).expect("open source");
73+ frames.recv().expect("frame present").bgra
74+}
75+
76+fn mean_abs_diff(a: &[u8], b: &[u8]) -> f64 {
77+ assert_eq!(a.len(), b.len(), "frame sizes differ");
78+ a.iter()
79+ .zip(b)
80+ .map(|(x, y)| f64::from(x.abs_diff(*y)))
81+ .sum::<f64>()
82+ / a.len() as f64
83+}
84+
85+/// Which of the two sources `frame` came from, by picture: the near one wins,
86+/// and the assertion is that the other is nowhere near.
87+fn assert_from(frame: &[u8], source: &str, source_frame: u32, timeline: u32) {
88+ let other = match source {
89+ "test_av.mp4" => "test_av2.mp4",
90+ _ => "test_av.mp4",
91+ };
92+ let mine = mean_abs_diff(frame, &frame_at(&asset(source), source_frame));
93+ let theirs = mean_abs_diff(frame, &frame_at(&asset(other), source_frame));
94+ println!("timeline {timeline}: {source} {source_frame} diff {mine:.2}, {other} {theirs:.2}");
95+ assert!(
96+ mine < 6.0,
97+ "timeline frame {timeline} drifted by {mine:.2} from {source} frame {source_frame}"
98+ );
99+ assert!(
100+ theirs > 4.0 * mine.max(0.5),
101+ "the two sources are too alike at frame {source_frame} for this test to mean anything"
102+ );
103+}
104+
105+fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> {
106+ let started = Instant::now();
107+ while !handle.is_finished() {
108+ assert!(
109+ started.elapsed() < limit,
110+ "export did not finish in {limit:?}"
111+ );
112+ std::thread::sleep(Duration::from_millis(20));
113+ }
114+ handle.result().expect("a finished export has an outcome")
115+}
116+
117+/// Plays the session up to `timeline` and hands back the frame shown there.
118+/// Times it, because a lane change costs exactly one decoder reopen -- the
119+/// composite is one span list, so N video lanes never mean N decoders.
120+fn frame_of(session: &mut PlaybackSession, timeline: u32) -> Vec<u8> {
121+ let started = Instant::now();
122+ session.seek(f64::from(timeline) / FPS);
123+ let deadline = Instant::now() + Duration::from_secs(20);
124+ loop {
125+ session.tick();
126+ if let Some(frame) = session.try_frame() {
127+ assert_eq!(frame.index, timeline, "a seek shows the frame it landed on");
128+ println!(
129+ "frame {timeline} ready {:.0} ms after the seek",
130+ started.elapsed().as_secs_f64() * 1000.0
131+ );
132+ return frame.bgra;
133+ }
134+ assert!(Instant::now() < deadline, "no frame at timeline {timeline}");
135+ std::thread::sleep(Duration::from_millis(5));
136+ }
137+}
138+
139+/// The slice, from the front door: a hand-written project with a second video
140+/// lane opens and *plays* the top lane where it has a clip, the one under it
141+/// everywhere else.
142+#[test]
143+fn playback_shows_the_topmost_video_lane() {
144+ pin_software();
145+ let project = three_lane_file();
146+ let mut session = PlaybackSession::open_project(&project).expect("open the project");
147+ session.set_gain(0.0);
148+ assert_eq!(session.timeline_duration(), f64::from(TOTAL) / FPS);
149+
150+ // Before the top lane starts, inside it, and after it ends.
151+ let head = frame_of(&mut session, 10);
152+ assert_from(&head, "test_av.mp4", 10, 10);
153+ let over = frame_of(&mut session, TOP_IN + 10);
154+ assert_from(&over, "test_av2.mp4", 10, TOP_IN + 10);
155+ let tail = frame_of(&mut session, TOP_OUT + 10);
156+ assert_from(&tail, "test_av.mp4", TOP_OUT + 10, TOP_OUT + 10);
157+
158+ std::fs::remove_file(&project).unwrap();
159+}
160+
161+/// Export is playback: the same project written out and decoded back shows the
162+/// same lane at the same frame.
163+#[test]
164+fn export_writes_the_same_composite() {
165+ pin_software();
166+ let file = three_lane_file();
167+ let session = PlaybackSession::open_project(&file).expect("open the project");
168+ let out = out_path("composite", "mp4");
169+
170+ let started = Instant::now();
171+ let handle = session.export_to(&out);
172+ wait(&handle, Duration::from_secs(300)).expect("export");
173+ println!(
174+ "composite export: {TOTAL} frames in {:.2} s",
175+ started.elapsed().as_secs_f64()
176+ );
177+
178+ let (meta, _) = engine::demux::Demuxer::open(&out).expect("reopen the export");
179+ assert_eq!(meta.frame_count, TOTAL, "timeline frames written");
180+ let (_, frames) = DecodeSession::open(&out).expect("decode the export");
181+ let frames: Vec<Vec<u8>> = frames.into_iter().map(|f| f.bgra).collect();
182+ assert_eq!(frames.len() as u32, TOTAL);
183+ assert_from(&frames[10], "test_av.mp4", 10, 10);
184+ assert_from(
185+ &frames[(TOP_IN + 10) as usize],
186+ "test_av2.mp4",
187+ 10,
188+ TOP_IN + 10,
189+ );
190+ assert_from(
191+ &frames[(TOP_OUT + 10) as usize],
192+ "test_av.mp4",
193+ TOP_OUT + 10,
194+ TOP_OUT + 10,
195+ );
196+
197+ std::fs::remove_file(&file).unwrap();
198+ std::fs::remove_file(&out).unwrap();
199+}
200+
201+/// Every sample of `path`'s first audio stream, interleaved -- what the export
202+/// wrote, read back through the engine's own decoder.
203+fn decoded_audio(path: &Path) -> Vec<f32> {
204+ let sources = [(path.to_path_buf(), 0)];
205+ let (_, chunks) =
206+ engine::AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)])
207+ .expect("open the audio")
208+ .expect("there is an audio track");
209+ chunks.into_iter().flat_map(|c| c.samples).collect()
210+}
211+
212+fn rms(samples: &[f32]) -> f64 {
213+ assert!(!samples.is_empty(), "no samples to measure");
214+ (samples
215+ .iter()
216+ .map(|s| f64::from(*s) * f64::from(*s))
217+ .sum::<f64>()
218+ / samples.len() as f64)
219+ .sqrt()
220+}
221+
222+/// The sound need not be on `A1`: a project that leaves `A1` empty and places
223+/// everything on `A2` is still *one* audio lane, so the mp4 export copies it
224+/// rather than refusing -- and rather than writing a file with no audio track
225+/// at all, which is what pinning the copy to `A1` did (verifier's repro: the
226+/// export succeeded, ffprobe showed video only, and nobody would notice until
227+/// they played it).
228+#[test]
229+fn the_mp4_copy_follows_the_lane_that_holds_the_sound() {
230+ pin_software();
231+ let source = asset("test_av.mp4");
232+ let clip = Clip {
233+ start: 0,
234+ in_frame: 0,
235+ out_frame: TOTAL,
236+ source: 0,
237+ link: None,
238+ eq: None,
239+ };
240+ let project = Project::from_parts(
241+ vec![Source::new(&source, 0)],
242+ vec![
243+ (LaneKind::Video, vec![clip]),
244+ (LaneKind::Audio, Vec::new()),
245+ (LaneKind::Audio, vec![clip]),
246+ ],
247+ vec![],
248+ )
249+ .expect("valid parts");
250+ assert_eq!(
251+ project.audio_segments_from(0, FPS).len(),
252+ 1,
253+ "one lane holds sound, so this is not a mix"
254+ );
255+
256+ let out = out_path("a2_only", "mp4");
257+ let (meta, _) = engine::demux::Demuxer::open(&source).unwrap();
258+ let handle = engine::export::start(project, meta, &out, &ExportSettings::default());
259+ wait(&handle, Duration::from_secs(300)).expect("export the A2-only timeline");
260+
261+ let written = decoded_audio(&out);
262+ let played = decoded_audio(&source);
263+ println!(
264+ "A2-only export: {} samples rms {:.4}, source {} samples rms {:.4}",
265+ written.len(),
266+ rms(&written),
267+ played.len(),
268+ rms(&played)
269+ );
270+ assert!(rms(&written) > 0.001, "the export has to carry the sound");
271+ assert!(
272+ (rms(&written) / rms(&played) - 1.0).abs() < 0.05,
273+ "the exported audio is not the lane's content"
274+ );
275+ std::fs::remove_file(&out).unwrap();
276+}
277+
278+/// `A1` and `A2` playing the *same* source range at the same place: over that
279+/// stretch the mix is that audio twice over, so it measures at exactly double
280+/// the level the one-lane export of the same timeline has there -- and outside
281+/// it, at the same level. The comparison is against the same window of the same
282+/// content, because the fixture's own level moves and comparing two *stretches*
283+/// would measure the fixture rather than the mixer.
284+#[test]
285+fn two_audio_lanes_are_summed() {
286+ pin_software();
287+ let one_lane = Project::single(asset("test_av.mp4"), TOTAL);
288+ let mut project = one_lane.clone();
289+ let doubled = Clip {
290+ start: TOP_IN,
291+ in_frame: TOP_IN,
292+ out_frame: TOP_OUT,
293+ source: 0,
294+ link: None,
295+ eq: None,
296+ };
297+ let a2 = project.add_lane(LaneKind::Audio);
298+ assert!(project.place(a2, TOP_IN, doubled), "place the second lane");
299+ let (sources, lanes, eq) = project.without_orphan_sources();
300+ assert_eq!(lanes.len(), 3, "V1, A1 and the new A2");
301+ let project = Project::from_parts(sources, lanes, eq).expect("valid parts");
302+
303+ let (meta, _) = engine::demux::Demuxer::open(&asset("test_av.mp4")).unwrap();
304+ let wav = |name: &str, project: Project| {
305+ let out = out_path(name, "wav");
306+ let settings = ExportSettings {
307+ format: Format::Wav,
308+ ..Default::default()
309+ };
310+ let handle = engine::export::start(project, meta, &out, &settings);
311+ wait(&handle, Duration::from_secs(120)).expect("wav export");
312+ let mut reader = hound::WavReader::open(&out).expect("reopen the wav");
313+ let spec = reader.spec();
314+ let samples: Vec<f64> = reader
315+ .samples::<i16>()
316+ .map(|s| f64::from(s.expect("sample")))
317+ .collect();
318+ std::fs::remove_file(&out).unwrap();
319+ (spec, samples)
320+ };
321+ let (spec, plain) = wav("one_lane", one_lane);
322+ let (_, mixed) = wav("mixed", project.clone());
323+ assert_eq!(plain.len(), mixed.len(), "both are the timeline's length");
324+
325+ let rms = |samples: &[f64], from: u32, to: u32| {
326+ let per = f64::from(spec.sample_rate) / FPS * f64::from(spec.channels);
327+ let (a, b) = (
328+ (f64::from(from) * per) as usize,
329+ (f64::from(to) * per) as usize,
330+ );
331+ let window = &samples[a..b.min(samples.len())];
332+ (window.iter().map(|s| s * s).sum::<f64>() / window.len() as f64).sqrt()
333+ };
334+ // A margin inside each region: a segment boundary lands on a packet edge,
335+ // and this measures the middle of a stretch, not the seam.
336+ let (over_one, over_two) = (
337+ rms(&plain, TOP_IN + 5, TOP_OUT - 5),
338+ rms(&mixed, TOP_IN + 5, TOP_OUT - 5),
339+ );
340+ let (out_one, out_two) = (
341+ rms(&plain, TOP_OUT + 5, TOTAL - 5),
342+ rms(&mixed, TOP_OUT + 5, TOTAL - 5),
343+ );
344+ println!("rms under A2: one lane {over_one:.1}, mixed {over_two:.1}");
345+ println!("rms past A2: one lane {out_one:.1}, mixed {out_two:.1}");
346+ assert!(over_one > 100.0, "the fixture has to be audible to measure");
347+ assert!(
348+ (over_two / over_one - 2.0).abs() < 0.05,
349+ "the overlap is {:.3}x one lane, not 2x",
350+ over_two / over_one
351+ );
352+ assert!(
353+ (out_two / out_one - 1.0).abs() < 0.05,
354+ "past the second lane the level is back to one lane's ({:.3}x)",
355+ out_two / out_one
356+ );
357+
358+ // The mp4 path *copies* AAC packets and cannot mix: it refuses by name
359+ // rather than writing a file missing half its sound.
360+ let out = out_path("mixed", "mp4");
361+ let handle = engine::export::start(project, meta, &out, &ExportSettings::default());
362+ let err = wait(&handle, Duration::from_secs(120)).expect_err("mp4 cannot mix");
363+ println!("mp4 refusal: {err}");
364+ assert!(err.to_string().contains("2 audio lanes"), "{err}");
365+ assert!(!out.exists(), "a refused export leaves no file");
366+}
367+
368+/// A project with one lane of each kind is what it always was: the composite of
369+/// a single video lane is that lane, and its audio is one un-mixed stream.
370+#[test]
371+fn one_lane_projects_are_untouched() {
372+ let project = Project::single(asset("test_av.mp4"), TOTAL);
373+ assert_eq!(
374+ project.composite_spans_from(0),
375+ project.spans_from(engine::project::Lane::V1, 0)
376+ );
377+ let lists = project.audio_segments_from(0, FPS);
378+ assert_eq!(lists, vec![project.segments_from(0, FPS)]);
379+ assert_eq!(project.sources(), [Source::new(asset("test_av.mp4"), 0)]);
380+}