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, Debug, PartialEq, Eq)]
158pub struct AttemptFailure {
159 pub code: FailureClass,
161 pub phase: String,
163 pub frame: Option<u64>,
165 pub retry_after_ms: Option<u64>,
167}
168
169#[derive(Clone, Debug, PartialEq)]
171pub struct AttemptOutcome {
172 pub failure: AttemptFailure,
174 pub profile: RetryProfile,
176 pub renderer: AttemptRenderer,
178 pub encoder: AttemptEncoder,
180}
181
182#[derive(Clone, Copy, Debug)]
184pub struct RetryOptions {
185 pub max_attempts: usize,
187 pub cpu_renderer: bool,
189 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#[derive(Clone, Debug, PartialEq)]
205pub enum RetryDecision {
206 Retry {
208 delay_ms: u64,
210 profile: RetryProfile,
212 renderer: AttemptRenderer,
214 encoder: AttemptEncoder,
216 reason: String,
218 },
219 Stop {
221 reason: String,
223 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#[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#[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;