mediadecode_ffmpeg/video/mod.rs
1//! `mediadecode::VideoStreamDecoder` impl with HW + SW fallback.
2//!
3//! [`FfmpegVideoStreamDecoder`] starts on the hardware path: an inner
4//! [`crate::VideoDecoder`] that auto-probes VideoToolbox / VAAPI /
5//! NVDEC / D3D11VA. When every HW backend fails — at `open` time
6//! (no backend opens) or mid-stream ([`crate::Error::AllBackendsFailed`]
7//! from `send_packet` / `receive_frame` / `send_eof`) — we transparently
8//! fall back to a **software** `ffmpeg::decoder::Video` opened from the
9//! same `Parameters`.
10//!
11//! Two HW-exhaustion shapes feed the same fallback, distinguished by an
12//! **explicit origin** the `AllBackendsFailed` carries
13//! ([`crate::error::FallbackOrigin`]) — *not* by whether its rescued
14//! `unconsumed_packets` is empty (both shapes can be empty: a probe-era
15//! failure on the first packet has no prior history, exactly like every
16//! post-commit failure):
17//!
18//! * **Probe-era** (pre-first-frame, [`crate::error::FallbackOrigin::Probe`]):
19//! the inner decoder buffered every packet it consumed and surfaces them in
20//! `unconsumed_packets`. We **replay exactly those** through the SW decoder
21//! (lossless — no frame was delivered yet), then route the still-unconsumed
22//! current packet (the one the inner decoder failed on / refused) to SW
23//! ourselves. This is the original pre-runtime-fallback behaviour and is
24//! unchanged.
25//! * **Post-commit** (after the first frame, the inner probe is gone,
26//! [`crate::error::FallbackOrigin::PostCommit`]): a runtime HW-decode failure
27//! — e.g. VideoToolbox choking on H.264 High 4:2:2 10-bit — is reclassified
28//! to `AllBackendsFailed` by the inner decoder with an **empty**
29//! `unconsumed_packets` (the probe buffer no longer exists). Here we
30//! **degrade and continue** rather than reconstruct: open the SW decoder with
31//! an empty replay set and let it **resync at the next keyframe**. Fed forward
32//! packets from the failure point, the SW decoder naturally produces nothing
33//! until that keyframe, then decodes normally from there. The bounded span
34//! from the failure point to the next keyframe is dropped — an accepted,
35//! **loudly logged** gap (a single `tracing::warn!`), not a silent one. The
36//! indexing pipeline this serves prefers a small logged gap over the
37//! error-prone mid-stream-reconstruction state machine a lossless replay
38//! would require (see findit-studio/mediadecode#12). The *bounded*-ness is
39//! **enforced, not assumed**: a post-commit fallback enters a degraded-resync
40//! mode that holds until a **keyframe-anchored** resync — the SW decoder
41//! delivering a frame *after* a keyframe was fed to it across the gap. (Gating
42//! on a keyframe, not on *any* frame, matters because a lenient codec will
43//! decode a lone P-frame from the dropped span into a concealed frame; that
44//! must not count as a resync, or the one-GOP bound isn't truly enforced.) If
45//! EOF is reached while the mode is still pending — no keyframe ever arrived
46//! across the gap and the whole tail was lost — `receive_frame` escalates with
47//! a distinct [`VideoDecodeError::PostCommitNeverResynced`] (and a
48//! `tracing::error!`) rather than surfacing a clean end-of-stream that would
49//! swallow the tail silently. So the gap is either bounded-and-logged (a real
50//! keyframe resync happened) or reported-at-EOF (it never did) — never
51//! silent-and-unbounded.
52//!
53//! The post-commit path retains and reconstructs **zero** frames: it opens SW
54//! cold, forwards only the failure arm's current packet (or EOF), and lets SW
55//! resync naturally. It never populates the replay-frame queue, so the
56//! replay/conversion machinery the probe-era path uses cannot touch it.
57//!
58//! The probe-era replay happens before the new packet (or the next
59//! `receive_frame` poll) is processed, so a probe-era HW exhaustion on a
60//! non-seekable input loses no compressed data. The post-commit path
61//! intentionally accepts the next-keyframe gap.
62//!
63//! After the transition the decoder stays on SW for the rest of its
64//! life — there's no probe-back-to-HW logic; once we've decided the
65//! stream isn't HW-decodable, that decision is sticky.
66//!
67//! Frames produced by either path are converted via
68//! [`crate::convert::av_frame_to_video_frame`] so the consumer sees
69//! the same `mediadecode::VideoFrame<PixelFormat, VideoFrameExtra,
70//! FfmpegBytes>` shape regardless of which backend produced it.
71
72use std::collections::VecDeque;
73
74/// Maximum number of frames the SW fallback replay path will buffer
75/// while draining the new SW decoder during packet/EOF replay.
76/// Replaying many compressed packets through SW can produce hundreds
77/// of decoded frames before the fallback commits; with no cap the
78/// resident memory grows unbounded (e.g. 4K frames at ~12 MB each ×
79/// 100s of frames). 64 frames is enough room to absorb every
80/// realistic codec's reorder/lookahead window without becoming a
81/// resource sink.
82const SW_REPLAY_FRAME_CAP: usize = 64;
83
84use derive_more::{IsVariant, TryUnwrap, Unwrap};
85use ffmpeg_next::{Packet, codec::Parameters, frame};
86use mediadecode::{
87 Received, Sent, Timebase,
88 decoder::{ScaledOutputCapability, VideoStreamDecoder},
89 frame::VideoFrame,
90 packet::VideoPacket,
91};
92
93use crate::{
94 Backend, DecoderLimits, Error, Ffmpeg, Frame, VideoDecoder, boundary,
95 convert::{self, ConvertError},
96 decoder::{build_codec_context, try_clone_parameters},
97 error::FallbackFailed,
98 extras::{VideoFrameExtra, VideoPacketExtra},
99 frame::alloc_av_video_frame,
100};
101
102/// Which decode path a video session takes — the choice
103/// [`CarrierVideoStreamDecoder::open_as`] is given.
104///
105/// # The arms differ in what they PERMIT, not only in where they start
106///
107/// [`Auto`](Self::Auto) is a preference: it starts on hardware and is
108/// free to end on software, at open or mid-stream. The other two are
109/// **pins**, and a pin that a mid-stream failure could quietly undo
110/// would not be one — so a session opened on either of them stays on
111/// the path it was opened on for its whole life, and a hardware failure
112/// that `Auto` would degrade through is reported instead.
113///
114/// That is the difference the two consumers of this door need. A
115/// determinism comparison decodes *one stream* both ways and compares
116/// the pixels; a run that silently swapped paths halfway would compare
117/// nothing and say it had. An operator turning hardware off for a lane
118/// over a driver that produces wrong pixels needs it to stay off.
119///
120/// # Observability is unchanged
121///
122/// [`is_hardware`](CarrierVideoStreamDecoder::is_hardware) and
123/// [`is_software`](CarrierVideoStreamDecoder::is_software) read where a
124/// session **is**, which stays a live reading — under
125/// [`Auto`](Self::Auto) it can still change once, and under the pins it
126/// answers what was pinned because nothing can move it.
127///
128/// This type deliberately grows **no** `is_*` predicates of its own,
129/// where most vocabularies in this crate do. They would spell the
130/// decoder's two questions a second time with a different meaning —
131/// `path.is_software()` is *what was asked for* and
132/// `decoder.is_software()` is *where it ended up*, and under
133/// [`Auto`](Self::Auto) those genuinely differ. A caller that needs to
134/// branch on the choice it made already holds the value and can
135/// `match` it.
136#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
137pub enum DecodePath {
138 /// Probe the platform's hardware backends in order and fall back to
139 /// software — at open, and again on a mid-stream hardware failure.
140 ///
141 /// What [`CarrierVideoStreamDecoder::open`] has always done, and what
142 /// it still does.
143 Auto,
144 /// **This hardware backend, or nothing.** No other backend is probed
145 /// and software is never opened.
146 ///
147 /// A backend that cannot be opened for the stream fails the
148 /// [`open_as`](CarrierVideoStreamDecoder::open_as) call. A backend
149 /// that opens and then fails to decode surfaces
150 /// [`Error::AllBackendsFailed`] from the send or receive road that
151 /// met it, carrying that backend and what it said — the same error
152 /// [`Auto`](Self::Auto) treats as its cue to degrade, reported here
153 /// because degrading is what this arm declines.
154 Hardware(Backend),
155 /// **Software, with no probe at all.**
156 ///
157 /// Opens `libavcodec`'s own decoder for the stream directly. There is
158 /// no hardware in this session to fail, so there is nothing for it to
159 /// fall back from — the terminal state [`Auto`](Self::Auto) reaches
160 /// by degrading, entered on purpose.
161 Software,
162}
163
164/// `mediadecode::VideoStreamDecoder` impl with transparent HW → SW
165/// fallback.
166pub struct CarrierVideoStreamDecoder<C: crate::FfmpegCarrier> {
167 state: DecodeState,
168 /// The path this session was opened on — see [`DecodePath`].
169 ///
170 /// Read for exactly one question, [`Self::may_open_software`]: whether
171 /// a hardware exhaustion is this session's cue to degrade or its cue
172 /// to report. Kept as the whole choice rather than reduced to that
173 /// bit so a session can say what it *is*, not only what it allows.
174 path: DecodePath,
175 /// Codec parameters retained so we can open a software
176 /// `ffmpeg::decoder::Video` if the HW probe exhausts.
177 parameters: Parameters,
178 /// HW-side scratch frame (filled by [`VideoDecoder::receive_frame`]).
179 hw_scratch: Frame,
180 /// SW-side scratch frame (filled by `ffmpeg::decoder::Video::receive_frame`).
181 sw_scratch: frame::Video,
182 /// Frames produced while draining the SW decoder during fallback
183 /// replay (see [`Self::fall_back_to_sw`]). The trait's
184 /// `receive_frame` delivers from this queue before pulling new
185 /// frames from the SW decoder. Empty in steady-state operation.
186 sw_replay_frames: VecDeque<frame::Video>,
187 /// Resource ceilings for the frames this decoder exports, and for the
188 /// `AVCodecContext`s it opens — HW candidates, the SW fallback, and
189 /// any decoder a later probe advance builds all get the same number.
190 limits: DecoderLimits,
191 /// `true` once `send_eof` has been called on the active decoder.
192 /// Used to propagate EOF to the SW decoder when fallback fires
193 /// during the drain phase — without this, codecs that hold tail
194 /// frames at EOF would hang waiting for an EOF they already saw on
195 /// the HW path.
196 eof_sent: bool,
197 /// `true` between a **post-commit** fallback firing and a *keyframe-anchored*
198 /// resync (the SW decoder delivering a frame **after** a keyframe was fed to
199 /// it across the gap). A post-commit fallback opens SW cold and drops the
200 /// bounded span up to the next keyframe; the promise is that the span is
201 /// *bounded* — SW resyncs at that keyframe. This flag makes the promise
202 /// enforced rather than assumed: while it is set we have no proof SW ever
203 /// recovered from a real keyframe. It is cleared only when SW delivers a frame
204 /// *and* [`Self::degraded_keyframe_seen`] is set (a lone concealed P-frame a
205 /// lenient codec emits from the gap does **not** clear it); if EOF is reached
206 /// while it is still set the loss is escalated (a distinct loud error) rather
207 /// than silently swallowing the whole tail. Probe-era fallbacks never set it —
208 /// they replay losslessly and produce frames immediately.
209 degraded_resync_pending: bool,
210 /// `true` once a **keyframe** packet has been successfully fed to the SW
211 /// decoder while [`Self::degraded_resync_pending`] is set — i.e. a real resync
212 /// anchor crossed the gap. The pending flag clears only on a delivered SW
213 /// frame *after* this is set, so a concealed non-keyframe frame (a lenient
214 /// codec decoding a lone P-frame from the dropped span) cannot masquerade as a
215 /// resync and prematurely clear the guard. Set alongside `enter`/cleared with
216 /// the pending flag.
217 degraded_keyframe_seen: bool,
218 /// Packets fed to the SW decoder since the post-commit fallback fired while
219 /// [`Self::degraded_resync_pending`] is set — i.e. across the unresolved
220 /// resync gap. Reported in the escalation message so the lost span is
221 /// quantified ("N packets, no keyframe found"). Reset whenever the flag
222 /// clears or on `flush`.
223 degraded_packets_since_fallback: u64,
224 /// Source-stream time base, used to label produced frames.
225 time_base: Timebase,
226 /// The lane this decoder captures into. A marker: the carrier
227 /// appears in the frames it produces, not in its own state.
228 /// `true` when the scratch frame holds a decoded frame whose
229 /// conversion has **not committed** — see
230 /// [`CarrierAudioStreamDecoder::scratch_pending`](crate::audio::CarrierAudioStreamDecoder)
231 /// for the reasoning, which is the same on both roads.
232 ///
233 /// **This decoder has two scratches and can change which one is
234 /// current, so the seat is enforced rather than merely recorded.**
235 /// While it is set, `send_packet` and `send_eof` answer
236 /// [`Sent::MustDrain`]: both are the roads that commit a
237 /// hardware-to-software fallback, and a fallback under a parked frame
238 /// would leave the retry reading the *other* scratch — delivering a
239 /// stale frame, or refusing permanently and stranding a decoded one.
240 /// Refusing makes the retry's state the state that parked it **by
241 /// construction**, which is a stronger guarantee than remembering
242 /// which road produced it.
243 ///
244 /// **The discipline is unchanged; only its spelling moved.** It was
245 /// `VideoDecodeError::FramePending`, and the escape was already
246 /// documented as "call `receive_frame`, or `flush` to abandon it" —
247 /// which is to say it was back pressure wearing an error's clothes.
248 /// Now it says so, and a caller can act on it without inspecting a
249 /// backend-specific error type. The subtitle decoder keeps the same
250 /// seat one road over, spelled the same way.
251 scratch_pending: bool,
252 _carrier: core::marker::PhantomData<C>,
253}
254
255/// Hardware-decode seam behind [`DecodeState::Hw`]. In production this is
256/// the real [`VideoDecoder`]; tests substitute a fake to drive the
257/// post-commit fallback path without a live GPU. Mirrors the subset of
258/// `VideoDecoder`'s surface the wrapper drives on the HW path.
259pub(crate) trait HwInner: Send {
260 /// See [`VideoDecoder::send_packet`].
261 fn send_packet(&mut self, packet: &Packet) -> Result<Sent, Error>;
262 /// See [`VideoDecoder::receive_frame`].
263 fn receive_frame(&mut self, frame: &mut Frame) -> Result<Received, Error>;
264 /// See [`VideoDecoder::send_eof`].
265 fn send_eof(&mut self) -> Result<Sent, Error>;
266 /// See [`VideoDecoder::flush`]. Returns `Result` for a uniform seam even
267 /// though the inherent method is infallible.
268 fn flush(&mut self) -> Result<(), Error>;
269 /// Downcast to the concrete [`VideoDecoder`] when this seam is the real
270 /// HW decoder, so [`FfmpegVideoStreamDecoder::hardware_inner`] can keep
271 /// exposing it. Returns `None` for a test fake.
272 fn as_video_decoder(&self) -> Option<&VideoDecoder>;
273
274 /// Whether a packet submitted **now** would be recorded for replay.
275 ///
276 /// The probe keeps a rescue history so that a decoder which exhausts
277 /// every backend can hand the caller everything FFmpeg consumed since
278 /// open. It records by `av_packet_ref`, and
279 /// [`AllBackendsFailed::into_unconsumed_packets`] hands those
280 /// recordings out as owned, **mutable** `Packet`s — which is why the
281 /// view lane must not share its carrier's storage into a submission
282 /// that could be recorded. See
283 /// [`CarrierVideoStreamDecoder::send_packet_impl`].
284 fn records_submissions(&self) -> bool;
285
286 /// See [`VideoDecoder::scaled_output_capability`].
287 ///
288 /// Defaulted to the refusal so a test fake — which has no
289 /// VideoToolbox road behind it, and therefore no stage — answers
290 /// honestly without having to say so.
291 fn scaled_output_capability(&self) -> ScaledOutputCapability {
292 ScaledOutputCapability::Unsupported
293 }
294
295 /// See [`VideoDecoder::request_scaled_output`]. Defaulted to the
296 /// refusal, for the same reason as above.
297 fn request_scaled_output(&mut self, size: (u32, u32)) -> ScaledOutputCapability {
298 let _ = size;
299 ScaledOutputCapability::Unsupported
300 }
301
302 /// See [`VideoDecoder::cancel_scaled_output`]. Defaulted to nothing,
303 /// because a seat that never accepts a request has none to withdraw.
304 fn cancel_scaled_output(&mut self) {}
305}
306
307impl HwInner for VideoDecoder {
308 #[inline]
309 fn records_submissions(&self) -> bool {
310 self.is_probing()
311 }
312
313 #[inline]
314 fn send_packet(&mut self, packet: &Packet) -> Result<Sent, Error> {
315 VideoDecoder::send_packet(self, packet)
316 }
317 #[inline]
318 fn receive_frame(&mut self, frame: &mut Frame) -> Result<Received, Error> {
319 VideoDecoder::receive_frame(self, frame)
320 }
321 #[inline]
322 fn send_eof(&mut self) -> Result<Sent, Error> {
323 VideoDecoder::send_eof(self)
324 }
325 #[inline]
326 fn flush(&mut self) -> Result<(), Error> {
327 VideoDecoder::flush(self);
328 Ok(())
329 }
330 #[inline]
331 fn as_video_decoder(&self) -> Option<&VideoDecoder> {
332 Some(self)
333 }
334 #[inline]
335 fn scaled_output_capability(&self) -> ScaledOutputCapability {
336 VideoDecoder::scaled_output_capability(self)
337 }
338 #[inline]
339 fn request_scaled_output(&mut self, size: (u32, u32)) -> ScaledOutputCapability {
340 VideoDecoder::request_scaled_output(self, size)
341 }
342 #[inline]
343 fn cancel_scaled_output(&mut self) {
344 VideoDecoder::cancel_scaled_output(self);
345 }
346}
347
348/// Internal: which backend is currently driving the decode.
349enum DecodeState {
350 /// Hardware-backed decoder (auto-probe). May transition to `Sw` on
351 /// `AllBackendsFailed`. Boxed behind [`HwInner`] so tests can inject a
352 /// fake HW decoder.
353 Hw(Box<dyn HwInner>),
354 /// Software decoder. Terminal state.
355 Sw(SwDecoder),
356}
357
358/// A software decoder and the callback state its codec context points
359/// at.
360///
361/// The state carries the allocator judge's byte budget and the
362/// `get_format` declination; it has to outlive the `AVCodecContext`
363/// that references it, which is why it is a field here rather than a
364/// value dropped at the end of `open_sw_decoder`.
365///
366/// `Deref` so that every call site keeps talking to the decoder and
367/// only the construction changed — this pairing is a lifetime fact, not
368/// a new abstraction.
369pub(crate) struct SwDecoder {
370 decoder: ffmpeg_next::decoder::Video,
371 /// Declared **after** the decoder: fields drop in declaration order,
372 /// so the codec context is freed before the state it points at.
373 _callback_state: Box<crate::ffi::CallbackState>,
374}
375
376impl SwDecoder {
377 /// The callback state this decoder's codec context points at.
378 ///
379 /// Handed out as a raw pointer so an error closure can consult it
380 /// while the decoder itself is mutably borrowed — every software send
381 /// / receive / EOF failure on this road goes through
382 /// [`crate::decoder::software_exit`] with it, so a frame the
383 /// allocator judge refused surfaces named instead of as the `EINVAL`
384 /// libavcodec also uses for corrupt input.
385 ///
386 /// `Deref` alone was not enough: it exposes the decoder and hides the
387 /// state, so every call site kept wrapping raw and the budget refusal
388 /// had no way out on the whole software road — including the replay
389 /// and cold-fallback helpers, which drop the state when they finish.
390 pub(crate) fn state(&self) -> *const crate::ffi::CallbackState {
391 &*self._callback_state
392 }
393}
394
395impl core::ops::Deref for SwDecoder {
396 type Target = ffmpeg_next::decoder::Video;
397 fn deref(&self) -> &Self::Target {
398 &self.decoder
399 }
400}
401
402impl core::ops::DerefMut for SwDecoder {
403 fn deref_mut(&mut self) -> &mut Self::Target {
404 &mut self.decoder
405 }
406}
407
408/// What the cold SW decoder is fed on a **post-commit** degrade transition,
409/// named by the failure arm so the three shapes stay mutually exclusive (a
410/// current packet and EOF are never forwarded together). The post-commit path
411/// retains no replay frames, so this is the *only* thing handed to the new SW
412/// decoder at fallback time. See [`FfmpegVideoStreamDecoder::degrade_to_sw`].
413enum PostCommitInput<'a> {
414 /// `send_packet` arm: forward this current packet — the one the HW decoder
415 /// refused (so it was never in any replay set). If it is a keyframe it is the
416 /// resync anchor.
417 Packet(&'a Packet),
418 /// `receive_frame` arm: a frame-time failure has no current packet to forward.
419 FrameTime,
420 /// `send_eof` arm: EOF was pending on the HW path; re-forward it to the cold
421 /// SW so tail-delaying codecs don't hang.
422 Eof,
423}
424
425impl<C: crate::FfmpegCarrier + crate::CarrierOps> CarrierVideoStreamDecoder<C> {
426 /// Opens a decoder for the given codec parameters with the default
427 /// HW backend probe order. If the HW probe can't open any backend,
428 /// falls back to a software `ffmpeg::decoder::Video` immediately —
429 /// `open` only returns `Err` when both paths fail.
430 ///
431 /// Subsequent mid-stream `AllBackendsFailed` from the HW path
432 /// triggers the same SW fallback (with rescued packets replayed).
433 ///
434 /// `limits` bounds what one decoded frame may cost. It is taken here
435 /// rather than through a builder because half of it —
436 /// [`DecoderLimits::max_pixels`] — is written into every
437 /// `AVCodecContext` this decoder opens, and a context's ceiling
438 /// cannot be moved after `avcodec_open2`. That includes the contexts
439 /// opened later, by a mid-stream fallback or a probe advance: the
440 /// limits are retained for exactly that reason.
441 pub(crate) fn open_impl(
442 parameters: Parameters,
443 time_base: Timebase,
444 limits: DecoderLimits,
445 ) -> Result<Self, Error> {
446 Self::open_as_impl(parameters, time_base, limits, DecodePath::Auto)
447 }
448
449 /// [`Self::open_impl`], with the decode path chosen rather than
450 /// probed. `DecodePath::Auto` is the constructor above, verbatim.
451 pub(crate) fn open_as_impl(
452 parameters: Parameters,
453 time_base: Timebase,
454 limits: DecoderLimits,
455 path: DecodePath,
456 ) -> Result<Self, Error> {
457 // ffmpeg-next's `Parameters` carries an optional `owner: Rc<dyn Any>`
458 // (when constructed from `stream.parameters()` it points back at
459 // the demuxer's `AVStream`). Upstream marks the type `Send`
460 // anyway, which is unsound the moment a non-`None` owner is in
461 // play — moving such a value across threads moves the `Rc`. We
462 // sidestep this by always storing a deep-cloned `Parameters`
463 // (`avcodec_parameters_copy` produces an owner-free copy), so
464 // the `FfmpegVideoStreamDecoder`'s `Send` reachability never
465 // depends on the caller's owner discipline.
466 //
467 // Use `try_clone_parameters` instead of `Parameters::clone` —
468 // ffmpeg-next's `clone` calls `Parameters::new()` which can
469 // return a `Parameters` whose inner pointer is null on OOM
470 // (`avcodec_parameters_alloc` returns null without indication);
471 // the subsequent `avcodec_parameters_copy` against that null
472 // destination is C UB. Our checked helper surfaces the OOM as
473 // an error instead.
474 let owned_parameters = try_clone_parameters(¶meters, limits.max_codec_parameter_bytes())?;
475 let hw_scratch = Frame::empty()?;
476 let sw_scratch = alloc_av_video_frame()?;
477 let state = match path {
478 DecodePath::Auto => match VideoDecoder::open_with_frame_limits(
479 try_clone_parameters(&owned_parameters, limits.max_codec_parameter_bytes())?,
480 limits,
481 ) {
482 Ok(hw) => DecodeState::Hw(Box::new(hw)),
483 Err(Error::AllBackendsFailed(_)) => {
484 // Open-time HW exhaustion: no rescued packets (open didn't
485 // see any). Just open SW directly from our owned copy.
486 let sw = open_sw_decoder(&owned_parameters, limits)?;
487 DecodeState::Sw(sw)
488 }
489 Err(other) => return Err(other),
490 },
491 // **The named backend, and no probe order at all.** Nothing is
492 // tried before it and nothing after it, which is what makes the
493 // arm a pin: an open that fails is the answer, where `Auto` would
494 // have read the same failure as a reason to look elsewhere.
495 DecodePath::Hardware(backend) => DecodeState::Hw(Box::new(VideoDecoder::open_with_limits(
496 try_clone_parameters(&owned_parameters, limits.max_codec_parameter_bytes())?,
497 backend,
498 limits,
499 )?)),
500 // The software decoder, opened on purpose rather than reached by
501 // degrading. `DecodeState::Sw` is terminal, so this session has
502 // nothing to keep it on its path but the shape of the state
503 // machine itself.
504 DecodePath::Software => DecodeState::Sw(open_sw_decoder(&owned_parameters, limits)?),
505 };
506 Ok(Self {
507 state,
508 path,
509 parameters: owned_parameters,
510 hw_scratch,
511 sw_scratch,
512 sw_replay_frames: VecDeque::new(),
513 eof_sent: false,
514 degraded_resync_pending: false,
515 degraded_keyframe_seen: false,
516 degraded_packets_since_fallback: 0,
517 time_base,
518 limits,
519 scratch_pending: false,
520 _carrier: core::marker::PhantomData,
521 })
522 }
523
524 /// Returns `true` when this decoder has fallen back to the software
525 /// path. `false` while still on the HW probe (the initial state).
526 #[cfg_attr(not(tarpaulin), inline(always))]
527 pub(crate) const fn is_software_impl(&self) -> bool {
528 matches!(self.state, DecodeState::Sw(_))
529 }
530
531 /// Returns `true` while the HW probe is still active.
532 #[cfg_attr(not(tarpaulin), inline(always))]
533 pub(crate) const fn is_hardware_impl(&self) -> bool {
534 matches!(self.state, DecodeState::Hw(_))
535 }
536
537 /// Whether this session can currently honor a
538 /// [`Self::request_scaled_output_impl`] request. See
539 /// [`ScaledOutputCapability`] for the determinism trade a caller
540 /// takes on by requesting one.
541 ///
542 /// **[`ScaledOutputCapability::Supported`] on exactly one road: a
543 /// live VideoToolbox session on an Apple target.** There, a
544 /// `VTPixelTransferSession` sits between the decoded hardware frame
545 /// and `av_hwframe_transfer_data` and resizes the `CVPixelBuffer` on
546 /// the GPU, so the fitted picture is what crosses to the CPU — see
547 /// [`crate::vtscale`] for the design, and
548 /// [mediadecode#55](https://github.com/findit-studio/mediadecode/issues/55)
549 /// for the ruling that chose it. Everything else answers
550 /// `Unsupported`, and each refusal has its own reason rather than a
551 /// shared shrug:
552 ///
553 /// - **A session that has degraded to software.** The stage is the
554 /// hardware road's; this answer follows the session, so it flips to
555 /// `Unsupported` the moment a fallback commits, and a caller that
556 /// asks again learns it.
557 /// - **The other hardware backends.** [`Backend::Vaapi`],
558 /// [`Backend::Cuda`] and [`Backend::D3d11va`] are wired in source
559 /// (`Backend::av_hwdevice_type`, `probe_order`) but cannot be
560 /// compiled, run or verified on a non-Linux, non-Windows host, and
561 /// each has a native scaling seam of its own that this crate has
562 /// not built: NVDEC/CUVID in-decode scaling
563 /// ([#56](https://github.com/findit-studio/mediadecode/issues/56)),
564 /// VAAPI VPP
565 /// ([#57](https://github.com/findit-studio/mediadecode/issues/57)),
566 /// the D3D11 Video Processor
567 /// ([#58](https://github.com/findit-studio/mediadecode/issues/58)).
568 /// Filed rather than fabricated.
569 /// - **Software.** See [`Self::request_scaled_output_impl`] for the
570 /// software road's own, separate refusal.
571 ///
572 /// What the VideoToolbox road did **not** get is decode-time
573 /// scaling, and the distinction is worth keeping: inter prediction
574 /// needs full-resolution reference frames, so every road decodes full
575 /// size internally. What this seam saves is the GPU→CPU crossing and
576 /// the CPU frame at the end of it — roughly thirtyfold on a 4K stream
577 /// fitted to a 512-class box. A caller-owned `VTDecompressionSession`
578 /// would save the same crossing and no more, which is why it stays
579 /// #55's standing future enhancement rather than this release's work.
580 ///
581 /// A pure query: calling it requests nothing and changes nothing
582 /// about what [`Self::receive_frame`] delivers.
583 #[cfg_attr(not(tarpaulin), inline(always))]
584 pub(crate) fn scaled_output_capability_impl(&self) -> ScaledOutputCapability {
585 match &self.state {
586 DecodeState::Hw(hw) => hw.scaled_output_capability(),
587 DecodeState::Sw(_) => ScaledOutputCapability::Unsupported,
588 }
589 }
590
591 /// Requests that this session emit pictures at `size` from the next
592 /// frame on. See [`Self::scaled_output_capability_impl`] for which
593 /// road can honor it at all.
594 ///
595 /// # A parked frame refuses
596 ///
597 /// While [`Self::scratch_pending`] holds a decoded picture whose
598 /// conversion did not commit, this refuses. That frame is already
599 /// decided — the retry delivers it from the scratch without
600 /// consulting the stage — so accepting a new size would promise an
601 /// extent the very next frame cannot have. Drain it and ask again;
602 /// the same escape every other seat guarded by that flag offers.
603 ///
604 /// The refusal carries the same meaning as every other: the session
605 /// returns to full coded size, so any request already standing is
606 /// withdrawn. The parked picture keeps the extent it was decoded at.
607 ///
608 /// # When a mid-stream request takes effect
609 ///
610 /// On the **next** picture [`Self::receive_frame`] produces. The
611 /// stage is consulted per frame, on the way out of the hardware
612 /// decoder and before the GPU→CPU download, so a request never
613 /// reaches back to a picture already decoded and never waits longer
614 /// than the one being decoded now.
615 ///
616 /// # The two refusals this seat mints itself
617 ///
618 /// Neither is an error, and each **returns the session to full coded
619 /// size**, dropping any request already standing — what the trait
620 /// says this answer means, and the only reading a caller can act on
621 /// without risking a second resample of an already-fitted picture:
622 ///
623 /// - **A zero extent.** A zero-extent picture is not a smaller
624 /// picture.
625 /// - **An upscale.** The stage exists to move fewer bytes across the
626 /// GPU→CPU bus; enlarging moves more, and inventing detail the
627 /// decoder did not produce is the caller's business rather than a
628 /// decode session's. An *equal* size is not an upscale: it is
629 /// accepted, and the stage simply has nothing to do.
630 ///
631 /// # The software road's refusal has its own, different shape
632 ///
633 /// Worth naming rather than folding into "no backend does this yet":
634 /// FFmpeg's software decoders have no *general* decode-time scaling
635 /// seam. The one option that comes close — `AVCodecContext.lowres`
636 /// (the CLI's `-lowres`) — falls short on three separate counts, any
637 /// one of which would disqualify it as this seam's software answer:
638 ///
639 /// 1. **Narrow codec coverage.** `lowres` is wired only into the
640 /// legacy MPEG-family decoders (MPEG-1/2/4 part 2, H.263) that
641 /// still carry the low-resolution IDCT machinery it depends on.
642 /// HEVC, AV1 and VP9 — the codecs a modern HDR pipeline actually
643 /// decodes — implement no `lowres` support at all.
644 /// 2. **The one codec that is wired is broken.** `lowres` on H.264
645 /// (also nominally covered) has been non-functional for years —
646 /// the decoder does not honor it correctly — so even the "old
647 /// family" half of the promise does not hold across the board.
648 /// 3. **It is not a resize, it is reduced reconstruction.** Where it
649 /// does work, `lowres` decodes at a coarser IDCT precision
650 /// (`1<<lowres`), skipping reconstruction detail rather than
651 /// decoding in full and scaling the result — later inter frames
652 /// drift from a reference the decoder itself degraded, which is a
653 /// different (and worse) contract than "the same picture, smaller".
654 ///
655 /// So the software road's answer is not "unimplemented" the way the
656 /// other hardware backends' is — it is "full-size decode, then the
657 /// fused conform walk downstream", by design, on every codec this
658 /// crate decodes in software.
659 #[cfg_attr(not(tarpaulin), inline(always))]
660 pub(crate) fn request_scaled_output_impl(&mut self, size: (u32, u32)) -> ScaledOutputCapability {
661 // **A parked frame is already decided, so it may not be
662 // re-promised.** [`Self::scratch_pending`] means a picture came out
663 // of the decoder and its conversion did not commit; the retry
664 // delivers *that* frame from the scratch without going back through
665 // the stage, so it will arrive at whatever extent it already has.
666 // Accepting a new size here would answer `Supported` and then hand
667 // the caller a frame the new request never touched — the exact
668 // silent mismatch [`Self::scaled_output_capability_impl`]'s promise
669 // exists to rule out. Refusing changes nothing, which is the
670 // contract for a refusal, and the caller's escape is the one this
671 // seat already documents everywhere else: drain the frame, then ask
672 // again.
673 if self.scratch_pending {
674 tracing::debug!(
675 requested_width = size.0,
676 requested_height = size.1,
677 "mediadecode-ffmpeg: scaled-output request refused while a decoded frame is parked; \
678 the session returns to full size — drain it and ask again"
679 );
680 // **A refusal means the same thing here as anywhere else.**
681 // Returning `Unsupported` while an earlier request stayed armed
682 // would leave the caller resampling pictures this session went on
683 // fitting — the very double-scale the word exists to prevent. So
684 // the standing request goes, and with it what was built for it.
685 // The parked picture keeps the extent it was decoded at, which is
686 // the same rule an *acceptance* has always carried.
687 if let DecodeState::Hw(hw) = &mut self.state {
688 hw.cancel_scaled_output();
689 }
690 return ScaledOutputCapability::Unsupported;
691 }
692 match &mut self.state {
693 DecodeState::Hw(hw) => hw.request_scaled_output(size),
694 DecodeState::Sw(_) => ScaledOutputCapability::Unsupported,
695 }
696 }
697
698 /// Borrow the inner [`VideoDecoder`] when this decoder is still on the
699 /// real HW path. Returns `None` after the SW fallback has fired (or, in
700 /// tests, when the HW seam is a fake rather than a real decoder).
701 #[cfg_attr(not(tarpaulin), inline(always))]
702 pub(crate) fn hardware_inner_impl(&self) -> Option<&VideoDecoder> {
703 match &self.state {
704 DecodeState::Hw(hw) => hw.as_video_decoder(),
705 DecodeState::Sw(_) => None,
706 }
707 }
708
709 /// Returns the time base associated with the source stream.
710 #[cfg_attr(not(tarpaulin), inline(always))]
711 pub(crate) const fn time_base_impl(&self) -> Timebase {
712 self.time_base
713 }
714
715 /// Whether this session may open a software decoder in answer to a
716 /// hardware exhaustion.
717 ///
718 /// **The one place the pin is enforced**, consulted by all three
719 /// roads that can meet [`Error::AllBackendsFailed`] — the two send
720 /// arms and the receive arm. It is one predicate rather than three
721 /// conditions because the pin is one promise: a session opened on
722 /// [`DecodePath::Hardware`] ends on hardware or ends in an error, and
723 /// a road that forgot to ask would break that promise silently,
724 /// which is the failure mode a caller cannot see.
725 ///
726 /// [`DecodePath::Software`] answers `true` and it costs nothing:
727 /// `DecodeState::Sw` is terminal, so no hardware exhaustion can
728 /// reach a road that asks. Answering for it by state rather than by
729 /// pin would make the predicate say something it does not mean.
730 #[cfg_attr(not(tarpaulin), inline(always))]
731 const fn may_open_software(&self) -> bool {
732 !matches!(self.path, DecodePath::Hardware(_))
733 }
734
735 /// Internal: **probe-era** transition from HW to SW. Replays the rescued
736 /// packets (the inner decoder's buffered history, already accepted by the HW
737 /// probe but not yet decoded) through the new SW decoder so the stream resumes
738 /// seamlessly. No frame was delivered on the HW path yet, so replaying the
739 /// history is lossless.
740 ///
741 /// Only the probe-era branches drive this. The **post-commit** path does
742 /// *not* — it retains and reconstructs zero frames, opening SW cold via
743 /// [`Self::degrade_to_sw`] and resyncing at the next keyframe instead of
744 /// replaying. (That is why this method's replay/drain machinery — and the
745 /// finding that the in-transaction drain doesn't cover later frame
746 /// *conversion* — cannot affect the post-commit path: it never produces a
747 /// post-commit replay frame to convert.)
748 ///
749 /// **Transactional**: drained replay frames accumulate in a local
750 /// queue; we only commit them to `self.sw_replay_frames` and switch
751 /// `self.state` to `Sw` after the replay (and EOF re-forwarding, if
752 /// needed) succeed. On failure, the SW decoder, the local frame
753 /// queue, and (where reachable) any consumed packets are dropped —
754 /// `self` is left in its prior state.
755 ///
756 /// **EOF-aware**: when EOF was already accepted on the HW path
757 /// (`self.eof_sent`), the new SW decoder also receives `send_eof()`
758 /// after replay. Without this, codecs that delay tail frames hang
759 /// forever in the drain phase.
760 ///
761 /// **EAGAIN-aware**: if SW's `send_packet` returns EAGAIN during
762 /// replay, drain produced frames into the local queue and retry.
763 ///
764 /// `eof_pending` is passed as a **local** argument rather than read from
765 /// `self.eof_sent`: callers must not mutate `self.eof_sent` before this
766 /// transaction commits (see [`VideoStreamDecoder::send_eof`]), so the
767 /// in-transaction SW EOF re-forward keys off the local flag and `self`'s
768 /// EOF state is updated only after a clean commit.
769 fn fall_back_to_sw(
770 &mut self,
771 unconsumed_packets: std::vec::Vec<ffmpeg_next::Packet>,
772 eof_pending: bool,
773 ) -> Result<(), Error> {
774 tracing::info!(
775 packets_replayed = unconsumed_packets.len(),
776 eof_pending,
777 "mediadecode-ffmpeg: HW probe exhausted, falling back to software decode",
778 );
779 // Wrap the internal worker so any failure path returns the
780 // rescued packets to the caller via `Error::FallbackFailed`.
781 // Without this, non-seekable streams (live feeds, pipes) would
782 // lose every compressed byte the HW path had consumed when a
783 // fallback transition fails partway.
784 match self.fall_back_to_sw_inner(&unconsumed_packets, eof_pending) {
785 Ok(()) => Ok(()),
786 Err(source) => Err(Error::FallbackFailed(FallbackFailed::new(
787 Box::new(source),
788 unconsumed_packets,
789 ))),
790 }
791 }
792
793 /// Worker for [`Self::fall_back_to_sw`]. Returns the rescued packets
794 /// untouched on the borrowed slice; the wrapper takes ownership of
795 /// them and surfaces them in `FallbackFailed` if this returns Err.
796 fn fall_back_to_sw_inner(
797 &mut self,
798 unconsumed_packets: &[ffmpeg_next::Packet],
799 eof_pending: bool,
800 ) -> Result<(), Error> {
801 let mut sw = open_sw_decoder(&self.parameters, self.limits)?;
802 // Bound before the decoder is mutably borrowed, so the error
803 // closures below can still consult it.
804 let sw_state = sw.state();
805 let mut local_replay: VecDeque<frame::Video> = VecDeque::new();
806 // Helper: drain SW into the local replay queue, capped at
807 // `SW_REPLAY_FRAME_CAP`.
808 //
809 // Error discipline: stop the drain **only** on the transient
810 // backpressure signals EAGAIN / EOF (the decoder has no more output for
811 // now). Every other `ffmpeg_next::Error` — e.g. `InvalidData` from a
812 // corrupt replayed packet — is a real decode failure and is propagated,
813 // so a non-recoverable error surfaces as `FallbackFailed` (carrying the
814 // replay packets) instead of being silently swallowed and the fallback
815 // committed over corruption.
816 fn drain_into(
817 sw: &mut ffmpeg_next::decoder::Video,
818 state: *const crate::ffi::CallbackState,
819 local_replay: &mut VecDeque<frame::Video>,
820 ) -> std::result::Result<(), Error> {
821 loop {
822 let mut tmp = alloc_av_video_frame()?;
823 match sw.receive_frame(&mut tmp) {
824 Ok(()) => {
825 if local_replay.len() >= SW_REPLAY_FRAME_CAP {
826 tracing::error!(
827 cap = SW_REPLAY_FRAME_CAP,
828 "mediadecode-ffmpeg: SW fallback replay produced more frames than the \
829 replay cap allows; aborting fallback (no frames dropped — they're \
830 still in the SW decoder's internal queue and will be released when \
831 it drops)",
832 );
833 return Err(Error::Ffmpeg(ffmpeg_next::Error::Other {
834 errno: libc::ENOMEM,
835 }));
836 }
837 local_replay.push_back(tmp);
838 }
839 // EAGAIN / EOF: no more output for now — stop draining, success.
840 Err(ffmpeg_next::Error::Other { errno }) if errno == ffmpeg_next::error::EAGAIN => {
841 break;
842 }
843 Err(ffmpeg_next::Error::Eof) => break,
844 // Any other error is a genuine decode failure on a replayed
845 // packet — surface it so it is not masked as a clean fallback.
846 Err(other) => return Err(crate::decoder::software_exit(state, other)),
847 }
848 }
849 Ok(())
850 }
851
852 for pkt in unconsumed_packets {
853 let mut attempts: u32 = 0;
854 loop {
855 match sw.send_packet(pkt) {
856 Ok(()) => break,
857 Err(ffmpeg_next::Error::Other { errno }) if errno == ffmpeg_next::error::EAGAIN => {
858 drain_into(&mut sw, sw_state, &mut local_replay)?;
859 attempts += 1;
860 if attempts > 16 {
861 return Err(Error::Ffmpeg(ffmpeg_next::Error::Other {
862 errno: ffmpeg_next::error::EAGAIN,
863 }));
864 }
865 }
866 Err(other) => return Err(crate::decoder::software_exit(sw_state, other)),
867 }
868 }
869 }
870 // Re-forward EOF if the HW path already saw it. SW EOF can also
871 // return EAGAIN until prior output is drained — mirror the
872 // packet-replay loop.
873 if eof_pending {
874 let mut attempts: u32 = 0;
875 loop {
876 match sw.send_eof() {
877 Ok(()) => break,
878 Err(ffmpeg_next::Error::Other { errno }) if errno == ffmpeg_next::error::EAGAIN => {
879 drain_into(&mut sw, sw_state, &mut local_replay)?;
880 attempts += 1;
881 if attempts > 16 {
882 return Err(Error::Ffmpeg(ffmpeg_next::Error::Other {
883 errno: ffmpeg_next::error::EAGAIN,
884 }));
885 }
886 }
887 Err(other) => return Err(crate::decoder::software_exit(sw_state, other)),
888 }
889 }
890 }
891 // Final drain BEFORE commit — the transactional commit boundary. The
892 // EAGAIN-triggered drains above only fire when SW exerts backpressure mid
893 // replay; a SW decoder that ACCEPTS every replayed packet (and the EOF)
894 // without one then surfaces a non-transient error — `InvalidData` from a
895 // corrupt replayed packet, or any other decode failure — only on the *next*
896 // `receive_frame`. Without this drain that error would land after the
897 // commit (frames appended, `state` flipped to `Sw`, rescued packets
898 // dropped) and reach the caller as a plain decode failure, not
899 // `FallbackFailed` — breaking probe-era recovery on non-seekable input.
900 // Draining to EAGAIN/EOF here forces any such error to surface now, so it is
901 // wrapped as `FallbackFailed` (retaining the rescued packets) and the
902 // decoder stays on HW — nothing is committed. (Only the probe-era path
903 // reaches this; the post-commit path degrades via `degrade_to_sw` and never
904 // replays, so it has no drained frames to commit or convert.)
905 drain_into(&mut sw, sw_state, &mut local_replay)?;
906 // Commit: only after replay, any EOF forwarding, AND the final drain
907 // succeeded do we move the new SW decoder and queue into `self`.
908 self.sw_replay_frames.append(&mut local_replay);
909 self.state = DecodeState::Sw(sw);
910 Ok(())
911 }
912
913 /// **Post-commit** degrade-and-continue transition: open the SW decoder
914 /// **cold** and forward only the failure-arm's input, retaining and
915 /// reconstructing **zero** frames. This is the whole post-commit path: open
916 /// SW, forward the current packet (or EOF), degrade-track — nothing is drained
917 /// into `sw_replay_frames`, so there is no replayed frame to convert later and
918 /// no terminal-drain transaction to reason about. SW naturally produces no
919 /// frame until the next keyframe arrives across the gap, then decodes normally;
920 /// the failure-point→next-keyframe span is the accepted, logged drop.
921 ///
922 /// **Transactional (SW-open only)**: `self.state` flips to `Sw` *only after*
923 /// `open_sw_decoder` and the input forward succeed. On any failure the new SW
924 /// decoder is dropped and the decoder is left on its prior HW state, the error
925 /// surfaced as [`Error::FallbackFailed`] (with an empty rescue set — a
926 /// post-commit failure never carries unconsumed packets). With no replay-frame
927 /// retention there is nothing else to roll back.
928 ///
929 /// On a clean commit it enters degraded-resync mode (see
930 /// [`Self::enter_degraded_resync`]); if the forwarded current packet is itself
931 /// a keyframe, the resync anchor is recorded immediately
932 /// ([`Self::note_degraded_keyframe`]).
933 ///
934 /// # `eof_pending`
935 ///
936 /// Whether the session's end-of-stream has already been **committed**,
937 /// and so must be re-forwarded into the cold decoder. Carried as a
938 /// local argument for the same two reasons the probe-era road carries
939 /// it (see [`Self::fall_back_to_sw`]): it is read from `eof_sent`
940 /// before anything is mutated, so a fallback that fails leaves no
941 /// half-truth behind — and one question deserves one mechanism on
942 /// both fallback roads.
943 ///
944 /// It is **not** expressed by selecting [`PostCommitInput::Eof`],
945 /// even though that arm forwards the same call. That enum is named by
946 /// the *failure arm* — which road raised the exhaustion — and the
947 /// `warn!` each site emits says so; borrowing the EOF arm for a
948 /// frame-time failure would make it lie about where the failure came
949 /// from.
950 fn degrade_to_sw(&mut self, input: PostCommitInput<'_>, eof_pending: bool) -> Result<(), Error> {
951 match self.degrade_to_sw_inner(input, eof_pending) {
952 Ok(()) => Ok(()),
953 // **A budget refusal is not a fallback failure.** It travels
954 // unwrapped, and the spelling was chosen rather than inherited:
955 //
956 // * `FallbackFailed` means the fallback *machinery* could not
957 // complete, and its contract is to hand back the unconsumed
958 // packets so a caller can re-drive them. On this road that set
959 // is empty by construction — the probe buffer is gone and no
960 // replay frames are retained — so the envelope carries no
961 // recovery affordance at all, only a label.
962 // * And the label is the wrong one. Re-driving is the natural
963 // response to a fallback failure, and re-driving a budget
964 // refusal under the same limits refuses identically. Naming it
965 // a fallback failure invites an action that cannot succeed,
966 // while `FrameBudgetExceeded` names the one that can: raise
967 // the ceiling, or accept the refusal.
968 //
969 // So it keeps the same spelling here as on every other road. One
970 // fact, one name.
971 Err(budget @ Error::FrameBudgetExceeded(_)) => Err(budget),
972 // Everything else really is the machinery failing, and keeps the
973 // envelope — empty rescue set and all, which is what a
974 // post-commit failure has to hand back.
975 Err(source) => Err(Error::FallbackFailed(FallbackFailed::new(
976 Box::new(source),
977 std::vec::Vec::new(),
978 ))),
979 }
980 }
981
982 /// Worker for [`Self::degrade_to_sw`]. Opens SW cold, forwards the arm's input,
983 /// and on success commits + enters degraded-resync mode. Returns `Err` (and
984 /// commits nothing) if SW cannot open or the forward fails.
985 fn degrade_to_sw_inner(
986 &mut self,
987 input: PostCommitInput<'_>,
988 eof_pending: bool,
989 ) -> Result<(), Error> {
990 // The invariant [`PostCommitInput`] documents, stated where it can
991 // be checked: a current packet and an end-of-stream are never
992 // forwarded together. The send road cannot violate it — its own
993 // gate refuses every packet once `eof_sent` is committed — so this
994 // records the coupling rather than defending against it.
995 debug_assert!(
996 !(matches!(input, PostCommitInput::Packet(_)) && eof_pending),
997 "a current packet and a committed EOF must never be forwarded together",
998 );
999 let mut sw = open_sw_decoder(&self.parameters, self.limits)?;
1000 // Captured before the decoder is borrowed for the forward, and
1001 // before it can be dropped on the error road: this temporary
1002 // decoder owns the callback state, so a `judge_buffer` refusal
1003 // recorded during either forward below dies with it unless the
1004 // reason is collected here. That was the last software road still
1005 // wrapping libavcodec's `EINVAL` raw.
1006 let state = sw.state();
1007 let mut forwarded_keyframe = false;
1008 let mut forwarded_packet = false;
1009 match input {
1010 PostCommitInput::Packet(pkt) => {
1011 // The HW decoder REFUSED this packet, so it was never decoded; forward
1012 // it to the cold SW. A failure here surfaces (it is not silently
1013 // dropped) and rolls back to HW.
1014 sw.send_packet(pkt)
1015 .map_err(|e| crate::decoder::software_exit(state, e))?;
1016 forwarded_keyframe = pkt.is_key();
1017 forwarded_packet = true;
1018 }
1019 // Neither of these forwards a packet; the end-of-stream below is
1020 // the only thing they can hand the cold decoder.
1021 PostCommitInput::FrameTime | PostCommitInput::Eof => {}
1022 }
1023 // **The end of the stream is re-forwarded here, on every arm that
1024 // has one, and that is the fix rather than an extra.**
1025 //
1026 // The cold decoder knows nothing: it was opened a moment ago, from
1027 // codec parameters alone. If the session had already been told the
1028 // stream ended and this new decoder is not, it answers `EAGAIN` to
1029 // every drain — which reaches the caller as
1030 // [`Received::NeedsInput`], an instruction to send another packet.
1031 // On a session whose end is committed there is no legal way to obey
1032 // that: both send gates refuse. The caller loops, or quietly
1033 // accepts a truncated tail, until `flush`.
1034 //
1035 // It used to be reachable only through the `Eof` failure arm, so
1036 // the frame-time road — a post-commit exhaustion raised *while
1037 // draining*, after EOF was accepted — opened cold and stayed cold.
1038 // A cold decoder has no buffered output, so this cannot answer
1039 // `EAGAIN` itself.
1040 if eof_pending {
1041 sw.send_eof()
1042 .map_err(|e| crate::decoder::software_exit(state, e))?;
1043 }
1044 // Commit: only after a clean open + forward.
1045 self.state = DecodeState::Sw(sw);
1046 self.enter_degraded_resync();
1047 if forwarded_keyframe {
1048 // The refused current packet was itself the resync anchor.
1049 self.note_degraded_keyframe(true);
1050 }
1051 if forwarded_packet {
1052 self.count_degraded_packet();
1053 }
1054 Ok(())
1055 }
1056
1057 /// Enter post-commit degraded mode after a post-commit fallback commits: the
1058 /// SW decoder opened cold and the span up to the next keyframe is being
1059 /// dropped. We hold this mode until SW proves a *keyframe-anchored* resync
1060 /// (a delivered frame after a keyframe was fed — see
1061 /// [`Self::note_degraded_keyframe`] / [`Self::resync_on_frame`]) and the EOF
1062 /// escalation in [`VideoStreamDecoder::receive_frame`]. Called only on the
1063 /// post-commit path, only after a clean commit. Resets the keyframe-seen anchor
1064 /// and the gap counter.
1065 #[inline]
1066 fn enter_degraded_resync(&mut self) {
1067 self.degraded_resync_pending = true;
1068 self.degraded_keyframe_seen = false;
1069 self.degraded_packets_since_fallback = 0;
1070 }
1071
1072 /// Record that a packet fed to the SW decoder across an unresolved post-commit
1073 /// gap was a **keyframe** — the resync anchor. Only a frame delivered *after*
1074 /// this clears the pending flag, so a lenient codec's concealed P-frame can't
1075 /// masquerade as a resync. A no-op outside degraded mode, or for a
1076 /// non-keyframe.
1077 #[inline]
1078 fn note_degraded_keyframe(&mut self, is_key: bool) {
1079 if self.degraded_resync_pending && is_key {
1080 self.degraded_keyframe_seen = true;
1081 }
1082 }
1083
1084 /// Count one packet fed to the SW decoder while a post-commit resync is still
1085 /// unproven, so the EOF escalation can quantify the lost tail. A no-op once
1086 /// SW has resynced (the flag is clear).
1087 #[inline]
1088 fn count_degraded_packet(&mut self) {
1089 if self.degraded_resync_pending {
1090 self.degraded_packets_since_fallback = self.degraded_packets_since_fallback.saturating_add(1);
1091 }
1092 }
1093
1094 /// A SW frame was delivered. Clear post-commit degraded mode **only if** a
1095 /// keyframe was fed across the gap ([`Self::degraded_keyframe_seen`]) — that is
1096 /// a real keyframe-anchored resync, so the dropped span is now the promised
1097 /// *bounded* gap. A frame delivered with no keyframe yet (a concealed P-frame
1098 /// from the dropped span) leaves the guard set, so the one-GOP bound stays
1099 /// enforced and the EOF escalation still fires if no keyframe ever arrives.
1100 /// Idempotent; a no-op outside degraded mode (steady state, probe-era replay).
1101 #[inline]
1102 fn resync_on_frame(&mut self) {
1103 if self.degraded_resync_pending && self.degraded_keyframe_seen {
1104 self.clear_degraded_resync();
1105 }
1106 }
1107
1108 /// Unconditionally reset post-commit degraded-mode state. Used where the gap
1109 /// is moot regardless of resync proof: a `flush` (seek/reset re-anchors the
1110 /// stream) and the cleanup after an EOF escalation has already fired (so a
1111 /// follow-up poll sees plain EOF, not a repeated escalation). The
1112 /// frame-delivery path uses the keyframe-gated [`Self::resync_on_frame`]
1113 /// instead.
1114 #[inline]
1115 fn clear_degraded_resync(&mut self) {
1116 self.degraded_resync_pending = false;
1117 self.degraded_keyframe_seen = false;
1118 self.degraded_packets_since_fallback = 0;
1119 }
1120
1121 /// The one place a delivered frame is committed.
1122 ///
1123 /// Every road that hands a frame to the caller passes through here —
1124 /// the hardware scratch, the software scratch, both replay-queue
1125 /// entries, and the retry of a parked frame — so the bookkeeping a
1126 /// delivery owes cannot be attached to some of them and forgotten on
1127 /// others. It was: a parked software frame delivered on the retry
1128 /// road skipped [`Self::resync_on_frame`], so the last recovered
1129 /// frame of a degraded stream could leave the resync guard standing
1130 /// and turn a clean EOF into a false
1131 /// [`PostCommitNeverResynced`].
1132 fn commit_delivery(
1133 &mut self,
1134 frame: VideoFrame<mediadecode::PixelFormat, VideoFrameExtra, C::Buffer>,
1135 dst: &mut VideoFrame<mediadecode::PixelFormat, VideoFrameExtra, C::Buffer>,
1136 ) {
1137 // The seat is free once a carrier exists for what it held.
1138 self.scratch_pending = false;
1139 // A delivered frame is what clears a keyframe-anchored resync. A
1140 // no-op on every road that never entered degraded mode, which is
1141 // why it can be unconditional here.
1142 self.resync_on_frame();
1143 *dst = frame;
1144 }
1145
1146 /// Where this session is. See
1147 /// [`SessionPhase`](crate::decoder::SessionPhase).
1148 ///
1149 /// The wrapper never sees a probe — that lives inside the hardware
1150 /// seam, which derives its own — so only the committed pair is
1151 /// reachable from here.
1152 const fn phase(&self) -> crate::decoder::SessionPhase {
1153 if self.eof_sent {
1154 crate::decoder::SessionPhase::Draining
1155 } else {
1156 crate::decoder::SessionPhase::Streaming
1157 }
1158 }
1159
1160 /// Reads a drain answer against the session's own committed end.
1161 ///
1162 /// Routes a settled end through the post-commit gap check.
1163 ///
1164 /// **The `NeedsInput`-past-the-end reading moved out of here.** It
1165 /// used to be this method's own comparison against `eof_sent` — one
1166 /// more road deriving the session's phase for itself, which is the
1167 /// habit [`SessionPhase`](crate::decoder::SessionPhase) ended. The
1168 /// classifier makes that reading now, for every road at once, and
1169 /// what is left here is the part that is genuinely this wrapper's:
1170 /// an end is not clean if a post-commit gap never closed.
1171 fn settle(&mut self, status: Received) -> Result<Received, VideoDecodeError> {
1172 match status {
1173 Received::Ended => self.ended(),
1174 other => Ok(other),
1175 }
1176 }
1177
1178 /// The end of the stream, read against a post-commit gap that never
1179 /// closed.
1180 ///
1181 /// One place, because there are now two spellings that reach it — the
1182 /// substrate's `AVERROR_EOF` and a settled [`Received::NeedsInput`]
1183 /// past a committed end — and a lost tail must escalate on both. The
1184 /// flag is cleared as it fires so a caller draining to the end sees
1185 /// the escalation once and the plain end afterwards.
1186 fn ended(&mut self) -> Result<Received, VideoDecodeError> {
1187 if !self.degraded_resync_pending {
1188 return Ok(Received::Ended);
1189 }
1190 let packets_lost = self.degraded_packets_since_fallback;
1191 tracing::error!(
1192 packets_lost,
1193 "mediadecode-ffmpeg: post-commit HW->SW fallback never resynced before EOF — \
1194 {packets_lost} packets fed to the software decoder produced no frame (no \
1195 keyframe found across the gap); the stream tail from the fallback point was \
1196 lost",
1197 );
1198 self.clear_degraded_resync();
1199 Err(VideoDecodeError::PostCommitNeverResynced(
1200 PostCommitNeverResynced::new(packets_lost),
1201 ))
1202 }
1203
1204 /// Internal: convert the active scratch frame into a
1205 /// `mediadecode::VideoFrame` and write into `dst`.
1206 fn deliver_frame(
1207 &mut self,
1208 dst: &mut VideoFrame<mediadecode::PixelFormat, VideoFrameExtra, C::Buffer>,
1209 ) -> Result<Received, VideoDecodeError> {
1210 let av_frame = match &mut self.state {
1211 DecodeState::Hw(_) => unsafe { self.hw_scratch.as_inner_mut().as_ptr() },
1212 DecodeState::Sw(_) => unsafe { self.sw_scratch.as_ptr() },
1213 };
1214 // SAFETY: the scratch frame is live — either just filled by the
1215 // inner decoder's `receive_frame`, or left holding a frame whose
1216 // conversion did not commit. Convert takes what it needs out of it,
1217 // so the scratch can be reused once this has committed.
1218 let converted = unsafe {
1219 convert::av_frame_to_video_frame_as::<C>(av_frame, self.time_base, self.limits.frame())
1220 };
1221 match converted {
1222 Ok(new_frame) => {
1223 self.commit_delivery(new_frame, dst);
1224 Ok(Received::Frame)
1225 }
1226 Err(e) => {
1227 // Park only what another attempt could survive.
1228 self.scratch_pending = e.parks_in_decode();
1229 Err(VideoDecodeError::Convert(e))
1230 }
1231 }
1232 }
1233}
1234
1235#[cfg(test)]
1236impl<C: crate::FfmpegCarrier + crate::CarrierOps> CarrierVideoStreamDecoder<C> {
1237 /// Build a decoder around an injected HW seam, bypassing the real probe.
1238 /// Lets tests drive the post-commit fallback path with a [`HwInner`] fake
1239 /// instead of a live GPU. The SW fallback still opens the **real**
1240 /// `ffmpeg::decoder::Video` from `parameters`, so a fallback in these tests
1241 /// genuinely decodes.
1242 pub(crate) fn from_hw_inner_for_test(
1243 hw: Box<dyn HwInner>,
1244 parameters: Parameters,
1245 time_base: Timebase,
1246 ) -> Result<Self, Error> {
1247 Self::from_hw_inner_for_test_as(hw, parameters, time_base, DecodePath::Auto)
1248 }
1249
1250 /// [`Self::from_hw_inner_for_test`], with the session's
1251 /// [`DecodePath`] named.
1252 ///
1253 /// The seam a **pinned** session's mid-stream behaviour is driven
1254 /// through: a pin's promise is about what happens when the hardware
1255 /// fails after opening, and the only way to reach that on a machine
1256 /// whose GPU works is to inject a seam that fails on demand. See
1257 /// `a_hardware_pin_reports_a_mid_stream_exhaustion_instead_of_degrading`.
1258 pub(crate) fn from_hw_inner_for_test_as(
1259 hw: Box<dyn HwInner>,
1260 parameters: Parameters,
1261 time_base: Timebase,
1262 path: DecodePath,
1263 ) -> Result<Self, Error> {
1264 let limits = DecoderLimits::default();
1265 let owned_parameters = try_clone_parameters(¶meters, limits.max_codec_parameter_bytes())?;
1266 Ok(Self {
1267 state: DecodeState::Hw(hw),
1268 path,
1269 parameters: owned_parameters,
1270 hw_scratch: Frame::empty()?,
1271 sw_scratch: alloc_av_video_frame()?,
1272 sw_replay_frames: VecDeque::new(),
1273 eof_sent: false,
1274 degraded_resync_pending: false,
1275 degraded_keyframe_seen: false,
1276 degraded_packets_since_fallback: 0,
1277 time_base,
1278 limits,
1279 scratch_pending: false,
1280 _carrier: core::marker::PhantomData,
1281 })
1282 }
1283
1284 /// Whether `send_eof` has been committed on the active decoder. Lets the
1285 /// rollback tests assert that a failed EOF fallback restores (never
1286 /// half-mutates) `eof_sent`.
1287 pub(crate) const fn eof_sent_for_test(&self) -> bool {
1288 self.eof_sent
1289 }
1290
1291 /// Whether a post-commit fallback is awaiting a keyframe-anchored resync.
1292 /// Lets the escalation tests observe the degraded-resync state machine.
1293 pub(crate) const fn degraded_resync_pending_for_test(&self) -> bool {
1294 self.degraded_resync_pending
1295 }
1296
1297 /// Whether a keyframe has been fed to the SW decoder across the unresolved
1298 /// post-commit gap (the resync anchor). Lets the keyframe-gating test confirm
1299 /// a concealed P-frame does not set it (so the resync clear stays blocked).
1300 pub(crate) const fn degraded_keyframe_seen_for_test(&self) -> bool {
1301 self.degraded_keyframe_seen
1302 }
1303
1304 /// Whether the post-commit path retained any replay frames — must always be
1305 /// empty for a post-commit fallback (it retains zero). Lets the finding-1
1306 /// dissolution test assert no replay frame was ever queued.
1307 pub(crate) fn sw_replay_frames_is_empty_for_test(&self) -> bool {
1308 self.sw_replay_frames.is_empty()
1309 }
1310
1311 /// Packets fed to SW across an unresolved post-commit resync gap. Lets the
1312 /// counter test confirm packets crossing the gap from the `send_packet` arm
1313 /// are tallied (and cleared on resync).
1314 pub(crate) const fn degraded_packets_since_fallback_for_test(&self) -> u64 {
1315 self.degraded_packets_since_fallback
1316 }
1317}
1318
1319impl<C: crate::FfmpegCarrier + crate::CarrierOps> CarrierVideoStreamDecoder<C> {
1320 /// The fault a submission after end-of-stream earns on this face.
1321 ///
1322 /// **Censused from the empty-seat road rather than invented.** With
1323 /// the seat free, a post-EOF `send_packet` or a repeated `send_eof`
1324 /// reaches libavcodec, which answers `AVERROR_EOF`, and all four
1325 /// roads through this wrapper — hardware and software, packet and
1326 /// EOF — surface it as exactly this value. The gates below short
1327 /// out to the same one so a parked seat cannot change *which* answer
1328 /// a caller gets, only how quickly. `the_post_eof_fault_is_the_one_the_substrate_gives`
1329 /// pins the two against each other.
1330 ///
1331 /// Deliberately **not** a new `VideoDecodeError` arm. The subtitle
1332 /// seam had to mint `AfterEof` because `avcodec_decode_subtitle2` has
1333 /// no state machine to refuse for it; this face already has an answer
1334 /// for the condition, and a second spelling for one fault on one
1335 /// surface is the disease this release is curing.
1336 fn after_eof() -> VideoDecodeError {
1337 VideoDecodeError::Decode(Error::Ffmpeg(ffmpeg_next::Error::Eof))
1338 }
1339
1340 pub(crate) fn send_packet_impl(
1341 &mut self,
1342 packet: &VideoPacket<VideoPacketExtra, C::Buffer>,
1343 ) -> Result<Sent, VideoDecodeError> {
1344 // **The end of the stream outranks the parked seat, and the order
1345 // is the whole point.**
1346 //
1347 // `Sent::MustDrain` is a promise: drain the output and this same
1348 // offer becomes acceptable. Past end-of-stream that promise is
1349 // false — draining empties the seat and the retry still faults,
1350 // until `flush`. Checking the seat first made the wrapper answer
1351 // `MustDrain` for a submission nothing could ever accept, which is
1352 // the same fault-under-back-pressure inversion the subtitle seam
1353 // carried: a caller obeying the contract loops, drains, re-offers,
1354 // and is refused anyway.
1355 //
1356 // It is reachable: `send_eof` is accepted and sets `eof_sent`, a
1357 // delayed tail frame comes out of the decoder, its carrier
1358 // allocation fails parkably, and the seat is taken on a session
1359 // that is already over.
1360 if !self.phase().accepts_input() {
1361 return Err(Self::after_eof());
1362 }
1363 // **Nothing is sent while a frame is parked.** Both send roads can
1364 // commit a hardware-to-software fallback, and a fallback under a
1365 // parked frame would leave the retry reading the other scratch. See
1366 // [`Self::scratch_pending`]. Nothing was consumed, so this is back
1367 // pressure and the packet is still the caller's to re-offer — which
1368 // is true precisely because the stream is not over, checked above.
1369 if self.scratch_pending {
1370 return Ok(Sent::MustDrain);
1371 }
1372 let phase = self.phase();
1373 // Scoped submission: the rebuilt `AVPacket` never leaves this call,
1374 // which is what lets the view lane share its buffer with libavcodec
1375 // rather than copy into it. See `boundary::with_ffmpeg_video_packet`.
1376 let limits = self.limits.packet_limits();
1377 // **The route depends on what this decoder does with what it is
1378 // sent.** While the hardware probe is open it `av_packet_ref`s
1379 // every accepted packet into a rescue history, and
1380 // `AllBackendsFailed::into_unconsumed_packets` hands those out as
1381 // owned, mutable `Packet`s — so a shared body would escape this
1382 // call as a live mutable alias of a carrier the caller may still be
1383 // reading. Inside that window the body is copied; once the probe
1384 // has committed, nothing is recorded and the send is zero-copy
1385 // again. The software road never records.
1386 let route = match &self.state {
1387 DecodeState::Hw(hw) if hw.records_submissions() => crate::carrier::BodyRoute::Copy,
1388 _ => crate::carrier::BodyRoute::Submission,
1389 };
1390 boundary::with_ffmpeg_video_packet::<C, _>(packet, limits, route, |av_pkt| {
1391 match &mut self.state {
1392 DecodeState::Hw(hw) => match hw.send_packet(av_pkt) {
1393 // The seam already classified libavcodec's back pressure, so
1394 // both states travel on unchanged.
1395 Ok(status) => Ok(status),
1396 Err(Error::AllBackendsFailed(p)) => {
1397 // **A pinned hardware session reports rather than degrades.**
1398 // See [`Self::may_open_software`]: this is the exhaustion
1399 // `DecodePath::Auto` reads as its cue to open software, and
1400 // the pin's whole content is that it is not that cue here.
1401 // Reported with the payload intact, so the caller keeps the
1402 // backend, its error, and any rescued packets.
1403 if !self.may_open_software() {
1404 return Err(VideoDecodeError::Decode(Error::AllBackendsFailed(p)));
1405 }
1406 // Route on the EXPLICIT origin, never on whether `rescued` is empty (a
1407 // probe-era first-packet cap trip is *also* empty).
1408 if p.origin().is_post_commit() {
1409 // Post-commit: DEGRADE AND CONTINUE. No lossless mid-stream
1410 // reconstruction — the SW decoder opens cold, retains zero replay
1411 // frames, and resyncs at the next keyframe. The current packet (the
1412 // one HW REFUSED) is forwarded to that cold SW: if it is the resync
1413 // keyframe SW decodes from it, otherwise SW drops it until a keyframe
1414 // arrives. The bounded span from here to that keyframe is dropped — a
1415 // loudly logged gap (see the `warn!`), not a silent one.
1416 tracing::warn!(
1417 backend = ?p.attempts().last().map(|(b, _)| *b),
1418 pts = ?av_pkt.pts(),
1419 "mediadecode-ffmpeg: HW decode failed post-commit; falling back to \
1420 software, resyncing at next keyframe — a bounded span of frames \
1421 may be dropped at this boundary",
1422 );
1423 // Transactional SW-open + current-packet forward; degrade-tracking
1424 // (incl. keyframe-anchor recording) happens inside on a clean commit.
1425 // A failure surfaces `FallbackFailed` and stays on HW.
1426 // A clean degrade forwarded this very packet into the
1427 // cold software decoder, so it was consumed.
1428 // `false`: this road is unreachable once the end is
1429 // committed — `send_packet_impl`'s first gate refuses
1430 // every packet past `eof_sent` — so there is no EOF to
1431 // re-forward, and forwarding one alongside a packet is
1432 // the pairing [`PostCommitInput`] forbids.
1433 return self
1434 .degrade_to_sw(PostCommitInput::Packet(av_pkt), false)
1435 .map(|()| Sent::Accepted)
1436 .map_err(VideoDecodeError::Decode);
1437 }
1438 // Probe-era: replay the inner decoder's buffered history (lossless —
1439 // no frame was delivered yet), then forward the still-unconsumed
1440 // current packet to SW.
1441 let rescued = p.into_unconsumed_packets();
1442 // `eof_pending` is the committed EOF state — never pre-mutated here.
1443 let eof_pending = self.eof_sent;
1444 self
1445 .fall_back_to_sw(rescued, eof_pending)
1446 .map_err(VideoDecodeError::Decode)?;
1447 // Forward the new (still-unconsumed) current packet to the
1448 // freshly-opened SW decoder — the HW decoder REFUSED it, so it was not
1449 // in the replay set. A failure here surfaces (it is not silently
1450 // dropped), and back pressure from the fresh decoder is reported as
1451 // such rather than mistaken for one: the fallback committed either
1452 // way, and the caller re-offers the packet.
1453 if let DecodeState::Sw(sw) = &mut self.state {
1454 let st = sw.state();
1455 if let Err(e) = sw.send_packet(av_pkt) {
1456 return crate::decoder::software_send(st, e, phase)
1457 .map_err(VideoDecodeError::Decode);
1458 }
1459 }
1460 Ok(Sent::Accepted)
1461 }
1462 Err(other) => Err(VideoDecodeError::Decode(other)),
1463 },
1464 DecodeState::Sw(sw) => {
1465 let st = sw.state();
1466 if let Err(e) = sw.send_packet(av_pkt) {
1467 // Funnel, then gate. **Nothing below runs on back pressure**,
1468 // which is the point of returning here rather than falling
1469 // through: a packet libavcodec did not take must not be
1470 // counted across the resync gap or recorded as a keyframe
1471 // anchor, or a caller's honest re-offer would double-count
1472 // it.
1473 return crate::decoder::software_send(st, e, phase).map_err(VideoDecodeError::Decode);
1474 }
1475 // A keyframe fed across an unresolved post-commit gap is the resync
1476 // anchor; record it so the next delivered frame can clear the guard.
1477 self.note_degraded_keyframe(av_pkt.is_key());
1478 // Count packets crossing an unresolved post-commit resync gap so the
1479 // escalation at EOF can report how much tail was lost.
1480 self.count_degraded_packet();
1481 Ok(Sent::Accepted)
1482 }
1483 }
1484 })
1485 .map_err(|e| VideoDecodeError::Decode(Error::PacketBuild(e)))?
1486 }
1487
1488 pub(crate) fn receive_frame_impl(
1489 &mut self,
1490 dst: &mut VideoFrame<mediadecode::PixelFormat, VideoFrameExtra, C::Buffer>,
1491 ) -> Result<Received, VideoDecodeError> {
1492 // Deliver any frames produced during SW fallback replay before
1493 // pulling new ones from the SW decoder. This is the queue
1494 // populated by `fall_back_to_sw` when SW returned EAGAIN during
1495 // packet replay — a **probe-era** path only (the post-commit path retains
1496 // no replay frames), so `resync_on_frame` here is a no-op (probe-era never
1497 // enters degraded mode).
1498 // **Peeked, not popped.** A replayed frame is the rescue history's
1499 // only copy: popping it before the conversion committed lost it to
1500 // any allocation failure, which is the one thing this queue exists
1501 // to prevent. It leaves the queue when a carrier exists for it.
1502 if let Some(replayed) = self.sw_replay_frames.front() {
1503 // SAFETY: `replayed` is a live AVFrame owned by this queue;
1504 // convert takes what it needs out of it.
1505 let converted = unsafe {
1506 convert::av_frame_to_video_frame_as::<C>(
1507 replayed.as_ptr(),
1508 self.time_base,
1509 self.limits.frame(),
1510 )
1511 };
1512 let new_frame = match converted {
1513 Ok(new_frame) => new_frame,
1514 Err(e) if e.parks_in_decode() => return Err(VideoDecodeError::Convert(e)),
1515 // A frame nothing can carry is dropped rather than re-offered
1516 // forever — the same rule the scratch seat follows.
1517 Err(e) => {
1518 self.sw_replay_frames.pop_front();
1519 return Err(VideoDecodeError::Convert(e));
1520 }
1521 };
1522 self.sw_replay_frames.pop_front();
1523 self.commit_delivery(new_frame, dst);
1524 return Ok(Received::Frame);
1525 }
1526 // A frame whose conversion did not commit is converted again before
1527 // the decoder is asked for another — see [`Self::scratch_pending`].
1528 // The scratch still holds it, and `deliver_frame` reads whichever
1529 // scratch the current state uses.
1530 if self.scratch_pending {
1531 return self.deliver_frame(dst);
1532 }
1533 let phase = self.phase();
1534 loop {
1535 match &mut self.state {
1536 DecodeState::Hw(hw) => match hw.receive_frame(&mut self.hw_scratch) {
1537 Ok(Received::Frame) => {
1538 // The frame is out of the decoder's queue from here; the
1539 // seat is what keeps it if the conversion cannot commit.
1540 self.scratch_pending = true;
1541 return self.deliver_frame(dst);
1542 }
1543 // The hardware seam already classified the two flow signals.
1544 // They still pass the session's own end: see [`Self::settle`].
1545 Ok(status) => return self.settle(status),
1546 Err(Error::AllBackendsFailed(p)) => {
1547 // The pin, on the receive road — see
1548 // [`Self::may_open_software`] and the identical gate on the
1549 // two send roads.
1550 if !self.may_open_software() {
1551 return Err(VideoDecodeError::Decode(Error::AllBackendsFailed(p)));
1552 }
1553 // HW exhausted at frame-time. There is no current packet here.
1554 // Route on the explicit origin.
1555 if p.origin().is_post_commit() {
1556 // Post-commit: DEGRADE AND CONTINUE — open SW cold (no current
1557 // packet to forward, no replay frames retained) and resync at the
1558 // next keyframe, dropping the bounded span up to it. Loud single
1559 // `warn!` marks that accepted gap. A clean commit enters degraded
1560 // mode; a SW-open failure surfaces `FallbackFailed` and stays HW.
1561 tracing::warn!(
1562 backend = ?p.attempts().last().map(|(b, _)| *b),
1563 "mediadecode-ffmpeg: HW decode failed post-commit at frame-time; \
1564 falling back to software, resyncing at next keyframe — a bounded \
1565 span of frames may be dropped at this boundary",
1566 );
1567 // **The committed end travels with the fallback.** Read
1568 // before anything mutates, exactly as the probe-era road
1569 // below reads it. Without it the cold decoder answers
1570 // `EAGAIN` forever on a session no send can feed.
1571 let eof_pending = self.eof_sent;
1572 self
1573 .degrade_to_sw(PostCommitInput::FrameTime, eof_pending)
1574 .map_err(VideoDecodeError::Decode)?;
1575 // Nothing to deliver yet — fall through to the loop; the next
1576 // iteration takes the Sw arm and pulls from the cold SW decoder.
1577 continue;
1578 }
1579 // Probe-era: replay the buffered history (lossless).
1580 let rescued = p.into_unconsumed_packets();
1581 // `eof_pending` is the committed EOF state — never pre-mutated here.
1582 let eof_pending = self.eof_sent;
1583 self
1584 .fall_back_to_sw(rescued, eof_pending)
1585 .map_err(VideoDecodeError::Decode)?;
1586 // If the replay produced any drained frames, return one
1587 // immediately — preserves stream order vs. whatever the
1588 // SW decoder will produce next.
1589 // **Peeked, not popped** — the second delivery path onto
1590 // this queue, and it owes the same discipline as the first
1591 // (see the head of `receive_frame_impl`). The replay queue
1592 // is the rescue history's only copy of these frames, so a
1593 // conversion that cannot commit must leave the head where
1594 // it is rather than advance past it.
1595 if let Some(replayed) = self.sw_replay_frames.front() {
1596 // SAFETY: `replayed` is a live AVFrame owned by this
1597 // queue; convert takes what it needs out of it.
1598 let converted = unsafe {
1599 convert::av_frame_to_video_frame_as::<C>(
1600 replayed.as_ptr(),
1601 self.time_base,
1602 self.limits.frame(),
1603 )
1604 };
1605 let new_frame = match converted {
1606 Ok(new_frame) => new_frame,
1607 Err(e) if e.parks_in_decode() => return Err(VideoDecodeError::Convert(e)),
1608 // A frame nothing can carry is dropped rather than
1609 // re-offered forever.
1610 Err(e) => {
1611 self.sw_replay_frames.pop_front();
1612 return Err(VideoDecodeError::Convert(e));
1613 }
1614 };
1615 self.sw_replay_frames.pop_front();
1616 self.commit_delivery(new_frame, dst);
1617 return Ok(Received::Frame);
1618 }
1619 // Fall through to the loop; next iteration takes the Sw arm.
1620 }
1621 Err(other) => return Err(VideoDecodeError::Decode(other)),
1622 },
1623 DecodeState::Sw(sw) => {
1624 // Convert inline (rather than via `deliver_frame`, which borrows all
1625 // of `self`) so only the disjoint fields `sw_scratch` / `time_base`
1626 // are touched alongside the `self.state` borrow `sw` holds.
1627 let st = sw.state();
1628 match sw.receive_frame(&mut self.sw_scratch) {
1629 Ok(()) => {
1630 // The frame is out of the decoder's queue from here; the
1631 // seat is what keeps it if the conversion cannot commit.
1632 self.scratch_pending = true;
1633 // SAFETY: the scratch frame is live (just filled by
1634 // `receive_frame`); convert takes what it needs out of
1635 // it, so the scratch can be reused once this commits.
1636 let converted = unsafe {
1637 convert::av_frame_to_video_frame_as::<C>(
1638 self.sw_scratch.as_ptr(),
1639 self.time_base,
1640 self.limits.frame(),
1641 )
1642 };
1643 let new_frame = match converted {
1644 Ok(new_frame) => new_frame,
1645 Err(e) => {
1646 self.scratch_pending = e.parks_in_decode();
1647 return Err(VideoDecodeError::Convert(e));
1648 }
1649 };
1650 // SW produced a frame. The commit point clears degraded mode only
1651 // if a keyframe was fed across the gap — a real keyframe-anchored
1652 // resync, so the dropped span is the promised bounded gap. A
1653 // concealed P-frame (no keyframe yet) does not clear it (see
1654 // `resync_on_frame`).
1655 self.commit_delivery(new_frame, dst);
1656 return Ok(Received::Frame);
1657 }
1658 // Funnel first — so a recorded budget refusal is named
1659 // rather than laundered — read as a status second (`EAGAIN`
1660 // is `NeedsInput`, `Eof` is `Ended`, and the errno stops
1661 // inside this crate either way), and settled against the
1662 // session's own end third.
1663 //
1664 // That last step is where a post-commit resync that never
1665 // closed becomes [`VideoDecodeError::PostCommitNeverResynced`]
1666 // instead of a clean end that would swallow the tail — and
1667 // it now catches the end however the codec spelled it. See
1668 // [`Self::settle`] and [`Self::ended`].
1669 Err(e) => {
1670 let status =
1671 crate::decoder::software_receive(st, e, phase).map_err(VideoDecodeError::Decode)?;
1672 return self.settle(status);
1673 }
1674 }
1675 }
1676 }
1677 }
1678 }
1679
1680 pub(crate) fn send_eof_impl(&mut self) -> Result<Sent, VideoDecodeError> {
1681 // The same two gates in the same order, for the same reason: a
1682 // repeated end-of-stream past a committed one is refused however
1683 // much is drained, so answering back pressure would be a promise
1684 // this face cannot keep. See [`Self::after_eof`].
1685 if !self.phase().accepts_input() {
1686 return Err(Self::after_eof());
1687 }
1688 // As `send_packet`: EOF can commit a fallback too, and the escalation
1689 // it may raise reads the resync standing a parked frame has not yet
1690 // had the chance to clear. Nothing was recorded, so drain and signal
1691 // again.
1692 if self.scratch_pending {
1693 return Ok(Sent::MustDrain);
1694 }
1695 let phase = self.phase();
1696 let outcome = match &mut self.state {
1697 DecodeState::Hw(hw) => match hw.send_eof() {
1698 // The seam classified libavcodec's back pressure already.
1699 Ok(status) => Ok(status),
1700 Err(Error::AllBackendsFailed(p)) => {
1701 // The pin, on the EOF road — see [`Self::may_open_software`].
1702 // Returned rather than folded into `outcome`: the commit below
1703 // fires only on `Ok(Sent::Accepted)`, so the two roads agree,
1704 // and leaving early keeps the fallback body at the nesting it
1705 // was written at.
1706 if !self.may_open_software() {
1707 return Err(VideoDecodeError::Decode(Error::AllBackendsFailed(p)));
1708 }
1709 // EOF is pending for this transaction, so the SW decoder must also
1710 // receive `send_eof` (codecs that delay tail frames hang otherwise).
1711 // We pass that intent locally rather than pre-setting `self.eof_sent`:
1712 // a fallback that fails returns `FallbackFailed` and stays on HW, and a
1713 // half-mutated `self.eof_sent = true` would then make a *later*
1714 // fallback inject an EOF into SW even though this `send_eof` errored.
1715 // `self.eof_sent` is committed only after the whole operation succeeds
1716 // (the `outcome` check below), keeping the fallback all-or-nothing.
1717 if p.origin().is_post_commit() {
1718 // Post-commit: DEGRADE AND CONTINUE — open SW cold, re-forward EOF
1719 // (no current packet, no replay frames). The cold SW produces no
1720 // frame from EOF alone, so the drain-to-EOF in `receive_frame`
1721 // escalates (`PostCommitNeverResynced`) unless a later keyframe-fed
1722 // poll resyncs first. A clean commit enters degraded mode; a SW-open
1723 // failure surfaces `FallbackFailed` and stays HW.
1724 tracing::warn!(
1725 backend = ?p.attempts().last().map(|(b, _)| *b),
1726 "mediadecode-ffmpeg: HW decode failed post-commit at EOF; falling \
1727 back to software — a bounded span of tail frames may be dropped",
1728 );
1729 // Both fallback roads forward the EOF inside their own
1730 // transaction, so a clean commit means it was recorded.
1731 // `true`: this *is* the end being sent. `eof_sent` is not
1732 // committed until the whole operation succeeds, so the
1733 // intent is passed locally rather than read back.
1734 self
1735 .degrade_to_sw(PostCommitInput::Eof, true)
1736 .map(|()| Sent::Accepted)
1737 .map_err(VideoDecodeError::Decode)
1738 } else {
1739 // Probe-era: replay the buffered history (lossless), re-forwarding
1740 // EOF inside the transaction.
1741 let rescued = p.into_unconsumed_packets();
1742 self
1743 .fall_back_to_sw(rescued, true)
1744 .map(|()| Sent::Accepted)
1745 .map_err(VideoDecodeError::Decode)
1746 }
1747 }
1748 Err(other) => Err(VideoDecodeError::Decode(other)),
1749 },
1750 DecodeState::Sw(sw) => {
1751 let st = sw.state();
1752 match sw.send_eof() {
1753 Ok(()) => Ok(Sent::Accepted),
1754 Err(e) => crate::decoder::software_send(st, e, phase).map_err(VideoDecodeError::Decode),
1755 }
1756 }
1757 };
1758 // Commit EOF state only when the EOF was actually **taken** — a failed
1759 // fallback left `self.eof_sent` untouched (restored-by-construction: we
1760 // never mutated it), so HW stays EOF-not-yet-sent and a retry behaves
1761 // correctly.
1762 //
1763 // **`is_ok()` is not the test any more, and that is not a stylistic
1764 // change.** `Ok(Sent::MustDrain)` means the decoder did not take the
1765 // end-of-stream; recording `eof_sent` there would make a later fallback
1766 // inject an EOF into the software decoder for a signal that was never
1767 // accepted — the exact half-mutation the local `eof_pending` argument
1768 // exists to prevent on the failure road.
1769 if matches!(outcome, Ok(Sent::Accepted)) {
1770 self.eof_sent = true;
1771 }
1772 outcome
1773 }
1774
1775 pub(crate) fn flush_impl(&mut self) -> Result<(), VideoDecodeError> {
1776 // Drop any frames buffered during SW fallback replay before
1777 // flushing the inner decoder — otherwise a seek/reset would
1778 // surface stale pre-flush frames on the next `receive_frame`.
1779 self.sw_replay_frames.clear();
1780 // And a parked frame belongs to the position being abandoned.
1781 self.scratch_pending = false;
1782 // Flush ends the drain phase; the decoder accepts new packets
1783 // after this, so reset EOF tracking.
1784 self.eof_sent = false;
1785 // A flush (seek/reset) re-anchors the stream — any in-flight post-commit
1786 // resync tracking from before the flush is moot. Clear it so the next EOF
1787 // doesn't escalate over a now-irrelevant pre-flush gap.
1788 self.clear_degraded_resync();
1789 match &mut self.state {
1790 // The HW seam's `flush` returns `Result` for a uniform trait; the
1791 // real `VideoDecoder::flush` is infallible (always `Ok`).
1792 DecodeState::Hw(hw) => hw.flush().map_err(VideoDecodeError::Decode)?,
1793 DecodeState::Sw(sw) => sw.flush(),
1794 }
1795 Ok(())
1796 }
1797}
1798
1799macro_rules! video_lane_face {
1800 ($($lane:ty),+ $(,)?) => { $(
1801 impl CarrierVideoStreamDecoder<$lane> {
1802 /// Opens a video decoder for `parameters`, probing hardware
1803 /// backends in order and falling back to software.
1804 ///
1805 /// [`open_as`](Self::open_as)`(.., DecodePath::Auto)`, which is
1806 /// what this has always done.
1807 pub fn open(
1808 parameters: Parameters,
1809 time_base: Timebase,
1810 limits: DecoderLimits,
1811 ) -> Result<Self, Error> {
1812 Self::open_impl(parameters, time_base, limits)
1813 }
1814
1815 /// Opens a video decoder on a **named decode path**.
1816 ///
1817 /// [`DecodePath::Auto`] is [`open`](Self::open) exactly; the
1818 /// other two arms pin the session to hardware or to software for
1819 /// its whole life. See [`DecodePath`] for what a pin promises and
1820 /// what it costs.
1821 ///
1822 /// Everything else about the session is unchanged — the same
1823 /// [`VideoStreamDecoder`] face, the same frames, the same
1824 /// [`is_hardware`](Self::is_hardware) / [`is_software`](Self::is_software)
1825 /// readings. The choice is *which decoder is behind them*, which
1826 /// is what a determinism comparison and a deployment policy each
1827 /// need and neither could reach.
1828 ///
1829 /// # Errors
1830 ///
1831 /// [`DecodePath::Hardware`] fails here when the named backend
1832 /// cannot be opened for the stream — where [`DecodePath::Auto`]
1833 /// would have gone on to software. [`DecodePath::Software`] fails
1834 /// only where libavcodec has no decoder for the stream, or the
1835 /// context cannot be built.
1836 ///
1837 /// # Examples
1838 ///
1839 /// ```no_run
1840 /// use mediadecode_ffmpeg::{DecodePath, DecoderLimits, FfmpegVideoStreamDecoder};
1841 /// # fn f(parameters: ffmpeg_next::codec::Parameters, time_base: mediadecode::Timebase)
1842 /// # -> Result<(), Box<dyn std::error::Error>> {
1843 /// // The same stream, decoded without a GPU anywhere in the story.
1844 /// let decoder = FfmpegVideoStreamDecoder::open_as(
1845 /// parameters,
1846 /// time_base,
1847 /// DecoderLimits::default(),
1848 /// DecodePath::Software,
1849 /// )?;
1850 /// assert!(decoder.is_software());
1851 /// # Ok(())
1852 /// # }
1853 /// ```
1854 pub fn open_as(
1855 parameters: Parameters,
1856 time_base: Timebase,
1857 limits: DecoderLimits,
1858 path: DecodePath,
1859 ) -> Result<Self, Error> {
1860 Self::open_as_impl(parameters, time_base, limits, path)
1861 }
1862
1863 /// Whether this decoder is currently running on software.
1864 pub const fn is_software(&self) -> bool {
1865 self.is_software_impl()
1866 }
1867
1868 /// Whether this decoder is currently running on hardware.
1869 pub const fn is_hardware(&self) -> bool {
1870 self.is_hardware_impl()
1871 }
1872
1873 /// Whether this session can currently emit pictures at a
1874 /// caller-requested output size. See
1875 /// [`ScaledOutputCapability`] and
1876 /// [`Self::request_scaled_output`].
1877 ///
1878 /// `Supported` on a live VideoToolbox session on an Apple
1879 /// target, `Unsupported` everywhere else — including on a
1880 /// session that has degraded to software, which is why this
1881 /// reads the session's live state rather than a fact recorded
1882 /// once at open.
1883 pub fn scaled_output_capability(&self) -> ScaledOutputCapability {
1884 self.scaled_output_capability_impl()
1885 }
1886
1887 /// Requests that this session emit pictures at `size` (width,
1888 /// height) from the next frame on, and reports whether the
1889 /// request was recorded. See
1890 /// [`VideoStreamDecoder::request_scaled_output`] for the full
1891 /// contract (never an error) and
1892 /// [`Self::scaled_output_capability`]'s documentation for which
1893 /// road can honor one, what a mid-stream request means, and the
1894 /// zero / upscale refusals this seat mints itself.
1895 pub fn request_scaled_output(&mut self, size: (u32, u32)) -> ScaledOutputCapability {
1896 self.request_scaled_output_impl(size)
1897 }
1898
1899 /// The hardware wrapper, when one is in use.
1900 pub fn hardware_inner(&self) -> Option<&VideoDecoder> {
1901 self.hardware_inner_impl()
1902 }
1903
1904 /// The stream timebase every produced timestamp is stamped with.
1905 pub const fn time_base(&self) -> Timebase {
1906 self.time_base_impl()
1907 }
1908 }
1909
1910 impl VideoStreamDecoder for CarrierVideoStreamDecoder<$lane> {
1911 type Adapter = Ffmpeg;
1912 type Buffer = <$lane as crate::FfmpegCarrier>::Buffer;
1913 type Error = VideoDecodeError;
1914
1915 fn send_packet(
1916 &mut self,
1917 packet: &VideoPacket<VideoPacketExtra, Self::Buffer>,
1918 ) -> Result<Sent, Self::Error> {
1919 self.send_packet_impl(packet)
1920 }
1921
1922 fn receive_frame(
1923 &mut self,
1924 dst: &mut VideoFrame<mediadecode::PixelFormat, VideoFrameExtra, Self::Buffer>,
1925 ) -> Result<Received, Self::Error> {
1926 self.receive_frame_impl(dst)
1927 }
1928
1929 fn send_eof(&mut self) -> Result<Sent, Self::Error> {
1930 self.send_eof_impl()
1931 }
1932
1933 fn flush(&mut self) -> Result<(), Self::Error> {
1934 self.flush_impl()
1935 }
1936
1937 fn scaled_output_capability(&self) -> ScaledOutputCapability {
1938 self.scaled_output_capability_impl()
1939 }
1940
1941 fn request_scaled_output(&mut self, size: (u32, u32)) -> ScaledOutputCapability {
1942 self.request_scaled_output_impl(size)
1943 }
1944 }
1945 )+ };
1946}
1947
1948video_lane_face!(crate::View, crate::Owned);
1949
1950fn open_sw_decoder(parameters: &Parameters, limits: DecoderLimits) -> Result<SwDecoder, Error> {
1951 // Use the checked codec-context builder — ffmpeg-next's
1952 // `Context::from_parameters` calls `Context::new()` which doesn't
1953 // null-check `avcodec_alloc_context3`'s return value before
1954 // running `avcodec_parameters_to_context` against it. Under
1955 // memory pressure that's C-level UB; `build_codec_context`
1956 // surfaces the OOM as an error instead.
1957 let (ctx, callback_state) = build_codec_context(parameters, limits)?;
1958 // Opened without forming a bindgen enum from FFmpeg memory: the codec
1959 // is resolved off a raw `codec_id`, and the medium is proved off a raw
1960 // `codec_type`. See `crate::decoder::ensure_codec_type`.
1961 let codec = crate::decoder::find_decoder(parameters)?;
1962 let opened = ctx.decoder().open_as(codec).map_err(Error::Ffmpeg)?;
1963 crate::decoder::ensure_video_codec_type(&opened)?;
1964 Ok(SwDecoder {
1965 decoder: ffmpeg_next::decoder::Video(opened),
1966 _callback_state: callback_state,
1967 })
1968}
1969
1970/// Payload for [`VideoDecodeError::PostCommitNeverResynced`].
1971///
1972/// A **post-commit** HW->SW fallback degraded the stream (dropping the
1973/// bounded span up to the next keyframe) but the software decoder
1974/// reached EOF without ever producing a frame — it never resynced, so
1975/// the entire tail from the failure point was lost. The "bounded,
1976/// logged gap" the post-commit path promises did not materialise (no
1977/// keyframe arrived before EOF), so the loss is surfaced loudly here
1978/// instead of being silently swallowed as a clean end-of-stream.
1979#[derive(thiserror::Error, Debug)]
1980#[error(
1981 "post-commit HW->SW fallback never resynced before EOF: {packets_lost} packets fed to the \
1982 software decoder produced no frame (no keyframe found across the gap) — the stream tail \
1983 from the fallback point was lost"
1984)]
1985pub struct PostCommitNeverResynced {
1986 packets_lost: u64,
1987}
1988
1989impl PostCommitNeverResynced {
1990 /// Constructs a `PostCommitNeverResynced` payload.
1991 #[inline]
1992 pub const fn new(packets_lost: u64) -> Self {
1993 Self { packets_lost }
1994 }
1995 /// Packets fed to the software decoder across the unresolved resync
1996 /// gap.
1997 #[inline]
1998 pub const fn packets_lost(&self) -> u64 {
1999 self.packets_lost
2000 }
2001}
2002
2003/// Error type for [`FfmpegVideoStreamDecoder`] — **faults and the
2004/// send-side refusal**.
2005///
2006/// Every arm here is something that went wrong or something the push
2007/// face declined. The drain's *needs input* and *ended* are
2008/// [`Received`] states out of `receive_frame`; they used to arrive as
2009/// `Decode(Ffmpeg(Other { errno: EAGAIN }))` and `Decode(Ffmpeg(Eof))`,
2010/// which is to say they had no name at this tier at all.
2011/// [`Self::PostCommitNeverResynced`] is the deliberate exception on the
2012/// end-of-stream road: it is not "the stream ended", it is "the stream
2013/// ended and the tail was lost", which is a fault.
2014///
2015/// **Open fault taxonomy, so it is `#[non_exhaustive]`.** New ways to
2016/// fail are discovered — a backend, a ceiling, a corruption a codec
2017/// learns to report — and a consumer that meets one it has never heard
2018/// of should take its generic-fault path. That is exactly what the
2019/// wildcard arm this attribute forces is for. The two status
2020/// vocabularies opposite it,
2021/// [`Sent`](mediadecode::Sent) and [`Received`](mediadecode::Received),
2022/// are exhaustive for the mirror-image reason: their arms are the
2023/// substrate's fixed state set, and there the wildcard would be dead
2024/// weight hiding a state a consumer forgot.
2025#[derive(thiserror::Error, Debug, IsVariant, Unwrap, TryUnwrap)]
2026#[unwrap(ref, ref_mut)]
2027#[try_unwrap(ref, ref_mut)]
2028#[non_exhaustive]
2029pub enum VideoDecodeError {
2030 /// The wrapped decoder (HW or SW) reported an error.
2031 #[error(transparent)]
2032 Decode(#[from] Error),
2033 /// Frame conversion from FFmpeg's native types to mediadecode's
2034 /// types failed.
2035 #[error(transparent)]
2036 Convert(#[from] ConvertError),
2037 /// A **post-commit** HW->SW fallback degraded the stream but the
2038 /// software decoder reached EOF without ever producing a frame.
2039 #[error(transparent)]
2040 PostCommitNeverResynced(#[from] PostCommitNeverResynced),
2041}
2042
2043#[cfg(test)]
2044mod tests;