alpha2-host-core 0.8.1

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
//! Export policy every native host applies: the H.264 profile ladder platform encoders are tried
//! with, and whether and how a failed export is retried.

use alpha2_media::FailureClass;
use alpha2_time::FrameRate;

/// An H.264 profile a platform encoder is asked for.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AvcProfile {
    /// High (`profile_idc` 100).
    High,
    /// Main (`profile_idc` 77).
    Main,
    /// Constrained Baseline: Baseline with `constraint_set1`, decodable by every H.264 decoder.
    ConstrainedBaseline,
}

impl AvcProfile {
    /// The ladder, tried in this order.
    pub const LADDER: [Self; 3] = [Self::High, Self::Main, Self::ConstrainedBaseline];

    /// The profile's name, as reports spell it.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::High => "High",
            Self::Main => "Main",
            Self::ConstrainedBaseline => "Constrained Baseline",
        }
    }

    /// `profile_idc` and the constraint flags byte, as an `avc1.PPCCLL` codec string carries them.
    #[must_use]
    pub const fn idc_and_constraints(self) -> (u8, u8) {
        match self {
            Self::High => (0x64, 0x00),
            Self::Main => (0x4d, 0x00),
            // constraint_set0, 1 and 2: decodable by Baseline, Main and Extended decoders.
            Self::ConstrainedBaseline => (0x42, 0xe0),
        }
    }
}

/// One row of ITU-T H.264 Table A-1.
struct AvcLevel {
    /// `MaxFS`: macroblocks per frame.
    frame: u64,
    /// `MaxMBPS`: macroblocks per second.
    rate: u64,
    /// `MaxBR` in bits per second.
    bitrate: u64,
    level_idc: u8,
}

const fn row(frame: u64, rate: u64, bitrate: u64, level_idc: u8) -> AvcLevel {
    AvcLevel {
        frame,
        rate,
        bitrate,
        level_idc,
    }
}

/// H.264 levels (ITU-T H.264 Table A-1), lowest first.
const AVC_LEVELS: [AvcLevel; 19] = [
    row(99, 1_485, 64_000, 10),
    row(396, 3_000, 192_000, 11),
    row(396, 6_000, 384_000, 12),
    row(396, 11_880, 768_000, 13),
    row(396, 11_880, 2_000_000, 20),
    row(792, 19_800, 4_000_000, 21),
    row(1_620, 20_250, 4_000_000, 22),
    row(1_620, 40_500, 10_000_000, 30),
    row(3_600, 108_000, 14_000_000, 31),
    row(5_120, 216_000, 20_000_000, 32),
    row(8_192, 245_760, 20_000_000, 40),
    row(8_192, 245_760, 50_000_000, 41),
    row(8_704, 522_240, 50_000_000, 42),
    row(22_080, 589_824, 135_000_000, 50),
    row(36_864, 983_040, 240_000_000, 51),
    row(36_864, 2_073_600, 240_000_000, 52),
    row(139_264, 4_177_920, 240_000_000, 60),
    row(139_264, 8_355_840, 480_000_000, 61),
    row(139_264, 16_711_680, 800_000_000, 62),
];

/// The lowest `level_idc` that holds `width` x `height` at `frame_rate` and `bitrate`, else the
/// highest level.
#[must_use]
pub fn avc_level(width: u32, height: u32, frame_rate: FrameRate, bitrate: u64) -> u8 {
    let frame = u64::from(width.div_ceil(16)) * u64::from(height.div_ceil(16));
    let (num, den) = (
        u64::from(frame_rate.numerator()),
        u64::from(frame_rate.denominator()),
    );
    AVC_LEVELS
        .iter()
        .find(|level| {
            frame <= level.frame
                && frame.saturating_mul(num) <= level.rate.saturating_mul(den)
                && bitrate <= level.bitrate
        })
        .map_or(62, |level| level.level_idc)
}

/// The `avc1.PPCCLL` codec string of `profile` at `level`.
#[must_use]
pub fn avc_codec_string(profile: AvcProfile, level: u8) -> String {
    let (idc, constraints) = profile.idc_and_constraints();
    format!("avc1.{idc:02x}{constraints:02x}{level:02x}")
}

/// An in-flight budget scale for an attempt.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RetryProfile {
    /// Matched by name in the history.
    pub name: &'static str,
    /// Fraction of each in-flight budget, in `(0, 1]`.
    pub memory_scale: f32,
}

/// Full, half and quarter budgets.
pub const RETRY_PROFILES: [RetryProfile; 3] = [
    RetryProfile {
        name: "default",
        memory_scale: 1.0,
    },
    RetryProfile {
        name: "reduced",
        memory_scale: 0.5,
    },
    RetryProfile {
        name: "minimal",
        memory_scale: 0.25,
    },
];

/// Which renderer an attempt used.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AttemptRenderer {
    /// The GPU renderer.
    Gpu,
    /// The CPU renderer.
    Cpu,
}

/// Which video encoder an attempt used.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AttemptEncoder {
    /// The platform's choice, hardware first.
    Default,
    /// A software encoder.
    Software,
}

/// The memory a failure's evidence names, as an export failure's `resource` spells it.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MemoryResource {
    /// Host memory.
    Cpu,
    /// GPU memory.
    Gpu,
    /// The JavaScript heap.
    Js,
    /// The engine's wasm linear memory.
    Wasm,
    /// No region named.
    Unknown,
}

impl MemoryResource {
    /// Parses its wire name (`cpu`, `gpu`, `js`, `wasm`, `unknown`).
    #[must_use]
    pub fn parse(name: &str) -> Option<Self> {
        match name {
            "cpu" => Some(Self::Cpu),
            "gpu" => Some(Self::Gpu),
            "js" => Some(Self::Js),
            "wasm" => Some(Self::Wasm),
            "unknown" => Some(Self::Unknown),
            _ => None,
        }
    }
}

/// A classified export failure, as the retry policy reads it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AttemptFailure {
    /// Its class.
    pub code: FailureClass,
    /// The memory its evidence names.
    pub resource: MemoryResource,
    /// The phase it failed in (`prepare`, `decode`, `render`, `encode`, `publish`).
    pub phase: String,
    /// The export frame it failed at, when known.
    pub frame: Option<u64>,
    /// A wait the failure asks for before retrying, in milliseconds.
    pub retry_after_ms: Option<u64>,
}

/// One failed attempt.
#[derive(Clone, Debug, PartialEq)]
pub struct AttemptOutcome {
    /// Its failure.
    pub failure: AttemptFailure,
    /// Its budget profile.
    pub profile: RetryProfile,
    /// Its renderer.
    pub renderer: AttemptRenderer,
    /// Its video encoder.
    pub encoder: AttemptEncoder,
}

/// What the host can change between attempts.
#[derive(Clone, Copy, Debug)]
pub struct RetryOptions {
    /// Total attempts, the first included.
    pub max_attempts: usize,
    /// Whether an attempt can run on the CPU renderer. Default false.
    pub cpu_renderer: bool,
    /// Whether a software video encoder exists for the export's codec.
    pub software_encoder: bool,
}

impl Default for RetryOptions {
    fn default() -> Self {
        Self {
            max_attempts: 3,
            cpu_renderer: false,
            software_encoder: true,
        }
    }
}

/// The policy's answer.
#[derive(Clone, Debug, PartialEq)]
pub enum RetryDecision {
    /// Run another attempt after `delay_ms` with these settings.
    Retry {
        /// Milliseconds to wait first.
        delay_ms: u64,
        /// The next attempt's budget profile.
        profile: RetryProfile,
        /// Its renderer.
        renderer: AttemptRenderer,
        /// Its video encoder.
        encoder: AttemptEncoder,
        /// Why, for the report.
        reason: String,
    },
    /// Stop with `code` (a GPU loss recurring at one frame stops as `DEVICE_HUNG`).
    Stop {
        /// Why, for the report.
        reason: String,
        /// The class the export fails with.
        code: Option<FailureClass>,
    },
}

const PERMANENT: [FailureClass; 7] = [
    FailureClass::Cancelled,
    FailureClass::InvalidInput,
    FailureClass::ValidationFailed,
    FailureClass::ResourceLimit,
    FailureClass::StorageQuotaExceeded,
    FailureClass::OutputIoFailed,
    FailureClass::DeviceHung,
];
const MEMORY: [FailureClass; 2] = [FailureClass::OutOfMemory, FailureClass::AllocationFailed];
const GPU_LOSSES: [FailureClass; 2] = [FailureClass::DeviceLost, FailureClass::GpuTimeout];

/// Whether a retry could help `failure` at all (the CPU renderer aside).
#[must_use]
pub fn retryable(failure: &AttemptFailure) -> bool {
    !PERMANENT.contains(&failure.code) && failure.phase != "download"
}

fn backoff(failed: usize) -> u64 {
    1_000_u64.saturating_mul(1 << failed.saturating_sub(1).min(16))
}

/// Whether and how to retry after the failed attempts in `history`, oldest first.
///
/// An export is retried whole on a fresh device; attempts change the in-flight budget, the
/// renderer and the video encoder, never the output settings. A GPU that hangs on the export's
/// own work moves to the CPU renderer; memory exhaustion steps down a profile, then GPU memory
/// exhaustion moves to the CPU renderer; an encode failure retries once in software; a busy
/// resource waits; an engine fault (`DEFECT`) retries once, unchanged and at once; anything else
/// transient retries unchanged and steps down only when it recurs at the same point.
// One rule after another, in the reference policy's order.
#[allow(clippy::too_many_lines)]
#[must_use]
pub fn decide_retry(history: &[AttemptOutcome], options: RetryOptions) -> RetryDecision {
    let Some(last) = history.last() else {
        return RetryDecision::Stop {
            reason: "nothing failed".into(),
            code: None,
        };
    };
    let failure = &last.failure;
    let code = failure.code;
    let mut note = "";
    let stop = |why: String, note: &str, final_code: FailureClass| RetryDecision::Stop {
        reason: format!("{why}{note}"),
        code: Some(final_code),
    };
    let attempts_left = history.len() < options.max_attempts;
    let index = RETRY_PROFILES
        .iter()
        .position(|profile| profile.name == last.profile.name)
        .unwrap_or(0);
    let smaller = RETRY_PROFILES.get(index + 1).copied();
    let retry = |why: String,
                 note: &str,
                 profile: Option<RetryProfile>,
                 renderer: Option<AttemptRenderer>,
                 encoder: Option<AttemptEncoder>,
                 delay: Option<u64>| RetryDecision::Retry {
        delay_ms: delay.unwrap_or_else(|| backoff(history.len())),
        profile: profile.unwrap_or(RETRY_PROFILES[index]),
        renderer: renderer.unwrap_or(last.renderer),
        encoder: encoder.unwrap_or(last.encoder),
        reason: format!("{why}{note}"),
    };
    let previous = history.len().checked_sub(2).map(|at| &history[at]);
    let same_point = previous.is_some_and(|previous| {
        previous.failure.phase == failure.phase && previous.failure.frame == failure.frame
    });
    let recurred_loss = GPU_LOSSES.contains(&code)
        && previous.is_some_and(|previous| {
            previous.renderer == AttemptRenderer::Gpu
                && (GPU_LOSSES.contains(&previous.failure.code)
                    || previous.failure.code == FailureClass::DeviceHung)
                && previous.failure.frame == failure.frame
        });
    if code == FailureClass::DeviceHung || recurred_loss {
        if last.renderer == AttemptRenderer::Gpu && options.cpu_renderer && attempts_left {
            return retry(
                format!(
                    "{code}: the export's own GPU work stops the GPU; retrying on the CPU renderer"
                ),
                note,
                None,
                Some(AttemptRenderer::Cpu),
                None,
                None,
            );
        }
        let why = if last.renderer == AttemptRenderer::Cpu {
            "it failed on the CPU renderer too"
        } else {
            "there is no CPU renderer to retry on"
        };
        return stop(
            format!("{code}: the export's own GPU work stops the GPU, and {why}"),
            note,
            FailureClass::DeviceHung,
        );
    }
    if code == FailureClass::Defect {
        let defects = history
            .iter()
            .filter(|attempt| attempt.failure.code == FailureClass::Defect)
            .count();
        if defects > 1 {
            return stop(
                "DEFECT again on a fresh attempt: the engine fails this export the same way".into(),
                note,
                code,
            );
        }
        if !attempts_left {
            return stop(
                format!("all {} attempts failed", options.max_attempts),
                note,
                code,
            );
        }
        return retry(
            "DEFECT: an engine fault; retrying once on a fresh host".into(),
            note,
            None,
            None,
            None,
            Some(0),
        );
    }
    if !retryable(failure) {
        return stop(
            format!("{code} at {} is not helped by a retry", failure.phase),
            note,
            code,
        );
    }
    if !attempts_left {
        return stop(
            format!("all {} attempts failed", options.max_attempts),
            note,
            code,
        );
    }
    if MEMORY.contains(&code) {
        return match smaller {
            Some(smaller) => retry(
                format!("{code}: retrying with less in flight ({})", smaller.name),
                note,
                Some(smaller),
                None,
                None,
                None,
            ),
            None if code == FailureClass::OutOfMemory
                && failure.resource == MemoryResource::Gpu
                && last.renderer == AttemptRenderer::Gpu
                && options.cpu_renderer =>
            {
                retry(
                    format!(
                        "{code} with the smallest profile ({}): the GPU cannot hold the export; \
                         retrying on the CPU renderer",
                        last.profile.name
                    ),
                    note,
                    None,
                    Some(AttemptRenderer::Cpu),
                    None,
                    None,
                )
            }
            None => stop(
                format!(
                    "{code} with the smallest profile ({}): nothing left to reduce",
                    last.profile.name
                ),
                note,
                code,
            ),
        };
    }
    if failure.phase == "encode" && last.encoder == AttemptEncoder::Default {
        if options.software_encoder {
            return retry(
                format!("{code} while encoding: retrying with the software video encoder"),
                note,
                None,
                None,
                Some(AttemptEncoder::Software),
                None,
            );
        }
        note = " (no software video encoder to switch to)";
    }
    if code == FailureClass::ResourceBusy {
        let delay = failure
            .retry_after_ms
            .unwrap_or(0)
            .max(backoff(history.len()));
        return retry(
            format!("{code}: retrying when the device may be free"),
            note,
            None,
            None,
            None,
            Some(delay),
        );
    }
    let repeated = same_point && previous.is_some_and(|previous| previous.failure.code == code);
    if !repeated {
        return retry(
            format!("{code}: retrying on a fresh device"),
            note,
            None,
            None,
            None,
            None,
        );
    }
    match smaller {
        Some(smaller) => retry(
            format!(
                "{code} again at the same point: retrying with less in flight ({})",
                smaller.name
            ),
            note,
            Some(smaller),
            None,
            None,
            None,
        ),
        None => stop(
            format!("{code} again at the same point with the smallest profile: stopping early"),
            note,
            code,
        ),
    }
}

#[cfg(test)]
#[path = "export_policy_tests.rs"]
mod tests;