1use alpha2_media::FailureClass;
5use alpha2_time::FrameRate;
6
7#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub enum AvcProfile {
10 High,
12 Main,
14 ConstrainedBaseline,
16}
17
18impl AvcProfile {
19 pub const LADDER: [Self; 3] = [Self::High, Self::Main, Self::ConstrainedBaseline];
21
22 #[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 #[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 Self::ConstrainedBaseline => (0x42, 0xe0),
40 }
41 }
42}
43
44struct AvcLevel {
46 frame: u64,
48 rate: u64,
50 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
64const 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#[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#[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#[derive(Clone, Copy, Debug, PartialEq)]
115pub struct RetryProfile {
116 pub name: &'static str,
118 pub memory_scale: f32,
120}
121
122pub 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
140pub enum AttemptRenderer {
141 Gpu,
143 Cpu,
145}
146
147#[derive(Clone, Copy, Debug, Eq, PartialEq)]
149pub enum AttemptEncoder {
150 Default,
152 Software,
154}
155
156#[derive(Clone, Copy, Debug, Eq, PartialEq)]
158pub enum MemoryResource {
159 Cpu,
161 Gpu,
163 Js,
165 Wasm,
167 Unknown,
169}
170
171impl MemoryResource {
172 #[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#[derive(Clone, Debug, PartialEq, Eq)]
188pub struct AttemptFailure {
189 pub code: FailureClass,
191 pub resource: MemoryResource,
193 pub phase: String,
195 pub frame: Option<u64>,
197 pub retry_after_ms: Option<u64>,
199}
200
201#[derive(Clone, Debug, PartialEq)]
203pub struct AttemptOutcome {
204 pub failure: AttemptFailure,
206 pub profile: RetryProfile,
208 pub renderer: AttemptRenderer,
210 pub encoder: AttemptEncoder,
212}
213
214#[derive(Clone, Copy, Debug)]
216pub struct RetryOptions {
217 pub max_attempts: usize,
219 pub cpu_renderer: bool,
221 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#[derive(Clone, Debug, PartialEq)]
237pub enum RetryDecision {
238 Retry {
240 delay_ms: u64,
242 profile: RetryProfile,
244 renderer: AttemptRenderer,
246 encoder: AttemptEncoder,
248 reason: String,
250 },
251 Stop {
253 reason: String,
255 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#[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#[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;