Skip to main content

alpha2_host_core/
export_policy.rs

1//! Export policy every native host applies: the H.264 profile ladder platform encoders are tried
2//! with, and whether and how a failed export is retried.
3
4use alpha2_media::FailureClass;
5use alpha2_time::FrameRate;
6
7/// An H.264 profile a platform encoder is asked for.
8#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub enum AvcProfile {
10    /// High (`profile_idc` 100).
11    High,
12    /// Main (`profile_idc` 77).
13    Main,
14    /// Constrained Baseline: Baseline with `constraint_set1`, decodable by every H.264 decoder.
15    ConstrainedBaseline,
16}
17
18impl AvcProfile {
19    /// The ladder, tried in this order.
20    pub const LADDER: [Self; 3] = [Self::High, Self::Main, Self::ConstrainedBaseline];
21
22    /// The profile's name, as reports spell it.
23    #[must_use]
24    pub const fn as_str(self) -> &'static str {
25        match self {
26            Self::High => "High",
27            Self::Main => "Main",
28            Self::ConstrainedBaseline => "Constrained Baseline",
29        }
30    }
31
32    /// `profile_idc` and the constraint flags byte, as an `avc1.PPCCLL` codec string carries them.
33    #[must_use]
34    pub const fn idc_and_constraints(self) -> (u8, u8) {
35        match self {
36            Self::High => (0x64, 0x00),
37            Self::Main => (0x4d, 0x00),
38            // constraint_set0, 1 and 2: decodable by Baseline, Main and Extended decoders.
39            Self::ConstrainedBaseline => (0x42, 0xe0),
40        }
41    }
42}
43
44/// One row of ITU-T H.264 Table A-1.
45struct AvcLevel {
46    /// `MaxFS`: macroblocks per frame.
47    frame: u64,
48    /// `MaxMBPS`: macroblocks per second.
49    rate: u64,
50    /// `MaxBR` in bits per second.
51    bitrate: u64,
52    level_idc: u8,
53}
54
55const fn row(frame: u64, rate: u64, bitrate: u64, level_idc: u8) -> AvcLevel {
56    AvcLevel {
57        frame,
58        rate,
59        bitrate,
60        level_idc,
61    }
62}
63
64/// H.264 levels (ITU-T H.264 Table A-1), lowest first.
65const AVC_LEVELS: [AvcLevel; 19] = [
66    row(99, 1_485, 64_000, 10),
67    row(396, 3_000, 192_000, 11),
68    row(396, 6_000, 384_000, 12),
69    row(396, 11_880, 768_000, 13),
70    row(396, 11_880, 2_000_000, 20),
71    row(792, 19_800, 4_000_000, 21),
72    row(1_620, 20_250, 4_000_000, 22),
73    row(1_620, 40_500, 10_000_000, 30),
74    row(3_600, 108_000, 14_000_000, 31),
75    row(5_120, 216_000, 20_000_000, 32),
76    row(8_192, 245_760, 20_000_000, 40),
77    row(8_192, 245_760, 50_000_000, 41),
78    row(8_704, 522_240, 50_000_000, 42),
79    row(22_080, 589_824, 135_000_000, 50),
80    row(36_864, 983_040, 240_000_000, 51),
81    row(36_864, 2_073_600, 240_000_000, 52),
82    row(139_264, 4_177_920, 240_000_000, 60),
83    row(139_264, 8_355_840, 480_000_000, 61),
84    row(139_264, 16_711_680, 800_000_000, 62),
85];
86
87/// The lowest `level_idc` that holds `width` x `height` at `frame_rate` and `bitrate`, else the
88/// highest level.
89#[must_use]
90pub fn avc_level(width: u32, height: u32, frame_rate: FrameRate, bitrate: u64) -> u8 {
91    let frame = u64::from(width.div_ceil(16)) * u64::from(height.div_ceil(16));
92    let (num, den) = (
93        u64::from(frame_rate.numerator()),
94        u64::from(frame_rate.denominator()),
95    );
96    AVC_LEVELS
97        .iter()
98        .find(|level| {
99            frame <= level.frame
100                && frame.saturating_mul(num) <= level.rate.saturating_mul(den)
101                && bitrate <= level.bitrate
102        })
103        .map_or(62, |level| level.level_idc)
104}
105
106/// The `avc1.PPCCLL` codec string of `profile` at `level`.
107#[must_use]
108pub fn avc_codec_string(profile: AvcProfile, level: u8) -> String {
109    let (idc, constraints) = profile.idc_and_constraints();
110    format!("avc1.{idc:02x}{constraints:02x}{level:02x}")
111}
112
113/// An in-flight budget scale for an attempt.
114#[derive(Clone, Copy, Debug, PartialEq)]
115pub struct RetryProfile {
116    /// Matched by name in the history.
117    pub name: &'static str,
118    /// Fraction of each in-flight budget, in `(0, 1]`.
119    pub memory_scale: f32,
120}
121
122/// Full, half and quarter budgets.
123pub const RETRY_PROFILES: [RetryProfile; 3] = [
124    RetryProfile {
125        name: "default",
126        memory_scale: 1.0,
127    },
128    RetryProfile {
129        name: "reduced",
130        memory_scale: 0.5,
131    },
132    RetryProfile {
133        name: "minimal",
134        memory_scale: 0.25,
135    },
136];
137
138/// Which renderer an attempt used.
139#[derive(Clone, Copy, Debug, Eq, PartialEq)]
140pub enum AttemptRenderer {
141    /// The GPU renderer.
142    Gpu,
143    /// The CPU renderer.
144    Cpu,
145}
146
147/// Which video encoder an attempt used.
148#[derive(Clone, Copy, Debug, Eq, PartialEq)]
149pub enum AttemptEncoder {
150    /// The platform's choice, hardware first.
151    Default,
152    /// A software encoder.
153    Software,
154}
155
156/// The memory a failure's evidence names, as an export failure's `resource` spells it.
157#[derive(Clone, Copy, Debug, Eq, PartialEq)]
158pub enum MemoryResource {
159    /// Host memory.
160    Cpu,
161    /// GPU memory.
162    Gpu,
163    /// The JavaScript heap.
164    Js,
165    /// The engine's wasm linear memory.
166    Wasm,
167    /// No region named.
168    Unknown,
169}
170
171impl MemoryResource {
172    /// Parses its wire name (`cpu`, `gpu`, `js`, `wasm`, `unknown`).
173    #[must_use]
174    pub fn parse(name: &str) -> Option<Self> {
175        match name {
176            "cpu" => Some(Self::Cpu),
177            "gpu" => Some(Self::Gpu),
178            "js" => Some(Self::Js),
179            "wasm" => Some(Self::Wasm),
180            "unknown" => Some(Self::Unknown),
181            _ => None,
182        }
183    }
184}
185
186/// A classified export failure, as the retry policy reads it.
187#[derive(Clone, Debug, PartialEq, Eq)]
188pub struct AttemptFailure {
189    /// Its class.
190    pub code: FailureClass,
191    /// The memory its evidence names.
192    pub resource: MemoryResource,
193    /// The phase it failed in (`prepare`, `decode`, `render`, `encode`, `publish`).
194    pub phase: String,
195    /// The export frame it failed at, when known.
196    pub frame: Option<u64>,
197    /// A wait the failure asks for before retrying, in milliseconds.
198    pub retry_after_ms: Option<u64>,
199}
200
201/// One failed attempt.
202#[derive(Clone, Debug, PartialEq)]
203pub struct AttemptOutcome {
204    /// Its failure.
205    pub failure: AttemptFailure,
206    /// Its budget profile.
207    pub profile: RetryProfile,
208    /// Its renderer.
209    pub renderer: AttemptRenderer,
210    /// Its video encoder.
211    pub encoder: AttemptEncoder,
212}
213
214/// What the host can change between attempts.
215#[derive(Clone, Copy, Debug)]
216pub struct RetryOptions {
217    /// Total attempts, the first included.
218    pub max_attempts: usize,
219    /// Whether an attempt can run on the CPU renderer. Default false.
220    pub cpu_renderer: bool,
221    /// Whether a software video encoder exists for the export's codec.
222    pub software_encoder: bool,
223}
224
225impl Default for RetryOptions {
226    fn default() -> Self {
227        Self {
228            max_attempts: 3,
229            cpu_renderer: false,
230            software_encoder: true,
231        }
232    }
233}
234
235/// The policy's answer.
236#[derive(Clone, Debug, PartialEq)]
237pub enum RetryDecision {
238    /// Run another attempt after `delay_ms` with these settings.
239    Retry {
240        /// Milliseconds to wait first.
241        delay_ms: u64,
242        /// The next attempt's budget profile.
243        profile: RetryProfile,
244        /// Its renderer.
245        renderer: AttemptRenderer,
246        /// Its video encoder.
247        encoder: AttemptEncoder,
248        /// Why, for the report.
249        reason: String,
250    },
251    /// Stop with `code` (a GPU loss recurring at one frame stops as `DEVICE_HUNG`).
252    Stop {
253        /// Why, for the report.
254        reason: String,
255        /// The class the export fails with.
256        code: Option<FailureClass>,
257    },
258}
259
260const PERMANENT: [FailureClass; 7] = [
261    FailureClass::Cancelled,
262    FailureClass::InvalidInput,
263    FailureClass::ValidationFailed,
264    FailureClass::ResourceLimit,
265    FailureClass::StorageQuotaExceeded,
266    FailureClass::OutputIoFailed,
267    FailureClass::DeviceHung,
268];
269const MEMORY: [FailureClass; 2] = [FailureClass::OutOfMemory, FailureClass::AllocationFailed];
270const GPU_LOSSES: [FailureClass; 2] = [FailureClass::DeviceLost, FailureClass::GpuTimeout];
271
272/// Whether a retry could help `failure` at all (the CPU renderer aside).
273#[must_use]
274pub fn retryable(failure: &AttemptFailure) -> bool {
275    !PERMANENT.contains(&failure.code) && failure.phase != "download"
276}
277
278fn backoff(failed: usize) -> u64 {
279    1_000_u64.saturating_mul(1 << failed.saturating_sub(1).min(16))
280}
281
282/// Whether and how to retry after the failed attempts in `history`, oldest first.
283///
284/// An export is retried whole on a fresh device; attempts change the in-flight budget, the
285/// renderer and the video encoder, never the output settings. A GPU that hangs on the export's
286/// own work moves to the CPU renderer; memory exhaustion steps down a profile, then GPU memory
287/// exhaustion moves to the CPU renderer; an encode failure retries once in software; a busy
288/// resource waits; an engine fault (`DEFECT`) retries once, unchanged and at once; anything else
289/// transient retries unchanged and steps down only when it recurs at the same point.
290// One rule after another, in the reference policy's order.
291#[allow(clippy::too_many_lines)]
292#[must_use]
293pub fn decide_retry(history: &[AttemptOutcome], options: RetryOptions) -> RetryDecision {
294    let Some(last) = history.last() else {
295        return RetryDecision::Stop {
296            reason: "nothing failed".into(),
297            code: None,
298        };
299    };
300    let failure = &last.failure;
301    let code = failure.code;
302    let mut note = "";
303    let stop = |why: String, note: &str, final_code: FailureClass| RetryDecision::Stop {
304        reason: format!("{why}{note}"),
305        code: Some(final_code),
306    };
307    let attempts_left = history.len() < options.max_attempts;
308    let index = RETRY_PROFILES
309        .iter()
310        .position(|profile| profile.name == last.profile.name)
311        .unwrap_or(0);
312    let smaller = RETRY_PROFILES.get(index + 1).copied();
313    let retry = |why: String,
314                 note: &str,
315                 profile: Option<RetryProfile>,
316                 renderer: Option<AttemptRenderer>,
317                 encoder: Option<AttemptEncoder>,
318                 delay: Option<u64>| RetryDecision::Retry {
319        delay_ms: delay.unwrap_or_else(|| backoff(history.len())),
320        profile: profile.unwrap_or(RETRY_PROFILES[index]),
321        renderer: renderer.unwrap_or(last.renderer),
322        encoder: encoder.unwrap_or(last.encoder),
323        reason: format!("{why}{note}"),
324    };
325    let previous = history.len().checked_sub(2).map(|at| &history[at]);
326    let same_point = previous.is_some_and(|previous| {
327        previous.failure.phase == failure.phase && previous.failure.frame == failure.frame
328    });
329    let recurred_loss = GPU_LOSSES.contains(&code)
330        && previous.is_some_and(|previous| {
331            previous.renderer == AttemptRenderer::Gpu
332                && (GPU_LOSSES.contains(&previous.failure.code)
333                    || previous.failure.code == FailureClass::DeviceHung)
334                && previous.failure.frame == failure.frame
335        });
336    if code == FailureClass::DeviceHung || recurred_loss {
337        if last.renderer == AttemptRenderer::Gpu && options.cpu_renderer && attempts_left {
338            return retry(
339                format!(
340                    "{code}: the export's own GPU work stops the GPU; retrying on the CPU renderer"
341                ),
342                note,
343                None,
344                Some(AttemptRenderer::Cpu),
345                None,
346                None,
347            );
348        }
349        let why = if last.renderer == AttemptRenderer::Cpu {
350            "it failed on the CPU renderer too"
351        } else {
352            "there is no CPU renderer to retry on"
353        };
354        return stop(
355            format!("{code}: the export's own GPU work stops the GPU, and {why}"),
356            note,
357            FailureClass::DeviceHung,
358        );
359    }
360    if code == FailureClass::Defect {
361        let defects = history
362            .iter()
363            .filter(|attempt| attempt.failure.code == FailureClass::Defect)
364            .count();
365        if defects > 1 {
366            return stop(
367                "DEFECT again on a fresh attempt: the engine fails this export the same way".into(),
368                note,
369                code,
370            );
371        }
372        if !attempts_left {
373            return stop(
374                format!("all {} attempts failed", options.max_attempts),
375                note,
376                code,
377            );
378        }
379        return retry(
380            "DEFECT: an engine fault; retrying once on a fresh host".into(),
381            note,
382            None,
383            None,
384            None,
385            Some(0),
386        );
387    }
388    if !retryable(failure) {
389        return stop(
390            format!("{code} at {} is not helped by a retry", failure.phase),
391            note,
392            code,
393        );
394    }
395    if !attempts_left {
396        return stop(
397            format!("all {} attempts failed", options.max_attempts),
398            note,
399            code,
400        );
401    }
402    if MEMORY.contains(&code) {
403        return match smaller {
404            Some(smaller) => retry(
405                format!("{code}: retrying with less in flight ({})", smaller.name),
406                note,
407                Some(smaller),
408                None,
409                None,
410                None,
411            ),
412            None if code == FailureClass::OutOfMemory
413                && failure.resource == MemoryResource::Gpu
414                && last.renderer == AttemptRenderer::Gpu
415                && options.cpu_renderer =>
416            {
417                retry(
418                    format!(
419                        "{code} with the smallest profile ({}): the GPU cannot hold the export; \
420                         retrying on the CPU renderer",
421                        last.profile.name
422                    ),
423                    note,
424                    None,
425                    Some(AttemptRenderer::Cpu),
426                    None,
427                    None,
428                )
429            }
430            None => stop(
431                format!(
432                    "{code} with the smallest profile ({}): nothing left to reduce",
433                    last.profile.name
434                ),
435                note,
436                code,
437            ),
438        };
439    }
440    if failure.phase == "encode" && last.encoder == AttemptEncoder::Default {
441        if options.software_encoder {
442            return retry(
443                format!("{code} while encoding: retrying with the software video encoder"),
444                note,
445                None,
446                None,
447                Some(AttemptEncoder::Software),
448                None,
449            );
450        }
451        note = " (no software video encoder to switch to)";
452    }
453    if code == FailureClass::ResourceBusy {
454        let delay = failure
455            .retry_after_ms
456            .unwrap_or(0)
457            .max(backoff(history.len()));
458        return retry(
459            format!("{code}: retrying when the device may be free"),
460            note,
461            None,
462            None,
463            None,
464            Some(delay),
465        );
466    }
467    let repeated = same_point && previous.is_some_and(|previous| previous.failure.code == code);
468    if !repeated {
469        return retry(
470            format!("{code}: retrying on a fresh device"),
471            note,
472            None,
473            None,
474            None,
475            None,
476        );
477    }
478    match smaller {
479        Some(smaller) => retry(
480            format!(
481                "{code} again at the same point: retrying with less in flight ({})",
482                smaller.name
483            ),
484            note,
485            Some(smaller),
486            None,
487            None,
488            None,
489        ),
490        None => stop(
491            format!("{code} again at the same point with the smallest profile: stopping early"),
492            note,
493            code,
494        ),
495    }
496}
497
498#[cfg(test)]
499#[path = "export_policy_tests.rs"]
500mod tests;