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