Skip to main content

zvidlib_hevc_decoder/
lib.rs

1//! Native HEVC/H.265 decoding with platform acceleration and a dependency-free software fallback.
2//!
3//! The software decoder is portable and also builds for `wasm32`, where it is the browser's
4//! fallback when WebCodecs cannot decode a track (issue #504); the platform backends and the
5//! encoder's public factory stay native-only.
6
7// internal — exposed for the criterion benchmark suite; not part of the stable API
8#[cfg(not(target_arch = "wasm32"))]
9pub mod decode_bench;
10// internal — exposed for the stage-attribution example; not part of the stable API
11#[cfg(not(target_arch = "wasm32"))]
12#[doc(hidden)]
13pub use engine::inter_pred::narrow_interp;
14// internal — exposed for the stage-attribution example; not part of the stable API
15#[cfg(not(target_arch = "wasm32"))]
16#[doc(hidden)]
17pub use engine::profile as decode_profile;
18// internal — the HEVC engine, shared with the encoder crate; not part of the stable API
19#[doc(hidden)]
20pub use zvidlib_hevc::engine;
21
22#[allow(unused_imports)]
23use zvidlib_color::color_convert;
24#[allow(unused_imports)]
25use zvidlib_core::*;
26// The platform backends the factory selects between.
27#[cfg(all(
28    feature = "hardware",
29    any(windows, target_os = "linux"),
30    target_pointer_width = "64"
31))]
32use zvidlib_hardware::nvdec;
33// internal — the hardware backends' readback seam, re-exported for the
34// benchmark suite; not part of the stable API
35#[cfg(all(feature = "hardware", not(target_arch = "wasm32")))]
36#[allow(unused_imports)]
37#[doc(hidden)]
38pub use zvidlib_hardware::readback;
39#[cfg(all(feature = "hardware", target_os = "macos"))]
40use zvidlib_hardware::videotoolbox;
41#[cfg(all(feature = "hardware", windows))]
42use zvidlib_hardware::windows_mf;
43// The containers and conformance harness the tests read their fixtures with.
44#[cfg(test)]
45#[allow(unused_imports)]
46use zvidlib_container::*;
47
48use std::cmp::Reverse;
49use std::collections::BinaryHeap;
50use std::panic::{AssertUnwindSafe, catch_unwind};
51
52use crate::{
53    CancellationToken, Codec, CodecImplementation, CodecProfile, CodecSupport, ColorRange,
54    DecodedVideoFrame, EncodedVideoSample, Error, ErrorKind, FrameIndex, HardwarePreference,
55    Limits, PixelFormat, Plane, Result, VideoDecoder, VideoDecoderConfig, VideoDecoderFactory,
56    VideoFrame,
57};
58use engine::hvcc::{HvccRecord, parse_hvcc, split_length_prefixed};
59use engine::picture::{Picture, Plane as HevcPlane, sub_wh_c};
60use engine::sequence::{DecodedFrame, SequenceDecoder, SequenceError};
61use engine::sps::SeqParameterSet;
62
63const DEFAULT_REORDER_DEPTH: usize = 8;
64
65/// Returns the native HEVC Main and Main 10 decoder backend.
66///
67/// For 8-bit Main, `Prefer` and `Require` select NVIDIA NVDEC on supported 64-bit Windows/Linux
68/// hosts, D3D11-aware Media Foundation on Windows, or VideoToolbox on macOS. `Prefer` falls back to
69/// the dependency-free software decoder when acceleration is unavailable; `Avoid` always selects
70/// software. Main 10 tracks with more than 8 bits per sample are always decoded in software, since
71/// none of the accelerated backends is wired for them, so `Require` reports them unavailable.
72pub fn native_hevc_video_decoder_factory() -> impl VideoDecoderFactory {
73    HevcDecoderFactory
74}
75
76#[derive(Clone, Copy, Debug)]
77struct HevcDecoderFactory;
78
79impl VideoDecoderFactory for HevcDecoderFactory {
80    fn capability(&self, configuration: &VideoDecoderConfig) -> CodecSupport {
81        if let unsupported @ (CodecSupport::UnsupportedCodec
82        | CodecSupport::UnsupportedProfile
83        | CodecSupport::InvalidConfiguration { .. }) =
84            self.capability_without_hardware(configuration)
85        {
86            return unsupported;
87        }
88        let parsed = match ParsedConfiguration::parse(configuration, &Limits::default()) {
89            Ok(parsed) => parsed,
90            Err(error) => return invalid_configuration(error.message()),
91        };
92        if configuration.hardware != HardwarePreference::Avoid
93            && !parsed.high_bit_depth
94            && hardware_available(configuration)
95        {
96            return CodecSupport::Supported {
97                implementation: CodecImplementation::Hardware,
98            };
99        }
100        if configuration.hardware == HardwarePreference::Require {
101            return CodecSupport::HardwareUnavailable;
102        }
103        CodecSupport::Supported {
104            implementation: CodecImplementation::Software,
105        }
106    }
107
108    fn create(
109        &self,
110        configuration: &VideoDecoderConfig,
111        limits: &Limits,
112    ) -> Result<Box<dyn VideoDecoder>> {
113        match self.capability_without_hardware(configuration) {
114            CodecSupport::Supported { .. } => {}
115            CodecSupport::UnsupportedCodec => {
116                return Err(Error::new(
117                    ErrorKind::Unsupported,
118                    "native HEVC decoder requires HEVC",
119                ));
120            }
121            CodecSupport::UnsupportedProfile => {
122                return Err(Error::new(
123                    ErrorKind::Unsupported,
124                    "native HEVC decoder supports the Main and Main 10 profiles",
125                ));
126            }
127            CodecSupport::HardwareUnavailable => unreachable!("hardware is not checked here"),
128            CodecSupport::InvalidConfiguration { reason } => {
129                return Err(Error::new(ErrorKind::InvalidInput, reason));
130            }
131            _ => {
132                return Err(Error::new(
133                    ErrorKind::Unsupported,
134                    "native HEVC decoder does not support this configuration",
135                ));
136            }
137        }
138        let parsed = ParsedConfiguration::parse(configuration, limits)?;
139        if configuration.hardware == HardwarePreference::Require && parsed.high_bit_depth {
140            // Every accelerated backend below is 8-bit Main only, and would only notice a 10-bit
141            // sequence once decoding had started.
142            return Err(Error::new(
143                ErrorKind::Unsupported,
144                "hardware HEVC decoding is unavailable (no accelerated backend decodes more than 8 bits per sample)",
145            ));
146        }
147        if configuration.hardware != HardwarePreference::Avoid && !parsed.high_bit_depth {
148            #[cfg_attr(
149                any(target_arch = "wasm32", not(feature = "hardware")),
150                allow(unused_mut)
151            )]
152            let mut hardware_errors = Vec::<String>::new();
153            #[cfg(all(
154                feature = "hardware",
155                any(windows, target_os = "linux"),
156                target_pointer_width = "64"
157            ))]
158            match nvdec::create(configuration, limits, &parsed.record) {
159                Ok(decoder) => return Ok(decoder),
160                Err(error) => hardware_errors.push(format!("NVDEC: {}", error.message())),
161            }
162            #[cfg(all(feature = "hardware", windows))]
163            match windows_mf::create(configuration, limits, &parsed.record) {
164                Ok(decoder) => return Ok(decoder),
165                Err(error) => {
166                    hardware_errors.push(format!("Media Foundation: {}", error.message()));
167                }
168            }
169            #[cfg(all(feature = "hardware", target_os = "macos"))]
170            match videotoolbox::create(configuration, limits, &parsed.record) {
171                Ok(decoder) => return Ok(decoder),
172                Err(error) => {
173                    hardware_errors.push(format!("VideoToolbox: {}", error.message()));
174                }
175            }
176            if configuration.hardware == HardwarePreference::Require {
177                let detail = if hardware_errors.is_empty() {
178                    "no accelerated backend exists for this target".to_owned()
179                } else {
180                    hardware_errors.join("; ")
181                };
182                return Err(Error::new(
183                    ErrorKind::Unsupported,
184                    format!("hardware HEVC decoding is unavailable ({detail})"),
185                ));
186            }
187        }
188        Ok(Box::new(HevcDecoder::new(
189            configuration.clone(),
190            *limits,
191            parsed,
192        )?))
193    }
194}
195
196impl HevcDecoderFactory {
197    fn capability_without_hardware(&self, configuration: &VideoDecoderConfig) -> CodecSupport {
198        if configuration.codec != Codec::Hevc {
199            return CodecSupport::UnsupportedCodec;
200        }
201        if !matches!(
202            configuration.profile,
203            CodecProfile::HevcMain | CodecProfile::HevcMain10
204        ) {
205            return CodecSupport::UnsupportedProfile;
206        }
207        if configuration.output_format != PixelFormat::Rgba8 {
208            return invalid_configuration("native HEVC decoding currently outputs RGBA8");
209        }
210        if configuration.color_range != ColorRange::Limited {
211            return invalid_configuration("native HEVC RGBA output requires limited-range input");
212        }
213        CodecSupport::Supported {
214            implementation: CodecImplementation::Software,
215        }
216    }
217}
218
219fn hardware_available(_configuration: &VideoDecoderConfig) -> bool {
220    // The probes for the backends this target builds, in preference order.
221    let backends: &[fn(VideoDimensions) -> bool] = &[
222        #[cfg(all(
223            feature = "hardware",
224            any(windows, target_os = "linux"),
225            target_pointer_width = "64"
226        ))]
227        nvdec::is_available,
228        #[cfg(all(feature = "hardware", windows))]
229        windows_mf::is_available,
230        #[cfg(all(feature = "hardware", target_os = "macos"))]
231        videotoolbox::is_available,
232    ];
233    backends
234        .iter()
235        .any(|is_available| is_available(_configuration.coded_dimensions))
236}
237
238fn invalid_configuration(reason: impl Into<String>) -> CodecSupport {
239    CodecSupport::InvalidConfiguration {
240        reason: reason.into(),
241    }
242}
243
244#[derive(Debug)]
245struct ParsedConfiguration {
246    record: HvccRecord,
247    /// Whether either component carries more than 8 bits per sample, which only the software
248    /// decoder handles.
249    high_bit_depth: bool,
250}
251
252impl ParsedConfiguration {
253    fn parse(configuration: &VideoDecoderConfig, limits: &Limits) -> Result<Self> {
254        if configuration.configuration.len() as u64 > limits.max_allocation_bytes {
255            return Err(limit("HEVC configuration exceeds the allocation limit"));
256        }
257        let payload = hvcc_payload(&configuration.configuration)?;
258        let record = parse_hvcc(payload)
259            .map_err(|error| malformed(format!("invalid hvcC configuration: {error}")))?;
260        let max_bit_depth_minus8 = max_bit_depth_minus8(configuration.profile);
261        let profile_idc_allowed = match configuration.profile {
262            // A Main 10 decoder also decodes Main.
263            CodecProfile::HevcMain10 => matches!(record.general_profile_idc, 1 | 2),
264            _ => record.general_profile_idc == 1,
265        };
266        if !profile_idc_allowed
267            || record.bit_depth_luma_minus8 > max_bit_depth_minus8
268            || record.bit_depth_chroma_minus8 > max_bit_depth_minus8
269            || record.chroma_format_idc != 1
270        {
271            return Err(Error::new(
272                ErrorKind::Unsupported,
273                match configuration.profile {
274                    CodecProfile::HevcMain10 => {
275                        "native HEVC decoder requires an 8- to 10-bit 4:2:0 Main or Main 10 hvcC configuration"
276                    }
277                    _ => {
278                        "native HEVC decoder requires an 8-bit 4:2:0 Main-profile hvcC configuration"
279                    }
280                },
281            ));
282        }
283        let sps_unit = record
284            .nal_units
285            .iter()
286            .find(|unit| unit.header.nal_unit_type == 33)
287            .ok_or_else(|| malformed("hvcC configuration does not contain an SPS"))?;
288        let sps = SeqParameterSet::parse(&sps_unit.rbsp)
289            .map_err(|error| malformed(format!("invalid HEVC SPS: {error}")))?;
290        validate_sps(&sps, configuration, limits)?;
291        let high_bit_depth = record.bit_depth_luma_minus8 != 0
292            || record.bit_depth_chroma_minus8 != 0
293            || sps.bit_depth_luma_minus8 != 0
294            || sps.bit_depth_chroma_minus8 != 0;
295        Ok(Self {
296            record,
297            high_bit_depth,
298        })
299    }
300}
301
302/// The deepest samples `profile` allows, as `bit_depth_*_minus8`: 8 bits for Main, 10 for
303/// Main 10.
304fn max_bit_depth_minus8(profile: CodecProfile) -> u8 {
305    match profile {
306        CodecProfile::HevcMain10 => 2,
307        _ => 0,
308    }
309}
310
311fn hvcc_payload(configuration: &[u8]) -> Result<&[u8]> {
312    if configuration.len() >= 8 && &configuration[4..8] == b"hvcC" {
313        let declared = u32::from_be_bytes(configuration[..4].try_into().expect("four bytes"));
314        if usize::try_from(declared).ok() != Some(configuration.len()) {
315            return Err(malformed(
316                "hvcC box size does not match its configuration bytes",
317            ));
318        }
319        return Ok(&configuration[8..]);
320    }
321    if configuration.first() == Some(&1) {
322        return Ok(configuration);
323    }
324    Err(malformed("HEVC configuration is not an hvcC record"))
325}
326
327fn validate_sps(
328    sps: &SeqParameterSet,
329    configuration: &VideoDecoderConfig,
330    limits: &Limits,
331) -> Result<()> {
332    let max_bit_depth_minus8 = max_bit_depth_minus8(configuration.profile);
333    if sps.chroma_format_idc != 1
334        || sps.separate_color_plane_flag
335        || sps.bit_depth_luma_minus8 > max_bit_depth_minus8
336        || sps.bit_depth_chroma_minus8 > max_bit_depth_minus8
337    {
338        return Err(Error::new(
339            ErrorKind::Unsupported,
340            match configuration.profile {
341                CodecProfile::HevcMain10 => {
342                    "native HEVC decoder requires SPS 8- to 10-bit 4:2:0 syntax"
343                }
344                _ => "native HEVC decoder requires SPS Main-profile 8-bit 4:2:0 syntax",
345            },
346        ));
347    }
348    if sps.pic_width_in_luma_samples > limits.max_width
349        || sps.pic_height_in_luma_samples > limits.max_height
350    {
351        return Err(limit("HEVC SPS coded dimensions exceed configured limits"));
352    }
353    let (sub_width, sub_height) = sub_wh_c(sps.chroma_format_idc);
354    let cropped_width = usize::try_from(sps.pic_width_in_luma_samples)
355        .ok()
356        .and_then(|width| {
357            let crop = usize::try_from(
358                sps.conformance_window.left_offset + sps.conformance_window.right_offset,
359            )
360            .ok()?
361            .checked_mul(sub_width)?;
362            width.checked_sub(crop)
363        })
364        .ok_or_else(|| malformed("HEVC SPS horizontal conformance window is invalid"))?;
365    let cropped_height = usize::try_from(sps.pic_height_in_luma_samples)
366        .ok()
367        .and_then(|height| {
368            let crop = usize::try_from(
369                sps.conformance_window.top_offset + sps.conformance_window.bottom_offset,
370            )
371            .ok()?
372            .checked_mul(sub_height)?;
373            height.checked_sub(crop)
374        })
375        .ok_or_else(|| malformed("HEVC SPS vertical conformance window is invalid"))?;
376    if cropped_width != configuration.coded_dimensions.width as usize
377        || cropped_height != configuration.coded_dimensions.height as usize
378    {
379        return Err(malformed(
380            "HEVC SPS display dimensions do not match decoder configuration",
381        ));
382    }
383    let pixels = u64::from(sps.pic_width_in_luma_samples)
384        .checked_mul(u64::from(sps.pic_height_in_luma_samples))
385        .ok_or_else(|| limit("HEVC picture dimensions overflow"))?;
386    let picture_bytes = pixels
387        .checked_mul(6)
388        .ok_or_else(|| limit("HEVC picture allocation overflows"))?;
389    let output_bytes = u64::from(configuration.coded_dimensions.width)
390        .checked_mul(u64::from(configuration.coded_dimensions.height))
391        .and_then(|value| value.checked_mul(4))
392        .ok_or_else(|| limit("HEVC RGBA output allocation overflows"))?;
393    let ordering = sps.sub_layer_ordering_info[usize::from(sps.max_sub_layers_minus1)];
394    let retained_pictures = u64::from(ordering.max_dec_pic_buffering_minus1)
395        .checked_add(2)
396        .ok_or_else(|| limit("HEVC decoded-picture-buffer size overflows"))?;
397    let decoder_bytes = picture_bytes
398        .checked_mul(retained_pictures)
399        .and_then(|value| value.checked_add(output_bytes))
400        .ok_or_else(|| limit("HEVC decoder allocation budget overflows"))?;
401    if decoder_bytes > limits.max_allocation_bytes {
402        return Err(limit(
403            "HEVC decoded-picture buffer exceeds the allocation limit",
404        ));
405    }
406    Ok(())
407}
408
409#[derive(Debug)]
410struct HevcDecoder {
411    configuration: VideoDecoderConfig,
412    limits: Limits,
413    configuration_nals: Vec<engine::nal::NalUnit>,
414    nal_length_size: usize,
415    sequence: SequenceDecoder,
416    reorder: Vec<DecodedFrame>,
417    presentation_indexes: BinaryHeap<Reverse<FrameIndex>>,
418    /// Whether a caller wants the pictures being decoded, or is only walking past them.
419    output_wanted: bool,
420}
421
422impl HevcDecoder {
423    fn new(
424        configuration: VideoDecoderConfig,
425        limits: Limits,
426        parsed: ParsedConfiguration,
427    ) -> Result<Self> {
428        let configuration_nals = parsed.record.nal_units;
429        let nal_length_size = parsed.record.length_size;
430        let mut decoder = Self {
431            configuration,
432            limits,
433            configuration_nals,
434            nal_length_size,
435            sequence: SequenceDecoder::new(),
436            reorder: Vec::new(),
437            presentation_indexes: BinaryHeap::new(),
438            output_wanted: true,
439        };
440        decoder.reinitialize()?;
441        Ok(decoder)
442    }
443
444    fn reinitialize(&mut self) -> Result<()> {
445        self.sequence = SequenceDecoder::new();
446        for unit in self.configuration_nals.clone() {
447            self.sequence.push_nal_unit(unit).map_err(sequence_error)?;
448        }
449        self.reorder.clear();
450        self.presentation_indexes.clear();
451        Ok(())
452    }
453
454    fn collect(&mut self, flush: bool) -> Result<Vec<DecodedVideoFrame>> {
455        let pictures = self.collect_pictures(flush)?;
456        if !self.output_wanted {
457            // The pictures are still taken from the reorder queue above, which is what keeps the
458            // decoder's own bookkeeping straight; only their conversion is skipped.
459            return Ok(Vec::new());
460        }
461        let mut output = Vec::with_capacity(pictures.len());
462        for (presentation_index, picture) in pictures {
463            output.push(DecodedVideoFrame {
464                presentation_index,
465                frame: picture_to_rgba(&picture, &self.configuration, &self.limits)?,
466            });
467        }
468        Ok(output)
469    }
470
471    /// The output pictures ready at this point, in presentation order, before
472    /// color conversion.
473    ///
474    /// Issue #220: this is the decoder's own product. [`collect`] converts each
475    /// one to RGBA, which is the round trip an application pays but is not
476    /// decoding, and `hevc_decoder_bench` times the two intervals separately so
477    /// a whole-frame SIMD ratio is not diluted by a stage no HEVC kernel
478    /// touches.
479    ///
480    /// [`collect`]: Self::collect
481    fn collect_pictures(&mut self, flush: bool) -> Result<Vec<(FrameIndex, Picture)>> {
482        self.reorder.extend(self.sequence.take_decoded());
483        self.reorder
484            .sort_by_key(|frame| (frame.cvs_index, frame.poc));
485        let depth = if flush {
486            0
487        } else {
488            self.sequence
489                .max_num_reorder_pics()
490                .map_or(DEFAULT_REORDER_DEPTH, |depth| depth as usize)
491        };
492        let mut output = Vec::new();
493        while self.reorder.len() > depth {
494            let decoded = self.reorder.remove(0);
495            if !decoded.output {
496                continue;
497            }
498            let presentation_index = self
499                .presentation_indexes
500                .pop()
501                .ok_or_else(|| {
502                    malformed("HEVC decoder produced a picture without a submitted identity")
503                })?
504                .0;
505            output.push((presentation_index, decoded.picture));
506        }
507        Ok(output)
508    }
509
510    /// Parses one access unit into the sequence decoder, without collecting
511    /// anything it made ready.
512    ///
513    /// The push and the collect are separate so [`VideoDecoder::submit`] and
514    /// the benchmark surface's picture-only path share exactly the same
515    /// bitstream handling and differ only in what they do with the result.
516    fn push_sample(
517        &mut self,
518        sample: &EncodedVideoSample,
519        cancellation: &CancellationToken,
520    ) -> Result<()> {
521        check_canceled(cancellation)?;
522        if sample.data.len() as u64 > self.limits.max_allocation_bytes {
523            return Err(limit("HEVC access unit exceeds the allocation limit"));
524        }
525        let units = split_length_prefixed(&sample.data, self.nal_length_size)
526            .map_err(|error| malformed(format!("invalid HEVC access unit: {error}")))?;
527        self.presentation_indexes
528            .push(Reverse(sample.presentation_index));
529        let skipped_before = self.sequence.skipped_pictures();
530        let result = catch_unwind(AssertUnwindSafe(|| {
531            for unit in units {
532                self.sequence.push_nal_unit(unit)?;
533            }
534            Ok::<(), SequenceError>(())
535        }));
536        match result {
537            Ok(Ok(())) => {
538                // A leading picture the decoder discarded because decoding
539                // started at its IRAP will never be output, so its identity
540                // must not be handed to the next picture that is.
541                if self.sequence.skipped_pictures() != skipped_before {
542                    self.presentation_indexes
543                        .retain(|Reverse(index)| *index != sample.presentation_index);
544                }
545                Ok(())
546            }
547            Ok(Err(error)) => Err(sequence_error(error)),
548            Err(_) => Err(malformed(
549                "HEVC bitstream triggered an invalid decoder state",
550            )),
551        }
552    }
553
554    /// Decodes one access unit and stops at the decoded pictures.
555    ///
556    /// The picture-only half of the issue #220 split, used by
557    /// [`crate::hevc_decoder_bench`].
558    #[cfg(not(target_arch = "wasm32"))]
559    fn submit_pictures(
560        &mut self,
561        sample: &EncodedVideoSample,
562        cancellation: &CancellationToken,
563    ) -> Result<Vec<Picture>> {
564        self.push_sample(sample, cancellation)?;
565        Ok(self
566            .collect_pictures(false)?
567            .into_iter()
568            .map(|(_, picture)| picture)
569            .collect())
570    }
571}
572
573impl VideoDecoder for HevcDecoder {
574    fn submit(
575        &mut self,
576        sample: &EncodedVideoSample,
577        cancellation: &CancellationToken,
578    ) -> Result<Vec<DecodedVideoFrame>> {
579        self.push_sample(sample, cancellation)?;
580        self.collect(false)
581    }
582
583    fn drain(&mut self, cancellation: &CancellationToken) -> Result<Vec<DecodedVideoFrame>> {
584        check_canceled(cancellation)?;
585        match catch_unwind(AssertUnwindSafe(|| self.sequence.flush())) {
586            Ok(Ok(())) => self.collect(true),
587            Ok(Err(error)) => Err(sequence_error(error)),
588            Err(_) => Err(malformed(
589                "HEVC bitstream triggered an invalid decoder state while draining",
590            )),
591        }
592    }
593
594    fn reset(&mut self) -> Result<()> {
595        self.reinitialize()
596    }
597
598    fn set_output_wanted(&mut self, wanted: bool) {
599        self.output_wanted = wanted;
600    }
601}
602
603/// Issue #189 stage attribution: color conversion is not decoding, but it is
604/// on the path every whole-frame measurement takes, so it is reported as its
605/// own stage rather than left in the unattributed remainder.
606fn picture_to_rgba(
607    picture: &Picture,
608    configuration: &VideoDecoderConfig,
609    limits: &Limits,
610) -> Result<VideoFrame> {
611    let _profile = engine::profile::scope(engine::profile::Stage::ColorConvert);
612    let max_bit_depth = 8 + max_bit_depth_minus8(configuration.profile);
613    if picture.chroma_array_type() != 1
614        || !(8..=max_bit_depth).contains(&picture.bit_depth_luma())
615        || !(8..=max_bit_depth).contains(&picture.bit_depth_chroma())
616    {
617        return Err(Error::new(
618            ErrorKind::Unsupported,
619            "decoded HEVC picture is not 4:2:0 at a bit depth its profile allows",
620        ));
621    }
622    let width = configuration.coded_dimensions.width as usize;
623    let height = configuration.coded_dimensions.height as usize;
624    if picture.width_luma() < width || picture.height_luma() < height {
625        return Err(malformed(
626            "decoded HEVC picture is smaller than its display dimensions",
627        ));
628    }
629    let stride = width
630        .checked_mul(4)
631        .ok_or_else(|| limit("HEVC RGBA stride overflows"))?;
632    let length = stride
633        .checked_mul(height)
634        .ok_or_else(|| limit("HEVC RGBA allocation overflows"))?;
635    if length as u64 > limits.max_allocation_bytes {
636        return Err(limit("HEVC RGBA output exceeds the allocation limit"));
637    }
638    let luma = picture.plane(HevcPlane::Luma);
639    let cb = picture.plane(HevcPlane::Cb);
640    let cr = picture.plane(HevcPlane::Cr);
641    let chroma_width = picture.plane_dims(HevcPlane::Cb).0;
642    let mut rgba = vec![0_u8; length];
643    if picture.bit_depth_luma() == 8 && picture.bit_depth_chroma() == 8 {
644        color_convert::convert_yuv420_to_rgba(
645            luma,
646            picture.width_luma(),
647            cb,
648            cr,
649            chroma_width,
650            width,
651            height,
652            &mut rgba,
653            stride,
654        );
655    } else {
656        color_convert::convert_high_bit_depth_yuv420_to_rgba(
657            luma,
658            picture.width_luma(),
659            picture.bit_depth_luma(),
660            cb,
661            cr,
662            chroma_width,
663            picture.bit_depth_chroma(),
664            width,
665            height,
666            &mut rgba,
667            stride,
668        );
669    }
670    VideoFrame::new(
671        configuration.coded_dimensions,
672        PixelFormat::Rgba8,
673        configuration.color_range,
674        vec![Plane { data: rgba, stride }],
675        limits,
676    )
677}
678
679fn check_canceled(cancellation: &CancellationToken) -> Result<()> {
680    if cancellation.is_canceled() {
681        Err(Error::new(ErrorKind::Canceled, "codec operation canceled"))
682    } else {
683        Ok(())
684    }
685}
686
687fn sequence_error(error: SequenceError) -> Error {
688    match error {
689        SequenceError::Unsupported(message) => Error::new(ErrorKind::Unsupported, message),
690        other => malformed(format!("invalid HEVC bitstream: {other}")),
691    }
692}
693
694fn malformed(message: impl Into<String>) -> Error {
695    Error::new(ErrorKind::MalformedMedia, message)
696}
697
698fn limit(message: impl Into<String>) -> Error {
699    Error::new(ErrorKind::ResourceLimit, message)
700}
701
702/// The SIMD dispatch sites in this crate, each with the instruction set it
703/// resolves to right now. `zvidlib::simd::active_by_site` reports every crate's
704/// sites together and documents what each one covers.
705#[doc(hidden)]
706#[must_use]
707pub fn simd_sites() -> Vec<(&'static str, SimdIsa)> {
708    // The HEVC kernels have no vector backend on `wasm32`, so they are not
709    // reported there.
710    #[cfg(target_arch = "wasm32")]
711    return Vec::new();
712    #[cfg(not(target_arch = "wasm32"))]
713    vec![
714        (
715            "hevc_prediction_filters",
716            engine::simd::detected_isa().as_simd_isa(),
717        ),
718        (
719            "hevc_transforms",
720            engine::transform_simd::detected().as_simd_isa(),
721        ),
722    ]
723}
724
725#[cfg(test)]
726mod tests {
727    use super::*;
728
729    #[test]
730    fn rejects_truncated_configuration_without_panicking() {
731        let limits = Limits::default();
732        let configuration = VideoDecoderConfig {
733            codec: Codec::Hevc,
734            profile: CodecProfile::HevcMain,
735            coded_dimensions: crate::VideoDimensions::new(16, 16, &limits).unwrap(),
736            output_format: PixelFormat::Rgba8,
737            color_range: ColorRange::Limited,
738            hardware: HardwarePreference::Avoid,
739            configuration: vec![1, 2, 3],
740        };
741        let support = native_hevc_video_decoder_factory().capability(&configuration);
742        assert!(matches!(support, CodecSupport::InvalidConfiguration { .. }));
743    }
744
745    fn block_on<T>(future: impl std::future::Future<Output = T>) -> T {
746        use std::task::{Context, Poll, Waker};
747        let mut future = Box::pin(future);
748        let mut context = Context::from_waker(Waker::noop());
749        loop {
750            if let Poll::Ready(value) = future.as_mut().poll(&mut context) {
751                return value;
752            }
753        }
754    }
755
756    /// The 12-frame HEVC Main 10 fixture's decoder configuration and decode-order samples.
757    fn main10_fixture(
758        profile: CodecProfile,
759        hardware: HardwarePreference,
760    ) -> (VideoDecoderConfig, Vec<EncodedVideoSample>) {
761        use crate::Mp4DemuxerOptions;
762        use crate::io::MemorySource;
763        use crate::mp4_demux::Mp4Demuxer;
764
765        let limits = Limits::default();
766        let source = MemorySource::new(
767            include_bytes!("../tests/fixtures/bbb_hevc_main10_128x72.mp4").to_vec(),
768        );
769        let movie = block_on(Mp4Demuxer::open(&source, Mp4DemuxerOptions::default())).unwrap();
770        let track = &movie.tracks[0];
771        let samples = block_on(track.to_encoded_video_samples(&source, &limits)).unwrap();
772        let configuration = VideoDecoderConfig {
773            codec: Codec::Hevc,
774            profile,
775            coded_dimensions: track.dimensions.unwrap(),
776            output_format: PixelFormat::Rgba8,
777            color_range: ColorRange::Limited,
778            hardware,
779            configuration: track.decoder_config.clone(),
780        };
781        (configuration, samples)
782    }
783
784    /// Issue #508: the 10-bit samples themselves are FFmpeg's `yuv420p10le` decode of the same
785    /// fixture exactly, and their RGBA conversion is the fixture's, which applies the documented
786    /// matrix to that FFmpeg decode.
787    #[test]
788    fn main10_pictures_match_an_independent_reference_decode() {
789        let digests = |fixture: &str| {
790            fixture
791                .lines()
792                .map(|line| line.split_once(' ').unwrap().1.to_owned())
793                .collect::<Vec<_>>()
794        };
795        let expected = digests(include_str!(
796            "../tests/fixtures/bbb_hevc_main10_128x72_yuv420p10le.sha256"
797        ));
798        let expected_rgba = digests(include_str!(
799            "../tests/fixtures/bbb_hevc_main10_128x72_rgba.sha256"
800        ));
801        let limits = Limits::default();
802        let (configuration, samples) =
803            main10_fixture(CodecProfile::HevcMain10, HardwarePreference::Avoid);
804        let parsed = ParsedConfiguration::parse(&configuration, &limits).unwrap();
805        assert!(parsed.high_bit_depth);
806        let mut decoder = HevcDecoder::new(configuration.clone(), limits, parsed).unwrap();
807        let cancellation = CancellationToken::new();
808        let mut pictures = Vec::new();
809        for sample in &samples {
810            decoder.push_sample(sample, &cancellation).unwrap();
811            pictures.extend(decoder.collect_pictures(false).unwrap());
812        }
813        decoder.sequence.flush().unwrap();
814        pictures.extend(decoder.collect_pictures(true).unwrap());
815        pictures.sort_by_key(|(index, _)| *index);
816
817        assert_eq!(pictures.len(), expected.len());
818        for (((index, picture), expected), expected_rgba) in
819            pictures.iter().zip(&expected).zip(&expected_rgba)
820        {
821            assert_eq!(picture.bit_depth_luma(), 10);
822            assert_eq!(picture.bit_depth_chroma(), 10);
823            let digest = crate::conformance::FrameDigest(crate::conformance::sha256(
824                &picture.to_planar_le16(),
825            ));
826            assert_eq!(&digest.to_hex(), expected, "frame {}", index.0);
827            let rgba = picture_to_rgba(picture, &configuration, &limits).unwrap();
828            let digest = crate::conformance::FrameDigest::from_frame(&rgba).unwrap();
829            assert_eq!(&digest.to_hex(), expected_rgba, "frame {} RGBA", index.0);
830        }
831    }
832
833    #[test]
834    fn main10_is_decoded_in_software_whatever_the_hardware_preference() {
835        let factory = native_hevc_video_decoder_factory();
836        for hardware in [HardwarePreference::Avoid, HardwarePreference::Prefer] {
837            let (configuration, _) = main10_fixture(CodecProfile::HevcMain10, hardware);
838            assert_eq!(
839                factory.capability(&configuration),
840                CodecSupport::Supported {
841                    implementation: CodecImplementation::Software
842                },
843                "{hardware:?}"
844            );
845        }
846        let (configuration, _) =
847            main10_fixture(CodecProfile::HevcMain10, HardwarePreference::Require);
848        assert_eq!(
849            factory.capability(&configuration),
850            CodecSupport::HardwareUnavailable
851        );
852        let error = factory
853            .create(&configuration, &Limits::default())
854            .err()
855            .expect("no accelerated backend decodes Main 10");
856        assert_eq!(error.kind(), ErrorKind::Unsupported);
857    }
858
859    #[test]
860    fn a_main_profile_configuration_still_refuses_a_10_bit_track() {
861        let (configuration, _) = main10_fixture(CodecProfile::HevcMain, HardwarePreference::Avoid);
862        let factory = native_hevc_video_decoder_factory();
863        assert!(matches!(
864            factory.capability(&configuration),
865            CodecSupport::InvalidConfiguration { .. }
866        ));
867        let error = factory
868            .create(&configuration, &Limits::default())
869            .err()
870            .expect("HEVC Main is 8-bit");
871        assert_eq!(error.kind(), ErrorKind::Unsupported);
872    }
873
874    #[test]
875    fn canonical_conversion_uses_decoder_integer_rounding() {
876        use color_convert::{clip_u8, multiply_high};
877
878        assert_eq!(multiply_high(-8, -3_209), 0);
879        assert_eq!(clip_u8(multiply_high(0, 9_539)), 0);
880    }
881
882    /// Issue #506: the 32-frame-cadence fixture is an open-GOP stream. Each CRA picture after
883    /// the first is followed in decode order by RASL pictures presented before it, and those
884    /// reference pictures from before the CRA. Every frame from 29 onwards used to fail from a
885    /// fresh reader: 29 to 31 because the reader started at the CRA that leads them, and later
886    /// frames because a decode started at a CRA tried to reconstruct its RASL pictures. Every
887    /// frame must now match FFmpeg's decode walked in order, in reverse and alternating, and
888    /// the frames around CRA boundaries must match it from a fresh reader.
889    #[test]
890    fn open_gop_leading_pictures_decode_from_every_starting_point() {
891        use crate::io::MemorySource;
892        use crate::{
893            ExactFrameReader, FrameDigest, FrameIndex, Mp4DemuxerOptions,
894            VideoDecoderConformanceVector, VideoDimensions, verify_video_decoder_conformance,
895        };
896
897        let expected = include_str!("../tests/fixtures/bbb_hevc_512x288_gop32_rgba.sha256")
898            .lines()
899            .map(|line| FrameDigest::from_hex(line.split_once(' ').unwrap().1).unwrap())
900            .collect::<Vec<_>>();
901        let limits = Limits::default();
902        let source = MemorySource::new(
903            include_bytes!("../tests/fixtures/bbb_hevc_512x288_gop32.mp4").to_vec(),
904        );
905        let vector = block_on(VideoDecoderConformanceVector::from_mp4(
906            "open-GOP HEVC Main fixture",
907            &source,
908            Mp4DemuxerOptions::default(),
909            1,
910            VideoDecoderConfig {
911                codec: Codec::Hevc,
912                profile: CodecProfile::HevcMain,
913                coded_dimensions: VideoDimensions::new(512, 288, &limits).unwrap(),
914                output_format: PixelFormat::Rgba8,
915                color_range: ColorRange::Limited,
916                hardware: HardwarePreference::Avoid,
917                configuration: Vec::new(),
918            },
919            &expected,
920        ))
921        .unwrap();
922        assert_eq!(vector.samples.len(), 768);
923        // The fixture's shape, which is what makes it a regression test: the CRA at frame 32
924        // is followed in decode order by the RASL pictures 30, 29 and 31.
925        let order = vector.samples[29..33]
926            .iter()
927            .map(|sample| (sample.presentation_index.0, sample.random_access))
928            .collect::<Vec<_>>();
929        assert_eq!(order, [(32, true), (30, false), (29, false), (31, false)]);
930
931        let factory = native_hevc_video_decoder_factory();
932        let report = verify_video_decoder_conformance(&factory, &vector, limits).unwrap();
933        assert_eq!(report.frames_verified, 3 * 768);
934
935        // A fresh reader for every frame of the first two CRA boundaries, and for the leading
936        // and trailing pictures of later ones.
937        let cancellation = CancellationToken::new();
938        for index in (20..=72).chain([413, 415, 416, 767]) {
939            let expected = &expected[index];
940            let mut reader = ExactFrameReader::new(
941                &factory,
942                vector.configuration.clone(),
943                vector.samples.clone(),
944                limits,
945            )
946            .unwrap();
947            let frame = reader
948                .get(FrameIndex(index as u64), &cancellation)
949                .unwrap_or_else(|error| panic!("frame {index} from a fresh reader: {error}"));
950            assert_eq!(
951                FrameDigest::from_frame(&frame).unwrap(),
952                *expected,
953                "frame {index} from a fresh reader"
954            );
955            // A frame at or after a CRA is reached from that CRA, skipping its RASL pictures,
956            // not by walking the whole track from frame 0.
957            if index == 40 {
958                assert!(
959                    reader.statistics().samples_submitted <= 16,
960                    "frame 40 is decoded from the CRA at frame 32: {:?}",
961                    reader.statistics()
962                );
963            }
964        }
965    }
966}