mediadecode_ffmpeg/decoder/mod.rs
1use std::{collections::VecDeque, mem::ManuallyDrop, ptr};
2
3use ffmpeg_next::{
4 Codec, Packet, Rational,
5 codec::{
6 self,
7 Context,
8 // Bring the `Mut` / `Ref` traits into scope so `Packet::as_ptr` /
9 // `Packet::as_mut_ptr` resolve. They are aliased to avoid shadowing
10 // any future `Mut`/`Ref` types we might add — `cargo clippy` would
11 // otherwise flag them as "unused" without the alias and the import
12 // can mistakenly look unused. Confirmed in use by all `packet.as_ptr()`
13 // / `packet.as_mut_ptr()` call sites in this module.
14 packet::{Mut as PacketMut, Ref as PacketRef},
15 },
16 ffi::{
17 AVBufferRef, AVCodec, AVFrame, AVHWFramesContext, AVMediaType, av_buffer_ref, av_buffer_unref,
18 av_frame_move_ref, av_frame_unref, av_hwdevice_ctx_create, av_hwframe_transfer_data,
19 av_packet_ref, avcodec_alloc_context3, avcodec_free_context, avcodec_parameters_to_context,
20 },
21 frame,
22};
23
24/// Local FFI shims: FFmpeg entry points re-declared with `c_int` where
25/// the generated bindings use a closed Rust enum.
26///
27/// Constructing `AVCodecID` / `AVPixelFormat` / `AVSampleFormat` from a
28/// runtime integer that is not in this build's discriminant set is UB —
29/// and these are open C enums that FFmpeg extends in ABI-compatible
30/// releases. Declaring the same C symbol with `c_int` sidesteps the
31/// boundary entirely: both Rust declarations resolve to the same symbol
32/// at link time, and the integer never becomes an enum on the Rust
33/// side.
34///
35/// **This is the enum class inside this crate's own code.** The
36/// dependency-API sweep closed every place *ffmpeg-next* formed an enum
37/// out of FFmpeg memory; these three are places the crate's own new
38/// code did the same thing. The census that walks the pixel-format
39/// table to price the worst format is the sharpest instance: it exists
40/// precisely to be correct about formats this build does not name, and
41/// the binding it called returned those very ids as a closed
42/// `AVPixelFormat`. Every id would have become an invalid enum value on
43/// the way *into* the pricing that was supposed to handle it.
44pub(crate) mod c_shims {
45 use libc::c_int;
46
47 use super::AVCodec;
48
49 unsafe extern "C" {
50 /// `AVCodecID` as `c_int`.
51 pub fn avcodec_find_decoder(id: c_int) -> *const AVCodec;
52
53 /// `AVCodecID` as `c_int`, answering the descriptor libavcodec keeps
54 /// for that id — or null where this build names no codec for it.
55 ///
56 /// The pointer is into `codec_descriptors[]`, a `static const` table
57 /// compiled into libavcodec, so the strings it names are live and
58 /// unwritten for the process — the contract `crate::ffi`'s bounded
59 /// reader is given. It is left **raw** at every call site: the
60 /// struct embeds an `AVCodecID` and an `AVMediaType`, and forming a
61 /// reference to it would assert two bindgen enums valid on a table
62 /// that belongs to the linked library rather than to the bindings.
63 /// See `crate::CodecId::descriptor`.
64 ///
65 /// Preferred over `avcodec_get_name`, which never answers null: for
66 /// an id it cannot place it returns the string `"unknown_codec"`,
67 /// a sentinel wearing a name's clothes. A descriptor that is absent
68 /// is `None` here, and a consumer can tell the two apart.
69 pub fn avcodec_descriptor_get(id: c_int) -> *const ffmpeg_next::ffi::AVCodecDescriptor;
70
71 /// Returns `AVPixelFormat` as `c_int` — the id of a descriptor that
72 /// may well name a format this build's bindings do not.
73 pub fn av_pix_fmt_desc_get_id(desc: *const ffmpeg_next::ffi::AVPixFmtDescriptor) -> c_int;
74
75 /// Takes `AVPixelFormat` as `c_int`, so an id straight out of
76 /// [`av_pix_fmt_desc_get_id`] can be priced without ever being an
77 /// enum.
78 pub fn av_image_get_buffer_size(
79 pix_fmt: c_int,
80 width: c_int,
81 height: c_int,
82 align: c_int,
83 ) -> c_int;
84
85 /// Takes `AVSampleFormat` as `c_int`. Kept for the footprint
86 /// sweep, which walks the format table to decide which cells
87 /// exist; production pricing goes through
88 /// `av_samples_get_buffer_size`, the allocator's own ruler.
89 #[cfg(test)]
90 pub fn av_get_bytes_per_sample(sample_fmt: c_int) -> c_int;
91
92 /// The allocator's own audio ruler, with `AVSampleFormat` as
93 /// `c_int`. `align = 0` asks for the alignment
94 /// `av_frame_get_buffer` itself uses.
95 pub fn av_samples_get_buffer_size(
96 linesize: *mut c_int,
97 nb_channels: c_int,
98 nb_samples: c_int,
99 sample_fmt: c_int,
100 align: c_int,
101 ) -> c_int;
102
103 /// Writes an `AV_PIX_FMT_NONE`-terminated list of destination
104 /// formats a transfer may produce. Declared `*mut *mut c_int` so
105 /// the list is walked as integers — a driver may well offer a
106 /// format this build's bindings do not name.
107 pub fn av_hwframe_transfer_get_formats(
108 hwframe_ctx: *mut ffmpeg_next::ffi::AVBufferRef,
109 dir: c_int,
110 formats: *mut *mut c_int,
111 flags: c_int,
112 ) -> c_int;
113 }
114}
115
116use mediadecode::{Received, Sent};
117
118use crate::{
119 backend::{self, Backend},
120 error::{AllBackendsFailed, Error, HwDeviceInitFailed, Result},
121 ffi::{CallbackState, codec_supports_hwaccel, get_hw_format},
122 frame::Frame,
123};
124
125/// Hardware-accelerated video decoder.
126///
127/// Hardware-only — there is no software fallback inside this crate. If
128/// every hardware backend in the platform's probe order fails to open,
129/// `open` returns [`Error::AllBackendsFailed`] and the caller is
130/// responsible for falling back to a software decoder of their choice
131/// (e.g. `ffmpeg::decoder::Video`).
132///
133/// Mirrors `ffmpeg::decoder::Video`'s `send_packet`/`receive_frame` interface.
134/// Decoded frames are returned through [`crate::Frame`], a CPU-side wrapper
135/// whose accessors avoid the `AVPixelFormat`-enum UB that an unvalidated read
136/// of FFmpeg's raw integer pixel formats can trigger.
137///
138/// `open` does a true probe: each backend opens with a strict `get_format`
139/// callback. On the first non-transient error from a backend the decoder is
140/// torn down and the next backend in probe order is tried, with all packets
141/// seen so far replayed through it. The advance is *transactional* — the
142/// candidate backend must successfully build and accept the replayed packets
143/// before any probe state is consumed, so a failing backend in the middle of
144/// the order does not strand the caller without history. Once the first frame
145/// is delivered the probe collapses and subsequent calls go straight to the
146/// active (committed) backend.
147///
148/// The committed backend can still fail at runtime — e.g. VideoToolbox can
149/// decode a clip's first frames and then hit content its kernel can't handle
150/// (H.264 High 4:2:2 10-bit), surfacing `AVERROR_EXTERNAL`. Post-commit a
151/// non-transient, non-EOF error from the committed backend is reclassified to
152/// [`Error::AllBackendsFailed`] (see the `is_hw_decode_failure` predicate), so
153/// the [`crate::FfmpegVideoStreamDecoder`] wrapper still recognises it as a
154/// HW-path exhaustion and falls back to software. The post-commit
155/// `unconsumed_packets` is empty (the probe buffer is gone); the wrapper's
156/// rolling since-last-keyframe buffer supplies the replay set.
157pub struct VideoDecoder {
158 /// Live FFmpeg state for the currently active backend.
159 state: DecoderState,
160 /// Reusable frame buffer used for hw-side decoding before transfer / move.
161 /// Internal use only — never handed to callers.
162 hw_frame: frame::Video,
163 /// Probe state: present until the first frame is received from the active
164 /// backend, then `None`. While `Some`, packets are buffered for replay and
165 /// non-transient errors / decoder failures advance to the next backend.
166 probe: Option<ProbeState>,
167 /// CPU-side frames produced by a candidate decoder during probe replay
168 /// (when its internal queue filled and we had to drain output before the
169 /// next `send_packet`). Already transferred from the candidate's
170 /// `AVHWFramesContext` to a CPU frame, so they remain valid after the
171 /// candidate state is committed. [`Self::receive_frame`] dequeues these
172 /// FIFO before reading from `state.inner`.
173 pending_frames: VecDeque<frame::Video>,
174 /// Per-decoder byte budget for [`Self::pending_frames`] during probe
175 /// replay. Defaults to [`DEFAULT_MAX_PROBE_PENDING_BYTES`]; override via
176 /// [`Self::with_max_probe_pending_bytes`].
177 max_probe_pending_bytes: usize,
178 /// Resource ceilings for the frames this decoder produces. Fixed at
179 /// open, because [`FrameLimits::max_pixels`] is written into every
180 /// `AVCodecContext` this decoder builds — including the ones a probe
181 /// advance builds later — and a context's ceiling cannot be moved
182 /// after `avcodec_open2`.
183 frame_limits: crate::limits::DecoderLimits,
184 /// `true` once [`Self::send_eof`] has been accepted, until
185 /// [`Self::flush`].
186 ///
187 /// **It lives here rather than in [`ProbeState`], and that move is
188 /// the point.** It used to be a probe field, so it vanished the
189 /// moment the probe collapsed — a committed decoder could not tell
190 /// whether the caller had signalled the end, and therefore could not
191 /// answer the one question [`SessionPhase`] exists to answer without
192 /// guessing. The probe machinery still reads it for replay; it simply
193 /// no longer owns it.
194 eof_sent: bool,
195}
196
197/// Owned FFmpeg state for one open codec context. Has its own `Drop` so we
198/// can swap it out cleanly during a probe advance via `mem::replace`.
199struct DecoderState {
200 /// Wrapped FFmpeg decoder. `ManuallyDrop` so we can sequence its drop
201 /// before freeing the callback state.
202 inner: ManuallyDrop<ffmpeg_next::decoder::Video>,
203 /// Backend driving this state.
204 backend: Backend,
205 /// Owned reference produced by `av_hwdevice_ctx_create`.
206 hw_device_ref: *mut AVBufferRef,
207 /// Owned `Box<CallbackState>` raw pointer; `AVCodecContext::opaque`
208 /// aliases it.
209 callback_state: *mut CallbackState,
210}
211
212/// Maximum number of packets we are willing to buffer for probe replay
213/// before abandoning the fallback safety net. Set high enough to absorb
214/// long B-frame GOPs and codec setup latency, low enough to bound memory
215/// against malicious / pathological streams that never produce a first
216/// frame.
217const MAX_PROBE_PACKETS: usize = 256;
218
219/// Maximum total compressed-byte size of buffered probe packets. Each
220/// `Packet` clone holds a refcounted reference to the demuxer's bitstream
221/// data — even though the clone itself is shallow, the underlying buffers
222/// stay alive until we drop them. 64 MiB is generous for normal video and
223/// gives untrusted media a hard ceiling.
224const MAX_PROBE_PACKET_BYTES: usize = 64 * 1024 * 1024;
225
226/// Hard cap on the number of side-data entries we tolerate per buffered
227/// packet. `av_packet_ref` allocates an `AVPacketSideData` descriptor and
228/// an `AVBufferRef` per entry, so a packet stuffed with many tiny or
229/// zero-sized entries can consume significant memory in descriptor /
230/// allocator overhead even after [`packet_side_data_bytes`] charges
231/// [`SIDE_DATA_ENTRY_OVERHEAD`] bytes per entry. Refusing to clone such
232/// packets short-circuits the descriptor explosion path.
233///
234/// Sized for legitimate streams (typical video packets carry 0-5 side-
235/// data entries; SEI-heavy HEVC/AV1 maybe a dozen) while comfortably
236/// rejecting weaponised input.
237///
238/// Shared with the [`crate::FfmpegVideoStreamDecoder`] rolling GOP buffer,
239/// which charges the same side-data budget so its byte cap is a true upper
240/// bound on retained memory rather than counting bare payloads.
241pub(crate) const MAX_PROBE_PACKET_SIDE_DATA_ENTRIES: usize = 64;
242
243/// Conservative per-side-data-entry overhead estimate used by both
244/// [`packet_side_data_bytes`] and the budget accounting in
245/// [`VideoDecoder::send_packet`]. Counts the `AVPacketSideData`
246/// descriptor (24 bytes per the FFmpeg 9.x bindings), the `AVBufferRef`
247/// FFmpeg allocates per entry, and a margin for malloc bookkeeping
248/// (header bytes, alignment slack). Setting it on the high side keeps
249/// the byte cap a true upper bound on retained memory; under-charging
250/// would let many tiny entries slip past the cap.
251const SIDE_DATA_ENTRY_OVERHEAD: usize = 80;
252
253/// Conservative upper-bound bytes-per-pixel multiplier used to estimate
254/// the size of a CPU frame **before** `av_hwframe_transfer_data`
255/// allocates its pixel buffers. Covers every HW download format this
256/// crate produces (worst case is `P416LE` / `P412LE` at 6 bytes/pixel
257/// for 16-bit 4:4:4 semi-planar) plus a margin for FFmpeg's per-row
258/// stride alignment (typically 32-byte aligned, ~5% extra at HD widths
259/// and below).
260///
261/// Used by [`drain_into_pending`] as a pre-transfer guard: if the
262/// product `width * height * WORST_CASE_BYTES_PER_PIXEL` would already
263/// push `pending_bytes` past `max_probe_pending_bytes`, the candidate
264/// replay refuses the frame *before* allocating. Without this, FFmpeg
265/// would perform the full HW→CPU download (potentially ~100 MiB for
266/// 8K HDR) and we would only reject the frame after RSS had already
267/// spiked. The post-transfer accounting via [`cpu_frame_bytes`] stays in
268/// place as a backstop using the frame's actual stride/format.
269///
270/// Slightly over-charges true 4:2:0 NV12 / P010 frames (which dominate
271/// real workloads) — that's the right side to err on. Callers feeding
272/// 8K+ workloads through the probe path can tune
273/// [`VideoDecoder::with_max_probe_pending_bytes`] upward to compensate.
274const WORST_CASE_BYTES_PER_PIXEL: usize = 8;
275
276/// Maximum number of CPU frames we are willing to queue from a candidate
277/// during probe replay. Each frame is a fully-allocated CPU buffer
278/// (~3 MiB for 1080p NV12, ~24 MiB for 4K P010, ~96 MiB for 8K P010), so
279/// an unbounded queue would OOM on a candidate with a shallow internal
280/// queue against a deep replay history. This cap, together with
281/// [`DEFAULT_MAX_PROBE_PENDING_BYTES`], is enforced as a hard limit during
282/// replay: once either limit is reached, probe buffering fails for the
283/// candidate (returns `ENOMEM` from `drain_into_pending`) instead of
284/// queueing additional drained frames. The probe loop then advances to
285/// the next backend or returns `Error::AllBackendsFailed` if exhausted.
286const MAX_PROBE_PENDING_FRAMES: usize = 16;
287
288/// Default byte budget for probe-replay drained frames. 256 MiB is enough
289/// for 16 frames at 4K P010 (~24 MiB each = 384 MiB worst case under the
290/// count cap), and is the cap that fires first for very high-resolution
291/// content (8K P010: ~96 MiB per frame → only ~2 frames fit).
292///
293/// Override per-decoder with [`VideoDecoder::with_max_probe_pending_bytes`]
294/// when targeting 8K+ workloads or memory-constrained environments.
295///
296/// TODO: when frames significantly exceed typical sizes, consider
297/// memmap-backed pending buffers (write transferred frames to a temp file
298/// or shared-memory segment) so the resident set stays bounded even when
299/// the byte cap is raised. Out of scope for now.
300pub const DEFAULT_MAX_PROBE_PENDING_BYTES: usize = 256 * 1024 * 1024;
301
302/// Where a decoding session is in its life — **the one derived fact the
303/// classifiers read, and the only place the latches are interpreted.**
304///
305/// Every road that must decide what an errno *means* needs the same two
306/// questions answered, and answering them ad hoc at each road is what
307/// let them disagree. `EAGAIN` means "send me more" only where more can
308/// come; `AVERROR_EOF` means "the stream is over" only where a backend
309/// has committed to producing it. Read those wrong and a caller is
310/// handed a state with no satisfying operation, or a candidate that
311/// will never produce a frame is mistaken for a finished stream.
312///
313/// The two questions are exactly the two dimensions the machinery
314/// already keeps latches for — whether an end has been recorded, and
315/// whether a backend is still on trial — so this enum is a census of
316/// those latches rather than a new idea. Deriving it lives in
317/// [`VideoDecoder::phase`] and its siblings, one per session type;
318/// nothing else reads a latch to answer a classification question.
319#[derive(Copy, Clone, Debug, PartialEq, Eq)]
320pub(crate) enum SessionPhase {
321 /// A committed backend, and no end-of-stream recorded. Both flow
322 /// signals mean what they say.
323 Streaming,
324 /// A committed backend draining its tail after a recorded end. "Send
325 /// me more" is no longer satisfiable here — the caller has nothing
326 /// left to send and the send gates refuse — so it reads as the end.
327 Draining,
328 /// A candidate backend on trial, no end recorded. It may legitimately
329 /// want more input; what it may not do is quietly end the stream on
330 /// the caller's behalf, which is the committed backend's privilege.
331 Auditioning,
332 /// A candidate on trial that has already been handed the whole
333 /// history, **end-of-stream included**.
334 ///
335 /// The arm that had no name. A candidate here has been given
336 /// everything there is and answers about a stream that is already
337 /// over: if it has produced no frame, it never will. That is a
338 /// candidate failing — the probe's business — and neither "send me
339 /// more" (nothing left to send) nor "the stream ended" (this backend
340 /// never decoded a thing) is a true reading of it.
341 AuditioningPastEnd,
342}
343
344impl SessionPhase {
345 /// Whether more input can still reach this session.
346 ///
347 /// The satisfiability question: [`Received::NeedsInput`] and
348 /// [`Sent::MustDrain`] are both instructions, and both are honest
349 /// only where the caller can carry them out.
350 pub(crate) const fn accepts_input(self) -> bool {
351 matches!(self, Self::Streaming | Self::Auditioning)
352 }
353
354 /// Whether a backend has committed, and so may speak for the stream.
355 ///
356 /// Only a committed backend's `AVERROR_EOF` is the stream's end. A
357 /// candidate's is its own: it drained to nothing without ever proving
358 /// it could decode this content.
359 pub(crate) const fn is_committed(self) -> bool {
360 matches!(self, Self::Streaming | Self::Draining)
361 }
362}
363
364/// How a funnel verdict routes. See [`VideoDecoder::verdict_routing`].
365enum VerdictRouting {
366 /// The name says this backend cannot decode this content.
367 CandidateFailed,
368 /// The name says retrying a backend cannot help — report it as it is.
369 Direct,
370 /// Nothing was named; the road's own reading decides.
371 Unnamed,
372}
373
374/// What an **unnamed** verdict means on the road that produced it — the
375/// one thing the shared routing policy cannot know for itself.
376enum BareVerdict {
377 /// A flow signal's own fault: `avcodec_send_packet` answering
378 /// `AVERROR_EOF` to a submission past the end. The probe must not
379 /// advance on it — the candidate did nothing wrong, the caller did.
380 Reported,
381 /// A real failure. While a candidate is on trial, that is the
382 /// candidate failing.
383 CandidateFailure,
384}
385
386/// What the caller should do with a routed hardware failure.
387enum HwRoute {
388 /// Hand this to the caller.
389 Report(Error),
390 /// The active candidate failed: advance the probe and retry.
391 Advance(Error),
392}
393
394/// State carried only during the probe window (before the first successful
395/// frame). Holds enough information to tear down the current decoder and
396/// retry with the next backend.
397struct ProbeState {
398 parameters: codec::Parameters,
399 codec: Codec,
400 /// Backends still to try, in order. Empty means "no more options after
401 /// the active one fails" — `advance_probe` then surfaces
402 /// [`Error::AllBackendsFailed`] so the contract is the same on
403 /// single-backend platforms (e.g. macOS) as on multi-backend ones.
404 remaining_backends: Vec<Backend>,
405 /// Packets sent so far, kept for replay through any candidate backend.
406 /// Preserved across failed candidates — only cleared when the probe
407 /// collapses on a successful first frame, or when the probe is
408 /// abandoned due to the size caps.
409 buffered_packets: Vec<Packet>,
410 /// Cumulative size (in compressed bytes) of `buffered_packets`. Tracked
411 /// incrementally so we don't have to re-sum on every send.
412 buffered_bytes: usize,
413 /// Whether `send_eof` has been called; replayed alongside packets.
414 /// Per-backend errors captured since the probe window opened. Pushed
415 /// whenever a backend's failure triggers `advance_probe` (the active
416 /// backend that just failed) or a candidate's build / replay rejects
417 /// it. Drained into [`Error::AllBackendsFailed`] when the probe
418 /// exhausts every option.
419 attempts: Vec<(Backend, Box<Error>)>,
420}
421
422// SAFETY: All raw pointers are exclusively owned by `DecoderState` and never
423// shared. `ffmpeg::decoder::Video` is itself `Send` (its `Context` carries an
424// `unsafe impl Send`). The decoder is not safe for concurrent use, hence not
425// `Sync`.
426unsafe impl Send for DecoderState {}
427unsafe impl Send for VideoDecoder {}
428
429impl Drop for DecoderState {
430 fn drop(&mut self) {
431 // Order matters:
432 // 1. Drop the codec context first. While it lives, FFmpeg may invoke
433 // `get_format`, which dereferences `callback_state` via `opaque`.
434 // 2. Free the callback state heap allocation.
435 // 3. Release our hw device reference (FFmpeg released its own when
436 // the codec context was freed in step 1).
437 unsafe {
438 ManuallyDrop::drop(&mut self.inner);
439 if !self.callback_state.is_null() {
440 drop(Box::from_raw(self.callback_state));
441 self.callback_state = ptr::null_mut();
442 }
443 if !self.hw_device_ref.is_null() {
444 av_buffer_unref(&mut self.hw_device_ref);
445 }
446 }
447 }
448}
449
450impl VideoDecoder {
451 /// Auto-probe hardware backends in the platform's default order.
452 ///
453 /// Each backend opens with a strict `get_format` callback. The first
454 /// backend whose `avcodec_open2` succeeds becomes active; if its first
455 /// frame is unusable (decode error, transfer failure, or a CPU-format
456 /// frame from a HW context) the decoder is torn down and the next backend
457 /// is tried — packets sent so far are replayed through the new decoder
458 /// transparently. The probe advance is transactional: the next backend
459 /// must build *and* accept the replayed history before any probe state is
460 /// consumed, so a misbehaving middle backend cannot strand the caller.
461 ///
462 /// [`Self::backend`] reflects whichever backend ultimately produced the
463 /// first frame.
464 ///
465 /// [`Error::AllBackendsFailed`] surfaces in two places, with the same
466 /// meaning ("no hardware backend can decode this stream — fall back to
467 /// software yourself"):
468 /// - From `open` itself, when no backend even opens.
469 /// - From [`Self::send_packet`] / [`Self::send_eof`] /
470 /// [`Self::receive_frame`], when the initially-opened backend fails
471 /// at decode time and every remaining backend in the probe order
472 /// either also fails or doesn't exist. On single-backend platforms
473 /// (e.g. macOS, where the order is `[VideoToolbox]`), this is the
474 /// only place a HW-only failure surfaces.
475 ///
476 /// In both cases, `attempts` carries the per-backend error log. When
477 /// the runtime path fires, `unconsumed_packets` also contains the
478 /// packets the decoder consumed from the caller before the probe
479 /// exhausted (refcounted shallow clones); for non-seekable inputs
480 /// (live streams, pipes) the caller can replay these directly into
481 /// a software decoder of their choice without re-demuxing. From the
482 /// open-time path the vec is empty since no packets have been sent.
483 ///
484 /// On `Ok`, the returned decoder **always** has an active probe
485 /// rescue safety net. If a parameters clone fails under memory
486 /// pressure before the probe state can be set up, `open` returns
487 /// `Err(Error::Ffmpeg(Other { errno: ENOMEM }))` rather than handing
488 /// back a live decoder with no fallback contract. No packets have
489 /// been sent yet, so the caller can retry or fall back to software
490 /// with the original `parameters` directly.
491 pub fn open(parameters: codec::Parameters) -> Result<Self> {
492 Self::open_with_frame_limits(parameters, crate::limits::DecoderLimits::default())
493 }
494
495 /// [`Self::open`], with the frame ceilings named.
496 ///
497 /// Taken at open for the reason [`Self::open_with_limits`] gives:
498 /// [`FrameLimits::max_pixels`] is written into every `AVCodecContext`
499 /// this decoder opens — including the ones a later probe advance
500 /// opens — and a context's ceiling cannot be moved after
501 /// `avcodec_open2`.
502 pub fn open_with_frame_limits(
503 parameters: codec::Parameters,
504 limits: crate::limits::DecoderLimits,
505 ) -> Result<Self> {
506 let codec = find_decoder(¶meters)?;
507 let order = backend::probe_order();
508
509 let mut attempts: Vec<(Backend, Box<Error>)> = Vec::new();
510 for (i, &backend) in order.iter().enumerate() {
511 // Use the checked clone — ffmpeg-next's `Parameters::clone` does
512 // `avcodec_parameters_alloc` without a null check and ignores the
513 // return of `avcodec_parameters_copy`. Under OOM that path silently
514 // produces a Parameters with a null inner pointer.
515 let cloned_for_build =
516 match try_clone_parameters(¶meters, limits.max_codec_parameter_bytes()) {
517 Ok(p) => p,
518 Err(e) => {
519 tracing::warn!(?backend, error = %e, "hwdecode: parameters clone failed");
520 attempts.push((backend, Box::new(e)));
521 continue;
522 }
523 };
524 match Self::build_state(cloned_for_build, codec, backend, limits) {
525 Ok(state) => {
526 tracing::info!(?backend, "hwdecode: opened video decoder (probing)");
527 let remaining = order[(i + 1)..].to_vec();
528 // Deep-copy the caller's `parameters` before storing in ProbeState.
529 // `codec::Parameters` from `stream.parameters()` carries an Rc
530 // owner pointing at the demuxer; moving that Rc to a worker
531 // thread (when VideoDecoder is sent) would race with the demuxer's
532 // Rc on the original thread. The checked clone copies the bytes
533 // into a fresh allocation with `owner: None`, severing the link.
534 //
535 // We always create ProbeState — even when `remaining` is empty
536 // (single-backend platforms like macOS) — so that a first-frame
537 // failure on the only backend surfaces as
538 // `Error::AllBackendsFailed` from `receive_frame` /
539 // `send_packet` rather than as a raw FFmpeg error. That keeps
540 // the API contract the same regardless of how many HW backends
541 // the platform exposes.
542 //
543 // If the clone fails (ENOMEM), fail the **whole open call**
544 // rather than returning a live decoder with `probe: None`.
545 // Returning Ok here would let the caller send packets that the
546 // active backend consumes, and a subsequent backend failure
547 // would then surface as a raw FFmpeg error with no
548 // `unconsumed_packets` — silently breaking the rescue contract
549 // for non-seekable inputs (live streams, pipes). Dropping the
550 // already-built `state` here runs its FFmpeg cleanup, and the
551 // caller can retry / fall back to software with the original
552 // parameters in their hand (no packets were consumed yet).
553 // Seed the probe's attempt log with any backends that failed
554 // to open earlier in this loop (including
555 // `BackendUnsupportedByCodec` and parameters-clone errors).
556 // Without this, a runtime exhaustion on the active backend
557 // would surface an `AllBackendsFailed` containing only the
558 // active backend's runtime failure — losing the original
559 // open-time causes that, on multi-backend platforms (Linux,
560 // Windows), are usually the more diagnostic signal. E.g. a
561 // VAAPI-then-CUDA host where VAAPI fails to open and CUDA
562 // later fails at first-frame must report both failures in
563 // probe order, not just CUDA.
564 let probe = match try_clone_parameters(¶meters, limits.max_codec_parameter_bytes()) {
565 Ok(probe_params) => ProbeState {
566 parameters: probe_params,
567 codec,
568 remaining_backends: remaining,
569 buffered_packets: Vec::new(),
570 buffered_bytes: 0,
571 attempts: std::mem::take(&mut attempts),
572 },
573 Err(e) => {
574 tracing::warn!(
575 error = %e,
576 "hwdecode: parameters clone failed for probe state at open; \
577 failing closed instead of returning a decoder without rescue"
578 );
579 return Err(e);
580 }
581 };
582 return Ok(Self {
583 state,
584 hw_frame: alloc_av_frame().map_err(Error::Ffmpeg)?,
585 probe: Some(probe),
586 pending_frames: VecDeque::new(),
587 max_probe_pending_bytes: DEFAULT_MAX_PROBE_PENDING_BYTES,
588 frame_limits: limits,
589 eof_sent: false,
590 });
591 }
592 Err(e) => {
593 tracing::warn!(?backend, error = %e, "hwdecode: backend open failed");
594 attempts.push((backend, Box::new(e)));
595 }
596 }
597 }
598 // No packets have been consumed at open time.
599 Err(Error::AllBackendsFailed(AllBackendsFailed::new(
600 attempts,
601 Vec::new(),
602 )))
603 }
604
605 /// Open the decoder with a specific backend. No probe, no fallback.
606 ///
607 /// If `backend` cannot actually decode this stream, the failure surfaces
608 /// from [`Self::receive_frame`] (the strict `get_format` callback returns
609 /// `AV_PIX_FMT_NONE`, the decoder errors out). The caller is responsible
610 /// for retrying with another hardware backend or falling back to a
611 /// software decoder of their choice (e.g. `ffmpeg::decoder::Video`).
612 pub fn open_with(parameters: codec::Parameters, backend: Backend) -> Result<Self> {
613 Self::open_with_limits(parameters, backend, crate::limits::DecoderLimits::default())
614 }
615
616 /// [`Self::open_with`], with the frame ceilings named.
617 ///
618 /// The limits are taken **at open**, not through a `with_*` builder,
619 /// because [`FrameLimits::max_pixels`] is written straight into the
620 /// `AVCodecContext` this call opens — that is the layer that makes
621 /// libavcodec refuse an oversized picture before allocating it, and a
622 /// context's ceiling cannot be moved after `avcodec_open2`. A builder
623 /// would have silently applied to only half the enforcement.
624 pub fn open_with_limits(
625 parameters: codec::Parameters,
626 backend: Backend,
627 limits: crate::limits::DecoderLimits,
628 ) -> Result<Self> {
629 let codec = find_decoder(¶meters)?;
630 let state = Self::build_state(parameters, codec, backend, limits)?;
631 Ok(Self {
632 state,
633 hw_frame: alloc_av_frame().map_err(Error::Ffmpeg)?,
634 probe: None,
635 pending_frames: VecDeque::new(),
636 max_probe_pending_bytes: DEFAULT_MAX_PROBE_PENDING_BYTES,
637 frame_limits: limits,
638 eof_sent: false,
639 })
640 }
641
642 /// Builds a decoder around a **software** `ffmpeg::decoder::Video`,
643 /// for tests that need [`VideoDecoder`]'s own send/receive arms driven
644 /// against real libavcodec.
645 ///
646 /// **Why this exists.** Those arms classify libavcodec's flow control
647 /// themselves, and the only other way to reach them is
648 /// [`VideoDecoder::open`], which needs a working hardware backend and
649 /// a sample file — so every existing lane through them is
650 /// `#[ignore]`-gated and runs nowhere. A regression that never runs is
651 /// a claim, not a check. This keeps the arms, the probe state and the
652 /// funnels exactly as production builds them and swaps only the
653 /// backend behind `state.inner`, which is the one thing a test cannot
654 /// otherwise supply.
655 ///
656 /// `auditioning` opens the probe window with **no backends left to
657 /// try**, which is what makes the candidate-failure road observable:
658 /// `advance_probe` has nowhere to advance to, so it surfaces
659 /// [`Error::AllBackendsFailed`] and a lane can tell "the probe road
660 /// was taken" from "a status was answered". Passing `false` leaves the
661 /// probe collapsed, for lanes that mean to exercise a committed
662 /// backend.
663 ///
664 /// The `backend` label is cosmetic here — it is read only for the
665 /// attempt log and [`Self::backend`], neither of which a software
666 /// decoder reaches — and `hw_device_ref` is null, which
667 /// [`DecoderState`]'s `Drop` already handles.
668 #[cfg(test)]
669 pub(crate) fn from_software_for_test(
670 parameters: codec::Parameters,
671 limits: crate::limits::DecoderLimits,
672 auditioning: bool,
673 ) -> Result<Self> {
674 let codec = find_decoder(¶meters)?;
675 let (ctx, callback_state) = build_codec_context(¶meters, limits)?;
676 let opened = ctx.decoder().open_as(codec).map_err(Error::Ffmpeg)?;
677 ensure_video_codec_type(&opened)?;
678 let state = DecoderState {
679 inner: ManuallyDrop::new(ffmpeg_next::decoder::Video(opened)),
680 backend: backend::probe_order()
681 .first()
682 .copied()
683 .unwrap_or(Backend::VideoToolbox),
684 hw_device_ref: ptr::null_mut(),
685 callback_state: Box::into_raw(callback_state),
686 };
687 let probe = auditioning.then(|| ProbeState {
688 parameters: try_clone_parameters(¶meters, limits.max_codec_parameter_bytes())
689 .expect("a clonable parameter set"),
690 codec,
691 remaining_backends: Vec::new(),
692 buffered_packets: Vec::new(),
693 buffered_bytes: 0,
694 attempts: Vec::new(),
695 });
696 Ok(Self {
697 state,
698 hw_frame: alloc_av_frame().map_err(Error::Ffmpeg)?,
699 probe,
700 pending_frames: VecDeque::new(),
701 max_probe_pending_bytes: DEFAULT_MAX_PROBE_PENDING_BYTES,
702 frame_limits: limits,
703 eof_sent: false,
704 })
705 }
706
707 /// Override the byte budget for probe-replay queued frames. Defaults to
708 /// [`DEFAULT_MAX_PROBE_PENDING_BYTES`]. Use a higher value when targeting
709 /// 8K+ workloads where 16 frames at full size could exceed the default;
710 /// use a lower value in memory-constrained services to bound peak
711 /// allocation more tightly.
712 ///
713 /// Setting after the first frame has been delivered is harmless but has
714 /// no observable effect — the probe has already collapsed and the cap
715 /// only applies during replay drain.
716 ///
717 /// Returns `self` for builder-style chaining:
718 /// ```ignore
719 /// let decoder = VideoDecoder::open(params)?
720 /// .with_max_probe_pending_bytes(1024 * 1024 * 1024); // 1 GiB
721 /// ```
722 #[must_use]
723 pub fn with_max_probe_pending_bytes(mut self, bytes: usize) -> Self {
724 self.max_probe_pending_bytes = bytes;
725 self
726 }
727
728 /// The backend currently producing frames. While the probe is still in
729 /// progress (no frame received yet) this returns the optimistically
730 /// selected backend; after the first frame, it is the backend that
731 /// actually produced it. Once stable, never changes again.
732 pub fn backend(&self) -> Backend {
733 self.state.backend
734 }
735
736 /// Decoder width in pixels.
737 pub fn width(&self) -> u32 {
738 self.state.inner.width()
739 }
740
741 /// Decoder height in pixels.
742 pub fn height(&self) -> u32 {
743 self.state.inner.height()
744 }
745
746 /// Codec context time base.
747 pub fn time_base(&self) -> Rational {
748 self.state.inner.time_base()
749 }
750
751 /// Frame rate from the codec context, if known.
752 pub fn frame_rate(&self) -> Option<Rational> {
753 self.state.inner.frame_rate()
754 }
755
756 /// Reclassify a post-commit runtime error from the committed HW backend
757 /// into [`Error::AllBackendsFailed`] so the [`crate::FfmpegVideoStreamDecoder`]
758 /// wrapper recognises it as a HW-path exhaustion and falls back to
759 /// software. The single attempt records the committed backend
760 /// (`self.state.backend` is the live backend post-commit) paired with the
761 /// underlying FFmpeg error. `unconsumed_packets` is empty: the probe
762 /// buffer is gone after commit, so the wrapper's rolling
763 /// since-last-keyframe buffer supplies the replay set.
764 ///
765 /// # `reason` is the funnel's verdict, and this does not mint another
766 ///
767 /// It used to call [`Self::hw_exit`] itself, which was right while it
768 /// was the *first* funnel on its road and wrong the moment it was the
769 /// second. On the receive road the verdict is minted at the top of the
770 /// arm, and `hw_exit` **consumes** the latch it reads — so a second
771 /// call finds nothing and records the raw errno libavcodec reported,
772 /// throwing away the refusal that had already been collected. A
773 /// caller's attempt log then blamed `InvalidData` for a coded surface
774 /// this crate declined over a configured ceiling.
775 ///
776 /// So the verdict is minted once, by whichever funnel is first on the
777 /// road, and threaded from there. See the doors' invariant on
778 /// [`software_receive`].
779 /// Mints a verdict for a road that holds none yet, then routes it.
780 ///
781 /// The funnel runs **exactly once** here, which is the law the doors
782 /// carry: see the invariant on [`software_receive`]. Roads that have
783 /// already minted (the receive arm) call [`Self::hw_route`] straight.
784 fn hw_failure(&self, e: ffmpeg_next::Error, bare: BareVerdict) -> HwRoute {
785 self.hw_route(self.hw_exit(Error::Ffmpeg(e)), e, bare)
786 }
787
788 /// How a funnel verdict routes, before the road's own reading of an
789 /// unnamed one applies.
790 ///
791 /// **Exhaustive on purpose, and with no wildcard.** A `_ => false`
792 /// stood here and was a hazard rather than a convenience: a future
793 /// named verdict that *did* require a fallback would inherit the
794 /// silence and be reported plain, which is a bug that compiles. The
795 /// match is total over this crate's own error vocabulary, so adding an
796 /// arm forces whoever adds it to say how it routes.
797 fn verdict_routing(reason: &Error) -> VerdictRouting {
798 match reason {
799 // The hardware pool declined the coded surface. Software is not
800 // subject to that ceiling, and neither is the next backend.
801 Error::HwSurfaceTooLarge(_) => VerdictRouting::CandidateFailed,
802 // Software would decode the same oversized frame and be refused
803 // by the same ceiling; so would the next backend. A fallback here
804 // invites an action that cannot succeed.
805 Error::FrameBudgetExceeded(_) => VerdictRouting::Direct,
806 // The funnel handed its fallback straight back: nothing was named,
807 // so the errno is all there is and the road decides.
808 Error::Ffmpeg(_) => VerdictRouting::Unnamed,
809 // None of these can leave a funnel — `hw_exit` mints only the two
810 // refusals above or returns its argument — and each is already a
811 // decided fact that did not ask for a backend to be retried. They
812 // are listed rather than swept up so a twelfth arm cannot join
813 // them silently.
814 Error::PacketBuild(_)
815 | Error::ParametersTooLarge(_)
816 | Error::NoCodec(_)
817 | Error::HwTransferTooLarge(_)
818 | Error::BackendUnsupportedByCodec(_)
819 | Error::HwDeviceInitFailed(_)
820 | Error::AllBackendsFailed(_)
821 | Error::FallbackFailed(_) => VerdictRouting::Direct,
822 }
823 }
824
825 /// Whether a post-commit failure means the hardware backend cannot
826 /// decode this content, so the wrapper must open a software decoder.
827 ///
828 /// A named verdict outranks the raw errno in **both** directions: a
829 /// name that says no is as binding as one that says yes, and the errno
830 /// is consulted only where nothing was named. See
831 /// [`Self::verdict_routing`].
832 fn fallback_required(reason: &Error, raw: ffmpeg_next::Error) -> bool {
833 match Self::verdict_routing(reason) {
834 VerdictRouting::CandidateFailed => true,
835 VerdictRouting::Direct => false,
836 VerdictRouting::Unnamed => is_hw_decode_failure(&raw),
837 }
838 }
839
840 /// **One policy for what a funnelled hardware failure means, shared by
841 /// every road that can produce one.**
842 ///
843 /// The send roads used to return their funnel's result the moment they
844 /// had it. That was right for a flow signal and wrong for anything
845 /// else: `hw_send` can mint [`Error::HwSurfaceTooLarge`], and returning
846 /// it plain meant the wrapper — which opens software only on
847 /// [`Error::AllBackendsFailed`] — simply stopped, and a probe still
848 /// auditioning never advanced past the candidate that had just
849 /// declined the surface.
850 ///
851 /// So minting and routing are one move now, and the receive road's
852 /// policy is the policy. What differs between roads is only what an
853 /// *unnamed* verdict means, which is why [`BareVerdict`] is a
854 /// parameter rather than an assumption.
855 fn hw_route(&self, reason: Error, raw: ffmpeg_next::Error, bare: BareVerdict) -> HwRoute {
856 let candidate_failed = match Self::verdict_routing(&reason) {
857 VerdictRouting::CandidateFailed => true,
858 VerdictRouting::Direct => false,
859 VerdictRouting::Unnamed => matches!(bare, BareVerdict::CandidateFailure),
860 };
861 if !candidate_failed {
862 return HwRoute::Report(reason);
863 }
864 if self.probe.is_some() {
865 return HwRoute::Advance(reason);
866 }
867 if Self::fallback_required(&reason, raw) {
868 return HwRoute::Report(self.post_commit_hw_failure(reason));
869 }
870 HwRoute::Report(reason)
871 }
872
873 fn post_commit_hw_failure(&self, reason: Error) -> Error {
874 // `new_post_commit` stamps `FallbackOrigin::PostCommit`: the wrapper
875 // routes its replay on that explicit signal, not on the (here-empty)
876 // `unconsumed_packets`, which a probe-era first-packet cap trip also
877 // leaves empty.
878 Error::AllBackendsFailed(AllBackendsFailed::new_post_commit(vec![(
879 self.state.backend,
880 Box::new(reason),
881 )]))
882 }
883
884 /// Whether the probe rescue history is still being recorded.
885 ///
886 /// While this is true, [`Self::send_packet`] `av_packet_ref`s every
887 /// accepted packet into `buffered_packets`, and a later
888 /// [`Error::AllBackendsFailed`] hands those recordings to the caller
889 /// as owned, mutable `Packet`s. A submission built to be dropped
890 /// inside one call therefore does **not** stay inside that call on
891 /// this road — which is what the view lane's send-side sharing
892 /// assumed. The window closes at commit, when the first frame
893 /// arrives and `probe` is taken.
894 #[inline]
895 pub(crate) const fn is_probing(&self) -> bool {
896 self.probe.is_some()
897 }
898
899 /// **Where this session is, derived here and nowhere else.**
900 ///
901 /// The two latches this reads — whether a backend is still on trial,
902 /// and whether an end has been recorded — are the only inputs any
903 /// classification question has ever needed. Reading them at the point
904 /// of a decision is what let the roads disagree; reading them once,
905 /// here, is what stops it.
906 pub(crate) const fn phase(&self) -> SessionPhase {
907 match (self.probe.is_some(), self.eof_sent) {
908 (false, false) => SessionPhase::Streaming,
909 (false, true) => SessionPhase::Draining,
910 (true, false) => SessionPhase::Auditioning,
911 (true, true) => SessionPhase::AuditioningPastEnd,
912 }
913 }
914
915 /// Submit a packet to the decoder.
916 ///
917 /// On success — and only on success — the packet is buffered for potential
918 /// replay through a fallback backend while the probe is active. `EAGAIN`
919 /// (the decoder needs `receive_frame` to drain output first) is
920 /// [`Sent::MustDrain`]: nothing was consumed, so the caller drains and
921 /// offers the same packet again. `AVERROR_EOF` is **not** back pressure
922 /// on this face — it means this decoder was already told the stream
923 /// ended — so it stays a fault. See [`send_status`].
924 ///
925 /// While the probe is active, a non-transient error (e.g. the active HW
926 /// backend rejecting this stream's geometry on first packet) advances the
927 /// probe to the next candidate and retries the packet there. The caller
928 /// observes only the eventual success or, if the probe is exhausted, the
929 /// final error.
930 ///
931 /// **Atomic probe rescue.** While the probe is active, the rescue
932 /// invariant is that everything FFmpeg has consumed since open is
933 /// reflected in `buffered_packets` (so a future
934 /// [`Error::AllBackendsFailed`] can hand a complete replay history
935 /// back to the caller for software fallback on a non-seekable input).
936 /// If we cannot prove this packet is buffer-able — its side-data
937 /// entry count exceeds [`MAX_PROBE_PACKET_SIDE_DATA_ENTRIES`], its
938 /// bytes would push the probe past [`MAX_PROBE_PACKETS`] or
939 /// [`MAX_PROBE_PACKET_BYTES`], or [`av_packet_ref`] fails ENOMEM —
940 /// `send_packet` returns [`Error::AllBackendsFailed`] **without
941 /// invoking** `state.inner.send_packet` on this packet. The caller's
942 /// packet stays in their hand and `unconsumed_packets` carries the
943 /// pre-existing buffered history, so they can replay
944 /// `unconsumed_packets` plus the current packet through their
945 /// software decoder of choice. The post-probe path (after the first
946 /// frame, when `self.probe` is `None`) skips this pre-flight
947 /// entirely.
948 pub fn send_packet(&mut self, packet: &Packet) -> Result<Sent> {
949 loop {
950 // Re-read each iteration: a probe advance moves this session from
951 // one phase to another underneath the loop.
952 let phase = self.phase();
953 // Pre-flight while probe is active: prove we can record this
954 // packet for replay BEFORE the active decoder consumes it.
955 // `staged_clone` carries the refcounted clone and the new
956 // `buffered_bytes` value through the send below; we only commit
957 // them to the probe state if FFmpeg accepts the packet.
958 let staged_clone: Option<(Packet, usize)> = if let Some(probe) = self.probe.as_ref() {
959 // Step 1: side-data entry count cap. Read just `side_data_elems`
960 // (no array walk yet) so a corrupt or weaponised value cannot
961 // drive an unbounded loop from the safe entry point.
962 let side_count = packet_side_data_count(packet);
963 if side_count > MAX_PROBE_PACKET_SIDE_DATA_ENTRIES {
964 let probe = self.probe.take().expect("probe present");
965 tracing::warn!(
966 side_data_entries = side_count,
967 max_side_data_entries = MAX_PROBE_PACKET_SIDE_DATA_ENTRIES,
968 trigger = "side_data_entry_cap",
969 "hwdecode: probe rescue exhausted before consuming packet; \
970 returning AllBackendsFailed without invoking decoder"
971 );
972 return Err(Error::AllBackendsFailed(AllBackendsFailed::new(
973 probe.attempts,
974 probe.buffered_packets,
975 )));
976 }
977 // Step 2: byte / packet count cap. `packet_side_data_bytes`
978 // clamps its walk to MAX_PROBE_PACKET_SIDE_DATA_ENTRIES as
979 // defense-in-depth even though the count check above already
980 // bounded the array length.
981 let pkt_size = packet.size().saturating_add(packet_side_data_bytes(
982 packet,
983 MAX_PROBE_PACKET_SIDE_DATA_ENTRIES,
984 ));
985 let new_count = probe.buffered_packets.len() + 1;
986 let new_bytes = probe.buffered_bytes.saturating_add(pkt_size);
987 if new_count > MAX_PROBE_PACKETS || new_bytes > MAX_PROBE_PACKET_BYTES {
988 let probe = self.probe.take().expect("probe present");
989 tracing::warn!(
990 packets = new_count,
991 bytes = new_bytes,
992 side_data_entries = side_count,
993 max_packets = MAX_PROBE_PACKETS,
994 max_bytes = MAX_PROBE_PACKET_BYTES,
995 trigger = "byte_or_packet_cap",
996 "hwdecode: probe rescue exhausted before consuming packet; \
997 returning AllBackendsFailed without invoking decoder"
998 );
999 return Err(Error::AllBackendsFailed(AllBackendsFailed::new(
1000 probe.attempts,
1001 probe.buffered_packets,
1002 )));
1003 }
1004 // Step 3: pre-clone before consuming. `av_packet_ref` is a
1005 // refcounted shallow clone (no payload deep-copy) but can still
1006 // ENOMEM on heavy side-data; if it does we bail rather than
1007 // consuming a packet we can't track.
1008 match try_clone_packet(packet) {
1009 Ok(c) => Some((c, new_bytes)),
1010 Err(e) => {
1011 let probe = self.probe.take().expect("probe present");
1012 tracing::warn!(
1013 error = %e,
1014 "hwdecode: packet clone failed before consuming; \
1015 returning AllBackendsFailed without invoking decoder"
1016 );
1017 return Err(Error::AllBackendsFailed(AllBackendsFailed::new(
1018 probe.attempts,
1019 probe.buffered_packets,
1020 )));
1021 }
1022 }
1023 } else {
1024 None
1025 };
1026
1027 match self.state.inner.send_packet(packet) {
1028 Ok(()) => {
1029 if let Some((cloned, new_bytes)) = staged_clone {
1030 // Probe is still Some here: the only paths that take it are
1031 // the bailouts above (which return) and `advance_probe`'s
1032 // exhaustion (which would have propagated via `?`). Commit
1033 // the clone now that FFmpeg has accepted the packet.
1034 if let Some(probe) = self.probe.as_mut() {
1035 probe.buffered_packets.push(cloned);
1036 probe.buffered_bytes = new_bytes;
1037 }
1038 }
1039 return Ok(Sent::Accepted);
1040 }
1041 // **libavcodec's send-side flow control, guarded here and read
1042 // through the funnel — the same door the software road uses.**
1043 //
1044 // The guard and the classification are two different questions
1045 // and they get two different answers. `is_transient` decides
1046 // *whether the probe may advance*: neither `EAGAIN` nor
1047 // `AVERROR_EOF` is a candidate failing, so both are taken here,
1048 // ahead of the failure road, exactly as this one guard always
1049 // took them. `send_status` then decides *which* of the two this
1050 // is — back pressure or the double-EOF fault — and that
1051 // decision is not written here at all, so this arm cannot drift
1052 // away from the road the software decoders take. The staged
1053 // clone drops; the caller drains and re-offers, and we re-clone
1054 // at the top of the loop.
1055 //
1056 // It reads the errno through [`Self::hw_send`] rather than
1057 // classifying it raw: a refusal this crate latched during the
1058 // submission — `get_format` declining a coded surface as the
1059 // decoder configures on its first packet — must be what the
1060 // caller is told, not the `EAGAIN` libavcodec reported over the
1061 // top of it.
1062 // **Mint, then route — not mint and return.** A flow signal
1063 // leaves immediately; anything else is a verdict, and a verdict
1064 // that names a declined surface has to reach the probe or the
1065 // fallback rather than exiting plain. `BareVerdict::Reported`
1066 // is the road's own reading of an *unnamed* verdict here: the
1067 // double-EOF is the caller's fault, not the candidate's, so the
1068 // probe must not advance on it.
1069 Err(e) if is_transient(&e) => match self.hw_send(e, phase) {
1070 Ok(status) => return Ok(status),
1071 Err(reason) => match self.hw_route(reason, e, BareVerdict::Reported) {
1072 HwRoute::Report(err) => return Err(err),
1073 HwRoute::Advance(err) => {
1074 self.advance_probe(err)?;
1075 continue;
1076 }
1077 },
1078 },
1079 // A real failure. Minted once and routed by the shared policy:
1080 // while a candidate is on trial this is that candidate failing,
1081 // so `advance_probe` consumes the reason into `attempts` and
1082 // either installs the next candidate or surfaces
1083 // `AllBackendsFailed`. Any staged clone drops without entering
1084 // history; the next iteration clones afresh.
1085 Err(e) => match self.hw_failure(e, BareVerdict::CandidateFailure) {
1086 HwRoute::Report(err) => return Err(err),
1087 HwRoute::Advance(err) => {
1088 self.advance_probe(err)?;
1089 continue;
1090 }
1091 },
1092 }
1093 }
1094 }
1095
1096 /// Signal end-of-stream to the decoder.
1097 ///
1098 /// Recorded for replay only if the underlying `send_eof` succeeds. While
1099 /// the probe is active, non-transient errors trigger probe advance and
1100 /// retry, matching `send_packet`'s behaviour.
1101 ///
1102 /// Answers [`Sent::MustDrain`] on `EAGAIN` — the end-of-stream was
1103 /// **not** recorded, so drain and signal again. A second EOF is a
1104 /// caller fault and stays one; see [`send_status`].
1105 pub fn send_eof(&mut self) -> Result<Sent> {
1106 loop {
1107 // Re-read each iteration: a probe advance moves this session from
1108 // one phase to another underneath the loop.
1109 let phase = self.phase();
1110 match self.state.inner.send_eof() {
1111 Ok(()) => {
1112 self.eof_sent = true;
1113 return Ok(Sent::Accepted);
1114 }
1115 // The same guard, the same door and the same routing as
1116 // `send_packet`; see the note there.
1117 Err(e) if is_transient(&e) => match self.hw_send(e, phase) {
1118 Ok(status) => return Ok(status),
1119 Err(reason) => match self.hw_route(reason, e, BareVerdict::Reported) {
1120 HwRoute::Report(err) => return Err(err),
1121 HwRoute::Advance(err) => {
1122 self.advance_probe(err)?;
1123 continue;
1124 }
1125 },
1126 },
1127 // The same shared policy; see `send_packet`.
1128 Err(e) => match self.hw_failure(e, BareVerdict::CandidateFailure) {
1129 HwRoute::Report(err) => return Err(err),
1130 HwRoute::Advance(err) => {
1131 self.advance_probe(err)?;
1132 continue;
1133 }
1134 },
1135 }
1136 }
1137 }
1138
1139 /// Receive a CPU-side decoded frame.
1140 ///
1141 /// The frame is downloaded with `av_hwframe_transfer_data` and metadata
1142 /// is copied via `av_frame_copy_props`. The caller's frame is always
1143 /// unref'd first, so reuse across resolution changes or different
1144 /// decoders is safe.
1145 ///
1146 /// While the probe window is open, *any* non-transient failure (decode
1147 /// error, transfer error, copy_props error, or a CPU-format frame from a
1148 /// HW-opened context) tears down the current decoder and advances to the
1149 /// next hardware backend in probe order, replaying buffered packets
1150 /// through it. Frames the candidate produced during replay (drained when
1151 /// `send_packet` returned EAGAIN) are queued and delivered FIFO via this
1152 /// method, so the caller never loses initial frames after a fallback.
1153 ///
1154 /// This crate is hardware-only: there is no software fallback inside the
1155 /// decoder. When every backend in the probe order has been exhausted —
1156 /// including the case of a single-backend platform whose only backend
1157 /// failed — this returns [`Error::AllBackendsFailed`] with the per-
1158 /// backend attempt log so the caller can branch into a software
1159 /// decoder of their choice.
1160 ///
1161 /// Answers the same three states `ffmpeg::decoder::Video` does, in
1162 /// the shape the trait tier publishes: [`Received::NeedsInput`] where
1163 /// libavcodec says `EAGAIN`, [`Received::Ended`] where it says `EOF`,
1164 /// and [`Received::Frame`] when `frame` was written. **The errno
1165 /// stops here** — the two flow signals never leave this crate as
1166 /// `Error::Ffmpeg`, so a caller has nothing to decode.
1167 pub fn receive_frame(&mut self, frame: &mut Frame) -> Result<Received> {
1168 // Pre-drain frames queued during probe replay. They are already CPU-side
1169 // (transferred at drain time, when the candidate's HW context was alive)
1170 // so we just move them into the caller's slot.
1171 if self.try_pop_pending(frame) {
1172 return Ok(Received::Frame);
1173 }
1174
1175 loop {
1176 // Re-read each iteration: a probe advance moves this session from
1177 // one phase to another underneath the loop.
1178 let phase = self.phase();
1179 let res = self.state.inner.receive_frame(&mut self.hw_frame);
1180 match res {
1181 Err(e) => {
1182 // **The phase decides whether this errno is a protocol state
1183 // at all, and this arm holds no opinion of its own.**
1184 //
1185 // `EAGAIN` used to short-circuit here unconditionally, which
1186 // was right for three of the four phases and quietly wrong for
1187 // the fourth: a candidate that has been replayed the whole
1188 // history *including the end* and still answers "nothing yet"
1189 // has produced zero frames and never will. Answering the
1190 // caller `NeedsInput` there asked for input nothing could
1191 // supply; answering `Ended` would have credited a backend that
1192 // never decoded a thing. It is a candidate failing, and the
1193 // classifier says so by handing it back — straight into the
1194 // probe road below, which is where candidate failures have
1195 // always gone.
1196 //
1197 // **And it reads the errno through the funnel, which is the
1198 // law this road lost and got back.** A `get_format`
1199 // declination or an allocator-judge refusal sits in the
1200 // callback state waiting to be collected; classifying the raw
1201 // errno first answers `Ended` or `NeedsInput` for a frame this
1202 // crate itself declined, and the reason dies unread. The
1203 // funnel is no longer a step to remember — [`Self::hw_receive`]
1204 // is the only way in, and the classifiers are private to this
1205 // module so no road can take a shortcut past it.
1206 let reason = match self.hw_receive(e, phase) {
1207 Ok(status) => return Ok(status),
1208 // The funnel's verdict: the latched refusal when there was
1209 // one, the original error when there was not. It travels
1210 // onward as it is — rebuilding `Error::Ffmpeg(e)` here would
1211 // throw away the collection that just happened.
1212 Err(reason) => reason,
1213 };
1214 // **The same shared policy every hardware road uses.** This
1215 // road mints its own verdict (above), so it routes rather than
1216 // minting again. `CandidateFailure` is its reading of an
1217 // unnamed verdict: a candidate that drains to `EOF` without
1218 // ever producing a frame is a candidate failing, not a stream
1219 // ending — which is why this road hands `AVERROR_EOF` to the
1220 // probe while the send roads report it.
1221 match self.hw_route(reason, e, BareVerdict::CandidateFailure) {
1222 HwRoute::Report(err) => return Err(err),
1223 HwRoute::Advance(err) => {
1224 self.advance_probe(err)?;
1225 // Probe advance may have populated `pending_frames`;
1226 // deliver one of those before reading more from the new
1227 // candidate.
1228 if self.try_pop_pending(frame) {
1229 return Ok(Received::Frame);
1230 }
1231 continue;
1232 }
1233 }
1234 }
1235 Ok(()) => {
1236 // Always attempt the HW→CPU transfer. With strict `get_format`,
1237 // libavcodec can only deliver frames in the wired-up HW format
1238 // (or fail). If a misbehaving codec ever hands us a CPU-side
1239 // frame anyway, `av_hwframe_transfer_data` returns AVERROR(EINVAL)
1240 // (neither src nor dst has an AVHWFramesContext attached) and we
1241 // route through the same error path below.
1242 // **The transfer is priced before it is paid, and a refusal
1243 // here is final.** See [`judge_hw_transfer`]: neither ceiling
1244 // hook reaches this allocation — `hwaccel->alloc_frame`
1245 // bypasses `get_buffer2` entirely, and the CPU destination is
1246 // allocated by `av_hwframe_transfer_data` outside both — so
1247 // this is the seat that bounds what the hardware road hands
1248 // back.
1249 //
1250 // Judged out here rather than inside `transfer_hw_frame`
1251 // deliberately. Errors from that function are FFmpeg's, and
1252 // the arms below reclassify them into "the hardware failed,
1253 // fall back to software". A byte ceiling is not a hardware
1254 // failure: software would decode the same oversized frame and
1255 // be refused again, so retrying it silently is exactly the
1256 // wrong answer. The named refusal returns straight to the
1257 // caller.
1258 if let Err(e) =
1259 unsafe { judge_hw_transfer(self.hw_frame.as_ptr(), self.frame_limits.frame()) }
1260 {
1261 return Err(Error::HwTransferTooLarge(e));
1262 }
1263 match unsafe { transfer_hw_frame(frame, &mut self.hw_frame) } {
1264 Ok(()) => {
1265 self.probe = None;
1266 return Ok(Received::Frame);
1267 }
1268 Err(e) => {
1269 // The same shared policy. A transfer failure is an
1270 // HW-output problem — an unsupported CPU pix_fmt surfaces
1271 // as `AVERROR(EINVAL)`, a context loss as Bug/Bug2/Unknown
1272 // — never input corruption, so while a candidate is on
1273 // trial it is that candidate failing.
1274 match self.hw_failure(e, BareVerdict::CandidateFailure) {
1275 HwRoute::Report(err) => return Err(err),
1276 HwRoute::Advance(err) => {
1277 self.advance_probe(err)?;
1278 unsafe { av_frame_unref(frame.as_inner_mut().as_mut_ptr()) };
1279 if self.try_pop_pending(frame) {
1280 return Ok(Received::Frame);
1281 }
1282 continue;
1283 }
1284 }
1285 }
1286 }
1287 }
1288 }
1289 }
1290 }
1291
1292 /// Pop one queued frame (produced by a candidate decoder during probe
1293 /// replay) into the caller's slot. Returns `true` when a frame was
1294 /// delivered, `false` when the queue was empty.
1295 fn try_pop_pending(&mut self, frame: &mut Frame) -> bool {
1296 let Some(mut buffered) = self.pending_frames.pop_front() else {
1297 return false;
1298 };
1299 // SAFETY: `buffered` is a CPU-side AVFrame we previously transferred
1300 // and pushed into the queue; both pointers are valid.
1301 unsafe {
1302 av_frame_unref(frame.as_inner_mut().as_mut_ptr());
1303 av_frame_move_ref(frame.as_inner_mut().as_mut_ptr(), buffered.as_mut_ptr());
1304 }
1305 // Probe semantics: delivering a frame collapses the probe.
1306 self.probe = None;
1307 true
1308 }
1309
1310 /// Flush internal buffers (e.g. after a seek).
1311 ///
1312 /// Discards every frame buffered by the decoder, every frame queued during
1313 /// probe replay (`pending_frames`), and the residual `hw_frame` scratch
1314 /// buffer. Probe-time replay state (buffered packets, EOF marker) is also
1315 /// cleared since post-seek packets do not align with the previously
1316 /// captured history. After a flush, the next `receive_frame` waits for new
1317 /// post-seek input.
1318 pub fn flush(&mut self) {
1319 self.state.inner.flush();
1320 // SAFETY: hw_frame is a valid AVFrame we own; av_frame_unref is a no-op
1321 // for an already-empty frame.
1322 unsafe { av_frame_unref(self.hw_frame.as_mut_ptr()) };
1323 self.pending_frames.clear();
1324 // The end belongs to the position being abandoned.
1325 self.eof_sent = false;
1326 if let Some(probe) = self.probe.as_mut() {
1327 probe.buffered_packets.clear();
1328 probe.buffered_bytes = 0;
1329 }
1330 }
1331
1332 /// Takes the coded-surface refusal the `get_format` callback left
1333 /// behind, if it left one, clearing it for the next candidate.
1334 fn take_ceiling_declination(&self) -> Option<Error> {
1335 ceiling_declination_of(self.state.callback_state)
1336 }
1337
1338 /// **The single hardware-exit funnel.** Every road that turns a
1339 /// hardware failure — or an end-of-stream that is really a refusal —
1340 /// into an `Error` goes through here, and it reads the callback's
1341 /// declination *before* anything wraps or tears down state.
1342 ///
1343 /// The reason there is a funnel at all: a `get_format` callback
1344 /// cannot return a reason, so it leaves one behind, and every exit
1345 /// that forgets to collect it hands the caller libavcodec's
1346 /// `Invalid data found when processing input` for a refusal this
1347 /// crate made — or, on the explicit-backend road, a stream that
1348 /// simply drains to EOF with nothing said at all.
1349 ///
1350 /// The lesson this encodes: R14 claimed four consumers of the
1351 /// declination and production had exactly one. Consumers added
1352 /// helper-by-helper are lost the next time the surrounding code is
1353 /// restructured; a single funnel that every exit *must* call is the
1354 /// only version of this that stays true. The per-road table in
1355 /// `decoder/tests.rs` is what checks that it did.
1356 /// The hardware road's funnel-and-classify entry — [`software_receive`]'s
1357 /// twin, and the same law: what a caller reads is what the funnel
1358 /// found, never the errno that reached it.
1359 ///
1360 /// Answers `Err` with the funnel's verdict, which is the latched
1361 /// refusal when there was one. Callers route *that* value onward
1362 /// rather than rebuilding the raw error, or the collection is undone
1363 /// the moment it is used.
1364 fn hw_receive(&self, e: ffmpeg_next::Error, phase: SessionPhase) -> Result<Received> {
1365 receive_status(self.hw_exit(Error::Ffmpeg(e)), phase)
1366 }
1367
1368 /// The send road's half of [`Self::hw_receive`].
1369 fn hw_send(&self, e: ffmpeg_next::Error, phase: SessionPhase) -> Result<Sent> {
1370 send_status(self.hw_exit(Error::Ffmpeg(e)), phase)
1371 }
1372
1373 fn hw_exit(&self, fallback: Error) -> Error {
1374 self
1375 .take_ceiling_declination()
1376 .or_else(|| frame_budget_declination_of(self.state.callback_state))
1377 .unwrap_or(fallback)
1378 }
1379
1380 /// Try the next backend in `remaining_backends`. Transactional: a
1381 /// candidate must successfully build and accept the replayed history
1382 /// before any probe state is consumed. Backends that fail to build or
1383 /// reject the replay are recorded into `probe.attempts` and the loop
1384 /// continues to the next one.
1385 ///
1386 /// `last_error` is the error that triggered this advance — i.e. the
1387 /// failure of the currently active backend on `send_packet` /
1388 /// `send_eof` / `receive_frame`. It is recorded against the active
1389 /// backend before any candidate is tried so that a final
1390 /// `AllBackendsFailed` carries the full attempt log including the
1391 /// initially-opened backend's runtime failure.
1392 ///
1393 /// Returns:
1394 /// - `Ok(())` when a candidate is installed and replay completed —
1395 /// caller should retry the operation.
1396 /// - `Err(Error::AllBackendsFailed(p))` when every remaining
1397 /// backend has been exhausted (including the just-failed active one).
1398 /// `p.attempts()` carries the per-backend failure log.
1399 /// This is what the documented `open` contract promises, surfaced at
1400 /// runtime so the caller can branch into a software fallback. On a
1401 /// single-backend platform (e.g. macOS), this fires after the only
1402 /// backend's first-frame failure; on multi-backend platforms it
1403 /// fires after the last candidate's failure.
1404 /// - `Err(_)` for other fatal conditions surfaced by probe machinery
1405 /// itself (e.g. `alloc_av_frame` ENOMEM during replay drain).
1406 fn advance_probe(&mut self, last_error: Error) -> Result<()> {
1407 // Record the failure that triggered this advance against the active
1408 // backend. If the probe was somehow already gone (shouldn't happen —
1409 // call sites guard with `self.probe.is_some()`), just propagate the
1410 // error so behaviour matches the pre-fix code path.
1411 let active_backend = self.state.backend;
1412 // **The reason the callback could not return.** Declining a format
1413 // in `get_format` surfaces from libavcodec as
1414 // `Invalid data found when processing input` — true about what it
1415 // saw, false about what happened, because the data was fine and
1416 // this crate declined it over the coded surface's size. The
1417 // callback leaves the real reason in its own state; this is where
1418 // it becomes the error the caller reads.
1419 // **Mint or no-op, and never a re-derivation.** Three of this
1420 // method's callers hand it a raw `Error::Ffmpeg` — no funnel has run
1421 // on their roads — so this is where their verdict is minted. The
1422 // receive road hands it one already minted, and this call then finds
1423 // the latch empty and returns its argument unchanged: `hw_exit`
1424 // answers with the recorded refusal when there is one and with its
1425 // fallback when there is not, so a verdict passed in comes back out.
1426 // Either way the caller's reason is what gets recorded. See the
1427 // invariant on [`software_receive`].
1428 let last_error = self.hw_exit(last_error);
1429 match self.probe.as_mut() {
1430 Some(probe) => probe.attempts.push((active_backend, Box::new(last_error))),
1431 None => return Err(last_error),
1432 }
1433
1434 // Drop frames previously queued from the backend we're now abandoning.
1435 // They came from a candidate that just failed for cause and cannot be
1436 // trusted alongside frames we may queue from the next candidate. (If
1437 // this method is called repeatedly via chained probe advances, this
1438 // also keeps `pending_frames` from accumulating frames from multiple
1439 // rejected backends.)
1440 self.pending_frames.clear();
1441 // Read before any `probe` borrow: the end is the *decoder's* fact
1442 // now, not the probe's, and a candidate must be handed it along
1443 // with the replayed history or it will sit at `EAGAIN` forever on a
1444 // stream that is already over.
1445 let eof_sent = self.eof_sent;
1446
1447 loop {
1448 // Snapshot inputs without mutating probe state. Use the checked
1449 // clone helper rather than `Parameters::clone` (which masks ENOMEM).
1450 let (next_backend, parameters, codec) = match self.probe.as_ref() {
1451 Some(probe) if !probe.remaining_backends.is_empty() => {
1452 let parameters = match try_clone_parameters(
1453 &probe.parameters,
1454 self.frame_limits.max_codec_parameter_bytes(),
1455 ) {
1456 Ok(p) => p,
1457 Err(e) => {
1458 tracing::warn!(
1459 error = %e,
1460 "hwdecode: parameters clone failed during probe advance; popping backend and trying next"
1461 );
1462 let popped = self
1463 .probe
1464 .as_mut()
1465 .expect("probe state present")
1466 .remaining_backends
1467 .remove(0);
1468 self
1469 .probe
1470 .as_mut()
1471 .expect("probe state present")
1472 .attempts
1473 .push((popped, Box::new(e)));
1474 continue;
1475 }
1476 };
1477 (probe.remaining_backends[0], parameters, probe.codec)
1478 }
1479 // No more candidates — surface the accumulated attempt log as
1480 // AllBackendsFailed so single- and multi-backend platforms have
1481 // the same contract for "every HW backend failed."
1482 //
1483 // Hand the buffered packet history back to the caller along
1484 // with the attempt log: those packets were consumed from the
1485 // caller's demuxer (and refcounted-cloned into `buffered_packets`)
1486 // before the probe exhausted, and for non-seekable inputs the
1487 // caller cannot re-demux them. Returning them here lets a
1488 // caller-side software fallback replay the same byte history
1489 // through `ffmpeg::decoder::Video` without losing initial frames.
1490 // Dropping `ProbeState` after the take frees the codec/params
1491 // refs we no longer need; only `attempts` and `buffered_packets`
1492 // are retained.
1493 _ => {
1494 let (attempts, unconsumed_packets) = self
1495 .probe
1496 .take()
1497 .map(|p| (p.attempts, p.buffered_packets))
1498 .unwrap_or_default();
1499 return Err(Error::AllBackendsFailed(AllBackendsFailed::new(
1500 attempts,
1501 unconsumed_packets,
1502 )));
1503 }
1504 };
1505
1506 let prev_backend = self.state.backend;
1507 tracing::warn!(from = ?prev_backend, to = ?next_backend, "hwdecode: advancing probe");
1508
1509 // Build candidate. On failure, record into attempts and continue
1510 // without touching the packet buffer.
1511 let mut candidate_state =
1512 match Self::build_state(parameters, codec, next_backend, self.frame_limits) {
1513 Ok(s) => s,
1514 Err(e) => {
1515 tracing::warn!(?next_backend, error = %e, "hwdecode: candidate build failed");
1516 self
1517 .probe
1518 .as_mut()
1519 .expect("probe state present")
1520 .remaining_backends
1521 .remove(0);
1522 self
1523 .probe
1524 .as_mut()
1525 .expect("probe state present")
1526 .attempts
1527 .push((next_backend, Box::new(e)));
1528 continue;
1529 }
1530 };
1531
1532 // Replay buffered history through the candidate WITHOUT installing it.
1533 // We borrow the buffer immutably; if replay fails the candidate's Drop
1534 // releases the FFmpeg state and the buffer is preserved for the next
1535 // attempt.
1536 //
1537 // EAGAIN handling: `avcodec_send_packet` may return EAGAIN when its
1538 // internal queue is full and the user is expected to drain output
1539 // first (B-frame buffering, candidate-specific queue depth, etc.).
1540 // This is normal flow — we drain frames out of the candidate, transfer
1541 // each one to a CPU frame, and stash them in `local_pending`. After
1542 // commit they move to `self.pending_frames` and are delivered FIFO
1543 // by `receive_frame`, so the caller never loses initial frames.
1544 let mut local_pending: VecDeque<frame::Video> = VecDeque::new();
1545 let mut local_pending_bytes: usize = 0;
1546 let max_pending_bytes = self.max_probe_pending_bytes;
1547 let replay_result: std::result::Result<(), ffmpeg_next::Error> = {
1548 let probe = self.probe.as_ref().expect("probe state present");
1549 let mut hw_buf = match alloc_av_frame() {
1550 Ok(f) => f,
1551 Err(e) => return Err(Error::Ffmpeg(e)),
1552 };
1553 let mut r: std::result::Result<(), ffmpeg_next::Error> = Ok(());
1554
1555 'replay: for pkt in &probe.buffered_packets {
1556 loop {
1557 match candidate_state.inner.send_packet(pkt) {
1558 Ok(()) => break,
1559 Err(e) if is_eagain(&e) => {
1560 // Drain candidate output (transferring + queueing each frame)
1561 // and retry the same packet.
1562 if let Err(de) = drain_into_pending(
1563 &mut candidate_state.inner,
1564 &mut hw_buf,
1565 &mut local_pending,
1566 &mut local_pending_bytes,
1567 max_pending_bytes,
1568 self.frame_limits.frame(),
1569 ) {
1570 r = Err(de);
1571 break 'replay;
1572 }
1573 }
1574 Err(e) => {
1575 r = Err(e);
1576 break 'replay;
1577 }
1578 }
1579 }
1580 }
1581 if r.is_ok() && eof_sent {
1582 // `avcodec_send_packet(NULL)` (which `send_eof` becomes) can
1583 // return EAGAIN with the same drain-output-first semantics as
1584 // a regular send_packet. Loop drain+retry instead of failing
1585 // the candidate on backpressure.
1586 loop {
1587 match candidate_state.inner.send_eof() {
1588 Ok(()) => break,
1589 Err(e) if is_eagain(&e) => {
1590 if let Err(de) = drain_into_pending(
1591 &mut candidate_state.inner,
1592 &mut hw_buf,
1593 &mut local_pending,
1594 &mut local_pending_bytes,
1595 max_pending_bytes,
1596 self.frame_limits.frame(),
1597 ) {
1598 r = Err(de);
1599 break;
1600 }
1601 }
1602 Err(e) => {
1603 r = Err(e);
1604 break;
1605 }
1606 }
1607 }
1608 }
1609 r
1610 };
1611
1612 if let Err(e) = replay_result {
1613 tracing::warn!(?next_backend, error = %e, "hwdecode: candidate replay failed");
1614 // **The candidate's own refusal, read before the candidate
1615 // dies.** `hw_exit` consults `self.state` — the backend that is
1616 // still active — but the error being recorded here belongs to
1617 // `candidate_state`, whose `get_format` callback is the one
1618 // that may have declined. Classifying through the wrong state
1619 // and then dropping the right one lost the reason entirely: the
1620 // attempt log recorded FFmpeg's `Invalid data found when
1621 // processing input` for a coded surface this crate refused.
1622 //
1623 // Order matters and is the whole fix — read, then drop.
1624 let recorded =
1625 ceiling_declination_of(candidate_state.callback_state).unwrap_or(Error::Ffmpeg(e));
1626 // Drop candidate explicitly so its FFI cleanup runs now. Discard any
1627 // frames we drained from this candidate — they're tied to a decoder
1628 // we're throwing away.
1629 drop(candidate_state);
1630 drop(local_pending);
1631 self
1632 .probe
1633 .as_mut()
1634 .expect("probe state present")
1635 .remaining_backends
1636 .remove(0);
1637 self
1638 .probe
1639 .as_mut()
1640 .expect("probe state present")
1641 .attempts
1642 .push((next_backend, Box::new(recorded)));
1643 continue;
1644 }
1645
1646 // Commit: install the candidate, clear residual hw_frame, queue the
1647 // drained frames for the caller, and pop the now-active backend.
1648 self.state = candidate_state;
1649 unsafe { av_frame_unref(self.hw_frame.as_mut_ptr()) };
1650 self.pending_frames.append(&mut local_pending);
1651 self
1652 .probe
1653 .as_mut()
1654 .expect("probe state present")
1655 .remaining_backends
1656 .remove(0);
1657 return Ok(());
1658 }
1659 }
1660
1661 /// Build raw FFmpeg state for one hardware backend. Strict `get_format`
1662 /// (NONE on missing HW format); cross-backend fallback is the caller's job.
1663 fn build_state(
1664 parameters: codec::Parameters,
1665 codec: Codec,
1666 backend: Backend,
1667 limits: crate::limits::DecoderLimits,
1668 ) -> Result<DecoderState> {
1669 // Use our checked allocator instead of Context::from_parameters, which
1670 // does not null-check avcodec_alloc_context3 and would feed a null
1671 // AVCodecContext into FFmpeg under OOM.
1672 let (mut ctx, mut state) = build_codec_context(¶meters, limits)?;
1673 let av_type = backend.av_hwdevice_type();
1674
1675 // Verify the codec advertises this hwaccel **with the exact HW pix_fmt
1676 // we're about to wire up in `get_format`**. FFmpeg's HW config table
1677 // is keyed per (device_type, pix_fmt); a codec can advertise the same
1678 // device with several HW pix_fmts, so matching only on device_type
1679 // would let probing succeed for a backend whose pix_fmt the codec
1680 // never offers — the failure would then surface deep inside the
1681 // probe/decode loop. Matching the exact pix_fmt keeps the strict
1682 // `get_format` honest and gives `open_with` a clean rejection.
1683 let hw_pix_fmt = backend.hw_pixel_format();
1684 if !codec_supports_hwaccel(unsafe { codec.as_ptr() }, av_type, hw_pix_fmt as i32) {
1685 return Err(Error::BackendUnsupportedByCodec(backend));
1686 }
1687
1688 // Create the device context.
1689 let mut hw_device_ref: *mut AVBufferRef = ptr::null_mut();
1690 // SAFETY: `hw_device_ref` is a stack ptr we hand FFmpeg to fill.
1691 let ret = unsafe {
1692 av_hwdevice_ctx_create(&mut hw_device_ref, av_type, ptr::null(), ptr::null_mut(), 0)
1693 };
1694 if ret < 0 {
1695 return Err(Error::HwDeviceInitFailed(HwDeviceInitFailed::new(
1696 backend,
1697 ffmpeg_next::Error::from(ret),
1698 )));
1699 }
1700
1701 // The state `build_codec_context` already installed in `opaque`,
1702 // told which format this backend wants. One allocation, one seat:
1703 // the budget the judge reads and the declination the funnel reads
1704 // are the same object, and `Box::into_raw` hands its ownership to
1705 // the guard below without moving it — so the pointer the context
1706 // holds stays the one that is freed.
1707 state.wanted = hw_pix_fmt;
1708 state.wanted_int = hw_pix_fmt as i32;
1709 let callback_state = Box::into_raw(state);
1710 // RAII guard: from now until the end-of-function `into_owned()`, every
1711 // early return — `av_buffer_ref` failure, `open_as` failure, codec_type
1712 // mismatch, or any future error path added between here and the
1713 // `DecoderState` construction — frees `hw_device_ref` and
1714 // `callback_state` via the guard's Drop. Without it, each error site
1715 // had to remember to clean up these two FFI-owned resources by hand;
1716 // the codec_type-mismatch branch was missed and silently leaked one
1717 // device ref + one heap allocation per bad input.
1718 let guard = PartialBuildState {
1719 hw_device_ref,
1720 callback_state,
1721 };
1722
1723 // SAFETY: ctx is a freshly-constructed AVCodecContext we own;
1724 // av_buffer_ref bumps the refcount of the device buffer for FFmpeg's
1725 // use (we keep our own ref in `hw_device_ref` for cleanup).
1726 // av_buffer_ref returns NULL on allocation failure; we must check it
1727 // before assigning, otherwise the codec context would be opened with a
1728 // HW-flagged setup but no actual device reference.
1729 let device_ref_for_ctx = unsafe { av_buffer_ref(hw_device_ref) };
1730 if device_ref_for_ctx.is_null() {
1731 // guard's Drop frees hw_device_ref (the first ref) and callback_state.
1732 return Err(Error::Ffmpeg(ffmpeg_next::Error::Other {
1733 errno: libc::ENOMEM,
1734 }));
1735 }
1736 // SAFETY: device_ref_for_ctx is a valid AVBufferRef* from av_buffer_ref;
1737 // ctx is freshly built and owned by us. After this point ctx aliases
1738 // `callback_state` via `opaque` (FFmpeg never frees opaque, so
1739 // `callback_state` ownership stays with us / the guard) and aliases
1740 // `device_ref_for_ctx` (the second ref) via `hw_device_ctx` (FFmpeg
1741 // unrefs that on codec context drop, independent of the guard's first
1742 // ref).
1743 unsafe {
1744 let raw = ctx.as_mut_ptr();
1745 (*raw).hw_device_ctx = device_ref_for_ctx;
1746 (*raw).opaque = callback_state.cast();
1747 (*raw).get_format = Some(get_hw_format);
1748 }
1749
1750 // Open the decoder. On failure `ctx`/`opened` Drop releases the codec
1751 // context (and via that the second device ref); the guard releases the
1752 // first device ref and the callback state.
1753 //
1754 // We deliberately bypass `Opened::video()` because it calls
1755 // `Context::medium()`, which reads `AVCodecContext.codec_type` as the
1756 // bindgen `AVMediaType` enum — the same UB hazard we've been
1757 // systematically removing. Instead: validate `codec_type` as a raw
1758 // `c_int` ourselves, then construct the `decoder::Video` wrapper
1759 // directly via its public tuple field.
1760 // Through the funnel's free-standing half — there is no decoder yet
1761 // to ask, and the guard frees the callback state on the way out, so
1762 // the reason has to be collected here or not at all.
1763 let opened = match ctx.decoder().open_as(codec) {
1764 Ok(opened) => opened,
1765 Err(e) => return Err(ceiling_declination_of(callback_state).unwrap_or(Error::Ffmpeg(e))),
1766 };
1767
1768 // Validate codec_type as a raw integer — never construct AVMediaType
1769 // from an unvalidated runtime value. On failure `opened`'s Drop
1770 // releases the codec context; the guard releases the first
1771 // hw_device_ref and the callback state.
1772 if let Err(e) = ensure_video_codec_type(&opened) {
1773 // Same exit, same collection: a declined format can leave the
1774 // context looking like the wrong medium.
1775 return Err(ceiling_declination_of(callback_state).unwrap_or(e));
1776 }
1777 // SAFETY of construction: `decoder::Video` is `pub struct Video(pub Opened)`.
1778 // We construct via the public field; this is the same wrapping
1779 // `Opened::video()` does on success, just without the enum read.
1780 let opened = ffmpeg_next::decoder::Video(opened);
1781
1782 // Disarm the guard and transfer ownership of both resources into the
1783 // returned DecoderState (whose own Drop handles their lifetime).
1784 let (hw_device_ref, callback_state) = guard.into_owned();
1785 Ok(DecoderState {
1786 inner: ManuallyDrop::new(opened),
1787 backend,
1788 hw_device_ref,
1789 callback_state,
1790 })
1791 }
1792}
1793
1794/// RAII guard for the partially-owned FFmpeg state that
1795/// [`VideoDecoder::build_state`] holds between the
1796/// `av_hwdevice_ctx_create` and `Box::into_raw(CallbackState)`
1797/// allocations and the final `DecoderState` construction.
1798///
1799/// If `build_state` returns `Err` for any reason in that window
1800/// (`av_buffer_ref` ENOMEM, `open_as` failure, codec_type mismatch, or
1801/// any future error path), this guard's `Drop` releases
1802/// `hw_device_ref` — the first ref returned by `av_hwdevice_ctx_create`,
1803/// distinct from the second ref FFmpeg unrefs when the codec context
1804/// drops — and the boxed `CallbackState`, which FFmpeg never touches
1805/// because `AVCodecContext::opaque` is purely user-owned.
1806///
1807/// Successful construction calls [`Self::into_owned`] to disarm the
1808/// guard and hand both pointers to the new `DecoderState`.
1809struct PartialBuildState {
1810 hw_device_ref: *mut AVBufferRef,
1811 callback_state: *mut CallbackState,
1812}
1813
1814impl PartialBuildState {
1815 /// Disarm the guard: return the owned pointers and replace the guard's
1816 /// fields with null so its Drop is a no-op.
1817 fn into_owned(mut self) -> (*mut AVBufferRef, *mut CallbackState) {
1818 let hw = std::mem::replace(&mut self.hw_device_ref, ptr::null_mut());
1819 let cb = std::mem::replace(&mut self.callback_state, ptr::null_mut());
1820 (hw, cb)
1821 }
1822}
1823
1824impl Drop for PartialBuildState {
1825 fn drop(&mut self) {
1826 // SAFETY: pointers are either freshly allocated by `build_state` (via
1827 // `av_hwdevice_ctx_create` and `Box::into_raw`) or null after
1828 // `into_owned`. Both `av_buffer_unref` and `Box::from_raw` need the
1829 // null check we apply here; both are otherwise sound on resources we
1830 // own.
1831 unsafe {
1832 if !self.hw_device_ref.is_null() {
1833 let mut hw = self.hw_device_ref;
1834 av_buffer_unref(&mut hw);
1835 }
1836 if !self.callback_state.is_null() {
1837 drop(Box::from_raw(self.callback_state));
1838 }
1839 }
1840 }
1841}
1842
1843/// Download a HW frame into a CPU [`Frame`]. Always unrefs the destination
1844/// first so reuse across resolution changes is safe.
1845///
1846/// Deliberately does **not** call `av_frame_copy_props`. That FFmpeg
1847/// helper deep-copies AVFrame side data (SEI, mastering display, ICC
1848/// profiles, dynamic HDR, etc.), the metadata dict, and bumps both
1849/// `opaque_ref` and `private_ref` on every receive — none of which
1850/// `Frame` exposes via its public accessors. On a crafted stream with
1851/// megabytes of per-frame metadata that would mean an unbounded
1852/// allocation per receive, with no caller-visible benefit. We instead
1853/// copy only the scalar fields the public API can read (today: `pts`);
1854/// pixel layout (`width`, `height`, `format`, `linesize`, `data`) is
1855/// already set by `av_hwframe_transfer_data`. If `Frame` ever grows
1856/// accessors for timing extras (`duration`, `time_base`, `pkt_dts`) or
1857/// color metadata, add those to `copy_frame_props_minimal` at the same
1858/// time.
1859unsafe fn transfer_hw_frame(
1860 dst: &mut Frame,
1861 src: &mut frame::Video,
1862) -> std::result::Result<(), ffmpeg_next::Error> {
1863 unsafe {
1864 av_frame_unref(dst.as_inner_mut().as_mut_ptr());
1865 let ret = av_hwframe_transfer_data(dst.as_inner_mut().as_mut_ptr(), src.as_ptr(), 0);
1866 if ret < 0 {
1867 return Err(ffmpeg_next::Error::from(ret));
1868 }
1869 // Validate the post-transfer CPU pix_fmt against the safe `Frame`
1870 // accessor's supported set. FFmpeg picks the destination format
1871 // when `dst.format == AV_PIX_FMT_NONE` on entry (which it always is
1872 // here — `av_frame_unref` clears it) by walking the result of
1873 // `av_hwframe_transfer_get_formats`. Driver/version ordering can
1874 // pick a layout outside our NV*/P0xx/P2xx/P4xx set; the call would
1875 // return success while the resulting frame is unreadable through
1876 // `Frame::row` / `Frame::as_ptr` (those return `None` for
1877 // unsupported formats). Surface the unsupported result as a
1878 // transfer failure so `receive_frame`'s probe-active path advances
1879 // to the next backend rather than collapsing on an unusable frame;
1880 // post-probe, the caller gets an `Err` they can branch into a
1881 // software fallback.
1882 let dst_raw_fmt: i32 = (*dst.as_inner_mut().as_ptr()).format;
1883 let dst_pix_fmt = crate::boundary::from_av_pixel_format(dst_raw_fmt);
1884 if !crate::frame::is_supported_cpu_pix_fmt(&dst_pix_fmt) {
1885 tracing::warn!(
1886 pix_fmt = dst_raw_fmt,
1887 "hwdecode: hw->cpu transfer produced unsupported pix_fmt; \
1888 treating as backend failure"
1889 );
1890 av_frame_unref(dst.as_inner_mut().as_mut_ptr());
1891 return Err(ffmpeg_next::Error::Other {
1892 errno: libc::EINVAL,
1893 });
1894 }
1895 if let Err(e) = copy_frame_props_minimal(dst.as_inner_mut().as_mut_ptr(), src.as_ptr()) {
1896 // Failed to propagate metadata. Reset the destination so the
1897 // partial frame doesn't leak (its pixel buffers were attached
1898 // by `av_hwframe_transfer_data` above) and surface as a
1899 // backend failure — the probe path will advance to the next
1900 // candidate; post-probe, the caller branches into SW fallback.
1901 av_frame_unref(dst.as_inner_mut().as_mut_ptr());
1902 return Err(e);
1903 }
1904 }
1905 Ok(())
1906}
1907
1908/// Copies AVFrame metadata (timestamps, color metadata, crop rect,
1909/// flags, side data, etc.) from the source HW frame to the destination
1910/// CPU frame so the post-transfer frame surfaces the same metadata a
1911/// SW-decoded frame would.
1912///
1913/// Defers to FFmpeg's `av_frame_copy_props`, which handles the per-
1914/// `side_data[i]` allocation, dict copy, and refcounted buffer
1915/// replacements internally. The cost is bounded by what the source
1916/// frame attaches — typical HDR streams carry 1–3 side-data entries
1917/// (mastering display, content light level, dolby/HDR10+ dynamic
1918/// metadata) totalling a few hundred bytes, so per-frame allocation
1919/// overhead stays negligible relative to the pixel data already
1920/// transferred via `av_hwframe_transfer_data`.
1921///
1922/// # Safety
1923/// Both pointers must be valid `AVFrame` pointers we own. We do not
1924/// form `&AVFrame` — `av_frame_copy_props` operates on raw pointers
1925/// directly.
1926/// Sum the byte sizes of every entry in `(*frame).side_data[]`.
1927/// Used by the probe replay queue's byte-cap accounting so a
1928/// frame's deep-copied side-data is charged against
1929/// `max_probe_pending_bytes` along with its pixel buffers.
1930///
1931/// # Safety
1932/// `frame` must be a live `*const AVFrame`. Reads only `nb_side_data`,
1933/// the `side_data` pointer array, and each `AVFrameSideData.size` —
1934/// no `&AVFrame` reference is formed.
1935unsafe fn sum_side_data_bytes(frame: *const AVFrame) -> usize {
1936 // Clamp `nb_side_data` to the same entry cap the copy path
1937 // enforces. Without the clamp, a decoder-controlled or
1938 // version-skew `nb_side_data` value (the bindgen field is
1939 // `c_int`, signed) could drive this walk arbitrarily long
1940 // before the cap downstream kicks in. Negative values are
1941 // pinned to zero before casting.
1942 let raw = unsafe { (*frame).nb_side_data };
1943 let arr = unsafe { (*frame).side_data };
1944 if raw <= 0 || arr.is_null() {
1945 return 0;
1946 }
1947 let count = (raw as usize).min(HW_COPY_SIDE_DATA_MAX_ENTRIES);
1948 let mut total: usize = 0;
1949 for i in 0..count {
1950 // SAFETY: `arr` points to `nb_side_data` valid `*mut AVFrameSideData`
1951 // entries per FFmpeg's contract; `i < count` is in-bounds.
1952 let entry = unsafe { *arr.add(i) };
1953 if entry.is_null() {
1954 continue;
1955 }
1956 let sz = unsafe { (*entry).size };
1957 total = total.saturating_add(sz);
1958 if total >= HW_COPY_SIDE_DATA_MAX_TOTAL_BYTES {
1959 // Already at or above the byte cap — further entries can't
1960 // change the projected-vs-cap decision the caller makes.
1961 total = HW_COPY_SIDE_DATA_MAX_TOTAL_BYTES;
1962 break;
1963 }
1964 }
1965 total
1966}
1967
1968/// Hard cap on the number of `AVFrameSideData` entries we copy from
1969/// HW source frame to CPU destination frame on the HW transfer
1970/// path. Mirrors `convert::SIDE_DATA_MAX_ENTRIES`; the public
1971/// converter re-enforces the same cap so this is defense in depth.
1972const HW_COPY_SIDE_DATA_MAX_ENTRIES: usize = 64;
1973/// Hard cap on the total side-data byte budget per HW transfer.
1974/// Mirrors `convert::SIDE_DATA_MAX_TOTAL_BYTES`.
1975const HW_COPY_SIDE_DATA_MAX_TOTAL_BYTES: usize = 256 * 1024;
1976
1977/// Maps a raw `AV_FRAME_DATA_*` integer to the matching bindgen
1978/// `AVFrameSideDataType` enum value when (and only when) the integer
1979/// is a known discriminant in the linked FFmpeg's bindgen output.
1980/// Returns `None` for unknown / version-skew / corrupt values —
1981/// the caller drops those entries instead of `transmute`-ing an
1982/// arbitrary integer back into the enum (which would be immediate
1983/// UB if the discriminant isn't in the enum's set).
1984///
1985/// The whitelist covers the entries safe to preserve across HW
1986/// transfer:
1987/// - HDR10 / HDR10+ / Dolby Vision / Vivid / ambient HDR metadata
1988/// - SMPTE / GOP timecodes
1989/// - ICC color profile
1990/// - A53 closed captions
1991/// - Spherical / display matrix orientation
1992/// - Stereo3D layout
1993///
1994/// Other AV_FRAME_DATA_* constants exist (motion vectors, encoder
1995/// params, RPU buffers, …) but are either decoder-internal or
1996/// rarely useful through the public mediadecode API; dropping them
1997/// is the safe default.
1998fn whitelisted_side_data_kind(kind_raw: i32) -> Option<ffmpeg_next::ffi::AVFrameSideDataType> {
1999 use ffmpeg_next::ffi::AVFrameSideDataType;
2000 // Each match arm compares `kind_raw` against the i32 cast of a
2001 // known constant, then returns the constant itself — we never
2002 // construct the enum from arbitrary integer bytes.
2003 let kind = match kind_raw {
2004 x if x == AVFrameSideDataType::AV_FRAME_DATA_PANSCAN as i32 => {
2005 AVFrameSideDataType::AV_FRAME_DATA_PANSCAN
2006 }
2007 x if x == AVFrameSideDataType::AV_FRAME_DATA_A53_CC as i32 => {
2008 AVFrameSideDataType::AV_FRAME_DATA_A53_CC
2009 }
2010 x if x == AVFrameSideDataType::AV_FRAME_DATA_STEREO3D as i32 => {
2011 AVFrameSideDataType::AV_FRAME_DATA_STEREO3D
2012 }
2013 x if x == AVFrameSideDataType::AV_FRAME_DATA_DISPLAYMATRIX as i32 => {
2014 AVFrameSideDataType::AV_FRAME_DATA_DISPLAYMATRIX
2015 }
2016 x if x == AVFrameSideDataType::AV_FRAME_DATA_AFD as i32 => {
2017 AVFrameSideDataType::AV_FRAME_DATA_AFD
2018 }
2019 x if x == AVFrameSideDataType::AV_FRAME_DATA_MASTERING_DISPLAY_METADATA as i32 => {
2020 AVFrameSideDataType::AV_FRAME_DATA_MASTERING_DISPLAY_METADATA
2021 }
2022 x if x == AVFrameSideDataType::AV_FRAME_DATA_GOP_TIMECODE as i32 => {
2023 AVFrameSideDataType::AV_FRAME_DATA_GOP_TIMECODE
2024 }
2025 x if x == AVFrameSideDataType::AV_FRAME_DATA_SPHERICAL as i32 => {
2026 AVFrameSideDataType::AV_FRAME_DATA_SPHERICAL
2027 }
2028 x if x == AVFrameSideDataType::AV_FRAME_DATA_CONTENT_LIGHT_LEVEL as i32 => {
2029 AVFrameSideDataType::AV_FRAME_DATA_CONTENT_LIGHT_LEVEL
2030 }
2031 x if x == AVFrameSideDataType::AV_FRAME_DATA_ICC_PROFILE as i32 => {
2032 AVFrameSideDataType::AV_FRAME_DATA_ICC_PROFILE
2033 }
2034 x if x == AVFrameSideDataType::AV_FRAME_DATA_S12M_TIMECODE as i32 => {
2035 AVFrameSideDataType::AV_FRAME_DATA_S12M_TIMECODE
2036 }
2037 x if x == AVFrameSideDataType::AV_FRAME_DATA_DYNAMIC_HDR_PLUS as i32 => {
2038 AVFrameSideDataType::AV_FRAME_DATA_DYNAMIC_HDR_PLUS
2039 }
2040 x if x == AVFrameSideDataType::AV_FRAME_DATA_REGIONS_OF_INTEREST as i32 => {
2041 AVFrameSideDataType::AV_FRAME_DATA_REGIONS_OF_INTEREST
2042 }
2043 x if x == AVFrameSideDataType::AV_FRAME_DATA_SEI_UNREGISTERED as i32 => {
2044 AVFrameSideDataType::AV_FRAME_DATA_SEI_UNREGISTERED
2045 }
2046 x if x == AVFrameSideDataType::AV_FRAME_DATA_FILM_GRAIN_PARAMS as i32 => {
2047 AVFrameSideDataType::AV_FRAME_DATA_FILM_GRAIN_PARAMS
2048 }
2049 x if x == AVFrameSideDataType::AV_FRAME_DATA_DOVI_RPU_BUFFER as i32 => {
2050 AVFrameSideDataType::AV_FRAME_DATA_DOVI_RPU_BUFFER
2051 }
2052 x if x == AVFrameSideDataType::AV_FRAME_DATA_DOVI_METADATA as i32 => {
2053 AVFrameSideDataType::AV_FRAME_DATA_DOVI_METADATA
2054 }
2055 x if x == AVFrameSideDataType::AV_FRAME_DATA_DYNAMIC_HDR_VIVID as i32 => {
2056 AVFrameSideDataType::AV_FRAME_DATA_DYNAMIC_HDR_VIVID
2057 }
2058 x if x == AVFrameSideDataType::AV_FRAME_DATA_AMBIENT_VIEWING_ENVIRONMENT as i32 => {
2059 AVFrameSideDataType::AV_FRAME_DATA_AMBIENT_VIEWING_ENVIRONMENT
2060 }
2061 _ => return None,
2062 };
2063 Some(kind)
2064}
2065
2066unsafe fn copy_frame_props_minimal(
2067 dst: *mut AVFrame,
2068 src: *const AVFrame,
2069) -> std::result::Result<(), ffmpeg_next::Error> {
2070 // We deliberately do NOT use `av_frame_copy_props` here, despite
2071 // its convenience. Upstream `av_frame_copy_props` deep-copies
2072 // *every* `AVFrameSideData` entry, the metadata `AVDictionary`,
2073 // and refcounted `opaque_ref` / `private_ref` buffers — all from
2074 // attacker-controlled decoder output. A crafted stream with many
2075 // multi-MiB side-data entries could drive the per-frame
2076 // allocation cost arbitrarily high (one alloc per entry, with the
2077 // entry's bytes copied via `memcpy`). The downstream
2078 // `convert::collect_side_data` cap helps the *Rust* side but the
2079 // FFmpeg-side allocations have already happened.
2080 //
2081 // Instead we copy scalar fields manually (timestamps, color
2082 // metadata, picture type, flags) and copy side-data with a hard
2083 // cap matching the converter's. Metadata dict and opaque_ref /
2084 // private_ref are intentionally NOT copied — they're rarely
2085 // populated on decoded frames and represent unbounded surfaces.
2086 use core::ptr::{addr_of, addr_of_mut, read_unaligned, write_unaligned};
2087 use ffmpeg_next::ffi::av_frame_new_side_data;
2088 unsafe {
2089 // Scalar timestamps / flags / color / SAR / crop. None of
2090 // these allocate.
2091 (*dst).pts = (*src).pts;
2092 (*dst).pkt_dts = (*src).pkt_dts;
2093 (*dst).duration = (*src).duration;
2094 (*dst).best_effort_timestamp = (*src).best_effort_timestamp;
2095 (*dst).quality = (*src).quality;
2096 (*dst).repeat_pict = (*src).repeat_pict;
2097 (*dst).flags = (*src).flags;
2098 (*dst).sample_aspect_ratio = (*src).sample_aspect_ratio;
2099 (*dst).crop_left = (*src).crop_left;
2100 (*dst).crop_top = (*src).crop_top;
2101 (*dst).crop_right = (*src).crop_right;
2102 (*dst).crop_bottom = (*src).crop_bottom;
2103 (*dst).time_base = (*src).time_base;
2104
2105 // Enum-typed fields: bit-copy raw to avoid materializing an
2106 // invalid `AVColorPrimaries` etc. on either side. `read_unaligned`
2107 // / `write_unaligned` on `i32` projections sidestep the bindgen
2108 // enum's discriminant-validity invariant.
2109 let pict_type_raw = read_unaligned(addr_of!((*src).pict_type) as *const i32);
2110 write_unaligned(addr_of_mut!((*dst).pict_type) as *mut i32, pict_type_raw);
2111 let cp_raw = read_unaligned(addr_of!((*src).color_primaries) as *const i32);
2112 write_unaligned(addr_of_mut!((*dst).color_primaries) as *mut i32, cp_raw);
2113 let trc_raw = read_unaligned(addr_of!((*src).color_trc) as *const i32);
2114 write_unaligned(addr_of_mut!((*dst).color_trc) as *mut i32, trc_raw);
2115 let cs_raw = read_unaligned(addr_of!((*src).colorspace) as *const i32);
2116 write_unaligned(addr_of_mut!((*dst).colorspace) as *mut i32, cs_raw);
2117 let cr_raw = read_unaligned(addr_of!((*src).color_range) as *const i32);
2118 write_unaligned(addr_of_mut!((*dst).color_range) as *mut i32, cr_raw);
2119 let cl_raw = read_unaligned(addr_of!((*src).chroma_location) as *const i32);
2120 write_unaligned(addr_of_mut!((*dst).chroma_location) as *mut i32, cl_raw);
2121
2122 // Side-data: bounded copy. `av_frame_new_side_data(dst, type,
2123 // size)` allocates the entry and returns a pointer to write
2124 // the payload bytes into; a null return is the OOM signal.
2125 // Callers (`transfer_hw_frame`, `drain_into_pending`) hand us
2126 // freshly-unref'd `dst` frames, so any prior side-data has
2127 // already been freed by `av_frame_unref` — we don't need to
2128 // strip dst's existing side-data here.
2129 // Read `nb_side_data` as the bindgen `c_int` and clamp non-
2130 // positive values BEFORE casting to `usize`. A negative value
2131 // (corrupt / version-skew decoder output) cast directly to
2132 // `usize` becomes a huge positive count and would walk OOB
2133 // memory below; pinning to zero up front collapses that to a
2134 // no-op. Same signed-count guard `sum_side_data_bytes` applies.
2135 let nb_side_data_raw = (*src).nb_side_data;
2136 let src_arr = (*src).side_data;
2137 if nb_side_data_raw > 0 && !src_arr.is_null() {
2138 let count_raw = nb_side_data_raw as usize;
2139 let count = count_raw.min(HW_COPY_SIDE_DATA_MAX_ENTRIES);
2140 if count_raw > HW_COPY_SIDE_DATA_MAX_ENTRIES {
2141 tracing::warn!(
2142 cap = HW_COPY_SIDE_DATA_MAX_ENTRIES,
2143 requested = count_raw,
2144 "mediadecode-ffmpeg: HW->CPU transfer side-data entry cap reached; truncating",
2145 );
2146 }
2147 let mut total_bytes: usize = 0;
2148 for i in 0..count {
2149 let entry = *src_arr.add(i);
2150 if entry.is_null() {
2151 continue;
2152 }
2153 let kind_raw = read_unaligned(addr_of!((*entry).type_) as *const i32);
2154 let size = (*entry).size;
2155 let data_ptr = (*entry).data;
2156 if size == 0 || data_ptr.is_null() {
2157 continue;
2158 }
2159 // Whitelist gate: only proceed when `kind_raw` matches a
2160 // known `AV_FRAME_DATA_*` constant the linked FFmpeg's
2161 // bindgen output knows about. Without this gate, a
2162 // version-skew or hostile decoder could write a side-data
2163 // type integer outside our bindgen's discriminant set, and
2164 // constructing the `AVFrameSideDataType` enum value (so
2165 // we could pass it to `av_frame_new_side_data`) would be
2166 // immediate UB before the call. Unknown types are dropped
2167 // with a debug-level log — the public converter's
2168 // `collect_side_data` walks the destination raw and would
2169 // also surface them as bare integers in `SideDataEntry.kind`.
2170 let Some(kind_enum) = whitelisted_side_data_kind(kind_raw) else {
2171 tracing::debug!(
2172 kind_raw,
2173 "mediadecode-ffmpeg: unknown AV_FRAME_DATA type during HW->CPU transfer; dropping",
2174 );
2175 continue;
2176 };
2177 let projected = total_bytes.saturating_add(size);
2178 if projected > HW_COPY_SIDE_DATA_MAX_TOTAL_BYTES {
2179 tracing::warn!(
2180 cap = HW_COPY_SIDE_DATA_MAX_TOTAL_BYTES,
2181 projected,
2182 "mediadecode-ffmpeg: HW->CPU transfer side-data byte cap reached; dropping rest",
2183 );
2184 break;
2185 }
2186 let new_entry = av_frame_new_side_data(dst, kind_enum, size);
2187 if new_entry.is_null() {
2188 // **OOM is reported, not absorbed.** This used to `break` and
2189 // return `Ok(())`, which published a frame carrying whatever
2190 // side data happened to fit before the allocator gave out —
2191 // silently dropping the entries behind it. Those entries are
2192 // the HDR mastering metadata, the ICC profile and the display
2193 // matrix: a picture that comes back with its colours or its
2194 // orientation quietly missing is worse than one that does not
2195 // come back, because nothing downstream can tell.
2196 //
2197 // The caller already knows what to do with an error here: it
2198 // unrefs the partial destination and either advances to the
2199 // next backend or surfaces the failure for a software retry.
2200 tracing::warn!("mediadecode-ffmpeg: av_frame_new_side_data OOM during HW->CPU transfer",);
2201 return Err(ffmpeg_next::Error::Other {
2202 errno: libc::ENOMEM,
2203 });
2204 }
2205 // SAFETY: `(*new_entry).data` is allocated for `size` bytes
2206 // per av_frame_new_side_data's contract; `data_ptr` is
2207 // valid for `size` reads per AVFrameSideData's contract.
2208 core::ptr::copy_nonoverlapping(data_ptr, (*new_entry).data, size);
2209 total_bytes = projected;
2210 }
2211 }
2212 }
2213 Ok(())
2214}
2215
2216/// `EAGAIN` and `EOF` together: "this decoder has no more output for
2217/// now", either because it wants input or because it is finished.
2218///
2219/// **What is left of a predicate that used to guard both roads.** Both
2220/// public faces classify at their boundary now — [`receive_status`] and
2221/// [`send_status`] — and the send face had to stop treating the two
2222/// alike, since `AVERROR_EOF` there is a caller fault rather than a
2223/// state. The one caller that still wants them together is
2224/// [`drain_into_pending`], the probe-replay drain: it reads a raw
2225/// `ffmpeg_next::decoder::Video` that never crosses a public seam, and
2226/// for it "wants input" and "finished" really are one answer — stop
2227/// draining, the candidate produced everything it is going to.
2228fn is_transient(e: &ffmpeg_next::Error) -> bool {
2229 is_eagain(e) || matches!(e, ffmpeg_next::Error::Eof)
2230}
2231
2232/// **The receive road's single errno gate, and it cannot be spent
2233/// without saying where the session is.**
2234///
2235/// Turns what a funnel (`software_exit` / `hw_exit`) handed back into
2236/// the trait's status vocabulary, keeping the two flow signals inside
2237/// this crate.
2238///
2239/// Takes the funnel's *output*, never libavcodec's raw error, and that
2240/// ordering is the point: the funnels collect a `get_format` or
2241/// allocator-judge refusal that the callback state is holding, and a
2242/// classifier placed in front of them would answer "needs input" for a
2243/// road that had a named refusal waiting. So every receive site funnels
2244/// first and gates second.
2245///
2246/// # Why the phase is a parameter and not a guess
2247///
2248/// The same errno means different things at different points in a
2249/// session's life, and every road that guessed guessed differently:
2250///
2251/// * `EAGAIN` is [`Received::NeedsInput`] only where more input can
2252/// arrive. Past a recorded end it is an instruction the caller cannot
2253/// carry out — the send gates refuse — so it is the end instead. And
2254/// on a candidate that has already been handed the whole history
2255/// including the end, it is neither: that candidate has produced no
2256/// frame and never will, which is a candidate failing, so it goes
2257/// back as an error for the probe machinery to act on.
2258/// * `AVERROR_EOF` is [`Received::Ended`] only from a backend that has
2259/// committed. A candidate's is its own exhaustion, not the stream's.
2260///
2261/// Making the phase an argument is what stops a road from having an
2262/// opinion about this. A classification without it does not compile.
2263fn receive_status(e: Error, phase: SessionPhase) -> Result<Received> {
2264 match &e {
2265 Error::Ffmpeg(f) if is_eagain(f) => {
2266 if phase.accepts_input() {
2267 Ok(Received::NeedsInput)
2268 } else if phase.is_committed() {
2269 // Draining. A committed backend with nothing more to give has
2270 // ended, whichever errno it chose — libavcodec is not supposed
2271 // to answer `EAGAIN` after a flush packet, but this crate has
2272 // met a codec that does (see `ImageDecodeError::NoImage`), and
2273 // the alternative is handing back a state nothing can satisfy.
2274 Ok(Received::Ended)
2275 } else {
2276 // `AuditioningPastEnd`: a candidate that has been given
2277 // everything and produced nothing. The probe road owns it.
2278 Err(e)
2279 }
2280 }
2281 Error::Ffmpeg(ffmpeg_next::Error::Eof) if phase.is_committed() => Ok(Received::Ended),
2282 _ => Err(e),
2283 }
2284}
2285
2286/// **The send road's gate, and it is deliberately narrower than its
2287/// sibling.** Only `EAGAIN` is back pressure here.
2288///
2289/// `avcodec_send_packet` answers `AVERROR_EOF` for a different fact than
2290/// `avcodec_receive_frame` does: not "the stream is over" but *"this
2291/// decoder has already been told the stream is over, and you sent
2292/// something anyway"* — a caller usage fault rather than a session
2293/// state, so it stays in `Err`. Reading it as `Accepted` would silently
2294/// drop the submission; reading it as `MustDrain` would send the caller
2295/// into a drain loop that can never make the next offer succeed.
2296///
2297/// The same line puts [`crate::ResampleError::AfterEof`] and the
2298/// WebCodecs adapter's `AfterEof` on the error side.
2299///
2300/// # The phase, here too
2301///
2302/// [`Sent::MustDrain`] is a promise — *drain, and this same offer
2303/// becomes acceptable* — and past a recorded end it is one no session
2304/// can keep. The send gates refuse there first, so this is the second
2305/// lock rather than the first; what it buys is that the classifier
2306/// itself becomes incapable of making the promise, which is the whole
2307/// point of moving the phase into the signature.
2308fn send_status(e: Error, phase: SessionPhase) -> Result<Sent> {
2309 match &e {
2310 Error::Ffmpeg(f) if is_eagain(f) && phase.accepts_input() => Ok(Sent::MustDrain),
2311 _ => Err(e),
2312 }
2313}
2314
2315/// Post-commit, a HW-only decoder's non-transient, non-EOF error means the
2316/// committed HW backend can't decode this content → fall back to SW. VT's
2317/// "hardware accelerator failed" surfaces as AVERROR_EXTERNAL; some HW
2318/// backends report unsupported geometry as InvalidData; context loss as
2319/// Bug/Bug2/Unknown. Broad-by-design (decode-all-kinds); fixtures will let us
2320/// narrow if a real backend proves a code should NOT trigger fallback.
2321///
2322/// `EAGAIN`/`EOF` are deliberately excluded by the caller, which guards on
2323/// them first — on the send roads through [`is_transient`] into
2324/// [`send_status`], and on `receive_frame` through [`is_eagain`] into
2325/// [`receive_status`], plus the probe/`hw_exit` road for `EOF`. `EAGAIN` is back pressure and `EOF` is a
2326/// genuine end-of-stream that must reach the caller as
2327/// [`Received::Ended`], never be trapped in an infinite fallback-retry
2328/// loop. `Other { errno: EINVAL }` from the HW→CPU transfer path is also
2329/// covered — an unsupported CPU output pix_fmt is a HW-output problem,
2330/// never input corruption.
2331fn is_hw_decode_failure(e: &ffmpeg_next::Error) -> bool {
2332 matches!(
2333 e,
2334 ffmpeg_next::Error::External
2335 | ffmpeg_next::Error::Bug
2336 | ffmpeg_next::Error::Bug2
2337 | ffmpeg_next::Error::Unknown
2338 | ffmpeg_next::Error::InvalidData
2339 | ffmpeg_next::Error::Other {
2340 errno: libc::EINVAL
2341 }
2342 )
2343}
2344
2345/// Reject a `codec::Parameters` whose inner `*mut AVCodecParameters` is
2346/// null. This guards the public trust boundary: ffmpeg-next can produce
2347/// such a `Parameters` under OOM (`Parameters::new()` does not check
2348/// `avcodec_parameters_alloc`), and a safe caller can legally hand one
2349/// in. Without this check, the very next `(*p.as_ptr()).field` read
2350/// would be a null deref.
2351fn ensure_parameters_non_null(parameters: &codec::Parameters) -> Result<()> {
2352 // SAFETY: as_ptr() returns the inner *const AVCodecParameters; we just
2353 // inspect the pointer value (no deref).
2354 if unsafe { parameters.as_ptr() }.is_null() {
2355 return Err(Error::Ffmpeg(ffmpeg_next::Error::Other {
2356 errno: libc::ENOMEM,
2357 }));
2358 }
2359 Ok(())
2360}
2361
2362/// Allocate a fresh `frame::Video`, checking that `av_frame_alloc` did not
2363/// return NULL. ffmpeg-next's `frame::Video::empty()` does not surface that
2364/// failure and the resulting null pointer would be UB on the next field
2365/// access; this wrapper catches it and surfaces it as `ENOMEM`.
2366fn alloc_av_frame() -> std::result::Result<frame::Video, ffmpeg_next::Error> {
2367 let inner = frame::Video::empty();
2368 // SAFETY: as_ptr() just exposes the inner pointer for inspection.
2369 if unsafe { inner.as_ptr() }.is_null() {
2370 return Err(ffmpeg_next::Error::Other {
2371 errno: libc::ENOMEM,
2372 });
2373 }
2374 Ok(inner)
2375}
2376
2377/// Build a fresh `Context` from `parameters`, checking the underlying
2378/// `avcodec_alloc_context3` for NULL before passing it to
2379/// `avcodec_parameters_to_context`. ffmpeg-next's `Context::from_parameters`
2380/// skips that check and would feed a null pointer into FFmpeg under OOM —
2381/// undefined behavior. This helper surfaces the failure as `ENOMEM` and
2382/// frees the context if `parameters_to_context` itself errors.
2383pub(crate) fn build_codec_context(
2384 parameters: &codec::Parameters,
2385 limits: crate::limits::DecoderLimits,
2386) -> Result<(Context, Box<CallbackState>)> {
2387 ensure_parameters_non_null(parameters)?;
2388 // **The choke point.** `avcodec_parameters_to_context` below is a
2389 // wholesale copy *into* FFmpeg — it duplicates `extradata`, every
2390 // `coded_side_data` entry and the channel map into the context, at
2391 // whatever size the caller's parameters declare. Every road that
2392 // opens a decoder in this crate arrives here, so measuring and
2393 // admitting once, right here, is what stops a caller handing
2394 // libavcodec parameters nobody budgeted: the four session `open`s,
2395 // the HW probe's `build_state`, its per-backend advances, and the
2396 // software fallback all pass through this function and none of them
2397 // can reach `avcodec_parameters_to_context` any other way.
2398 //
2399 // The outbound clone (`extras::bounded_clone_parameters`) closed the
2400 // Rust-side copy; this closes the FFmpeg-side one. They are the same
2401 // budget.
2402 //
2403 // SAFETY: `ensure_parameters_non_null` just proved the pointer is
2404 // live; the measurement allocates nothing.
2405 let footprint = unsafe { crate::extras::measure_parameters(parameters.as_ptr()) };
2406 let declared = footprint.and_then(|f| f.total()).unwrap_or(usize::MAX);
2407 if declared > limits.max_codec_parameter_bytes() {
2408 return Err(Error::ParametersTooLarge(
2409 crate::demuxer::ParametersTooLarge::new(0, declared, limits.max_codec_parameter_bytes()),
2410 ));
2411 }
2412 // SAFETY: avcodec_alloc_context3(NULL) returns a fresh AVCodecContext
2413 // or NULL on allocation failure.
2414 let ctx_ptr = unsafe { avcodec_alloc_context3(ptr::null()) };
2415 if ctx_ptr.is_null() {
2416 return Err(Error::Ffmpeg(ffmpeg_next::Error::Other {
2417 errno: libc::ENOMEM,
2418 }));
2419 }
2420 // SAFETY: ctx_ptr is non-null and freshly allocated; parameters.as_ptr()
2421 // returns a valid AVCodecParameters pointer; the function copies bytes
2422 // out of parameters into the context.
2423 let ret = unsafe { avcodec_parameters_to_context(ctx_ptr, parameters.as_ptr()) };
2424 if ret < 0 {
2425 // SAFETY: ctx_ptr was allocated by us and never handed to anyone else.
2426 let mut p = ctx_ptr;
2427 unsafe { avcodec_free_context(&mut p) };
2428 return Err(Error::Ffmpeg(ffmpeg_next::Error::from(ret)));
2429 }
2430 // **The push-down.** The same pixel ceiling this crate checks against
2431 // a decoded frame is written into the decoder itself, so libavcodec
2432 // refuses an oversized picture *before allocating it*. Checking only
2433 // on our side would mean FFmpeg had already paid for the frame by the
2434 // time we declined to copy it — two layers, one number, and this is
2435 // the layer that matters.
2436 //
2437 // FFmpeg's own default here is `INT_MAX`, i.e. no ceiling worth the
2438 // name. `max_pixels` is a plain `int64_t` field on `AVCodecContext`
2439 // (and has been since FFmpeg 4.0), so it is set directly rather than
2440 // through `av_opt_set_int` and a stringly-typed option name.
2441 //
2442 // **And the byte ceiling, pushed down through the same field.**
2443 //
2444 // The pixel ceiling alone does not bound bytes, because a pixel is not
2445 // a fixed price: 10000x10000 is 100 Mpx — comfortably under the 256
2446 // Mpx default — and in `rgba64` it is 800 MB, well over the 512 MiB
2447 // byte ceiling. A highly compressible frame of that shape is a few KB
2448 // on disk, so nothing upstream sees it coming.
2449 //
2450 // **`max_pixels` carries the caller's number, verbatim.** It used to
2451 // carry `min(that, max_frame_bytes / worst-bytes-per-pixel)`, so the
2452 // byte ceiling could be enforced before libavcodec allocated — and
2453 // that translation charged every stream the widest format in
2454 // existence, 16 bytes a pixel. A 1920x1080 `yuv420p` frame costs
2455 // 3.14 MiB and was refused under a 4 MiB budget, at
2456 // `ff_set_dimensions`, before anything accurate had a chance to look
2457 // at it. Over-refusing ordinary video is not a conservative failure;
2458 // it is a broken decoder.
2459 //
2460 // The translation is gone because it is no longer needed: the byte
2461 // ceiling is enforced by [`judge_buffer`], which is *also* a
2462 // pre-allocation seat — `get_buffer2` is the allocator, so it runs
2463 // before the allocation and prices the frame's real format at its
2464 // real aligned dimensions. Nothing is lost on the software road by
2465 // stating the pixel limit as what it is.
2466 //
2467 // SAFETY: `ctx_ptr` is the non-null context just allocated and
2468 // populated above; `max_pixels` is a public field.
2469 unsafe {
2470 (*ctx_ptr).max_pixels = i64::try_from(limits.frame().max_pixels()).unwrap_or(i64::MAX);
2471 }
2472
2473 // **The byte ceiling's own seat, in the allocator itself.**
2474 // `max_pixels` bounds an extent; what an extent costs depends on its
2475 // format and on how the allocator aligns it — a `gray8` frame of
2476 // 65536x1 is 64 KiB by `w * h` and 2 MiB once its single row is
2477 // rounded up. No scalar compared against a pixel product can bound
2478 // that, so the byte question is asked where the answer is knowable:
2479 // in `get_buffer2`, which *is* the allocation, against the caller's
2480 // own `max_frame_bytes`.
2481 //
2482 // See [`judge_buffer`] for why this hook rather than `get_format`
2483 // (measured: `get_format` never fires for a one-shot `png` decode).
2484 //
2485 // SAFETY: `ctx_ptr` is the non-null context; `get_buffer2` is a
2486 // public function-pointer field, and `judge_buffer` delegates every
2487 // frame it accepts to the allocator libavcodec would have used.
2488 unsafe {
2489 (*ctx_ptr).get_buffer2 = Some(judge_buffer);
2490 }
2491
2492 // **`max_samples` is deliberately left alone.**
2493 //
2494 // It bounds `nb_samples * channels`, so bounding *bytes* with it
2495 // means dividing by a per-channel-sample cost — and the only sound
2496 // divisor is the widest sample format the build can emit, 8 bytes.
2497 // That charged every stream `f64` rates: a 6-channel `s16` frame
2498 // fitting a 64 KiB budget was refused, because the translation
2499 // priced it at four times its real cost.
2500 //
2501 // The audio pre-allocation story is now the same as the video one,
2502 // and it is stronger than the translation was: [`judge_buffer`] runs
2503 // in `get_buffer2`, before the planes are allocated, and prices the
2504 // frame's real sample format at its real channel count through
2505 // [`crate::footprint`] — which asks `av_samples_get_buffer_size`, the
2506 // allocator's own ruler. An exact judge at the allocation beats an
2507 // approximate one before it.
2508
2509 // **The judge's budget seat.** `judge_buffer` runs as a C callback
2510 // with nothing but the context to read, and the byte ceiling is not
2511 // recoverable from any field on it — see
2512 // [`CallbackState::max_frame_bytes`]. So the state that already
2513 // carries the `get_format` declination carries the budget too, and
2514 // every road gets one: this is the single point every decoder in the
2515 // crate is built through.
2516 //
2517 // Ownership stays with the caller, which keeps the box alive for as
2518 // long as the context. `Box` contents do not move when the box does,
2519 // so the pointer installed here stays valid across the return.
2520 let mut state = Box::new(CallbackState {
2521 wanted: ffmpeg_next::ffi::AVPixelFormat::AV_PIX_FMT_NONE,
2522 wanted_int: ffmpeg_next::ffi::AVPixelFormat::AV_PIX_FMT_NONE as i32,
2523 ceiling_declined: core::sync::atomic::AtomicBool::new(false),
2524 declined_pixels: core::sync::atomic::AtomicI64::new(0),
2525 declined_limit: core::sync::atomic::AtomicI64::new(0),
2526 max_frame_bytes: limits.frame().max_frame_bytes() as u64,
2527 frame_budget_declined: core::sync::atomic::AtomicBool::new(false),
2528 declined_frame_bytes: core::sync::atomic::AtomicU64::new(0),
2529 declined_frame_audio: core::sync::atomic::AtomicBool::new(false),
2530 });
2531 // SAFETY: `ctx_ptr` is the non-null context; `opaque` is a public
2532 // field FFmpeg never reads or frees.
2533 unsafe {
2534 (*ctx_ptr).opaque = (&raw mut *state).cast();
2535 }
2536
2537 // SAFETY: ctx_ptr is valid; passing `owner: None` means our wrapper owns
2538 // the allocation and `Context::drop` will run `avcodec_free_context`.
2539 Ok((unsafe { Context::wrap(ctx_ptr, None) }, state))
2540}
2541
2542/// Checked deep-clone of `codec::Parameters`. ffmpeg-next's
2543/// `Parameters::clone` allocates via `avcodec_parameters_alloc` without
2544/// checking for NULL and runs `avcodec_parameters_copy` without checking
2545/// the return code. On `ENOMEM` the result is a `Parameters` with a null
2546/// inner pointer, which becomes UB when later passed to FFmpeg.
2547///
2548/// This helper performs both calls explicitly, frees a partial allocation
2549/// on failure, and surfaces the AVERROR. The returned `Parameters` has
2550/// `owner: None`, severing any Rc link to the caller's demuxer (the
2551/// reason we deep-clone in the first place — see Send safety in
2552/// `VideoDecoder::open`).
2553pub(crate) fn try_clone_parameters(
2554 src: &codec::Parameters,
2555 budget: usize,
2556) -> std::result::Result<codec::Parameters, Error> {
2557 // Through the bounded clone, like every other parameter copy in this
2558 // crate — see [`crate::extras::bounded_clone_parameters`] for the
2559 // rule and why the wholesale `avcodec_parameters_copy` this used to
2560 // call is gone. This path is attacker-facing: `VideoDecoder::open`
2561 // takes whatever `stream.parameters()` hands it, straight off a
2562 // container.
2563 //
2564 // `budget` is the **active** ceiling, threaded from the session's own
2565 // `DecoderLimits` — through the initial ownership clone, the probe
2566 // state's copy, every probe advance and the software fallback. It
2567 // used to be the crate default, so a lowered ceiling did not bind
2568 // here (the clone admitted 16 MiB whatever the caller configured,
2569 // and only `build_codec_context` downstream refused) and a raised one
2570 // could not be used at all.
2571 //
2572 // The stream index is reported as 0: this helper is handed
2573 // parameters, not a stream, and inventing a coordinate it cannot
2574 // know would be worse than admitting it has none.
2575 crate::extras::bounded_clone_parameters(src, 0, budget).map_err(|e| match e {
2576 crate::demuxer::DemuxError::ParametersTooLarge(p) => Error::ParametersTooLarge(p),
2577 crate::demuxer::DemuxError::ParametersCopy(p) => Error::Ffmpeg(*p.source()),
2578 // A missing or unallocatable destination is the out-of-memory this
2579 // helper has always reported.
2580 _ => Error::Ffmpeg(ffmpeg_next::Error::Other {
2581 errno: libc::ENOMEM,
2582 }),
2583 })
2584}
2585
2586/// Checked counterpart to `Packet::clone()`. ffmpeg-next's `clone_from`
2587/// calls `av_packet_ref` and ignores the int return value; on `ENOMEM`
2588/// the destination is left empty while the caller assumes the clone
2589/// succeeded — corrupting any later replay history. This helper surfaces
2590/// the AVERROR. The result is a refcounted shallow clone — the payload
2591/// buffer is shared with `src` rather than deep-copied; the probe replay
2592/// only sends packets through `avcodec_send_packet`, which does not
2593/// require a writable buffer.
2594pub(crate) fn try_clone_packet(src: &Packet) -> std::result::Result<Packet, ffmpeg_next::Error> {
2595 let mut dst = Packet::empty();
2596 // SAFETY: dst is a freshly zero-initialized Packet (av_init_packet inside
2597 // Packet::empty); av_packet_ref initializes its data fields from src's
2598 // refcounted buffer or returns AVERROR(ENOMEM) on failure.
2599 let ret = unsafe { av_packet_ref(dst.as_mut_ptr(), src.as_ptr()) };
2600 if ret < 0 {
2601 return Err(ffmpeg_next::Error::from(ret));
2602 }
2603 Ok(dst)
2604}
2605
2606/// Sum of `AVPacket.side_data[i].size` across every entry, plus
2607/// `nb_entries * SIDE_DATA_ENTRY_OVERHEAD` (descriptor + AVBufferRef +
2608/// allocator bookkeeping per entry). `av_packet_ref` performs a deep
2609/// copy of side data via `av_packet_copy_props`, so each probe-buffered
2610/// clone retains every one of these bytes. Charging both keeps
2611/// `MAX_PROBE_PACKET_BYTES` a true upper bound — without the overhead,
2612/// many zero-size entries slip past the cap on pure descriptor cost.
2613///
2614/// Walks at most `max_entries` entries even when `side_data_elems`
2615/// reports a larger count. Defense-in-depth against a corrupt or hostile
2616/// packet whose `side_data_elems` lies about the actual array length:
2617/// the caller is expected to also reject any packet whose count exceeds
2618/// the cap (so the inflated clone is never created), but bounding the
2619/// walk here means a stale or weaponised value can never trigger an
2620/// unbounded raw-pointer scan from the safe API.
2621///
2622/// Reads only the `size` field of each `AVPacketSideData` entry — never
2623/// touches the bindgen `AVPacketSideDataType` enum, so no UB even if a
2624/// future FFmpeg adds a side-data type discriminant our build doesn't
2625/// know.
2626pub(crate) fn packet_side_data_bytes(packet: &Packet, max_entries: usize) -> usize {
2627 // SAFETY: AVPacket.side_data is `*mut AVPacketSideData` and
2628 // side_data_elems is `c_int`; both are raw struct fields safe to read.
2629 // Field projection (`.size`) does not reconstruct the enum-typed `type_`
2630 // field, so the bindgen-enum UB hazard does not apply here.
2631 unsafe {
2632 let raw = packet.as_ptr();
2633 let nel = (*raw).side_data_elems;
2634 let arr = (*raw).side_data;
2635 if arr.is_null() || nel <= 0 || max_entries == 0 {
2636 return 0;
2637 }
2638 let count = (nel as usize).min(max_entries);
2639 let mut total = count.saturating_mul(SIDE_DATA_ENTRY_OVERHEAD);
2640 for i in 0..count {
2641 let entry = arr.add(i);
2642 total = total.saturating_add((*entry).size);
2643 }
2644 total
2645 }
2646}
2647
2648/// Number of `AVPacketSideData` entries on `packet`. The probe buffer
2649/// uses this to enforce [`MAX_PROBE_PACKET_SIDE_DATA_ENTRIES`] before
2650/// cloning, so a packet whose entry count alone would dominate retained
2651/// memory is rejected up front.
2652pub(crate) fn packet_side_data_count(packet: &Packet) -> usize {
2653 // SAFETY: side_data_elems is `c_int`, safe to read; clamp negatives to 0.
2654 let nel = unsafe { (*packet.as_ptr()).side_data_elems };
2655 if nel <= 0 { 0 } else { nel as usize }
2656}
2657
2658/// Just `EAGAIN` (separate from EOF — the FFmpeg send/receive state machine
2659/// distinguishes "drain output and retry" from "stream over").
2660fn is_eagain(e: &ffmpeg_next::Error) -> bool {
2661 matches!(e, ffmpeg_next::Error::Other { errno } if *errno == ffmpeg_next::error::EAGAIN)
2662}
2663
2664/// The probe square the per-pixel cost is measured on.
2665///
2666/// 256 divides every chroma subsampling FFmpeg has **and** every
2667/// alignment libavcodec uses, so the measurement is exact: no plane is
2668/// rounded up to cover a half-sized dimension, and no row is padded to
2669/// an alignment boundary. Measured at 257 the same census reads 16.934
2670/// bytes per pixel instead of 16.000 — that 5.8% is per-*row* padding,
2671/// a term linear in height rather than in pixels, and it is not part of
2672/// the per-pixel rate.
2673pub(crate) const PROBE_PIXELS: usize = 256 * 256;
2674
2675/// Bytes a [`PROBE_PIXELS`]-pixel picture costs in the **most expensive
2676/// pixel format this build of libavcodec can describe**.
2677///
2678/// # Why the worst case and not the declared one
2679///
2680/// The first cut of this ceiling charged the format the *container*
2681/// declared, and a container's declaration is not an upper bound on
2682/// anything. It may be unset, it may be wrong, and it may be narrower
2683/// than what the decoder actually emits — a stream declaring `yuv420p`
2684/// at 1.5 bytes per pixel whose decoder outputs `rgbaf32` at 16 got a
2685/// ceiling more than ten times too generous, which is the same hole one
2686/// layer down from the one it was added to close.
2687///
2688/// So the rate is not negotiated with the file at all. Every stream is
2689/// charged the worst case, and the worst case is **measured**, not
2690/// tabulated: this build's descriptor list is walked once and each
2691/// format priced through `av_image_get_buffer_size`, the same function
2692/// `avcodec_default_get_buffer2` sizes from. A future FFmpeg that adds
2693/// a wider format is priced correctly without this crate learning its
2694/// name.
2695///
2696/// # The census, at the time of writing
2697///
2698/// 267 descriptors, 251 of them CPU formats that price (the rest are
2699/// hardware surfaces, which carry no CPU bytes and return no size). The
2700/// maximum is **16.000 bytes per pixel**, reached by eight formats —
2701/// `gbrapf32be/le`, `rgbaf32be/le`, `rgba128be/le`, `gbrap32be/le`.
2702/// Next below are the 12-byte `gbrpf32`/`rgbf32` family.
2703///
2704/// # What this trades
2705///
2706/// Over-refusal for cheap formats, and it is deliberate. At the 512 MiB
2707/// default the effective ceiling becomes ~33.55 Mpx, so 8K (33.18 Mpx)
2708/// still decodes in *any* format — including the 16-byte ones, where it
2709/// really does cost 506 MiB — but a 16K `yuv420p` frame, which would
2710/// only have cost 199 MB, is refused too. That is the honest shape of a
2711/// bound that has to hold before the format is known: the deployment
2712/// answer is to raise `max_frame_bytes`, which is exactly the knob that
2713/// says how much memory one frame may cost.
2714///
2715/// # The residual, stated
2716///
2717/// Row alignment adds at most `align x planes x height` bytes on top of
2718/// this rate — about 1 MB on an 8K frame, 0.2%, and covered by the fact
2719/// that `max_frame_bytes` is a policy number rather than a hardware
2720/// limit. It is only significant for degenerate aspect ratios (a
2721/// one-pixel-wide frame is all padding), which the *pixel* ceiling has
2722/// always been the wrong shape to bound and which this change neither
2723/// introduces nor worsens.
2724pub(crate) fn worst_bytes_per_probe() -> usize {
2725 /// The census result, taken once. `av_pix_fmt_desc_next` walks a
2726 /// static table that cannot change during the process.
2727 static WORST: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2728 *WORST.get_or_init(|| {
2729 /// The measured maximum at the time of writing, and the floor this
2730 /// census may not fall below. A build whose census comes back
2731 /// *smaller* than the eight 16-byte formats has failed to walk the
2732 /// table, not discovered a cheaper world — take the known number
2733 /// rather than a ceiling built on a failed measurement.
2734 const KNOWN_WORST_BYTES_PER_PIXEL: usize = 16;
2735
2736 let mut worst = 0usize;
2737 let mut desc: *const ffmpeg_next::ffi::AVPixFmtDescriptor = ptr::null();
2738 loop {
2739 // SAFETY: `av_pix_fmt_desc_next` walks libavutil's own static
2740 // descriptor table, taking the previous entry (or null to start)
2741 // and returning null at the end. It traffics in descriptor
2742 // pointers, not enums, so it needs no shim.
2743 desc = unsafe { ffmpeg_next::ffi::av_pix_fmt_desc_next(desc) };
2744 if desc.is_null() {
2745 break;
2746 }
2747 // **Both of these go through the `c_int` shims**, and this is the
2748 // place it matters most: the whole point of walking the table is
2749 // to price formats this build's bindings may not name, and the
2750 // generated `av_pix_fmt_desc_get_id` hands those ids back as a
2751 // closed `AVPixelFormat`. Every future format would have become
2752 // an invalid enum value on the way into the pricing meant to
2753 // handle it — the census would have been UB on exactly its reason
2754 // for existing.
2755 //
2756 // SAFETY: `desc` is a live entry from libavutil's static table;
2757 // the id is passed straight back to libavutil as the integer it
2758 // is, and `av_image_get_buffer_size` returns a negative AVERROR
2759 // for ids it cannot size rather than misbehaving.
2760 let id = unsafe { c_shims::av_pix_fmt_desc_get_id(desc) };
2761 let size = unsafe { c_shims::av_image_get_buffer_size(id, 256, 256, 1) };
2762 if size > 0 {
2763 worst = worst.max(size as usize);
2764 }
2765 }
2766 worst.max(KNOWN_WORST_BYTES_PER_PIXEL * PROBE_PIXELS)
2767 })
2768}
2769/// `AVCodecContext.get_buffer2`: the same pixel ceiling, applied where
2770/// the **aligned** dimensions are knowable.
2771///
2772/// # The hole this closes
2773///
2774/// `max_pixels` is checked by libavcodec against the frame's *raw*
2775/// `width * height`. What it then allocates is the **aligned** shape —
2776/// `avcodec_align_dimensions2` rounds both dimensions up to whatever
2777/// the codec and the CPU want — and for degenerate aspect ratios those
2778/// are not the same number at all. Measured on this build:
2779///
2780/// | shape | raw | aligned | inflation |
2781/// |---|---|---|---|
2782/// | `gray8` 65536x1 | 65,536 px / 64 KiB | 65536x32 = 2,097,152 px / 2 MiB | **32x** |
2783/// | `gray8` 1x65536 | 65,536 px / 64 KiB | 16x65536 = 1,048,576 px / 2 MiB | 16x |
2784/// | `yuv420p` 7680x4320 | 33,177,600 px | 7680x4320 | 1.00x |
2785/// | `gray8` 1024x1024 | 1,048,576 px | 1024x1024 | 1.00x |
2786///
2787/// So a one-pixel-tall frame slips 32 times its declared cost past a
2788/// scalar compared against `w * h`, and no value of that scalar can fix
2789/// it: bounding the product cannot bound a product whose factors are
2790/// then rounded up independently. Real pictures inflate by nothing at
2791/// all, which is why the ceiling looked sound.
2792///
2793/// # Why this hook and not `get_format`
2794///
2795/// `get_format` was measured first, because it needs no allocation
2796/// decision and receives the context. It **does not fire on every
2797/// road**: on this build a one-shot `mjpeg` decode calls it once and a
2798/// `png` decode calls it *zero* times. Cover art is overwhelmingly
2799/// mjpeg or png, so half the road this ceiling exists to guard would
2800/// have been unguarded.
2801///
2802/// `get_buffer2` fired on both — it is the allocator, so every frame
2803/// libavcodec hands back comes through it, and it sees the frame's
2804/// *real* format rather than a negotiated candidate.
2805///
2806/// # No state, so no lifetime to prove
2807///
2808/// The composed-`opaque` design was not needed. This callback reads the
2809/// ceiling from `AVCodecContext.max_pixels` — the field this crate set
2810/// itself, one number, already carrying the byte ceiling converted at
2811/// the worst per-pixel rate — and applies it to the aligned dimensions.
2812/// Same scalar, same meaning, applied where alignment is knowable.
2813/// `opaque` is untouched, so the hardware path keeps it and there is no
2814/// allocation whose lifetime has to outlive a C callback.
2815///
2816/// Panic discipline is likewise structural rather than asserted: the
2817/// body allocates nothing, indexes nothing, unwraps nothing, and calls
2818/// exactly three FFmpeg functions. There is no Rust operation in it
2819/// that can panic, and an `extern "C"` function aborts rather than
2820/// unwinding into C in any case.
2821///
2822/// # Safety
2823///
2824/// Called by libavcodec with a live context and a frame whose `format`,
2825/// `width` and `height` are set. Delegates every accepted frame to
2826/// `avcodec_default_get_buffer2`, which is what libavcodec would have
2827/// called had this hook not been installed.
2828unsafe extern "C" fn judge_buffer(
2829 ctx: *mut ffmpeg_next::ffi::AVCodecContext,
2830 frame: *mut ffmpeg_next::ffi::AVFrame,
2831 flags: libc::c_int,
2832) -> libc::c_int {
2833 // SAFETY: libavcodec passes a live context and frame; both fields are
2834 // plain integers.
2835 let (width, height) = unsafe { ((*frame).width, (*frame).height) };
2836
2837 // **This seat judges cost, and only cost.**
2838 //
2839 // `max_pixels` is a *logical* limit on a picture's extent, and
2840 // libavcodec already enforces it — against the **raw** dimensions, in
2841 // `ff_set_dimensions` via `av_image_check_size2`, before any frame
2842 // exists. That is the semantics the caller asked for and the
2843 // semantics FFmpeg documents, and this callback does not restate it.
2844 //
2845 // It used to. R11 added an *aligned*-dimension comparison here
2846 // against `max_pixels`, because at the time the callback had no
2847 // accurate byte check and a degenerate shape could slip its real cost
2848 // past a raw-pixel gate — 65536x1 aligns to 65536x32, thirty-two
2849 // times the pixels. That instrument is now both **redundant** and
2850 // **wrong**:
2851 //
2852 // * redundant, because since the byte ceiling was threaded in the
2853 // footprint below prices the aligned dimensions itself, so the
2854 // degenerate shape is refused on its actual cost; and
2855 // * wrong, because `max_pixels` is `min(the caller's pixel limit,
2856 // byte ceiling / worst-bytes-per-pixel)` — so when the caller's
2857 // pixel limit was the tighter seat, alignment inflation alone
2858 // refused frames satisfying *both* requested limits. A 65536x1
2859 // `gray8` frame under `max_pixels = 65536` and a generous byte
2860 // budget fits the pixel limit exactly and costs 2 MiB, and was
2861 // refused anyway — for arithmetic the caller never asked about.
2862 //
2863 // Logical extent is libavcodec's gate on raw dimensions; allocation
2864 // cost is this one, against the caller's own `max_frame_bytes`. One
2865 // question each.
2866 //
2867 // Audio reaches here too, and used to pass unpriced entirely:
2868 // `max_samples` bounds the sample *count*, so one sample across eight
2869 // packed `f64` channels is 64 valid bytes under a 64-byte ceiling and
2870 // a 2,080-byte allocation — delivered, because the copy-out only ever
2871 // rechecks the valid bytes.
2872 //
2873 // SAFETY: `ctx` and `frame` are live; every field read is a plain
2874 // integer, and `format` stays an integer throughout.
2875 // SAFETY: `frame` is live; the field is a plain pointer.
2876 let hw_frames = unsafe { (*frame).hw_frames_ctx };
2877
2878 // A hardware frame carries no CPU bytes for this seat to price — its
2879 // pool is judged where it is declared, in the `get_format` callback —
2880 // so it is delegated rather than failed closed on an unpriceable
2881 // format.
2882 if hw_frames.is_null() {
2883 // **The caller's own number, read from the seat that carries it.**
2884 // This used to recover a byte ceiling from `AVCodecContext.max_pixels`,
2885 // and the recovery was wrong in both directions:
2886 //
2887 // * `max_pixels` is `min(pixel ceiling, byte ceiling / worst)`, so
2888 // when the *pixel* seat was the tighter of the two it stopped
2889 // encoding the byte ceiling at all — and the recovery invented a
2890 // smaller one. A 256x256 frame at 16 bytes a pixel under
2891 // `max_pixels = 65536` with a 2 MiB byte budget satisfies both of
2892 // the caller's limits, costs 1,050,624 bytes, and was judged
2893 // against 1,048,576 and refused. The claim that the conflation
2894 // was harmless in one direction was simply wrong: it omitted the
2895 // footprint's own alignment and slack, which is exactly where
2896 // those extra 2,048 bytes live.
2897 // * and for audio a pixel ceiling has no business being consulted
2898 // at all.
2899 //
2900 // The audio road briefly recovered from `max_samples` instead,
2901 // which *is* exact — but two sources of truth for one number is how
2902 // the first one went wrong. Both media read the seat now.
2903 //
2904 // SAFETY: `opaque` holds the `CallbackState` that
2905 // `build_codec_context` installed and whose owner outlives the
2906 // context. A null one means a context this crate did not build, and
2907 // is refused rather than assumed generous.
2908 let state = unsafe { (*ctx).opaque } as *const CallbackState;
2909 if state.is_null() {
2910 return -(libc::EINVAL);
2911 }
2912 // SAFETY: non-null per the check above; the field is a plain `u64`.
2913 let byte_ceiling = u128::from(unsafe { (*state).max_frame_bytes });
2914
2915 // SAFETY: `frame` is live; both are plain integer fields.
2916 let (format_raw, nb_samples) = unsafe { ((*frame).format, (*frame).nb_samples) };
2917 let priced = if width > 0 && height > 0 {
2918 crate::footprint::video_frame_bytes(format_raw, width, height)
2919 } else if nb_samples > 0 {
2920 // **The frame's layout, not the context's.** FFmpeg's
2921 // `get_buffer2` contract says the callback reads the values on
2922 // the *frame*, and `avcodec_default_get_buffer2` sizes from them
2923 // — the context's layout is whatever was last negotiated and can
2924 // differ outright. A context claiming mono against a frame
2925 // carrying 255 `dblp` channels at 130,000 samples prices about a
2926 // megabyte and allocates about 265 MB.
2927 //
2928 // Read raw and signed, per the house discipline, and refused
2929 // rather than floored: a negative count is malformed, and
2930 // flooring it to zero would price an allocation that is about to
2931 // happen at nothing.
2932 // SAFETY: `frame` is live; `ch_layout.nb_channels` is a plain
2933 // `c_int`.
2934 let channels = unsafe { (*frame).ch_layout.nb_channels };
2935 if channels <= 0 {
2936 return -(libc::EINVAL);
2937 }
2938 crate::footprint::audio_frame_bytes(format_raw, nb_samples as usize, channels as usize)
2939 } else {
2940 // Neither geometry nor samples: nothing is being allocated that
2941 // this seat can price, and nothing is claimed.
2942 Some(0)
2943 };
2944
2945 // **The refusal leaves its reason behind.** A `get_buffer2`
2946 // callback can only answer libavcodec with an errno, and
2947 // `AVERROR(EINVAL)` is also what libavcodec reports for corrupt
2948 // input — so a bare refusal here was indistinguishable from a
2949 // broken file, and only one of those is worth retrying with a
2950 // larger ceiling. The decoder funnels collect this the same way
2951 // they collect the `get_format` declination.
2952 let record = |bytes: u64| {
2953 use core::sync::atomic::Ordering;
2954 // SAFETY: `state` was proved non-null above.
2955 unsafe {
2956 (*state)
2957 .declined_frame_bytes
2958 .store(bytes, Ordering::Relaxed);
2959 (*state)
2960 .declined_frame_audio
2961 .store(width <= 0 && height <= 0, Ordering::Relaxed);
2962 (*state)
2963 .frame_budget_declined
2964 .store(true, Ordering::Release);
2965 }
2966 -(libc::EINVAL)
2967 };
2968 match priced {
2969 // Fail closed. An allocation whose size cannot be established is
2970 // not a small one — the same stance every other judge here takes.
2971 // Reported as an unbounded cost, which is what an unprovable one
2972 // is.
2973 None => return record(u64::MAX),
2974 // Nothing to buy, so nothing to refuse.
2975 Some(0) => {}
2976 // A budget of zero admits nothing, and this is the arm that used
2977 // to be a skipped guard.
2978 Some(bytes) if byte_ceiling == 0 => return record(bytes as u64),
2979 Some(bytes) if bytes as u128 > byte_ceiling => return record(bytes as u64),
2980 Some(_) => {}
2981 }
2982 }
2983
2984 // SAFETY: delegating to the allocator libavcodec would have used.
2985 unsafe { ffmpeg_next::ffi::avcodec_default_get_buffer2(ctx, frame, flags) }
2986}
2987
2988/// Prices the CPU frame `av_hwframe_transfer_data` would allocate, and
2989/// refuses it if it is over the ceiling — **before** the transfer runs.
2990///
2991/// # Why the hardware road needs its own seat
2992///
2993/// [`judge_buffer`] is not a universal choke point, and the census says
2994/// so on this machine. `ff_get_buffer` calls `hwaccel->alloc_frame`
2995/// directly and never reaches `get_buffer2` at all: a VideoToolbox
2996/// h264 decode of a 160x120 clip records **zero** `get_buffer2` calls
2997/// while producing a hardware frame. And the CPU destination of a
2998/// download is allocated by `av_hwframe_transfer_data` itself, outside
2999/// both hooks.
3000///
3001/// # What the census settled about the surface itself
3002///
3003/// `max_pixels` **does** bite before `alloc_frame`, and this was
3004/// measured rather than assumed: with `max_pixels = 100`, a 160x120
3005/// VideoToolbox h264 decode fails at `avcodec_open2` with
3006/// `Picture size 160x120 exceeds specified max pixel count 100` from
3007/// `av_image_check_size2`, zero `get_buffer2` calls and no frame. The
3008/// check lives in `ff_set_dimensions`, which every decoder runs when it
3009/// learns its dimensions and before any surface pool exists — so the
3010/// seat `max_pixels` already occupies covers the hardware surface too.
3011///
3012/// The residual on that road is the aligned-dimensions gap
3013/// [`judge_buffer`] closes for software frames, and it applies to
3014/// **driver-owned GPU memory** rather than to anything this crate
3015/// carries. What this crate does carry off the hardware road is the CPU
3016/// frame downloaded here, and that is bounded exactly, by this
3017/// function.
3018///
3019/// # How the price is taken
3020///
3021/// The destination format is not chosen by this crate: `dst.format` is
3022/// `AV_PIX_FMT_NONE` on entry and FFmpeg picks from
3023/// `av_hwframe_transfer_get_formats`. So the whole candidate list is
3024/// priced and the **worst** taken — walked as `*const c_int` through
3025/// the shim, because a driver may offer a format this build's bindings
3026/// do not name, which is the same discipline the pixel census keeps.
3027///
3028/// When the list cannot be obtained the global worst rate stands in;
3029/// over-refusing is the safe direction for a ceiling.
3030///
3031/// # Safety
3032///
3033/// `hw_frame` must be a live `*const AVFrame`.
3034unsafe fn judge_hw_transfer(
3035 hw_frame: *const ffmpeg_next::ffi::AVFrame,
3036 limits: crate::FrameLimits,
3037) -> std::result::Result<(), crate::error::HwTransferTooLarge> {
3038 // SAFETY: `hw_frame` is live per the contract; the field is a plain
3039 // pointer.
3040 let frames_ctx = unsafe { (*hw_frame).hw_frames_ctx };
3041
3042 // **The allocated extent, not the displayed one.** `AVFrame.width` /
3043 // `.height` are the *display* dims; what
3044 // `av_hwframe_transfer_data` allocates is sized from the frames
3045 // context, and on a cropped stream the two diverge by orders of
3046 // magnitude — measured on this build, an h264 stream with SPS
3047 // cropping shows 32x32 display over a 1920x1088 coded surface, a
3048 // 2040x gap. This crate already had a helper that reads the pool
3049 // dims, with a doc comment naming this exact trap; the first version
3050 // of this judge reached past it for `AVFrame.width` anyway.
3051 //
3052 // **Fail closed.** No context, no dims, or no priceable candidate
3053 // means the allocation extent cannot be proved — and an unprovable
3054 // extent is not a small one. The same stance
3055 // `estimate_transfer_bytes` takes next door, and for the same reason:
3056 // falling back to display dims here would restore precisely the hole
3057 // this judge exists to close.
3058 if frames_ctx.is_null() {
3059 // Not a hardware frame at all. `av_hwframe_transfer_data` refuses
3060 // such a source with `EINVAL` and allocates nothing, so there is no
3061 // extent to bound here — and answering "too large" would put a
3062 // ceiling's name on a completely different fault. The existing path
3063 // reports it accurately.
3064 return Ok(());
3065 }
3066 let Some((width, height)) = (unsafe { hw_frames_ctx_dimensions_raw(hw_frame) }) else {
3067 // A hardware frame whose pool extent cannot be read. The transfer
3068 // may well allocate; nothing here can say how much. Charged as
3069 // unbounded, which is what an unprovable extent is.
3070 return Err(crate::error::HwTransferTooLarge::new(
3071 usize::MAX,
3072 limits.max_frame_bytes(),
3073 ));
3074 };
3075
3076 // **Every candidate folded in, priceable or not.**
3077 //
3078 // FFmpeg picks the destination format from this list; this crate does
3079 // not get to choose. So the bound has to be the maximum over the
3080 // *whole* list — and the fold used to skip the members libavutil
3081 // would not size, updating `worst` only on priceable ones and
3082 // reaching for a fallback only when *nothing* priced. A list holding
3083 // one cheap priceable format beside one unpriceable format was
3084 // therefore judged at the cheap price, while FFmpeg remained free to
3085 // select the one that was ignored.
3086 //
3087 // An unpriceable candidate is charged
3088 // [`crate::footprint::video_frame_bytes_upper_bound`] instead: the
3089 // same dimension alignment and per-plane overhead at the widest rate,
3090 // so it dominates whatever that layout would have cost had it been
3091 // priceable.
3092 let mut worst: usize = 0;
3093 let mut judged_any = false;
3094 if !frames_ctx.is_null() {
3095 let mut list: *mut libc::c_int = ptr::null_mut();
3096 // `AV_HWFRAME_TRANSFER_DIRECTION_FROM` is 0 — passed as the integer
3097 // it is, like every other open C enum on this road.
3098 // SAFETY: `frames_ctx` is the frame's live `AVHWFramesContext`
3099 // reference; on success FFmpeg allocates a NONE-terminated list
3100 // that the caller frees.
3101 let rc = unsafe { c_shims::av_hwframe_transfer_get_formats(frames_ctx, 0, &mut list, 0) };
3102 if rc >= 0 && !list.is_null() {
3103 let none = ffmpeg_next::ffi::AVPixelFormat::AV_PIX_FMT_NONE as libc::c_int;
3104 let mut p = list;
3105 loop {
3106 // SAFETY: FFmpeg guarantees the list is NONE-terminated; reads
3107 // up to and including the sentinel are in bounds.
3108 let candidate = unsafe { ptr::read(p) };
3109 if candidate == none {
3110 break;
3111 }
3112 // **The allocator's arithmetic, not the payload's.** Pricing
3113 // `av_image_get_buffer_size` at a fixed alignment is what the
3114 // pixels weigh laid out tightly — for a 16x16 NV12 destination
3115 // that is 768 bytes against the 1,792 `av_frame_get_buffer`
3116 // really takes. See [`crate::footprint`].
3117 let cost = crate::footprint::video_frame_bytes(candidate, width, height)
3118 .or_else(|| crate::footprint::video_frame_bytes_upper_bound(width, height));
3119 match cost {
3120 Some(size) => {
3121 worst = worst.max(size);
3122 judged_any = true;
3123 }
3124 // Not even the dimension-only bound could be formed, so the
3125 // extent itself is not a picture. Nothing here will guess.
3126 None => {
3127 // SAFETY: `list` is freed exactly once, on every road out.
3128 unsafe { ffmpeg_next::ffi::av_freep(ptr::addr_of_mut!(list).cast()) };
3129 return Err(crate::error::HwTransferTooLarge::new(
3130 usize::MAX,
3131 limits.max_frame_bytes(),
3132 ));
3133 }
3134 }
3135 p = unsafe { p.add(1) };
3136 }
3137 // SAFETY: `list` was allocated by `av_hwframe_transfer_get_formats`
3138 // and is freed exactly once here.
3139 unsafe { ffmpeg_next::ffi::av_freep(ptr::addr_of_mut!(list).cast()) };
3140 }
3141 }
3142
3143 if !judged_any {
3144 // An empty list, or a query that failed: no candidate was seen at
3145 // all. Charge the dimension-only bound over the pool extent, which
3146 // is the most any format this build can emit could cost there.
3147 let Some(bound) = crate::footprint::video_frame_bytes_upper_bound(width, height) else {
3148 return Err(crate::error::HwTransferTooLarge::new(
3149 usize::MAX,
3150 limits.max_frame_bytes(),
3151 ));
3152 };
3153 worst = bound;
3154 }
3155
3156 if worst > limits.max_frame_bytes() {
3157 return Err(crate::error::HwTransferTooLarge::new(
3158 worst,
3159 limits.max_frame_bytes(),
3160 ));
3161 }
3162 Ok(())
3163}
3164/// Reads and clears the coded-surface refusal a `get_format` callback
3165/// left in its state, if it left one.
3166///
3167/// Free-standing rather than a method because the reason has to survive
3168/// on **every** hardware exit, and one of them — the open-time failure
3169/// path — runs before a decoder exists to ask.
3170fn ceiling_declination_of(state: *const CallbackState) -> Option<Error> {
3171 use core::sync::atomic::Ordering;
3172 if state.is_null() {
3173 return None;
3174 }
3175 // SAFETY: `state` is the live `CallbackState` the caller owns; it is
3176 // freed only after the codec context it belongs to.
3177 let (declined, pixels, limit) = unsafe {
3178 (
3179 (*state).ceiling_declined.swap(false, Ordering::Acquire),
3180 (*state).declined_pixels.load(Ordering::Relaxed),
3181 (*state).declined_limit.load(Ordering::Relaxed),
3182 )
3183 };
3184 declined.then(|| Error::HwSurfaceTooLarge(crate::error::HwSurfaceTooLarge::new(pixels, limit)))
3185}
3186/// The software decoders' error funnel.
3187///
3188/// Every road that turns a libavcodec decode failure into an `Error`
3189/// goes through here, so a frame the allocator judge refused comes back
3190/// named instead of as the `EINVAL` libavcodec also uses for corrupt
3191/// input. The hardware roads have their own funnel (`hw_exit`); this is
3192/// its software twin, and the discipline is the same one: **a consumer
3193/// added helper-by-helper is lost the next time the surrounding code is
3194/// restructured, so every exit calls one function.**
3195///
3196/// # Safety
3197///
3198/// `state` must be null or a live `CallbackState` the caller owns.
3199pub(crate) fn software_exit(state: *const CallbackState, e: ffmpeg_next::Error) -> Error {
3200 frame_budget_declination_of(state).unwrap_or(Error::Ffmpeg(e))
3201}
3202
3203/// **The software road's only way to read an errno — funnel and
3204/// classify in one call, because the order between them is a law and
3205/// laws that depend on remembering get broken.**
3206///
3207/// Every receive site used to write the two steps out: funnel, then
3208/// classify. The R1 report called that ordering load-bearing and
3209/// explained why — a `get_format` declination or an allocator-judge
3210/// refusal sits in the callback state waiting to be collected, and a
3211/// classifier that runs first reads the errno libavcodec reported
3212/// instead of the refusal this crate made, answering `Ended` or
3213/// `NeedsInput` for a frame that was declined. Then a restructure
3214/// reordered one road and the law was simply gone, silently, because
3215/// nothing enforced it.
3216///
3217/// So the classifiers are private to this module now and this is the
3218/// door. A caller cannot classify a raw error because it cannot reach a
3219/// classifier; the funnel is not something to remember to call first,
3220/// it is the only thing there is to call.
3221///
3222/// # The verdict is minted once and threaded
3223///
3224/// **A funnel consumes what it collects.** `take_ceiling_declination`
3225/// and `take_frame_budget_declination` both *clear* the latch they
3226/// read, because a refusal reported twice would be a refusal invented
3227/// once. That makes the verdict a one-shot value, and the rule that
3228/// follows is the whole of this invariant:
3229///
3230/// > The first funnel on a road mints the verdict. Every later step on
3231/// > that road **threads it**. A site that re-funnels, or that rebuilds
3232/// > `Error::Ffmpeg(raw)` after a funnel has run, is the bug class —
3233/// > the second call finds the latch empty and reports the errno the
3234/// > substrate happened to give over the refusal this crate made.
3235///
3236/// A raw errno may still be *read* after minting — `is_hw_decode_failure`
3237/// does, to decide whether a fallback is required — but reading it to
3238/// decide a route is not the same as reporting it. What the caller is
3239/// told is always the verdict.
3240///
3241/// # Safety
3242///
3243/// `state` must be null or a live [`CallbackState`] the caller owns.
3244pub(crate) fn software_receive(
3245 state: *const CallbackState,
3246 e: ffmpeg_next::Error,
3247 phase: SessionPhase,
3248) -> Result<Received> {
3249 receive_status(software_exit(state, e), phase)
3250}
3251
3252/// The send road's half of [`software_receive`]. Same law, same door.
3253///
3254/// # Safety
3255///
3256/// `state` must be null or a live [`CallbackState`] the caller owns.
3257pub(crate) fn software_send(
3258 state: *const CallbackState,
3259 e: ffmpeg_next::Error,
3260 phase: SessionPhase,
3261) -> Result<Sent> {
3262 send_status(software_exit(state, e), phase)
3263}
3264
3265/// Reads and clears a software frame-budget refusal left by
3266/// [`judge_buffer`], as the named error it deserves.
3267///
3268/// The software twin of [`ceiling_declination_of`]: the allocator judge
3269/// can only answer libavcodec with an errno, so the reason lives in the
3270/// callback state and every decoder funnel collects it.
3271pub(crate) fn frame_budget_declination_of(state: *const CallbackState) -> Option<Error> {
3272 crate::ffi::take_frame_budget_declination(state).map(|(bytes, limit, audio)| {
3273 Error::FrameBudgetExceeded(crate::error::FrameBudgetExceeded::new(
3274 bytes,
3275 limit,
3276 if audio {
3277 crate::error::FrameMedium::Audio
3278 } else {
3279 crate::error::FrameMedium::Video
3280 },
3281 ))
3282 })
3283}
3284
3285/// Proves an opened codec context is a **video** one without going
3286/// through `Opened::video()`.
3287///
3288/// `Opened::video()` calls `Context::medium()`, which reads
3289/// `AVCodecContext.codec_type` as the bindgen `AVMediaType` enum — a
3290/// value outside this build's discriminant set is UB the moment it is
3291/// formed, before any comparison can run. The hardware path has always
3292/// bypassed that API for this reason; this is that bypass, extracted so
3293/// the second caller reuses it instead of restating it.
3294///
3295/// The caller keeps ownership of `opened` on failure, so its `Drop`
3296/// still releases the codec context.
3297pub(crate) fn ensure_video_codec_type(opened: &codec::decoder::Opened) -> Result<()> {
3298 ensure_codec_type(opened, AVMediaType::AVMEDIA_TYPE_VIDEO)
3299}
3300
3301/// The general form: proves an opened context has the medium expected,
3302/// reading `codec_type` as the integer it is.
3303///
3304/// `Opened::{video,audio,subtitle}()` all go through
3305/// `Context::medium()`, so all three carried the same hazard and all
3306/// three now come through here.
3307pub(crate) fn ensure_codec_type(
3308 opened: &codec::decoder::Opened,
3309 expected: AVMediaType,
3310) -> Result<()> {
3311 // SAFETY: `codec_type` is bound as `AVMediaType` (`#[repr(i32)]`),
3312 // the same size and alignment as `i32`; reading the bytes as `i32`
3313 // cannot be UB whatever FFmpeg wrote there.
3314 let codec_type_int: i32 =
3315 unsafe { ptr::read(ptr::addr_of!((*opened.as_ptr()).codec_type) as *const i32) };
3316 if codec_type_int != expected as i32 {
3317 // The same error `Opened::video()` would have produced, without the
3318 // enum construction.
3319 return Err(Error::Ffmpeg(ffmpeg_next::Error::InvalidData));
3320 }
3321 Ok(())
3322}
3323
3324/// Look up the decoder for `parameters` without going through the bindgen
3325/// `AVCodecID` Rust enum. Reads the codec_id field as raw `u32` via
3326/// `addr_of!` + `ptr::read` so a value not in our build's discriminant
3327/// set never invokes UB.
3328pub(crate) fn find_decoder(parameters: &codec::Parameters) -> Result<Codec> {
3329 ensure_parameters_non_null(parameters)?;
3330 // SAFETY: parameters' inner pointer is non-null (checked above);
3331 // addr_of! projects to the codec_id field; the *const u32 cast is sound
3332 // because AVCodecID is `#[repr(u32)]` (same size and alignment as u32).
3333 // Reading as u32 cannot be UB regardless of the value FFmpeg wrote.
3334 let raw_id: u32 =
3335 unsafe { ptr::read(ptr::addr_of!((*parameters.as_ptr()).codec_id) as *const u32) };
3336
3337 // Call C `avcodec_find_decoder` via our local `c_int`-typed shim — we
3338 // never construct an `AVCodecID` enum from `raw_id`. The C function
3339 // returns NULL for unknown ids, which we surface as `Error::NoCodec`.
3340 // SAFETY: avcodec_find_decoder is a pure FFmpeg lookup; passing any
3341 // c_int is sound (returns NULL for unknown).
3342 let codec_ptr = unsafe { c_shims::avcodec_find_decoder(raw_id as libc::c_int) };
3343 if codec_ptr.is_null() {
3344 return Err(Error::NoCodec(raw_id));
3345 }
3346 // SAFETY: codec_ptr is a non-null *const AVCodec into FFmpeg's static
3347 // codec table; it lives for the duration of the program.
3348 Ok(unsafe { Codec::wrap(codec_ptr) })
3349}
3350
3351/// Drain output frames from a candidate decoder during probe replay,
3352/// transferring each one from the candidate's HW context to a fresh CPU
3353/// frame and queueing it. Returns `Ok(())` once the candidate signals
3354/// EAGAIN/EOF. The transfer happens while the candidate is still alive
3355/// (its `AVHWFramesContext` is reachable); the resulting CPU frames remain
3356/// valid after the candidate is committed because they hold their own
3357/// buffer references with no dependency on the original device context.
3358fn drain_into_pending(
3359 decoder: &mut ffmpeg_next::decoder::Video,
3360 hw_buf: &mut frame::Video,
3361 pending: &mut VecDeque<frame::Video>,
3362 pending_bytes: &mut usize,
3363 max_bytes: usize,
3364 frame_limits: crate::FrameLimits,
3365) -> std::result::Result<(), ffmpeg_next::Error> {
3366 loop {
3367 match decoder.receive_frame(hw_buf) {
3368 Ok(()) => {
3369 // Pre-transfer cap check: if we are already at or over either cap,
3370 // the candidate is producing more than we can hold. Treat as an
3371 // explicit candidate failure so `advance_probe` can try the next
3372 // backend instead of committing a stream with silently-dropped
3373 // frames in the middle.
3374 //
3375 // TODO: at very large frame sizes (8K HDR P010, > ~96 MiB each)
3376 // even a single retained frame is significant. Future direction:
3377 // memmap-backed pending frames (write to a temp file or shared
3378 // memory segment) so the resident set stays bounded even when the
3379 // byte cap is raised. Out of scope for now.
3380 if pending.len() >= MAX_PROBE_PENDING_FRAMES || *pending_bytes >= max_bytes {
3381 tracing::warn!(
3382 frames = pending.len(),
3383 bytes = *pending_bytes,
3384 max_frames = MAX_PROBE_PENDING_FRAMES,
3385 max_bytes = max_bytes,
3386 "hwdecode: probe pending cap reached; failing candidate replay"
3387 );
3388 // SAFETY: hw_buf is owned and valid; unref of an empty frame is a no-op.
3389 unsafe { av_frame_unref(hw_buf.as_mut_ptr()) };
3390 return Err(ffmpeg_next::Error::Other {
3391 errno: libc::ENOMEM,
3392 });
3393 }
3394 // Pre-transfer size guard: `av_hwframe_transfer_data` will
3395 // allocate the CPU buffer based on `hw_buf`'s dimensions. If a
3396 // single frame's worst-case footprint already pushes past the
3397 // cap, refuse the candidate **before** allocating so RSS does
3398 // not spike on a frame we'd immediately drop. Uses a width *
3399 // height * `WORST_CASE_BYTES_PER_PIXEL` upper bound; the
3400 // post-transfer accounting via `cpu_frame_bytes` below stays in
3401 // place as a backstop using the actual stride/format.
3402 let estimated_bytes = match estimate_transfer_bytes(hw_buf) {
3403 Some(b) => b,
3404 None => {
3405 // SAFETY: AVFrame.width/height are c_int reads.
3406 let (w, h) = unsafe {
3407 let raw = hw_buf.as_ptr();
3408 ((*raw).width, (*raw).height)
3409 };
3410 tracing::warn!(
3411 width = w,
3412 height = h,
3413 "hwdecode: HW frame dimensions invalid for sizing; failing candidate replay"
3414 );
3415 unsafe { av_frame_unref(hw_buf.as_mut_ptr()) };
3416 return Err(ffmpeg_next::Error::Other {
3417 errno: libc::ENOMEM,
3418 });
3419 }
3420 };
3421 let estimated_total = pending_bytes.saturating_add(estimated_bytes);
3422 if estimated_total > max_bytes {
3423 // SAFETY: AVFrame.width/height are c_int reads.
3424 let (w, h) = unsafe {
3425 let raw = hw_buf.as_ptr();
3426 ((*raw).width, (*raw).height)
3427 };
3428 tracing::warn!(
3429 pending_bytes = *pending_bytes,
3430 estimated_bytes,
3431 width = w,
3432 height = h,
3433 max_bytes = max_bytes,
3434 "hwdecode: pre-transfer size estimate exceeds cap; \
3435 refusing candidate replay before allocating CPU frame"
3436 );
3437 unsafe { av_frame_unref(hw_buf.as_mut_ptr()) };
3438 return Err(ffmpeg_next::Error::Other {
3439 errno: libc::ENOMEM,
3440 });
3441 }
3442 // **The same exact judge, on the replay road.** This site
3443 // already had a pre-transfer *estimate* (`w * h * 8`) against
3444 // the probe's own pending budget; that stays, and this adds the
3445 // frame ceiling itself, priced exactly.
3446 //
3447 // The refusal is reported through this function's existing
3448 // `ffmpeg_next::Error` channel rather than the named arm: every
3449 // error out of a probe-replay drain is collapsed by the caller
3450 // into "this candidate failed, try the next backend", so a name
3451 // has no consumer here. The reason is logged so it is not lost.
3452 // SAFETY: `hw_buf` holds a live decoded HW frame.
3453 if let Err(e) = unsafe { judge_hw_transfer(hw_buf.as_ptr(), frame_limits) } {
3454 tracing::warn!(
3455 bytes = e.bytes(),
3456 limit = e.limit(),
3457 "hwdecode: candidate's hw->cpu transfer would exceed the frame ceiling; \
3458 refusing the candidate before the download"
3459 );
3460 // SAFETY: `hw_buf` is owned and valid.
3461 unsafe { av_frame_unref(hw_buf.as_mut_ptr()) };
3462 return Err(ffmpeg_next::Error::Other {
3463 errno: libc::EINVAL,
3464 });
3465 }
3466 let mut cpu = alloc_av_frame()?;
3467 // SAFETY: hw_buf is a freshly-decoded HW frame;
3468 // `av_hwframe_transfer_data` allocates pixel buffers on `cpu`.
3469 // We use `copy_frame_props_minimal` (only `pts`) instead of
3470 // `av_frame_copy_props` for the same reason as
3471 // `transfer_hw_frame`: the public `Frame` API does not expose
3472 // side data / metadata / opaque refs, so deep-copying them per
3473 // frame is pure cost and an unbounded allocation source on
3474 // attacker-controlled streams.
3475 unsafe {
3476 let r1 = av_hwframe_transfer_data(cpu.as_mut_ptr(), hw_buf.as_ptr(), 0);
3477 if r1 < 0 {
3478 return Err(ffmpeg_next::Error::from(r1));
3479 }
3480 }
3481 // Same post-transfer pix_fmt validation as `transfer_hw_frame`.
3482 // A driver that picks a CPU format outside our supported set
3483 // would queue an unusable frame here; later, when
3484 // `try_pop_pending` hands it to the caller, `Frame::row` /
3485 // `Frame::as_ptr` would return `None`. Refuse the candidate
3486 // before the queue grows so probing advances to the next
3487 // backend instead.
3488 let cpu_raw_fmt: i32 = unsafe { (*cpu.as_ptr()).format };
3489 let cpu_pix_fmt = crate::boundary::from_av_pixel_format(cpu_raw_fmt);
3490 if !crate::frame::is_supported_cpu_pix_fmt(&cpu_pix_fmt) {
3491 tracing::warn!(
3492 pix_fmt = cpu_raw_fmt,
3493 "hwdecode: candidate produced unsupported CPU pix_fmt during \
3494 probe replay; failing candidate"
3495 );
3496 return Err(ffmpeg_next::Error::Other {
3497 errno: libc::EINVAL,
3498 });
3499 }
3500 let pixel_bytes = match cpu_frame_bytes(&cpu) {
3501 Some(b) => b,
3502 None => {
3503 // Unknown pix_fmt or vertically-flipped layout — we cannot
3504 // bound this frame's contribution against the byte cap, so up
3505 // to MAX_PROBE_PENDING_FRAMES of them could exhaust memory.
3506 // Fail the candidate so probing tries the next backend
3507 // rather than queueing untracked allocations.
3508 // SAFETY: AVFrame.format is c_int, safe to read.
3509 let pix_fmt: i32 = unsafe { (*cpu.as_ptr()).format };
3510 tracing::warn!(
3511 pix_fmt,
3512 "hwdecode: cannot size unknown CPU pix_fmt during replay; failing candidate"
3513 );
3514 // cpu drops here.
3515 return Err(ffmpeg_next::Error::Other {
3516 errno: libc::ENOMEM,
3517 });
3518 }
3519 };
3520 // Account for side-data bytes that `av_frame_copy_props`
3521 // will deep-copy from the source HW frame. HDR streams
3522 // typically carry mastering display + content light level
3523 // (~50 bytes) and dynamic HDR metadata (~few hundred bytes);
3524 // pathological side-data could otherwise quietly bypass the
3525 // pixel-data byte cap.
3526 // SAFETY: hw_buf is a valid AVFrame; we read scalar fields
3527 // and pointer arrays without forming a `&AVFrame`.
3528 let side_data_bytes = unsafe { sum_side_data_bytes(hw_buf.as_ptr()) };
3529 let new_total = pending_bytes
3530 .saturating_add(pixel_bytes)
3531 .saturating_add(side_data_bytes);
3532 if new_total > max_bytes {
3533 tracing::warn!(
3534 pending_bytes = *pending_bytes,
3535 pixel_bytes,
3536 side_data_bytes,
3537 max_bytes,
3538 "hwdecode: queueing this frame would exceed byte cap; \
3539 failing candidate replay"
3540 );
3541 // cpu drops here without ever paying a metadata deep copy.
3542 return Err(ffmpeg_next::Error::Other {
3543 errno: libc::ENOMEM,
3544 });
3545 }
3546 // Cap check passed — copy AVFrame metadata. SAFETY: cpu and
3547 // hw_buf are both valid AVFrames we own. On failure (OOM
3548 // during side-data alloc) we propagate so the probe candidate
3549 // is treated as failed rather than queueing a frame whose
3550 // metadata silently disappeared.
3551 unsafe { copy_frame_props_minimal(cpu.as_mut_ptr(), hw_buf.as_ptr()) }?;
3552 *pending_bytes = new_total;
3553 pending.push_back(cpu);
3554 }
3555 Err(e) if is_transient(&e) => return Ok(()),
3556 Err(e) => return Err(e),
3557 }
3558 }
3559}
3560
3561/// Allocated frame dimensions according to `hw_buf.hw_frames_ctx`.
3562///
3563/// Per FFmpeg's `libavutil/hwcontext.c::transfer_data_alloc`, the CPU
3564/// destination of `av_hwframe_transfer_data` is allocated using
3565/// `AVHWFramesContext.width / .height` (the *allocated* surface size of
3566/// the HW pool); only afterwards is `dst->width / dst->height` reset to
3567/// `src->width / src->height` (the *display* size). For cropped or
3568/// heavily aligned streams the allocated dims can be much larger than
3569/// the display dims (e.g. coded 8192×8192 surface with a 100×100
3570/// display crop), so any byte-cap accounting that uses display dims
3571/// undercounts by `allocated_height / display_height` and lets the
3572/// real allocation slip past the cap.
3573///
3574/// Returns `None` when no `hw_frames_ctx` is attached or the dimensions
3575/// are non-positive — the caller treats `None` as "cannot prove
3576/// allocation extent, fail the candidate."
3577fn hw_frames_ctx_dimensions(frame: &frame::Video) -> Option<(i32, i32)> {
3578 // SAFETY: `frame` owns a live `AVFrame` for the call.
3579 unsafe { hw_frames_ctx_dimensions_raw(frame.as_ptr()) }
3580}
3581
3582/// Pointer form of [`hw_frames_ctx_dimensions`], for the judges that
3583/// hold a raw `AVFrame` rather than a wrapper.
3584///
3585/// # Safety
3586///
3587/// `raw` must be a live `*const AVFrame`.
3588unsafe fn hw_frames_ctx_dimensions_raw(raw: *const AVFrame) -> Option<(i32, i32)> {
3589 // SAFETY: AVFrame.hw_frames_ctx is `*mut AVBufferRef`. When non-null,
3590 // its `data` field points to an `AVHWFramesContext`. We read `.width`
3591 // and `.height` (both `c_int`) via field projection — neither field is
3592 // enum-typed, so no bindgen-enum UB hazard.
3593 unsafe {
3594 let hw_ctx_ref = (*raw).hw_frames_ctx;
3595 if hw_ctx_ref.is_null() {
3596 return None;
3597 }
3598 let data = (*hw_ctx_ref).data;
3599 if data.is_null() {
3600 return None;
3601 }
3602 let frames_ctx = data as *const AVHWFramesContext;
3603 let w: i32 = ptr::read(ptr::addr_of!((*frames_ctx).width));
3604 let h: i32 = ptr::read(ptr::addr_of!((*frames_ctx).height));
3605 if w <= 0 || h <= 0 {
3606 return None;
3607 }
3608 Some((w, h))
3609 }
3610}
3611
3612/// Conservative upper-bound estimate of the bytes
3613/// `av_hwframe_transfer_data` will allocate when downloading `hw_buf` to
3614/// a CPU frame. Used by [`drain_into_pending`] as a pre-transfer guard
3615/// so a candidate replay can refuse a frame whose footprint would
3616/// exceed the byte budget *without* first paying the allocation.
3617///
3618/// Sizes from `hw_buf.hw_frames_ctx` (the allocated dims used by the
3619/// FFmpeg transfer path) rather than `AVFrame.width / .height` (display
3620/// dims). On a cropped stream the two can differ by orders of magnitude
3621/// and using display dims would let the real allocation slip past the
3622/// cap.
3623///
3624/// Returns `None` when `hw_frames_ctx` is missing or its width/height
3625/// are non-positive — caller treats as candidate failure since we
3626/// cannot prove the allocation extent. (A SW source frame on the probe
3627/// replay path is not expected; we don't fall back to display dims
3628/// because that's the exact attack the cap is meant to prevent.)
3629fn estimate_transfer_bytes(hw_buf: &frame::Video) -> Option<usize> {
3630 let (w, h) = hw_frames_ctx_dimensions(hw_buf)?;
3631 Some(
3632 (w as usize)
3633 .saturating_mul(h as usize)
3634 .saturating_mul(WORST_CASE_BYTES_PER_PIXEL),
3635 )
3636}
3637
3638/// Exact resident size of a CPU frame: sum of `AVFrame.buf[i].size`
3639/// across every populated buffer.
3640///
3641/// `AVBufferRef.size` is documented as "Size of data in bytes" — the
3642/// real allocated extent FFmpeg used. Reading it directly handles the
3643/// cropped/aligned case where `AVFrame.height` (display) is smaller
3644/// than the underlying allocation height (the `AVHWFramesContext`
3645/// surface size FFmpeg sized the buffer for); a `linesize *
3646/// plane_height_for(display_height)` formula would undercount in that
3647/// case.
3648///
3649/// Returns `None` only when `linesize[0]` is negative — FFmpeg's
3650/// vertically-flipped layout. The crate's safe row accessors
3651/// ([`crate::Frame::row`] / [`crate::Frame::rows`]) already reject
3652/// negative-stride frames, so queueing one during probe replay would
3653/// just delay the failure to the consumer; refusing here lets the
3654/// probe loop advance to the next backend instead.
3655fn cpu_frame_bytes(frame: &frame::Video) -> Option<usize> {
3656 // SAFETY: AVFrame.linesize is `[c_int; 8]`; AVFrame.buf is
3657 // `[*mut AVBufferRef; 8]`; AVBufferRef.size is `usize`. All are
3658 // primitive reads / pointer dereferences with no enum interpretation.
3659 unsafe {
3660 let raw = frame.as_ptr();
3661 let first_linesize = (*raw).linesize[0];
3662 // Vertically-flipped (negative linesize) is the only "unsizeable"
3663 // case we still surface as `None`; everything else can be exactly
3664 // measured from buf[i].size.
3665 if first_linesize < 0 {
3666 return None;
3667 }
3668 let mut total: usize = 0;
3669 for i in 0..(*raw).buf.len() {
3670 let buf = (*raw).buf[i];
3671 if buf.is_null() {
3672 continue;
3673 }
3674 total = total.saturating_add((*buf).size);
3675 }
3676 Some(total)
3677 }
3678}
3679
3680#[allow(dead_code)]
3681fn _assert_send() {
3682 fn check<T: Send>() {}
3683 check::<VideoDecoder>();
3684}
3685
3686#[cfg(test)]
3687mod tests;