Skip to main content

alpha2_engine/
passthrough.rs

1//! Whether an export range is its sources' pictures, untouched.
2//!
3//! Copying compressed packets is correct only when rendering would reproduce those pictures
4//! exactly: opaque clips tiling the range at their own size and speed with nothing else drawn.
5//! This checks the project alone; the native host still checks the files (codec, frame grid,
6//! keyframes, color tags, bitstream compatibility across joins).
7//!
8//! The check is conservative: anything that could change a pixel or frame timing refuses, even an
9//! identity-valued keyframe track, and the refusal names the cause. Audio never refuses; it is
10//! classified for the host to copy or encode.
11//!
12//! It uses the renderer's own predicates: [`alpha2_model::Timeline::matte_sources`],
13//! [`alpha2_model::AudioRouting::liveness`] and [`alpha2_model::AudioProperties::is_audible`].
14
15use alpha2_media::SourceId;
16use alpha2_model::{
17    Animated, Clip, ClipBlendMode, ClipId, MediaKind, Project, TimeMap, Track, TrackKind, Vec2,
18};
19use alpha2_time::{MediaTime, TimeRange};
20
21/// What an export range copies: its segments in timeline order, and its audio.
22#[derive(Clone, Debug, Eq, PartialEq)]
23pub struct PassthroughPlan {
24    /// The clips that tile the range, one after another.
25    pub segments: Vec<PassthroughSegment>,
26    /// What the export's audio is over the range.
27    pub audio: PassthroughAudio,
28}
29
30/// One clip's share of a copied range.
31#[derive(Clone, Debug, Eq, PartialEq)]
32pub struct PassthroughSegment {
33    /// The clip whose source is copied.
34    pub clip_id: ClipId,
35    /// The source copied.
36    pub source_id: SourceId,
37    /// The part of the export range this clip shows.
38    pub timeline_range: TimeRange,
39    /// The source interval shown there.
40    pub source_range: TimeRange,
41}
42
43impl PassthroughSegment {
44    /// The source time shown at timeline time `time`, inside this segment.
45    #[must_use]
46    pub fn source_time(&self, time: MediaTime) -> MediaTime {
47        MediaTime::from_ticks(
48            self.source_range.start().ticks()
49                + (time.ticks() - self.timeline_range.start().ticks()),
50        )
51    }
52}
53
54/// What an export's audio is over a copied range: copied too, or encoded from the mix.
55#[derive(Clone, Debug, Eq, PartialEq)]
56pub enum PassthroughAudio {
57    /// The export carries no audio.
58    Absent,
59    /// One copied clip's unprocessed audio is the whole mix, so its packets can be copied.
60    Untouched,
61    /// A mix the engine renders (several clips, any processing, or silence); the reason says
62    /// which.
63    Mixed(String),
64}
65
66/// Whether `range` of `project` shows its sources untouched.
67///
68/// `range` is the export's effective range, already on the frame grid.
69/// `include_audio` is whether the export carries audio.
70///
71/// # Errors
72/// Names the first thing in the project that rendering would change.
73pub fn passthrough_plan(
74    project: &Project,
75    range: TimeRange,
76    include_audio: bool,
77) -> Result<PassthroughPlan, String> {
78    let clips = tiling_clips(project, range)?;
79    let mattes = project.timeline.matte_sources();
80    let mut segments = Vec::with_capacity(clips.len());
81    for &(_, clip) in &clips {
82        let source = project
83            .sources
84            .iter()
85            .find(|source| source.id == clip.source_id)
86            .ok_or_else(|| format!("clip {} has no source", clip.id))?;
87        shows_source_untouched(clip, source)?;
88        if mattes.contains(&clip.id) {
89            return Err(format!(
90                "clip {} is another clip's matte, which is never drawn itself",
91                clip.id
92            ));
93        }
94        let timeline_range = TimeRange::new(
95            clip.timeline_range.start().max(range.start()),
96            clip.timeline_range.end().min(range.end()),
97        )
98        .map_err(|error| {
99            format!(
100                "clip {}'s share of the range is invalid: {error:?}",
101                clip.id
102            )
103        })?;
104        let offset = timeline_range.start().ticks() - clip.timeline_range.start().ticks();
105        let source_start = clip.source_range.start().ticks().saturating_add(offset);
106        let source_range = TimeRange::new(
107            MediaTime::from_ticks(source_start),
108            MediaTime::from_ticks(
109                source_start.saturating_add(timeline_range.duration().map_or(0, MediaTime::ticks)),
110            ),
111        )
112        .map_err(|error| format!("the copied source interval is invalid: {error:?}"))?;
113        segments.push(PassthroughSegment {
114            clip_id: clip.id.clone(),
115            source_id: clip.source_id.clone(),
116            timeline_range,
117            source_range,
118        });
119    }
120    let audio = if include_audio {
121        mix_over(project, range, &clips)
122    } else {
123        PassthroughAudio::Absent
124    };
125    Ok(PassthroughPlan { segments, audio })
126}
127
128fn mix_over(project: &Project, range: TimeRange, tiling: &[(&Track, &Clip)]) -> PassthroughAudio {
129    let heard = heard_clips(project, range);
130    let copied = |clip: &Clip| tiling.iter().any(|(_, tiled)| tiled.id == clip.id);
131    if heard.is_empty() {
132        return PassthroughAudio::Mixed(
133            "nothing in the range is heard, so the mix is silence".to_owned(),
134        );
135    }
136    if let Some((track, clip)) = heard.iter().find(|(_, clip)| !copied(clip)) {
137        return PassthroughAudio::Mixed(format!(
138            "clip {} on track {} is heard in the range too",
139            clip.id, track.id
140        ));
141    }
142    match (&heard[..], tiling) {
143        ([(track, clip)], [_]) => heard_untouched(project, track, clip)
144            .map_or_else(PassthroughAudio::Mixed, |()| PassthroughAudio::Untouched),
145        _ => PassthroughAudio::Mixed("the range's audio joins more than one clip".to_owned()),
146    }
147}
148
149/// Clips whose sound reaches the mix over `range`, including earlier clips on buses whose
150/// effects can ring past the clip's end.
151fn heard_clips(project: &Project, range: TimeRange) -> Vec<(&Track, &Clip)> {
152    let heard = project
153        .audio_routing()
154        .map(|routing| routing.liveness(project).tracks)
155        .unwrap_or_default();
156    let audible_source = |clip: &Clip| {
157        project
158            .sources
159            .iter()
160            .any(|source| source.id == clip.source_id && source.is_audible())
161    };
162    project
163        .timeline
164        .tracks
165        .iter()
166        .zip(heard)
167        .filter(|&(_, heard)| heard)
168        .flat_map(|(track, _)| track.clips.iter().map(move |clip| (track, clip)))
169        .filter(|(track, clip)| {
170            let rings = !track.audio.effects.is_empty() || is_routed(track);
171            let reaches = clip.timeline_range.start() < range.end()
172                && (range.start() < clip.timeline_range.end() || rings);
173            reaches && clip.audio.is_audible() && audible_source(clip)
174        })
175        .collect()
176}
177
178fn is_routed(track: &Track) -> bool {
179    track.audio.output.is_some() || !track.audio.sends.is_empty()
180}
181
182/// The visual clips that tile `range`, in timeline order, with their tracks.
183fn tiling_clips(project: &Project, range: TimeRange) -> Result<Vec<(&Track, &Clip)>, String> {
184    let overlaps = |other: TimeRange| other.start() < range.end() && range.start() < other.end();
185    let mut visual = Vec::new();
186    for track in &project.timeline.tracks {
187        match track.kind {
188            TrackKind::Caption => {
189                // Cues built from words are not resolved here, so a track with words may show text.
190                if track.captions.as_ref().is_some_and(|captions| {
191                    captions.from_words.is_some()
192                        || captions.cues.iter().any(|cue| overlaps(cue.timeline_range))
193                }) {
194                    return Err(format!(
195                        "caption track {} shows text in the range",
196                        track.id
197                    ));
198                }
199            }
200            TrackKind::Video => {
201                visual.extend(
202                    track
203                        .clips
204                        .iter()
205                        .filter(|clip| overlaps(clip.timeline_range))
206                        .map(|clip| (track, clip)),
207                );
208            }
209            TrackKind::Audio => {}
210            _ => {
211                return Err(format!(
212                    "track {} is of a kind this check does not know",
213                    track.id
214                ));
215            }
216        }
217    }
218    visual.sort_by_key(|(_, clip)| clip.timeline_range.start());
219    let first = visual
220        .first()
221        .ok_or_else(|| "no visual clip is in the range".to_owned())?;
222    if first.1.timeline_range.start() > range.start() {
223        return Err(format!(
224            "clip {} starts after the range does, so the background would show",
225            first.1.id
226        ));
227    }
228    for pair in visual.windows(2) {
229        let (before, after) = (pair[0].1, pair[1].1);
230        if after.timeline_range.start() < before.timeline_range.end() {
231            return Err(format!(
232                "clips {} and {} are both visible at once, so the frame is a composite",
233                before.id, after.id
234            ));
235        }
236        if after.timeline_range.start() > before.timeline_range.end() {
237            return Err(format!(
238                "the background shows between clips {} and {}",
239                before.id, after.id
240            ));
241        }
242    }
243    let last = visual.last().map_or(first.1, |(_, clip)| clip);
244    if last.timeline_range.end() < range.end() {
245        return Err(format!(
246            "clip {} ends before the range does, so the background would show",
247            last.id
248        ));
249    }
250    for &(track, clip) in &visual {
251        if track.transitions.iter().any(|transition| {
252            (transition.from_clip == clip.id || transition.to_clip == clip.id)
253                && overlaps(transition.timeline_range)
254        }) {
255            return Err(format!("clip {} is in a transition in the range", clip.id));
256        }
257    }
258    Ok(visual)
259}
260
261/// Whether `clip` shows `source`'s pictures at their own size and speed with nothing applied.
262fn shows_source_untouched(clip: &Clip, source: &alpha2_model::MediaSource) -> Result<(), String> {
263    if source.kind != MediaKind::Video || source.provider.is_some() {
264        return Err(format!(
265            "clip {} shows a {} source, not a decoded video file",
266            clip.id,
267            media_kind(source.kind)
268        ));
269    }
270    // A render honours a declared color over stream tags; a copy keeps the stream's tags.
271    if source
272        .color_metadata
273        .is_some_and(|declared| declared != alpha2_media::ColorMetadata::EXPORT)
274    {
275        return Err(format!(
276            "clip {}'s source declares a color other than the output's, which a render converts",
277            clip.id
278        ));
279    }
280    if clip.composition.is_some() {
281        return Err(format!(
282            "clip {} is shown through a composition graph",
283            clip.id
284        ));
285    }
286    if !clip.masks.is_empty() || clip.matte.is_some() {
287        return Err(format!("clip {} is masked or matted", clip.id));
288    }
289    if clip.blend_mode != ClipBlendMode::Normal {
290        return Err(format!(
291            "clip {} blends with a mode other than normal",
292            clip.id
293        ));
294    }
295    let visual_identity = matches!(
296        clip.visual.position,
297        alpha2_model::AnimatedPoint::Constant { value } if value == Vec2::new(0.5, 0.5)
298    ) && clip.visual.anchor == Vec2::new(0.5, 0.5)
299        && constant(&clip.visual.scale) == Some(Vec2::new(1.0, 1.0))
300        && constant(&clip.visual.rotation_degrees) == Some(0.0)
301        && constant(&clip.visual.opacity) == Some(1.0)
302        && clip.visual.correction.is_none();
303    if !visual_identity {
304        return Err(format!(
305            "clip {} is moved, scaled, rotated, faded or corrected; only a constant identity transform is copied",
306            clip.id
307        ));
308    }
309    if clip.time_map != TimeMap::Forward
310        || clip.source_range.duration() != clip.timeline_range.duration()
311    {
312        return Err(format!(
313            "clip {} is retimed, reversed, frozen, or looped",
314            clip.id
315        ));
316    }
317    if !clip.frame_interpolation.is_hold() {
318        return Err(format!(
319            "clip {} mixes frames, which a render draws and a copy does not",
320            clip.id
321        ));
322    }
323    Ok(())
324}
325
326/// Whether the mix is `clip`'s audio alone with no processing on the way to the output. `clip`
327/// is the only one heard.
328fn heard_untouched(project: &Project, track: &Track, clip: &Clip) -> Result<(), String> {
329    let clip_audio = &clip.audio;
330    if constant(&clip_audio.gain) != Some(1.0)
331        || constant(&clip_audio.pan) != Some(0.0)
332        || clip_audio.fade_in.ticks() != 0
333        || clip_audio.fade_out.ticks() != 0
334        || !clip_audio.effects.is_empty()
335    {
336        return Err(format!("clip {}'s audio is processed", clip.id));
337    }
338    if clip_audio.stream.is_some() || clip_audio.channel_map.is_some() {
339        return Err(format!(
340            "clip {} plays a chosen audio stream or a channel map, not the file's default audio",
341            clip.id
342        ));
343    }
344    if constant(&track.audio.gain) != Some(1.0)
345        || constant(&track.audio.pan) != Some(0.0)
346        || !track.audio.effects.is_empty()
347    {
348        return Err(format!("track {}'s audio bus processes the clip", track.id));
349    }
350    if is_routed(track) {
351        return Err(format!("track {} routes the clip through a bus", track.id));
352    }
353    let master = &project.audio;
354    if constant(&master.gain) != Some(1.0) || !master.effects.is_empty() || master.limiter.is_some()
355    {
356        return Err("the master bus processes the mix (gain, effects, or its limiter)".to_owned());
357    }
358    Ok(())
359}
360
361fn constant<T: Copy>(animated: &Animated<T>) -> Option<T> {
362    match animated {
363        Animated::Constant { value } => Some(*value),
364        Animated::Keyframes { .. } | Animated::Split { .. } | Animated::Data(_) => None,
365    }
366}
367
368const fn media_kind(kind: MediaKind) -> &'static str {
369    match kind {
370        MediaKind::Video => "video",
371        MediaKind::Audio => "audio",
372        MediaKind::Image => "image",
373        MediaKind::Generated => "generated",
374        MediaKind::Composition => "composition",
375        MediaKind::Adjustment => "adjustment",
376    }
377}
378
379#[cfg(test)]
380#[path = "passthrough_tests.rs"]
381mod tests;