Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

M8: MP4 and Matroska colour from the bitstream when the container has none

lloydd7b7027f420d
diff --git a/crates/codecs/src/hw_frame.rs b/crates/codecs/src/hw_frame.rs
index 59537d808..b37fc4d01 100644
--- a/crates/codecs/src/hw_frame.rs
+++ b/crates/codecs/src/hw_frame.rs
@@ -53,7 +53,7 @@ pub struct FrameStreamInfo {
}
/// The OBUs of a low-overhead AV1 sample: `(type, payload)`, stopping at the first malformed one.
-fn obus(data: &[u8]) -> Vec<(u8, &[u8])> {
+pub(crate) fn obus(data: &[u8]) -> Vec<(u8, &[u8])> {
let mut out = Vec::new();
let mut pos = 0usize;
while let Some(&h) = data.get(pos) {
diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs
index fb405cd74..a31da3a7e 100644
--- a/crates/codecs/src/lib.rs
+++ b/crates/codecs/src/lib.rs
@@ -28,6 +28,7 @@ pub mod mp4;
pub mod mpeg;
pub mod mxf;
pub mod ogg;
+mod stream_color;
pub mod video;
use std::sync::{Arc, RwLock};
@@ -178,4 +179,6 @@ mod audio_timing_tests;
#[cfg(test)]
mod rounded_pts_tests;
#[cfg(test)]
+mod stream_color_tests;
+#[cfg(test)]
mod tests;
diff --git a/crates/codecs/src/mkv.rs b/crates/codecs/src/mkv.rs
index e1fa14824..70222b378 100644
--- a/crates/codecs/src/mkv.rs
+++ b/crates/codecs/src/mkv.rs
@@ -15,7 +15,7 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
-use filmcraft_color::{ColorInfo, Matrix, Primaries, Range, Transfer};
+use filmcraft_color::{ColorInfo, Matrix, Transfer};
use filmcraft_frame::{AudioBuffer, VideoFrame};
use filmcraft_isobmff::{AvcConfig, CodecConfig, FourCc, HevcConfig, PcmConfig, SampleEntry, VpcConfig};
use filmcraft_matroska::{Codec, MkvFile, TrackKind};
@@ -24,6 +24,7 @@ use filmcraft_time::{FrameRate, Tick};
use crate::audio::{PacketDecoder, decode_pcm};
use crate::gop::{GopCache, VideoSamples};
+use crate::stream_color::ColorCodes;
use crate::video::VideoDecoder;
use crate::{CodecError, make_video_decoder};
@@ -211,32 +212,24 @@ fn hdr_metadata(c: &filmcraft_matroska::Colour) -> Option<filmcraft_color::HdrMe
})
}
-fn color_of(v: &filmcraft_matroska::VideoInfo, w: u32, h: u32) -> (ColorInfo, bool) {
- let mut c = ColorInfo { matrix: filmcraft_frame::default_matrix(w, h), transfer: Transfer::Bt709, primaries: Primaries::Bt709, range: Range::Limited };
- let Some(col) = &v.colour else { return (c, false) };
- let mut explicit = false;
- if let Some(m) = col.matrix_coefficients.and_then(|m| Matrix::from_code(m as u8)) {
- c.matrix = m;
- explicit = true;
- }
- if let Some(t) = col.transfer_characteristics.and_then(|t| Transfer::from_code(t as u8)) {
- c.transfer = t;
- explicit = true;
- }
- if let Some(p) = col.primaries {
- c.primaries = match p {
- 9 => Primaries::Bt2020,
- 12 => Primaries::P3D65,
- 5 => Primaries::Bt601_625,
- 6 => Primaries::Bt601_525,
- _ => Primaries::Bt709,
+/// Colour of a video track: the `Colour` element wins; what it leaves unspecified, or all of it
+/// when there is none, comes from the stream's own description (the SPS VUI in an `avcC` /
+/// `hvcC`, the sequence header in an `av1C`); the rest defaults by frame size. The flag says
+/// whether `Colour` signals anything that overrides the decoder.
+fn color_of(v: &filmcraft_matroska::VideoInfo, w: u32, h: u32, stream: Option<ColorCodes>) -> (ColorInfo, bool) {
+ // H.273 code points; `Range`: 1 broadcast (limited), 2 full, 0 / 3 not signalled here
+ let code = |c: Option<u64>| c.unwrap_or(2);
+ let container = v.colour.as_ref().map(|col| {
+ let range = match col.range {
+ Some(1) => Some(false),
+ Some(2) => Some(true),
+ _ => None,
};
- }
- if col.full_range() {
- c.range = Range::Full;
- explicit = true;
- }
- (c, explicit)
+ ColorCodes::from_wide(code(col.primaries), code(col.transfer_characteristics), code(col.matrix_coefficients), range)
+ });
+ let explicit = container.is_some_and(|c| Matrix::from_code(c.matrix).is_some() || Transfer::from_code(c.transfer).is_some() || c.full_range == Some(true));
+ let sources: Vec<ColorCodes> = [container, stream].into_iter().flatten().collect();
+ (crate::stream_color::resolve(w, h, &sources), explicit)
}
fn codec_label(c: &Codec) -> String {
@@ -297,11 +290,11 @@ impl MkvSource {
FrameRate::from_f64(1.0 / step)
}
};
- let (color, explicit) = color_of(&v, w, h);
+ ventry = sample_entry(&t.codec, &t.codec_private, t.video.as_ref(), w as u16, h as u16);
+ let (color, explicit) = color_of(&v, w, h, ventry.as_ref().and_then(|e| crate::stream_color::from_codec_config(&e.codec)));
if explicit {
explicit_color = Some(color);
}
- ventry = sample_entry(&t.codec, &t.codec_private, t.video.as_ref(), w as u16, h as u16);
let secs = file.duration_ns().unwrap_or(0) as f64 / 1e9;
let bitrate = (secs > 0.0).then(|| (t.samples.iter().map(|s| s.size as u64).sum::<u64>() as f64 * 8.0 / secs) as u64);
let ((w, h), par) = if rotation % 2 == 1 { ((h, w), (v.pixel_aspect().1, v.pixel_aspect().0)) } else { ((w, h), v.pixel_aspect()) };
diff --git a/crates/codecs/src/mp4.rs b/crates/codecs/src/mp4.rs
index 2cdcad31f..5e085593d 100644
--- a/crates/codecs/src/mp4.rs
+++ b/crates/codecs/src/mp4.rs
@@ -7,7 +7,7 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
-use filmcraft_color::{ColorInfo, Matrix, Primaries, Range, Transfer};
+use filmcraft_color::ColorInfo;
use filmcraft_frame::{AudioBuffer, VideoFrame};
use filmcraft_isobmff::{CodecConfig, Mp4File, TrackKind};
use filmcraft_media::{AudioStreamInfo, FrameRequest, MediaError, MediaInfo, MediaKind, MediaSource, SharedSource, VideoStreamInfo};
@@ -97,48 +97,40 @@ fn hdr_metadata(md: Option<&filmcraft_isobmff::MasteringDisplay>, cll: Option<(u
})
}
+/// Colour of a video sample entry. The `colr` box (`nclx` / `nclc`) wins; what it leaves
+/// unspecified, or all of it when there is none (ffmpeg writes MP4 without `colr` by default),
+/// comes from the stream's own description: `vpcC` / `apvC`, or the SPS VUI in `avcC` / `hvcC`
+/// and the sequence header in `av1C`. The rest defaults by frame size.
fn color_from(entry: &filmcraft_isobmff::SampleEntry, w: u32, h: u32) -> ColorInfo {
- let mut c = ColorInfo { matrix: filmcraft_frame::default_matrix(w, h), transfer: Transfer::Bt709, primaries: Primaries::Bt709, range: Range::Limited };
- // VP9 and APV carry their colour description in vpcC / apvC (used when there is no colr box).
- let vpc = match &entry.codec {
- CodecConfig::Vp9(v) => Some(filmcraft_isobmff::ColorInfo::Nclx {
- primaries: v.colour_primaries as u16,
- transfer: v.transfer_characteristics as u16,
- matrix: v.matrix_coefficients as u16,
- full_range: v.full_range,
+ use crate::stream_color::ColorCodes;
+ use filmcraft_isobmff::ColorInfo as Colr;
+ let colr = match entry.video.as_ref().and_then(|v| v.color.as_ref()) {
+ Some(Colr::Nclx { primaries, transfer, matrix, full_range }) => {
+ Some(ColorCodes::from_wide((*primaries).into(), (*transfer).into(), (*matrix).into(), Some(*full_range)))
+ }
+ // QuickTime `nclc` has no range flag
+ Some(Colr::Nclc { primaries, transfer, matrix }) => Some(ColorCodes::from_wide((*primaries).into(), (*transfer).into(), (*matrix).into(), None)),
+ // an ICC profile, or no `colr`: no code points
+ _ => None,
+ };
+ let stream = match &entry.codec {
+ CodecConfig::Vp9(v) => Some(ColorCodes {
+ primaries: v.colour_primaries,
+ transfer: v.transfer_characteristics,
+ matrix: v.matrix_coefficients,
+ full_range: Some(v.full_range),
}),
- CodecConfig::Apv(a) if a.color_description_present => Some(filmcraft_isobmff::ColorInfo::Nclx {
- primaries: a.color_primaries as u16,
- transfer: a.transfer_characteristics as u16,
- matrix: a.matrix_coefficients as u16,
- full_range: a.full_range,
+ CodecConfig::Apv(a) if a.color_description_present => Some(ColorCodes {
+ primaries: a.color_primaries,
+ transfer: a.transfer_characteristics,
+ matrix: a.matrix_coefficients,
+ full_range: Some(a.full_range),
}),
- _ => None,
+ CodecConfig::Apv(_) => None,
+ codec => crate::stream_color::from_codec_config(codec),
};
- if let Some(col) = entry.video.as_ref().and_then(|v| v.color.as_ref()).or(vpc.as_ref()) {
- let (p, t, m, full) = match col {
- filmcraft_isobmff::ColorInfo::Nclx { primaries, transfer, matrix, full_range } => (*primaries, *transfer, *matrix, *full_range),
- filmcraft_isobmff::ColorInfo::Nclc { primaries, transfer, matrix } => (*primaries, *transfer, *matrix, false),
- _ => return c,
- };
- if let Some(m) = Matrix::from_code(m as u8) {
- c.matrix = m;
- }
- if let Some(t) = Transfer::from_code(t as u8) {
- c.transfer = t;
- }
- c.primaries = match p {
- 9 => Primaries::Bt2020,
- 12 => Primaries::P3D65,
- 5 => Primaries::Bt601_625,
- 6 => Primaries::Bt601_525,
- _ => Primaries::Bt709,
- };
- if full {
- c.range = Range::Full;
- }
- }
- c
+ let sources: Vec<ColorCodes> = [colr, stream].into_iter().flatten().collect();
+ crate::stream_color::resolve(w, h, &sources)
}
impl Mp4Source {
diff --git a/crates/codecs/src/stream_color.rs b/crates/codecs/src/stream_color.rs
new file mode 100644
index 000000000..d01d6a640
--- /dev/null
+++ b/crates/codecs/src/stream_color.rs
@@ -0,0 +1,92 @@
+//! The colour description a video stream carries in its own bitstream, for containers that don't
+//! repeat it: the H.264 / HEVC sequence parameter set's VUI (from `avcC` / `hvcC`) and the AV1
+//! sequence header's `color_config` (from `av1C`), read with the decoders' own parsers.
+//!
+//! ffmpeg writes MP4 without a `colr` box unless asked (`-movflags +write_colr`), so for most
+//! files the bitstream is the only place their colour is described. [`resolve`] merges it with
+//! what the container signals, which wins.
+
+use filmcraft_color::{ColorInfo, Matrix, Range, Transfer};
+use filmcraft_isobmff::{AvcConfig, CodecConfig, HevcConfig};
+
+use crate::video::primaries_from_code;
+
+/// ITU-T H.273 `Unspecified`.
+const UNSPECIFIED: u8 = 2;
+
+/// Colour code points (ITU-T H.273 / ISO/IEC 23091-2) and range as one place in a file (a
+/// container colour box, a sequence header) signals them.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct ColorCodes {
+ pub primaries: u8,
+ pub transfer: u8,
+ pub matrix: u8,
+ /// `None`: this place doesn't say.
+ pub full_range: Option<bool>,
+}
+
+impl ColorCodes {
+ /// From wider code points (a `colr` box or a Matroska `Colour` element): a value that doesn't
+ /// fit a byte is no H.273 code point, so it counts as unspecified.
+ pub fn from_wide(primaries: u64, transfer: u64, matrix: u64, full_range: Option<bool>) -> Self {
+ let code = |v: u64| u8::try_from(v).unwrap_or(UNSPECIFIED);
+ Self { primaries: code(primaries), transfer: code(transfer), matrix: code(matrix), full_range }
+ }
+}
+
+/// The colour a video codec configuration's bitstream signals: the VUI of the first SPS in an
+/// `avcC` / `hvcC`, or the `color_config` of the sequence header in an `av1C`. `None` for other
+/// codecs, an SPS without VUI, and a configuration that is truncated or corrupt.
+pub fn from_codec_config(codec: &CodecConfig) -> Option<ColorCodes> {
+ match codec {
+ CodecConfig::Avc(c) => avc(c),
+ CodecConfig::Hevc(c) => hevc(c),
+ CodecConfig::Av1(c) => av1(&c.config_obus),
+ _ => None,
+ }
+}
+
+fn avc(c: &AvcConfig) -> Option<ColorCodes> {
+ // NAL header byte: nal_unit_type 7 is an SPS
+ let nal = c.sps.iter().find(|n| n.first().is_some_and(|h| h & 0x1f == 7))?;
+ let sps = filmcraft_h264::params::Sps::parse(&filmcraft_bitstream::unescape_rbsp(nal.get(1..)?)).ok()?;
+ let v = sps.vui?;
+ Some(ColorCodes { primaries: v.colour_primaries, transfer: v.transfer_characteristics, matrix: v.matrix_coefficients, full_range: Some(v.full_range) })
+}
+
+fn hevc(c: &HevcConfig) -> Option<ColorCodes> {
+ // two-byte NAL header: nal_unit_type 33 is an SPS (whatever array the record files it under)
+ let nal = c.arrays.iter().flat_map(|a| &a.nalus).find(|n| n.first().is_some_and(|h| (h >> 1) & 0x3f == 33))?;
+ let sps = filmcraft_hevc::params::Sps::parse(&filmcraft_bitstream::unescape_rbsp(nal.get(2..)?)).ok()?;
+ let v = sps.vui?;
+ Some(ColorCodes { primaries: v.colour_primaries, transfer: v.transfer_characteristics, matrix: v.matrix_coefficients, full_range: Some(v.full_range) })
+}
+
+fn av1(config_obus: &[u8]) -> Option<ColorCodes> {
+ // OBU type 1: the sequence header
+ let (_, payload) = crate::hw_frame::obus(config_obus).into_iter().find(|(t, _)| *t == 1)?;
+ let c = filmcraft_av1::SequenceHeader::parse(payload).ok()?.color;
+ Some(ColorCodes { primaries: c.color_primaries, transfer: c.transfer_characteristics, matrix: c.matrix_coefficients, full_range: Some(c.color_range) })
+}
+
+/// Colour from the code points a file signals, most authoritative first (the container's colour
+/// box, then the bitstream's): the matrix, transfer, primaries and range each come from the first
+/// source that signals a value we know. What no source signals keeps the defaults: the matrix by
+/// frame size ([`filmcraft_frame::default_matrix`]: BT.601 for SD, BT.709 otherwise), BT.709
+/// transfer and primaries, limited range.
+pub fn resolve(width: u32, height: u32, sources: &[ColorCodes]) -> ColorInfo {
+ let mut c = ColorInfo { matrix: filmcraft_frame::default_matrix(width, height), ..ColorInfo::REC709 };
+ if let Some(m) = sources.iter().find_map(|s| Matrix::from_code(s.matrix)) {
+ c.matrix = m;
+ }
+ if let Some(t) = sources.iter().find_map(|s| Transfer::from_code(s.transfer)) {
+ c.transfer = t;
+ }
+ if let Some(p) = sources.iter().find_map(|s| primaries_from_code(s.primaries)) {
+ c.primaries = p;
+ }
+ if sources.iter().find_map(|s| s.full_range) == Some(true) {
+ c.range = Range::Full;
+ }
+ c
+}
diff --git a/crates/codecs/src/stream_color_tests.rs b/crates/codecs/src/stream_color_tests.rs
new file mode 100644
index 000000000..1c6526fee
--- /dev/null
+++ b/crates/codecs/src/stream_color_tests.rs
@@ -0,0 +1,340 @@
+//! Colour from the bitstream when the container has none (`crate::stream_color`): ffmpeg writes MP4
+//! without a `colr` box by default, and an HEVC PQ file imported as Rec. 709 SDR, a full-range
+//! H.264 file as limited range, and a BT.601 SD file with BT.709 primaries. The parameter sets
+//! are built here bit by bit; no media files.
+
+use std::io::Cursor;
+use std::sync::Arc;
+
+use filmcraft_bitstream::{BitWriter, escape_rbsp};
+use filmcraft_color::{ColorInfo, ColorSpace, Matrix, Primaries, Range, Transfer};
+use filmcraft_isobmff::{Av1Config, AvcConfig, Brand, CodecConfig, HevcConfig, HevcNalArray, Mp4Writer, SampleEntry, TrackConfig, WriteSample, WriterOptions};
+use filmcraft_matroska::{MkvWriter, MuxOptions, TrackKind, TrackSpec};
+use filmcraft_media::MediaSource;
+
+use crate::stream_color::{ColorCodes, from_codec_config, resolve};
+
+/// The video signal description of a VUI: (colour_primaries, transfer_characteristics,
+/// matrix_coefficients) when `colour_description_present_flag` is set, and the range flag.
+#[derive(Clone, Copy)]
+struct Signal {
+ codes: Option<(u8, u8, u8)>,
+ full_range: bool,
+}
+
+const PQ_2020: Signal = Signal { codes: Some((9, 16, 9)), full_range: false };
+const SMPTE_170M: Signal = Signal { codes: Some((6, 6, 6)), full_range: false };
+const FULL_ONLY: Signal = Signal { codes: None, full_range: true };
+
+fn signal(w: &mut BitWriter, s: Signal) {
+ w.write_bit(true); // video_signal_type_present_flag
+ w.write_bits(5, 3); // video_format: unspecified
+ w.write_bit(s.full_range);
+ w.write_bit(s.codes.is_some()); // colour_description_present_flag
+ if let Some((p, t, m)) = s.codes {
+ w.write_bits(p.into(), 8);
+ w.write_bits(t.into(), 8);
+ w.write_bits(m.into(), 8);
+ }
+}
+
+/// A Baseline H.264 SPS NAL unit (ITU-T H.264 §7.3.2.1.1, VUI per Annex E.1.1) of
+/// `mbs_w`×`mbs_h` macroblocks, with a VUI carrying `vui` (no VUI when `None`).
+fn h264_sps(mbs_w: u32, mbs_h: u32, vui: Option<Signal>) -> Vec<u8> {
+ let mut w = BitWriter::new();
+ w.write_bits(66, 8); // profile_idc: Baseline
+ w.write_bits(0, 8); // constraint flags
+ w.write_bits(30, 8); // level_idc
+ w.write_ue(0); // seq_parameter_set_id
+ w.write_ue(0); // log2_max_frame_num_minus4
+ w.write_ue(2); // pic_order_cnt_type
+ w.write_ue(1); // max_num_ref_frames
+ w.write_bit(false); // gaps_in_frame_num_value_allowed_flag
+ w.write_ue(mbs_w - 1);
+ w.write_ue(mbs_h - 1);
+ w.write_bits(0b110, 3); // frame_mbs_only, direct_8x8_inference, no cropping
+ w.write_bit(vui.is_some()); // vui_parameters_present_flag
+ if let Some(s) = vui {
+ w.write_bit(false); // aspect_ratio_info_present_flag
+ w.write_bit(false); // overscan_info_present_flag
+ signal(&mut w, s);
+ w.write_bit(false); // chroma_loc_info_present_flag
+ w.write_bit(false); // timing_info_present_flag
+ w.write_bit(false); // nal_hrd_parameters_present_flag
+ w.write_bit(false); // vcl_hrd_parameters_present_flag
+ w.write_bit(false); // pic_struct_present_flag
+ w.write_bit(false); // bitstream_restriction_flag
+ }
+ w.rbsp_trailing();
+ let mut nal = vec![0x67];
+ nal.extend(escape_rbsp(&w.finish()));
+ nal
+}
+
+/// A Main 10 HEVC SPS NAL unit (ITU-T H.265 §7.3.2.2, VUI per Annex E.2.1) of `width`×`height`
+/// (multiples of 8), with a VUI carrying `vui` (no VUI when `None`).
+fn hevc_sps(width: u32, height: u32, vui: Option<Signal>) -> Vec<u8> {
+ let mut w = BitWriter::new();
+ w.write_bits(0, 4); // sps_video_parameter_set_id
+ w.write_bits(0, 3); // sps_max_sub_layers_minus1
+ w.write_bit(true); // sps_temporal_id_nesting_flag
+ // profile_tier_level: Main 10, level 4.1
+ w.write_bits(0, 2);
+ w.write_bit(false);
+ w.write_bits(2, 5);
+ w.write_bits(0x2000_0000, 32);
+ w.write_bits(0b1001, 4);
+ w.write_bits(0, 32);
+ w.write_bits(0, 12);
+ w.write_bits(123, 8);
+ w.write_ue(0); // sps_seq_parameter_set_id
+ w.write_ue(1); // chroma_format_idc 4:2:0
+ w.write_ue(width);
+ w.write_ue(height);
+ w.write_bit(false); // conformance_window_flag
+ w.write_ue(2); // bit_depth_luma_minus8
+ w.write_ue(2); // bit_depth_chroma_minus8
+ w.write_ue(4); // log2_max_pic_order_cnt_lsb_minus4
+ w.write_bit(true); // sps_sub_layer_ordering_info_present_flag
+ w.write_ue(4); // sps_max_dec_pic_buffering_minus1
+ w.write_ue(0); // sps_max_num_reorder_pics
+ w.write_ue(0); // sps_max_latency_increase_plus1
+ w.write_ue(0); // log2_min_luma_coding_block_size_minus3 (8)
+ w.write_ue(1); // log2_diff_max_min_luma_coding_block_size (CTB 16)
+ w.write_ue(0); // log2_min_luma_transform_block_size_minus2 (4)
+ w.write_ue(2); // log2_diff_max_min_luma_transform_block_size (16)
+ w.write_ue(0); // max_transform_hierarchy_depth_inter
+ w.write_ue(0); // max_transform_hierarchy_depth_intra
+ w.write_bit(false); // scaling_list_enabled_flag
+ w.write_bit(false); // amp_enabled_flag
+ w.write_bit(false); // sample_adaptive_offset_enabled_flag
+ w.write_bit(false); // pcm_enabled_flag
+ w.write_ue(0); // num_short_term_ref_pic_sets
+ w.write_bit(false); // long_term_ref_pics_present_flag
+ w.write_bit(false); // sps_temporal_mvp_enabled_flag
+ w.write_bit(false); // strong_intra_smoothing_enabled_flag
+ w.write_bit(vui.is_some()); // vui_parameters_present_flag
+ if let Some(s) = vui {
+ w.write_bit(false); // aspect_ratio_info_present_flag
+ w.write_bit(false); // overscan_info_present_flag
+ signal(&mut w, s);
+ w.write_bit(false); // chroma_loc_info_present_flag
+ w.write_bit(false); // neutral_chroma_indication_flag
+ w.write_bit(false); // field_seq_flag
+ w.write_bit(false); // frame_field_info_present_flag
+ w.write_bit(false); // default_display_window_flag
+ w.write_bit(false); // vui_timing_info_present_flag
+ w.write_bit(false); // bitstream_restriction_flag
+ }
+ w.write_bit(false); // sps_extension_present_flag
+ w.rbsp_trailing();
+ let mut nal = vec![33 << 1, 1];
+ nal.extend(escape_rbsp(&w.finish()));
+ nal
+}
+
+/// An AV1 sequence header OBU (AV1 bitstream spec §5.5; reduced still-picture header, profile 0,
+/// 10-bit 4:2:0) of `width`×`height` with `color_config` signalling `codes` and `full_range`.
+fn av1_sequence_header(width: u32, height: u32, codes: Option<(u8, u8, u8)>, full_range: bool) -> Vec<u8> {
+ let mut w = BitWriter::new();
+ w.write_bits(0, 3); // seq_profile
+ w.write_bit(true); // still_picture
+ w.write_bit(true); // reduced_still_picture_header
+ w.write_bits(0, 5); // seq_level_idx[0]
+ w.write_bits(15, 4); // frame_width_bits_minus_1
+ w.write_bits(15, 4); // frame_height_bits_minus_1
+ w.write_bits(width - 1, 16);
+ w.write_bits(height - 1, 16);
+ w.write_bits(0, 3); // use_128x128_superblock, enable_filter_intra, enable_intra_edge_filter
+ w.write_bits(0, 3); // enable_superres, enable_cdef, enable_restoration
+ w.write_bit(true); // high_bitdepth
+ w.write_bit(false); // mono_chrome
+ w.write_bit(codes.is_some()); // color_description_present_flag
+ if let Some((p, t, m)) = codes {
+ w.write_bits(p.into(), 8);
+ w.write_bits(t.into(), 8);
+ w.write_bits(m.into(), 8);
+ }
+ w.write_bit(full_range); // color_range
+ w.write_bits(0, 2); // chroma_sample_position
+ w.write_bit(false); // separate_uv_delta_q
+ w.write_bit(false); // film_grain_params_present
+ w.rbsp_trailing();
+ let payload = w.finish();
+ // OBU header: type 1 (OBU_SEQUENCE_HEADER), obu_has_size_field; one-byte leb128 size
+ let mut obu = vec![(1 << 3) | 2, u8::try_from(payload.len()).expect("short payload")];
+ obu.extend(payload);
+ obu
+}
+
+fn avc(sps: Vec<u8>) -> CodecConfig {
+ CodecConfig::Avc(AvcConfig::new(vec![sps], vec![vec![0x68, 0xCE, 0x38, 0x80]], 4))
+}
+
+fn hevc(sps: Vec<u8>) -> CodecConfig {
+ CodecConfig::Hevc(HevcConfig {
+ general_profile_idc: 2,
+ chroma_format_idc: 1,
+ bit_depth_luma: 10,
+ bit_depth_chroma: 10,
+ length_size: 4,
+ arrays: vec![HevcNalArray { completeness: true, nal_type: 33, nalus: vec![sps] }],
+ ..Default::default()
+ })
+}
+
+fn av1(obus: Vec<u8>) -> CodecConfig {
+ CodecConfig::Av1(Av1Config { high_bitdepth: true, chroma_subsampling_x: true, chroma_subsampling_y: true, config_obus: obus, ..Default::default() })
+}
+
+/// A one-sample MP4 with `codec` (the sample is never decoded) and, when given, a `colr` box.
+fn mp4(codec: CodecConfig, w: u16, h: u16, colr: Option<filmcraft_isobmff::ColorInfo>) -> Arc<[u8]> {
+ let mut entry = match codec {
+ CodecConfig::Avc(c) => SampleEntry::avc(c, w, h),
+ CodecConfig::Hevc(c) => SampleEntry::hevc(c, w, h),
+ other => SampleEntry::video(filmcraft_isobmff::FourCc(*b"av01"), other, w, h),
+ };
+ if let Some(v) = entry.video.as_mut() {
+ v.color = colr;
+ }
+ let mut mux = Mp4Writer::new(Cursor::new(Vec::new()), WriterOptions::new(Brand::Mp4)).expect("writer");
+ let t = mux.add_track(TrackConfig::new(entry, 30)).expect("track");
+ mux.write_sample(t, WriteSample { data: &[0, 0, 0, 1, 0x65], duration: 1, composition_offset: 0, is_sync: true }).expect("sample");
+ mux.finish().expect("finish").into_inner().into()
+}
+
+fn mp4_color(codec: CodecConfig, w: u16, h: u16, colr: Option<filmcraft_isobmff::ColorInfo>) -> ColorInfo {
+ let src = crate::Mp4Source::open("clip.mp4", mp4(codec, w, h, colr)).expect("open");
+ src.info().video.as_ref().expect("video").color
+}
+
+#[test]
+fn hevc_pq_without_colr_is_rec2100_pq() {
+ let c = mp4_color(hevc(hevc_sps(1920, 1080, Some(PQ_2020))), 1920, 1080, None);
+ assert_eq!(c, ColorInfo { matrix: Matrix::Bt2020Ncl, transfer: Transfer::Pq, primaries: Primaries::Bt2020, range: Range::Limited });
+ assert_eq!(ColorSpace::from_info(&c), ColorSpace::Rec2100Pq);
+ assert!(ColorSpace::from_info(&c).is_hdr());
+}
+
+#[test]
+fn full_range_h264_without_colr_is_full_range() {
+ // video_full_range_flag with no colour description: full range, the rest by size
+ let c = mp4_color(avc(h264_sps(80, 45, Some(FULL_ONLY))), 1280, 720, None);
+ assert_eq!(c, ColorInfo { range: Range::Full, ..ColorInfo::REC709 });
+}
+
+#[test]
+fn bt601_sd_h264_without_colr_has_bt601_primaries() {
+ let c = mp4_color(avc(h264_sps(45, 30, Some(SMPTE_170M))), 720, 480, None);
+ assert_eq!(c, ColorInfo { matrix: Matrix::Bt601, transfer: Transfer::Bt709, primaries: Primaries::Bt601_525, range: Range::Limited });
+ // PAL (BT.470 BG primaries, BT.601 matrix)
+ let pal = Signal { codes: Some((5, 6, 5)), full_range: false };
+ let c = mp4_color(avc(h264_sps(45, 36, Some(pal))), 720, 576, None);
+ assert_eq!((c.primaries, c.matrix), (Primaries::Bt601_625, Matrix::Bt601));
+}
+
+#[test]
+fn unspecified_or_missing_vui_keeps_the_size_defaults() {
+ let unspecified = Signal { codes: Some((2, 2, 2)), full_range: false };
+ for vui in [None, Some(unspecified)] {
+ assert_eq!(mp4_color(avc(h264_sps(80, 45, vui)), 1280, 720, None), ColorInfo::REC709);
+ assert_eq!(mp4_color(hevc(hevc_sps(1920, 1080, vui)), 1920, 1080, None), ColorInfo::REC709);
+ // SD: the BT.601 matrix, as before
+ assert_eq!(mp4_color(avc(h264_sps(45, 30, vui)), 720, 480, None), ColorInfo { matrix: Matrix::Bt601, ..ColorInfo::REC709 });
+ }
+}
+
+#[test]
+fn colr_wins_over_the_bitstream() {
+ use filmcraft_isobmff::ColorInfo::{Nclc, Nclx};
+ let sps = || hevc(hevc_sps(1920, 1080, Some(PQ_2020)));
+ // a BT.709 nclx box beats a PQ VUI, and is what the decoder's frames are tagged with
+ let colr = Nclx { primaries: 1, transfer: 1, matrix: 1, full_range: false };
+ assert_eq!(mp4_color(sps(), 1920, 1080, Some(colr.clone())), ColorInfo::REC709);
+ // HLG in colr, PQ in the VUI: HLG
+ let hlg = Nclx { primaries: 9, transfer: 18, matrix: 9, full_range: false };
+ assert_eq!(mp4_color(sps(), 1920, 1080, Some(hlg)).transfer, Transfer::Hlg);
+ // limited range in colr beats a full-range VUI
+ assert_eq!(mp4_color(avc(h264_sps(80, 45, Some(FULL_ONLY))), 1280, 720, Some(colr)).range, Range::Limited);
+ // what colr leaves unspecified comes from the VUI
+ let partial = Nclx { primaries: 2, transfer: 16, matrix: 2, full_range: false };
+ assert_eq!(mp4_color(sps(), 1920, 1080, Some(partial)), mp4_color(sps(), 1920, 1080, None));
+ // QuickTime nclc has no range flag: the VUI's range stands
+ let nclc = Nclc { primaries: 1, transfer: 1, matrix: 1 };
+ assert_eq!(mp4_color(avc(h264_sps(80, 45, Some(FULL_ONLY))), 1280, 720, Some(nclc)).range, Range::Full);
+ // an ICC profile has no code points: the bitstream decides
+ let icc = filmcraft_isobmff::ColorInfo::Icc { kind: filmcraft_isobmff::FourCc(*b"prof"), profile: vec![0; 8] };
+ assert_eq!(mp4_color(sps(), 1920, 1080, Some(icc)).transfer, Transfer::Pq);
+}
+
+#[test]
+fn av1_sequence_header_colour() {
+ let obu = av1_sequence_header(1920, 1080, Some((9, 16, 9)), false);
+ assert_eq!(from_codec_config(&av1(obu.clone())), Some(ColorCodes { primaries: 9, transfer: 16, matrix: 9, full_range: Some(false) }));
+ let c = mp4_color(av1(obu), 1920, 1080, None);
+ assert_eq!(ColorSpace::from_info(&c), ColorSpace::Rec2100Pq);
+ // no colour description: unspecified code points, the range flag still counts
+ let obu = av1_sequence_header(640, 360, None, true);
+ assert_eq!(from_codec_config(&av1(obu)), Some(ColorCodes { primaries: 2, transfer: 2, matrix: 2, full_range: Some(true) }));
+}
+
+#[test]
+fn matroska_without_colour_uses_the_bitstream() {
+ let CodecConfig::Hevc(hvcc) = hevc(hevc_sps(1920, 1080, Some(PQ_2020))) else { panic!("an hvcC") };
+ let mut spec = TrackSpec::new(TrackKind::Video, "V_MPEGH/ISO/HEVC");
+ spec.codec_private = hvcc.to_bytes();
+ spec.video_size = Some((1920, 1080));
+ spec.default_duration_ns = Some(33_333_333);
+ let mut w = MkvWriter::new(Cursor::new(Vec::new()), vec![spec], MuxOptions::default()).expect("writer");
+ w.write_frame(0, 0, true, &[0, 0, 0, 1, 0x26], None).expect("frame");
+ let b: Arc<[u8]> = w.finish().expect("finish").into_inner().into();
+ let src = crate::MkvSource::open("clip.mkv", b).expect("open");
+ let c = src.info().video.as_ref().expect("video").color;
+ assert_eq!(ColorSpace::from_info(&c), ColorSpace::Rec2100Pq);
+ assert_eq!((c.primaries, c.matrix), (Primaries::Bt2020, Matrix::Bt2020Ncl));
+}
+
+#[test]
+fn resolve_takes_each_field_from_the_first_source_that_knows_it() {
+ let colr = ColorCodes { primaries: 1, transfer: 2, matrix: 0, full_range: None };
+ let vui = ColorCodes { primaries: 9, transfer: 18, matrix: 9, full_range: Some(true) };
+ // matrix 0 (identity) is not one we know: the VUI's BT.2020 is used
+ let c = resolve(1920, 1080, &[colr, vui]);
+ assert_eq!(c, ColorInfo { matrix: Matrix::Bt2020Ncl, transfer: Transfer::Hlg, primaries: Primaries::Bt709, range: Range::Full });
+ assert_eq!(resolve(720, 480, &[]), ColorInfo { matrix: Matrix::Bt601, ..ColorInfo::REC709 });
+ // code points that don't fit a byte are unspecified, not truncated (0x109 is not 9)
+ assert_eq!(ColorCodes::from_wide(0x109, 0x110, 0x109, None), ColorCodes { primaries: 2, transfer: 2, matrix: 2, full_range: None });
+}
+
+/// Every truncation and many bit flips of each configuration: never a panic, and the result is
+/// either some colour or none (the size defaults).
+#[test]
+fn hostile_parameter_sets_never_panic() {
+ let configs: Vec<(Vec<u8>, fn(Vec<u8>) -> CodecConfig)> = vec![
+ (h264_sps(45, 30, Some(SMPTE_170M)), avc),
+ (hevc_sps(1920, 1080, Some(PQ_2020)), hevc),
+ (av1_sequence_header(1920, 1080, Some((9, 16, 9)), false), av1),
+ ];
+ for (good, make) in configs {
+ assert!(from_codec_config(&make(good.clone())).is_some());
+ let mut variants: Vec<Vec<u8>> = (0..good.len()).map(|n| good[..n].to_vec()).collect();
+ for bit in 0..good.len() * 8 {
+ let mut b = good.clone();
+ b[bit / 8] ^= 0x80 >> (bit % 8);
+ variants.push(b);
+ }
+ variants.push(vec![0xff; 64]);
+ variants.push(Vec::new());
+ for v in variants {
+ let r = std::panic::catch_unwind(|| from_codec_config(&make(v.clone())));
+ assert!(r.is_ok(), "panicked on {v:02x?}");
+ }
+ }
+ // configurations with no parameter sets at all
+ assert_eq!(from_codec_config(&CodecConfig::Avc(AvcConfig::default())), None);
+ assert_eq!(from_codec_config(&CodecConfig::Hevc(HevcConfig::default())), None);
+ assert_eq!(from_codec_config(&CodecConfig::Av1(Av1Config::default())), None);
+ // a garbage SPS imports with the size defaults
+ assert_eq!(mp4_color(avc(vec![0x67, 0xff, 0xff]), 1280, 720, None), ColorInfo::REC709);
+ assert_eq!(mp4_color(hevc(vec![33 << 1, 1, 0xff]), 1920, 1080, None), ColorInfo::REC709);
+}
diff --git a/crates/codecs/src/tests.rs b/crates/codecs/src/tests.rs
index 819a41f90..be3e30a4d 100644
--- a/crates/codecs/src/tests.rs
+++ b/crates/codecs/src/tests.rs
@@ -615,3 +615,32 @@ fn apv_mp4_and_raw_bitstream_decode() {
let decoded_mp4 = mp4_src.video_frame(FrameRequest::full(Tick::ZERO)).expect("decode mp4 frame");
assert_eq!(decoded_mp4.to_rgba8(), decoded_raw.to_rgba8());
}
+
+/// ffmpeg writes MP4 without a `colr` box unless asked: the colour comes from the x265 / x264
+/// SPS VUI, and matches the same stream remuxed with `colr`.
+#[test]
+fn mp4_colour_comes_from_the_sps_without_colr() {
+ use filmcraft_color::{ColorSpace, Primaries, Range};
+ let src = |name: &str, args: &[&str]| fixture(name, args).map(|b| crate::open_bytes(name, b).expect("open"));
+ let color = |s: &filmcraft_media::SharedSource| s.info().video.as_ref().expect("video").color;
+ let lavfi = |size: &'static str| ["-f", "lavfi", "-i", size, "-t", "0.2"];
+ let x265 = "colorprim=bt2020:transfer=smpte2084:colormatrix=bt2020nc:log-level=error";
+ let mut pq = lavfi("testsrc2=s=640x360:r=25").to_vec();
+ pq.extend(["-c:v", "libx265", "-tag:v", "hvc1", "-pix_fmt", "yuv420p10le", "-x265-params", x265]);
+ let Some(plain) = src("hevc_pq_no_colr.mp4", &pq) else { return };
+ assert_eq!(ColorSpace::from_info(&color(&plain)), ColorSpace::Rec2100Pq);
+ let colr_path = fixture_path("hevc_pq_no_colr.mp4", &pq).expect("fixture");
+ if let Some(with_colr) = src("hevc_pq_colr.mp4", &["-i", colr_path.to_str().expect("path"), "-c", "copy", "-movflags", "+write_colr"]) {
+ assert_eq!(color(&with_colr), color(&plain));
+ }
+ let mut full = lavfi("testsrc2=s=640x360:r=25").to_vec();
+ full.extend(["-c:v", "libx264", "-pix_fmt", "yuvj420p", "-color_range", "pc"]);
+ if let Some(s) = src("h264_full_no_colr.mp4", &full) {
+ assert_eq!(color(&s).range, Range::Full);
+ }
+ let mut sd = lavfi("testsrc2=s=720x480:r=30000/1001").to_vec();
+ sd.extend(["-c:v", "libx264", "-pix_fmt", "yuv420p", "-x264-params", "colorprim=smpte170m:transfer=smpte170m:colormatrix=smpte170m"]);
+ if let Some(s) = src("h264_sd601_no_colr.mp4", &sd) {
+ assert_eq!(color(&s).primaries, Primaries::Bt601_525);
+ }
+}