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.
72///
73/// Frames are `Rgba8` by default. A 10-bit Main 10 track can instead request
74/// `PixelFormat::Yuv420p10` output, which returns the decoded Y, U and V samples unchanged in
75/// FFmpeg's `yuv420p10le` layout; 8- and 9-bit tracks refuse that format.
76pub fn native_hevc_video_decoder_factory() -> impl VideoDecoderFactory {
77    HevcDecoderFactory
78}
79
80#[derive(Clone, Copy, Debug)]
81struct HevcDecoderFactory;
82
83impl VideoDecoderFactory for HevcDecoderFactory {
84    fn capability(&self, configuration: &VideoDecoderConfig) -> CodecSupport {
85        if let unsupported @ (CodecSupport::UnsupportedCodec
86        | CodecSupport::UnsupportedProfile
87        | CodecSupport::InvalidConfiguration { .. }) =
88            self.capability_without_hardware(configuration)
89        {
90            return unsupported;
91        }
92        let parsed = match ParsedConfiguration::parse(configuration, &Limits::default()) {
93            Ok(parsed) => parsed,
94            Err(error) => return invalid_configuration(error.message()),
95        };
96        if configuration.hardware != HardwarePreference::Avoid
97            && !parsed.high_bit_depth
98            && hardware_available(configuration)
99        {
100            return CodecSupport::Supported {
101                implementation: CodecImplementation::Hardware,
102            };
103        }
104        if configuration.hardware == HardwarePreference::Require {
105            return CodecSupport::HardwareUnavailable;
106        }
107        CodecSupport::Supported {
108            implementation: CodecImplementation::Software,
109        }
110    }
111
112    fn create(
113        &self,
114        configuration: &VideoDecoderConfig,
115        limits: &Limits,
116    ) -> Result<Box<dyn VideoDecoder>> {
117        self.capability_without_hardware(configuration)
118            .into_result(&DECODER_SUPPORT_MESSAGES)?;
119        let parsed = ParsedConfiguration::parse(configuration, limits)?;
120        if configuration.hardware == HardwarePreference::Require && parsed.high_bit_depth {
121            // Every accelerated backend below is 8-bit Main only, and would only notice a 10-bit
122            // sequence once decoding had started.
123            return Err(Error::new(
124                ErrorKind::Unsupported,
125                "hardware HEVC decoding is unavailable (no accelerated backend decodes more than 8 bits per sample)",
126            ));
127        }
128        if configuration.hardware != HardwarePreference::Avoid && !parsed.high_bit_depth {
129            #[cfg_attr(
130                any(target_arch = "wasm32", not(feature = "hardware")),
131                allow(unused_mut)
132            )]
133            let mut hardware_errors = Vec::<String>::new();
134            #[cfg(all(
135                feature = "hardware",
136                any(windows, target_os = "linux"),
137                target_pointer_width = "64"
138            ))]
139            match nvdec::create(configuration, limits, &parsed.record) {
140                Ok(decoder) => return Ok(decoder),
141                Err(error) => hardware_errors.push(format!("NVDEC: {}", error.message())),
142            }
143            #[cfg(all(feature = "hardware", windows))]
144            match windows_mf::create(configuration, limits, &parsed.record) {
145                Ok(decoder) => return Ok(decoder),
146                Err(error) => {
147                    hardware_errors.push(format!("Media Foundation: {}", error.message()));
148                }
149            }
150            #[cfg(all(feature = "hardware", target_os = "macos"))]
151            match videotoolbox::create(configuration, limits, &parsed.record) {
152                Ok(decoder) => return Ok(decoder),
153                Err(error) => {
154                    hardware_errors.push(format!("VideoToolbox: {}", error.message()));
155                }
156            }
157            if configuration.hardware == HardwarePreference::Require {
158                let detail = if hardware_errors.is_empty() {
159                    "no accelerated backend exists for this target".to_owned()
160                } else {
161                    hardware_errors.join("; ")
162                };
163                return Err(Error::new(
164                    ErrorKind::Unsupported,
165                    format!("hardware HEVC decoding is unavailable ({detail})"),
166                ));
167            }
168        }
169        Ok(Box::new(HevcDecoder::new(
170            configuration.clone(),
171            *limits,
172            parsed,
173        )?))
174    }
175}
176
177impl HevcDecoderFactory {
178    fn capability_without_hardware(&self, configuration: &VideoDecoderConfig) -> CodecSupport {
179        if configuration.codec != Codec::Hevc {
180            return CodecSupport::UnsupportedCodec;
181        }
182        if !matches!(
183            configuration.profile,
184            CodecProfile::HevcMain | CodecProfile::HevcMain10
185        ) {
186            return CodecSupport::UnsupportedProfile;
187        }
188        if !matches!(
189            configuration.output_format,
190            PixelFormat::Rgba8 | PixelFormat::Yuv420p10
191        ) {
192            return invalid_configuration(
193                "native HEVC decoding outputs Rgba8, or Yuv420p10 for 10-bit Main 10 streams",
194            );
195        }
196        // `Yuv420p10` returns the samples unchanged, so only the RGBA conversion depends on the
197        // range.
198        if configuration.output_format == PixelFormat::Rgba8
199            && configuration.color_range != ColorRange::Limited
200        {
201            return invalid_configuration("native HEVC RGBA output requires limited-range input");
202        }
203        CodecSupport::Supported {
204            implementation: CodecImplementation::Software,
205        }
206    }
207}
208
209fn hardware_available(_configuration: &VideoDecoderConfig) -> bool {
210    // The probes for the backends this target builds, in preference order.
211    let backends: &[fn(VideoDimensions) -> bool] = &[
212        #[cfg(all(
213            feature = "hardware",
214            any(windows, target_os = "linux"),
215            target_pointer_width = "64"
216        ))]
217        nvdec::is_available,
218        #[cfg(all(feature = "hardware", windows))]
219        windows_mf::is_available,
220        #[cfg(all(feature = "hardware", target_os = "macos"))]
221        videotoolbox::is_available,
222    ];
223    backends
224        .iter()
225        .any(|is_available| is_available(_configuration.coded_dimensions))
226}
227
228fn invalid_configuration(reason: impl Into<String>) -> CodecSupport {
229    CodecSupport::InvalidConfiguration {
230        reason: reason.into(),
231    }
232}
233
234#[derive(Debug)]
235struct ParsedConfiguration {
236    record: HvccRecord,
237    /// Whether either component carries more than 8 bits per sample, which only the software
238    /// decoder handles.
239    high_bit_depth: bool,
240}
241
242impl ParsedConfiguration {
243    fn parse(configuration: &VideoDecoderConfig, limits: &Limits) -> Result<Self> {
244        if configuration.configuration.len() as u64 > limits.max_allocation_bytes {
245            return Err(limit("HEVC configuration exceeds the allocation limit"));
246        }
247        let payload = zvidlib_core::avc_config::configuration_record_payload(
248            &configuration.configuration,
249            "hvcC",
250            "HEVC",
251        )?;
252        let record = parse_hvcc(payload)
253            .map_err(|error| malformed(format!("invalid hvcC configuration: {error}")))?;
254        let max_bit_depth_minus8 = max_bit_depth_minus8(configuration.profile);
255        let profile_idc_allowed = match configuration.profile {
256            // A Main 10 decoder also decodes Main.
257            CodecProfile::HevcMain10 => matches!(record.general_profile_idc, 1 | 2),
258            _ => record.general_profile_idc == 1,
259        };
260        if !profile_idc_allowed
261            || record.bit_depth_luma_minus8 > max_bit_depth_minus8
262            || record.bit_depth_chroma_minus8 > max_bit_depth_minus8
263            || record.chroma_format_idc != 1
264        {
265            return Err(Error::new(
266                ErrorKind::Unsupported,
267                match configuration.profile {
268                    CodecProfile::HevcMain10 => {
269                        "native HEVC decoder requires an 8- to 10-bit 4:2:0 Main or Main 10 hvcC configuration"
270                    }
271                    _ => {
272                        "native HEVC decoder requires an 8-bit 4:2:0 Main-profile hvcC configuration"
273                    }
274                },
275            ));
276        }
277        let sps_unit = record
278            .nal_units
279            .iter()
280            .find(|unit| unit.header.nal_unit_type == 33)
281            .ok_or_else(|| malformed("hvcC configuration does not contain an SPS"))?;
282        let sps = SeqParameterSet::parse(&sps_unit.rbsp)
283            .map_err(|error| malformed(format!("invalid HEVC SPS: {error}")))?;
284        validate_sps(&sps, configuration, limits)?;
285        let high_bit_depth = record.bit_depth_luma_minus8 != 0
286            || record.bit_depth_chroma_minus8 != 0
287            || sps.bit_depth_luma_minus8 != 0
288            || sps.bit_depth_chroma_minus8 != 0;
289        if configuration.output_format == PixelFormat::Yuv420p10
290            && (sps.bit_depth_luma_minus8 != 2 || sps.bit_depth_chroma_minus8 != 2)
291        {
292            // Issue #756: the format carries 10-bit samples unchanged; widening 8- or 9-bit
293            // samples would misrepresent them.
294            return Err(Error::new(
295                ErrorKind::InvalidInput,
296                "Yuv420p10 output requires a 10-bit HEVC Main 10 stream",
297            ));
298        }
299        Ok(Self {
300            record,
301            high_bit_depth,
302        })
303    }
304}
305
306/// The [`CodecSupport`] errors [`VideoDecoderFactory::create`] reports. The
307/// capability check `create` runs never asks about hardware, so
308/// `hardware_unavailable` is only a fallback.
309const DECODER_SUPPORT_MESSAGES: CodecSupportMessages = CodecSupportMessages {
310    unsupported_codec: "native HEVC decoder requires HEVC",
311    unsupported_profile: "native HEVC decoder supports the Main and Main 10 profiles",
312    hardware_unavailable: "native HEVC decoder does not support this configuration",
313};
314
315/// The deepest samples `profile` allows, as `bit_depth_*_minus8`: 8 bits for Main, 10 for
316/// Main 10.
317fn max_bit_depth_minus8(profile: CodecProfile) -> u8 {
318    match profile {
319        CodecProfile::HevcMain10 => 2,
320        _ => 0,
321    }
322}
323
324fn validate_sps(
325    sps: &SeqParameterSet,
326    configuration: &VideoDecoderConfig,
327    limits: &Limits,
328) -> Result<()> {
329    let max_bit_depth_minus8 = max_bit_depth_minus8(configuration.profile);
330    if sps.chroma_format_idc != 1
331        || sps.separate_color_plane_flag
332        || sps.bit_depth_luma_minus8 > max_bit_depth_minus8
333        || sps.bit_depth_chroma_minus8 > max_bit_depth_minus8
334    {
335        return Err(Error::new(
336            ErrorKind::Unsupported,
337            match configuration.profile {
338                CodecProfile::HevcMain10 => {
339                    "native HEVC decoder requires SPS 8- to 10-bit 4:2:0 syntax"
340                }
341                _ => "native HEVC decoder requires SPS Main-profile 8-bit 4:2:0 syntax",
342            },
343        ));
344    }
345    if sps.pic_width_in_luma_samples > limits.max_width
346        || sps.pic_height_in_luma_samples > limits.max_height
347    {
348        return Err(limit("HEVC SPS coded dimensions exceed configured limits"));
349    }
350    let (sub_width, sub_height) = sub_wh_c(sps.chroma_format_idc);
351    let cropped_width = usize::try_from(sps.pic_width_in_luma_samples)
352        .ok()
353        .and_then(|width| {
354            let crop = usize::try_from(
355                sps.conformance_window.left_offset + sps.conformance_window.right_offset,
356            )
357            .ok()?
358            .checked_mul(sub_width)?;
359            width.checked_sub(crop)
360        })
361        .ok_or_else(|| malformed("HEVC SPS horizontal conformance window is invalid"))?;
362    let cropped_height = usize::try_from(sps.pic_height_in_luma_samples)
363        .ok()
364        .and_then(|height| {
365            let crop = usize::try_from(
366                sps.conformance_window.top_offset + sps.conformance_window.bottom_offset,
367            )
368            .ok()?
369            .checked_mul(sub_height)?;
370            height.checked_sub(crop)
371        })
372        .ok_or_else(|| malformed("HEVC SPS vertical conformance window is invalid"))?;
373    if cropped_width != configuration.coded_dimensions.width as usize
374        || cropped_height != configuration.coded_dimensions.height as usize
375    {
376        return Err(malformed(
377            "HEVC SPS display dimensions do not match decoder configuration",
378        ));
379    }
380    let pixels = u64::from(sps.pic_width_in_luma_samples)
381        .checked_mul(u64::from(sps.pic_height_in_luma_samples))
382        .ok_or_else(|| limit("HEVC picture dimensions overflow"))?;
383    let picture_bytes = pixels
384        .checked_mul(6)
385        .ok_or_else(|| limit("HEVC picture allocation overflows"))?;
386    let output_bytes = u64::from(configuration.coded_dimensions.width)
387        .checked_mul(u64::from(configuration.coded_dimensions.height))
388        .and_then(|value| value.checked_mul(4))
389        .ok_or_else(|| limit("HEVC RGBA output allocation overflows"))?;
390    let ordering = sps.sub_layer_ordering_info[usize::from(sps.max_sub_layers_minus1)];
391    let retained_pictures = u64::from(ordering.max_dec_pic_buffering_minus1)
392        .checked_add(2)
393        .ok_or_else(|| limit("HEVC decoded-picture-buffer size overflows"))?;
394    let decoder_bytes = picture_bytes
395        .checked_mul(retained_pictures)
396        .and_then(|value| value.checked_add(output_bytes))
397        .ok_or_else(|| limit("HEVC decoder allocation budget overflows"))?;
398    if decoder_bytes > limits.max_allocation_bytes {
399        return Err(limit(
400            "HEVC decoded-picture buffer exceeds the allocation limit",
401        ));
402    }
403    Ok(())
404}
405
406#[derive(Debug)]
407struct HevcDecoder {
408    configuration: VideoDecoderConfig,
409    limits: Limits,
410    configuration_nals: Vec<engine::nal::NalUnit>,
411    nal_length_size: usize,
412    sequence: SequenceDecoder,
413    reorder: Vec<DecodedFrame>,
414    presentation_indexes: BinaryHeap<Reverse<FrameIndex>>,
415    /// Whether a caller wants the pictures being decoded, or is only walking past them.
416    output_wanted: bool,
417}
418
419impl HevcDecoder {
420    fn new(
421        configuration: VideoDecoderConfig,
422        limits: Limits,
423        parsed: ParsedConfiguration,
424    ) -> Result<Self> {
425        let configuration_nals = parsed.record.nal_units;
426        let nal_length_size = parsed.record.length_size;
427        let mut decoder = Self {
428            configuration,
429            limits,
430            configuration_nals,
431            nal_length_size,
432            sequence: SequenceDecoder::new(),
433            reorder: Vec::new(),
434            presentation_indexes: BinaryHeap::new(),
435            output_wanted: true,
436        };
437        decoder.reinitialize()?;
438        Ok(decoder)
439    }
440
441    fn reinitialize(&mut self) -> Result<()> {
442        self.sequence = SequenceDecoder::new();
443        for unit in self.configuration_nals.clone() {
444            self.sequence.push_nal_unit(unit).map_err(sequence_error)?;
445        }
446        self.reorder.clear();
447        self.presentation_indexes.clear();
448        Ok(())
449    }
450
451    fn collect(&mut self, flush: bool) -> Result<Vec<DecodedVideoFrame>> {
452        let pictures = self.collect_pictures(flush)?;
453        if !self.output_wanted {
454            // The pictures are still taken from the reorder queue above, which is what keeps the
455            // decoder's own bookkeeping straight; only their conversion is skipped.
456            return Ok(Vec::new());
457        }
458        let mut output = Vec::with_capacity(pictures.len());
459        for (presentation_index, picture) in pictures {
460            output.push(DecodedVideoFrame {
461                presentation_index,
462                frame: match self.configuration.output_format {
463                    PixelFormat::Yuv420p10 => {
464                        picture_to_yuv420p10(&picture, &self.configuration, &self.limits)?
465                    }
466                    _ => picture_to_rgba(&picture, &self.configuration, &self.limits)?,
467                },
468            });
469        }
470        Ok(output)
471    }
472
473    /// The output pictures ready at this point, in presentation order, before
474    /// color conversion.
475    ///
476    /// Issue #220: this is the decoder's own product. [`collect`] converts each
477    /// one to RGBA, which is the round trip an application pays but is not
478    /// decoding, and `hevc_decoder_bench` times the two intervals separately so
479    /// a whole-frame SIMD ratio is not diluted by a stage no HEVC kernel
480    /// touches.
481    ///
482    /// [`collect`]: Self::collect
483    fn collect_pictures(&mut self, flush: bool) -> Result<Vec<(FrameIndex, Picture)>> {
484        self.reorder.extend(self.sequence.take_decoded());
485        self.reorder
486            .sort_by_key(|frame| (frame.cvs_index, frame.poc));
487        let depth = if flush {
488            0
489        } else {
490            self.sequence
491                .max_num_reorder_pics()
492                .map_or(DEFAULT_REORDER_DEPTH, |depth| depth as usize)
493        };
494        let mut output = Vec::new();
495        while self.reorder.len() > depth {
496            let decoded = self.reorder.remove(0);
497            if !decoded.output {
498                continue;
499            }
500            let presentation_index = self
501                .presentation_indexes
502                .pop()
503                .ok_or_else(|| {
504                    malformed("HEVC decoder produced a picture without a submitted identity")
505                })?
506                .0;
507            output.push((presentation_index, decoded.picture));
508        }
509        Ok(output)
510    }
511
512    /// Parses one access unit into the sequence decoder, without collecting
513    /// anything it made ready.
514    ///
515    /// The push and the collect are separate so [`VideoDecoder::submit`] and
516    /// the benchmark surface's picture-only path share exactly the same
517    /// bitstream handling and differ only in what they do with the result.
518    fn push_sample(
519        &mut self,
520        sample: &EncodedVideoSample,
521        cancellation: &CancellationToken,
522    ) -> Result<()> {
523        check_canceled(cancellation)?;
524        if sample.data.len() as u64 > self.limits.max_allocation_bytes {
525            return Err(limit("HEVC access unit exceeds the allocation limit"));
526        }
527        let units = split_length_prefixed(&sample.data, self.nal_length_size)
528            .map_err(|error| malformed(format!("invalid HEVC access unit: {error}")))?;
529        self.presentation_indexes
530            .push(Reverse(sample.presentation_index));
531        let skipped_before = self.sequence.skipped_pictures();
532        let result = catch_unwind(AssertUnwindSafe(|| {
533            for unit in units {
534                self.sequence.push_nal_unit(unit)?;
535            }
536            Ok::<(), SequenceError>(())
537        }));
538        match result {
539            Ok(Ok(())) => {
540                // A leading picture the decoder discarded because decoding
541                // started at its IRAP will never be output, so its identity
542                // must not be handed to the next picture that is.
543                if self.sequence.skipped_pictures() != skipped_before {
544                    self.presentation_indexes
545                        .retain(|Reverse(index)| *index != sample.presentation_index);
546                }
547                Ok(())
548            }
549            Ok(Err(error)) => Err(sequence_error(error)),
550            Err(_) => Err(malformed(
551                "HEVC bitstream triggered an invalid decoder state",
552            )),
553        }
554    }
555
556    /// Decodes one access unit and stops at the decoded pictures.
557    ///
558    /// The picture-only half of the issue #220 split, used by
559    /// [`crate::hevc_decoder_bench`].
560    #[cfg(not(target_arch = "wasm32"))]
561    fn submit_pictures(
562        &mut self,
563        sample: &EncodedVideoSample,
564        cancellation: &CancellationToken,
565    ) -> Result<Vec<Picture>> {
566        self.push_sample(sample, cancellation)?;
567        Ok(self
568            .collect_pictures(false)?
569            .into_iter()
570            .map(|(_, picture)| picture)
571            .collect())
572    }
573}
574
575impl VideoDecoder for HevcDecoder {
576    fn submit(
577        &mut self,
578        sample: &EncodedVideoSample,
579        cancellation: &CancellationToken,
580    ) -> Result<Vec<DecodedVideoFrame>> {
581        self.push_sample(sample, cancellation)?;
582        self.collect(false)
583    }
584
585    fn drain(&mut self, cancellation: &CancellationToken) -> Result<Vec<DecodedVideoFrame>> {
586        check_canceled(cancellation)?;
587        match catch_unwind(AssertUnwindSafe(|| self.sequence.flush())) {
588            Ok(Ok(())) => self.collect(true),
589            Ok(Err(error)) => Err(sequence_error(error)),
590            Err(_) => Err(malformed(
591                "HEVC bitstream triggered an invalid decoder state while draining",
592            )),
593        }
594    }
595
596    fn reset(&mut self) -> Result<()> {
597        self.reinitialize()
598    }
599
600    fn set_output_wanted(&mut self, wanted: bool) {
601        self.output_wanted = wanted;
602    }
603}
604
605/// Issue #756: returns a 10-bit picture's samples unchanged as a `Yuv420p10` frame, each sample
606/// a little-endian 16-bit word in tightly packed rows, cropped to the display dimensions the same
607/// way [`picture_to_rgba`] crops.
608fn picture_to_yuv420p10(
609    picture: &Picture,
610    configuration: &VideoDecoderConfig,
611    limits: &Limits,
612) -> Result<VideoFrame> {
613    if picture.chroma_array_type() != 1
614        || picture.bit_depth_luma() != 10
615        || picture.bit_depth_chroma() != 10
616    {
617        return Err(malformed(
618            "Yuv420p10 output requires 10-bit 4:2:0 HEVC pictures, but this picture is not",
619        ));
620    }
621    let width = configuration.coded_dimensions.width as usize;
622    let height = configuration.coded_dimensions.height as usize;
623    let chroma_width = width.div_ceil(2);
624    let chroma_height = height.div_ceil(2);
625    let (source_chroma_width, source_chroma_height) = picture.plane_dims(HevcPlane::Cb);
626    if picture.width_luma() < width
627        || picture.height_luma() < height
628        || source_chroma_width < chroma_width
629        || source_chroma_height < chroma_height
630    {
631        return Err(malformed(
632            "decoded HEVC picture is smaller than its display dimensions",
633        ));
634    }
635    let length = (width * height)
636        .checked_add(chroma_width * chroma_height * 2)
637        .and_then(|samples| samples.checked_mul(2))
638        .ok_or_else(|| limit("HEVC Yuv420p10 allocation overflows"))?;
639    if length as u64 > limits.max_allocation_bytes {
640        return Err(limit("HEVC Yuv420p10 output exceeds the allocation limit"));
641    }
642    let plane = |samples: &[i32], source_width: usize, width: usize, height: usize| {
643        let mut data = Vec::with_capacity(width * height * 2);
644        for row in samples.chunks_exact(source_width).take(height) {
645            for &sample in &row[..width] {
646                data.extend_from_slice(&(sample as u16).to_le_bytes());
647            }
648        }
649        Plane {
650            data,
651            stride: width * 2,
652        }
653    };
654    VideoFrame::new(
655        configuration.coded_dimensions,
656        PixelFormat::Yuv420p10,
657        configuration.color_range,
658        vec![
659            plane(
660                picture.plane(HevcPlane::Luma),
661                picture.width_luma(),
662                width,
663                height,
664            ),
665            plane(
666                picture.plane(HevcPlane::Cb),
667                source_chroma_width,
668                chroma_width,
669                chroma_height,
670            ),
671            plane(
672                picture.plane(HevcPlane::Cr),
673                source_chroma_width,
674                chroma_width,
675                chroma_height,
676            ),
677        ],
678        limits,
679    )
680}
681
682/// Issue #189 stage attribution: color conversion is not decoding, but it is
683/// on the path every whole-frame measurement takes, so it is reported as its
684/// own stage rather than left in the unattributed remainder.
685fn picture_to_rgba(
686    picture: &Picture,
687    configuration: &VideoDecoderConfig,
688    limits: &Limits,
689) -> Result<VideoFrame> {
690    let _profile = engine::profile::scope(engine::profile::Stage::ColorConvert);
691    let max_bit_depth = 8 + max_bit_depth_minus8(configuration.profile);
692    if picture.chroma_array_type() != 1
693        || !(8..=max_bit_depth).contains(&picture.bit_depth_luma())
694        || !(8..=max_bit_depth).contains(&picture.bit_depth_chroma())
695    {
696        return Err(Error::new(
697            ErrorKind::Unsupported,
698            "decoded HEVC picture is not 4:2:0 at a bit depth its profile allows",
699        ));
700    }
701    let width = configuration.coded_dimensions.width as usize;
702    let height = configuration.coded_dimensions.height as usize;
703    if picture.width_luma() < width || picture.height_luma() < height {
704        return Err(malformed(
705            "decoded HEVC picture is smaller than its display dimensions",
706        ));
707    }
708    let stride = width
709        .checked_mul(4)
710        .ok_or_else(|| limit("HEVC RGBA stride overflows"))?;
711    let length = stride
712        .checked_mul(height)
713        .ok_or_else(|| limit("HEVC RGBA allocation overflows"))?;
714    if length as u64 > limits.max_allocation_bytes {
715        return Err(limit("HEVC RGBA output exceeds the allocation limit"));
716    }
717    let luma = picture.plane(HevcPlane::Luma);
718    let cb = picture.plane(HevcPlane::Cb);
719    let cr = picture.plane(HevcPlane::Cr);
720    let chroma_width = picture.plane_dims(HevcPlane::Cb).0;
721    let mut rgba = vec![0_u8; length];
722    if picture.bit_depth_luma() == 8 && picture.bit_depth_chroma() == 8 {
723        color_convert::convert_yuv420_to_rgba(
724            luma,
725            picture.width_luma(),
726            cb,
727            cr,
728            chroma_width,
729            width,
730            height,
731            &mut rgba,
732            stride,
733        );
734    } else {
735        color_convert::convert_high_bit_depth_yuv420_to_rgba(
736            luma,
737            picture.width_luma(),
738            picture.bit_depth_luma(),
739            cb,
740            cr,
741            chroma_width,
742            picture.bit_depth_chroma(),
743            width,
744            height,
745            &mut rgba,
746            stride,
747        );
748    }
749    VideoFrame::new(
750        configuration.coded_dimensions,
751        PixelFormat::Rgba8,
752        configuration.color_range,
753        vec![Plane { data: rgba, stride }],
754        limits,
755    )
756}
757
758fn check_canceled(cancellation: &CancellationToken) -> Result<()> {
759    if cancellation.is_canceled() {
760        Err(Error::new(ErrorKind::Canceled, "codec operation canceled"))
761    } else {
762        Ok(())
763    }
764}
765
766fn sequence_error(error: SequenceError) -> Error {
767    match error {
768        SequenceError::Unsupported(message) => Error::new(ErrorKind::Unsupported, message),
769        other => malformed(format!("invalid HEVC bitstream: {other}")),
770    }
771}
772
773fn malformed(message: impl Into<String>) -> Error {
774    Error::new(ErrorKind::MalformedMedia, message)
775}
776
777fn limit(message: impl Into<String>) -> Error {
778    Error::new(ErrorKind::ResourceLimit, message)
779}
780
781/// The SIMD dispatch sites in this crate, each with the instruction set it
782/// resolves to right now. `zvidlib::simd::active_by_site` reports every crate's
783/// sites together and documents what each one covers.
784#[doc(hidden)]
785#[must_use]
786pub fn simd_sites() -> Vec<(&'static str, SimdIsa)> {
787    // The HEVC kernels have no vector backend on `wasm32`, so they are not
788    // reported there.
789    #[cfg(target_arch = "wasm32")]
790    return Vec::new();
791    #[cfg(not(target_arch = "wasm32"))]
792    vec![
793        (
794            "hevc_prediction_filters",
795            engine::simd::detected_isa().as_simd_isa(),
796        ),
797        (
798            "hevc_transforms",
799            engine::transform_simd::detected().as_simd_isa(),
800        ),
801    ]
802}
803
804#[cfg(test)]
805mod tests {
806    use super::*;
807
808    #[test]
809    fn rejects_truncated_configuration_without_panicking() {
810        let limits = Limits::default();
811        let configuration = VideoDecoderConfig {
812            codec: Codec::Hevc,
813            profile: CodecProfile::HevcMain,
814            coded_dimensions: crate::VideoDimensions::new(16, 16, &limits).unwrap(),
815            output_format: PixelFormat::Rgba8,
816            color_range: ColorRange::Limited,
817            hardware: HardwarePreference::Avoid,
818            configuration: vec![1, 2, 3],
819        };
820        let support = native_hevc_video_decoder_factory().capability(&configuration);
821        assert!(matches!(support, CodecSupport::InvalidConfiguration { .. }));
822    }
823
824    fn block_on<T>(future: impl std::future::Future<Output = T>) -> T {
825        use std::task::{Context, Poll, Waker};
826        let mut future = Box::pin(future);
827        let mut context = Context::from_waker(Waker::noop());
828        loop {
829            if let Poll::Ready(value) = future.as_mut().poll(&mut context) {
830                return value;
831            }
832        }
833    }
834
835    /// The 12-frame HEVC Main 10 fixture's decoder configuration and decode-order samples.
836    fn main10_fixture(
837        profile: CodecProfile,
838        hardware: HardwarePreference,
839    ) -> (VideoDecoderConfig, Vec<EncodedVideoSample>) {
840        use crate::Mp4DemuxerOptions;
841        use crate::io::MemorySource;
842        use crate::mp4_demux::Mp4Demuxer;
843
844        let limits = Limits::default();
845        let source = MemorySource::new(
846            include_bytes!("../tests/fixtures/bbb_hevc_main10_128x72.mp4").to_vec(),
847        );
848        let movie = block_on(Mp4Demuxer::open(&source, Mp4DemuxerOptions::default())).unwrap();
849        let track = &movie.tracks[0];
850        let samples = block_on(track.to_encoded_video_samples(&source, &limits)).unwrap();
851        let configuration = VideoDecoderConfig {
852            codec: Codec::Hevc,
853            profile,
854            coded_dimensions: track.dimensions.unwrap(),
855            output_format: PixelFormat::Rgba8,
856            color_range: ColorRange::Limited,
857            hardware,
858            configuration: track.decoder_config.clone(),
859        };
860        (configuration, samples)
861    }
862
863    /// Issue #508: the 10-bit samples themselves are FFmpeg's `yuv420p10le` decode of the same
864    /// fixture exactly, and their RGBA conversion is the fixture's, which applies the documented
865    /// matrix to that FFmpeg decode.
866    #[test]
867    fn main10_pictures_match_an_independent_reference_decode() {
868        let digests = |fixture: &str| {
869            fixture
870                .lines()
871                .map(|line| line.split_once(' ').unwrap().1.to_owned())
872                .collect::<Vec<_>>()
873        };
874        let expected = digests(include_str!(
875            "../tests/fixtures/bbb_hevc_main10_128x72_yuv420p10le.sha256"
876        ));
877        let expected_rgba = digests(include_str!(
878            "../tests/fixtures/bbb_hevc_main10_128x72_rgba.sha256"
879        ));
880        let limits = Limits::default();
881        let (configuration, samples) =
882            main10_fixture(CodecProfile::HevcMain10, HardwarePreference::Avoid);
883        let parsed = ParsedConfiguration::parse(&configuration, &limits).unwrap();
884        assert!(parsed.high_bit_depth);
885        let mut decoder = HevcDecoder::new(configuration.clone(), limits, parsed).unwrap();
886        let cancellation = CancellationToken::new();
887        let mut pictures = Vec::new();
888        for sample in &samples {
889            decoder.push_sample(sample, &cancellation).unwrap();
890            pictures.extend(decoder.collect_pictures(false).unwrap());
891        }
892        decoder.sequence.flush().unwrap();
893        pictures.extend(decoder.collect_pictures(true).unwrap());
894        pictures.sort_by_key(|(index, _)| *index);
895
896        assert_eq!(pictures.len(), expected.len());
897        for (((index, picture), expected), expected_rgba) in
898            pictures.iter().zip(&expected).zip(&expected_rgba)
899        {
900            assert_eq!(picture.bit_depth_luma(), 10);
901            assert_eq!(picture.bit_depth_chroma(), 10);
902            let digest = crate::conformance::FrameDigest(crate::conformance::sha256(
903                &picture.to_planar_le16(),
904            ));
905            assert_eq!(&digest.to_hex(), expected, "frame {}", index.0);
906            let rgba = picture_to_rgba(picture, &configuration, &limits).unwrap();
907            let digest = crate::conformance::FrameDigest::from_frame(&rgba).unwrap();
908            assert_eq!(&digest.to_hex(), expected_rgba, "frame {} RGBA", index.0);
909        }
910    }
911
912    #[test]
913    fn main10_is_decoded_in_software_whatever_the_hardware_preference() {
914        let factory = native_hevc_video_decoder_factory();
915        for hardware in [HardwarePreference::Avoid, HardwarePreference::Prefer] {
916            let (configuration, _) = main10_fixture(CodecProfile::HevcMain10, hardware);
917            assert_eq!(
918                factory.capability(&configuration),
919                CodecSupport::Supported {
920                    implementation: CodecImplementation::Software
921                },
922                "{hardware:?}"
923            );
924        }
925        let (configuration, _) =
926            main10_fixture(CodecProfile::HevcMain10, HardwarePreference::Require);
927        assert_eq!(
928            factory.capability(&configuration),
929            CodecSupport::HardwareUnavailable
930        );
931        let error = factory
932            .create(&configuration, &Limits::default())
933            .err()
934            .expect("no accelerated backend decodes Main 10");
935        assert_eq!(error.kind(), ErrorKind::Unsupported);
936    }
937
938    #[test]
939    fn a_main_profile_configuration_still_refuses_a_10_bit_track() {
940        let (configuration, _) = main10_fixture(CodecProfile::HevcMain, HardwarePreference::Avoid);
941        let factory = native_hevc_video_decoder_factory();
942        assert!(matches!(
943            factory.capability(&configuration),
944            CodecSupport::InvalidConfiguration { .. }
945        ));
946        let error = factory
947            .create(&configuration, &Limits::default())
948            .err()
949            .expect("HEVC Main is 8-bit");
950        assert_eq!(error.kind(), ErrorKind::Unsupported);
951    }
952
953    /// Issue #756: `Yuv420p10` output is offered for 10-bit Main 10 tracks, always in software,
954    /// whatever their signaled range, and refused for 8-bit tracks before decoding starts.
955    #[test]
956    fn yuv420p10_output_is_offered_only_for_10_bit_tracks() {
957        use crate::Mp4DemuxerOptions;
958        use crate::io::MemorySource;
959        use crate::mp4_demux::Mp4Demuxer;
960
961        let factory = native_hevc_video_decoder_factory();
962        let limits = Limits::default();
963        for (hardware, range) in [
964            (HardwarePreference::Avoid, ColorRange::Limited),
965            (HardwarePreference::Prefer, ColorRange::Full),
966        ] {
967            let (mut configuration, _) = main10_fixture(CodecProfile::HevcMain10, hardware);
968            configuration.output_format = PixelFormat::Yuv420p10;
969            configuration.color_range = range;
970            assert_eq!(
971                factory.capability(&configuration),
972                CodecSupport::Supported {
973                    implementation: CodecImplementation::Software
974                },
975                "{hardware:?} {range:?}"
976            );
977            assert!(factory.create(&configuration, &limits).is_ok());
978        }
979        let (mut configuration, _) =
980            main10_fixture(CodecProfile::HevcMain10, HardwarePreference::Require);
981        configuration.output_format = PixelFormat::Yuv420p10;
982        assert_eq!(
983            factory.capability(&configuration),
984            CodecSupport::HardwareUnavailable
985        );
986
987        // An 8-bit Main track, even under a Main 10 configuration.
988        let source = MemorySource::new(
989            include_bytes!("../tests/fixtures/bbb_hevc_512x288_gop32.mp4").to_vec(),
990        );
991        let movie = block_on(Mp4Demuxer::open(&source, Mp4DemuxerOptions::default())).unwrap();
992        let track = &movie.tracks[0];
993        for profile in [CodecProfile::HevcMain, CodecProfile::HevcMain10] {
994            let configuration = VideoDecoderConfig {
995                codec: Codec::Hevc,
996                profile,
997                coded_dimensions: track.dimensions.unwrap(),
998                output_format: PixelFormat::Yuv420p10,
999                color_range: ColorRange::Limited,
1000                hardware: HardwarePreference::Avoid,
1001                configuration: track.decoder_config.clone(),
1002            };
1003            assert!(
1004                matches!(
1005                    factory.capability(&configuration),
1006                    CodecSupport::InvalidConfiguration { .. }
1007                ),
1008                "{profile:?}"
1009            );
1010            let error = factory
1011                .create(&configuration, &limits)
1012                .err()
1013                .expect("8-bit HEVC has no Yuv420p10 output");
1014            assert_eq!(error.kind(), ErrorKind::InvalidInput, "{profile:?}");
1015        }
1016    }
1017
1018    /// Issue #756: the samples are copied unchanged and cropped to the display dimensions, and a
1019    /// picture that is not 10-bit is refused rather than widened.
1020    #[test]
1021    fn yuv420p10_output_crops_and_keeps_every_sample() {
1022        let limits = Limits::default();
1023        let configuration = VideoDecoderConfig {
1024            codec: Codec::Hevc,
1025            profile: CodecProfile::HevcMain10,
1026            coded_dimensions: VideoDimensions::new(6, 2, &limits).unwrap(),
1027            output_format: PixelFormat::Yuv420p10,
1028            color_range: ColorRange::Limited,
1029            hardware: HardwarePreference::Avoid,
1030            configuration: Vec::new(),
1031        };
1032        let mut picture = Picture::new(8, 4, 1, 10, 10);
1033        for (plane, offset) in [
1034            (HevcPlane::Luma, 0),
1035            (HevcPlane::Cb, 500),
1036            (HevcPlane::Cr, 1000),
1037        ] {
1038            let (samples, _) = picture.plane_mut(plane);
1039            for (index, sample) in samples.iter_mut().enumerate() {
1040                *sample = (offset + index as i32).min(1023);
1041            }
1042        }
1043        let frame = picture_to_yuv420p10(&picture, &configuration, &limits).unwrap();
1044        assert_eq!(frame.pixel_format, PixelFormat::Yuv420p10);
1045        let words = |plane: &Plane| {
1046            plane
1047                .data
1048                .chunks_exact(2)
1049                .map(|pair| u16::from_le_bytes([pair[0], pair[1]]))
1050                .collect::<Vec<_>>()
1051        };
1052        assert_eq!(
1053            frame.planes.iter().map(|p| p.stride).collect::<Vec<_>>(),
1054            [12, 6, 6]
1055        );
1056        assert_eq!(
1057            words(&frame.planes[0]),
1058            [0, 1, 2, 3, 4, 5, 8, 9, 10, 11, 12, 13]
1059        );
1060        assert_eq!(words(&frame.planes[1]), [500, 501, 502]);
1061        assert_eq!(words(&frame.planes[2]), [1000, 1001, 1002]);
1062
1063        let error = picture_to_yuv420p10(&Picture::new(8, 4, 1, 8, 8), &configuration, &limits)
1064            .unwrap_err();
1065        assert_eq!(error.kind(), ErrorKind::MalformedMedia);
1066    }
1067
1068    #[test]
1069    fn canonical_conversion_uses_decoder_integer_rounding() {
1070        use color_convert::{clip_u8, multiply_high};
1071
1072        assert_eq!(multiply_high(-8, -3_209), 0);
1073        assert_eq!(clip_u8(multiply_high(0, 9_539)), 0);
1074    }
1075
1076    /// Issue #506: the 32-frame-cadence fixture is an open-GOP stream. Each CRA picture after
1077    /// the first is followed in decode order by RASL pictures presented before it, and those
1078    /// reference pictures from before the CRA. Every frame from 29 onwards used to fail from a
1079    /// fresh reader: 29 to 31 because the reader started at the CRA that leads them, and later
1080    /// frames because a decode started at a CRA tried to reconstruct its RASL pictures. Every
1081    /// frame must now match FFmpeg's decode walked in order, in reverse and alternating, and
1082    /// the frames around CRA boundaries must match it from a fresh reader.
1083    #[test]
1084    fn open_gop_leading_pictures_decode_from_every_starting_point() {
1085        use crate::io::MemorySource;
1086        use crate::{
1087            ExactFrameReader, FrameDigest, FrameIndex, Mp4DemuxerOptions,
1088            VideoDecoderConformanceVector, VideoDimensions, verify_video_decoder_conformance,
1089        };
1090
1091        let expected = include_str!("../tests/fixtures/bbb_hevc_512x288_gop32_rgba.sha256")
1092            .lines()
1093            .map(|line| FrameDigest::from_hex(line.split_once(' ').unwrap().1).unwrap())
1094            .collect::<Vec<_>>();
1095        let limits = Limits::default();
1096        let source = MemorySource::new(
1097            include_bytes!("../tests/fixtures/bbb_hevc_512x288_gop32.mp4").to_vec(),
1098        );
1099        let vector = block_on(VideoDecoderConformanceVector::from_mp4(
1100            "open-GOP HEVC Main fixture",
1101            &source,
1102            Mp4DemuxerOptions::default(),
1103            1,
1104            VideoDecoderConfig {
1105                codec: Codec::Hevc,
1106                profile: CodecProfile::HevcMain,
1107                coded_dimensions: VideoDimensions::new(512, 288, &limits).unwrap(),
1108                output_format: PixelFormat::Rgba8,
1109                color_range: ColorRange::Limited,
1110                hardware: HardwarePreference::Avoid,
1111                configuration: Vec::new(),
1112            },
1113            &expected,
1114        ))
1115        .unwrap();
1116        assert_eq!(vector.samples.len(), 768);
1117        // The fixture's shape, which is what makes it a regression test: the CRA at frame 32
1118        // is followed in decode order by the RASL pictures 30, 29 and 31.
1119        let order = vector.samples[29..33]
1120            .iter()
1121            .map(|sample| (sample.presentation_index.0, sample.random_access))
1122            .collect::<Vec<_>>();
1123        assert_eq!(order, [(32, true), (30, false), (29, false), (31, false)]);
1124
1125        let factory = native_hevc_video_decoder_factory();
1126        let report = verify_video_decoder_conformance(&factory, &vector, limits).unwrap();
1127        assert_eq!(report.frames_verified, 3 * 768);
1128
1129        // A fresh reader for every frame of the first two CRA boundaries, and for the leading
1130        // and trailing pictures of later ones.
1131        let cancellation = CancellationToken::new();
1132        for index in (20..=72).chain([413, 415, 416, 767]) {
1133            let expected = &expected[index];
1134            let mut reader = ExactFrameReader::new(
1135                &factory,
1136                vector.configuration.clone(),
1137                vector.samples.clone(),
1138                limits,
1139            )
1140            .unwrap();
1141            let frame = reader
1142                .get(FrameIndex(index as u64), &cancellation)
1143                .unwrap_or_else(|error| panic!("frame {index} from a fresh reader: {error}"));
1144            assert_eq!(
1145                FrameDigest::from_frame(&frame).unwrap(),
1146                *expected,
1147                "frame {index} from a fresh reader"
1148            );
1149            // A frame at or after a CRA is reached from that CRA, skipping its RASL pictures,
1150            // not by walking the whole track from frame 0.
1151            if index == 40 {
1152                assert!(
1153                    reader.statistics().samples_submitted <= 16,
1154                    "frame 40 is decoded from the CRA at frame 32: {:?}",
1155                    reader.statistics()
1156                );
1157            }
1158        }
1159    }
1160}