Skip to main content

alpha2_eval/
audio.rs

1use crate::{ActiveIndex, EvalError, IndexedClip, collect_overlapping, count_overlapping};
2use alpha2_media::SourceId;
3use alpha2_model::{AudioProperties, ClipId, Project, TimeMap, TrackId};
4use alpha2_time::{MediaTime, TimeRange};
5
6/// One audio clip overlapping an evaluated timeline span.
7///
8/// Identities and authored properties are borrowed from the [`crate::ActiveIndex`].
9#[derive(Clone, Copy, Debug, PartialEq)]
10pub struct ActiveAudioClip<'a> {
11    /// Active clip identity.
12    pub clip_id: &'a ClipId,
13    /// Media source needed for this clip.
14    pub source_id: &'a SourceId,
15    /// Track containing the clip.
16    pub track_id: &'a TrackId,
17    /// Position of the containing track in project order.
18    pub track_order: usize,
19    /// Position of the clip in its track's clip list.
20    pub clip_order: usize,
21    /// Whether the clip is on a video track (and so also reported by [`crate::evaluate`]).
22    pub visual_track: bool,
23    /// Whole timeline interval occupied by the clip.
24    pub timeline_range: TimeRange,
25    /// Whole source interval consumed by the clip.
26    pub source_range: TimeRange,
27    /// How the clip's timeline time maps onto its source range.
28    pub time_map: &'a TimeMap,
29    /// Part of the evaluated span this clip covers.
30    pub active_range: TimeRange,
31    /// Authored presentation of the immutable project snapshot.
32    pub audio: &'a AudioProperties,
33}
34
35impl ActiveAudioClip<'_> {
36    /// Source consumption rate: the source-to-timeline duration ratio, 1 for a loop, 0 for a
37    /// freeze. A curve has no one rate and reports 1; [`crate::TimeCurve::position`] gives
38    /// its speed at a time.
39    ///
40    /// The mixer resamples, so a rate of 2 raises pitch an octave unless `preserve_pitch`
41    /// time-stretches instead; `pitch_cents` moves the pitch from either by its own interval.
42    #[must_use]
43    pub fn speed(&self) -> f64 {
44        match self.time_map {
45            TimeMap::Loop { .. } | TimeMap::Curve { .. } => return 1.0,
46            TimeMap::Freeze { .. } => return 0.0,
47            TimeMap::Forward | TimeMap::Reverse => {}
48        }
49        let timeline = self.timeline_range.duration().map_or(0, MediaTime::ticks);
50        let source = self.source_range.duration().map_or(0, MediaTime::ticks);
51        if timeline <= 0 || source <= 0 {
52            return 1.0;
53        }
54        #[allow(clippy::cast_precision_loss)]
55        {
56            source as f64 / timeline as f64
57        }
58    }
59
60    /// Maps a timeline timestamp inside [`Self::timeline_range`] to source time.
61    #[must_use]
62    pub fn source_time_at(&self, time: MediaTime) -> Option<MediaTime> {
63        crate::map_source_time(
64            self.timeline_range,
65            self.source_range,
66            self.time_map,
67            crate::Mirror::TICK,
68            time,
69        )
70    }
71}
72
73/// Audio activity over one half-open timeline span.
74#[derive(Clone, Debug, PartialEq)]
75pub struct AudioSpanDesc<'a> {
76    /// Span evaluated on the project timeline.
77    pub range: TimeRange,
78    /// Clips overlapping the span, ordered by track, start time, then position in the track.
79    pub clips: Vec<ActiveAudioClip<'a>>,
80}
81
82/// Evaluates every audible clip overlapping a half-open timeline span.
83///
84/// Clips on audio tracks always qualify; a clip on a visual track qualifies when its source
85/// declares an audio stream. Overlapping clips are all reported and the mixer sums them.
86///
87/// Gain, pan and fade curves are left unsampled; the mixer evaluates them per sample so that
88/// automation is independent of the host block size.
89///
90/// Allocates two exactly sized lists; use [`evaluate_audio_in`] to reuse memory across spans.
91///
92/// # Errors
93/// Returns [`EvalError::IndexProjectMismatch`] when the index was built for another
94/// project, and [`EvalError::UnmappableClip`] for unrepresentable retiming.
95pub fn evaluate_audio<'a>(
96    project: &Project,
97    index: &'a ActiveIndex,
98    range: TimeRange,
99) -> Result<AudioSpanDesc<'a>, EvalError> {
100    crate::ensure_index_matches(project, index)?;
101    let capacity = index.root.map_or(0, |root| {
102        count_overlapping(&index.nodes, root, range, &|entry| entry.source_is_audible)
103    });
104    let mut scratch = AudioSpanScratch {
105        nodes: Vec::with_capacity(capacity),
106    };
107    let span = fill_span(index, range, &mut scratch)?;
108    Ok(AudioSpanDesc {
109        range,
110        clips: span.iter().collect(),
111    })
112}
113
114/// Reusable working memory for [`evaluate_audio_in`].
115///
116/// Holds index positions rather than borrows, so one scratch can outlive snapshots.
117#[derive(Clone, Debug, Default)]
118pub struct AudioSpanScratch {
119    nodes: Vec<usize>,
120}
121
122/// The clips of one span, read from an [`AudioSpanScratch`] without copying.
123#[derive(Clone, Copy, Debug)]
124pub struct AudioSpan<'a, 's> {
125    index: &'a ActiveIndex,
126    range: TimeRange,
127    nodes: &'s [usize],
128}
129
130impl<'a> AudioSpan<'a, '_> {
131    /// Span evaluated on the project timeline.
132    #[must_use]
133    pub const fn range(&self) -> TimeRange {
134        self.range
135    }
136
137    /// Number of clips in the span.
138    #[must_use]
139    pub const fn len(&self) -> usize {
140        self.nodes.len()
141    }
142
143    /// Whether no audible clip overlaps the span.
144    #[must_use]
145    pub const fn is_empty(&self) -> bool {
146        self.nodes.is_empty()
147    }
148
149    /// The clips in mix order.
150    #[must_use = "iterators are lazy and do nothing unless consumed"]
151    pub fn iter(&self) -> impl ExactSizeIterator<Item = ActiveAudioClip<'a>> {
152        let (index, range) = (self.index, self.range);
153        self.nodes
154            .iter()
155            .map(move |&node| active_clip(index.nodes[node].entry(), range))
156    }
157}
158
159/// Evaluates the same clips as [`evaluate_audio`] into reusable memory.
160///
161/// # Errors
162/// Returns any error emitted by [`evaluate_audio`].
163pub fn evaluate_audio_in<'a, 's>(
164    project: &Project,
165    index: &'a ActiveIndex,
166    range: TimeRange,
167    scratch: &'s mut AudioSpanScratch,
168) -> Result<AudioSpan<'a, 's>, EvalError> {
169    crate::ensure_index_matches(project, index)?;
170    fill_span(index, range, scratch)
171}
172
173fn fill_span<'a, 's>(
174    index: &'a ActiveIndex,
175    range: TimeRange,
176    scratch: &'s mut AudioSpanScratch,
177) -> Result<AudioSpan<'a, 's>, EvalError> {
178    let nodes = &mut scratch.nodes;
179    nodes.clear();
180    let mix_order = |entry: &IndexedClip| {
181        (
182            entry.track_order,
183            entry.timeline_range.start(),
184            entry.clip_order,
185        )
186    };
187    let mut unmappable: Option<&IndexedClip> = None;
188    if let Some(root) = index.root {
189        collect_overlapping(&index.nodes, root, range, &mut |node, entry| {
190            if !entry.source_is_audible {
191                return;
192            }
193            let Some(active_range) = entry.timeline_range.intersection(range) else {
194                return;
195            };
196            if active_range.is_empty() {
197                return;
198            }
199            // Reject retiming the mixer could not map, matching visual evaluation.
200            if crate::map_source_time(
201                entry.timeline_range,
202                entry.source_range,
203                &entry.time_map,
204                crate::Mirror::TICK,
205                active_range.start(),
206            )
207            .is_none()
208            {
209                if unmappable.is_none_or(|first| mix_order(entry) < mix_order(first)) {
210                    unmappable = Some(entry);
211                }
212                return;
213            }
214            nodes.push(node);
215        });
216    }
217    if let Some(entry) = unmappable {
218        return Err(EvalError::UnmappableClip {
219            clip: entry.clip_id.clone(),
220        });
221    }
222    nodes.sort_unstable_by_key(|&node| mix_order(index.nodes[node].entry()));
223    Ok(AudioSpan {
224        index,
225        range,
226        nodes,
227    })
228}
229
230fn active_clip(entry: &IndexedClip, range: TimeRange) -> ActiveAudioClip<'_> {
231    ActiveAudioClip {
232        clip_id: &entry.clip_id,
233        source_id: &entry.source_id,
234        track_id: &entry.track_id,
235        track_order: entry.track_order,
236        clip_order: entry.clip_order,
237        visual_track: entry.track_kind == alpha2_model::TrackKind::Video,
238        timeline_range: entry.timeline_range,
239        source_range: entry.source_range,
240        time_map: &entry.time_map,
241        active_range: entry.timeline_range.intersection(range).unwrap_or(range),
242        audio: &entry.audio,
243    }
244}