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