use crate::boxes::BoxHeader;
use crate::error::{Error, Result};
use crate::hevc::VideoSignal;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum MatrixCoefficients {
Identity,
Bt709,
Unspecified,
Bt601,
Smpte240m,
Bt2020Ncl,
Other(u16),
}
impl MatrixCoefficients {
pub fn from_code(code: u16) -> MatrixCoefficients {
match code {
0 => MatrixCoefficients::Identity,
1 => MatrixCoefficients::Bt709,
2 => MatrixCoefficients::Unspecified,
5 | 6 => MatrixCoefficients::Bt601,
7 => MatrixCoefficients::Smpte240m,
9 => MatrixCoefficients::Bt2020Ncl,
n => MatrixCoefficients::Other(n),
}
}
pub fn luma_weights(self) -> (f32, f32) {
match self {
MatrixCoefficients::Bt601 | MatrixCoefficients::Unspecified => (0.299, 0.114),
MatrixCoefficients::Smpte240m => (0.212, 0.087),
MatrixCoefficients::Bt2020Ncl => (0.2627, 0.0593),
_ => (0.2126, 0.0722),
}
}
pub fn is_identity(self) -> bool {
matches!(self, MatrixCoefficients::Identity)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Range {
Limited,
Full,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Nclx {
pub primaries: u16,
pub transfer: u16,
pub matrix: MatrixCoefficients,
pub matrix_code: u16,
pub range: Range,
}
impl Default for Nclx {
fn default() -> Self {
Nclx {
primaries: 1,
transfer: 13,
matrix: MatrixCoefficients::Bt709,
matrix_code: 1,
range: Range::Limited,
}
}
}
impl From<VideoSignal> for Nclx {
fn from(signal: VideoSignal) -> Self {
let [primaries, transfer, matrix] = signal.description.unwrap_or([2, 2, 2]);
Nclx {
primaries: u16::from(primaries),
transfer: u16::from(transfer),
matrix: MatrixCoefficients::from_code(u16::from(matrix)),
matrix_code: u16::from(matrix),
range: if signal.full_range {
Range::Full
} else {
Range::Limited
},
}
}
}
#[derive(Debug, Clone, Copy)]
pub enum ColorInfo<'a> {
Nclx(Nclx),
Icc {
restricted: bool,
data: &'a [u8],
},
}
pub fn parse<'a>(b: &BoxHeader<'a>) -> Result<ColorInfo<'a>> {
let mut r = b.reader();
let kind = r.fourcc("colr colour type")?;
match &kind {
b"nclx" => {
let primaries = r.u16("colr primaries")?;
let transfer = r.u16("colr transfer")?;
let matrix_code = r.u16("colr matrix")?;
let flags = r.u8("colr range flag")?;
let range = if flags & 0x80 != 0 {
Range::Full
} else {
Range::Limited
};
Ok(ColorInfo::Nclx(Nclx {
primaries,
transfer,
matrix: MatrixCoefficients::from_code(matrix_code),
matrix_code,
range,
}))
}
b"rICC" => Ok(ColorInfo::Icc {
restricted: true,
data: r.rest(),
}),
b"prof" => Ok(ColorInfo::Icc {
restricted: false,
data: r.rest(),
}),
b"nclc" => Err(Error::Unsupported(
"the `nclc` colour type belongs to QuickTime, not HEIF",
)),
_ => Err(Error::Malformed("unknown colr colour type")),
}
}