use alpha2_media::FailureClass;
use alpha2_time::FrameRate;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AvcProfile {
High,
Main,
ConstrainedBaseline,
}
impl AvcProfile {
pub const LADDER: [Self; 3] = [Self::High, Self::Main, Self::ConstrainedBaseline];
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::High => "High",
Self::Main => "Main",
Self::ConstrainedBaseline => "Constrained Baseline",
}
}
#[must_use]
pub const fn idc_and_constraints(self) -> (u8, u8) {
match self {
Self::High => (0x64, 0x00),
Self::Main => (0x4d, 0x00),
Self::ConstrainedBaseline => (0x42, 0xe0),
}
}
}
struct AvcLevel {
frame: u64,
rate: u64,
bitrate: u64,
level_idc: u8,
}
const fn row(frame: u64, rate: u64, bitrate: u64, level_idc: u8) -> AvcLevel {
AvcLevel {
frame,
rate,
bitrate,
level_idc,
}
}
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),
];
#[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)
}
#[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}")
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RetryProfile {
pub name: &'static str,
pub memory_scale: f32,
}
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,
},
];
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AttemptRenderer {
Gpu,
Cpu,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AttemptEncoder {
Default,
Software,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MemoryResource {
Cpu,
Gpu,
Js,
Wasm,
Unknown,
}
impl MemoryResource {
#[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,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AttemptFailure {
pub code: FailureClass,
pub resource: MemoryResource,
pub phase: String,
pub frame: Option<u64>,
pub retry_after_ms: Option<u64>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct AttemptOutcome {
pub failure: AttemptFailure,
pub profile: RetryProfile,
pub renderer: AttemptRenderer,
pub encoder: AttemptEncoder,
}
#[derive(Clone, Copy, Debug)]
pub struct RetryOptions {
pub max_attempts: usize,
pub cpu_renderer: bool,
pub software_encoder: bool,
}
impl Default for RetryOptions {
fn default() -> Self {
Self {
max_attempts: 3,
cpu_renderer: false,
software_encoder: true,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum RetryDecision {
Retry {
delay_ms: u64,
profile: RetryProfile,
renderer: AttemptRenderer,
encoder: AttemptEncoder,
reason: String,
},
Stop {
reason: String,
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];
#[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))
}
#[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;