From 08af6bc080fd66811a99a87ecc234bf7337c33bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 10 Aug 2026 10:38:07 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(engine):=20N-lane=20compositin?= =?UTF-8?q?g=20in=20playback=20and=20export?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Video: the topmost video lane with a clip there wins, topmost being the last lane in display order (V2 over V1, the overlay convention). No blending, so exactly one lane is visible per frame and the composite is itself a span list -- Project::composite_span_at -- which one decoder plays. N video lanes never mean N decoders; a lane change costs the one decoder reopen a cut already costs. Audio: every audio lane that holds something gets a play list (Project::audio_segments_from) and AudioSession::open_mixed_streams sums them, clamped, each lane keeping its own gap rule so the master clock counts a sample per sample of timeline. One lane skips the mixer entirely and is the byte-for- byte path it always was. Export walks the same composite and mixes the same lanes for WAV/FLAC. The mp4 path copies AAC packets and cannot mix, so a timeline whose sound is spread over two lanes is refused there by name rather than silently exported without half of it. --- crates/engine/src/audio.rs | 118 +++++++++++++ crates/engine/src/export.rs | 49 ++++-- crates/engine/src/playback.rs | 15 +- crates/engine/src/project.rs | 236 +++++++++++++++++++++++++- crates/engine/tests/lanes.rs | 302 ++++++++++++++++++++++++++++++++++ 5 files changed, 697 insertions(+), 23 deletions(-) create mode 100644 crates/engine/tests/lanes.rs diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index d3e44cc..5ab7ea1 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -10,6 +10,11 @@ //! same samples either way; only the packet copy asks which reader it came from, //! because there is nothing to copy out of an mp3 that an mp4 can hold. //! +//! One output, however many lanes: a timeline's audio lanes are decoded side by +//! side and summed ([`AudioSession::open_mixed_streams`]), which is what both +//! the device and an audio-only export are handed. One lane skips the mixer +//! entirely and is the plain single-stream path it always was. +//! //! Both readers are addressed as `(path, stream)`. An mp4 may carry several //! audio tracks and the caller picks one; a standalone audio file carries //! exactly one, so any stream above 0 there is an `Err` rather than a silent @@ -292,6 +297,53 @@ impl AudioSession { Ok(Some((meta, rx))) } + /// Every audio lane of a timeline, summed into one stream: `lanes` is one + /// play list per lane, each in the shape + /// [`open_multi_streams`](Self::open_multi_streams) takes, and what comes + /// out is what the device hears -- the lanes decoded side by side and added + /// sample for sample, clamped to `[-1, 1]` so a loud pair cannot wrap the + /// output. + /// + /// **One lane is not mixed at all**: it is `open_multi_streams` verbatim, so + /// a timeline with a single audio lane decodes exactly the samples it always + /// did, down to the bit and down to the thread count. + /// + /// Lengths need not agree: a lane that has run out contributes silence to + /// what is left, which is what a shorter lane means. Each lane keeps its own + /// gap rule -- a hole in it is real silence from its own worker, not a + /// skipped chunk -- so the sum feeds the master clock a sample per sample of + /// timeline however the lanes are arranged. `start_sample` numbers from the + /// first lane's own start (see [`AudioChunk`]). + pub fn open_mixed_streams( + sources: &[(PathBuf, usize)], + lanes: &[Vec<(Option, f64, f64)>], + ) -> crate::Result)>> { + let [first, rest @ ..] = lanes else { + return Ok(None); + }; + if rest.is_empty() { + return Self::open_multi_streams(sources, first); + } + let mut meta = None; + let mut rxs = Vec::with_capacity(lanes.len()); + for segs in lanes { + // Every lane probes the same source 0, so the metas agree by + // construction; `None` from any of them is a silent timeline. + let Some((lane_meta, rx)) = Self::open_multi_streams(sources, segs)? else { + return Ok(None); + }; + meta = Some(lane_meta); + rxs.push(rx); + } + let meta = meta.expect("at least two lanes opened above"); + let (tx, rx) = sync_channel(32); + let channels = usize::from(meta.channels); + thread::Builder::new() + .name("audio-mix".into()) + .spawn(move || mix(&rxs, channels, &tx))?; + Ok(Some((meta, rx))) + } + /// Why [`open`](Self::open) came back silent for a file that *has* sound: /// `Some(reason)` when there is an audio track and it is not the AAC-LC /// this decodes (an AC-3 remux, say). `None` when the file is simply silent @@ -1170,6 +1222,72 @@ struct Worker { tx: SyncSender, } +/// Sums one worker per lane into one stream (see +/// [`AudioSession::open_mixed_streams`]). Every lane starts at the same timeline +/// position and synthesises its own gaps, so the lanes are sample-aligned by +/// construction and a mix is an add: no resampling, no positioning, no drift to +/// correct. What is emitted at each turn is the shortest block every still-live +/// lane can supply, which keeps a slow lane from being outrun and never buffers +/// more than the chunks already in flight. +/// +/// A lane whose channel has closed has ended and simply stops being added -- +/// that is what "shorter lane" means here. The mix ends when all of them have. +/// The accumulator is reused across turns; the one allocation per chunk is the +/// buffer the channel takes ownership of, and none of this is the RT path (the +/// device callback reads the ring the feeder has already filled). +fn mix(rxs: &[Receiver], channels: usize, tx: &SyncSender) { + let mut pending: Vec> = rxs.iter().map(|_| Vec::new()).collect(); + let mut live: Vec = rxs.iter().map(|_| true).collect(); + // Numbering follows lane 0, whose first chunk says where it starts. + let mut base = 0; + let mut emitted = 0; + let mut out: Vec = Vec::new(); + loop { + for (i, rx) in rxs.iter().enumerate() { + while live[i] && pending[i].is_empty() { + match rx.recv() { + Ok(chunk) => { + if i == 0 && emitted == 0 { + base = chunk.start_sample; + } + pending[i] = chunk.samples; + } + Err(_) => live[i] = false, + } + } + } + // The block every lane still playing can cover; `None` once they are all + // done, which is the only way out of this loop besides a gone consumer. + let Some(frames) = pending + .iter() + .filter(|p| !p.is_empty()) + .map(|p| p.len() / channels) + .min() + .filter(|&f| f > 0) + else { + return; + }; + let block = frames * channels; + out.clear(); + out.resize(block, 0.0); + for lane in pending.iter_mut().filter(|p| !p.is_empty()) { + for (sum, sample) in out.iter_mut().zip(lane.drain(..block)) { + *sum += sample; + } + } + let chunk = AudioChunk { + start_sample: base + emitted, + // Clamped, not wrapped: two lanes at full scale are what a mix has + // to survive, and the device takes `[-1, 1]`. + samples: out.iter().map(|s| s.clamp(-1.0, 1.0)).collect(), + }; + if tx.send(chunk).is_err() { + return; // caller moved on + } + emitted += frames as u64; + } +} + fn run(mut w: Worker) { let mut interleaved = Vec::new(); let channels = w.channels; diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 117a287..4a0db4b 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -31,7 +31,7 @@ use crate::audio::{AudioMeta, AudioSession}; use crate::demux::{Demuxer, VideoMeta}; use crate::hw::{HwEncoder, HwSession}; use crate::mux::{AudioParams, Mp4Muxer, VideoParams}; -use crate::project::{Lane, Project}; +use crate::project::Project; /// Progress is reported in permille: an atomic integer the render loop can read /// without a lock, fine enough for any progress bar. @@ -51,7 +51,9 @@ const MAX_BITRATE: u64 = 20_000_000; /// front-end says so rather than hiding the rows. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub enum Format { - /// Picture and sound: video re-encoded, AAC copied. + /// Picture and sound: video re-encoded, AAC copied. Copied, so it carries + /// **one** audio lane: a timeline whose sound is spread over two is refused + /// by name here and mixed by the other two formats, which decode. #[default] Mp4, /// The audio lane alone, 16-bit PCM. @@ -210,6 +212,22 @@ fn run( // The stream each source is copied from is the one it plays: `audio_sources` // is the same list `PlaybackSession::seek` hands the decoder, so an export // of a timeline playing a file's second audio track carries *that* track. + // + // One lane, because this path *copies* AAC packets and a mix is not a copy: + // summing two lanes means decoding both and encoding the result, and there + // is no AAC encoder here to encode it with. Refused by name rather than + // silently exporting the first lane -- a file missing half its sound is the + // one failure a user would not notice. + let lanes = project.audio_segments_from(0, meta.frame_rate); + if lanes.len() > 1 { + return Err(format!( + "this timeline has {} audio lanes and an mp4 export copies one: \ + there is no AAC encoder here to mix them with. Export WAV or FLAC, \ + which are mixed, or put the sound on one lane", + lanes.len() + ) + .into()); + } let audio = AudioSession::copy_multi_streams( &project.audio_sources(), &project.segments_from(0, meta.frame_rate), @@ -223,10 +241,12 @@ fn run( let mut muxer = None; let mut done = 0u32; let black = Black::new(meta); - // Spans, not clips: a gap in the video lane is part of the timeline and - // gets encoded too, as black frames. The picture count is therefore - // `timeline_frames` however the lane is arranged. - for span in project.spans_from(Lane::V1, 0) { + // Spans, not clips: a gap in the video is part of the timeline and gets + // encoded too, as black frames. The picture count is therefore + // `timeline_frames` however the lanes are arranged -- and *which* lane a + // span comes from is `composite_spans_from`'s answer, the same one playback + // shows, so an export is what was watched. + for span in project.composite_spans_from(0) { // Every clip reopens its own source file at its own in point; the // encoder is *not* reopened, so the export is one continuous stream // whose GOP boundaries need not line up with the cuts -- nor with the @@ -279,13 +299,14 @@ fn run( Ok(()) } -/// The audio lane alone, as a WAV or a FLAC. +/// The audio lanes alone, summed, as a WAV or a FLAC. /// -/// Nothing here re-derives the edit: the play list is -/// [`Project::segments_from`] and it is handed to the very -/// [`AudioSession::open_multi_streams`] playback feeds from, so what is written -/// is what was heard -- gaps included, which arrive as real silence from that -/// choke point rather than as a hole this would have to invent. +/// Nothing here re-derives the edit: the play lists are +/// [`Project::audio_segments_from`] and they are handed to the very +/// [`AudioSession::open_mixed_streams`] playback feeds from, so what is written +/// is what was heard -- every lane, mixed the same way, gaps included, which +/// arrive as real silence from that choke point rather than as a hole this would +/// have to invent. /// /// The length is the *timeline's*: each segment resolves its window to whole /// samples on its own, so the sum can miss the timeline by a sample or two, and @@ -300,8 +321,8 @@ fn run_audio( format: Format, ) -> crate::Result<()> { let sources = project.audio_sources(); - let segs = project.segments_from(0, meta.frame_rate); - let Some((audio, chunks)) = AudioSession::open_multi_streams(&sources, &segs)? else { + let segs = project.audio_segments_from(0, meta.frame_rate); + let Some((audio, chunks)) = AudioSession::open_mixed_streams(&sources, &segs)? else { return Err("this timeline has no audio to export".into()); }; let channels = usize::from(audio.channels); diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index a98ed2e..68b6ffc 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -149,7 +149,7 @@ impl PlaybackSession { // One clip per lane covering the file, so timeline == source until the // first edit -- and the range opened above is exactly that clip's. let project = Project::single(&path, meta.frame_count); - let span = project.span_at(Lane::V1, 0).expect("never empty"); + let span = project.composite_span_at(0).expect("never empty"); Ok(Self { meta, frames: stream.frames, @@ -247,7 +247,7 @@ impl PlaybackSession { let playhead = doc.playhead; let project = Project::from_parts(doc.sources, doc.lanes)?; - let span = project.span_at(Lane::V1, 0).expect("never empty"); + let span = project.composite_span_at(0).expect("never empty"); // Last, because it is the one thing here that cannot be taken back: the // feeder thread outlives the `Audio` value (it holds its own clones) and // only a session's `drop` retires it, so a refusal above this line would @@ -364,7 +364,7 @@ impl PlaybackSession { /// clip under the running worker and only the mapping stays true. fn next_clip(&mut self) -> bool { let next = self.span.end(); - let Some(span) = self.project.span_at(Lane::V1, next) else { + let Some(span) = self.project.composite_span_at(next) else { return false; }; // We only get here on a disconnect, so the old worker has already @@ -757,7 +757,7 @@ impl PlaybackSession { // `target` is inside the timeline (never empty), so this always spans; // the span runs from there to the end of whatever it landed in -- a // clip, or a gap, which starts a black-frame worker instead. - if let Some(span) = self.project.span_at(Lane::V1, target) { + if let Some(span) = self.project.composite_span_at(target) { self.start_span(span); } self.eos = false; @@ -775,11 +775,14 @@ impl PlaybackSession { // between clips are gapless: the video reopens at a boundary, the // ear never hears it -- and a join between two *files* is just // another segment, because every segment names its own source. - let segs = self.project.segments_from(target, fps); + // One play list per audio lane, summed by the mixer: what the ear + // hears is every lane at once, and a lane's own gaps are silence in + // it rather than a hole in the count the master clock keeps. + let segs = self.project.audio_segments_from(target, fps); // Each source on the stream it was placed with: what plays is what // the library row said, and what an export copies (`export::run`). let sources = self.project.audio_sources(); - audio_running = match AudioSession::open_multi_streams(&sources, &segs) { + audio_running = match AudioSession::open_mixed_streams(&sources, &segs) { Ok(Some((_, rx))) => audio.spawn_feeder(rx), _ => false, }; diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index b208938..c4d545c 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -15,8 +15,10 @@ //! splice of the list; //! * the lanes are independent and are peers: deleting audio under a picture is //! one lane's business, and the picture does not shift. No lane is special -//! except by what a *caller* reads -- playback and export take `V1`, the audio -//! worker takes `A1`, until a compositing slice teaches them the rest. +//! except by what a *caller* reads -- and what playback and export read is the +//! whole stack: [`Project::composite_span_at`] resolves the video lanes to the +//! one picture that shows, [`Project::audio_segments_from`] hands every audio +//! lane over to be summed. //! //! The price is one invariant this module enforces at every mutation and every //! constructor: within a lane, clips are **sorted by `start` and never overlap** @@ -532,6 +534,80 @@ impl Project { out } + /// What the *composite* shows from `timeline_frame` on -- the answer + /// [`span_at`](Project::span_at) gives for one lane, resolved across every + /// video lane by one rule: **the topmost lane with a clip there wins**, and + /// topmost is the *last* video lane in display order, so `V2` covers `V1` + /// (the usual overlay convention). A frame no video lane covers is a gap, + /// which is black however many lanes are above or below it. + /// + /// No blending, so exactly one lane is visible at a time and the composite + /// is itself a span list -- which is why one decoder plays it, the same one + /// a single-lane timeline uses, rather than N running at once. + /// + /// The span is cut short wherever a *higher* lane's clip starts, because + /// from that frame on a different lane wins; that is what makes walking + /// [`composite_spans_from`](Project::composite_spans_from) correct. + /// + /// ponytail: alpha, opacity or any blend mode makes this untrue -- two + /// lanes would then be visible in one frame and the caller needs a decoder + /// per lane plus a compositor. Upgrade path is a `Vec` per frame + /// (this same walk, per lane) feeding N decoders. + pub fn composite_span_at(&self, timeline_frame: u32) -> Option { + let total = self.timeline_frames(); + if timeline_frame >= total { + return None; + } + let video: Vec = self + .lanes() + .into_iter() + .filter(|l| l.kind == LaneKind::Video) + .collect(); + // The last covering lane is the winner; only the lanes above it can + // interrupt what it shows. + let winner = video + .iter() + .rposition(|&lane| at(self.lane(lane), timeline_frame).is_some()); + let (from, until) = match winner { + Some(i) => { + let clips = self.lane(video[i]); + let idx = at(clips, timeline_frame).expect("just found above"); + ( + Some(( + clips[idx].source, + clips[idx].in_frame + (timeline_frame - clips[idx].start), + )), + clips[idx].end(), + ) + } + // Nothing covers it: black until something above the floor starts. + None => (None, total), + }; + let takeover = video[winner.map_or(0, |i| i + 1)..] + .iter() + .filter_map(|&lane| self.lane(lane).iter().find(|c| c.start > timeline_frame)) + .map(|c| c.start) + .min(); + Some(Span { + start: timeline_frame, + len: takeover.map_or(until, |t| t.min(until)) - timeline_frame, + from, + }) + } + + /// [`spans_from`](Project::spans_from) over the composite: every stretch the + /// viewer sees from `timeline_frame` to the end, in order. What an export + /// encodes and what playback walks at a clip boundary. + pub fn composite_spans_from(&self, timeline_frame: u32) -> Vec { + let mut out = Vec::new(); + let mut t = timeline_frame; + while let Some(span) = self.composite_span_at(t) { + t = span.end(); + out.push(span); + } + out + } + /// Split every lane at `timeline_frame`, so that frame becomes the first /// frame of a new clip, and hand the two sides two fresh group ids. Refused /// (`false`, no change) when no lane has a clip to split there -- at a @@ -752,10 +828,20 @@ impl Project { /// The first entry is partial when the position is mid-clip. Empty when the /// position is past the end or `fps` is not usable. pub fn segments_from(&self, timeline_frame: u32, fps: f64) -> Vec<(Option, f64, f64)> { + self.lane_segments_from(Lane::A1, timeline_frame, fps) + } + + /// [`segments_from`](Project::segments_from) for a named lane. + pub fn lane_segments_from( + &self, + lane: Lane, + timeline_frame: u32, + fps: f64, + ) -> Vec<(Option, f64, f64)> { if !(fps.is_finite() && fps > 0.0) { return Vec::new(); } - self.spans_from(Lane::A1, timeline_frame) + self.spans_from(lane, timeline_frame) .iter() .map(|span| match span.from { // A clip's window is in *source* seconds: where in the file it @@ -771,6 +857,32 @@ impl Project { .collect() } + /// One play list per audio lane that *holds* something, in display order -- + /// what the mixer sums ([`crate::AudioSession::open_mixed_streams`]) and + /// what an export asks how many lanes it would have to mix. + /// + /// Never empty: a timeline whose audio lanes are all empty (or which has no + /// audio lane at all) still yields one all-gap list, so it plays silence + /// against a master clock exactly as it did before there were lanes to + /// count. Lanes with nothing on them are left out rather than mixed in as + /// silence: they would cost a decode thread each and add zero. + pub fn audio_segments_from( + &self, + timeline_frame: u32, + fps: f64, + ) -> Vec, f64, f64)>> { + let lists: Vec<_> = self + .lanes() + .into_iter() + .filter(|l| l.kind == LaneKind::Audio && !self.lane(*l).is_empty()) + .map(|lane| self.lane_segments_from(lane, timeline_frame, fps)) + .collect(); + match lists.is_empty() { + true => vec![self.lane_segments_from(Lane::A1, timeline_frame, fps)], + false => lists, + } + } + /// Pushes the undo snapshot. Every mutating method calls this once, *after* /// it has decided it will succeed -- a refusal must not cost an undo step. fn snapshot(&mut self) { @@ -2152,4 +2264,122 @@ mod tests { } } } + + /// The compositing rule, in one walk: `V2` covers `V1` while it has a clip + /// there, `V1` shows again on either side of it, and a frame no video lane + /// covers is a gap however many lanes there are. + #[test] + fn the_composite_is_the_topmost_lane_with_a_clip() { + let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)]; + let lanes = vec![ + // V1: the whole 30 frames of source 0. + (LaneKind::Video, vec![clip(0, 0, 30, 0)]), + // V2: source 1 over the middle third. + (LaneKind::Video, vec![clip(10, 5, 15, 1)]), + (LaneKind::Audio, vec![clip(0, 0, 30, 0)]), + ]; + let p = Project::from_parts(sources, lanes).expect("valid parts"); + assert_eq!( + p.composite_spans_from(0), + vec![ + Span { + start: 0, + len: 10, + from: Some((0, 0)) + }, + Span { + start: 10, + len: 10, + from: Some((1, 5)) + }, + Span { + start: 20, + len: 10, + from: Some((0, 20)) + }, + ], + "V2 takes over for its own span and hands V1 back" + ); + // A mid-span ask resolves the same way, which is what a seek does. + assert_eq!( + p.composite_span_at(15), + Some(Span { + start: 15, + len: 5, + from: Some((1, 10)) + }) + ); + assert_eq!(p.composite_span_at(30), None, "past the end"); + + // A hole in V1 under V2's clip: black between the two, and black after + // both run out (the audio lane is still holding the timeline open). + let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)]; + let holed = vec![ + (LaneKind::Video, vec![clip(0, 0, 5, 0)]), + (LaneKind::Video, vec![clip(10, 0, 10, 1)]), + (LaneKind::Audio, vec![clip(0, 0, 30, 0)]), + ]; + let p = Project::from_parts(sources, holed).expect("valid parts"); + assert_eq!( + p.composite_spans_from(0), + vec![ + Span { + start: 0, + len: 5, + from: Some((0, 0)) + }, + Span { + start: 5, + len: 5, + from: None + }, + Span { + start: 10, + len: 10, + from: Some((1, 0)) + }, + Span { + start: 20, + len: 10, + from: None + }, + ] + ); + + // One video lane: the composite *is* that lane, span for span -- the + // promise every existing two-lane project rests on. + let p = Project::single(FILE, 30); + assert_eq!(p.composite_spans_from(0), p.spans_from(Lane::V1, 0)); + assert_eq!(p.composite_span_at(7), p.span_at(Lane::V1, 7)); + } + + /// Every audio lane holding something gets a play list, and only those. + #[test] + fn audio_segments_cover_every_lane_that_holds_something() { + let sources = vec![Source::new(FILE, 0), Source::new(FILE2, 0)]; + let lanes = vec![ + (LaneKind::Video, vec![clip(0, 0, 30, 0)]), + (LaneKind::Audio, vec![clip(0, 0, 30, 0)]), + (LaneKind::Audio, vec![clip(15, 0, 15, 1)]), + (LaneKind::Audio, Vec::new()), + ]; + let p = Project::from_parts(sources, lanes).expect("valid parts"); + let lists = p.audio_segments_from(0, FPS); + assert_eq!(lists.len(), 2, "the empty lane is not mixed in"); + assert_eq!(lists[0], p.segments_from(0, FPS), "A1 is unchanged"); + // A2 is a gap up to frame 15, then the whole of source 1. + assert_eq!(lists[1], vec![(None, 0.0, 0.5), (Some(1), 0.0, 0.5)]); + + // No audio lane holds anything: one all-gap list, so such a timeline + // still plays silence against a master clock. + let p = Project::from_parts( + vec![Source::new(FILE, 0)], + vec![ + (LaneKind::Video, vec![clip(0, 0, 30, 0)]), + (LaneKind::Audio, Vec::new()), + ], + ) + .expect("valid parts"); + assert_eq!(p.audio_segments_from(0, FPS), vec![vec![(None, 0.0, 1.0)]]); + } } diff --git a/crates/engine/tests/lanes.rs b/crates/engine/tests/lanes.rs new file mode 100644 index 0000000..6a1e285 --- /dev/null +++ b/crates/engine/tests/lanes.rs @@ -0,0 +1,302 @@ +//! N lanes, composited: what a timeline with a `V2` over its `V1` and an `A2` +//! over its `A1` plays, and that an export of it is the same thing. +//! +//! The fixtures are the two video assets, which differ picture for picture, so +//! "which lane is showing" is answered by comparing the decoded frame against +//! each source rather than by trusting the edit list. +//! +//! ```text +//! cargo test -p engine --release --test lanes -- --nocapture +//! ``` + +use std::path::{Path, PathBuf}; +use std::sync::Once; +use std::time::{Duration, Instant}; + +use engine::export::{ExportSettings, Format}; +use engine::project::{Clip, LaneKind, Source}; +use engine::{DecodeSession, ExportHandle, PlaybackSession, Project}; + +const FPS: f64 = 30.0; +/// `test_av.mp4` is 150 frames, `test_av2.mp4` 120; the top lane covers the +/// middle third of the first. +const TOTAL: u32 = 150; +const TOP_IN: u32 = 50; +const TOP_OUT: u32 = 100; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// Software on both halves, so this suite proves the composite on any machine +/// rather than whatever the local VA-API driver does. +fn pin_software() { + static PIN: Once = Once::new(); + PIN.call_once(|| unsafe { + std::env::set_var("VE_SW", "1"); + std::env::set_var("VE_SW_ENC", "1"); + }); +} + +/// Per-run unique, like the export suite's: two suites at once must not write +/// each other's files. +fn out_path(name: &str, ext: &str) -> PathBuf { + let path = std::env::temp_dir().join(format!("ve_lanes_{name}_{}.{ext}", std::process::id())); + let _ = std::fs::remove_file(&path); + path +} + +/// A hand-written v4 project: `V1` the whole of `test_av`, `V2` the middle +/// third playing `test_av2` from its own frame 0, `A1` the whole of `test_av`. +/// Exactly the file a user would write by hand, parsed by the real loader. +fn three_lane_file() -> PathBuf { + let path = out_path("project", "edith"); + // `source