diff --git a/crates/video/Cargo.toml b/crates/video/Cargo.toml index 6a8cb336a..0989feb73 100644 --- a/crates/video/Cargo.toml +++ b/crates/video/Cargo.toml @@ -80,8 +80,13 @@ rav1e = { version = "0.8", default-features = false, optional = true } [dev-dependencies] craft-media-testkit = { workspace = true } -# The AVI muxer, for the MPEG-4 Part 2 encoder's end-to-end test, and the VMD demuxer for the VMD decoder's. -craft-media = { workspace = true, features = ["avi", "vmd"] } +# The AVI muxer, for the MPEG-4 Part 2 encoder's end-to-end test; the MP4, MPEG-TS and AVI +# demuxers, for the track decoder's tests; the VMD demuxer, for the VMD decoder's. +craft-media = { workspace = true, features = ["avi", "isobmff", "mpegts", "vmd"] } + +# Built with any decoder feature; each codec's tests need its own. +[[test]] +name = "track" [[test]] name = "vmd" diff --git a/crates/video/README.md b/crates/video/README.md index c2c5b2745..d05d50312 100644 --- a/crates/video/README.md +++ b/crates/video/README.md @@ -55,3 +55,31 @@ comes with its codec's feature): The constructors check that every plane's buffer, stride and size fit the frame, so a picture with inconsistent fields is an error, not an out-of-bounds read. + +## Decoding a track + +`TrackDecoder` is the counterpart of `craft_audio::TrackDecoder` for an app with its own demuxer. +It picks the decoder from a track's `CodecParams`, takes packets in decode order with their +timestamps, and returns `VideoFrame`s in display order. `flush` returns the frames still held at +the end of the stream, and `reset` prepares for decoding from another key frame after a seek. It +is built with any of the decoder features below and decodes the codecs whose feature is on. + +| Codec | Feature | `extradata` | +|---|---|---| +| H.264 | `h264-decode` | an `avcC` record (length-prefixed packets), Annex B parameter sets, or empty (Annex B packets) | +| HEVC | `hevc-decode` | an `hvcC` record (length-prefixed packets), Annex B parameter sets, or empty (Annex B packets) | +| VP9 | `vp9-decode` | ignored | +| AV1 | `av1-decode` | an `av1C` record, or empty | +| MPEG-2 and MPEG-1 video | `mpeg2-decode` | a sequence header and its extensions, or empty | + +Configuration that holds picture data (a slice, a frame OBU, an MPEG-2 picture) is refused. +Errors are `VideoError`: `Unsupported`, `Malformed`, or a picture that did not convert. + +When a picture does not convert, the frames finished with it are kept and the next call returns +them first. When the codec itself fails, the pictures it had finished are up to the codec: + +- H.264 keeps them for later calls, also when the error comes at `flush`. +- HEVC does too, but only its newest 32 while calls keep failing, which bounds its memory. +- VP9 keeps those of earlier packets. +- MPEG-2 returns them with the call, unless the packet made too many pictures. +- AV1 drops those the failing `decode` or `flush` had finished. diff --git a/crates/video/src/av1/decode/mod.rs b/crates/video/src/av1/decode/mod.rs index 63f66120a..b5e410341 100644 --- a/crates/video/src/av1/decode/mod.rs +++ b/crates/video/src/av1/decode/mod.rs @@ -5,7 +5,7 @@ #![allow(clippy::needless_range_loop, clippy::type_complexity)] -mod bits; +pub(crate) mod bits; mod cdef; mod cdf; mod decoder; diff --git a/crates/video/src/error.rs b/crates/video/src/error.rs new file mode 100644 index 000000000..21706aaf9 --- /dev/null +++ b/crates/video/src/error.rs @@ -0,0 +1,73 @@ +//! [`VideoError`], the error of the codec-agnostic layer ([`crate::TrackDecoder`]). + +use crate::frame::FrameError; + +/// Errors from the codec-agnostic layer. +/// +/// Codec errors convert into it, so code mixing [`crate::TrackDecoder`] with the codec modules can +/// use `?` throughout: a codec's "unsupported" stays [`VideoError::Unsupported`], anything else in +/// the input is [`VideoError::Malformed`]. The message starts with the codec's name. +#[non_exhaustive] +#[derive(Debug, thiserror::Error)] +pub enum VideoError { + /// The codec, or a feature of the stream, is valid but not supported (or its decoder is not + /// in this build). + #[error("unsupported video: {0}")] + Unsupported(String), + /// The input is corrupt or not what it claims to be. + #[error("malformed video: {0}")] + Malformed(String), + /// A decoded picture did not convert into a [`crate::frame::VideoFrame`]. + #[error(transparent)] + Frame(#[from] FrameError), +} + +#[cfg(feature = "h264-decode")] +impl From for VideoError { + fn from(e: crate::h264::decode::Error) -> Self { + match e { + crate::h264::decode::Error::Unsupported(_) => VideoError::Unsupported(format!("H.264: {e}")), + _ => VideoError::Malformed(format!("H.264: {e}")), + } + } +} + +#[cfg(feature = "hevc-decode")] +impl From for VideoError { + fn from(e: crate::hevc::decode::Error) -> Self { + match e { + crate::hevc::decode::Error::Unsupported(_) => VideoError::Unsupported(format!("HEVC: {e}")), + _ => VideoError::Malformed(format!("HEVC: {e}")), + } + } +} + +#[cfg(feature = "vp9-decode")] +impl From for VideoError { + fn from(e: crate::vp9::decode::Error) -> Self { + match e { + crate::vp9::decode::Error::Unsupported(_) => VideoError::Unsupported(format!("VP9: {e}")), + _ => VideoError::Malformed(format!("VP9: {e}")), + } + } +} + +#[cfg(feature = "av1-decode")] +impl From for VideoError { + fn from(e: crate::av1::decode::Error) -> Self { + match e { + crate::av1::decode::Error::Unsupported(_) => VideoError::Unsupported(format!("AV1: {e}")), + _ => VideoError::Malformed(format!("AV1: {e}")), + } + } +} + +#[cfg(feature = "mpeg2-decode")] +impl From for VideoError { + fn from(e: crate::mpeg2::Error) -> Self { + match e { + crate::mpeg2::Error::Unsupported(_) => VideoError::Unsupported(format!("MPEG-2: {e}")), + crate::mpeg2::Error::Invalid(_) => VideoError::Malformed(format!("MPEG-2: {e}")), + } + } +} diff --git a/crates/video/src/lib.rs b/crates/video/src/lib.rs index 249f1a1b4..174e7573a 100644 --- a/crates/video/src/lib.rs +++ b/crates/video/src/lib.rs @@ -28,12 +28,23 @@ //! Each decoder returns its own picture type. [`frame::VideoFrame`] is the codec-agnostic form //! they all convert into (`VideoFrame::try_from`). //! +//! `TrackDecoder` picks the decoder for a track from its `craft_media::CodecParams` and returns +//! `VideoFrame`s, for H.264, HEVC, VP9, AV1 and MPEG-2 (built with any of their decoder features). +//! //! Containers and bit-level I/O are in `craft-media`; the codecs here share its `bitstream` //! module and describe their streams with `craft_media::CodecParams`. pub mod budget; +mod error; pub mod frame; +pub use error::VideoError; + +#[cfg(any(feature = "h264-decode", feature = "hevc-decode", feature = "vp9-decode", feature = "av1-decode", feature = "mpeg2-decode"))] +mod track; +#[cfg(any(feature = "h264-decode", feature = "hevc-decode", feature = "vp9-decode", feature = "av1-decode", feature = "mpeg2-decode"))] +pub use track::TrackDecoder; + #[cfg(any(feature = "apv-decode", feature = "apv-encode"))] pub mod apv; diff --git a/crates/video/src/track.rs b/crates/video/src/track.rs new file mode 100644 index 000000000..a4f246271 --- /dev/null +++ b/crates/video/src/track.rs @@ -0,0 +1,413 @@ +//! [`TrackDecoder`]: one video track's packets in, [`VideoFrame`]s out, whatever the codec. The +//! counterpart of `craft_audio::TrackDecoder`, for an app with its own demuxer. + +#[cfg(feature = "av1-decode")] +use crate::av1; +use crate::error::VideoError; +use crate::frame::{FrameError, VideoFrame}; +#[cfg(feature = "h264-decode")] +use crate::h264; +#[cfg(feature = "hevc-decode")] +use crate::hevc; +#[cfg(feature = "mpeg2-decode")] +use crate::mpeg2; +#[cfg(feature = "vp9-decode")] +use crate::vp9; +use craft_media::{CodecId, CodecParams}; + +/// The codec-specific decoder behind a [`TrackDecoder`]. +enum Inner { + /// The decoder, and the `avcC` record or Annex B parameter sets that [`TrackDecoder::reset`] + /// applies again (the decoder's own reset forgets them). + #[cfg(feature = "h264-decode")] + H264 { dec: Box, config: Vec }, + /// The decoder, and the `hvcC` record or Annex B parameter sets a reset rebuilds it from. + #[cfg(feature = "hevc-decode")] + Hevc { dec: Box, config: Vec }, + #[cfg(feature = "vp9-decode")] + Vp9(Box), + /// The decoder, and the `av1C` config OBUs a reset rebuilds it from. + #[cfg(feature = "av1-decode")] + Av1 { dec: Box, config_obus: Vec }, + #[cfg(feature = "mpeg2-decode")] + Mpeg2(Box), +} + +/// A decoder for one video track, whatever its codec: built from the track's [`CodecParams`], +/// it takes the track's packets in decode order and returns [`VideoFrame`]s in display order. +/// +/// | Codec | Feature | `extradata` | +/// |---|---|---| +/// | H.264 | `h264-decode` | an `avcC` record, Annex B parameter sets, or empty | +/// | HEVC | `hevc-decode` | an `hvcC` record, Annex B parameter sets, or empty | +/// | VP9 | `vp9-decode` | ignored (the frame headers repeat the `vpcC` values) | +/// | AV1 | `av1-decode` | an `av1C` record, or empty | +/// | MPEG-2 and MPEG-1 video | `mpeg2-decode` | a sequence header and its extensions, or empty | +/// +/// With an `avcC` or `hvcC` record, packets are length-prefixed NAL units, as MP4 and Matroska +/// store them. Otherwise they are Annex B, as MPEG-TS and AVI store them, and the parameter sets +/// may come in the packets themselves. The configuration must not hold picture data: an `avcC` +/// or `hvcC` record holds parameter sets (and SEI for `hvcC`), Annex B `extradata` holds +/// parameter sets, SEI and access unit delimiters, `av1C` config OBUs are sequence headers and +/// metadata, and MPEG-2 `extradata` holds sequence headers, their extensions, user data and GOP +/// headers. +/// +/// Other codecs are [`VideoError::Unsupported`], as is a codec whose decoder feature is off. +/// +/// A packet carries its presentation timestamp, in any unit; each frame returns with the timestamp +/// of the packet that coded it, through reordering ([`VideoFrame::pts`]). +/// +/// ```no_run +/// # fn run(params: &craft_media::CodecParams, packets: &[(Vec, i64)]) -> Result<(), craft_video::VideoError> { +/// use craft_video::TrackDecoder; +/// +/// let mut dec = TrackDecoder::new(params)?; +/// for (packet, pts) in packets { +/// for frame in dec.decode(packet, *pts)? { +/// println!("{}x{} at {:?}", frame.width(), frame.height(), frame.pts); +/// } +/// } +/// for frame in dec.flush()? { +/// let _ = frame; +/// } +/// # Ok(()) } +/// ``` +pub struct TrackDecoder { + inner: Inner, + codec: CodecId, + /// Frames finished by a call that then failed, which the next call returns first. + held: Vec, +} + +impl std::fmt::Debug for TrackDecoder { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TrackDecoder").field("codec", &self.codec).field("held", &self.held.len()).finish_non_exhaustive() + } +} + +impl TrackDecoder { + /// A decoder for the track `params` describes. Only `codec` and `extradata` are read; the + /// picture size and format come from the stream. + /// + /// Configuration that the codec refuses, or that holds picture data, is + /// [`VideoError::Malformed`]. + pub fn new(params: &CodecParams) -> Result { + Ok(TrackDecoder { inner: Inner::new(params.codec, ¶ms.extradata)?, codec: params.codec, held: Vec::new() }) + } + + /// The track's codec, as `params` gave it. + pub fn codec(&self) -> CodecId { + self.codec + } + + /// Decode one packet (an access unit, a VP9 frame or superframe, an AV1 temporal unit) with + /// its presentation timestamp. Returns the frames that became ready for display, in display + /// order; a decoder that reorders or decodes on worker threads returns a packet's frame from a + /// later call or from [`TrackDecoder::flush`]. + /// + /// When a call fails because a picture does not convert, the frames finished with it are + /// kept: the next call returns them first. When the codec itself fails, the pictures it had + /// finished are up to the codec. H.264 keeps them for later calls. HEVC does too, but only + /// its newest 32 while calls keep failing, which bounds its memory. VP9 keeps those of earlier + /// packets. MPEG-2 returns them with the call, unless the packet made too many pictures. AV1 + /// drops those the failing call had finished. + /// + /// Decoding can go on with the next packet; a decoder that lost its references waits for the + /// next random access point or conceals, as the codec does. + pub fn decode(&mut self, packet: &[u8], pts: i64) -> Result, VideoError> { + match &mut self.inner { + #[cfg(feature = "h264-decode")] + Inner::H264 { dec, .. } => { + let pics = dec.decode(packet, pts)?; + self.output(pics, None) + } + #[cfg(feature = "hevc-decode")] + Inner::Hevc { dec, .. } => { + let pics = dec.decode(packet, pts)?; + self.output(pics, None) + } + #[cfg(feature = "vp9-decode")] + Inner::Vp9(dec) => { + let pics = dec.decode(packet, pts)?; + self.output(pics, None) + } + #[cfg(feature = "av1-decode")] + Inner::Av1 { dec, .. } => { + let pics = dec.decode_pts(packet, pts)?; + self.output(pics, None) + } + #[cfg(feature = "mpeg2-decode")] + Inner::Mpeg2(dec) => { + let pics = dec.decode(packet, pts)?; + self.output(pics, None) + } + } + } + + /// End of stream: every frame the decoder still holds, in display order. + /// + /// A decoding error found while finishing them is returned instead; the H.264 and HEVC frames + /// are then kept for the next call, while the AV1 decoder drops its own. + pub fn flush(&mut self) -> Result, VideoError> { + match &mut self.inner { + #[cfg(feature = "h264-decode")] + Inner::H264 { dec, .. } => { + let pics = dec.flush(); + let err = dec.take_error().map(VideoError::from); + self.output(pics, err) + } + #[cfg(feature = "hevc-decode")] + Inner::Hevc { dec, .. } => { + let pics = dec.flush(); + let err = dec.take_error().map(VideoError::from); + self.output(pics, err) + } + #[cfg(feature = "vp9-decode")] + Inner::Vp9(dec) => { + let pics = dec.flush(); + self.output(pics, None) + } + #[cfg(feature = "av1-decode")] + Inner::Av1 { dec, .. } => { + let pics = dec.flush_result()?; + self.output(pics, None) + } + #[cfg(feature = "mpeg2-decode")] + Inner::Mpeg2(dec) => { + let pics = dec.flush(); + self.output(pics, None) + } + } + } + + /// Forget the pictures and references, and the frames kept from a failed call, before decoding + /// from another random access point (after a seek). The track's configuration is kept: H.264 + /// and HEVC parameter sets from `extradata`, the AV1 sequence header from `av1C`, and the + /// MPEG-2 sequence; parameter sets that came in packets are forgotten (MPEG-2 keeps its + /// latest sequence header). + /// + /// An error is the configuration failing to apply again, which it did not when the decoder was + /// built. + pub fn reset(&mut self) -> Result<(), VideoError> { + self.held.clear(); + match &mut self.inner { + #[cfg(feature = "h264-decode")] + Inner::H264 { dec, config } => { + dec.reset(); + configure_h264(dec, config) + } + #[cfg(feature = "hevc-decode")] + Inner::Hevc { dec, config } => { + // The HEVC decoder has no reset of its own: a new one starts from nothing. + let mut fresh = Box::new(hevc::decode::Decoder::new()); + configure_hevc(&mut fresh, config)?; + *dec = fresh; + Ok(()) + } + #[cfg(feature = "vp9-decode")] + Inner::Vp9(dec) => { + dec.reset(); + Ok(()) + } + #[cfg(feature = "av1-decode")] + Inner::Av1 { dec, config_obus } => { + // The AV1 decoder has no reset of its own: a new one starts from nothing. + let mut fresh = Box::new(av1::decode::Decoder::new()); + configure_av1(&mut fresh, config_obus)?; + *dec = fresh; + Ok(()) + } + #[cfg(feature = "mpeg2-decode")] + Inner::Mpeg2(dec) => { + dec.reset(); + Ok(()) + } + } + } + + /// The frames kept from a failed call, then `pics` converted. On `err`, or on a picture that + /// does not convert, the frames are kept for the next call and the (first) error returned. + fn output

(&mut self, pics: Vec

, err: Option) -> Result, VideoError> + where + VideoFrame: TryFrom, + { + let mut frames = std::mem::take(&mut self.held); + frames.reserve(pics.len()); + let mut err = err; + for pic in pics { + match VideoFrame::try_from(pic) { + Ok(frame) => frames.push(frame), + Err(e) => { + err.get_or_insert(e.into()); + } + } + } + match err { + None => Ok(frames), + Some(e) => { + self.held = frames; + Err(e) + } + } + } +} + +impl Inner { + fn new(codec: CodecId, extradata: &[u8]) -> Result { + #[cfg(not(any(feature = "h264-decode", feature = "hevc-decode", feature = "av1-decode", feature = "mpeg2-decode")))] + let _ = extradata; + match codec { + #[cfg(feature = "h264-decode")] + CodecId::H264 => { + let mut dec = Box::new(h264::decode::Decoder::new()); + configure_h264(&mut dec, extradata)?; + Ok(Inner::H264 { dec, config: extradata.to_vec() }) + } + #[cfg(feature = "hevc-decode")] + CodecId::Hevc => { + let mut dec = Box::new(hevc::decode::Decoder::new()); + configure_hevc(&mut dec, extradata)?; + Ok(Inner::Hevc { dec, config: extradata.to_vec() }) + } + #[cfg(feature = "vp9-decode")] + CodecId::Vp9 => Ok(Inner::Vp9(Box::default())), + #[cfg(feature = "av1-decode")] + CodecId::Av1 => { + let config_obus = av1c_config_obus(extradata)?.to_vec(); + let mut dec = Box::new(av1::decode::Decoder::new()); + configure_av1(&mut dec, &config_obus)?; + Ok(Inner::Av1 { dec, config_obus }) + } + #[cfg(feature = "mpeg2-decode")] + CodecId::Mpeg2Video => { + let mut dec = Box::new(mpeg2::Decoder::new()); + if !extradata.is_empty() { + check_mpeg2_config(extradata)?; + dec.decode(extradata, 0)?; + } + Ok(Inner::Mpeg2(dec)) + } + other => Err(VideoError::Unsupported(format!("no {} decoder in this build", other.name()))), + } + } +} + +/// Whether `extradata` is Annex B (starts with a start code) rather than an `avcC` / `hvcC` record. +#[cfg(any(feature = "h264-decode", feature = "hevc-decode"))] +fn is_annex_b(extradata: &[u8]) -> bool { + extradata.starts_with(&[0, 0, 1]) || extradata.starts_with(&[0, 0, 0, 1]) +} + +/// Annex B `extradata` holds only NAL units whose type `allowed` accepts (`codec` names it in the +/// error). +#[cfg(any(feature = "h264-decode", feature = "hevc-decode"))] +fn check_annex_b(codec: &str, extradata: &[u8], nal_type: fn(u8) -> u8, allowed: &[u8]) -> Result<(), VideoError> { + for nal in craft_media::bitstream::annexb_nals(extradata) { + let t = nal.first().map_or(u8::MAX, |&b| nal_type(b)); + if !allowed.contains(&t) { + return Err(VideoError::Malformed(format!("{codec}: configuration holds NAL unit type {t}, not a parameter set"))); + } + } + Ok(()) +} + +/// H.264 NAL unit types Annex B `extradata` may hold: SEI, SPS, PPS, access unit delimiter, SPS +/// extension and subset SPS. +#[cfg(feature = "h264-decode")] +const H264_CONFIG_NALS: [u8; 6] = [6, 7, 8, 9, 13, 15]; + +/// HEVC NAL unit types Annex B `extradata` may hold: VPS, SPS, PPS, access unit delimiter, prefix +/// and suffix SEI. +#[cfg(feature = "hevc-decode")] +const HEVC_CONFIG_NALS: [u8; 6] = [32, 33, 34, 35, 39, 40]; + +/// Apply H.264 `extradata`: an `avcC` record, Annex B parameter sets, or nothing. +#[cfg(feature = "h264-decode")] +fn configure_h264(dec: &mut h264::decode::Decoder, extradata: &[u8]) -> Result<(), VideoError> { + if extradata.is_empty() { + Ok(()) + } else if is_annex_b(extradata) { + check_annex_b("H.264", extradata, |b| b & 0x1f, &H264_CONFIG_NALS)?; + dec.decode(extradata, 0)?; + Ok(()) + } else { + Ok(dec.configure_avcc(extradata)?) + } +} + +/// Apply HEVC `extradata`: an `hvcC` record, Annex B parameter sets, or nothing. +#[cfg(feature = "hevc-decode")] +fn configure_hevc(dec: &mut hevc::decode::Decoder, extradata: &[u8]) -> Result<(), VideoError> { + if extradata.is_empty() { + Ok(()) + } else if is_annex_b(extradata) { + check_annex_b("HEVC", extradata, |b| (b >> 1) & 0x3f, &HEVC_CONFIG_NALS)?; + dec.decode(extradata, 0)?; + Ok(()) + } else { + Ok(dec.configure_hvcc(extradata)?) + } +} + +/// MPEG-2 start codes `extradata` may hold: user data, sequence header, extension and GOP header. +#[cfg(feature = "mpeg2-decode")] +const MPEG2_CONFIG_CODES: [u8; 4] = [0xb2, 0xb3, 0xb5, 0xb8]; + +/// MPEG-2 `extradata` holds no picture: every start code in it is one of [`MPEG2_CONFIG_CODES`]. +#[cfg(feature = "mpeg2-decode")] +fn check_mpeg2_config(extradata: &[u8]) -> Result<(), VideoError> { + for w in extradata.windows(4) { + if let [0, 0, 1, code] = *w + && !MPEG2_CONFIG_CODES.contains(&code) + { + return Err(VideoError::Malformed(format!("MPEG-2: configuration holds start code {code:#04x}, not a sequence header"))); + } + } + Ok(()) +} + +/// The config OBUs of an `av1C` record (empty for empty `extradata`), once they are checked to +/// hold only sequence headers and metadata. +#[cfg(feature = "av1-decode")] +fn av1c_config_obus(extradata: &[u8]) -> Result<&[u8], VideoError> { + const SEQUENCE_HEADER: u8 = 1; + const METADATA: u8 = 5; + if extradata.is_empty() { + return Ok(&[]); + } + // marker (1) and version (1), then three bytes of profile, level and chroma fields + let obus = match extradata { + [0x81, _, _, _, obus @ ..] => obus, + _ => return Err(VideoError::Malformed("AV1: configuration is not an av1C record (version 1)".into())), + }; + let mut rest = obus; + while let Some(&header) = rest.first() { + let obu_type = (header >> 3) & 0xf; + if obu_type != SEQUENCE_HEADER && obu_type != METADATA { + return Err(VideoError::Malformed(format!("AV1: av1C holds OBU type {obu_type}, not a sequence header or metadata"))); + } + // obu_extension_flag adds a byte; without obu_has_size_field the OBU runs to the end + let start = 1 + usize::from(header & 4 != 0); + let body = rest.get(start..).ok_or_else(|| VideoError::Malformed("AV1: av1C OBU header truncated".into()))?; + rest = if header & 2 != 0 { + let (size, n) = av1::decode::bits::leb128(body)?; + let end = usize::try_from(size).ok().and_then(|s| s.checked_add(n)); + end.and_then(|end| body.get(end..)).ok_or_else(|| VideoError::Malformed("AV1: av1C OBU truncated".into()))? + } else { + &[] + }; + } + Ok(obus) +} + +/// Apply `av1C` config OBUs (sequence headers and metadata, checked by [`av1c_config_obus`]). +#[cfg(feature = "av1-decode")] +fn configure_av1(dec: &mut av1::decode::Decoder, config_obus: &[u8]) -> Result<(), VideoError> { + if !config_obus.is_empty() { + dec.decode_pts(config_obus, 0)?; + } + Ok(()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/video/src/track/tests.rs b/crates/video/src/track/tests.rs new file mode 100644 index 000000000..5b20e81f1 --- /dev/null +++ b/crates/video/src/track/tests.rs @@ -0,0 +1,266 @@ +//! Unit tests of the track decoder: codec selection, configuration checks and the frames kept +//! from a failed call. Decoding real streams is in `tests/track`. + +use super::*; + +fn params(codec: CodecId, extradata: &[u8]) -> CodecParams { + CodecParams::new(codec).with_extradata(extradata.to_vec()) +} + +fn new_err(codec: CodecId, extradata: &[u8]) -> VideoError { + match TrackDecoder::new(¶ms(codec, extradata)) { + Ok(_) => panic!("{codec:?} with extradata {extradata:02x?} was accepted"), + Err(e) => e, + } +} + +#[test] +fn a_codec_without_a_decoder_is_unsupported() { + let off = [ + CodecId::Theora, + CodecId::Aac, + CodecId::Unknown, + #[cfg(not(feature = "h264-decode"))] + CodecId::H264, + #[cfg(not(feature = "hevc-decode"))] + CodecId::Hevc, + #[cfg(not(feature = "vp9-decode"))] + CodecId::Vp9, + #[cfg(not(feature = "av1-decode"))] + CodecId::Av1, + #[cfg(not(feature = "mpeg2-decode"))] + CodecId::Mpeg2Video, + ]; + for codec in off { + let err = new_err(codec, &[]); + assert!(matches!(err, VideoError::Unsupported(_)), "{codec:?}: {err}"); + assert!(err.to_string().contains(codec.name()), "{err}"); + } +} + +#[test] +fn every_built_decoder_starts_without_configuration() { + let on = [ + #[cfg(feature = "h264-decode")] + CodecId::H264, + #[cfg(feature = "hevc-decode")] + CodecId::Hevc, + #[cfg(feature = "vp9-decode")] + CodecId::Vp9, + #[cfg(feature = "av1-decode")] + CodecId::Av1, + #[cfg(feature = "mpeg2-decode")] + CodecId::Mpeg2Video, + ]; + for codec in on { + let mut dec = TrackDecoder::new(¶ms(codec, &[])).unwrap(); + assert_eq!(dec.codec(), codec); + assert!(dec.flush().unwrap().is_empty(), "{codec:?}"); + dec.reset().unwrap(); + assert!(dec.decode(&[], 0).unwrap_or_default().is_empty(), "{codec:?}"); + } +} + +#[test] +fn track_decoder_is_send() { + fn send() {} + send::(); +} + +/// An Annex B configuration that holds a slice would start a picture: it is refused before any +/// NAL unit reaches the decoder (which would report the slice's missing parameter set instead). +#[cfg(feature = "h264-decode")] +#[test] +fn h264_annex_b_configuration_with_a_slice_is_refused() { + let err = new_err(CodecId::H264, &[0, 0, 0, 1, 0x65, 0x88, 0x84, 0x00]); + assert!(matches!(err, VideoError::Malformed(_)), "{err}"); + assert!(err.to_string().contains("NAL unit type 5"), "{err}"); +} + +#[cfg(feature = "hevc-decode")] +#[test] +fn hevc_annex_b_configuration_with_a_slice_is_refused() { + // IDR_W_RADL (19): (19 << 1) = 0x26 + let err = new_err(CodecId::Hevc, &[0, 0, 1, 0x26, 0x01, 0xaf, 0x00]); + assert!(matches!(err, VideoError::Malformed(_)), "{err}"); + assert!(err.to_string().contains("NAL unit type 19"), "{err}"); +} + +/// A picture after a valid sequence header is refused, not decoded and then dropped. +#[cfg(feature = "mpeg2-decode")] +#[test] +fn mpeg2_configuration_with_a_picture_is_refused() { + // 32x32, 4:3, 25 fps + let header = [0, 0, 1, 0xb3, 0x02, 0x00, 0x20, 0x23, 0xff, 0xff, 0xe0, 0x18]; + assert!(TrackDecoder::new(¶ms(CodecId::Mpeg2Video, &header)).is_ok()); + // a picture header (I picture) and the start of its first slice + let picture = [0, 0, 1, 0x00, 0x00, 0x0f, 0xff, 0xf8, 0, 0, 1, 0x01, 0x12, 0x34]; + let err = new_err(CodecId::Mpeg2Video, &[&header[..], &picture].concat()); + assert!(matches!(err, VideoError::Malformed(_)), "{err}"); + assert!(err.to_string().contains("start code 0x00"), "{err}"); +} + +/// A record that is neither Annex B nor version 1 is the codec's own error. +#[cfg(feature = "h264-decode")] +#[test] +fn h264_configuration_that_is_not_avcc_is_refused() { + let err = new_err(CodecId::H264, &[2, 0x42, 0, 0x1e, 0xff, 0xe0, 0]); + assert!(matches!(err, VideoError::Malformed(_)), "{err}"); + assert!(err.to_string().contains("avcC"), "{err}"); +} + +#[cfg(feature = "av1-decode")] +mod av1c { + use super::*; + + const HEADER: [u8; 4] = [0x81, 0x00, 0x0c, 0x00]; + + fn with_obus(obus: &[u8]) -> Vec { + [&HEADER[..], obus].concat() + } + + #[test] + fn empty_and_header_only_records_hold_no_obus() { + assert_eq!(av1c_config_obus(&[]).unwrap(), &[] as &[u8]); + assert_eq!(av1c_config_obus(&HEADER).unwrap(), &[] as &[u8]); + } + + #[test] + fn sequence_headers_and_metadata_pass() { + // a sequence header (size 2), one with an extension byte (size 0), metadata (size 1), and + // a sequence header without a size field that runs to the end + let obus = [0x0a, 2, 0xaa, 0xbb, 0x0e, 0x00, 0, 0x2a, 1, 0xcc, 0x08, 0xdd, 0xee]; + assert_eq!(av1c_config_obus(&with_obus(&obus)).unwrap(), &obus); + } + + #[test] + fn a_record_that_is_not_av1c_version_1_is_refused() { + for bad in [&[0x81, 0, 0][..], &[0x80, 0, 0, 0], &[0x82, 0, 0, 0], &[0x0a, 0, 0, 0, 0]] { + let err = av1c_config_obus(bad).unwrap_err(); + assert!(err.to_string().contains("not an av1C record"), "{bad:02x?}: {err}"); + } + } + + #[test] + fn a_frame_or_temporal_delimiter_is_refused() { + // temporal delimiter (2), frame header (3), tile group (4), frame (6), after a valid OBU + for t in [2u8, 3, 4, 6] { + let obus = [0x0a, 0, (t << 3) | 2, 0]; + let err = av1c_config_obus(&with_obus(&obus)).unwrap_err(); + assert!(err.to_string().contains(&format!("OBU type {t}")), "{t}: {err}"); + } + assert!(matches!(new_err(CodecId::Av1, &with_obus(&[0x32, 0])), VideoError::Malformed(_))); + } + + #[test] + fn truncated_obus_are_refused() { + for obus in [&[0x0a, 5, 1, 2][..], &[0x0a, 0x80], &[0x0a, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff], &[0x0e]] { + let err = av1c_config_obus(&with_obus(obus)).unwrap_err(); + assert!(matches!(err, VideoError::Malformed(_)), "{obus:02x?}: {err}"); + } + } + + #[test] + fn hostile_records_do_not_panic() { + let seed = with_obus(&[0x0a, 2, 0xaa, 0xbb, 0x2a, 1, 0xcc]); + craft_media_testkit::hostile::hammer("av1C config OBUs", &seed, 2000, |data| { + let _ = av1c_config_obus(data); + }); + } +} + +/// Configuration bytes of every codec, damaged, never panic the decoder that applies them. +#[test] +fn hostile_configuration_does_not_panic() { + let seeds: &[(CodecId, &[u8])] = &[ + #[cfg(feature = "h264-decode")] + (CodecId::H264, &[1, 0x42, 0xc0, 0x1e, 0xff, 0xe1, 0x00, 0x04, 0x67, 0x42, 0xc0, 0x1e, 0x01, 0x00, 0x02, 0x68, 0xce]), + #[cfg(feature = "h264-decode")] + (CodecId::H264, &[0, 0, 0, 1, 0x67, 0x42, 0xc0, 0x1e, 0, 0, 1, 0x68, 0xce]), + #[cfg(feature = "hevc-decode")] + (CodecId::Hevc, &[0, 0, 0, 1, 0x40, 0x01, 0x0c, 0, 0, 1, 0x42, 0x01, 0x01, 0, 0, 1, 0x44, 0x01, 0xc1]), + #[cfg(feature = "av1-decode")] + (CodecId::Av1, &[0x81, 0x00, 0x0c, 0x00, 0x0a, 0x0b, 0x00, 0x00, 0x00, 0x24, 0xc4, 0xff, 0xdf, 0x00, 0x68, 0x02, 0x10]), + #[cfg(feature = "mpeg2-decode")] + (CodecId::Mpeg2Video, &[0, 0, 1, 0xb3, 0x02, 0x00, 0x20, 0x13, 0xff, 0xff, 0xe0, 0x18, 0, 0, 1, 0xb5, 0x14, 0x8a, 0x00, 0x01, 0x00, 0x00]), + ]; + for &(codec, seed) in seeds { + craft_media_testkit::hostile::hammer(codec.name(), seed, 300, move |data| { + if let Ok(mut dec) = TrackDecoder::new(¶ms(codec, data)) { + let _ = dec.reset(); + } + }); + } +} + +#[cfg(feature = "h264-decode")] +mod held { + use super::*; + + /// A 4x2 picture with timestamp `pts`; `y_len` other than 8 makes it fail to convert. + fn picture(y_len: usize, pts: i64) -> h264::decode::Picture { + h264::decode::Picture { + width: 4, + height: 2, + chroma_width: 2, + chroma_height: 1, + y: vec![16; y_len], + u: vec![128; 2], + v: vec![128; 2], + y_stride: 4, + uv_stride: 2, + pts, + poc: 0, + key: true, + color: h264::decode::ColorInfo { full_range: false, primaries: 1, transfer: 1, matrix: 1 }, + sar: (0, 0), + draft: false, + } + } + + fn decoder() -> TrackDecoder { + TrackDecoder::new(¶ms(CodecId::H264, &[])).unwrap() + } + + fn pts(frames: &[VideoFrame]) -> Vec> { + frames.iter().map(|f| f.pts).collect() + } + + /// A picture that does not convert fails the call; the others come with the next call, ahead + /// of its own frames and in order. + #[test] + fn frames_around_a_picture_that_does_not_convert_come_next() { + let mut dec = decoder(); + let err = dec.output(vec![picture(8, 1), picture(3, 2), picture(8, 3)], None).unwrap_err(); + assert!(matches!(err, VideoError::Frame(FrameError::Plane(_))), "{err}"); + assert_eq!(pts(&dec.output(vec![picture(8, 4)], None).unwrap()), [Some(1), Some(3), Some(4)]); + assert!(dec.output(Vec::::new(), None).unwrap().is_empty()); + } + + /// An error reported with the pictures (a flush whose decoding job failed) keeps them too. + #[test] + fn frames_finished_with_an_error_come_next() { + let mut dec = decoder(); + let err = dec.output(vec![picture(8, 1)], Some(VideoError::Malformed("job".into()))).unwrap_err(); + assert!(matches!(err, VideoError::Malformed(_))); + assert_eq!(pts(&dec.flush().unwrap()), [Some(1)]); + } + + /// An error from the codec itself leaves the kept frames for the call after it. + #[test] + fn a_failed_packet_does_not_drop_kept_frames() { + let mut dec = decoder(); + assert!(dec.output(vec![picture(8, 1), picture(0, 2)], None).is_err()); + // an IDR slice without parameter sets + assert!(dec.decode(&[0, 0, 1, 0x65, 0x88, 0x84], 5).is_err()); + assert_eq!(pts(&dec.decode(&[], 6).unwrap()), [Some(1)]); + } + + #[test] + fn reset_drops_kept_frames() { + let mut dec = decoder(); + assert!(dec.output(vec![picture(8, 1), picture(0, 2)], None).is_err()); + dec.reset().unwrap(); + assert!(dec.flush().unwrap().is_empty()); + } +} diff --git a/crates/video/tests/track/av1.rs b/crates/video/tests/track/av1.rs new file mode 100644 index 000000000..cef856f2b --- /dev/null +++ b/crates/video/tests/track/av1.rs @@ -0,0 +1,72 @@ +//! AV1 in MP4 (an `av1C` record whose config OBUs hold the sequence header). + +use crate::common; +use craft_media::CodecId; + +/// libaom when ffmpeg has it, else SVT-AV1: a fixture name and the encoder arguments. +fn encoder() -> Option<(&'static str, &'static [&'static str])> { + if common::has_encoder("libaom-av1") { + Some(("av1_aom", &["-c:v", "libaom-av1", "-cpu-used", "8", "-b:v", "300k", "-g", "12", "-pix_fmt", "yuv420p"])) + } else if common::has_encoder("libsvtav1") { + Some(("av1_svt", &["-c:v", "libsvtav1", "-preset", "12", "-g", "12", "-pix_fmt", "yuv420p"])) + } else { + craft_media_testkit::skip("ffmpeg has neither libaom-av1 nor libsvtav1") + } +} + +fn fixture() -> Option<(common::Track, common::Fixture)> { + let (name, args) = encoder()?; + let f = common::fixture(name, "mp4", args, "yuv420p")?; + let track = common::mp4(&f.file); + assert_eq!(track.params.codec, CodecId::Av1); + Some((track, f)) +} + +/// The OBUs of a packet as (type, bytes); every OBU has a size field, as MP4 stores them. +fn obus(data: &[u8]) -> Vec<(u8, &[u8])> { + let mut out = Vec::new(); + let mut pos = 0; + while pos < data.len() { + let header = data[pos]; + assert!(header & 2 != 0, "an OBU without a size field"); + let mut p = pos + 1 + usize::from(header & 4 != 0); + let mut size = 0usize; + for i in 0.. { + let b = data[p]; + p += 1; + size |= usize::from(b & 0x7f) << (7 * i); + if b & 0x80 == 0 { + break; + } + } + out.push(((header >> 3) & 0xf, &data[pos..p + size])); + pos = p + size; + } + out +} + +#[test] +fn mp4_av1c() { + let Some((track, f)) = fixture() else { return }; + common::check_track(&track, &f); +} + +/// With every sequence header taken out of the packets, the one in `av1C` is what decodes them. +/// +/// The record's config OBUs are the stream's own sequence header: SVT-AV1 writes `av1C` before it +/// encodes, with a sequence header that differs from the one it then puts in the stream. +#[test] +fn sequence_header_from_av1c() { + let Some((mut track, f)) = fixture() else { return }; + let header = obus(&track.packets[0].data).into_iter().find(|o| o.0 == 1).unwrap().1.to_vec(); + track.params.extradata = [&track.params.extradata[..4], &header].concat(); + for p in &mut track.packets { + p.data = obus(&p.data).into_iter().filter(|o| o.0 != 1).flat_map(|o| o.1.to_vec()).collect(); + } + let mut bare = track.clone(); + bare.params.extradata.clear(); + let mut dec = craft_video::TrackDecoder::new(&bare.params).unwrap(); + let decoded = bare.packets.iter().filter_map(|p| dec.decode(&p.data, p.pts).ok()).flatten().count(); + assert_eq!(decoded, 0, "the packets decode without a sequence header"); + common::check_track(&track, &f); +} diff --git a/crates/video/tests/track/common/mod.rs b/crates/video/tests/track/common/mod.rs new file mode 100644 index 000000000..bd3f14461 --- /dev/null +++ b/crates/video/tests/track/common/mod.rs @@ -0,0 +1,201 @@ +//! Fixtures (ffmpeg encodes a short clip into a container), demuxing with craft-media, ffmpeg's +//! own decode of each fixture as the reference, and the checks every codec runs. +#![allow(dead_code)] + +use craft_media::CodecParams; +use craft_video::TrackDecoder; +use craft_video::frame::{Samples, VideoFrame}; +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// Frames in every fixture. +pub const FRAMES: usize = 24; + +/// One packet of a demuxed track, in decode order. +#[derive(Clone)] +pub struct Packet { + pub data: Vec, + pub pts: i64, + /// The container marks it as a random access point. + pub key: bool, +} + +/// A demuxed video track. +#[derive(Clone)] +pub struct Track { + pub params: CodecParams, + pub packets: Vec, +} + +/// A fixture and ffmpeg's decode of it. +pub struct Fixture { + pub file: PathBuf, + /// Raw frames in display order, planes one after another, 16-bit samples little-endian. + pub reference: Vec, + /// How far a sample may be from the reference: 0 (bit-exact) unless a test sets it. + pub max_diff: u8, +} + +/// Lowest PSNR of a frame decoded within a tolerance, as the MPEG-2 oracle tests require. +const MIN_PSNR: f64 = 58.0; + +/// `name.ext` made by ffmpeg from 24 frames of a noisy test pattern at 176x144, with `args` +/// choosing the encoder, and its decode as `pix_fmt` raw video. `None` (a skip) without ffmpeg or +/// the encoder; a failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`. +pub fn fixture(name: &str, ext: &str, args: &[&str], pix_fmt: &str) -> Option { + let ff = craft_media_testkit::ffmpeg()?; + let dir = craft_media_testkit::fixture_subdir("video-track"); + let required = craft_media_testkit::oracles_required(); + let file = dir.join(format!("{name}.{ext}")); + let raw = dir.join(format!("{name}.{ext}.{pix_fmt}.raw")); + craft_media_testkit::generate_and_report(name, &[file.clone(), raw.clone()], || { + if !file.exists() { + let tmp = craft_media_testkit::temp_path(&file); + let mut cmd = Command::new(&ff); + cmd.args(["-hide_banner", "-loglevel", "error", "-y", "-f", "lavfi", "-i"]) + .arg("testsrc2=size=176x144:rate=25,noise=alls=12:allf=t+u") + .args(["-frames:v", &FRAMES.to_string(), "-an"]) + .args(args) + .arg(&tmp); + craft_media_testkit::run_generator(&mut cmd, &tmp, &file, required)?; + } + if !raw.exists() { + let tmp = craft_media_testkit::temp_path(&raw); + let mut cmd = Command::new(&ff); + cmd.args(["-hide_banner", "-loglevel", "error", "-y", "-i"]) + .arg(&file) + .args(["-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", pix_fmt]) + .arg(&tmp); + craft_media_testkit::run_generator(&mut cmd, &tmp, &raw, required)?; + } + Some(Fixture { reference: std::fs::read(&raw).unwrap(), file: file.clone(), max_diff: 0 }) + }) +} + +/// Whether ffmpeg has `encoder`, without skipping. +pub fn has_encoder(encoder: &str) -> bool { + craft_media_testkit::tool("ffmpeg").is_some_and(|ff| craft_media_testkit::ffmpeg_has_encoder(&ff, encoder)) +} + +/// The video track of an MP4 file. +pub fn mp4(path: &Path) -> Track { + use craft_media::isobmff::{TrackKind, open}; + let bytes = std::fs::read(path).unwrap(); + let file = open(bytes.as_slice()).unwrap(); + let t = file.track_of_kind(TrackKind::Video).unwrap(); + let track = &file.tracks[t]; + let packets = (track.samples.iter().enumerate()) + .map(|(i, s)| Packet { data: file.read_sample(bytes.as_slice(), t, i).unwrap(), pts: s.pts, key: s.is_sync }) + .collect(); + Track { params: track.codec_params(), packets } +} + +/// The video stream of an MPEG transport stream. +pub fn ts(path: &Path) -> Track { + use craft_media::mpegts::{Kind, open}; + let bytes = std::fs::read(path).unwrap(); + let file = open(bytes.as_slice()).unwrap(); + let s = file.find(Kind::Video, |_| true).unwrap(); + let stream = &file.streams[s]; + let packets = (stream.units.iter().enumerate()) + .map(|(i, u)| Packet { data: file.read_unit(bytes.as_slice(), s, i).unwrap(), pts: u.pts.unwrap(), key: u.key }) + .collect(); + Track { params: stream.codec_params(), packets } +} + +/// The video stream of an AVI file. AVI has no timestamps: a chunk's index stands in. +pub fn avi(path: &Path) -> Track { + use craft_media::avi::{StreamKind, open}; + let bytes = std::fs::read(path).unwrap(); + let file = open(bytes.as_slice()).unwrap(); + let s = file.streams.iter().position(|s| s.kind == StreamKind::Video).unwrap(); + let stream = &file.streams[s]; + let packets = (stream.chunks.iter().enumerate()) + .map(|(i, c)| Packet { data: file.read_chunk(bytes.as_slice(), s, i).unwrap(), pts: i as i64, key: c.key }) + .collect(); + Track { params: stream.codec_params(), packets } +} + +/// Decode `packets` with `dec` and flush it. +pub fn run(dec: &mut TrackDecoder, packets: &[Packet]) -> Vec { + let mut frames = Vec::new(); + for (i, p) in packets.iter().enumerate() { + frames.extend(dec.decode(&p.data, p.pts).unwrap_or_else(|e| panic!("packet {i}: {e}"))); + } + frames.extend(dec.flush().unwrap()); + frames +} + +/// Every frame of `track`, from a new decoder. +pub fn decode(track: &Track) -> Vec { + run(&mut TrackDecoder::new(&track.params).unwrap(), &track.packets) +} + +/// The samples of `frame`, planes one after another, as ffmpeg's raw video has them: a byte per +/// sample up to 8 bits (whatever the storage; AV1 stores 8-bit samples in `u16`), else two bytes +/// little-endian. +pub fn frame_bytes(frame: &VideoFrame) -> Vec { + let mut out = Vec::new(); + for p in frame.planes() { + for y in 0..p.height() { + match p.samples() { + Samples::U8(_) => out.extend_from_slice(p.row_u8(y).unwrap()), + Samples::U16(_) if p.bit_depth() <= 8 => out.extend(p.row_u16(y).unwrap().iter().map(|&s| u8::try_from(s).unwrap())), + Samples::U16(_) => out.extend(p.row_u16(y).unwrap().iter().flat_map(|s| s.to_le_bytes())), + } + } + } + out +} + +/// `frames` are every frame of `track` in display order, each with the timestamp of the packet +/// that coded it, and their samples are ffmpeg's (within `fixture.max_diff`). +pub fn check_frames(track: &Track, frames: &[VideoFrame], fixture: &Fixture) { + let reference = &fixture.reference; + assert_eq!(frames.len(), FRAMES, "frame count"); + let got: Vec = frames.iter().map(|f| f.pts.unwrap()).collect(); + let mut want: Vec = track.packets.iter().map(|p| p.pts).collect(); + want.sort_unstable(); + assert_eq!(got, want, "timestamps in display order"); + let size = reference.len() / FRAMES; + assert_eq!(size * FRAMES, reference.len(), "reference size"); + for (i, (frame, want)) in frames.iter().zip(reference.chunks(size)).enumerate() { + assert_eq!((frame.width(), frame.height()), (176, 144), "frame {i} size"); + let got = frame_bytes(frame); + assert_eq!(got.len(), want.len(), "frame {i} bytes"); + let diff: Vec = (0..got.len()).filter(|&k| got[k] != want[k]).collect(); + let max = diff.iter().map(|&k| got[k].abs_diff(want[k])).max().unwrap_or(0); + let what = format!("frame {i} (pts {:?}): {} of {} bytes differ from ffmpeg's decode, by up to {max}", frame.pts, diff.len(), got.len()); + if fixture.max_diff == 0 { + assert!(diff.is_empty(), "{what}"); + } else { + let sse: f64 = diff.iter().map(|&k| f64::from(got[k].abs_diff(want[k])).powi(2)).sum(); + let psnr = if sse == 0.0 { f64::INFINITY } else { 10.0 * (255.0f64.powi(2) * got.len() as f64 / sse).log10() }; + assert!(max <= fixture.max_diff && psnr >= MIN_PSNR, "{what}, PSNR {psnr:.1} dB"); + } + } +} + +/// Decode `track`, check it against `fixture`'s reference, then reset the decoder twice: once +/// halfway through, decoding the whole track again, and once to decode from its last key packet +/// (a seek), which gives the frames of the packets from there on. +pub fn check_track(track: &Track, fixture: &Fixture) { + let frames = decode(track); + check_frames(track, &frames, fixture); + + let mut dec = TrackDecoder::new(&track.params).unwrap(); + let half = track.packets.len() / 2; + for p in &track.packets[..half] { + dec.decode(&p.data, p.pts).unwrap(); + } + dec.reset().unwrap(); + assert!(run(&mut dec, &track.packets) == frames, "decoding again after a reset"); + + let key = track.packets.iter().rposition(|p| p.key).unwrap(); + assert!(key > 0, "the track has a second key packet"); + dec.reset().unwrap(); + let seek = run(&mut dec, &track.packets[key..]); + let pts: Vec = track.packets[key..].iter().map(|p| p.pts).collect(); + let want: Vec<&VideoFrame> = frames.iter().filter(|f| pts.contains(&f.pts.unwrap())).collect(); + assert!(seek.iter().eq(want.iter().copied()), "decoding from key packet {key} after a reset"); +} diff --git a/crates/video/tests/track/h264.rs b/crates/video/tests/track/h264.rs new file mode 100644 index 000000000..74a9477de --- /dev/null +++ b/crates/video/tests/track/h264.rs @@ -0,0 +1,63 @@ +//! H.264 in MP4 (an `avcC` record, length-prefixed packets), MPEG-TS (Annex B, no configuration) +//! and AVI with the parameter sets in the stream header only (an Annex B configuration). + +use crate::common; +use craft_media::CodecId; +use craft_video::{TrackDecoder, VideoError}; + +const X264: &[&str] = &["-c:v", "libx264", "-preset", "fast", "-bf", "2", "-g", "12", "-pix_fmt", "yuv420p"]; + +/// The NAL unit types of an Annex B packet. +fn nal_types(data: &[u8]) -> Vec { + craft_media::bitstream::annexb_nals(data).iter().filter_map(|n| n.first()).map(|b| b & 0x1f).collect() +} + +/// The parameter sets are in the `avcC` record only, so decoding again after a reset needs them +/// applied again. +#[test] +fn mp4_avcc() { + let Some(f) = common::fixture("h264_avcc", "mp4", X264, "yuv420p") else { return }; + let track = common::mp4(&f.file); + assert_eq!((track.params.codec, track.params.extradata.first()), (CodecId::H264, Some(&1)), "an avcC record"); + common::check_track(&track, &f); +} + +#[test] +fn ts_annex_b() { + let Some(f) = common::fixture("h264", "ts", X264, "yuv420p") else { return }; + let track = common::ts(&f.file); + assert_eq!((track.params.codec, track.params.extradata.len()), (CodecId::H264, 0)); + common::check_track(&track, &f); +} + +fn global_header_avi() -> Option<(common::Track, common::Fixture)> { + let args = ["-c:v", "libx264", "-preset", "fast", "-bf", "0", "-g", "12", "-pix_fmt", "yuv420p", "-flags", "+global_header"]; + let f = common::fixture("h264_global_header", "avi", &args, "yuv420p")?; + let track = common::avi(&f.file); + assert_eq!(track.params.codec, CodecId::H264); + assert_eq!(nal_types(&track.params.extradata).iter().filter(|&&t| t == 7 || t == 8).count(), 2, "an SPS and a PPS in the stream header"); + for (i, p) in track.packets.iter().enumerate() { + assert!(!nal_types(&p.data).contains(&7), "chunk {i} repeats the SPS"); + } + Some((track, f)) +} + +/// AVI written with global headers: the chunks need the parameter sets from the stream header. +#[test] +fn avi_annex_b_configuration() { + let Some((track, f)) = global_header_avi() else { return }; + common::check_track(&track, &f); +} + +/// Annex B configuration with the first picture's slice after the parameter sets is refused, +/// rather than decoding that picture into the reference store. +#[test] +fn annex_b_configuration_with_a_slice_is_refused() { + let Some((mut track, _)) = global_header_avi() else { return }; + track.params.extradata.extend_from_slice(&track.packets[0].data); + assert!(nal_types(&track.params.extradata).contains(&5), "an IDR slice"); + match TrackDecoder::new(&track.params) { + Err(VideoError::Malformed(m)) => assert!(m.contains("NAL unit type 5"), "{m}"), + other => panic!("{other:?}"), + } +} diff --git a/crates/video/tests/track/hevc.rs b/crates/video/tests/track/hevc.rs new file mode 100644 index 000000000..ac2cf672d --- /dev/null +++ b/crates/video/tests/track/hevc.rs @@ -0,0 +1,68 @@ +//! HEVC in MP4 (an `hvcC` record, length-prefixed packets) and MPEG-TS (Annex B, no +//! configuration), 8-bit and 10-bit. + +use crate::common; +use craft_media::CodecId; + +/// Closed GOPs every 12 frames with B-frames, so decoding from a key packet gives every frame +/// from there on. +const X265: &[&str] = &["-c:v", "libx265", "-preset", "fast", "-x265-params", "log-level=error:keyint=12:min-keyint=12:open-gop=0:bframes=2"]; + +fn args(pix_fmt: &str, mp4: bool) -> Vec<&str> { + let mut a = X265.to_vec(); + a.extend(["-pix_fmt", pix_fmt]); + if mp4 { + a.extend(["-tag:v", "hvc1"]); + } + a +} + +/// The parameter sets are in the `hvcC` record only, so decoding again after a reset needs them +/// applied again. +#[test] +fn mp4_hvcc() { + let Some(f) = common::fixture("hevc_hvcc", "mp4", &args("yuv420p", true), "yuv420p") else { return }; + let track = common::mp4(&f.file); + assert_eq!((track.params.codec, track.params.extradata.first()), (CodecId::Hevc, Some(&1)), "an hvcC record"); + common::check_track(&track, &f); +} + +#[test] +fn mp4_hvcc_10bit() { + let Some(f) = common::fixture("hevc_hvcc_10bit", "mp4", &args("yuv420p10le", true), "yuv420p10le") else { return }; + let track = common::mp4(&f.file); + let frames = common::decode(&track); + assert!(frames.iter().all(|f| f.bit_depth() == 10)); + common::check_track(&track, &f); +} + +#[test] +fn ts_annex_b() { + let Some(f) = common::fixture("hevc", "ts", &args("yuv420p", false), "yuv420p") else { return }; + let track = common::ts(&f.file); + assert_eq!((track.params.codec, track.params.extradata.len()), (CodecId::Hevc, 0)); + common::check_track(&track, &f); +} + +/// The NAL unit types of an Annex B packet. +fn nal_types(data: &[u8]) -> Vec { + craft_media::bitstream::annexb_nals(data).iter().filter_map(|n| n.first()).map(|b| (b >> 1) & 0x3f).collect() +} + +/// AVI written with global headers: the chunks need the VPS, SPS and PPS from the stream header. +/// (ffmpeg writes an empty FourCC for HEVC in AVI unless it is given one.) +#[test] +fn avi_annex_b_configuration() { + // AVI has no timestamps (a chunk's index stands in), so no B-frames. + let params = "log-level=error:keyint=12:min-keyint=12:open-gop=0:bframes=0"; + let a = ["-c:v", "libx265", "-preset", "fast", "-x265-params", params, "-pix_fmt", "yuv420p", "-flags", "+global_header", "-tag:v", "HEVC"]; + let Some(f) = common::fixture("hevc_global_header", "avi", &a, "yuv420p") else { return }; + let track = common::avi(&f.file); + assert_eq!(track.params.codec, CodecId::Hevc); + let sets = nal_types(&track.params.extradata); + assert!([32, 33, 34].iter().all(|t| sets.contains(t)), "a VPS, an SPS and a PPS in the stream header: {sets:?}"); + for (i, p) in track.packets.iter().enumerate() { + assert!(!nal_types(&p.data).contains(&33), "chunk {i} repeats the SPS"); + } + common::check_track(&track, &f); +} diff --git a/crates/video/tests/track/main.rs b/crates/video/tests/track/main.rs new file mode 100644 index 000000000..425302df4 --- /dev/null +++ b/crates/video/tests/track/main.rs @@ -0,0 +1,18 @@ +//! `TrackDecoder` on real streams: ffmpeg encodes a short clip into MP4, MPEG-TS or AVI, +//! craft-media demuxes it, and the decoder's frames must be ffmpeg's decode of the file, in display +//! order, with the timestamps of the packets that coded them. Each codec also checks that a reset +//! decodes the track again and decodes from a later key packet. +#![cfg(any(feature = "h264-decode", feature = "hevc-decode", feature = "vp9-decode", feature = "av1-decode", feature = "mpeg2-decode"))] + +mod common; + +#[cfg(feature = "av1-decode")] +mod av1; +#[cfg(feature = "h264-decode")] +mod h264; +#[cfg(feature = "hevc-decode")] +mod hevc; +#[cfg(feature = "mpeg2-decode")] +mod mpeg2; +#[cfg(feature = "vp9-decode")] +mod vp9; diff --git a/crates/video/tests/track/mpeg2.rs b/crates/video/tests/track/mpeg2.rs new file mode 100644 index 000000000..e0fc19328 --- /dev/null +++ b/crates/video/tests/track/mpeg2.rs @@ -0,0 +1,55 @@ +//! MPEG-2 video in MPEG-TS (no configuration), and with its sequence header moved from the +//! packets into `extradata`. + +use crate::common; +use craft_media::CodecId; + +/// Closed GOPs every 12 frames with B-frames (ffmpeg's encoder needs scene change detection off +/// for closed GOPs). +const MPEG2: &[&str] = + &["-c:v", "mpeg2video", "-bf", "2", "-g", "12", "-flags", "+cgop", "-sc_threshold", "1000000000", "-q:v", "4", "-pix_fmt", "yuv420p"]; + +/// MPEG-2's IDCT is not bit-exact by definition (any IEEE 1180-accurate IDCT conforms), so the +/// frames are compared with ffmpeg's within the MPEG-2 oracle tests' tolerance. +fn fixture() -> Option<(common::Track, common::Fixture)> { + let mut f = common::fixture("mpeg2", "ts", MPEG2, "yuv420p")?; + f.max_diff = 4; + let track = common::ts(&f.file); + assert_eq!((track.params.codec, track.params.extradata.len()), (CodecId::Mpeg2Video, 0)); + Some((track, f)) +} + +/// The byte range of the sequence header and its extensions in `data`: from the sequence header +/// start code to the next start code that is not an extension. +fn sequence_header(data: &[u8]) -> Option> { + let codes: Vec<(usize, u8)> = (0..data.len().saturating_sub(3)).filter(|&i| data[i..i + 3] == [0, 0, 1]).map(|i| (i, data[i + 3])).collect(); + let k = codes.iter().position(|c| c.1 == 0xb3)?; + let end = codes[k + 1..].iter().find(|c| c.1 != 0xb5).map_or(data.len(), |c| c.0); + Some(codes[k].0..end) +} + +#[test] +fn ts() { + let Some((track, f)) = fixture() else { return }; + common::check_track(&track, &f); +} + +/// With every sequence header taken out of the packets, the one in `extradata` is what decodes +/// them, before and after a reset. +#[test] +fn sequence_header_from_extradata() { + let Some((mut track, f)) = fixture() else { return }; + let first = sequence_header(&track.packets[0].data).unwrap(); + track.params.extradata = track.packets[0].data[first].to_vec(); + for p in &mut track.packets { + while let Some(r) = sequence_header(&p.data) { + p.data.drain(r); + } + } + let mut bare = track.clone(); + bare.params.extradata.clear(); + let mut dec = craft_video::TrackDecoder::new(&bare.params).unwrap(); + let decoded = bare.packets.iter().filter_map(|p| dec.decode(&p.data, p.pts).ok()).flatten().count(); + assert_eq!(decoded, 0, "the packets decode without a sequence header"); + common::check_track(&track, &f); +} diff --git a/crates/video/tests/track/vp9.rs b/crates/video/tests/track/vp9.rs new file mode 100644 index 000000000..3fd75484c --- /dev/null +++ b/crates/video/tests/track/vp9.rs @@ -0,0 +1,14 @@ +//! VP9 in MP4 (a `vpcC` record, which the decoder does not need). + +use crate::common; +use craft_media::CodecId; + +#[test] +fn mp4() { + let args = ["-c:v", "libvpx-vp9", "-deadline", "good", "-cpu-used", "5", "-b:v", "400k", "-g", "12", "-pix_fmt", "yuv420p"]; + let Some(f) = common::fixture("vp9", "mp4", &args, "yuv420p") else { return }; + let track = common::mp4(&f.file); + assert_eq!(track.params.codec, CodecId::Vp9); + assert!(!track.params.extradata.is_empty(), "a vpcC record"); + common::check_track(&track, &f); +}