Skip to main content

alpha2_engine/
audio.rs

1//! Project-driven audio mixing.
2//!
3//! [`AudioRenderer`] turns a project snapshot and host-decoded source blocks into one mixed,
4//! project-rate planar block. The host owns decode; this renderer owns gain, panning, fades,
5//! effects, bus summing, and limiting.
6//!
7//! Signal order per clip is fixed:
8//! source -> resample -> clip effects -> clip gain/fades -> pan -> track bus.
9//! Gain and fades come after the clip effects so a fade reaches true silence even when an effect
10//! has a tail.
11//!
12//! Track buses sum into the master bus. A ducked track reads the *pre-duck* output of its
13//! sidechain track, so the mix never depends on track order. A bus nothing writes in a block is
14//! neither cleared nor summed.
15
16use std::collections::HashMap;
17
18use alpha2_audio::{
19    Biquad, BiquadKind, ChannelLayout, Compressor, Ducker, Interpolator, LoudnessMeter,
20    LoudnessReport, PeakLimiter, ProcessCtx, Processor, ProcessorChain, SchroederReverb, Stretch,
21    TransportState,
22};
23use alpha2_eval::{ActiveAudioClip, AudioSpanScratch, SampleContext, sample_scalar};
24use alpha2_media::{AudioBlock, AudioBlockProvider, SourceId, SpeakerLayout};
25use alpha2_model::{
26    Animated, AudioEffect, ClipId, EqBandKind, LOOP_FADE_SECONDS, LoopMode, MAX_GAIN, MasterAudio,
27    TimeMap, TrackAudio, TrackId,
28};
29use alpha2_time::{MediaTime, TICKS_PER_SECOND, TimeRange};
30
31use crate::downmix::{ChannelMix, Downmix};
32use crate::{EngineError, EngineProject};
33
34mod stretch_read;
35
36use stretch_read::{StretchSlot, stretched_request, stretches};
37
38/// Cap on cached interpolation weights for a retimed read (256 KiB).
39const MAX_CACHED_WEIGHTS: usize = 1 << 15;
40
41/// Largest block a renderer will mix in one call.
42pub const MAX_AUDIO_BLOCK: usize = 8_192;
43
44// The model counts a clip's effects as built from a margin before its lookahead. That margin must
45// hold one largest block at the lowest rate plus the rounding at each clip end and chain lookahead.
46const _: () = {
47    let rate = *alpha2_model::SAMPLE_RATE_RANGE.start() as usize;
48    let samples = MAX_AUDIO_BLOCK + 2 + alpha2_model::MAX_CHAIN_EFFECTS;
49    assert!(
50        samples * 1_000 <= alpha2_model::AUDIO_EFFECT_STATE_MARGIN_MS as usize * rate,
51        "AUDIO_EFFECT_STATE_MARGIN_MS must hold a largest block at the lowest rate"
52    );
53};
54
55/// Longest a stage replays to settle before a seek target, in seconds.
56///
57/// A recursive effect's settling horizon is unbounded as it nears infinite memory, so each
58/// stage's lead is capped here. A seek replays at most this much audio plus the graph's lookahead;
59/// a stage with a longer horizon only approximates its settled state.
60pub const MAX_SETTLING_SECONDS: u32 = 30;
61
62/// What [`AudioRenderer::render`] does with a block that does not start
63/// where the previous one ended.
64#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
65pub enum AudioContinuity {
66    /// Every such block resets the renderer and replays the settling history before it, so it
67    /// mixes what a fresh renderer would. Use for exports, loudness measurement, and any output
68    /// that must repeat.
69    #[default]
70    Exact,
71    /// For live preview only. A block starting within [`AudioRenderer::max_block`] samples of
72    /// where the previous one ended continues from that state without a reset or replay, so a
73    /// small step costs one block instead of up to [`MAX_SETTLING_SECONDS`] of replay. The result
74    /// differs from a fresh renderer's but is still determined by the blocks asked for, in order.
75    /// Longer jumps, and the first block after a reset, are exact.
76    ContinueSmallGaps,
77}
78
79/// Outcome of mixing one block.
80#[derive(Clone, Debug, PartialEq, Eq)]
81pub struct AudioRenderStatus {
82    /// Sample index of the first mixed sample.
83    pub start_sample: i64,
84    /// Number of mixed samples per channel.
85    pub frames: usize,
86    /// Sources an audible clip needed but the provider could not supply.
87    ///
88    /// Those clips contributed silence and the block was not metered. Decode them and render the
89    /// block again. With [`AudioRenderer::set_hold_incomplete_blocks`] the whole block was silent,
90    /// nothing advanced, and the retry gives the uninterrupted mix; otherwise it gives the mix
91    /// after a seek.
92    pub missing_sources: Vec<SourceId>,
93}
94
95impl AudioRenderStatus {
96    /// Returns whether every audible clip was mixed from real samples.
97    #[must_use]
98    pub fn is_complete(&self) -> bool {
99        self.missing_sources.is_empty()
100    }
101}
102
103/// A source interval a host decodes before a render reads it.
104#[derive(Clone, Debug, PartialEq, Eq)]
105pub struct AudioNeed {
106    /// Source to decode or retrieve.
107    pub source_id: SourceId,
108    /// The source's audio stream, counted over its audio streams (`AudioProperties::stream`);
109    /// `None` is the host's default stream.
110    pub stream: Option<u32>,
111    /// Half-open source interval in ticks, including interpolation neighbours.
112    pub source_range: TimeRange,
113}
114
115struct TrackBus {
116    id: TrackId,
117    audio: TrackAudio,
118    chain: ProcessorChain,
119    ducker: Option<BusDucker>,
120    sidechain: Option<usize>,
121    /// The bus's samples for the block, valid only while [`Self::live`].
122    output: [Vec<f32>; 2],
123    /// Whether `output` holds this block's samples. Otherwise it is stale and is cleared only when
124    /// a stage reads or adds to it ([`Self::make_live`]).
125    live: bool,
126    /// Samples the bus chain delays its input by.
127    latency: i64,
128    /// One slot per clip on the track, in the track's order.
129    clips: Vec<ClipSlot>,
130    /// How long before a seek target the bus chain must run to settle (see [`Leads`]).
131    chain_lead: i64,
132    /// The same for the ducker, when one runs.
133    ducker_lead: i64,
134    /// Whether the bus is heard or keys the ducker of one that is (see [`read_buses`]).
135    read: bool,
136}
137
138impl TrackBus {
139    /// The bus driving this bus's ducker, if any and not itself; `index` is this bus's own.
140    fn active_sidechain(&self, index: usize) -> Option<usize> {
141        self.ducker.as_ref()?;
142        self.sidechain.filter(|&sidechain| sidechain != index)
143    }
144
145    /// Clears the first `frames` samples of `output` unless something already wrote the block.
146    fn make_live(&mut self, channels: usize, frames: usize) {
147        if self.live {
148            return;
149        }
150        for plane in self.output.iter_mut().take(channels) {
151            plane[..frames].fill(0.0);
152        }
153        self.live = true;
154        #[cfg(test)]
155        BUS_PLANES_CLEARED.set(BUS_PLANES_CLEARED.get() + channels);
156    }
157}
158
159/// A track's ducker and its output buffer, held only by buses that duck.
160struct BusDucker {
161    ducker: Ducker,
162    output: [Vec<f32>; 2],
163}
164
165struct ClipSlot {
166    id: ClipId,
167    chain: Option<ClipChain>,
168}
169
170/// A clip's own effect chain.
171///
172/// Processors exist only while the clip sounds (see [`AudioRenderer::keep_mixed_chains`]), so
173/// renderer state is bounded by the clips one block mixes
174/// ([`alpha2_model::Project::audio_effect_load`]), not by the whole timeline.
175struct ClipChain {
176    effects: Vec<AudioEffect>,
177    chain: Option<ProcessorChain>,
178    /// The block that last ran the chain.
179    ran_in: u64,
180    /// Samples the chain delays its input by.
181    latency: i64,
182    /// Samples the chain's nodes need to settle, excluding their delay.
183    history: u32,
184    /// Input position the chain continues from; anything else resets it.
185    next_input: Option<i64>,
186    /// How long before a seek target the chain must run to settle.
187    lead: i64,
188}
189
190/// Mixes a project's audio tracks into one project-rate block.
191pub struct AudioRenderer {
192    layout: ChannelLayout,
193    sample_rate: u32,
194    max_block: usize,
195    /// One bus per track, in project order.
196    buses: Vec<TrackBus>,
197    /// Buses by track ID, for clips evaluated from a different snapshot than the renderer's.
198    bus_of_track: HashMap<TrackId, usize>,
199    /// Clip slots by clip ID, `(bus, position)`, for the same case.
200    slot_of_clip: HashMap<ClipId, (usize, usize)>,
201    span_scratch: AudioSpanScratch,
202    master_chain: ProcessorChain,
203    /// Samples the master chain delays its input by.
204    master_latency: i64,
205    /// The longest latency from any clip's source to the output.
206    lookahead: i64,
207    /// Settling history beyond latency compensation: the longest lead of any stage.
208    history: i64,
209    /// How long before a seek target the master chain must run to settle.
210    master_lead: i64,
211    /// The same for the limiter.
212    limiter_lead: i64,
213    /// Distinct stage leads, longest first; a replay cuts its blocks at these so each stage starts
214    /// at its own sample whatever the block size (see [`Self::replay_frames`]).
215    stage_leads: Vec<i64>,
216    master: MasterAudio,
217    limiter: Option<PeakLimiter>,
218    /// Loudness normalization gain, between the master gain and the limiter. 1.0 unless set.
219    normalization_gain: f32,
220    hold_incomplete: bool,
221    continuity: AudioContinuity,
222    /// Measures what reaches the limiter, when metering is on.
223    meter: Option<LoudnessMeter>,
224    /// Measures the output after the limiter, when output metering is on.
225    output_meter: Option<LoudnessMeter>,
226    any_solo: bool,
227    clip_a: [Vec<f32>; 2],
228    clip_b: [Vec<f32>; 2],
229    bus_in: [Vec<f32>; 2],
230    mix: [Vec<f32>; 2],
231    output: [Vec<f32>; 2],
232    /// Per-sample gain and left/right pan weights (see [`fill_envelope`]).
233    envelope: [Vec<f32>; 3],
234    /// Where the last successful render ended; `None` before the first.
235    next_sample: Option<i64>,
236    /// Slots, `(bus, position)`, whose clip chain is built.
237    live_chains: Vec<(usize, usize)>,
238    blocks_mixed: u64,
239    /// Interpolation weights for a retimed read, per position or per repeating fraction.
240    weights: Vec<f64>,
241    /// Scratch for one fraction's weights while `weights` holds them all.
242    phase_weights: Vec<f64>,
243    /// Pitch-preserving stretch state for clips a block reads.
244    stretch: Stretch,
245    stretch_slots: HashMap<ClipId, StretchSlot>,
246    /// The most clip effects, and their delay in ticks, built at once.
247    #[cfg(test)]
248    most_held: (usize, u64),
249    /// Project samples [`Self::read_source`] has read from sources.
250    #[cfg(test)]
251    samples_read: usize,
252}
253
254/// What [`AudioRenderer::fill_clip`] does with a clip's source samples.
255#[derive(Clone, Copy, Debug, PartialEq, Eq)]
256enum Fill {
257    /// Reads and resamples them into `clip_a`.
258    Samples,
259    /// Only checks that `provider` supplies them, as a held render does before mixing.
260    Presence,
261}
262
263impl AudioRenderer {
264    /// Builds every track and master processor for a project snapshot. Clip processors are built
265    /// when the clip is first mixed.
266    ///
267    /// # Errors
268    /// Returns [`EngineError::InvalidAudioConfiguration`] for an unsupported
269    /// channel count, a zero sample rate, or an oversized block.
270    pub fn new(
271        snapshot: &EngineProject,
272        channels: usize,
273        max_block: usize,
274    ) -> Result<Self, EngineError> {
275        let layout =
276            ChannelLayout::from_channels(channels).ok_or(EngineError::InvalidAudioConfiguration)?;
277        let project = snapshot.project();
278        let sample_rate = project.settings.sample_rate;
279        if sample_rate == 0 || max_block == 0 || max_block > MAX_AUDIO_BLOCK {
280            return Err(EngineError::InvalidAudioConfiguration);
281        }
282
283        let (mut buses, bus_of_track) = track_buses(project, layout, sample_rate, max_block);
284        resolve_sidechains(&mut buses, &bus_of_track);
285        let slot_of_clip = buses
286            .iter()
287            .enumerate()
288            .flat_map(|(bus, track)| {
289                track
290                    .clips
291                    .iter()
292                    .enumerate()
293                    .map(move |(position, slot)| (slot.id.clone(), (bus, position)))
294            })
295            .collect();
296
297        let mut master_chain = ProcessorChain::new(layout);
298        push_effects(&mut master_chain, &project.audio.effects);
299        master_chain.prepare(sample_rate, max_block);
300        let limiter = project.audio.limiter.map(|limiter| {
301            let mut peak = PeakLimiter::new(limiter.threshold, limiter.release_ms);
302            peak.prepare(sample_rate, max_block);
303            peak
304        });
305        let any_solo = project.timeline.any_solo();
306        read_buses(&mut buses, any_solo);
307        let master_latency = i64::from(master_chain.latency_samples());
308        let lookahead = master_latency + longest_path_latency(&buses);
309        let settling = Settling(i64::from(sample_rate) * i64::from(MAX_SETTLING_SECONDS));
310        let limiter_lead = settling.lead(0, limiter.as_ref().map_or(0, Processor::history_samples));
311        let master_lead = settling.lead(limiter_lead, master_chain.history_samples());
312        let history = assign_leads(&mut buses, master_lead, settling).max(master_lead);
313        let stage_leads = stage_leads(&buses, master_lead, limiter_lead);
314
315        Ok(Self {
316            layout,
317            sample_rate,
318            max_block,
319            buses,
320            bus_of_track,
321            slot_of_clip,
322            span_scratch: AudioSpanScratch::default(),
323            master_chain,
324            master_latency,
325            lookahead,
326            history,
327            master_lead,
328            limiter_lead,
329            stage_leads,
330            master: project.audio.clone(),
331            limiter,
332            normalization_gain: 1.0,
333            hold_incomplete: false,
334            continuity: AudioContinuity::Exact,
335            meter: None,
336            output_meter: None,
337            any_solo,
338            clip_a: buffers(max_block),
339            clip_b: buffers(max_block),
340            bus_in: buffers(max_block),
341            mix: buffers(max_block),
342            output: buffers(max_block),
343            envelope: [
344                vec![0.0; max_block],
345                vec![0.0; max_block],
346                vec![0.0; max_block],
347            ],
348            next_sample: None,
349            live_chains: Vec::new(),
350            blocks_mixed: 0,
351            weights: Vec::new(),
352            phase_weights: Vec::new(),
353            stretch: Stretch::new(sample_rate),
354            stretch_slots: HashMap::new(),
355            #[cfg(test)]
356            most_held: (0, 0),
357            #[cfg(test)]
358            samples_read: 0,
359        })
360    }
361
362    /// Returns the project sample rate every block uses.
363    #[must_use]
364    pub const fn sample_rate(&self) -> u32 {
365        self.sample_rate
366    }
367
368    /// Returns the channel count of every mixed block.
369    #[must_use]
370    pub const fn channels(&self) -> usize {
371        self.layout.channels()
372    }
373
374    /// Returns the audio tracks this renderer mixes, in bus order.
375    #[must_use]
376    pub fn track_ids(&self) -> Vec<&TrackId> {
377        self.buses.iter().map(|bus| &bus.id).collect()
378    }
379
380    /// Returns the largest block this renderer accepts.
381    #[must_use]
382    pub const fn max_block(&self) -> usize {
383        self.max_block
384    }
385
386    /// Returns one mixed output channel from the most recent render.
387    #[must_use]
388    pub fn channel(&self, index: usize) -> &[f32] {
389        self.output.get(index).map_or(&[], Vec::as_slice)
390    }
391
392    /// How far ahead of a block, in samples, the renderer reads its sources.
393    ///
394    /// The renderer reads each path's input early by its latency to the output (for example a
395    /// compressor's `lookahead_ms`), so the output lines up with the timeline. Use
396    /// [`Self::audio_needs`] for source supply, since a cold seek also needs settling history.
397    #[must_use]
398    pub fn required_lookahead_samples(&self) -> u32 {
399        u32::try_from(self.lookahead).unwrap_or(u32::MAX)
400    }
401
402    /// The source intervals rendering `frames` samples from `start_sample` reads, for a host to
403    /// decode first.
404    ///
405    /// These are exactly what [`Self::render`] would read, including any settling replay, so a
406    /// host that holds them needs no margin. Overlapping or touching intervals of one source are
407    /// merged; disjoint ones stay separate.
408    ///
409    /// # Errors
410    /// Returns [`EngineError::InvalidAudioConfiguration`] for a negative start, an empty or
411    /// oversized block, or a span that does not fit in ticks, and an evaluation error when the
412    /// snapshot cannot be evaluated over a block's span.
413    pub fn audio_needs(
414        &self,
415        snapshot: &EngineProject,
416        start_sample: i64,
417        frames: usize,
418    ) -> Result<Vec<AudioNeed>, EngineError> {
419        self.check_block(start_sample, frames)?;
420        let mut needs = Vec::new();
421        let mut scratch = AudioSpanScratch::default();
422        if self.continues_at(start_sample).is_none() {
423            let mut position = self.preroll_start(start_sample)?;
424            while position < start_sample {
425                let count = self.replay_frames(position, start_sample);
426                self.block_needs(
427                    snapshot,
428                    position,
429                    count,
430                    Some(start_sample),
431                    &mut scratch,
432                    &mut needs,
433                )?;
434                position += i64::try_from(count).unwrap_or(i64::MAX);
435            }
436        }
437        self.block_needs(
438            snapshot,
439            start_sample,
440            frames,
441            None,
442            &mut scratch,
443            &mut needs,
444        )?;
445        Ok(needs)
446    }
447
448    /// Adds what one block of [`Self::mix_block`] reads to `needs`.
449    fn block_needs(
450        &self,
451        snapshot: &EngineProject,
452        start: i64,
453        frames: usize,
454        replay_target: Option<i64>,
455        scratch: &mut AudioSpanScratch,
456        needs: &mut Vec<AudioNeed>,
457    ) -> Result<(), EngineError> {
458        let frames_i64 = i64::try_from(frames).map_err(|_| EngineError::OutOfRange)?;
459        let stages = Stages {
460            target: replay_target,
461            block_end: start + frames_i64,
462            lookahead: self.lookahead,
463        };
464        let span = self.block_span(start, frames_i64)?;
465        let described = snapshot
466            .evaluate_audio_in(span, scratch)
467            .map_err(EngineError::Evaluate)?;
468        let master_input = start + self.master_latency;
469        let rate = self.sample_rate;
470        for clip in described.iter() {
471            let Some(read) = self.clip_read(&clip, master_input, frames, stages) else {
472                continue;
473            };
474            source_requests(
475                &self.stretch,
476                &clip,
477                read.first,
478                read.window.content,
479                rate,
480                |from, to| {
481                    let (Some(start), Some(end)) =
482                        (checked_ticks_at(from, rate), ticks_at_or_after(to, rate))
483                    else {
484                        return;
485                    };
486                    if let Ok(range) =
487                        TimeRange::new(MediaTime::from_ticks(start), MediaTime::from_ticks(end))
488                    {
489                        merge_need(needs, clip.source_id, clip.audio.stream, range);
490                    }
491                },
492            );
493        }
494        Ok(())
495    }
496
497    fn check_block(&self, start_sample: i64, frames: usize) -> Result<(), EngineError> {
498        if start_sample < 0 || frames == 0 || frames > self.max_block {
499            return Err(EngineError::InvalidAudioConfiguration);
500        }
501        // Every later position lies inside this span, so nothing below can overflow.
502        i64::try_from(frames)
503            .ok()
504            .and_then(|frames| start_sample.checked_add(frames))
505            .and_then(|end| end.checked_add(self.lookahead))
506            .and_then(|end| checked_ticks_at(end, self.sample_rate))
507            .map(|_| ())
508            .ok_or(EngineError::InvalidAudioConfiguration)
509    }
510
511    /// Settling history replayed on discontinuities, in samples, excluding latency. At most
512    /// [`MAX_SETTLING_SECONDS`].
513    #[must_use]
514    pub const fn required_history_samples(&self) -> i64 {
515        self.history
516    }
517
518    fn preroll_start(&self, start: i64) -> Result<i64, EngineError> {
519        if start < 0 {
520            return Err(EngineError::InvalidAudioConfiguration);
521        }
522        let history = if self.continues_at(start).is_some() {
523            0
524        } else {
525            self.history
526        };
527        // Input before timeline zero is silent, so only the latency pre-roll reaches before it.
528        Ok(start
529            .saturating_sub(history)
530            .max(0)
531            .saturating_sub(self.lookahead))
532    }
533
534    /// Samples the replay before a seek to `target` mixes at `position`. Blocks are cut where a
535    /// stage starts, so the replay is the same for every block size.
536    fn replay_frames(&self, position: i64, target: i64) -> usize {
537        let room = i64::try_from(self.max_block).unwrap_or(i64::MAX);
538        let mut end = target.min(position.saturating_add(room));
539        // Leads are sorted longest first, so stage starts ascend.
540        let begun = self
541            .stage_leads
542            .partition_point(|&lead| Stages::start(target, lead, self.lookahead) <= position);
543        if let Some(&lead) = self.stage_leads.get(begun) {
544            end = end.min(Stages::start(target, lead, self.lookahead));
545        }
546        usize::try_from(end - position).unwrap_or(1)
547    }
548
549    /// The step from where the last block ended, when a block at `start` continues it. `None`
550    /// when it must reset and replay.
551    fn continues_at(&self, start: i64) -> Option<i64> {
552        let step = start.checked_sub(self.next_sample?)?;
553        let room = i64::try_from(self.max_block).unwrap_or(i64::MAX);
554        let joins = self.continuity == AudioContinuity::ContinueSmallGaps && step.abs() <= room;
555        (step == 0 || joins).then_some(step)
556    }
557
558    /// Shifts every built clip chain's next input by `step` so it carries its state across a
559    /// small step.
560    fn step_live_chains(&mut self, step: i64) {
561        if step == 0 {
562            return;
563        }
564        for &(bus, position) in &self.live_chains {
565            if let Some(clip) = self.buses[bus].clips[position].chain.as_mut() {
566                clip.next_input = clip.next_input.and_then(|next| next.checked_add(step));
567            }
568        }
569    }
570
571    /// Sets the [`AudioContinuity`] policy (default [`AudioContinuity::Exact`]). Changing it resets
572    /// the renderer.
573    pub fn set_continuity(&mut self, continuity: AudioContinuity) {
574        if self.continuity != continuity {
575            self.reset();
576            self.continuity = continuity;
577        }
578    }
579
580    /// The policy [`Self::set_continuity`] last chose.
581    #[must_use]
582    pub const fn continuity(&self) -> AudioContinuity {
583        self.continuity
584    }
585
586    /// Clears every processor history without changing authored parameters.
587    ///
588    /// [`Self::render`] resets on its own at discontinuities. Call this only to start fresh exactly
589    /// where the last block ended, such as an export beginning where preview stopped.
590    pub fn reset(&mut self) {
591        self.next_sample = None;
592        // Built chains stay allocated; the next block drops the ones it does not mix.
593        for &(bus, position) in &self.live_chains {
594            if let Some(clip) = self.buses[bus].clips[position].chain.as_mut() {
595                if let Some(chain) = clip.chain.as_mut() {
596                    chain.reset();
597                }
598                clip.next_input = None;
599            }
600        }
601        for bus in &mut self.buses {
602            bus.chain.reset();
603            if let Some(ducking) = bus.ducker.as_mut() {
604                ducking.ducker.reset();
605            }
606        }
607        self.master_chain.reset();
608        if let Some(limiter) = self.limiter.as_mut() {
609            limiter.reset();
610        }
611    }
612
613    /// Mixes `frames` samples starting at an absolute project-rate sample index.
614    ///
615    /// A block that does not continue the previous one (see [`AudioContinuity`]) first resets
616    /// every processor and replays the settling history [`Self::audio_needs`] asks for, so its
617    /// output matches a fresh renderer's regardless of block size.
618    ///
619    /// Recursive effects settle over a finite horizon (32 exponential time constants plus
620    /// filter/feedback margins, capped at [`MAX_SETTLING_SECONDS`]), not bit-exactly. Each stage
621    /// joins the replay only at its own horizon, so a long reverb on one track replays only that
622    /// track.
623    ///
624    /// # Errors
625    /// Returns [`EngineError::InvalidAudioConfiguration`] for a negative start, an oversized block,
626    /// or a span that does not fit in ticks, and an evaluation error when the snapshot cannot be
627    /// evaluated over the block's span.
628    pub fn render(
629        &mut self,
630        snapshot: &EngineProject,
631        start_sample: i64,
632        frames: usize,
633        provider: &dyn AudioBlockProvider,
634        transport: TransportState,
635    ) -> Result<AudioRenderStatus, EngineError> {
636        self.check_block(start_sample, frames)?;
637        let end_sample = start_sample + i64::try_from(frames).unwrap_or(i64::MAX);
638        if self.hold_incomplete {
639            let missing_sources = self.unready_sources(snapshot, start_sample, frames, provider)?;
640            if !missing_sources.is_empty() {
641                for channel in 0..self.layout.channels() {
642                    self.output[channel][..frames].fill(0.0);
643                }
644                return Ok(AudioRenderStatus {
645                    start_sample,
646                    frames,
647                    missing_sources,
648                });
649            }
650        }
651        let mut missing_sources: Vec<SourceId> = Vec::new();
652        if let Some(step) = self.continues_at(start_sample) {
653            self.step_live_chains(step);
654        } else {
655            let mut position = self.preroll_start(start_sample)?;
656            self.reset();
657            while position < start_sample {
658                let count = self.replay_frames(position, start_sample);
659                self.mix_block(
660                    snapshot,
661                    position,
662                    count,
663                    provider,
664                    transport,
665                    Some(start_sample),
666                    &mut missing_sources,
667                )?;
668                position += i64::try_from(count).unwrap_or(i64::MAX);
669            }
670        }
671        self.mix_block(
672            snapshot,
673            start_sample,
674            frames,
675            provider,
676            transport,
677            None,
678            &mut missing_sources,
679        )?;
680        self.next_sample = Some(end_sample);
681
682        Ok(AudioRenderStatus {
683            start_sample,
684            frames,
685            missing_sources,
686        })
687    }
688
689    /// Sources a render of `[start_sample, start_sample + frames)`, pre-roll included, would read
690    /// that `provider` lacks. Reads no samples and changes no renderer state.
691    fn unready_sources(
692        &mut self,
693        snapshot: &EngineProject,
694        start_sample: i64,
695        frames: usize,
696        provider: &dyn AudioBlockProvider,
697    ) -> Result<Vec<SourceId>, EngineError> {
698        let mut missing = Vec::new();
699        let mut position = if self.continues_at(start_sample).is_some() {
700            start_sample
701        } else {
702            self.preroll_start(start_sample)?
703        };
704        while position < start_sample {
705            let count = self.replay_frames(position, start_sample);
706            self.read_block(
707                snapshot,
708                position,
709                count,
710                provider,
711                Some(start_sample),
712                &mut missing,
713            )?;
714            position += i64::try_from(count).unwrap_or(i64::MAX);
715        }
716        self.read_block(snapshot, start_sample, frames, provider, None, &mut missing)?;
717        Ok(missing)
718    }
719
720    /// Adds the sources `provider` lacks for one block of [`Self::mix_block`] to `missing`.
721    fn read_block(
722        &mut self,
723        snapshot: &EngineProject,
724        start: i64,
725        frames: usize,
726        provider: &dyn AudioBlockProvider,
727        replay_target: Option<i64>,
728        missing: &mut Vec<SourceId>,
729    ) -> Result<(), EngineError> {
730        let frames_i64 = i64::try_from(frames).map_err(|_| EngineError::OutOfRange)?;
731        let stages = Stages {
732            target: replay_target,
733            block_end: start + frames_i64,
734            lookahead: self.lookahead,
735        };
736        let span = self.block_span(start, frames_i64)?;
737        let mut scratch = std::mem::take(&mut self.span_scratch);
738        let described = match snapshot.evaluate_audio_in(span, &mut scratch) {
739            Ok(described) => described,
740            Err(error) => {
741                self.span_scratch = scratch;
742                return Err(EngineError::Evaluate(error));
743            }
744        };
745        let master_input = start + self.master_latency;
746        for clip in described.iter() {
747            let Some(read) = self.clip_read(&clip, master_input, frames, stages) else {
748                continue;
749            };
750            let window = read.window;
751            let complete = self.fill_clip(
752                &clip,
753                read.first,
754                window.count,
755                window.content,
756                provider,
757                Fill::Presence,
758            );
759            if !complete && !missing.contains(clip.source_id) {
760                missing.push(clip.source_id.clone());
761            }
762        }
763        self.span_scratch = scratch;
764        Ok(())
765    }
766
767    /// Mixes output samples `[start, start + frames)` into `output`, carrying processor state
768    /// forward.
769    ///
770    /// Each stage reads ahead by its latency to the output (master input at
771    /// `start + master_latency`, each bus and clip chain adding its own), so stage outputs line
772    /// up. A replay before a seek to `replay_target` runs only stages whose settling has begun.
773    #[allow(clippy::too_many_arguments)]
774    fn mix_block(
775        &mut self,
776        snapshot: &EngineProject,
777        start: i64,
778        frames: usize,
779        provider: &dyn AudioBlockProvider,
780        transport: TransportState,
781        replay_target: Option<i64>,
782        missing_sources: &mut Vec<SourceId>,
783    ) -> Result<(), EngineError> {
784        let channels = self.layout.channels();
785        let context = snapshot.sample_context();
786        let frames_i64 = i64::try_from(frames).map_err(|_| EngineError::OutOfRange)?;
787        let stages = Stages {
788            target: replay_target,
789            block_end: start + frames_i64,
790            lookahead: self.lookahead,
791        };
792        let span = self.block_span(start, frames_i64)?;
793        // Take the scratch out of `self` so the clip loop can still borrow `self` mutably.
794        let mut scratch = std::mem::take(&mut self.span_scratch);
795        let described = match snapshot.evaluate_audio_in(span, &mut scratch) {
796            Ok(described) => described,
797            Err(error) => {
798                self.span_scratch = scratch;
799                return Err(EngineError::Evaluate(error));
800            }
801        };
802
803        for channel in 0..channels {
804            self.mix[channel][..frames].fill(0.0);
805        }
806        for bus in &mut self.buses {
807            bus.live = false;
808        }
809
810        let master_input = start + self.master_latency;
811        self.keep_mixed_chains(&described, master_input, frames, stages);
812        let mut complete_block = true;
813        for clip in described.iter() {
814            let clip = &clip;
815            let Some(read) = self.clip_read(clip, master_input, frames, stages) else {
816                continue;
817            };
818            let window = read.window;
819            let complete = self.fill_clip(
820                clip,
821                read.first,
822                window.count,
823                window.content,
824                provider,
825                Fill::Samples,
826            );
827            complete_block &= complete;
828            if !complete && !missing_sources.contains(clip.source_id) {
829                missing_sources.push(clip.source_id.clone());
830            }
831            if let Some(slot) = read.slot {
832                self.apply_clip_chain(slot, read.first, transport, window.count);
833            }
834            self.mix_clip_into_bus(
835                clip,
836                read.bus,
837                read.bus_input,
838                window.offset,
839                window.count,
840                frames,
841                &context,
842            );
843        }
844        self.span_scratch = scratch;
845        // Drop stretch readers this block did not use.
846        let block = self.blocks_mixed;
847        self.stretch_slots.retain(|_, slot| slot.used_in == block);
848
849        self.process_buses(master_input, transport, frames, stages);
850        self.apply_ducking(&self.ctx(master_input, transport), frames, stages);
851        if stages.run(self.master_lead) {
852            self.sum_buses(master_input, frames, &context);
853            self.finish_master(
854                start,
855                master_input,
856                transport,
857                frames,
858                stages,
859                complete_block,
860                &context,
861            );
862        }
863        self.blocks_mixed += 1;
864        Ok(())
865    }
866
867    /// Drops the chain of every clip the block does not mix, before the block builds any, so only
868    /// one block's clips hold chains at once. A dropped clip mixed again would start from fresh
869    /// state anyway.
870    fn keep_mixed_chains(
871        &mut self,
872        described: &alpha2_eval::AudioSpan<'_, '_>,
873        master_input: i64,
874        frames: usize,
875        stages: Stages,
876    ) {
877        let block = self.blocks_mixed;
878        for clip in described.iter() {
879            let Some((bus, position)) = self
880                .clip_read(&clip, master_input, frames, stages)
881                .and_then(|read| read.slot)
882            else {
883                continue;
884            };
885            if let Some(chain) = self.buses[bus].clips[position].chain.as_mut() {
886                chain.ran_in = block;
887            }
888        }
889        let buses = &mut self.buses;
890        self.live_chains.retain(|&(bus, position)| {
891            let Some(clip) = buses[bus].clips[position].chain.as_mut() else {
892                return false;
893            };
894            if clip.ran_in == block {
895                return true;
896            }
897            clip.chain = None;
898            clip.next_input = None;
899            false
900        });
901    }
902
903    fn ctx(&self, sample: i64, transport: TransportState) -> ProcessCtx {
904        ProcessCtx {
905            position: MediaTime::from_ticks(ticks_at(sample, self.sample_rate)),
906            sample_position: sample,
907            sample_rate: self.sample_rate,
908            transport,
909        }
910    }
911
912    /// Sets the loudness normalization gain in dB, applied between the master gain and the
913    /// limiter. Zero removes it, as does [`Self::set_loudness_metering`].
914    ///
915    /// # Errors
916    /// Returns [`EngineError::InvalidNormalizationGain`] for a non-finite gain or one whose linear
917    /// factor is not a normal `f32` (beyond about 760 dB either way).
918    pub fn set_normalization_gain_db(&mut self, gain_db: f64) -> Result<(), EngineError> {
919        #[allow(clippy::cast_possible_truncation)]
920        let gain = libm::pow(10.0, gain_db / 20.0) as f32;
921        if !gain_db.is_finite() || !gain.is_normal() {
922            return Err(EngineError::InvalidNormalizationGain);
923        }
924        self.normalization_gain = gain;
925        Ok(())
926    }
927
928    /// Whether a block missing a source is held: output as silence with nothing advanced, so
929    /// rendering it again after the host supplies the source matches an uninterrupted render.
930    /// Off by default (live playback); exports turn it on.
931    pub const fn set_hold_incomplete_blocks(&mut self, hold: bool) {
932        self.hold_incomplete = hold;
933    }
934
935    /// Starts (or restarts from empty) measuring the loudness of what reaches the limiter; `false`
936    /// stops. Only complete requested blocks are measured, never replayed history.
937    ///
938    /// Starting removes the normalization gain ([`Self::set_normalization_gain_db`]) so the
939    /// authored mix is measured; a gain set afterwards is included.
940    ///
941    /// # Errors
942    /// Returns [`EngineError::InvalidAudioConfiguration`] for an unsupported layout or rate.
943    pub fn set_loudness_metering(&mut self, enabled: bool) -> Result<(), EngineError> {
944        if enabled {
945            self.normalization_gain = 1.0;
946        }
947        self.meter = if enabled {
948            Some(
949                LoudnessMeter::new(self.sample_rate, self.layout.channels())
950                    .map_err(|_| EngineError::InvalidAudioConfiguration)?,
951            )
952        } else {
953            None
954        };
955        Ok(())
956    }
957
958    /// What the meter has measured, if metering is on.
959    #[must_use]
960    pub fn loudness_report(&self) -> Option<LoudnessReport> {
961        self.meter.as_ref().map(LoudnessMeter::report)
962    }
963
964    /// The master limiter's linear threshold, if any. Pass it to
965    /// [`alpha2_audio::LoudnessNormalization::plan`] so the planned gain stops short of the limiter.
966    #[must_use]
967    pub fn limiter_threshold(&self) -> Option<f64> {
968        self.master
969            .limiter
970            .map(|limiter| f64::from(limiter.threshold))
971    }
972
973    /// Starts (or restarts from empty) measuring the loudness of the final output, after the
974    /// limiter and normalization gain; `false` stops. Unlike [`Self::set_loudness_metering`] it
975    /// leaves the gain unchanged.
976    ///
977    /// # Errors
978    /// Returns [`EngineError::InvalidAudioConfiguration`] for an unsupported layout or rate.
979    pub fn set_output_loudness_metering(&mut self, enabled: bool) -> Result<(), EngineError> {
980        self.output_meter = if enabled {
981            Some(
982                LoudnessMeter::new(self.sample_rate, self.layout.channels())
983                    .map_err(|_| EngineError::InvalidAudioConfiguration)?,
984            )
985        } else {
986            None
987        };
988        Ok(())
989    }
990
991    /// What the output meter has measured, if output metering is on.
992    #[must_use]
993    pub fn output_loudness_report(&self) -> Option<LoudnessReport> {
994        self.output_meter.as_ref().map(LoudnessMeter::report)
995    }
996
997    /// Copies the most recent render into an owned block for offline sinks.
998    #[must_use]
999    pub fn block(&self, status: &AudioRenderStatus) -> AudioBlock {
1000        AudioBlock {
1001            start_sample: status.start_sample,
1002            sample_rate: self.sample_rate,
1003            speakers: match self.layout {
1004                ChannelLayout::Mono => SpeakerLayout::MONO,
1005                ChannelLayout::Stereo => SpeakerLayout::STEREO,
1006            },
1007            channels: (0..self.layout.channels())
1008                .map(|channel| self.output[channel][..status.frames].to_vec())
1009                .collect(),
1010        }
1011    }
1012
1013    /// The bus of a clip's track, by track order or, for another snapshot's clip, by track ID.
1014    fn bus_of(&self, clip: &ActiveAudioClip) -> Option<usize> {
1015        match self.buses.get(clip.track_order) {
1016            Some(bus) if bus.id == *clip.track_id => Some(clip.track_order),
1017            _ => self.bus_of_track.get(clip.track_id).copied(),
1018        }
1019    }
1020
1021    /// A clip's slot, `(bus, position)`, found as [`Self::bus_of`] finds its bus.
1022    fn slot_of(&self, clip: &ActiveAudioClip) -> Option<(usize, usize)> {
1023        let slot = (clip.track_order, clip.clip_order);
1024        let matches = self
1025            .buses
1026            .get(slot.0)
1027            .and_then(|bus| bus.clips.get(slot.1))
1028            .is_some_and(|found| found.id == *clip.clip_id);
1029        if matches {
1030            Some(slot)
1031        } else {
1032            self.slot_of_clip.get(clip.clip_id).copied()
1033        }
1034    }
1035
1036    fn clip_chain(&self, (bus, position): (usize, usize)) -> Option<&ClipChain> {
1037        self.buses[bus].clips[position].chain.as_ref()
1038    }
1039
1040    /// Whether the bus is muted or outside the solo.
1041    fn is_silent_bus(&self, index: usize) -> bool {
1042        self.buses[index].audio.is_silenced(self.any_solo)
1043    }
1044
1045    /// The timeline span evaluated for output samples `[start, start + frames)`, including the
1046    /// lookahead.
1047    fn block_span(&self, start: i64, frames: i64) -> Result<TimeRange, EngineError> {
1048        let invalid = EngineError::InvalidAudioConfiguration;
1049        let span_end = start
1050            .checked_add(frames)
1051            .and_then(|end| end.checked_add(self.lookahead))
1052            .ok_or(invalid.clone())?;
1053        let start_ticks = checked_ticks_at(start, self.sample_rate).ok_or(invalid.clone())?;
1054        let end_ticks = checked_ticks_at(span_end, self.sample_rate)
1055            .zip(start_ticks.checked_add(1))
1056            .map(|(end, after_start)| end.max(after_start))
1057            .ok_or(invalid.clone())?;
1058        TimeRange::new(
1059            MediaTime::from_ticks(start_ticks),
1060            MediaTime::from_ticks(end_ticks),
1061        )
1062        .map_err(|_| invalid)
1063    }
1064
1065    /// Where a block reads a clip, or `None` if it skips it. The mix and [`Self::audio_needs`]
1066    /// share this so a host is asked for exactly what the mix reads.
1067    fn clip_read(
1068        &self,
1069        clip: &ActiveAudioClip,
1070        master_input: i64,
1071        frames: usize,
1072        stages: Stages,
1073    ) -> Option<ClipRead> {
1074        let bus = self.bus_of(clip)?;
1075        if !clip.audio.is_audible() || !self.buses[bus].read {
1076            return None;
1077        }
1078        let bus_input = master_input + self.buses[bus].latency;
1079        let slot = self.slot_of(clip);
1080        let chain = slot.and_then(|slot| self.clip_chain(slot));
1081        let lead = chain.map_or(self.buses[bus].chain_lead, |chain| chain.lead);
1082        if !stages.run(lead) {
1083            return None;
1084        }
1085        let clip_latency = chain.map_or(0, |chain| chain.latency);
1086        let chain_input = bus_input + clip_latency;
1087        let window = self.clip_window(clip, chain_input, frames, clip_latency)?;
1088        Some(ClipRead {
1089            bus,
1090            bus_input,
1091            slot,
1092            first: chain_input + i64::try_from(window.offset).ok()?,
1093            window,
1094        })
1095    }
1096
1097    /// The part of a block of chain input that a clip covers, plus `latency` samples of silence to
1098    /// flush its chain's delay line.
1099    fn clip_window(
1100        &self,
1101        clip: &ActiveAudioClip,
1102        input: i64,
1103        frames: usize,
1104        latency: i64,
1105    ) -> Option<ClipWindow> {
1106        let first = sample_at_or_after(clip.timeline_range.start().ticks(), self.sample_rate);
1107        let last = sample_at_or_after(clip.timeline_range.end().ticks(), self.sample_rate);
1108        let block_end = input.checked_add(i64::try_from(frames).ok()?)?;
1109        let begin = first.max(input);
1110        let end = last.saturating_add(latency).min(block_end);
1111        if end <= begin {
1112            return None;
1113        }
1114        Some(ClipWindow {
1115            offset: usize::try_from(begin - input).ok()?,
1116            count: usize::try_from(end - begin).ok()?,
1117            content: usize::try_from((last.min(end) - begin).max(0)).ok()?,
1118        })
1119    }
1120
1121    /// Reads one clip's source window into `clip_a` (or only checks it, with [`Fill::Presence`]).
1122    /// Returns whether every requested sample came from supplied media.
1123    fn fill_clip(
1124        &mut self,
1125        clip: &ActiveAudioClip,
1126        first_sample: i64,
1127        count: usize,
1128        content: usize,
1129        provider: &dyn AudioBlockProvider,
1130        fill: Fill,
1131    ) -> bool {
1132        if fill == Fill::Samples {
1133            for channel in 0..self.layout.channels() {
1134                self.clip_a[channel][..count].fill(0.0);
1135            }
1136        }
1137        // Past the clip's end is the silence that flushes its chain.
1138        let count = content;
1139        if count == 0 {
1140            return true;
1141        }
1142        let rate = self.sample_rate;
1143        match clip.time_map {
1144            // A frozen clip is silent.
1145            TimeMap::Freeze { .. } => true,
1146            TimeMap::Forward | TimeMap::Reverse if stretches(clip) => {
1147                self.read_stretched(clip, first_sample, count, provider, fill)
1148            }
1149            TimeMap::Forward | TimeMap::Reverse => {
1150                let reversed = clip.time_map == TimeMap::Reverse;
1151                SourceMap::stretched(clip, reversed, rate).is_some_and(|map| {
1152                    self.read_source(clip, &map, first_sample, 0, count, provider, fill)
1153                })
1154            }
1155            TimeMap::Loop { mode } => {
1156                self.fill_loop(clip, mode, first_sample, count, provider, fill)
1157            }
1158        }
1159    }
1160
1161    /// Reads a looping clip one pass at a time. A repeating loop fades out and in around each wrap.
1162    fn fill_loop(
1163        &mut self,
1164        clip: &ActiveAudioClip,
1165        mode: LoopMode,
1166        first_sample: i64,
1167        count: usize,
1168        provider: &dyn AudioBlockProvider,
1169        fill: Fill,
1170    ) -> bool {
1171        let rate = self.sample_rate;
1172        let end = clip.timeline_range.end().ticks();
1173        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
1174        let fade = ((f64::from(rate) * LOOP_FADE_SECONDS).round() as i64).max(1);
1175        let mut complete = true;
1176        let mapped = loop_pieces(clip, mode, first_sample, count, rate, |piece| {
1177            complete &= self.read_source(
1178                clip,
1179                &piece.map,
1180                piece.sample,
1181                piece.index,
1182                piece.length,
1183                provider,
1184                fill,
1185            );
1186            if mode == LoopMode::Repeat && fill == Fill::Samples {
1187                // Fade around wraps inside the clip only; its own ends have authored fades.
1188                let fade_in = (piece.pass > 0).then(|| sample_at_or_after(piece.pass_start, rate));
1189                let fade_out = (piece.pass_end < end).then_some(piece.piece_end);
1190                self.fade_wraps(
1191                    piece.sample,
1192                    piece.index,
1193                    piece.length,
1194                    fade_in,
1195                    fade_out,
1196                    fade,
1197                );
1198            }
1199        });
1200        mapped && complete
1201    }
1202
1203    /// Applies a linear `fade`-sample ramp after the wrap at `fade_in` and before the one at
1204    /// `fade_out`, centred between the samples either side of the wrap.
1205    fn fade_wraps(
1206        &mut self,
1207        first_sample: i64,
1208        offset: usize,
1209        count: usize,
1210        fade_in: Option<i64>,
1211        fade_out: Option<i64>,
1212        fade: i64,
1213    ) {
1214        #[allow(clippy::cast_precision_loss)]
1215        let fade = fade as f64;
1216        for index in 0..count {
1217            let sample = first_sample + i64::try_from(index).unwrap_or(i64::MAX);
1218            #[allow(clippy::cast_precision_loss)]
1219            let after = fade_in.map_or(f64::INFINITY, |wrap| (sample - wrap) as f64 + 0.5);
1220            #[allow(clippy::cast_precision_loss)]
1221            let before = fade_out.map_or(f64::INFINITY, |wrap| (wrap - sample) as f64 - 0.5);
1222            let distance = after.min(before);
1223            if distance >= fade {
1224                continue;
1225            }
1226            #[allow(clippy::cast_possible_truncation)]
1227            let gain = (distance / fade).clamp(0.0, 1.0) as f32;
1228            for channel in 0..self.layout.channels() {
1229                self.clip_a[channel][offset + index] *= gain;
1230            }
1231        }
1232    }
1233
1234    /// Reads `count` project samples from `first_sample` through `map` into `clip_a` at `offset`.
1235    /// Returns whether every requested sample came from supplied media.
1236    #[allow(clippy::too_many_arguments)]
1237    fn read_source(
1238        &mut self,
1239        clip: &ActiveAudioClip,
1240        map: &SourceMap,
1241        first_sample: i64,
1242        offset: usize,
1243        count: usize,
1244        provider: &dyn AudioBlockProvider,
1245        fill: Fill,
1246    ) -> bool {
1247        // Positions are exact rationals, so a source aligned with the project grid copies unchanged.
1248        let Some((request_start, request_end)) = map.request(first_sample, count) else {
1249            return false;
1250        };
1251        let request_frames =
1252            usize::try_from(request_end.saturating_sub(request_start)).unwrap_or(0);
1253        let Some(span) = provider.block(
1254            clip.source_id,
1255            clip.audio.stream,
1256            request_start,
1257            request_frames,
1258        ) else {
1259            return false;
1260        };
1261        // An uncovered part of the window is media that has not arrived, not silence.
1262        if !span.covers(request_start, request_end) {
1263            return false;
1264        }
1265        let source = span.block;
1266        if source.sample_rate != self.sample_rate {
1267            return false;
1268        }
1269
1270        let Some(downmix) = clip_downmix(clip, source, self.layout) else {
1271            return false;
1272        };
1273        if fill == Fill::Presence {
1274            return true;
1275        }
1276        #[cfg(test)]
1277        {
1278            self.samples_read += count;
1279        }
1280        let read = SourceRead {
1281            planes: source.channels.as_slice(),
1282            downmix: &downmix,
1283            start: source.start_sample,
1284            offset,
1285            count,
1286        };
1287        match (map.cursor(first_sample), map.interpolator()) {
1288            // The divisor does not fit the cursor, so divide per sample.
1289            (None, interpolator) => self.read_divided(&read, map, first_sample, interpolator),
1290            (Some(cursor), None) => self.read_copied(&read, cursor),
1291            (Some(cursor), Some(interpolator)) => {
1292                self.read_filtered(&read, map, cursor, interpolator);
1293            }
1294        }
1295        true
1296    }
1297
1298    /// [`Self::read_source`] where every position lands on a whole source sample.
1299    fn read_copied(&mut self, read: &SourceRead<'_>, cursor: RationalCursor) {
1300        let Some(first) = cursor.whole.checked_sub(read.start) else {
1301            return;
1302        };
1303        for channel in 0..self.layout.channels() {
1304            let mix = read.downmix.channel(channel);
1305            let mut at = first;
1306            let outputs = &mut self.clip_a[channel][read.offset..read.offset + read.count];
1307            if let Some(plane) = mix.unity() {
1308                let plane = read.planes[plane].as_slice();
1309                for output in outputs {
1310                    *output = copied(plane, at);
1311                    at = at.wrapping_add(cursor.step_whole);
1312                }
1313            } else {
1314                for output in outputs {
1315                    *output = mixed_sample(mix, read.planes, at);
1316                    at = at.wrapping_add(cursor.step_whole);
1317                }
1318            }
1319        }
1320    }
1321
1322    /// [`Self::read_source`] through `interpolator`. When the fractional positions repeat with a
1323    /// short period (small speed ratios), each phase's weights are computed once per read.
1324    fn read_filtered(
1325        &mut self,
1326        read: &SourceRead<'_>,
1327        map: &SourceMap,
1328        mut cursor: RationalCursor,
1329        interpolator: Interpolator,
1330    ) {
1331        let mut weights = std::mem::take(&mut self.weights);
1332        let reach = interpolator.half_taps() - 1;
1333        let taps = usize::try_from(2 * interpolator.half_taps()).unwrap_or(0);
1334        let phases = usize::try_from(cursor.period())
1335            .ok()
1336            .filter(|&period| period <= read.count / 2 && period * taps <= MAX_CACHED_WEIGHTS);
1337        if let Some(phases) = phases {
1338            weights.resize(phases * taps, 0.0);
1339            let mut scratch = std::mem::take(&mut self.phase_weights);
1340            let mut walk = cursor;
1341            for row in weights.chunks_exact_mut(taps) {
1342                interpolator.weights(map.fraction(&walk).1, &mut scratch);
1343                row.copy_from_slice(&scratch);
1344                walk.advance();
1345            }
1346            self.phase_weights = scratch;
1347        }
1348        let mut phase = 0;
1349        for index in 0..read.count {
1350            let (whole, fraction) = map.fraction(&cursor);
1351            cursor.advance();
1352            let row = if let Some(phases) = phases {
1353                let row = phase;
1354                phase = if phase + 1 == phases { 0 } else { phase + 1 };
1355                &weights[row * taps..(row + 1) * taps]
1356            } else {
1357                interpolator.weights(fraction, &mut weights);
1358                &weights[..]
1359            };
1360            let Some(first) = whole
1361                .checked_sub(read.start)
1362                .and_then(|at| at.checked_sub(reach))
1363            else {
1364                continue;
1365            };
1366            for channel in 0..self.layout.channels() {
1367                self.clip_a[channel][read.offset + index] =
1368                    filtered_sample(read.downmix.channel(channel), read.planes, first, row);
1369            }
1370        }
1371        self.weights = weights;
1372    }
1373
1374    /// [`Self::read_source`] for a map whose divisor does not fit a cursor.
1375    fn read_divided(
1376        &mut self,
1377        read: &SourceRead<'_>,
1378        map: &SourceMap,
1379        first_sample: i64,
1380        interpolator: Option<Interpolator>,
1381    ) {
1382        let mut weights = std::mem::take(&mut self.weights);
1383        for index in 0..read.count {
1384            let sample = first_sample + i64::try_from(index).unwrap_or(0);
1385            let Some((whole, fraction)) = map.position(sample) else {
1386                continue;
1387            };
1388            let Some(at) = whole.checked_sub(read.start) else {
1389                continue;
1390            };
1391            if let Some(interpolator) = interpolator {
1392                interpolator.weights(fraction, &mut weights);
1393            }
1394            for channel in 0..self.layout.channels() {
1395                let mix = read.downmix.channel(channel);
1396                self.clip_a[channel][read.offset + index] = match interpolator {
1397                    None => mixed_sample(mix, read.planes, at),
1398                    Some(interpolator) => filtered_sample(
1399                        mix,
1400                        read.planes,
1401                        at - interpolator.half_taps() + 1,
1402                        &weights,
1403                    ),
1404                };
1405            }
1406        }
1407        self.weights = weights;
1408    }
1409
1410    /// Runs a clip's chain over `count` samples starting at `input`, resetting it unless it
1411    /// continues from where it stopped.
1412    fn apply_clip_chain(
1413        &mut self,
1414        (bus, position): (usize, usize),
1415        input: i64,
1416        transport: TransportState,
1417        count: usize,
1418    ) {
1419        let ctx = self.ctx(input, transport);
1420        let (layout, sample_rate, max_block) = (self.layout, self.sample_rate, self.max_block);
1421        let Some(clip_chain) = self.buses[bus].clips[position].chain.as_mut() else {
1422            return;
1423        };
1424        if clip_chain.chain.is_none() {
1425            self.live_chains.push((bus, position));
1426        }
1427        let effects = &clip_chain.effects;
1428        let chain = clip_chain
1429            .chain
1430            .get_or_insert_with(|| clip_processors(effects, layout, sample_rate, max_block));
1431        clip_chain.ran_in = self.blocks_mixed;
1432        if clip_chain.next_input != Some(input) {
1433            chain.reset();
1434        }
1435        clip_chain.next_input = Some(input + i64::try_from(count).unwrap_or(0));
1436        chain.process_in_place(&ctx, &mut self.clip_a, &mut self.clip_b, count);
1437        #[cfg(test)]
1438        self.note_held();
1439    }
1440
1441    /// Records the clip effects built now in [`Self::most_held`].
1442    #[cfg(test)]
1443    fn note_held(&mut self) {
1444        let held = self
1445            .live_chains
1446            .iter()
1447            .filter_map(|&(bus, position)| self.buses[bus].clips[position].chain.as_ref())
1448            .filter(|clip| clip.chain.is_some())
1449            .fold((0, 0), |(effects, delay), clip| {
1450                (
1451                    effects + clip.effects.len(),
1452                    delay
1453                        + clip
1454                            .effects
1455                            .iter()
1456                            .map(AudioEffect::delay_ticks)
1457                            .sum::<u64>(),
1458                )
1459            });
1460        self.most_held = (self.most_held.0.max(held.0), self.most_held.1.max(held.1));
1461    }
1462
1463    /// Applies gain, fades, and panning, then sums into the bus. Constant gain and pan with no
1464    /// fade in the window are evaluated once; otherwise they follow [`fill_envelope`].
1465    #[allow(clippy::too_many_arguments)]
1466    fn mix_clip_into_bus(
1467        &mut self,
1468        clip: &ActiveAudioClip,
1469        bus_index: usize,
1470        start_sample: i64,
1471        offset: usize,
1472        count: usize,
1473        frames: usize,
1474        context: &SampleContext<'_>,
1475    ) {
1476        let channels = self.layout.channels();
1477        let sample_rate = self.sample_rate;
1478        let bus = &mut self.buses[bus_index];
1479        let first = start_sample + i64::try_from(offset).unwrap_or(0);
1480        bus.make_live(channels, frames);
1481        let gain = constant_value(&clip.audio.gain).map(|gain| gain.clamp(0.0, MAX_GAIN));
1482        let weights =
1483            constant_value(&clip.audio.pan).map(|pan| pan_gains(pan.clamp(-1.0, 1.0), channels));
1484        if let (Some(gain), Some(weights), false) =
1485            (gain, weights, fades_reach(clip, first, count, sample_rate))
1486        {
1487            for (channel, weight) in weights.iter().enumerate().take(channels) {
1488                let input = &self.clip_a[channel][..count];
1489                let output = &mut bus.output[channel][offset..offset + count];
1490                for (output, sample) in output.iter_mut().zip(input) {
1491                    *output += sample * gain * weight;
1492                }
1493            }
1494            return;
1495        }
1496        let audio = clip.audio;
1497        fill_envelope(
1498            &mut self.envelope[..],
1499            first,
1500            count,
1501            sample_rate,
1502            |ticks| {
1503                earliest(
1504                    earliest(
1505                        next_keyframe(&audio.gain, ticks, context),
1506                        next_keyframe(&audio.pan, ticks, context),
1507                    ),
1508                    next_fade_edge(clip, ticks),
1509                )
1510            },
1511            |time| {
1512                let gain = sample_scalar(&audio.gain, time, context).clamp(0.0, MAX_GAIN)
1513                    * fade_gain(clip, time);
1514                let [left, right] = pan_gains(sample_scalar(&audio.pan, time, context), channels);
1515                [gain, left, right]
1516            },
1517        );
1518        let [gains, left, right] = &self.envelope;
1519        for (channel, weights) in [left, right].into_iter().enumerate().take(channels) {
1520            let input = &self.clip_a[channel][..count];
1521            let output = &mut bus.output[channel][offset..offset + count];
1522            for (((output, sample), gain), weight) in
1523                output.iter_mut().zip(input).zip(gains).zip(weights)
1524            {
1525                *output += sample * gain * weight;
1526            }
1527        }
1528    }
1529
1530    fn process_buses(
1531        &mut self,
1532        master_input: i64,
1533        transport: TransportState,
1534        frames: usize,
1535        stages: Stages,
1536    ) {
1537        let channels = self.layout.channels();
1538        let sample_rate = self.sample_rate;
1539        for bus in &mut self.buses {
1540            if !stages.run(bus.chain_lead) || bus.chain.passes_through() {
1541                continue;
1542            }
1543            let input = master_input + bus.latency;
1544            let ctx = &ProcessCtx {
1545                position: MediaTime::from_ticks(ticks_at(input, sample_rate)),
1546                sample_position: input,
1547                sample_rate,
1548                transport,
1549            };
1550            bus.make_live(channels, frames);
1551            for channel in 0..channels {
1552                self.bus_in[channel][..frames].copy_from_slice(&bus.output[channel][..frames]);
1553            }
1554            match channels {
1555                1 => bus.chain.process(
1556                    ctx,
1557                    &[&self.bus_in[0][..frames]],
1558                    &mut [&mut bus.output[0][..frames]],
1559                ),
1560                2 => {
1561                    let (left, right) = bus.output.split_at_mut(1);
1562                    bus.chain.process(
1563                        ctx,
1564                        &[&self.bus_in[0][..frames], &self.bus_in[1][..frames]],
1565                        &mut [&mut left[0][..frames], &mut right[0][..frames]],
1566                    );
1567                }
1568                _ => {}
1569            }
1570        }
1571    }
1572
1573    /// Attenuates ducked buses from the pre-duck output of their sidechain.
1574    ///
1575    /// Every ducker writes its own buffer before any bus `output` changes, so a ducked sidechain
1576    /// is read pre-duck regardless of track order.
1577    fn apply_ducking(&mut self, ctx: &ProcessCtx, frames: usize, stages: Stages) {
1578        let channels = self.layout.channels();
1579        let ducks = |bus: &TrackBus, index: usize| {
1580            bus.active_sidechain(index).is_some() && stages.run(bus.ducker_lead)
1581        };
1582        for index in 0..self.buses.len() {
1583            if !ducks(&self.buses[index], index) {
1584                continue;
1585            }
1586            let Some(sidechain) = self.buses[index].active_sidechain(index) else {
1587                continue;
1588            };
1589            // Either bus may be idle; the ducker still runs on silence.
1590            self.buses[sidechain].make_live(channels, frames);
1591            for channel in 0..channels {
1592                self.bus_in[channel][..frames]
1593                    .copy_from_slice(&self.buses[sidechain].output[channel][..frames]);
1594            }
1595            let bus = &mut self.buses[index];
1596            bus.make_live(channels, frames);
1597            let Some(BusDucker { ducker, output }) = bus.ducker.as_mut() else {
1598                continue;
1599            };
1600            match channels {
1601                1 => ducker.process(
1602                    ctx,
1603                    &[&bus.output[0][..frames], &self.bus_in[0][..frames]],
1604                    &mut [&mut output[0][..frames]],
1605                ),
1606                2 => {
1607                    let (left, right) = output.split_at_mut(1);
1608                    ducker.process(
1609                        ctx,
1610                        &[
1611                            &bus.output[0][..frames],
1612                            &bus.output[1][..frames],
1613                            &self.bus_in[0][..frames],
1614                            &self.bus_in[1][..frames],
1615                        ],
1616                        &mut [&mut left[0][..frames], &mut right[0][..frames]],
1617                    );
1618                }
1619                _ => {}
1620            }
1621        }
1622        for (index, bus) in self.buses.iter_mut().enumerate() {
1623            if ducks(bus, index)
1624                && let Some(ducking) = bus.ducker.as_mut()
1625            {
1626                std::mem::swap(&mut bus.output, &mut ducking.output);
1627            }
1628        }
1629    }
1630
1631    fn sum_buses(&mut self, start_sample: i64, frames: usize, context: &SampleContext<'_>) {
1632        let channels = self.layout.channels();
1633        for bus_index in 0..self.buses.len() {
1634            // Skipping an idle bus is exact: adding `+0.0` to a sum that is never `-0.0` is a no-op.
1635            if self.is_silent_bus(bus_index) || !self.buses[bus_index].live {
1636                continue;
1637            }
1638            let bus = &self.buses[bus_index];
1639            #[cfg(test)]
1640            BUS_PLANES_SUMMED.set(BUS_PLANES_SUMMED.get() + channels);
1641            let gain = constant_value(&bus.audio.gain).map(|gain| gain.clamp(0.0, MAX_GAIN));
1642            let weights =
1643                constant_value(&bus.audio.pan).map(|pan| pan_gains(pan.clamp(-1.0, 1.0), channels));
1644            if let (Some(gain), Some(weights)) = (gain, weights) {
1645                for (channel, weight) in weights.iter().enumerate().take(channels) {
1646                    let input = &bus.output[channel][..frames];
1647                    let output = &mut self.mix[channel][..frames];
1648                    for (output, sample) in output.iter_mut().zip(input) {
1649                        *output += sample * gain * weight;
1650                    }
1651                }
1652                continue;
1653            }
1654            let audio = &bus.audio;
1655            fill_envelope(
1656                &mut self.envelope[..],
1657                start_sample,
1658                frames,
1659                self.sample_rate,
1660                |ticks| {
1661                    earliest(
1662                        next_keyframe(&audio.gain, ticks, context),
1663                        next_keyframe(&audio.pan, ticks, context),
1664                    )
1665                },
1666                |time| {
1667                    let gain = sample_scalar(&audio.gain, time, context).clamp(0.0, MAX_GAIN);
1668                    let [left, right] =
1669                        pan_gains(sample_scalar(&audio.pan, time, context), channels);
1670                    [gain, left, right]
1671                },
1672            );
1673            let [gains, left, right] = &self.envelope;
1674            for (channel, weights) in [left, right].into_iter().enumerate().take(channels) {
1675                let input = &bus.output[channel][..frames];
1676                let output = &mut self.mix[channel][..frames];
1677                for (((output, sample), gain), weight) in
1678                    output.iter_mut().zip(input).zip(gains).zip(weights)
1679                {
1680                    *output += sample * gain * weight;
1681                }
1682            }
1683        }
1684    }
1685
1686    #[allow(clippy::too_many_arguments)]
1687    fn finish_master(
1688        &mut self,
1689        start_sample: i64,
1690        master_input: i64,
1691        transport: TransportState,
1692        frames: usize,
1693        stages: Stages,
1694        complete: bool,
1695        context: &SampleContext<'_>,
1696    ) {
1697        let channels = self.layout.channels();
1698        let input_ctx = self.ctx(master_input, transport);
1699        let ctx = &self.ctx(start_sample, transport);
1700        match channels {
1701            1 => self.master_chain.process(
1702                &input_ctx,
1703                &[&self.mix[0][..frames]],
1704                &mut [&mut self.output[0][..frames]],
1705            ),
1706            2 => {
1707                let (left, right) = self.output.split_at_mut(1);
1708                self.master_chain.process(
1709                    &input_ctx,
1710                    &[&self.mix[0][..frames], &self.mix[1][..frames]],
1711                    &mut [&mut left[0][..frames], &mut right[0][..frames]],
1712                );
1713            }
1714            _ => {}
1715        }
1716        if let Some(gain) = constant_value(&self.master.gain) {
1717            let gain = gain.clamp(0.0, MAX_GAIN);
1718            for channel in 0..channels {
1719                for sample in &mut self.output[channel][..frames] {
1720                    *sample *= gain;
1721                }
1722            }
1723        } else {
1724            let gain = &self.master.gain;
1725            fill_envelope(
1726                &mut self.envelope[..],
1727                start_sample,
1728                frames,
1729                self.sample_rate,
1730                |ticks| next_keyframe(gain, ticks, context),
1731                |time| [sample_scalar(gain, time, context).clamp(0.0, MAX_GAIN)],
1732            );
1733            for channel in 0..channels {
1734                let envelope = &self.envelope[0][..frames];
1735                for (sample, gain) in self.output[channel][..frames].iter_mut().zip(envelope) {
1736                    *sample *= gain;
1737                }
1738            }
1739        }
1740        if self.normalization_gain.to_bits() != 1.0_f32.to_bits() {
1741            for channel in 0..channels {
1742                for sample in &mut self.output[channel][..frames] {
1743                    *sample *= self.normalization_gain;
1744                }
1745            }
1746        }
1747        // Meter only complete requested blocks, never replayed history or blocks missing a source.
1748        let measured = stages.target.is_none() && complete;
1749        if measured && let Some(meter) = self.meter.as_mut() {
1750            let planes = [&self.output[0][..frames], &self.output[1][..frames]];
1751            // The meter was made for this layout, so the block always fits.
1752            let _ = meter.push(&planes[..channels]);
1753        }
1754        if let Some(limiter) = self
1755            .limiter
1756            .as_mut()
1757            .filter(|_| stages.run(self.limiter_lead))
1758        {
1759            for channel in 0..channels {
1760                self.mix[channel][..frames].copy_from_slice(&self.output[channel][..frames]);
1761            }
1762            match channels {
1763                1 => limiter.process(
1764                    ctx,
1765                    &[&self.mix[0][..frames]],
1766                    &mut [&mut self.output[0][..frames]],
1767                ),
1768                2 => {
1769                    let (left, right) = self.output.split_at_mut(1);
1770                    limiter.process(
1771                        ctx,
1772                        &[&self.mix[0][..frames], &self.mix[1][..frames]],
1773                        &mut [&mut left[0][..frames], &mut right[0][..frames]],
1774                    );
1775                }
1776                _ => {}
1777            }
1778        }
1779        if measured && let Some(meter) = self.output_meter.as_mut() {
1780            let planes = [&self.output[0][..frames], &self.output[1][..frames]];
1781            let _ = meter.push(&planes[..channels]);
1782        }
1783    }
1784}
1785
1786fn track_buses(
1787    project: &alpha2_model::Project,
1788    layout: ChannelLayout,
1789    sample_rate: u32,
1790    max_block: usize,
1791) -> (Vec<TrackBus>, HashMap<TrackId, usize>) {
1792    let mut buses = Vec::new();
1793    let mut bus_of_track = HashMap::new();
1794    // Every track gets a bus, since a clip on a visual track can carry audio.
1795    for track in &project.timeline.tracks {
1796        let mut chain = ProcessorChain::new(layout);
1797        push_effects(&mut chain, &track.audio.effects);
1798        chain.prepare(sample_rate, max_block);
1799        let chain_latency = chain.latency_samples();
1800        let ducker = track.audio.ducking.as_ref().map(|ducking| {
1801            let mut ducker = Ducker::new(
1802                ducking.threshold,
1803                ducking.depth_db,
1804                ducking.attack_ms,
1805                ducking.release_ms,
1806            );
1807            ducker.prepare(sample_rate, max_block);
1808            BusDucker {
1809                ducker,
1810                output: buffers(max_block),
1811            }
1812        });
1813        bus_of_track.insert(track.id.clone(), buses.len());
1814        buses.push(TrackBus {
1815            id: track.id.clone(),
1816            audio: track.audio.clone(),
1817            chain,
1818            ducker,
1819            sidechain: None,
1820            output: buffers(max_block),
1821            live: false,
1822            latency: i64::from(chain_latency),
1823            clips: clip_slots(&track.clips, layout, sample_rate, max_block),
1824            chain_lead: 0,
1825            ducker_lead: 0,
1826            read: false,
1827        });
1828    }
1829    (buses, bus_of_track)
1830}
1831
1832/// One slot per clip. Chains are measured here and built when their clip is mixed.
1833fn clip_slots(
1834    clips: &[alpha2_model::Clip],
1835    layout: ChannelLayout,
1836    sample_rate: u32,
1837    max_block: usize,
1838) -> Vec<ClipSlot> {
1839    clips
1840        .iter()
1841        .map(|clip| ClipSlot {
1842            id: clip.id.clone(),
1843            chain: (!clip.audio.effects.is_empty()).then(|| {
1844                // Built once to measure latency and history, then dropped.
1845                let chain = clip_processors(&clip.audio.effects, layout, sample_rate, max_block);
1846                ClipChain {
1847                    effects: clip.audio.effects.clone(),
1848                    chain: None,
1849                    ran_in: 0,
1850                    latency: i64::from(chain.latency_samples()),
1851                    history: chain.history_samples(),
1852                    next_input: None,
1853                    lead: 0,
1854                }
1855            }),
1856        })
1857        .collect()
1858}
1859
1860fn clip_processors(
1861    effects: &[AudioEffect],
1862    layout: ChannelLayout,
1863    sample_rate: u32,
1864    max_block: usize,
1865) -> ProcessorChain {
1866    let mut chain = ProcessorChain::new(layout);
1867    push_effects(&mut chain, effects);
1868    chain.prepare_nodes(sample_rate, max_block);
1869    chain
1870}
1871
1872/// The longest latency from any clip's input to its bus's output.
1873fn longest_path_latency(buses: &[TrackBus]) -> i64 {
1874    buses
1875        .iter()
1876        .map(|bus| {
1877            bus.latency
1878                + bus
1879                    .clips
1880                    .iter()
1881                    .filter_map(|slot| slot.chain.as_ref())
1882                    .map(|chain| chain.latency)
1883                    .max()
1884                    .unwrap_or(0)
1885        })
1886        .max()
1887        .unwrap_or(0)
1888}
1889
1890/// Gives every bus, ducker, and clip chain its lead, and returns the longest.
1891///
1892/// A stage's lead is its own history plus the lead of the stage consuming its output. A bus that
1893/// feeds both the master sum and other buses' duckers takes the longest of their leads.
1894fn assign_leads(buses: &mut [TrackBus], master_lead: i64, settling: Settling) -> i64 {
1895    let ducker_leads: Vec<Option<i64>> = buses
1896        .iter()
1897        .enumerate()
1898        .map(|(index, bus)| {
1899            let ducking = bus.ducker.as_ref()?;
1900            bus.active_sidechain(index)?;
1901            Some(settling.lead(master_lead, ducking.ducker.history_samples()))
1902        })
1903        .collect();
1904    let mut longest = master_lead;
1905    for index in 0..buses.len() {
1906        let sidechained = buses
1907            .iter()
1908            .enumerate()
1909            .filter(|&(user, bus)| bus.active_sidechain(user) == Some(index))
1910            .filter_map(|(user, _)| ducker_leads[user]);
1911        let settled_from = sidechained
1912            .chain(ducker_leads[index])
1913            .fold(master_lead, i64::max);
1914        let bus = &mut buses[index];
1915        bus.ducker_lead = ducker_leads[index].unwrap_or(0);
1916        bus.chain_lead = settling.lead(settled_from, bus.chain.history_samples());
1917        longest = longest.max(bus.chain_lead);
1918        for clip in bus.clips.iter_mut().filter_map(|slot| slot.chain.as_mut()) {
1919            clip.lead = settling.lead(bus.chain_lead, clip.history);
1920            longest = longest.max(clip.lead);
1921        }
1922    }
1923    longest
1924}
1925
1926/// The lead cap in samples ([`MAX_SETTLING_SECONDS`]).
1927#[derive(Clone, Copy)]
1928struct Settling(i64);
1929
1930impl Settling {
1931    /// The lead of a stage with `history` feeding one with lead `downstream`. Never shorter than
1932    /// `downstream`, otherwise capped.
1933    fn lead(self, downstream: i64, history: u32) -> i64 {
1934        downstream
1935            .saturating_add(i64::from(history))
1936            .min(self.0.max(downstream))
1937    }
1938}
1939
1940/// Which stages a block runs. In a replay before a seek to `target`, a stage runs once its lead
1941/// has begun; otherwise all run.
1942#[derive(Clone, Copy)]
1943struct Stages {
1944    target: Option<i64>,
1945    block_end: i64,
1946    lookahead: i64,
1947}
1948
1949impl Stages {
1950    fn run(self, lead: i64) -> bool {
1951        self.target
1952            .is_none_or(|target| self.block_end > Self::start(target, lead, self.lookahead))
1953    }
1954
1955    /// The output sample from which a stage with `lead` runs in the replay. As in
1956    /// `preroll_start`, history stops at timeline zero but the lookahead reaches before it.
1957    fn start(target: i64, lead: i64, lookahead: i64) -> i64 {
1958        (target - lead).max(0).saturating_sub(lookahead)
1959    }
1960}
1961
1962/// Every distinct stage lead, longest first.
1963fn stage_leads(buses: &[TrackBus], master_lead: i64, limiter_lead: i64) -> Vec<i64> {
1964    let mut leads = vec![master_lead, limiter_lead];
1965    for (index, bus) in buses.iter().enumerate() {
1966        leads.push(bus.chain_lead);
1967        if bus.active_sidechain(index).is_some() {
1968            leads.push(bus.ducker_lead);
1969        }
1970        leads.extend(
1971            bus.clips
1972                .iter()
1973                .filter_map(|slot| slot.chain.as_ref())
1974                .map(|chain| chain.lead),
1975        );
1976    }
1977    leads.sort_unstable_by(|a, b| b.cmp(a));
1978    leads.dedup();
1979    leads
1980}
1981
1982/// Marks the buses whose clips the mix reads: every heard bus and every unmuted bus keying the
1983/// ducker of a heard one. Solo changes what is heard, not how a ducked track sounds, so a soloed
1984/// track still reads its sidechain.
1985fn read_buses(buses: &mut [TrackBus], any_solo: bool) {
1986    let heard: Vec<bool> = buses
1987        .iter()
1988        .map(|bus| !bus.audio.is_silenced(any_solo))
1989        .collect();
1990    let keys: Vec<Option<usize>> = buses
1991        .iter()
1992        .enumerate()
1993        .map(|(index, bus)| heard[index].then(|| bus.active_sidechain(index)).flatten())
1994        .collect();
1995    for (index, bus) in buses.iter_mut().enumerate() {
1996        bus.read = heard[index] || (!bus.audio.muted && keys.contains(&Some(index)));
1997    }
1998}
1999
2000fn resolve_sidechains(buses: &mut [TrackBus], bus_of_track: &HashMap<TrackId, usize>) {
2001    for bus in buses {
2002        bus.sidechain = bus
2003            .audio
2004            .ducking
2005            .as_ref()
2006            .and_then(|ducking| bus_of_track.get(&ducking.sidechain_track).copied());
2007    }
2008}
2009
2010fn buffers(max_block: usize) -> [Vec<f32>; 2] {
2011    [vec![0.0; max_block], vec![0.0; max_block]]
2012}
2013
2014fn push_effects(chain: &mut ProcessorChain, effects: &[AudioEffect]) {
2015    for effect in effects {
2016        match effect {
2017            AudioEffect::Eq { bands } => {
2018                for band in bands {
2019                    push_effect(
2020                        chain,
2021                        Biquad::new(
2022                            match band.kind {
2023                                EqBandKind::Peaking => BiquadKind::Peaking,
2024                                EqBandKind::LowPass => BiquadKind::LowPass,
2025                                EqBandKind::HighPass => BiquadKind::HighPass,
2026                            },
2027                            band.frequency_hz,
2028                            band.q,
2029                            band.gain_db,
2030                        ),
2031                    );
2032                }
2033            }
2034            AudioEffect::Compressor {
2035                threshold_db,
2036                ratio,
2037                attack_ms,
2038                release_ms,
2039                lookahead_ms,
2040            } => push_effect(
2041                chain,
2042                Compressor::new(
2043                    *threshold_db,
2044                    *ratio,
2045                    *attack_ms,
2046                    *release_ms,
2047                    *lookahead_ms,
2048                ),
2049            ),
2050            AudioEffect::Reverb {
2051                room_size,
2052                damping,
2053                mix,
2054            } => push_effect(chain, SchroederReverb::new(*room_size, *damping, *mix)),
2055        }
2056    }
2057}
2058
2059fn push_effect(chain: &mut ProcessorChain, effect: impl Processor + 'static) {
2060    chain
2061        .push(effect)
2062        .expect("a model effect reads one input per output");
2063}
2064
2065fn ticks_at(sample: i64, sample_rate: u32) -> i64 {
2066    checked_ticks_at(sample, sample_rate).unwrap_or(i64::MAX)
2067}
2068
2069/// The tick position of a sample, or `None` when it does not fit in ticks.
2070fn checked_ticks_at(sample: i64, sample_rate: u32) -> Option<i64> {
2071    let rate = i128::from(sample_rate.max(1));
2072    i64::try_from((i128::from(sample) * i128::from(TICKS_PER_SECOND)).div_euclid(rate)).ok()
2073}
2074
2075/// A source block and where its samples go in `clip_a`.
2076struct SourceRead<'a> {
2077    planes: &'a [Vec<f32>],
2078    downmix: &'a Downmix,
2079    /// The source sample the planes start at.
2080    start: i64,
2081    offset: usize,
2082    count: usize,
2083}
2084
2085/// How one block reads one clip: see [`AudioRenderer::clip_read`].
2086struct ClipRead {
2087    bus: usize,
2088    bus_input: i64,
2089    slot: Option<(usize, usize)>,
2090    /// The project sample of the clip's first read sample.
2091    first: i64,
2092    window: ClipWindow,
2093}
2094
2095/// Where a clip lands in one block of its chain's input.
2096#[derive(Clone, Copy)]
2097struct ClipWindow {
2098    /// First block sample the clip covers.
2099    offset: usize,
2100    /// Samples the chain runs for, including the flush.
2101    count: usize,
2102    /// Of those, samples read from the source; the rest are silence.
2103    content: usize,
2104}
2105
2106/// The first tick at or after a sample, or `None` when it does not fit.
2107fn ticks_at_or_after(sample: i64, sample_rate: u32) -> Option<i64> {
2108    let rate = i128::from(sample_rate.max(1));
2109    let numerator = i128::from(sample) * i128::from(TICKS_PER_SECOND);
2110    i64::try_from(numerator.div_euclid(rate) + i128::from(numerator.rem_euclid(rate) != 0)).ok()
2111}
2112
2113/// How `clip` folds `source`'s planes into `layout`: its selected channels, or every plane by
2114/// speaker. The engine downmixes so the fold is the same on every platform. `None` when the block
2115/// is malformed or lacks a selected channel.
2116pub(crate) fn clip_downmix(
2117    clip: &ActiveAudioClip,
2118    source: &AudioBlock,
2119    layout: ChannelLayout,
2120) -> Option<Downmix> {
2121    if source.speakers.channels() != source.channels.len() {
2122        return None;
2123    }
2124    match clip.audio.channels.as_deref() {
2125        Some(selection) => Downmix::selected(selection, source.channels.len(), layout),
2126        None => Downmix::new(source.speakers.speakers(), layout),
2127    }
2128}
2129
2130/// Adds `source_range` to `needs`, merged with every need of that source stream it overlaps or
2131/// touches.
2132fn merge_need(
2133    needs: &mut Vec<AudioNeed>,
2134    source_id: &SourceId,
2135    stream: Option<u32>,
2136    mut source_range: TimeRange,
2137) {
2138    // A new range can bridge two existing needs, so keep absorbing until none touch.
2139    while let Some(index) = needs.iter().position(|need| {
2140        need.source_id == *source_id
2141            && need.stream == stream
2142            && need.source_range.start() <= source_range.end()
2143            && source_range.start() <= need.source_range.end()
2144    }) {
2145        let existing = needs.remove(index).source_range;
2146        let merged_start = existing.start().min(source_range.start());
2147        let merged_end = existing.end().max(source_range.end());
2148        if let Ok(merged) = TimeRange::new(merged_start, merged_end) {
2149            source_range = merged;
2150        }
2151    }
2152    needs.push(AudioNeed {
2153        source_id: source_id.clone(),
2154        stream,
2155        source_range,
2156    });
2157}
2158
2159/// Calls `request` with each source window `[from, to)` that [`AudioRenderer::fill_clip`] would
2160/// read for the same arguments.
2161fn source_requests(
2162    stretch: &Stretch,
2163    clip: &ActiveAudioClip,
2164    first_sample: i64,
2165    count: usize,
2166    rate: u32,
2167    mut request: impl FnMut(i64, i64),
2168) {
2169    if count == 0 {
2170        return;
2171    }
2172    match clip.time_map {
2173        TimeMap::Freeze { .. } => {}
2174        TimeMap::Forward | TimeMap::Reverse if stretches(clip) => {
2175            if let Some((from, to)) = stretched_request(stretch, clip, first_sample, count, rate) {
2176                request(from, to);
2177            }
2178        }
2179        TimeMap::Forward | TimeMap::Reverse => {
2180            let reversed = clip.time_map == TimeMap::Reverse;
2181            if let Some((from, to)) = SourceMap::stretched(clip, reversed, rate)
2182                .and_then(|map| map.request(first_sample, count))
2183            {
2184                request(from, to);
2185            }
2186        }
2187        TimeMap::Loop { mode } => {
2188            loop_pieces(clip, mode, first_sample, count, rate, |piece| {
2189                if let Some((from, to)) = piece.map.request(piece.sample, piece.length) {
2190                    request(from, to);
2191                }
2192            });
2193        }
2194    }
2195}
2196
2197/// One pass's share of a looping clip's read.
2198struct LoopPiece {
2199    /// The project sample the piece starts at; `index` is its offset into the read.
2200    sample: i64,
2201    index: usize,
2202    length: usize,
2203    /// The pass number; `pass_start` and `pass_end` are in timeline ticks.
2204    pass: i64,
2205    pass_start: i64,
2206    pass_end: i64,
2207    /// The first project sample of the next pass.
2208    piece_end: i64,
2209    map: SourceMap,
2210}
2211
2212/// Cuts a looping clip's read at its wraps and calls `piece` for each pass. Returns false if the
2213/// clip cannot be mapped.
2214fn loop_pieces(
2215    clip: &ActiveAudioClip,
2216    mode: LoopMode,
2217    first_sample: i64,
2218    count: usize,
2219    rate: u32,
2220    mut piece: impl FnMut(LoopPiece),
2221) -> bool {
2222    let Some(period) = clip.source_range.duration().map(MediaTime::ticks) else {
2223        return false;
2224    };
2225    if period <= 0 {
2226        return false;
2227    }
2228    let start = clip.timeline_range.start().ticks();
2229    let mut index = 0;
2230    while index < count {
2231        let sample = first_sample + i64::try_from(index).unwrap_or(i64::MAX);
2232        let pass = (ticks_at(sample, rate) - start).div_euclid(period);
2233        let Some(pass_start) = pass
2234            .checked_mul(period)
2235            .and_then(|ticks| ticks.checked_add(start))
2236        else {
2237            return false;
2238        };
2239        let pass_end = pass_start.saturating_add(period);
2240        let piece_end = sample_at_or_after(pass_end, rate);
2241        let length = usize::try_from(piece_end.saturating_sub(sample))
2242            .unwrap_or(usize::MAX)
2243            .clamp(1, count - index);
2244        let reversed = mode == LoopMode::PingPong && pass.rem_euclid(2) == 1;
2245        let Some(map) = SourceMap::pass(clip, pass_start, reversed, rate) else {
2246            return false;
2247        };
2248        piece(LoopPiece {
2249            sample,
2250            index,
2251            length,
2252            pass,
2253            pass_start,
2254            pass_end,
2255            piece_end,
2256            map,
2257        });
2258        index += length;
2259    }
2260    true
2261}
2262
2263fn sample_at_or_after(ticks: i64, sample_rate: u32) -> i64 {
2264    let rate = i128::from(sample_rate.max(1));
2265    let numerator = i128::from(ticks) * rate;
2266    let denominator = i128::from(TICKS_PER_SECOND);
2267    let value =
2268        numerator.div_euclid(denominator) + i128::from(numerator.rem_euclid(denominator) != 0);
2269    i64::try_from(value).unwrap_or(i64::MAX)
2270}
2271
2272/// One project channel's sample at source sample `index`, folded by `mix`. Terms are summed in
2273/// plane order so the result is the same on every platform.
2274fn mixed_sample(mix: &ChannelMix, planes: &[Vec<f32>], index: i64) -> f32 {
2275    if let Some(plane) = mix.unity() {
2276        return copied(&planes[plane], index);
2277    }
2278    let mut sum = 0.0;
2279    for &(plane, weight) in mix.terms() {
2280        sum += weight * copied(&planes[plane], index);
2281    }
2282    sum
2283}
2284
2285/// Like [`mixed_sample`], filtering source samples `first..` by `weights`.
2286fn filtered_sample(mix: &ChannelMix, planes: &[Vec<f32>], first: i64, weights: &[f64]) -> f32 {
2287    if let Some(plane) = mix.unity() {
2288        return filtered(&planes[plane], first, weights);
2289    }
2290    let mut sum = 0.0;
2291    for &(plane, weight) in mix.terms() {
2292        sum += weight * filtered(&planes[plane], first, weights);
2293    }
2294    sum
2295}
2296
2297/// Source sample `index` of `plane`. Samples outside the plane or non-finite are silence; reads
2298/// happen only where the block covers the request, so this matches explicit zeros.
2299fn copied(plane: &[f32], index: i64) -> f32 {
2300    let value = usize::try_from(index)
2301        .ok()
2302        .and_then(|index| plane.get(index).copied())
2303        .unwrap_or(0.0);
2304    if value.is_finite() { value } else { 0.0 }
2305}
2306
2307/// The weighted sum of `plane[first..first + weights.len()]`, treating samples as [`copied`] does.
2308fn filtered(plane: &[f32], first: i64, weights: &[f64]) -> f32 {
2309    let mut sum = weighed(plane, first, weights, false);
2310    if !sum.is_finite() {
2311        sum = weighed(plane, first, weights, true);
2312    }
2313    #[allow(clippy::cast_possible_truncation)]
2314    let value = sum as f32;
2315    if value.is_finite() { value } else { 0.0 }
2316}
2317
2318/// The sum behind [`filtered`]. Four interleaved running sums added pairwise give a fixed order
2319/// (identical on every platform) without one long dependency chain.
2320fn weighed(plane: &[f32], first: i64, weights: &[f64], finite_only: bool) -> f64 {
2321    let inside = usize::try_from(first).ok().filter(|&from| {
2322        from.checked_add(weights.len())
2323            .is_some_and(|end| end <= plane.len())
2324    });
2325    let mut sums = [0.0_f64; 4];
2326    match inside {
2327        Some(from) if !finite_only => {
2328            let (weight_quads, weight_rest) = weights.as_chunks::<4>();
2329            let (sample_quads, sample_rest) = plane[from..from + weights.len()].as_chunks::<4>();
2330            for (weight, value) in weight_quads.iter().zip(sample_quads) {
2331                for lane in 0..4 {
2332                    sums[lane] += weight[lane] * f64::from(value[lane]);
2333                }
2334            }
2335            for (lane, (weight, value)) in weight_rest.iter().zip(sample_rest).enumerate() {
2336                sums[lane] += weight * f64::from(*value);
2337            }
2338        }
2339        _ => {
2340            for (index, (at, weight)) in (first..).zip(weights).enumerate() {
2341                let value = usize::try_from(at)
2342                    .ok()
2343                    .and_then(|at| plane.get(at).copied())
2344                    .unwrap_or(0.0);
2345                if value.is_finite() {
2346                    sums[index % 4] += weight * f64::from(value);
2347                }
2348            }
2349        }
2350    }
2351    (sums[0] + sums[1]) + (sums[2] + sums[3])
2352}
2353
2354/// Where each project sample of a clip reads its source, in source samples.
2355///
2356/// `p(n) = (a + n * b) / d` with integer terms, so positions are exact and independent of the
2357/// tick grid.
2358struct SourceMap {
2359    a: i128,
2360    b: i128,
2361    d: i128,
2362}
2363
2364impl SourceMap {
2365    /// A forward or reverse clip's timeline range stretched over its source range. Reversed reads
2366    /// the forward positions in the opposite order.
2367    fn stretched(clip: &ActiveAudioClip, reversed: bool, rate: u32) -> Option<Self> {
2368        let timeline = clip.timeline_range;
2369        let forward = Self::line(
2370            i128::from(timeline.start().ticks()),
2371            i128::from(clip.source_range.start().ticks()),
2372            i128::from(timeline.duration()?.ticks()),
2373            i128::from(clip.source_range.duration()?.ticks()),
2374            rate,
2375        )?;
2376        if !reversed {
2377            return Some(forward);
2378        }
2379        forward.mirrored(
2380            sample_at_or_after(timeline.start().ticks(), rate),
2381            sample_at_or_after(timeline.end().ticks(), rate),
2382        )
2383    }
2384
2385    /// One loop pass starting at timeline tick `pass_start`, at source speed.
2386    fn pass(clip: &ActiveAudioClip, pass_start: i64, reversed: bool, rate: u32) -> Option<Self> {
2387        let period = clip.source_range.duration()?.ticks();
2388        let forward = Self::line(
2389            i128::from(pass_start),
2390            i128::from(clip.source_range.start().ticks()),
2391            i128::from(period),
2392            i128::from(period),
2393            rate,
2394        )?;
2395        if !reversed {
2396            return Some(forward);
2397        }
2398        forward.mirrored(
2399            sample_at_or_after(pass_start, rate),
2400            sample_at_or_after(pass_start.checked_add(period)?, rate),
2401        )
2402    }
2403
2404    /// This map mirrored over `first..last`: sample `n` reads what `first + last - 1 - n` reads.
2405    fn mirrored(&self, first: i64, last: i64) -> Option<Self> {
2406        let pivot = i128::from(first)
2407            .checked_add(i128::from(last))?
2408            .checked_sub(1)?;
2409        Some(Self {
2410            a: self.a.checked_add(pivot.checked_mul(self.b)?)?,
2411            b: self.b.checked_neg()?,
2412            d: self.d,
2413        })
2414    }
2415
2416    /// The line through source tick `s0` at timeline tick `t0`, advancing
2417    /// `source` ticks per `timeline` ticks.
2418    fn line(t0: i128, s0: i128, timeline: i128, source: i128, rate: u32) -> Option<Self> {
2419        if timeline <= 0 || source <= 0 {
2420            return None;
2421        }
2422        let divisor = gcd(timeline, source);
2423        let (timeline, source) = (timeline / divisor, source / divisor);
2424        let rate = i128::from(rate);
2425        let ticks = i128::from(TICKS_PER_SECOND);
2426        // p(n) = (s0 + (n * TPS / rate - t0) * source / timeline) * rate / TPS
2427        let a = rate.checked_mul(
2428            s0.checked_mul(timeline)?
2429                .checked_sub(t0.checked_mul(source)?)?,
2430        )?;
2431        let b = ticks.checked_mul(source)?;
2432        let d = ticks.checked_mul(timeline)?;
2433        Some(Self { a, b, d })
2434    }
2435
2436    /// The source sample at or before `sample`, and the fraction toward the next.
2437    fn position(&self, sample: i64) -> Option<(i64, f64)> {
2438        let numerator = self
2439            .a
2440            .checked_add(i128::from(sample).checked_mul(self.b)?)?;
2441        let whole = i64::try_from(numerator.div_euclid(self.d)).ok()?;
2442        let remainder = numerator.rem_euclid(self.d);
2443        #[allow(clippy::cast_precision_loss)]
2444        let fraction = remainder as f64 / self.d as f64;
2445        Some((whole, fraction))
2446    }
2447
2448    /// The interpolation filter, or `None` at unity speed with every position on a source sample.
2449    fn interpolator(&self) -> Option<Interpolator> {
2450        if self.b.unsigned_abs() == self.d.unsigned_abs() && self.a.rem_euclid(self.d) == 0 {
2451            return None;
2452        }
2453        #[allow(clippy::cast_precision_loss)]
2454        let speed = self.b.unsigned_abs() as f64 / self.d.unsigned_abs() as f64;
2455        Some(Interpolator::new(speed))
2456    }
2457
2458    /// The source window `[from, to)` that reading `count` samples from `first_sample` touches,
2459    /// including [`Interpolator`] taps. The map is linear, so the endpoints bound it.
2460    fn request(&self, first_sample: i64, count: usize) -> Option<(i64, i64)> {
2461        let last_sample = first_sample.checked_add(i64::try_from(count).ok()?.checked_sub(1)?)?;
2462        let (first, _) = self.position(first_sample)?;
2463        let (last, _) = self.position(last_sample)?;
2464        let (low, high) = (first.min(last), first.max(last));
2465        let Some(interpolator) = self.interpolator() else {
2466            return Some((low.max(0), high.saturating_add(1)));
2467        };
2468        let half = interpolator.half_taps();
2469        Some((
2470            low.saturating_sub(half - 1).max(0),
2471            high.saturating_add(half + 1),
2472        ))
2473    }
2474
2475    /// A cursor stepping one project sample at a time from `sample`, or `None` if it would not fit.
2476    fn cursor(&self, sample: i64) -> Option<RationalCursor> {
2477        let numerator = self
2478            .a
2479            .checked_add(i128::from(sample).checked_mul(self.b)?)?;
2480        RationalCursor::new(numerator, self.b, self.d)
2481    }
2482
2483    /// What [`Self::position`] returns at the cursor's sample, bit for bit.
2484    fn fraction(&self, cursor: &RationalCursor) -> (i64, f64) {
2485        // The u64 remainder converts to f64 exactly as the i128 one would.
2486        #[allow(clippy::cast_precision_loss)]
2487        let fraction = cursor.remainder as f64 / self.d as f64;
2488        (cursor.whole, fraction)
2489    }
2490}
2491
2492/// Walks `(numerator + n * step) / divisor` over consecutive `n` with additions instead of 128-bit
2493/// divisions. The caller bounds the walk so every floor fits in `i64`.
2494#[derive(Clone, Copy, Debug)]
2495struct RationalCursor {
2496    whole: i64,
2497    remainder: u64,
2498    step_whole: i64,
2499    step_remainder: u64,
2500    divisor: u64,
2501}
2502
2503impl RationalCursor {
2504    fn new(numerator: i128, step: i128, divisor: i128) -> Option<Self> {
2505        // A divisor below 2^63 keeps `remainder + step_remainder` in a u64.
2506        if divisor <= 0 || divisor > i128::from(i64::MAX) {
2507            return None;
2508        }
2509        Some(Self {
2510            whole: i64::try_from(numerator.div_euclid(divisor)).ok()?,
2511            remainder: u64::try_from(numerator.rem_euclid(divisor)).ok()?,
2512            step_whole: i64::try_from(step.div_euclid(divisor)).ok()?,
2513            step_remainder: u64::try_from(step.rem_euclid(divisor)).ok()?,
2514            divisor: u64::try_from(divisor).ok()?,
2515        })
2516    }
2517
2518    /// Steps until the remainder repeats.
2519    const fn period(&self) -> u64 {
2520        let (mut a, mut b) = (self.step_remainder, self.divisor);
2521        while b != 0 {
2522            (a, b) = (b, a % b);
2523        }
2524        self.divisor / a
2525    }
2526
2527    fn advance(&mut self) {
2528        self.whole = self.whole.wrapping_add(self.step_whole);
2529        self.remainder += self.step_remainder;
2530        if self.remainder >= self.divisor {
2531            self.remainder -= self.divisor;
2532            self.whole = self.whole.wrapping_add(1);
2533        }
2534    }
2535}
2536
2537/// [`ticks_at`] for consecutive samples, without a division per sample.
2538fn tick_cursor(sample: i64, sample_rate: u32) -> RationalCursor {
2539    let ticks = i128::from(TICKS_PER_SECOND);
2540    RationalCursor::new(
2541        i128::from(sample) * ticks,
2542        ticks,
2543        i128::from(sample_rate.max(1)),
2544    )
2545    // Unreachable for blocks `render` accepts; saturates like `ticks_at`.
2546    .unwrap_or(RationalCursor {
2547        whole: i64::MAX,
2548        remainder: 0,
2549        step_whole: 0,
2550        step_remainder: 0,
2551        divisor: 1,
2552    })
2553}
2554
2555fn gcd(mut a: i128, mut b: i128) -> i128 {
2556    while b != 0 {
2557        (a, b) = (b, a % b);
2558    }
2559    a.abs().max(1)
2560}
2561
2562/// Project samples between the points where automation is evaluated.
2563///
2564/// About 0.7 ms at 48 kHz: finer than any authored move, coarse enough that keyframe evaluation
2565/// (a cubic Bezier solve) stays cheap.
2566const ENVELOPE_INTERVAL: i64 = 32;
2567
2568/// Writes the `N` multipliers from `at` for `count` samples from `first` into `envelope`.
2569///
2570/// `at` is evaluated at multiples of [`ENVELOPE_INTERVAL`] and interpolated linearly between them.
2571/// An interval containing a knot from `next_knot` (keyframe or fade edge) is evaluated per sample
2572/// instead. Values depend only on the project sample, so block size and seeks never change them.
2573fn fill_envelope<const N: usize>(
2574    envelope: &mut [Vec<f32>],
2575    first: i64,
2576    count: usize,
2577    sample_rate: u32,
2578    next_knot: impl Fn(i64) -> Option<i64>,
2579    at: impl Fn(MediaTime) -> [f32; N],
2580) {
2581    #[allow(clippy::cast_precision_loss)]
2582    let fraction = 1.0 / ENVELOPE_INTERVAL as f32;
2583    // Outer `None` means not yet looked up; inner `None` means no further knot.
2584    let mut knot: Option<Option<i64>> = None;
2585    let mut point: Option<(i64, [f32; N])> = None;
2586    let mut written = 0;
2587    while written < count {
2588        let sample = first.saturating_add(i64::try_from(written).unwrap_or(i64::MAX));
2589        let start = sample.div_euclid(ENVELOPE_INTERVAL) * ENVELOPE_INTERVAL;
2590        let stop = start.saturating_add(ENVELOPE_INTERVAL);
2591        let run = usize::try_from(stop - sample)
2592            .unwrap_or(count)
2593            .clamp(1, count - written);
2594        let (from, to) = (ticks_at(start, sample_rate), ticks_at(stop, sample_rate));
2595        let next = match knot {
2596            Some(next) if next.is_none_or(|next| next > from) => next,
2597            _ => next_knot(from),
2598        };
2599        knot = Some(next);
2600        let outputs = written..written + run;
2601        if next.is_some_and(|next| next <= to) {
2602            let mut ticks = tick_cursor(sample, sample_rate);
2603            for index in outputs {
2604                let value = at(MediaTime::from_ticks(ticks.whole));
2605                ticks.advance();
2606                for (plane, value) in envelope.iter_mut().zip(value) {
2607                    plane[index] = value;
2608                }
2609            }
2610            #[cfg(test)]
2611            ENVELOPE_POINTS.set(ENVELOPE_POINTS.get() + run);
2612        } else {
2613            let left = match point {
2614                Some((at_sample, value)) if at_sample == start => value,
2615                _ => {
2616                    #[cfg(test)]
2617                    ENVELOPE_POINTS.set(ENVELOPE_POINTS.get() + 1);
2618                    at(MediaTime::from_ticks(from))
2619                }
2620            };
2621            let right = at(MediaTime::from_ticks(to));
2622            #[cfg(test)]
2623            ENVELOPE_POINTS.set(ENVELOPE_POINTS.get() + 1);
2624            point = Some((stop, right));
2625            #[allow(clippy::cast_precision_loss)]
2626            let along = (sample - start) as f32;
2627            for (plane, (left, right)) in envelope.iter_mut().zip(left.into_iter().zip(right)) {
2628                let slope = right - left;
2629                for (position, output) in plane[outputs.clone()].iter_mut().enumerate() {
2630                    #[allow(clippy::cast_precision_loss)]
2631                    let position = along + position as f32;
2632                    *output = left + slope * (position * fraction);
2633                }
2634            }
2635        }
2636        written += run;
2637    }
2638}
2639
2640#[cfg(test)]
2641thread_local! {
2642    /// How many times [`fill_envelope`] evaluated an envelope on this thread.
2643    static ENVELOPE_POINTS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2644    /// Bus channels cleared and summed on this thread.
2645    static BUS_PLANES_CLEARED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2646    static BUS_PLANES_SUMMED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2647}
2648
2649/// The earlier of two optional ticks, where `None` means never.
2650fn earliest(left: Option<i64>, right: Option<i64>) -> Option<i64> {
2651    match (left, right) {
2652        (Some(left), Some(right)) => Some(left.min(right)),
2653        (left, right) => left.or(right),
2654    }
2655}
2656
2657/// The first keyframe of `animation` after `ticks`; none for a constant or single keyframe.
2658fn next_keyframe(
2659    animation: &Animated<f32>,
2660    ticks: i64,
2661    context: &SampleContext<'_>,
2662) -> Option<i64> {
2663    match animation {
2664        Animated::Data(binding) => {
2665            alpha2_eval::next_data_change(binding, MediaTime(ticks), context).map(MediaTime::ticks)
2666        }
2667        Animated::Keyframes { keyframes } if keyframes.len() > 1 => {
2668            let next = keyframes.partition_point(|keyframe| keyframe.time.ticks() <= ticks);
2669            keyframes.get(next).map(|keyframe| keyframe.time.ticks())
2670        }
2671        _ => None,
2672    }
2673}
2674
2675/// The first fade start or end after `ticks`.
2676fn next_fade_edge(clip: &ActiveAudioClip, ticks: i64) -> Option<i64> {
2677    let start = clip.timeline_range.start().ticks();
2678    let end = clip.timeline_range.end().ticks();
2679    let fade_in = clip.audio.fade_in.ticks();
2680    let fade_out = clip.audio.fade_out.ticks();
2681    let mut next = None;
2682    if fade_in > 0 {
2683        for edge in [start, start.saturating_add(fade_in)] {
2684            if edge > ticks {
2685                next = earliest(next, Some(edge));
2686            }
2687        }
2688    }
2689    if fade_out > 0 {
2690        for edge in [end.saturating_sub(fade_out), end] {
2691            if edge > ticks {
2692                next = earliest(next, Some(edge));
2693            }
2694        }
2695    }
2696    next
2697}
2698
2699/// The value of a scalar that does not change over time, including a single keyframe.
2700fn constant_value(animation: &Animated<f32>) -> Option<f32> {
2701    match animation {
2702        Animated::Constant { value } => Some(*value),
2703        Animated::Data(_) => None,
2704        Animated::Keyframes { keyframes } => match keyframes.as_slice() {
2705            [only] => Some(only.value),
2706            _ => None,
2707        },
2708    }
2709}
2710
2711/// Whether either fade changes the gain in the `count` samples from `first`. Where it does not,
2712/// [`fade_gain`] is exactly one.
2713fn fades_reach(clip: &ActiveAudioClip, first: i64, count: usize, sample_rate: u32) -> bool {
2714    let fade_in = clip.audio.fade_in.ticks();
2715    let fade_out = clip.audio.fade_out.ticks();
2716    if fade_in <= 0 && fade_out <= 0 {
2717        return false;
2718    }
2719    let last = first.saturating_add(i64::try_from(count).unwrap_or(i64::MAX).saturating_sub(1));
2720    // Saturate: pre-roll can read before the clip, and clips may end near the largest tick.
2721    let elapsed = ticks_at(first, sample_rate).saturating_sub(clip.timeline_range.start().ticks());
2722    let remaining = clip
2723        .timeline_range
2724        .end()
2725        .ticks()
2726        .saturating_sub(ticks_at(last, sample_rate));
2727    (fade_in > 0 && elapsed < fade_in) || (fade_out > 0 && remaining < fade_out)
2728}
2729
2730/// The clip's fade multiplier at `time`, using its [`alpha2_model::FadeShape`].
2731fn fade_gain(clip: &ActiveAudioClip, time: MediaTime) -> f32 {
2732    let start = clip.timeline_range.start().ticks();
2733    let end = clip.timeline_range.end().ticks();
2734    let shape = clip.audio.fade_shape;
2735    let mut gain = 1.0_f32;
2736    let fade_in = clip.audio.fade_in.ticks();
2737    if fade_in > 0 {
2738        let elapsed = time.ticks().saturating_sub(start);
2739        if elapsed < fade_in {
2740            gain *= shape.amplitude(ratio(elapsed, fade_in));
2741        }
2742    }
2743    let fade_out = clip.audio.fade_out.ticks();
2744    if fade_out > 0 {
2745        let remaining = end.saturating_sub(time.ticks());
2746        if remaining < fade_out {
2747            gain *= shape.amplitude(ratio(remaining, fade_out));
2748        }
2749    }
2750    gain.clamp(0.0, 1.0)
2751}
2752
2753#[allow(clippy::cast_precision_loss)]
2754fn ratio(value: i64, span: i64) -> f32 {
2755    if span <= 0 {
2756        return 1.0;
2757    }
2758    (value.max(0) as f32 / span as f32).clamp(0.0, 1.0)
2759}
2760
2761/// Constant-power pan weights normalized to unity at the centre, so clip and track pans compose
2762/// without attenuating a default project. A hard pan raises the remaining channel by 3 dB. Mono
2763/// output ignores pan.
2764fn pan_gains(pan: f32, channels: usize) -> [f32; 2] {
2765    if channels < 2 {
2766        return [1.0, 1.0];
2767    }
2768    // Computed in f64 so the centre rounds to exactly 1.0 in f32 (f32 math gives 0.99999994).
2769    let angle = (f64::from(pan.clamp(-1.0, 1.0)) + 1.0) * core::f64::consts::FRAC_PI_4;
2770    let normalize = core::f64::consts::SQRT_2;
2771    #[allow(clippy::cast_possible_truncation)]
2772    let weights = [
2773        (libm::cos(angle) * normalize) as f32,
2774        (libm::sin(angle) * normalize) as f32,
2775    ];
2776    weights
2777}
2778
2779#[cfg(test)]
2780mod tests;