Skip to main content

alpha2_render/
error.rs

1use std::fmt;
2
3/// Render input or output failure.
4#[derive(Copy, Clone, Debug, Eq, PartialEq)]
5#[non_exhaustive]
6pub enum RenderError {
7    /// Render targets must have non-zero dimensions.
8    ZeroDimension,
9    /// Render dimensions exceed the configured or physical device limit.
10    DimensionTooLarge,
11    /// Colors must be finite, in the unit interval, and premultiplied.
12    InvalidColor,
13    /// A layer transform is non-finite, has zero scale, or invalid opacity.
14    InvalidVisual,
15    /// An effect parameter is non-finite or outside its supported range.
16    InvalidEffectParameter,
17    /// No effect with the requested identity is registered.
18    UnknownEffect,
19    /// Supplied parameter names or types do not match the effect schema.
20    InvalidEffectParams,
21    /// An uploaded effect resource has an invalid identity, shape, or payload.
22    InvalidEffectResource,
23    /// An effect invocation omitted a required registered resource.
24    MissingEffectResource,
25    /// A resource identity resolves to a different representation than required.
26    EffectResourceKindMismatch,
27    /// A transition invocation omitted its second texture.
28    MissingEffectInput,
29    /// A frame needs a caption, text generator or layout its host did not prepare at this size.
30    MissingText,
31    /// RGBA input byte length does not match the declared image size.
32    InvalidImageData,
33    /// A rendered texture could not be read back to host memory, and where.
34    TextureReadback(ReadbackFailure),
35    /// An internally constructed render graph was structurally invalid.
36    InvalidGraph,
37    /// A native texture could not synchronize with the submission, with the platform's device
38    /// status when available.
39    ExternalTextureSync(Option<alpha2_media::GpuFault>),
40    /// Caller NV12 planes are not R8 luma and RG8 chroma render attachments at full and half size.
41    InvalidPlaneTarget,
42    /// GPU work did not complete within the renderer's wait timeout.
43    GpuTimeout,
44    /// The device completed a submission without running it (a readback lacked its canary). The
45    /// renderer refuses further work; only a new process gets a working device.
46    GpuWorkDropped,
47    /// The GPU rejected this frame's work (failed allocation or invalid use). Nothing ran, the
48    /// device is fine, and the renderer kept nothing of the frame.
49    Gpu {
50        /// The class of error the GPU reported.
51        kind: alpha2_gpu::GpuErrorKind,
52    },
53    /// The device can no longer create the resources a frame needs; the renderer refuses further
54    /// work.
55    GpuDeviceLost,
56    /// The device was lost after a recent submission kept the GPU busy for at least half the OS
57    /// watchdog ([`alpha2_gpu::hung_threshold_ms`]), or submissions completed together did and
58    /// ran more than [`alpha2_gpu::MARGIN`] times their predicted time. Rerunning the same work
59    /// will hang again.
60    GpuDeviceHung {
61        /// The export frame the long submission rendered, when known; for several, the first's.
62        frame: Option<u64>,
63        /// That frame's timeline time, in ticks, when known.
64        time_ticks: Option<i64>,
65        /// How long the submission, or the submissions together, kept the GPU busy, in
66        /// milliseconds.
67        gpu_ms: u32,
68        /// Submissions whose completions were seen together, so only their total is known; 1 for
69        /// one submission.
70        submissions: u32,
71        /// Whether `gpu_ms` is measured; otherwise a completion was seen late and it is an upper
72        /// bound.
73        measured: bool,
74        /// The watchdog it was measured against, in milliseconds.
75        watchdog_ms: u32,
76    },
77    /// An HDR (PQ or HLG) source met [`crate::ColorPolicy::RejectHdr`].
78    UnsupportedHdr,
79    /// A source belongs to the other backend (CPU source on GPU renderer or vice versa).
80    InvalidSource,
81    /// A pack was asked for an output color it cannot write: an HDR transfer, or primaries
82    /// other than BT.709 or BT.601. Packs follow the color's matrix and range only.
83    UnsupportedOutputColor(alpha2_media::ColorMetadata),
84    /// A pass wrote more uniform data than its frame reserved, a defect in the renderer. The
85    /// frame fails; the renderer stays usable.
86    UniformArenaOverrun,
87    /// The textures one frame holds at once need more than the GPU memory budget the adapter
88    /// reports, so the frame was not drawn. Freeing idle textures cannot make it fit.
89    FrameExceedsGpuMemory {
90        /// Bytes of textures the frame holds at its peak.
91        needed: u64,
92        /// The adapter's memory budget, in bytes.
93        budget: u64,
94    },
95}
96
97impl fmt::Display for RenderError {
98    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
99        match self {
100            Self::ZeroDimension => formatter.write_str("render dimensions must be non-zero"),
101            Self::DimensionTooLarge => {
102                formatter.write_str("render dimensions exceed the supported texture budget")
103            }
104            Self::InvalidColor => {
105                formatter.write_str(
106                    "color components must be finite values from zero to one, premultiplied: none above alpha",
107                )
108            }
109            Self::InvalidVisual => formatter.write_str("layer presentation values are invalid"),
110            Self::InvalidEffectParameter => formatter.write_str("effect parameter is invalid"),
111            Self::UnknownEffect => formatter.write_str("effect is not registered"),
112            Self::InvalidEffectParams => {
113                formatter.write_str("effect parameters do not match schema")
114            }
115            Self::InvalidEffectResource => formatter.write_str("effect resource is invalid"),
116            Self::MissingEffectResource => {
117                formatter.write_str("effect resource is missing or not registered")
118            }
119            Self::MissingText => {
120                formatter.write_str("text was not prepared for this frame and size")
121            }
122            Self::EffectResourceKindMismatch => {
123                formatter.write_str("effect resource kind does not match schema")
124            }
125            Self::MissingEffectInput => formatter.write_str("effect input texture is missing"),
126            Self::InvalidImageData => {
127                formatter.write_str("RGBA byte length does not match the image size")
128            }
129            Self::TextureReadback(failure) => {
130                write!(formatter, "GPU texture readback failed: {failure}")
131            }
132            Self::InvalidGraph => formatter.write_str("render graph is structurally invalid"),
133            Self::ExternalTextureSync(None) => {
134                formatter.write_str("external texture synchronization failed")
135            }
136            Self::ExternalTextureSync(Some(fault)) => write!(
137                formatter,
138                "external texture synchronization failed ({})",
139                fault.as_str()
140            ),
141            Self::InvalidPlaneTarget => formatter.write_str(
142                "NV12 plane targets must be an R8 luma and an RG8 chroma render attachment at the output size and half of it",
143            ),
144            Self::GpuTimeout => formatter.write_str(GPU_TIMEOUT_MESSAGE),
145            Self::GpuWorkDropped => formatter.write_str(GPU_WORK_DROPPED_MESSAGE),
146            Self::Gpu { kind } => write!(
147                formatter,
148                "the GPU rejected this frame's work with a {} error",
149                kind.as_str()
150            ),
151            Self::GpuDeviceLost => formatter.write_str(GPU_DEVICE_LOST_MESSAGE),
152            Self::GpuDeviceHung {
153                frame,
154                gpu_ms,
155                submissions,
156                measured,
157                watchdog_ms,
158                ..
159            } => device_hung(
160                formatter,
161                *frame,
162                (*gpu_ms, *submissions, *measured),
163                *watchdog_ms,
164            ),
165            Self::UnsupportedHdr => {
166                formatter.write_str("the color policy refuses HDR (PQ or HLG) sources")
167            }
168            Self::InvalidSource => {
169                formatter.write_str("the source belongs to another renderer backend")
170            }
171            Self::UnsupportedOutputColor(color) => write!(
172                formatter,
173                "the output color ({:?} primaries, {:?} transfer) cannot be packed: packs write \
174                 BT.709 or BT.601 primaries with an SDR transfer",
175                color.primaries, color.transfer
176            ),
177            Self::UniformArenaOverrun => formatter.write_str(UNIFORM_ARENA_OVERRUN_MESSAGE),
178            Self::FrameExceedsGpuMemory { needed, budget } => {
179                frame_exceeds_memory(formatter, *needed, *budget)
180            }
181        }
182    }
183}
184
185impl std::error::Error for RenderError {}
186
187/// Where a texture readback failed.
188///
189/// `wgpu`'s `BufferAsyncError` carries no cause, so [`Self::MapFailed`] only says mapping was
190/// refused; device diagnostics (`alpha2_gpu::GpuDiagnosticLog`) may explain it. None of these
191/// implies memory exhaustion.
192#[derive(Copy, Clone, Debug, Eq, PartialEq)]
193#[non_exhaustive]
194pub enum ReadbackFailure {
195    /// The rendered texture's format or size is not one the readback packs.
196    UnsupportedTarget,
197    /// A row, plane, or buffer size overflowed or could not be represented.
198    Layout,
199    /// Mapping was requested twice for one readback.
200    DuplicateMapRequest,
201    /// The GPU refused to map the staging buffer.
202    MapFailed,
203    /// The mapping callback was dropped without reporting.
204    CallbackDropped,
205    /// The staging buffer was read before its mapping succeeded.
206    NotMapped,
207    /// A caller-supplied plane destination is too small for the frame.
208    DestinationTooSmall,
209    /// The device was polled for a submission it did not recognise.
210    SubmissionMismatch,
211}
212
213impl ReadbackFailure {
214    /// Stable lowercase name for logs and protocols.
215    #[must_use]
216    pub const fn as_str(self) -> &'static str {
217        match self {
218            Self::UnsupportedTarget => "unsupported-target",
219            Self::Layout => "layout",
220            Self::DuplicateMapRequest => "duplicate-map-request",
221            Self::MapFailed => "map-failed",
222            Self::CallbackDropped => "callback-dropped",
223            Self::NotMapped => "not-mapped",
224            Self::DestinationTooSmall => "destination-too-small",
225            Self::SubmissionMismatch => "submission-mismatch",
226        }
227    }
228}
229
230impl fmt::Display for ReadbackFailure {
231    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
232        formatter.write_str(self.as_str())
233    }
234}
235
236fn device_hung(
237    formatter: &mut fmt::Formatter<'_>,
238    frame: Option<u64>,
239    (gpu_ms, submissions, measured): (u32, u32, bool),
240    watchdog_ms: u32,
241) -> fmt::Result {
242    formatter.write_str("GPU device hung: ")?;
243    let ran = if measured { "ran" } else { "ran up to" };
244    let within = if measured { "in" } else { "within" };
245    match (frame, submissions) {
246        (Some(frame), 0 | 1) => {
247            write!(
248                formatter,
249                "frame {frame} {ran} {gpu_ms} ms in one submission"
250            )?;
251        }
252        (None, 0 | 1) => write!(formatter, "a submission {ran} {gpu_ms} ms")?,
253        (Some(frame), submissions) => write!(
254            formatter,
255            "{submissions} submissions from frame {frame} on completed together \
256                 {within} {gpu_ms} ms"
257        )?,
258        (None, submissions) => write!(
259            formatter,
260            "{submissions} submissions completed together {within} {gpu_ms} ms"
261        )?,
262    }
263    write!(
264        formatter,
265        " against a {watchdog_ms} ms watchdog; this work stops the GPU, so it is not \
266             retried on the GPU"
267    )
268}
269
270fn frame_exceeds_memory(
271    formatter: &mut fmt::Formatter<'_>,
272    needed: u64,
273    budget: u64,
274) -> fmt::Result {
275    write!(
276        formatter,
277        "GPU out of memory: one frame needs {needed} bytes of textures, more than the \
278         {budget}-byte GPU memory budget"
279    )
280}
281
282const UNIFORM_ARENA_OVERRUN_MESSAGE: &str =
283    "a pass wrote more uniform data than its frame reserved; this is a renderer defect";
284
285/// Message every GPU wait timeout carries, so hosts can classify errors from text alone.
286pub use alpha2_media::GPU_TIMEOUT_MESSAGE;
287
288/// Message of [`RenderError::GpuWorkDropped`]; names a lost device, as hosts classify it.
289pub const GPU_WORK_DROPPED_MESSAGE: &str = "GPU device lost: it completed submitted work without \
290     running it (a readback lacked its canary), so this process can no longer render";
291
292/// The message of [`RenderError::GpuDeviceLost`].
293pub const GPU_DEVICE_LOST_MESSAGE: &str = "GPU device lost: it can no longer make the resources \
294     a frame needs, so this process can no longer render";
295
296/// Default native wait for GPU work before giving up.
297pub const DEFAULT_GPU_WAIT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
298
299#[cfg(not(target_arch = "wasm32"))]
300#[allow(clippy::needless_pass_by_value)] // Shaped for `map_err`.
301pub(crate) fn poll_error(error: wgpu::PollError) -> RenderError {
302    match error {
303        wgpu::PollError::Timeout => RenderError::GpuTimeout,
304        wgpu::PollError::WrongSubmissionIndex(..) => {
305            RenderError::TextureReadback(ReadbackFailure::SubmissionMismatch)
306        }
307    }
308}