alpha2-engine 0.10.0

Player and exporter facade for alpha2.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
//! Reading a clip that keeps or shifts its pitch through [`StretchReader`], not the plain read.
//!
//! Read positions are source samples, negated for a reversed clip, so a grain always reads
//! forward. Each grain's centre sits where the clip's [`SourceMap`] puts that project sample, so
//! speed and picture alignment match the plain read up to the search tolerance.

use std::collections::HashMap;

use alpha2_audio::{Interpolator, Stretch, StretchReader, StretchSignal};
use alpha2_eval::{ActiveAudioClip, TimeCurve};
use alpha2_media::{AudioBlock, AudioBlockProvider, SourceId};
use alpha2_model::{AudioRead, ClipId, TimeMap};
use alpha2_time::{TICKS_PER_SECOND, TimeRange};

use super::{AudioRenderer, Fill, SourceMap, filtered, mixed_sample, sample_at_or_after};
use crate::downmix::Downmix;

pub(super) fn read_of(clip: &ActiveAudioClip) -> AudioRead {
    clip.audio
        .read(clip.time_map, clip.timeline_range, clip.source_range)
}

pub(super) fn stretches(clip: &ActiveAudioClip) -> bool {
    read_of(clip).stretches()
}

fn floored(value: f64) -> Option<i64> {
    const I64_RANGE: f64 = 9.0e18;
    #[expect(
        clippy::cast_possible_truncation,
        reason = "the value is whole and inside the range of an i64"
    )]
    (value.abs() < I64_RANGE).then(|| libm::floor(value) as i64)
}

#[expect(
    clippy::cast_precision_loss,
    reason = "sample counts stay far below 2^53"
)]
const fn real(sample: i64) -> f64 {
    sample as f64
}

struct ReadLine {
    whole: i64,
    fraction: f64,
    step: f64,
}

impl ReadLine {
    fn floor_at(&self, stretched_sample: i64) -> Option<i64> {
        self.whole
            .checked_add(floored(self.fraction + real(stretched_sample) * self.step)?)
    }
}

struct Tap {
    at: i64,
    fraction: f64,
    interpolator: Interpolator,
}

impl Tap {
    fn first(&self) -> Option<i64> {
        self.at.checked_sub(self.interpolator.half_taps() - 1)
    }

    fn end(&self) -> Option<i64> {
        self.at.checked_add(self.interpolator.half_taps() + 1)
    }
}

enum Resampling {
    Constant {
        pitch: f64,
        interpolator: Interpolator,
    },
    Along(Vec<Tap>),
}

impl Resampling {
    fn new(pitch: f64) -> Option<Self> {
        (pitch.is_finite() && pitch > 0.0).then(|| Self::Constant {
            pitch,
            interpolator: Interpolator::new(pitch),
        })
    }

    fn along(path: &CurvePath, ratio: f64, clip_first: i64, clip_end: i64) -> Option<Self> {
        if !(ratio.is_finite() && ratio > 0.0) {
            return None;
        }
        let start = path.ends[0].0;
        (clip_first..clip_end)
            .map(|clip_sample| {
                let (position, speed) = path.inside(real(clip_sample));
                let stretched = ratio * (position - start);
                Some(Tap {
                    at: floored(stretched)?,
                    fraction: stretched - libm::floor(stretched),
                    interpolator: Interpolator::new(ratio * speed.abs()),
                })
            })
            .collect::<Option<Vec<Tap>>>()
            .map(Self::Along)
    }

    fn tap(&self, clip_sample: i64) -> Option<Tap> {
        let Self::Constant {
            pitch,
            interpolator,
        } = self
        else {
            return None;
        };
        let position = real(clip_sample) * pitch;
        Some(Tap {
            at: floored(position)?,
            fraction: position - libm::floor(position),
            interpolator: *interpolator,
        })
    }

    fn resample(
        &self,
        stretched: &[Vec<f32>],
        stretched_first: i64,
        clip_first: i64,
        outputs: &mut [&mut [f32]],
        weights: &mut Vec<f64>,
    ) {
        let count = outputs.first().map_or(0, |output| output.len());
        for (index, clip_sample) in (clip_first..).take(count).enumerate() {
            let constant = self.tap(clip_sample);
            let tap = match self {
                Self::Constant { .. } => constant.as_ref(),
                Self::Along(taps) => taps.get(index),
            };
            let Some(tap) = tap else {
                continue;
            };
            let Some(first_tap) = tap.first().and_then(|tap| tap.checked_sub(stretched_first))
            else {
                continue;
            };
            tap.interpolator.weights(tap.fraction, weights);
            for (output, plane) in outputs.iter_mut().zip(stretched) {
                output[index] = filtered(plane, first_tap, weights);
            }
        }
    }

    fn stretched_span(&self, clip_first: i64, clip_end: i64) -> Option<(i64, i64)> {
        match self {
            Self::Constant { .. } => Some((
                self.tap(clip_first)?.first()?,
                self.tap(clip_end.checked_sub(1)?)?.end()?,
            )),
            Self::Along(taps) => {
                let mut span = (i64::MAX, i64::MIN);
                for tap in taps {
                    span = (span.0.min(tap.first()?), span.1.max(tap.end()?));
                }
                (span.0 < span.1).then_some(span)
            }
        }
    }
}

pub(super) struct CurveRun<'a> {
    pub(super) curve: TimeCurve<'a>,
    pub(super) number: usize,
    pub(super) falling: bool,
    pub(super) origin: i64,
    pub(super) end: i64,
}

struct CurvePath<'a> {
    curve: TimeCurve<'a>,
    rate: u32,
    falling: bool,
    origin: i64,
    last: f64,
    clip_samples_per_stretched: f64,
    ends: [(f64, f64); 2],
}

impl<'a> CurvePath<'a> {
    fn new(run: &CurveRun<'a>, rate: u32, read: AudioRead) -> Option<Self> {
        let clip_samples_per_stretched = match read {
            AudioRead::PitchedAlong {
                ratio,
                preserve: true,
            } => 1.0 / ratio,
            _ => 1.0,
        };
        if !(clip_samples_per_stretched.is_finite() && clip_samples_per_stretched > 0.0) {
            return None;
        }
        let mut path = Self {
            curve: run.curve,
            rate,
            falling: run.falling,
            origin: run.origin,
            last: real(run.end.checked_sub(run.origin)?.checked_sub(1)?.max(0)),
            clip_samples_per_stretched,
            ends: [(0.0, 0.0); 2],
        };
        path.ends = [path.inside(0.0), path.inside(path.last)];
        Some(path)
    }

    fn inside(&self, clip_sample: f64) -> (f64, f64) {
        let time =
            (real(self.origin) + clip_sample) * real(TICKS_PER_SECOND) / f64::from(self.rate);
        let (value, speed) = self.curve.position(time);
        let position = value * f64::from(self.rate) / real(TICKS_PER_SECOND);
        if self.falling {
            (-position, -speed)
        } else {
            (position, speed)
        }
    }

    fn at(&self, clip_sample: f64) -> f64 {
        let continued =
            |(position, speed): (f64, f64), beyond: f64| position + beyond * speed.max(0.0);
        if clip_sample < 0.0 {
            continued(self.ends[0], clip_sample)
        } else if clip_sample > self.last {
            continued(self.ends[1], clip_sample - self.last)
        } else {
            self.inside(clip_sample).0
        }
    }
}

enum Along<'a> {
    Clip(SourceMap),
    Curve(CurvePath<'a>),
}

/// Where a stretched clip's grains read.
struct GrainMap<'a> {
    along: Along<'a>,
    reversed: bool,
    /// The clip's first project sample, which is the stretch's output sample zero.
    origin: i64,
    hop: i64,
    /// The read positions of the clip's source range, `[from, to)`.
    bounds: (i64, i64),
    pitched: Option<ReadLine>,
}

impl<'a> GrainMap<'a> {
    fn new(
        clip: &ActiveAudioClip,
        run: Option<&CurveRun<'a>>,
        rate: u32,
        hop: i64,
        read: AudioRead,
    ) -> Option<Self> {
        let (along, reversed, origin) = if let Some(run) = run {
            (
                Along::Curve(CurvePath::new(run, rate, read)?),
                run.falling,
                run.origin,
            )
        } else {
            let reversed = *clip.time_map == TimeMap::Reverse;
            (
                Along::Clip(SourceMap::stretched(clip, reversed, rate)?),
                reversed,
                sample_at_or_after(clip.timeline_range.start().ticks(), rate),
            )
        };
        let low = sample_at_or_after(clip.source_range.start().ticks(), rate);
        let high = sample_at_or_after(clip.source_range.end().ticks(), rate);
        let mut grains = Self {
            along,
            reversed,
            origin,
            hop,
            bounds: if reversed {
                (1 - high, 1 - low)
            } else {
                (low, high)
            },
            pitched: None,
        };
        let step = match read {
            AudioRead::Pitched { stretch, .. } => stretch,
            AudioRead::PitchedAlong {
                ratio,
                preserve: false,
            } => 1.0 / ratio,
            _ => return Some(grains),
        };
        if !(step.is_finite() && step > 0.0) {
            return None;
        }
        let (whole, fraction) = grains.read_position(grains.origin)?;
        grains.pitched = Some(ReadLine {
            whole,
            fraction,
            step,
        });
        Some(grains)
    }

    fn read_position(&self, sample: i64) -> Option<(i64, f64)> {
        let map = match &self.along {
            Along::Clip(map) => map,
            Along::Curve(path) => {
                let position = path.at(real(sample.checked_sub(self.origin)?));
                return Some((floored(position)?, position - libm::floor(position)));
            }
        };
        let (whole, fraction) = map.position(sample)?;
        if !self.reversed {
            return Some((whole, fraction));
        }
        if fraction > 0.0 {
            Some((whole.checked_add(1)?.checked_neg()?, 1.0 - fraction))
        } else {
            Some((whole.checked_neg()?, 0.0))
        }
    }

    /// The read position of a grain's start, one hop before its centre, floored in read order.
    fn position(&self, grain: i64) -> Option<i64> {
        let centre = grain.checked_add(1)?.checked_mul(self.hop)?;
        let at = match (&self.pitched, &self.along) {
            (Some(line), _) => line.floor_at(centre)?,
            (None, Along::Curve(path)) => {
                floored(path.at(real(centre) * path.clip_samples_per_stretched))?
            }
            (None, Along::Clip(_)) => self.read_position(self.origin.checked_add(centre)?)?.0,
        };
        at.checked_sub(self.hop)
    }

    const fn source(&self, at: i64) -> i64 {
        if self.reversed { -at } else { at }
    }

    fn folded(
        &self,
        (from, to): (i64, i64),
        downmix: &Downmix,
        source: &AudioBlock,
        channels: usize,
    ) -> Vec<Vec<f32>> {
        (0..channels)
            .map(|channel| {
                let mix = downmix.channel(channel);
                (from..to)
                    .map(|at| {
                        if at < self.bounds.0 || at >= self.bounds.1 {
                            0.0
                        } else {
                            mixed_sample(
                                mix,
                                &source.channels,
                                self.source(at) - source.start_sample,
                            )
                        }
                    })
                    .collect()
            })
            .collect()
    }

    /// The source samples of read positions `[from, to)` clamped to the source range.
    fn source_window(&self, from: i64, to: i64) -> Option<(i64, i64)> {
        let (from, to) = (from.max(self.bounds.0), to.min(self.bounds.1));
        if from >= to {
            return None;
        }
        Some(if self.reversed {
            (1 - to, 1 - from)
        } else {
            (from, to)
        })
    }
}

/// What a stretched read of project samples takes.
struct Window<'a> {
    grains: GrainMap<'a>,
    /// The stretch's first output sample.
    first: i64,
    stretched_frames: usize,
    /// The read positions the stretch can touch, `[from, to)`.
    read: (i64, i64),
    source: Option<(i64, i64)>,
    clip_first: i64,
    resampling: Option<Resampling>,
}

fn window<'a>(
    stretch: &Stretch,
    clip: &ActiveAudioClip,
    run: Option<&CurveRun<'a>>,
    first_sample: i64,
    count: usize,
    rate: u32,
) -> Option<Window<'a>> {
    let read = read_of(clip);
    let grains = GrainMap::new(clip, run, rate, stretch.hop(), read)?;
    let clip_first = first_sample.checked_sub(grains.origin)?;
    let clip_end = clip_first.checked_add(i64::try_from(count).ok()?)?;
    let resampling = match (read, &grains.along) {
        (AudioRead::Pitched { pitch, .. }, _) => Some(Resampling::new(pitch)?),
        (
            AudioRead::PitchedAlong {
                ratio,
                preserve: true,
            },
            _,
        ) => Some(Resampling::new(ratio)?),
        (
            AudioRead::PitchedAlong {
                ratio,
                preserve: false,
            },
            Along::Curve(path),
        ) => Some(Resampling::along(path, ratio, clip_first, clip_end)?),
        _ => None,
    };
    let (first, end) = match &resampling {
        Some(resampling) => resampling.stretched_span(clip_first, clip_end)?,
        None => (clip_first, clip_end),
    };
    // The map is monotonic, so checking the outermost grains checks every one in between.
    let (low, high) = stretch.grains(first, end);
    grains.position(Stretch::chain(Stretch::segment(low)).0)?;
    grains.position(Stretch::chain(Stretch::segment(high)).1)?;
    let read = stretch.reach_output(first, end, |grain| grains.position(grain).unwrap_or(0));
    let source = grains.source_window(read.0, read.1);
    Some(Window {
        grains,
        first,
        stretched_frames: usize::try_from(end.checked_sub(first)?).ok()?,
        read,
        source,
        clip_first,
        resampling,
    })
}

/// The source samples `[from, to)` that [`AudioRenderer::read_stretched`] asks for.
pub(super) fn stretched_request(
    stretch: &Stretch,
    clip: &ActiveAudioClip,
    run: Option<&CurveRun<'_>>,
    first_sample: i64,
    count: usize,
    rate: u32,
) -> Option<(i64, i64)> {
    window(stretch, clip, run, first_sample, count, rate)?.source
}

/// A clip's reader and the clip state it was made for, since its offsets are only valid for that.
pub(super) struct StretchSlot {
    source: SourceId,
    stream: Option<u32>,
    channel_map: Option<alpha2_model::ChannelMap>,
    timeline_range: TimeRange,
    source_range: TimeRange,
    time_map: TimeMap,
    read: AudioRead,
    reader: StretchReader,
    pub(super) used_in: u64,
}

/// The reader of `clip`, recreated if missing or if the clip changed, marked used in `block`.
fn reader_for<'a>(
    slots: &'a mut HashMap<(ClipId, usize), StretchSlot>,
    clip: &ActiveAudioClip,
    run: usize,
    rate: u32,
    block: u64,
) -> &'a mut StretchReader {
    let fresh = || StretchSlot {
        source: clip.source_id.clone(),
        stream: clip.audio.stream,
        channel_map: clip.audio.channel_map.clone(),
        timeline_range: clip.timeline_range,
        source_range: clip.source_range,
        time_map: clip.time_map.clone(),
        read: read_of(clip),
        reader: StretchReader::new(rate),
        used_in: block,
    };
    let slot = slots
        .entry((clip.clip_id.clone(), run))
        .or_insert_with(fresh);
    if slot.source != *clip.source_id
        || slot.stream != clip.audio.stream
        || slot.channel_map != clip.audio.channel_map
        || slot.timeline_range != clip.timeline_range
        || slot.source_range != clip.source_range
        || slot.time_map != *clip.time_map
        || slot.read != read_of(clip)
    {
        *slot = fresh();
    }
    slot.used_in = block;
    &mut slot.reader
}

impl AudioRenderer {
    /// Stretched counterpart of [`AudioRenderer::read_source`]. Returns whether every requested
    /// sample came from supplied media.
    #[expect(
        clippy::too_many_arguments,
        reason = "a read is a clip, a span of it, where it goes and where it comes from"
    )]
    pub(super) fn read_stretched(
        &mut self,
        clip: &ActiveAudioClip,
        run: Option<&CurveRun<'_>>,
        first_sample: i64,
        offset: usize,
        count: usize,
        provider: &dyn AudioBlockProvider,
        fill: Fill,
    ) -> bool {
        let rate = self.sample_rate;
        let Some(window) = window(&self.stretch, clip, run, first_sample, count, rate) else {
            return false;
        };
        // Wholly outside the source range: `clip_a` already holds silence.
        let Some((source_from, source_to)) = window.source else {
            return true;
        };
        let frames = usize::try_from(source_to - source_from).unwrap_or(0);
        let Some(span) = provider.block(clip.source_id, clip.audio.stream, source_from, frames)
        else {
            return false;
        };
        if !span.covers(source_from, source_to) {
            return false;
        }
        let source = span.block;
        if source.sample_rate != rate {
            return false;
        }
        let Some(downmix) = super::clip_downmix(clip, source, self.layout) else {
            return false;
        };
        if fill == Fill::Presence {
            return true;
        }
        #[cfg(test)]
        {
            self.samples_read += count;
        }

        let grains = &window.grains;
        let (from, _) = window.read;
        let channels = self.layout.channels();
        let planes = grains.folded(window.read, &downmix, source, channels);
        // The search runs on the channel mean, summed in channel order.
        #[allow(clippy::cast_precision_loss)]
        let scale = 1.0 / channels as f32;
        let mono: Vec<f32> = (0..planes[0].len())
            .map(|index| planes.iter().map(|plane| plane[index]).sum::<f32>() * scale)
            .collect();
        let signals: Vec<StretchSignal<'_>> = planes
            .iter()
            .map(|plane| StretchSignal {
                start: from,
                samples: plane,
            })
            .collect();

        let reader = reader_for(
            &mut self.stretch_slots,
            clip,
            run.map_or(0, |run| run.number),
            rate,
            self.blocks_mixed,
        );
        let mut stretched = match window.resampling {
            Some(_) => vec![vec![0.0; window.stretched_frames]; channels],
            None => Vec::new(),
        };
        let mut outputs: Vec<&mut [f32]> = if window.resampling.is_some() {
            stretched.iter_mut().map(Vec::as_mut_slice).collect()
        } else {
            self.clip_a
                .iter_mut()
                .take(channels)
                .map(|plane| &mut plane[offset..offset + count])
                .collect()
        };
        reader.render(
            window.first,
            &mut outputs,
            |grain| grains.position(grain).unwrap_or(0),
            &signals,
            StretchSignal {
                start: from,
                samples: &mono,
            },
        );
        let Some(resampling) = &window.resampling else {
            return true;
        };
        let mut outputs: Vec<&mut [f32]> = self
            .clip_a
            .iter_mut()
            .take(channels)
            .map(|plane| &mut plane[offset..offset + count])
            .collect();
        resampling.resample(
            &stretched,
            window.first,
            window.clip_first,
            &mut outputs,
            &mut self.weights,
        );
        true
    }
}