Skip to main content

rawshift_hwdec/
lib.rs

1//! # rawshift-hwdec
2//!
3//! Hardware still-frame codestream decode for rawshift: HEVC (HEIC) and AV1
4//! (AVIF) intra pictures through the platform decode APIs fixed in
5//! [`docs/SUPPORT.md`] — VideoToolbox (macOS/iOS), VAAPI (linux-gnu, dlopen'd
6//! at runtime), and NDK MediaCodec (Android).
7//!
8//! ## Safety boundary
9//!
10//! Per `PRINCIPLES.md`, **all** platform FFI for hardware decode lives in this
11//! crate and nowhere else: `#![deny(unsafe_op_in_unsafe_fn)]`, every public
12//! item is safe, and every `unsafe` block documents its invariants inside the
13//! platform backend module that owns it. The **VAAPI backend** (linux-gnu,
14//! dlopen'd libva — see the `vaapi` module) is implemented; VideoToolbox and
15//! MediaCodec land as separate issues. On targets/builds with no backend
16//! every entry point reports "no decoder" — [`decoder`] returns `None`,
17//! [`backend`] returns `None`, and [`available_codecs`] is empty.
18//!
19//! On NVIDIA GPUs the VAAPI backend works through the maintained
20//! [`nvidia-vaapi-driver`](https://github.com/elFarto/nvidia-vaapi-driver)
21//! translation layer over NVDEC (see `docs/SUPPORT.md`).
22//!
23//! ## Verified feature flags
24//!
25//! - `hw` — portable: selects the native backend for the compile target via
26//!   the build script; on a target with no hardware decode API
27//!   (windows-msvc, linux-musl, wasm — see the SUPPORT.md matrix) it emits a
28//!   build warning and compiles this stub. Valid everywhere.
29//! - `videotoolbox` / `vaapi` / `mediacodec` — pin one explicit backend;
30//!   **`compile_error!` on any other target**. For example, this fails to
31//!   compile anywhere but Apple platforms (a compile-fail test matrix in CI
32//!   is tracked separately):
33//!
34//!   ```text
35//!   cargo check -p rawshift-hwdec --features videotoolbox   # non-Apple host
36//!   error: rawshift-hwdec: the `videotoolbox` feature requires an Apple target ...
37//!   ```
38//!
39//! ## Request/response contract
40//!
41//! The request is misuse-resistant by construction: the codec is implied by
42//! the [`CodecConfig`] variant (an `hvcC` config with an OBU payload, or an
43//! `av1C` config claiming to be HEVC, is unrepresentable), and
44//! [`DecodedFrame::new`] validates plane geometry against the pixel format so
45//! an internally inconsistent frame cannot be constructed.
46//!
47//! [`docs/SUPPORT.md`]: https://github.com/visualcommons/rawshift/blob/master/docs/SUPPORT.md
48
49#![deny(unsafe_op_in_unsafe_fn)]
50
51// The VAAPI platform backend: compiled only when build.rs selected it
52// (`vaapi` explicit flag, or `hw` on a linux-gnu target).
53#[cfg(hwdec_backend = "vaapi")]
54mod vaapi;
55
56// ── Verified feature boundaries ─────────────────────────────────────────────
57// Explicit backend flags are hard errors on targets whose platform API does
58// not exist — a mis-pinned build must fail at compile time, not degrade
59// silently. The portable `hw` flag never errors; build.rs handles it.
60
61#[cfg(all(
62    feature = "videotoolbox",
63    not(any(target_os = "macos", target_os = "ios"))
64))]
65compile_error!(
66    "rawshift-hwdec: the `videotoolbox` feature requires an Apple target \
67     (macOS or iOS). Use the portable `hw` feature to select the native \
68     backend for the compile target, or see docs/SUPPORT.md."
69);
70
71#[cfg(all(feature = "vaapi", not(all(target_os = "linux", target_env = "gnu"))))]
72compile_error!(
73    "rawshift-hwdec: the `vaapi` feature requires a linux-gnu target (VAAPI \
74     is dlopen'd; musl has no dlopen deployment story — see docs/SUPPORT.md). \
75     Use the portable `hw` feature to select the native backend for the \
76     compile target."
77);
78
79#[cfg(all(feature = "mediacodec", not(target_os = "android")))]
80compile_error!(
81    "rawshift-hwdec: the `mediacodec` feature requires an Android target \
82     (NDK MediaCodec). Use the portable `hw` feature to select the native \
83     backend for the compile target, or see docs/SUPPORT.md."
84);
85
86use thiserror::Error;
87
88pub use gamut_color::{ChromaSubsampling, ColorRange};
89
90// ── Codec / backend identity ────────────────────────────────────────────────
91
92/// A codec this crate can decode still frames of.
93///
94/// The set is fixed at v1 (see `docs/SUPPORT.md`): HEVC for HEIC and AV1 for
95/// AVIF. It is deliberately exhaustive — a new codec is a deliberate,
96/// breaking decision, not an additive one.
97#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
98pub enum HwCodec {
99    /// HEVC / H.265 intra (HEIC still images).
100    Hevc,
101    /// AV1 intra (AVIF still images).
102    Av1,
103}
104
105impl HwCodec {
106    /// The conventional display name of the codec (`"HEVC"` / `"AV1"`).
107    #[must_use]
108    pub fn name(self) -> &'static str {
109        match self {
110            HwCodec::Hevc => "HEVC",
111            HwCodec::Av1 => "AV1",
112        }
113    }
114}
115
116impl std::fmt::Display for HwCodec {
117    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
118        f.write_str(self.name())
119    }
120}
121
122/// A platform hardware-decode API — the fixed set from `docs/SUPPORT.md`.
123#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
124pub enum HwBackend {
125    /// Apple VideoToolbox (macOS 11+, iOS 14+).
126    VideoToolbox,
127    /// VAAPI / libva on linux-gnu, dlopen'd at runtime (absence degrades to
128    /// "no decoder", never a link failure).
129    Vaapi,
130    /// Android NDK MediaCodec.
131    MediaCodec,
132}
133
134impl HwBackend {
135    /// The conventional display name of the backend.
136    #[must_use]
137    pub fn name(self) -> &'static str {
138        match self {
139            HwBackend::VideoToolbox => "VideoToolbox",
140            HwBackend::Vaapi => "VAAPI",
141            HwBackend::MediaCodec => "MediaCodec",
142        }
143    }
144}
145
146impl std::fmt::Display for HwBackend {
147    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
148        f.write_str(self.name())
149    }
150}
151
152// ── Decode request ──────────────────────────────────────────────────────────
153
154/// The codec configuration record of a still-decode request. **The variant is
155/// the codec**: an [`Hvcc`](CodecConfig::Hvcc) request is an HEVC request and
156/// an [`Av1c`](CodecConfig::Av1c) request is an AV1 request, so a mismatched
157/// codec/config pair is unrepresentable.
158///
159/// The bytes are the raw record **body** as stored in the container property
160/// (the `hvcC` HEVCDecoderConfigurationRecord per ISO/IEC 14496-15 §8.3.3.1,
161/// or the `av1C` AV1CodecConfigurationRecord), without any box header.
162#[derive(Debug, Clone, Copy, PartialEq, Eq)]
163pub enum CodecConfig<'a> {
164    /// An `hvcC` HEVCDecoderConfigurationRecord body. The matching
165    /// [`StillDecodeRequest::payload`] is the length-prefixed NAL stream of
166    /// the coded item.
167    Hvcc(&'a [u8]),
168    /// An `av1C` AV1CodecConfigurationRecord body. The matching
169    /// [`StillDecodeRequest::payload`] is the OBU stream of the coded item.
170    Av1c(&'a [u8]),
171}
172
173impl<'a> CodecConfig<'a> {
174    /// The codec this configuration record belongs to — implied by the
175    /// variant, never stored separately.
176    #[must_use]
177    pub fn codec(&self) -> HwCodec {
178        match self {
179            CodecConfig::Hvcc(_) => HwCodec::Hevc,
180            CodecConfig::Av1c(_) => HwCodec::Av1,
181        }
182    }
183
184    /// The raw configuration-record body bytes.
185    #[must_use]
186    pub fn bytes(&self) -> &'a [u8] {
187        match self {
188            CodecConfig::Hvcc(bytes) | CodecConfig::Av1c(bytes) => bytes,
189        }
190    }
191}
192
193/// One still-frame decode request: the codec configuration (which implies the
194/// codec), the coded payload, and the caller's advisory picture description.
195///
196/// `payload` framing follows the config variant: a length-prefixed NAL stream
197/// for [`CodecConfig::Hvcc`] (the prefix width is inside the `hvcC` record),
198/// an OBU stream for [`CodecConfig::Av1c`].
199///
200/// `width`/`height`/`bit_depth`/`chroma` are **advisory**: they describe what
201/// the container claims (`ispe`, `hvcC`/`av1C` fields) so a backend can size
202/// its output surfaces up front, but the coded bitstream is authoritative and
203/// the returned [`DecodedFrame`] carries the real geometry.
204#[derive(Debug, Clone, Copy, PartialEq, Eq)]
205pub struct StillDecodeRequest<'a> {
206    /// The codec configuration record; its variant is the codec.
207    pub config: CodecConfig<'a>,
208    /// The coded picture payload (length-prefixed NAL units or OBUs — see the
209    /// type-level docs).
210    pub payload: &'a [u8],
211    /// Advisory coded picture width in pixels (0 = unknown).
212    pub width: u32,
213    /// Advisory coded picture height in pixels (0 = unknown).
214    pub height: u32,
215    /// Advisory per-sample bit depth (from the configuration record).
216    pub bit_depth: u8,
217    /// Advisory chroma subsampling (from the configuration record).
218    pub chroma: ChromaSubsampling,
219}
220
221impl StillDecodeRequest<'_> {
222    /// The codec of this request — implied by the configuration variant.
223    #[must_use]
224    pub fn codec(&self) -> HwCodec {
225        self.config.codec()
226    }
227}
228
229// ── Decoded frame ───────────────────────────────────────────────────────────
230
231/// The pixel layout of a [`DecodedFrame`] — the four surface formats the
232/// platform decoders emit for 4:2:0 content.
233#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
234pub enum PixelFormat {
235    /// 8-bit 4:2:0, biplanar: full-size Y plane + half-size interleaved CbCr
236    /// plane.
237    Nv12,
238    /// 10..16-bit 4:2:0, biplanar: like [`Nv12`](Self::Nv12) but 16-bit
239    /// little-endian words with the sample value in the **most** significant
240    /// bits (the VideoToolbox / DXGI `P010` convention).
241    P010,
242    /// 8-bit 4:2:0, planar: full-size Y plane + half-size Cb and Cr planes.
243    I420,
244    /// 10..16-bit 4:2:0, planar: like [`I420`](Self::I420) but 16-bit
245    /// little-endian words with the sample value in the **least** significant
246    /// bits.
247    I010,
248}
249
250impl PixelFormat {
251    /// The number of planes this format carries (2 for biplanar NV12/P010,
252    /// 3 for planar I420/I010).
253    #[must_use]
254    pub fn plane_count(self) -> usize {
255        match self {
256            PixelFormat::Nv12 | PixelFormat::P010 => 2,
257            PixelFormat::I420 | PixelFormat::I010 => 3,
258        }
259    }
260
261    /// The storage size of one sample in bytes (1 for the 8-bit formats, 2
262    /// for the 16-bit-word formats).
263    #[must_use]
264    pub fn bytes_per_sample(self) -> usize {
265        match self {
266            PixelFormat::Nv12 | PixelFormat::I420 => 1,
267            PixelFormat::P010 | PixelFormat::I010 => 2,
268        }
269    }
270
271    /// Whether `bit_depth` is representable in this format: exactly 8 for the
272    /// 8-bit formats, `9..=16` for the 16-bit-word formats.
273    #[must_use]
274    pub fn supports_bit_depth(self, bit_depth: u8) -> bool {
275        match self {
276            PixelFormat::Nv12 | PixelFormat::I420 => bit_depth == 8,
277            PixelFormat::P010 | PixelFormat::I010 => (9..=16).contains(&bit_depth),
278        }
279    }
280}
281
282/// One image plane of a [`DecodedFrame`]: raw bytes plus the row stride.
283#[derive(Debug, Clone, PartialEq, Eq)]
284pub struct Plane {
285    /// The raw plane bytes, row-major. Sample encoding follows the frame's
286    /// [`PixelFormat`].
287    pub data: Vec<u8>,
288    /// The distance between the starts of two consecutive rows, in **bytes**
289    /// (at least the row's used width; may be larger for aligned surfaces).
290    pub stride: usize,
291}
292
293/// The validated output of a [`HwStillDecoder`]: a decoded 4:2:0 (or
294/// monochrome-in-4:2:0) picture in one of the four platform surface layouts.
295///
296/// Construct with [`DecodedFrame::new`], which checks the plane count and
297/// every plane's geometry against `format`/`width`/`height`, and the
298/// `bit_depth` against the format's sample width — an internally inconsistent
299/// frame is unrepresentable, so consumers can trust the plane sizes.
300#[derive(Debug, Clone, PartialEq, Eq)]
301pub struct DecodedFrame {
302    format: PixelFormat,
303    width: u32,
304    height: u32,
305    bit_depth: u8,
306    range: ColorRange,
307    planes: Vec<Plane>,
308}
309
310impl DecodedFrame {
311    /// Builds a frame from its planes, validating internal consistency.
312    ///
313    /// `width`/`height` are the luma dimensions (post conformance-window
314    /// crop). Chroma planes use **ceiling** division on the subsampled axes.
315    ///
316    /// # Errors
317    ///
318    /// Returns [`HwDecodeError::InvalidFrame`] if either dimension is zero,
319    /// `bit_depth` does not fit `format` (see
320    /// [`PixelFormat::supports_bit_depth`]), the plane count is wrong, a
321    /// stride is smaller than the row's used width, or a plane buffer is too
322    /// short for its rows.
323    pub fn new(
324        format: PixelFormat,
325        width: u32,
326        height: u32,
327        bit_depth: u8,
328        range: ColorRange,
329        planes: Vec<Plane>,
330    ) -> Result<Self, HwDecodeError> {
331        let invalid = |message: &str| HwDecodeError::InvalidFrame {
332            message: message.to_string(),
333        };
334        if width == 0 || height == 0 {
335            return Err(invalid("frame dimensions must be non-zero"));
336        }
337        if !format.supports_bit_depth(bit_depth) {
338            return Err(invalid(
339                "bit depth is not representable in the pixel format",
340            ));
341        }
342        if planes.len() != format.plane_count() {
343            return Err(invalid("plane count does not match the pixel format"));
344        }
345
346        let bps = format.bytes_per_sample();
347        let (cw, ch) = (width.div_ceil(2) as usize, height.div_ceil(2) as usize);
348        for (index, plane) in planes.iter().enumerate() {
349            // Plane geometry: index 0 is luma; for biplanar formats index 1 is
350            // the interleaved CbCr plane (two samples per chroma column); for
351            // planar formats indexes 1/2 are the Cb/Cr planes.
352            let (row_samples, rows) = match (format.plane_count(), index) {
353                (_, 0) => (width as usize, height as usize),
354                (2, 1) => (cw * 2, ch),
355                (3, 1 | 2) => (cw, ch),
356                // Unreachable: plane count was validated above.
357                _ => unreachable!("plane index out of range for format"),
358            };
359            let row_bytes = row_samples
360                .checked_mul(bps)
361                .ok_or_else(|| invalid("plane row size overflows"))?;
362            if plane.stride < row_bytes {
363                return Err(invalid("plane stride is smaller than the row width"));
364            }
365            let required = plane
366                .stride
367                .checked_mul(rows - 1)
368                .and_then(|n| n.checked_add(row_bytes))
369                .ok_or_else(|| invalid("plane size overflows"))?;
370            if plane.data.len() < required {
371                return Err(invalid("plane buffer is shorter than its rows"));
372            }
373        }
374
375        Ok(Self {
376            format,
377            width,
378            height,
379            bit_depth,
380            range,
381            planes,
382        })
383    }
384
385    /// The pixel layout of the planes.
386    #[must_use]
387    pub fn format(&self) -> PixelFormat {
388        self.format
389    }
390
391    /// The luma width in pixels (post conformance-window crop).
392    #[must_use]
393    pub fn width(&self) -> u32 {
394        self.width
395    }
396
397    /// The luma height in pixels (post conformance-window crop).
398    #[must_use]
399    pub fn height(&self) -> u32 {
400        self.height
401    }
402
403    /// The per-sample bit depth (8 for NV12/I420, 9..=16 for P010/I010).
404    #[must_use]
405    pub fn bit_depth(&self) -> u8 {
406        self.bit_depth
407    }
408
409    /// The signal range of the samples (limited/studio vs full swing).
410    #[must_use]
411    pub fn range(&self) -> ColorRange {
412        self.range
413    }
414
415    /// The planes, in format order (Y, then CbCr or Cb/Cr).
416    #[must_use]
417    pub fn planes(&self) -> &[Plane] {
418        &self.planes
419    }
420}
421
422// ── Decoder seam ────────────────────────────────────────────────────────────
423
424/// A hardware still-frame decoder for one codec, obtained from [`decoder`].
425///
426/// `&mut self`: platform decoder sessions are stateful (reused contexts,
427/// surface pools). `Send`: a decoder may be moved to a worker thread; none of
428/// the planned backends hand out thread-affine handles.
429pub trait HwStillDecoder: Send {
430    /// Decodes one coded still picture to a [`DecodedFrame`].
431    ///
432    /// # Errors
433    ///
434    /// Returns [`HwDecodeError`] when the backend rejects the configuration,
435    /// the bitstream is malformed, or the platform decoder fails.
436    fn decode_still(
437        &mut self,
438        request: &StillDecodeRequest<'_>,
439    ) -> Result<DecodedFrame, HwDecodeError>;
440}
441
442/// Errors reported by hardware still-frame decode.
443#[derive(Debug, Error)]
444#[non_exhaustive]
445pub enum HwDecodeError {
446    /// No hardware decoder is available for the codec — none compiled in, or
447    /// the runtime probe (driver, entry point, codec support) failed.
448    #[error("no hardware decoder available for {codec}: {reason}")]
449    Unavailable {
450        /// The codec that was requested.
451        codec: HwCodec,
452        /// Why no decoder is available (which probe failed, or that no
453        /// backend is compiled in).
454        reason: String,
455    },
456    /// The platform decoder accepted the job and then failed.
457    #[error("hardware {codec} decode failed: {message}")]
458    Decode {
459        /// The codec being decoded.
460        codec: HwCodec,
461        /// The backend's failure description.
462        message: String,
463    },
464    /// A [`DecodedFrame`] failed validation (backend bug or corrupted
465    /// output).
466    #[error("invalid decoded frame: {message}")]
467    InvalidFrame {
468        /// What was inconsistent.
469        message: String,
470    },
471}
472
473// ── Backend discovery ───────────────────────────────────────────────────────
474
475/// Returns a decoder for `codec`, or `None` when no compiled-in backend can
476/// decode it at runtime.
477///
478/// With the VAAPI backend compiled in (`vaapi`, or `hw` on linux-gnu), this
479/// dlopens libva on first use and answers from the driver's actual
480/// profile/entrypoint list; missing libraries, render nodes, or driver
481/// support all degrade to `None` (never a link or startup failure).
482/// VideoToolbox and MediaCodec land as separate issues; without a backend
483/// this returns `None` everywhere.
484#[must_use]
485pub fn decoder(codec: HwCodec) -> Option<Box<dyn HwStillDecoder>> {
486    #[cfg(hwdec_backend = "vaapi")]
487    {
488        vaapi::decoder(codec)
489    }
490    #[cfg(not(hwdec_backend = "vaapi"))]
491    {
492        let _ = codec;
493        None
494    }
495}
496
497/// The platform backend compiled into this build and usable at runtime, or
498/// `None`.
499///
500/// Reports `Some` only when the runtime probe succeeds (e.g. VAAPI's dlopen
501/// finding a driver with at least one supported codec at the VLD entry
502/// point).
503#[must_use]
504pub fn backend() -> Option<HwBackend> {
505    #[cfg(hwdec_backend = "vaapi")]
506    {
507        vaapi::backend()
508    }
509    #[cfg(not(hwdec_backend = "vaapi"))]
510    {
511        None
512    }
513}
514
515/// The codecs [`decoder`] can currently return a decoder for, per the
516/// runtime probe (e.g. `vaQueryConfigProfiles` for VAAPI).
517///
518/// Empty when no backend is compiled in or usable.
519#[must_use]
520pub fn available_codecs() -> &'static [HwCodec] {
521    #[cfg(hwdec_backend = "vaapi")]
522    {
523        vaapi::available_codecs()
524    }
525    #[cfg(not(hwdec_backend = "vaapi"))]
526    {
527        &[]
528    }
529}
530
531#[cfg(test)]
532mod tests {
533    use super::*;
534
535    // ── stub behaviour (builds with no selected backend) ────────────────────
536
537    #[cfg(not(hwdec_backend = "vaapi"))]
538    #[test]
539    fn stub_has_no_decoder_for_any_codec() {
540        assert!(decoder(HwCodec::Hevc).is_none());
541        assert!(decoder(HwCodec::Av1).is_none());
542    }
543
544    #[cfg(not(hwdec_backend = "vaapi"))]
545    #[test]
546    fn stub_reports_no_backend_and_no_codecs() {
547        assert_eq!(backend(), None);
548        assert!(available_codecs().is_empty());
549    }
550
551    // ── backend discovery consistency (any build) ───────────────────────────
552
553    /// `decoder()`, `backend()`, and `available_codecs()` must agree with
554    /// each other whether or not a platform backend/driver is present.
555    #[test]
556    fn discovery_entry_points_are_consistent() {
557        let codecs = available_codecs();
558        assert_eq!(backend().is_some(), !codecs.is_empty());
559        for codec in [HwCodec::Hevc, HwCodec::Av1] {
560            assert_eq!(
561                decoder(codec).is_some(),
562                codecs.contains(&codec),
563                "decoder({codec}) must match available_codecs()"
564            );
565        }
566    }
567
568    // ── request construction ────────────────────────────────────────────────
569
570    #[test]
571    fn codec_is_implied_by_the_config_variant() {
572        let hvcc = [0x01u8, 0x02];
573        let av1c = [0x81u8];
574        assert_eq!(CodecConfig::Hvcc(&hvcc).codec(), HwCodec::Hevc);
575        assert_eq!(CodecConfig::Av1c(&av1c).codec(), HwCodec::Av1);
576        assert_eq!(CodecConfig::Hvcc(&hvcc).bytes(), &hvcc);
577
578        let request = StillDecodeRequest {
579            config: CodecConfig::Hvcc(&hvcc),
580            payload: &[0, 0, 0, 1, 0x26],
581            width: 64,
582            height: 48,
583            bit_depth: 8,
584            chroma: ChromaSubsampling::Cs420,
585        };
586        assert_eq!(request.codec(), HwCodec::Hevc);
587    }
588
589    // ── frame validation ────────────────────────────────────────────────────
590
591    fn plane(len: usize, stride: usize) -> Plane {
592        Plane {
593            data: vec![0u8; len],
594            stride,
595        }
596    }
597
598    #[test]
599    fn i420_frame_validates() {
600        // 5x3 luma → 3x2 chroma (ceiling division).
601        let frame = DecodedFrame::new(
602            PixelFormat::I420,
603            5,
604            3,
605            8,
606            ColorRange::Limited,
607            vec![plane(15, 5), plane(6, 3), plane(6, 3)],
608        )
609        .expect("valid I420 frame");
610        assert_eq!(frame.format(), PixelFormat::I420);
611        assert_eq!((frame.width(), frame.height()), (5, 3));
612        assert_eq!(frame.planes().len(), 3);
613    }
614
615    #[test]
616    fn nv12_frame_validates_with_padded_stride() {
617        // 4x4 luma with a 8-byte stride; interleaved CbCr plane is 2x2 pairs.
618        let frame = DecodedFrame::new(
619            PixelFormat::Nv12,
620            4,
621            4,
622            8,
623            ColorRange::Full,
624            vec![plane(8 * 3 + 4, 8), plane(4 * 2, 4)],
625        )
626        .expect("valid NV12 frame");
627        assert_eq!(frame.range(), ColorRange::Full);
628        assert_eq!(frame.planes()[0].stride, 8);
629    }
630
631    #[test]
632    fn p010_requires_high_bit_depth_and_i420_requires_8() {
633        // P010 with bit depth 8 is inconsistent.
634        let err = DecodedFrame::new(
635            PixelFormat::P010,
636            2,
637            2,
638            8,
639            ColorRange::Limited,
640            vec![plane(8, 4), plane(4, 4)],
641        )
642        .unwrap_err();
643        assert!(matches!(err, HwDecodeError::InvalidFrame { .. }));
644
645        // I420 with bit depth 10 is inconsistent.
646        assert!(
647            DecodedFrame::new(
648                PixelFormat::I420,
649                2,
650                2,
651                10,
652                ColorRange::Limited,
653                vec![plane(4, 2), plane(1, 1), plane(1, 1)],
654            )
655            .is_err()
656        );
657
658        // P010 at 10 bits with correctly sized 16-bit planes is fine.
659        assert!(
660            DecodedFrame::new(
661                PixelFormat::P010,
662                2,
663                2,
664                10,
665                ColorRange::Limited,
666                vec![plane(8, 4), plane(4, 4)],
667            )
668            .is_ok()
669        );
670    }
671
672    #[test]
673    fn frame_rejects_wrong_plane_count_and_short_planes() {
674        // I420 with two planes.
675        assert!(
676            DecodedFrame::new(
677                PixelFormat::I420,
678                2,
679                2,
680                8,
681                ColorRange::Limited,
682                vec![plane(4, 2), plane(1, 1)],
683            )
684            .is_err()
685        );
686        // Luma plane one byte short.
687        assert!(
688            DecodedFrame::new(
689                PixelFormat::I420,
690                2,
691                2,
692                8,
693                ColorRange::Limited,
694                vec![plane(3, 2), plane(1, 1), plane(1, 1)],
695            )
696            .is_err()
697        );
698        // Stride smaller than the row width.
699        assert!(
700            DecodedFrame::new(
701                PixelFormat::I420,
702                4,
703                2,
704                8,
705                ColorRange::Limited,
706                vec![plane(8, 3), plane(2, 2), plane(2, 2)],
707            )
708            .is_err()
709        );
710        // Zero dimensions.
711        assert!(
712            DecodedFrame::new(
713                PixelFormat::I420,
714                0,
715                2,
716                8,
717                ColorRange::Limited,
718                vec![plane(0, 0), plane(0, 0), plane(0, 0)],
719            )
720            .is_err()
721        );
722    }
723
724    // ── error surface ───────────────────────────────────────────────────────
725
726    #[test]
727    fn errors_name_the_codec() {
728        let err = HwDecodeError::Unavailable {
729            codec: HwCodec::Hevc,
730            reason: "no backend compiled in".to_string(),
731        };
732        let text = err.to_string();
733        assert!(text.contains("HEVC"), "{text}");
734        assert!(text.contains("no backend compiled in"), "{text}");
735
736        assert_eq!(HwCodec::Av1.to_string(), "AV1");
737        assert_eq!(HwBackend::Vaapi.to_string(), "VAAPI");
738    }
739}