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/// A classified export failure, as the retry policy reads it.
157#[derive(Clone, Debug, PartialEq, Eq)]
158pub struct AttemptFailure {
159    /// Its class.
160    pub code: FailureClass,
161    /// The phase it failed in (`prepare`, `decode`, `render`, `encode`, `publish`).
162    pub phase: String,
163    /// The export frame it failed at, when known.
164    pub frame: Option<u64>,
165    /// A wait the failure asks for before retrying, in milliseconds.
166    pub retry_after_ms: Option<u64>,
167}
168
169/// One failed attempt.
170#[derive(Clone, Debug, PartialEq)]
171pub struct AttemptOutcome {
172    /// Its failure.
173    pub failure: AttemptFailure,
174    /// Its budget profile.
175    pub profile: RetryProfile,
176    /// Its renderer.
177    pub renderer: AttemptRenderer,
178    /// Its video encoder.
179    pub encoder: AttemptEncoder,
180}
181
182/// What the host can change between attempts.
183#[derive(Clone, Copy, Debug)]
184pub struct RetryOptions {
185    /// Total attempts, the first included.
186    pub max_attempts: usize,
187    /// Whether an attempt can run on the CPU renderer. Default false.
188    pub cpu_renderer: bool,
189    /// Whether a software video encoder exists for the export's codec.
190    pub software_encoder: bool,
191}
192
193impl Default for RetryOptions {
194    fn default() -> Self {
195        Self {
196            max_attempts: 3,
197            cpu_renderer: false,
198            software_encoder: true,
199        }
200    }
201}
202
203/// The policy's answer.
204#[derive(Clone, Debug, PartialEq)]
205pub enum RetryDecision {
206    /// Run another attempt after `delay_ms` with these settings.
207    Retry {
208        /// Milliseconds to wait first.
209        delay_ms: u64,
210        /// The next attempt's budget profile.
211        profile: RetryProfile,
212        /// Its renderer.
213        renderer: AttemptRenderer,
214        /// Its video encoder.
215        encoder: AttemptEncoder,
216        /// Why, for the report.
217        reason: String,
218    },
219    /// Stop with `code` (a GPU loss recurring at one frame stops as `DEVICE_HUNG`).
220    Stop {
221        /// Why, for the report.
222        reason: String,
223        /// The class the export fails with.
224        code: Option<FailureClass>,
225    },
226}
227
228const PERMANENT: [FailureClass; 7] = [
229    FailureClass::Cancelled,
230    FailureClass::InvalidInput,
231    FailureClass::ValidationFailed,
232    FailureClass::ResourceLimit,
233    FailureClass::StorageQuotaExceeded,
234    FailureClass::OutputIoFailed,
235    FailureClass::DeviceHung,
236];
237const MEMORY: [FailureClass; 2] = [FailureClass::OutOfMemory, FailureClass::AllocationFailed];
238const GPU_LOSSES: [FailureClass; 2] = [FailureClass::DeviceLost, FailureClass::GpuTimeout];
239
240/// Whether a retry could help `failure` at all (the CPU renderer aside).
241#[must_use]
242pub fn retryable(failure: &AttemptFailure) -> bool {
243    !PERMANENT.contains(&failure.code) && failure.phase != "download"
244}
245
246fn backoff(failed: usize) -> u64 {
247    1_000_u64.saturating_mul(1 << failed.saturating_sub(1).min(16))
248}
249
250/// Whether and how to retry after the failed attempts in `history`, oldest first.
251///
252/// An export is retried whole on a fresh device; attempts change the in-flight budget, the
253/// renderer and the video encoder, never the output settings. A GPU that hangs on the export's
254/// own work moves to the CPU renderer; memory exhaustion steps down a profile; an encode failure
255/// retries once in software; a busy resource waits; an engine fault (`DEFECT`) retries once,
256/// unchanged and at once; anything else transient retries unchanged and steps down only when it
257/// recurs at the same point.
258// One rule after another, in the reference policy's order.
259#[allow(clippy::too_many_lines)]
260#[must_use]
261pub fn decide_retry(history: &[AttemptOutcome], options: RetryOptions) -> RetryDecision {
262    let Some(last) = history.last() else {
263        return RetryDecision::Stop {
264            reason: "nothing failed".into(),
265            code: None,
266        };
267    };
268    let failure = &last.failure;
269    let code = failure.code;
270    let mut note = "";
271    let stop = |why: String, note: &str, final_code: FailureClass| RetryDecision::Stop {
272        reason: format!("{why}{note}"),
273        code: Some(final_code),
274    };
275    let attempts_left = history.len() < options.max_attempts;
276    let index = RETRY_PROFILES
277        .iter()
278        .position(|profile| profile.name == last.profile.name)
279        .unwrap_or(0);
280    let smaller = RETRY_PROFILES.get(index + 1).copied();
281    let retry = |why: String,
282                 note: &str,
283                 profile: Option<RetryProfile>,
284                 renderer: Option<AttemptRenderer>,
285                 encoder: Option<AttemptEncoder>,
286                 delay: Option<u64>| RetryDecision::Retry {
287        delay_ms: delay.unwrap_or_else(|| backoff(history.len())),
288        profile: profile.unwrap_or(RETRY_PROFILES[index]),
289        renderer: renderer.unwrap_or(last.renderer),
290        encoder: encoder.unwrap_or(last.encoder),
291        reason: format!("{why}{note}"),
292    };
293    let previous = history.len().checked_sub(2).map(|at| &history[at]);
294    let same_point = previous.is_some_and(|previous| {
295        previous.failure.phase == failure.phase && previous.failure.frame == failure.frame
296    });
297    let recurred_loss = GPU_LOSSES.contains(&code)
298        && previous.is_some_and(|previous| {
299            previous.renderer == AttemptRenderer::Gpu
300                && (GPU_LOSSES.contains(&previous.failure.code)
301                    || previous.failure.code == FailureClass::DeviceHung)
302                && previous.failure.frame == failure.frame
303        });
304    if code == FailureClass::DeviceHung || recurred_loss {
305        if last.renderer == AttemptRenderer::Gpu && options.cpu_renderer && attempts_left {
306            return retry(
307                format!(
308                    "{code}: the export's own GPU work stops the GPU; retrying on the CPU renderer"
309                ),
310                note,
311                None,
312                Some(AttemptRenderer::Cpu),
313                None,
314                None,
315            );
316        }
317        let why = if last.renderer == AttemptRenderer::Cpu {
318            "it failed on the CPU renderer too"
319        } else {
320            "there is no CPU renderer to retry on"
321        };
322        return stop(
323            format!("{code}: the export's own GPU work stops the GPU, and {why}"),
324            note,
325            FailureClass::DeviceHung,
326        );
327    }
328    if code == FailureClass::Defect {
329        let defects = history
330            .iter()
331            .filter(|attempt| attempt.failure.code == FailureClass::Defect)
332            .count();
333        if defects > 1 {
334            return stop(
335                "DEFECT again on a fresh attempt: the engine fails this export the same way".into(),
336                note,
337                code,
338            );
339        }
340        if !attempts_left {
341            return stop(
342                format!("all {} attempts failed", options.max_attempts),
343                note,
344                code,
345            );
346        }
347        return retry(
348            "DEFECT: an engine fault; retrying once on a fresh host".into(),
349            note,
350            None,
351            None,
352            None,
353            Some(0),
354        );
355    }
356    if !retryable(failure) {
357        return stop(
358            format!("{code} at {} is not helped by a retry", failure.phase),
359            note,
360            code,
361        );
362    }
363    if !attempts_left {
364        return stop(
365            format!("all {} attempts failed", options.max_attempts),
366            note,
367            code,
368        );
369    }
370    if MEMORY.contains(&code) {
371        return match smaller {
372            Some(smaller) => retry(
373                format!("{code}: retrying with less in flight ({})", smaller.name),
374                note,
375                Some(smaller),
376                None,
377                None,
378                None,
379            ),
380            None => stop(
381                format!(
382                    "{code} with the smallest profile ({}): nothing left to reduce",
383                    last.profile.name
384                ),
385                note,
386                code,
387            ),
388        };
389    }
390    if failure.phase == "encode" && last.encoder == AttemptEncoder::Default {
391        if options.software_encoder {
392            return retry(
393                format!("{code} while encoding: retrying with the software video encoder"),
394                note,
395                None,
396                None,
397                Some(AttemptEncoder::Software),
398                None,
399            );
400        }
401        note = " (no software video encoder to switch to)";
402    }
403    if code == FailureClass::ResourceBusy {
404        let delay = failure
405            .retry_after_ms
406            .unwrap_or(0)
407            .max(backoff(history.len()));
408        return retry(
409            format!("{code}: retrying when the device may be free"),
410            note,
411            None,
412            None,
413            None,
414            Some(delay),
415        );
416    }
417    let repeated = same_point && previous.is_some_and(|previous| previous.failure.code == code);
418    if !repeated {
419        return retry(
420            format!("{code}: retrying on a fresh device"),
421            note,
422            None,
423            None,
424            None,
425            None,
426        );
427    }
428    match smaller {
429        Some(smaller) => retry(
430            format!(
431                "{code} again at the same point: retrying with less in flight ({})",
432                smaller.name
433            ),
434            note,
435            Some(smaller),
436            None,
437            None,
438            None,
439        ),
440        None => stop(
441            format!("{code} again at the same point with the smallest profile: stopping early"),
442            note,
443            code,
444        ),
445    }
446}
447
448#[cfg(test)]
449#[path = "export_policy_tests.rs"]
450mod tests;