alpha2-host-core 0.6.2

FFmpeg-free native host logic for alpha2: the policies, audio timelines, cursor rules, providers, plugin runtime, protocol frames and request parsing native hosts share, and the decode, export and still pipeline the mobile hosts run.
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
//! Decoded audio held in windows around what a mix reads, within a byte budget: each source's
//! decoder moves forward with a clip playing through, and seeks for other reads.

use std::collections::HashMap;

use alpha2_media::{
    AudioBlock, AudioBlockProvider, AudioSpan, CancelToken, DecodeError, DecodeEvent,
    DecodeRequest, DecodeRequestKind, Decoder, SourceId, SpeakerLayout,
};
use alpha2_time::{MediaTime, TICKS_PER_SECOND};

/// Samples each side of a read the mix's interpolation reaches.
pub const AUDIO_INTERPOLATION_MARGIN: i64 = 2;

/// A source's audio decoder as the windows drive it.
pub trait WindowedAudioDecoder: Decoder {
    /// Channels of every block it returns.
    fn channels(&self) -> usize;
    /// The speaker each channel feeds.
    fn speakers(&self) -> SpeakerLayout;
    /// Where the source's audio ends, as the project reads it; `None` when unknown.
    fn audio_duration(&self) -> Option<MediaTime>;
}

/// Why the windows could not hold what a mix reads.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum AudioWindowError {
    /// A source the mix reads has no file.
    MissingInput(String),
    /// The windows cannot fit the byte budget.
    ResourceLimit(String),
    /// A decoder failed.
    Decode(DecodeError),
    /// A decoder broke its contract.
    Broken(String),
}

impl std::fmt::Display for AudioWindowError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::MissingInput(message) | Self::ResourceLimit(message) | Self::Broken(message) => {
                formatter.write_str(message)
            }
            Self::Decode(error) => write!(formatter, "{error}"),
        }
    }
}

impl std::error::Error for AudioWindowError {}

/// A byte budget a scale may shrink, which still holds what one read needs up to the unscaled
/// budget: only a budget too small before any scale refuses.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct ByteBudget {
    /// The budget after the scale.
    pub bytes: u64,
    /// The unscaled budget.
    pub ceiling: u64,
}

impl ByteBudget {
    /// A budget no scale shrank.
    #[must_use]
    pub const fn exact(bytes: u64) -> Self {
        Self {
            bytes,
            ceiling: bytes,
        }
    }

    /// The budget, or `least` up to the unscaled budget where the scale shrank it below that.
    #[must_use]
    pub fn holding(self, least: u64) -> u64 {
        self.bytes.max(least.min(self.ceiling))
    }
}

impl From<u64> for ByteBudget {
    fn from(bytes: u64) -> Self {
        Self::exact(bytes)
    }
}

/// Opens a source's audio stream (`None` is its default one) for the windows.
pub type OpenAudio<D> =
    Box<dyn FnMut(&SourceId, Option<u32>) -> Result<D, AudioWindowError> + Send>;

/// One window of a source stream and the decoder that fills it.
pub struct WindowedAudioSource<D> {
    /// The decoder filling the window.
    pub decoder: D,
    /// The decoded samples held, from the read's start.
    pub window: Option<AudioBlock>,
    /// The request can start before the stream's first sample; that prefix is known silence and
    /// is not allocated.
    covered_start: i64,
    /// Past the window the source is silent.
    ended: bool,
    /// A read before this moves backward, as a reversed clip reads.
    last_start: Option<i64>,
}

/// Seeking this far before a backward read lets the following, slightly earlier reads continue the
/// window.
const BACKWARD_READAHEAD_SECONDS: i64 = 1;

/// A window filled to a sample ends at most one block past it.
const AUDIO_DECODE_BLOCK_FRAMES: usize = 4_096;

impl<D: WindowedAudioDecoder> WindowedAudioSource<D> {
    fn continues_at(&self, start: i64) -> bool {
        self.window.as_ref().is_some_and(|window| {
            let window_start = window.start_sample;
            let window_end = window_start.saturating_add(audio_block_frames(window));
            start >= self.covered_start && (start <= window_end || self.ended)
        })
    }

    /// The full growth is reserved and checked against `limit` before anything past the first
    /// block is decoded.
    fn ensure_window(
        &mut self,
        source: &SourceId,
        (start, end): (i64, i64),
        sample_rate: u32,
        limit: u64,
        cancel: &CancelToken,
    ) -> Result<(), AudioWindowError> {
        let backward = self.last_start.is_some_and(|last| start < last);
        self.last_start = Some(start);
        if !self.continues_at(start) {
            let seek_start = if backward {
                start
                    .saturating_sub(BACKWARD_READAHEAD_SECONDS * i64::from(sample_rate))
                    .max(0)
            } else {
                start
            };
            let request_time =
                MediaTime::from_ticks(samples_to_ticks_ceil(seek_start, sample_rate));
            crate::request_watch::beat_request();
            let result = self.decoder.seek(
                DecodeRequest {
                    source: source.clone(),
                    time: request_time,
                    kind: DecodeRequestKind::Seek,
                    generation: 0,
                },
                cancel,
            );
            match result {
                Ok(result) => {
                    let DecodeEvent::Audio(block) = result.event else {
                        return Err(AudioWindowError::Broken(format!(
                            "audio source {} did not decode a block",
                            source.as_str()
                        )));
                    };
                    self.window = Some(block);
                    self.ended = false;
                }
                // Past the stream's end (audio that stops early) the source is silent.
                Err(DecodeError::OutOfRange) => {
                    self.window = Some(AudioBlock {
                        start_sample: seek_start,
                        sample_rate,
                        speakers: self.decoder.speakers(),
                        channels: vec![Vec::new(); self.decoder.channels()],
                    });
                    self.ended = true;
                }
                Err(error) => return Err(AudioWindowError::Decode(error)),
            }
            self.covered_start = seek_start.min(start);
        }
        self.reserve_to(source, end, limit)?;
        loop {
            let window = self
                .window
                .as_ref()
                .ok_or_else(|| AudioWindowError::Broken("audio window disappeared".to_owned()))?;
            let window_start = window.start_sample;
            let window_end = window_start.saturating_add(audio_block_frames(window));
            if window_end >= end || self.ended {
                break;
            }
            crate::request_watch::beat_request();
            match self
                .decoder
                .decode_next(cancel)
                .map_err(AudioWindowError::Decode)?
            {
                DecodeEvent::Audio(block) => append_audio_block(
                    self.window.as_mut().ok_or_else(|| {
                        AudioWindowError::Broken("audio window disappeared".to_owned())
                    })?,
                    block,
                )?,
                DecodeEvent::EndOfStream => {
                    self.ended = true;
                    break;
                }
                DecodeEvent::Retry | DecodeEvent::Video(_) => {}
            }
        }
        let declared_duration = self.decoder.audio_duration();
        let window = self
            .window
            .as_mut()
            .ok_or_else(|| AudioWindowError::Broken("audio window disappeared".to_owned()))?;
        if self.ended {
            pad_audio_window_to_declared_end(window, end, declared_duration, sample_rate);
        }
        // Reading backward, what lies before this read is what the next reads want.
        if !backward {
            trim_audio_window(window, start);
            self.covered_start = start;
        }
        Ok(())
    }

    /// Reserves every channel up to `end` plus the decoder block that may run past it, so the
    /// window's growth never doubles past what was checked.
    fn reserve_to(
        &mut self,
        source: &SourceId,
        end: i64,
        limit: u64,
    ) -> Result<(), AudioWindowError> {
        let ended = self.ended;
        let Some(window) = self.window.as_mut() else {
            return Ok(());
        };
        let held = audio_block_frames(window);
        if ended || window.start_sample.saturating_add(held) >= end {
            return Ok(());
        }
        let frames = usize::try_from(end.saturating_sub(window.start_sample))
            .unwrap_or(usize::MAX)
            .saturating_add(AUDIO_DECODE_BLOCK_FRAMES);
        let bytes = u64::try_from(frames)
            .unwrap_or(u64::MAX)
            .saturating_mul(u64::try_from(window.channels.len()).unwrap_or(u64::MAX))
            .saturating_mul(4);
        if bytes > limit {
            return Err(AudioWindowError::ResourceLimit(format!(
                "the audio mix reads {frames} samples of {} channels of source {} at once, \
                 {bytes} bytes, over the {limit} bytes the audio window budget has left",
                window.channels.len(),
                source.as_str(),
            )));
        }
        for channel in &mut window.channels {
            channel.reserve_exact(frames.saturating_sub(channel.len()));
        }
        Ok(())
    }
}

/// A source's audio stream as the mix reads it (`AudioNeed::stream`); `None` is the default one.
pub type AudioStreamKey = (SourceId, Option<u32>);

/// Every source stream's windows, for one mix.
pub struct WindowedAudioSources<D> {
    /// The rate the mix reads at.
    pub sample_rate: u32,
    open: OpenAudio<D>,
    /// One window per disjoint range of a source stream: two clips of one media may read
    /// unrelated ranges, and one window over both would decode and retain everything between.
    pub sources: HashMap<AudioStreamKey, Vec<WindowedAudioSource<D>>>,
    /// A block that needs more than a scaled budget still gets up to the unscaled one
    /// ([`ByteBudget::holding`]).
    pub byte_budget: ByteBudget,
    /// Bytes the windows hold after the last [`Self::prepare`].
    pub retained_bytes: u64,
    /// The most bytes the windows held after any [`Self::prepare`].
    pub peak_bytes: u64,
}

impl<D: WindowedAudioDecoder> WindowedAudioSources<D> {
    /// Windows at `sample_rate` within `byte_budget`, opening source streams with `open` as the
    /// mix first reads them.
    #[must_use]
    pub fn new(sample_rate: u32, byte_budget: impl Into<ByteBudget>, open: OpenAudio<D>) -> Self {
        Self {
            sample_rate,
            open,
            sources: HashMap::new(),
            byte_budget: byte_budget.into(),
            retained_bytes: 0,
            peak_bytes: 0,
        }
    }

    /// Decodes what `needs` reads, plus the interpolation margin, and drops unneeded windows.
    ///
    /// # Errors
    /// Fails with `RESOURCE_LIMIT` when the windows cannot fit the budget, and with the
    /// decoder's error or a cancellation otherwise.
    pub fn prepare(
        &mut self,
        needs: &[alpha2_engine::AudioNeed],
        cancel: &CancelToken,
    ) -> Result<(), AudioWindowError> {
        let mut ranges = HashMap::<AudioStreamKey, Vec<(i64, i64)>>::new();
        for need in needs {
            let start = ticks_to_samples(need.source_range.start().ticks(), self.sample_rate)
                .saturating_sub(AUDIO_INTERPOLATION_MARGIN)
                .max(0);
            let end = ticks_to_samples_ceil(need.source_range.end().ticks(), self.sample_rate)
                .saturating_add(AUDIO_INTERPOLATION_MARGIN);
            if end > start {
                ranges
                    .entry((need.source_id.clone(), need.stream))
                    .or_default()
                    .push((start, end));
            }
        }
        // The least the windows will hold, in 32-bit samples per channel. A mix that cannot fit is
        // refused before decoding.
        let least = ranges.iter().fold(0_u64, |bytes, (source, spans)| {
            let channels = self
                .sources
                .get(source)
                .and_then(|states| states.first())
                .map_or(1, |state| state.decoder.channels().max(1));
            spans.iter().fold(bytes, |bytes, &(start, end)| {
                bytes.saturating_add(
                    u64::try_from(end.saturating_sub(start))
                        .unwrap_or(u64::MAX)
                        .saturating_mul(u64::try_from(channels).unwrap_or(u64::MAX))
                        .saturating_mul(4),
                )
            })
        });
        let budget = self.byte_budget.holding(least);
        if least > budget {
            return Err(AudioWindowError::ResourceLimit(format!(
                "the audio mix needs at least {least} bytes of decoded audio at once, over the {budget} byte audio window budget"
            )));
        }
        self.sources.retain(|source, _| ranges.contains_key(source));
        for (source, spans) in ranges {
            self.ensure_windows(&source, &merge_sample_ranges(spans), budget, cancel)?;
        }
        self.retained_bytes = window_bytes(self.sources.values().flatten());
        if self.retained_bytes > budget {
            return Err(AudioWindowError::ResourceLimit(format!(
                "decoded audio window exceeds {budget} byte budget"
            )));
        }
        self.peak_bytes = self.peak_bytes.max(self.retained_bytes);
        Ok(())
    }

    /// A span that continues a window keeps its decoder, so a clip playing through reads
    /// sequentially. Other spans seek an unused window or open a decoder.
    fn ensure_windows(
        &mut self,
        source: &AudioStreamKey,
        spans: &[(i64, i64)],
        budget: u64,
        cancel: &CancelToken,
    ) -> Result<(), AudioWindowError> {
        let sample_rate = self.sample_rate;
        let mut idle = self.sources.remove(source).unwrap_or_default();
        let continued = spans
            .iter()
            .map(|&(start, _)| {
                idle.iter()
                    .position(|state| state.continues_at(start))
                    .map(|index| idle.swap_remove(index))
            })
            .collect::<Vec<_>>();
        let mut windows = Vec::with_capacity(spans.len());
        let mut continued = continued.into_iter();
        for &span in spans {
            let mut state = match continued.next().flatten().or_else(|| idle.pop()) {
                Some(state) => state,
                None => self.open(&source.0, source.1)?,
            };
            let held = window_bytes(self.sources.values().flatten())
                .saturating_add(window_bytes(&idle))
                .saturating_add(window_bytes(&windows))
                .saturating_add(window_bytes(continued.as_slice().iter().flatten()));
            state.ensure_window(
                &source.0,
                span,
                sample_rate,
                budget.saturating_sub(held),
                cancel,
            )?;
            windows.push(state);
        }
        self.sources.insert(source.clone(), windows);
        Ok(())
    }

    fn open(
        &mut self,
        source: &SourceId,
        stream: Option<u32>,
    ) -> Result<WindowedAudioSource<D>, AudioWindowError> {
        Ok(WindowedAudioSource {
            decoder: (self.open)(source, stream)?,
            window: None,
            covered_start: 0,
            ended: false,
            last_start: None,
        })
    }

    /// The most decoded audio the windows held at once.
    #[must_use]
    pub const fn peak_bytes(&self) -> u64 {
        self.peak_bytes
    }
}

impl<D: WindowedAudioDecoder> AudioBlockProvider for WindowedAudioSources<D> {
    /// Windows are decoded in whole decoder blocks, so one can run past the start of another; the
    /// first window holding the read's start is not always the one that holds the read.
    fn block(
        &self,
        source: &SourceId,
        stream: Option<u32>,
        start_sample: i64,
        frames: usize,
    ) -> Option<AudioSpan<'_>> {
        let request_end = start_sample.saturating_add(i64::try_from(frames).unwrap_or(i64::MAX));
        let spans = self
            .sources
            .get(&(source.clone(), stream))?
            .iter()
            .filter_map(|state| {
                let window = state.window.as_ref()?;
                let window_start = window.start_sample;
                let window_end = window_start.saturating_add(audio_block_frames(window));
                (start_sample >= state.covered_start && (start_sample < window_end || state.ended))
                    .then_some(AudioSpan {
                        block: window,
                        // A seek before the first sample decodes from it; what lies before is silence.
                        starts_source: state.covered_start < window_start,
                        // A clip ending exactly at the stream's end reads interpolation samples past
                        // it.
                        ends_source: state.ended,
                    })
            });
        let mut first = None;
        for span in spans {
            if span.covers(start_sample, request_end) {
                return Some(span);
            }
            first.get_or_insert(span);
        }
        first
    }
}

/// `ranges` sorted, with overlapping and touching ones merged.
#[must_use]
pub fn merge_sample_ranges(mut ranges: Vec<(i64, i64)>) -> Vec<(i64, i64)> {
    ranges.sort_unstable();
    let mut merged: Vec<(i64, i64)> = Vec::with_capacity(ranges.len());
    for (start, end) in ranges {
        match merged.last_mut() {
            Some(last) if start <= last.1 => last.1 = last.1.max(end),
            _ => merged.push((start, end)),
        }
    }
    merged
}

/// Samples per channel `block` holds.
#[must_use]
pub fn audio_block_frames(block: &AudioBlock) -> i64 {
    block
        .channels
        .first()
        .and_then(|channel| i64::try_from(channel.len()).ok())
        .unwrap_or(0)
}

fn window_bytes<'a, D: 'a>(states: impl IntoIterator<Item = &'a WindowedAudioSource<D>>) -> u64 {
    states.into_iter().fold(0_u64, |bytes, state| {
        bytes.saturating_add(state.window.as_ref().map_or(0, audio_block_bytes))
    })
}

/// Bytes `block`'s 32-bit samples take.
#[must_use]
pub fn audio_block_bytes(block: &AudioBlock) -> u64 {
    block.channels.iter().fold(0_u64, |bytes, channel| {
        bytes.saturating_add(
            u64::try_from(channel.len())
                .unwrap_or(u64::MAX)
                .saturating_mul(4),
        )
    })
}

/// # Errors
/// Fails when the format changes or `block` does not start exactly where `window` ends.
pub fn append_audio_block(
    window: &mut AudioBlock,
    block: AudioBlock,
) -> Result<(), AudioWindowError> {
    if window.sample_rate != block.sample_rate || window.channels.len() != block.channels.len() {
        return Err(AudioWindowError::Broken(
            "decoded audio format changed inside a source".to_owned(),
        ));
    }
    if block.start_sample
        != window
            .start_sample
            .saturating_add(audio_block_frames(window))
    {
        return Err(AudioWindowError::Broken(
            "decoded audio has an unreported gap or overlap inside AudioSpan".to_owned(),
        ));
    }
    for (output, input) in window.channels.iter_mut().zip(block.channels) {
        output.extend(input);
    }
    Ok(())
}

/// Pads no further than the declared duration plus the interpolation margin; does nothing without
/// a declared duration.
pub fn pad_audio_window_to_declared_end(
    window: &mut AudioBlock,
    requested_end: i64,
    declared_duration: Option<MediaTime>,
    sample_rate: u32,
) {
    let window_start = window.start_sample;
    let window_end = window_start.saturating_add(audio_block_frames(window));
    let Some(declared_end) =
        declared_duration.map(|duration| ticks_to_samples_ceil(duration.ticks(), sample_rate))
    else {
        return;
    };
    let padded_end = requested_end.min(declared_end.saturating_add(AUDIO_INTERPOLATION_MARGIN));
    let Ok(padding) = usize::try_from(padded_end.saturating_sub(window_end).max(0)) else {
        return;
    };
    if padding == 0 {
        return;
    }
    for channel in &mut window.channels {
        channel.resize(channel.len().saturating_add(padding), 0.0);
    }
}

/// Drops what `window` holds before `requested_start`.
pub fn trim_audio_window(window: &mut AudioBlock, requested_start: i64) {
    let window_start = window.start_sample;
    let discard = usize::try_from(requested_start.saturating_sub(window_start).max(0))
        .unwrap_or(usize::MAX)
        .min(window.channels.first().map_or(0, Vec::len));
    if discard == 0 {
        return;
    }
    for channel in &mut window.channels {
        channel.drain(..discard.min(channel.len()));
    }
    window.start_sample = window_start.saturating_add(i64::try_from(discard).unwrap_or(i64::MAX));
}

/// Rounds toward negative infinity.
#[must_use]
pub fn ticks_to_samples(ticks: i64, sample_rate: u32) -> i64 {
    ticks
        .saturating_mul(i64::from(sample_rate))
        .div_euclid(TICKS_PER_SECOND)
}

/// Rounds up.
#[must_use]
pub fn ticks_to_samples_ceil(ticks: i64, sample_rate: u32) -> i64 {
    let numerator = i128::from(ticks).saturating_mul(i128::from(sample_rate));
    let denominator = i128::from(TICKS_PER_SECOND);
    let samples =
        numerator.div_euclid(denominator) + i128::from(numerator.rem_euclid(denominator) != 0);
    i64::try_from(samples).unwrap_or(i64::MAX)
}

/// Rounds up; a zero rate is treated as 1.
#[must_use]
pub fn samples_to_ticks_ceil(samples: i64, sample_rate: u32) -> i64 {
    let numerator = i128::from(samples).saturating_mul(i128::from(TICKS_PER_SECOND));
    let denominator = i128::from(sample_rate.max(1));
    let ticks =
        numerator.div_euclid(denominator) + i128::from(numerator.rem_euclid(denominator) != 0);
    i64::try_from(ticks).unwrap_or(i64::MAX)
}

impl<D: WindowedAudioDecoder> crate::audio_host::ProjectAudioSources for WindowedAudioSources<D> {
    fn prepare(
        &mut self,
        needs: &[alpha2_engine::AudioNeed],
        cancel: &CancelToken,
    ) -> Result<(), AudioWindowError> {
        Self::prepare(self, needs, cancel)
    }
}