use smallvec::SmallVec;
#[derive(Debug, Clone, PartialEq)]
pub enum AttributeValue {
ChannelList(ChannelList),
Chromaticities(Chromaticities),
Compression(Compression),
EnvironmentMap(EnvironmentMap),
KeyCode(KeyCode),
LineOrder(LineOrder),
Matrix3x3(Matrix3x3),
Matrix4x4(Matrix4x4),
Preview(Preview),
Rational(Rational),
BlockType(BlockType),
TextVector(Vec<Text>),
TileDescription(TileDescription),
TimeCode(TimeCode),
Text(Text),
F64(f64),
F32(f32),
I32(i32),
IntegerBounds(IntegerBounds),
FloatRect(FloatRect),
IntVec2(Vec2<i32>),
FloatVec2(Vec2<f32>),
IntVec3((i32, i32, i32)),
FloatVec3((f32, f32, f32)),
Bytes {
type_hint: Text,
bytes: SmallVec<[u8; 16]>,
},
Custom {
kind: Text,
bytes: SmallVec<[u8; 16]>,
},
}
#[derive(Clone, PartialEq, Ord, PartialOrd, Default)] pub struct Text {
bytes: TextBytes,
}
#[derive(Copy, Debug, Clone, Eq, PartialEq, Hash, Default)]
pub struct TimeCode {
pub hours: u8,
pub minutes: u8,
pub seconds: u8,
pub frame: u8,
pub drop_frame: bool,
pub color_frame: bool,
pub field_phase: bool,
pub binary_group_flags: [bool; 3],
pub binary_groups: [u8; 8],
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum BlockType {
ScanLine,
Tile,
DeepScanLine,
DeepTile,
}
pub mod block_type_strings {
pub const SCAN_LINE: &[u8] = b"scanlineimage";
pub const TILE: &[u8] = b"tiledimage";
pub const DEEP_SCAN_LINE: &[u8] = b"deepscanline";
pub const DEEP_TILE: &[u8] = b"deeptile";
}
pub use crate::compression::Compression;
pub type DataWindow = IntegerBounds;
pub type DisplayWindow = IntegerBounds;
pub type Rational = (i32, u32);
pub type Matrix4x4 = [f32; 4 * 4];
pub type Matrix3x3 = [f32; 3 * 3];
#[derive(Clone, Copy, Debug, Eq, PartialEq, Default, Hash)]
pub struct IntegerBounds {
pub position: Vec2<i32>,
pub size: Vec2<usize>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FloatRect {
pub min: Vec2<f32>,
pub max: Vec2<f32>,
}
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct ChannelList {
pub list: SmallVec<[ChannelDescription; 5]>,
pub bytes_per_pixel: usize,
pub uniform_sample_type: Option<SampleType>,
}
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct ChannelDescription {
pub name: Text,
pub sample_type: SampleType,
pub quantize_linearly: bool,
pub sampling: Vec2<usize>,
}
#[derive(Clone, Debug, Eq, PartialEq, Copy, Hash)]
pub enum SampleType {
U32,
F16,
F32,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Chromaticities {
pub red: Vec2<f32>,
pub green: Vec2<f32>,
pub blue: Vec2<f32>,
pub white: Vec2<f32>,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum EnvironmentMap {
LatitudeLongitude,
Cube,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub struct KeyCode {
pub film_manufacturer_code: i32,
pub film_type: i32,
pub film_roll_prefix: i32,
pub count: i32,
pub perforation_offset: i32,
pub perforations_per_frame: i32,
pub perforations_per_count: i32,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum LineOrder {
Increasing,
Decreasing,
Unspecified,
}
#[derive(Clone, Eq, PartialEq)]
pub struct Preview {
pub size: Vec2<usize>,
pub pixel_data: Vec<i8>,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub struct TileDescription {
pub tile_size: Vec2<usize>,
pub level_mode: LevelMode,
pub rounding_mode: RoundingMode,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum LevelMode {
Singular,
MipMap,
RipMap,
}
pub type TextBytes = SmallVec<[u8; 24]>;
pub type TextSlice = [u8];
use std::{
borrow::Borrow,
convert::TryFrom,
hash::{Hash, Hasher},
};
use bit_field::BitField;
use half::f16;
use crate::{
error::*,
io::*,
math::{RoundingMode, Vec2},
meta::sequence_end,
};
fn invalid_type() -> Error {
Error::invalid("attribute type mismatch")
}
impl Text {
pub fn new_or_none(string: impl AsRef<str>) -> Option<Self> {
let vec: Option<TextBytes> =
string.as_ref().chars().map(|character| u8::try_from(character as u64).ok()).collect();
vec.map(Self::from_bytes_unchecked)
}
pub fn new_or_panic(string: impl AsRef<str>) -> Self {
Self::new_or_none(string).expect("exr::Text contains unsupported characters")
}
#[must_use]
pub fn from_slice_unchecked(text: &TextSlice) -> Self {
Self::from_bytes_unchecked(SmallVec::from_slice(text))
}
#[must_use]
pub const fn from_bytes_unchecked(bytes: TextBytes) -> Self {
Self {
bytes,
}
}
pub fn as_slice(&self) -> &TextSlice {
self.bytes.as_slice()
}
pub fn validate(&self, null_terminated: bool, long_names: Option<&mut bool>) -> UnitResult {
Self::validate_bytes(self.as_slice(), null_terminated, long_names)
}
pub fn validate_bytes(
text: &TextSlice,
null_terminated: bool,
long_names: Option<&mut bool>,
) -> UnitResult {
if null_terminated && text.is_empty() {
return Err(Error::invalid("text must not be empty"));
}
if let Some(long) = long_names {
if text.len() >= 256 {
return Err(Error::invalid("text must not be longer than 255"));
}
if text.len() >= 32 {
*long = true;
}
}
Ok(())
}
pub fn null_terminated_byte_size(&self) -> usize {
self.bytes.len() + sequence_end::byte_size()
}
pub fn i32_sized_byte_size(&self) -> usize {
self.bytes.len() + i32::BYTE_SIZE
}
pub fn u32_sized_byte_size(&self) -> usize {
self.bytes.len() + u32::BYTE_SIZE
}
pub fn write_i32_sized_le<W: Write>(&self, write: &mut W) -> UnitResult {
debug_assert!(self.validate(false, None).is_ok(), "text size bug");
i32::write_le(usize_to_i32(self.bytes.len(), "text length")?, write)?;
Self::write_unsized_bytes(self.bytes.as_slice(), write)
}
pub fn write_u32_sized_le<W: Write>(&self, write: &mut W) -> UnitResult {
debug_assert!(self.validate(false, None).is_ok(), "text size bug");
u32::write_le(usize_to_u32(self.bytes.len(), "text length")?, write)?;
Self::write_unsized_bytes(self.bytes.as_slice(), write)
}
fn write_unsized_bytes<W: Write>(bytes: &[u8], write: &mut W) -> UnitResult {
u8::write_slice_le(write, bytes)?;
Ok(())
}
pub fn read_i32_sized_le<R: Read>(read: &mut R, max_size: usize) -> Result<Self> {
let size = i32_to_usize(i32::read_le(read)?, "vector size")?;
Ok(Self::from_bytes_unchecked(SmallVec::from_vec(u8::read_vec_le(
read,
size,
1024,
Some(max_size),
"text attribute length",
)?)))
}
pub fn read_u32_sized_le<R: Read>(read: &mut R, max_size: usize) -> Result<Self> {
let size = u32_to_usize(u32::read_le(read)?, "text length")?;
Ok(Self::from_bytes_unchecked(SmallVec::from_vec(u8::read_vec_le(
read,
size,
1024,
Some(max_size),
"text attribute length",
)?)))
}
pub fn read_sized<R: Read>(read: &mut R, size: usize) -> Result<Self> {
const SMALL_SIZE: usize = 24;
if size <= SMALL_SIZE {
let mut buffer = [0_u8; SMALL_SIZE];
let data = &mut buffer[..size];
read.read_exact(data)?;
Ok(Self::from_bytes_unchecked(SmallVec::from_slice(data)))
}
else {
Ok(Self::from_bytes_unchecked(SmallVec::from_vec(u8::read_vec_le(
read,
size,
1024,
None,
"text attribute length",
)?)))
}
}
pub fn write_null_terminated<W: Write>(&self, write: &mut W) -> UnitResult {
Self::write_null_terminated_bytes(self.as_slice(), write)
}
fn write_null_terminated_bytes<W: Write>(bytes: &[u8], write: &mut W) -> UnitResult {
debug_assert!(!bytes.is_empty(), "text is empty bug");
Self::write_unsized_bytes(bytes, write)?;
sequence_end::write(write)?;
Ok(())
}
pub fn read_null_terminated<R: Read>(read: &mut R, max_len: usize) -> Result<Self> {
let mut bytes = smallvec![u8::read_le(read)?];
loop {
match u8::read_le(read)? {
0 => break,
non_terminator => bytes.push(non_terminator),
}
if bytes.len() > max_len {
return Err(Error::invalid("text too long"));
}
}
Ok(Self {
bytes,
})
}
fn read_vec_of_i32_sized_texts_le(
read: &mut PeekRead<impl Read>,
total_byte_size: usize,
) -> Result<Vec<Self>> {
let mut result = Vec::with_capacity(2);
let mut processed_bytes = 0;
while processed_bytes < total_byte_size {
let text = Self::read_i32_sized_le(read, total_byte_size)?;
processed_bytes += ::std::mem::size_of::<i32>(); processed_bytes += text.bytes.len();
result.push(text);
}
if processed_bytes != total_byte_size {
return Err(Error::invalid("text array byte size"));
}
Ok(result)
}
fn write_vec_of_i32_sized_texts_le<W: Write>(write: &mut W, texts: &[Self]) -> UnitResult {
for text in texts {
text.write_i32_sized_le(write)?;
}
Ok(())
}
pub fn bytes(&self) -> &[u8] {
self.bytes.as_slice()
}
pub fn chars(&self) -> impl '_ + Iterator<Item = char> {
self.bytes.iter().map(|&byte| byte as char)
}
pub fn eq(&self, string: &str) -> bool {
string.chars().eq(self.chars())
}
pub fn eq_case_insensitive(&self, string: &str) -> bool {
let self_chars = self.chars().map(|char| char.to_ascii_lowercase());
let string_chars = string.chars().flat_map(char::to_lowercase);
string_chars.eq(self_chars)
}
}
impl PartialEq<str> for Text {
fn eq(&self, other: &str) -> bool {
self.eq(other)
}
}
impl PartialEq<Text> for str {
fn eq(&self, other: &Text) -> bool {
other.eq(self)
}
}
impl Eq for Text {}
impl Borrow<TextSlice> for Text {
fn borrow(&self) -> &TextSlice {
self.as_slice()
}
}
impl Hash for Text {
fn hash<H: Hasher>(&self, state: &mut H) {
self.bytes.hash(state);
}
}
impl From<Text> for String {
fn from(val: Text) -> Self {
val.to_string()
}
}
impl<'s> From<&'s str> for Text {
fn from(str: &'s str) -> Self {
Self::new_or_panic(str)
}
}
impl ::std::fmt::Debug for Text {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(f, "exr::Text(\"{self}\")")
}
}
impl ::std::fmt::Display for Text {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
use std::fmt::Write;
for &byte in &self.bytes {
f.write_char(byte as char)?;
}
Ok(())
}
}
impl ChannelList {
#[must_use]
pub fn new(channels: SmallVec<[ChannelDescription; 5]>) -> Self {
let uniform_sample_type = {
if let Some(first) = channels.first() {
let has_uniform_types =
channels.iter().skip(1).all(|chan| chan.sample_type == first.sample_type);
if has_uniform_types {
Some(first.sample_type)
} else {
None
}
} else {
None
}
};
Self {
bytes_per_pixel: channels
.iter()
.map(|channel| channel.sample_type.bytes_per_sample())
.sum(),
list: channels,
uniform_sample_type,
}
}
pub fn channels_with_byte_offset(&self) -> impl Iterator<Item = (usize, &ChannelDescription)> {
self.list.iter().scan(0, |byte_position, channel| {
let previous_position = *byte_position;
*byte_position += channel.sample_type.bytes_per_sample();
Some((previous_position, channel))
})
}
#[must_use]
pub fn find_index_of_channel(&self, exact_name: &Text) -> Option<usize> {
self.list.binary_search_by_key(&exact_name.bytes(), |chan| chan.name.bytes()).ok()
}
}
impl BlockType {
const TYPE_NAME: &'static [u8] = type_names::TEXT;
pub fn parse(text: Text) -> Result<Self> {
match text.as_slice() {
block_type_strings::SCAN_LINE => Ok(Self::ScanLine),
block_type_strings::TILE => Ok(Self::Tile),
block_type_strings::DEEP_SCAN_LINE => Ok(Self::DeepScanLine),
block_type_strings::DEEP_TILE => Ok(Self::DeepTile),
_ => Err(Error::invalid("block type attribute value")),
}
}
pub fn write(&self, write: &mut impl Write) -> UnitResult {
u8::write_slice_le(write, self.to_text_bytes())?;
Ok(())
}
#[must_use]
pub const fn to_text_bytes(&self) -> &[u8] {
match self {
Self::ScanLine => block_type_strings::SCAN_LINE,
Self::Tile => block_type_strings::TILE,
Self::DeepScanLine => block_type_strings::DEEP_SCAN_LINE,
Self::DeepTile => block_type_strings::DEEP_TILE,
}
}
pub fn byte_size(&self) -> usize {
self.to_text_bytes().len()
}
}
impl IntegerBounds {
pub fn zero() -> Self {
Self::from_dimensions(Vec2(0, 0))
}
pub fn from_dimensions(size: impl Into<Vec2<usize>>) -> Self {
Self::new(Vec2(0, 0), size)
}
pub fn new(start: impl Into<Vec2<i32>>, size: impl Into<Vec2<usize>>) -> Self {
Self {
position: start.into(),
size: size.into(),
}
}
pub fn end(self) -> Vec2<i32> {
self.position + self.size.to_i32() }
pub fn max(self) -> Vec2<i32> {
self.end() - Vec2(1, 1)
}
pub fn validate(&self, max_size: Option<Vec2<usize>>) -> UnitResult {
if let Some(max_size) = max_size {
if self.size.width() > max_size.width() || self.size.height() > max_size.height() {
return Err(Error::invalid("window attribute dimension value"));
}
}
let min_i64 = Vec2(i64::from(self.position.x()), i64::from(self.position.y()));
let max_i64 = Vec2(
i64::from(self.position.x()) + self.size.width() as i64,
i64::from(self.position.y()) + self.size.height() as i64,
);
Self::validate_min_max_u64(min_i64, max_i64)
}
fn validate_min_max_u64(min: Vec2<i64>, max: Vec2<i64>) -> UnitResult {
let max_box_size_as_i64 = i64::from(i32::MAX / 2);
if max.x() >= max_box_size_as_i64
|| max.y() >= max_box_size_as_i64
|| min.x() <= -max_box_size_as_i64
|| min.y() <= -max_box_size_as_i64
{
return Err(Error::invalid("window size exceeding integer maximum"));
}
Ok(())
}
pub const fn byte_size() -> usize {
4 * i32::BYTE_SIZE
}
pub fn write<W: Write>(&self, write: &mut W) -> UnitResult {
let Vec2(x_min, y_min) = self.position;
let Vec2(x_max, y_max) = self.max();
x_min.write_le(write)?;
y_min.write_le(write)?;
x_max.write_le(write)?;
y_max.write_le(write)?;
Ok(())
}
pub fn read<R: Read>(read: &mut R) -> Result<Self> {
let x_min = i32::read_le(read)?;
let y_min = i32::read_le(read)?;
let x_max = i32::read_le(read)?;
let y_max = i32::read_le(read)?;
let min = Vec2(x_min.min(x_max), y_min.min(y_max));
let max = Vec2(x_min.max(x_max), y_min.max(y_max));
Self::validate_min_max_u64(
Vec2(i64::from(min.x()), i64::from(min.y())),
Vec2(i64::from(max.x()), i64::from(max.y())),
)?;
let size = Vec2(max.x() + 1 - min.x(), max.y() + 1 - min.y());
let size = size.to_usize("box coordinates")?;
Ok(Self {
position: min,
size,
})
}
pub fn with_origin(self, origin: Vec2<i32>) -> Self {
Self {
position: self.position + origin,
..self
}
}
pub fn contains(self, subset: Self) -> bool {
subset.position.x() >= self.position.x()
&& subset.position.y() >= self.position.y()
&& subset.end().x() <= self.end().x()
&& subset.end().y() <= self.end().y()
}
}
impl FloatRect {
pub const fn byte_size() -> usize {
4 * f32::BYTE_SIZE
}
pub fn write<W: Write>(&self, write: &mut W) -> UnitResult {
self.min.x().write_le(write)?;
self.min.y().write_le(write)?;
self.max.x().write_le(write)?;
self.max.y().write_le(write)?;
Ok(())
}
pub fn read<R: Read>(read: &mut R) -> Result<Self> {
let x_min = f32::read_le(read)?;
let y_min = f32::read_le(read)?;
let x_max = f32::read_le(read)?;
let y_max = f32::read_le(read)?;
Ok(Self {
min: Vec2(x_min, y_min),
max: Vec2(x_max, y_max),
})
}
}
impl SampleType {
pub const fn bytes_per_sample(&self) -> usize {
match self {
Self::F16 => f16::BYTE_SIZE,
Self::F32 => f32::BYTE_SIZE,
Self::U32 => u32::BYTE_SIZE,
}
}
pub const fn byte_size() -> usize {
i32::BYTE_SIZE
}
pub fn write<W: Write>(&self, write: &mut W) -> UnitResult {
match *self {
Self::U32 => 0_i32,
Self::F16 => 1_i32,
Self::F32 => 2_i32,
}
.write_le(write)?;
Ok(())
}
pub fn read<R: Read>(read: &mut R) -> Result<Self> {
Ok(match i32::read_le(read)? {
0 => Self::U32,
1 => Self::F16,
2 => Self::F32,
_ => return Err(Error::invalid("pixel type attribute value")),
})
}
}
impl ChannelDescription {
pub fn guess_quantization_linearity(name: &Text) -> bool {
!(name.eq_case_insensitive("R")
|| name.eq_case_insensitive("G")
|| name.eq_case_insensitive("B")
|| name.eq_case_insensitive("L")
|| name.eq_case_insensitive("Y")
|| name.eq_case_insensitive("X")
|| name.eq_case_insensitive("Z"))
}
pub fn named(name: impl Into<Text>, sample_type: SampleType) -> Self {
let name = name.into();
let linearity = Self::guess_quantization_linearity(&name);
Self::new(name, sample_type, linearity)
}
pub fn new(name: impl Into<Text>, sample_type: SampleType, quantize_linearly: bool) -> Self {
Self {
name: name.into(),
sample_type,
quantize_linearly,
sampling: Vec2(1, 1),
}
}
pub fn subsampled_pixels(&self, dimensions: Vec2<usize>) -> usize {
self.subsampled_resolution(dimensions).area()
}
pub fn subsampled_resolution(&self, dimensions: Vec2<usize>) -> Vec2<usize> {
dimensions / self.sampling
}
pub fn byte_size(&self) -> usize {
self.name.null_terminated_byte_size()
+ SampleType::byte_size()
+ 1 + 3 + 2 * u32::BYTE_SIZE }
pub fn write<W: Write>(&self, write: &mut W) -> UnitResult {
Text::write_null_terminated(&self.name, write)?;
self.sample_type.write(write)?;
match self.quantize_linearly {
false => 0_u8,
true => 1_u8,
}
.write_le(write)?;
i8::write_slice_le(write, &[0_i8, 0_i8, 0_i8])?;
i32::write_le(usize_to_i32(self.sampling.x(), "text length")?, write)?;
i32::write_le(usize_to_i32(self.sampling.y(), "text length")?, write)?;
Ok(())
}
pub fn read<R: Read>(read: &mut R) -> Result<Self> {
let name = Text::read_null_terminated(read, 256)?;
let sample_type = SampleType::read(read)?;
let is_linear = match u8::read_le(read)? {
1 => true,
0 => false,
_ => return Err(Error::invalid("channel linearity attribute value")),
};
let mut reserved = [0_i8; 3];
i8::read_slice_le(read, &mut reserved)?;
let x_sampling = i32_to_usize(i32::read_le(read)?, "x channel sampling")?;
let y_sampling = i32_to_usize(i32::read_le(read)?, "y channel sampling")?;
Ok(Self {
name,
sample_type,
quantize_linearly: is_linear,
sampling: Vec2(x_sampling, y_sampling),
})
}
pub fn validate(
&self,
allow_sampling: bool,
data_window: IntegerBounds,
strict: bool,
) -> UnitResult {
self.name.validate(true, None)?;
if self.sampling.x() == 0 || self.sampling.y() == 0 {
return Err(Error::invalid("zero sampling factor"));
}
if strict && !allow_sampling && self.sampling != Vec2(1, 1) {
return Err(Error::invalid("subsampling is only allowed in flat scan line images"));
}
if data_window.position.x() % self.sampling.x() as i32 != 0
|| data_window.position.y() % self.sampling.y() as i32 != 0
{
return Err(Error::invalid(
"channel sampling factor not dividing data window position",
));
}
if data_window.size.x() % self.sampling.x() != 0
|| data_window.size.y() % self.sampling.y() != 0
{
return Err(Error::invalid("channel sampling factor not dividing data window size"));
}
if self.sampling != Vec2(1, 1) {
return Err(Error::unsupported("channel subsampling not supported yet"));
}
Ok(())
}
}
impl ChannelList {
pub fn byte_size(&self) -> usize {
self.list.iter().map(ChannelDescription::byte_size).sum::<usize>()
+ sequence_end::byte_size()
}
pub fn write(&self, write: &mut impl Write) -> UnitResult {
for channel in &self.list {
channel.write(write)?;
}
sequence_end::write(write)?;
Ok(())
}
pub fn read(read: &mut PeekRead<impl Read>) -> Result<Self> {
let mut channels = SmallVec::new();
while !sequence_end::has_come(read)? {
channels.push(ChannelDescription::read(read)?);
}
Ok(Self::new(channels))
}
pub fn validate(
&self,
allow_sampling: bool,
data_window: IntegerBounds,
strict: bool,
) -> UnitResult {
let mut iter = self
.list
.iter()
.map(|chan| chan.validate(allow_sampling, data_window, strict).map(|()| &chan.name));
let mut previous =
iter.next().ok_or_else(|| Error::invalid("at least one channel is required"))??;
for result in iter {
let value = result?;
if strict && previous == value {
return Err(Error::invalid("channel names are not unique"));
} else if previous > value {
return Err(Error::invalid("channel names are not sorted alphabetically"));
} else {
previous = value;
}
}
Ok(())
}
}
fn u8_to_decimal32(binary: u8) -> u32 {
let units = u32::from(binary) % 10;
let tens = (u32::from(binary) / 10) % 10;
units | (tens << 4)
}
const fn u8_from_decimal32(coded: u32) -> u8 {
((coded & 0x0f) + 10 * ((coded >> 4) & 0x0f)) as u8
}
impl TimeCode {
pub const BYTE_SIZE: usize = 2 * u32::BYTE_SIZE;
pub fn validate(&self, strict: bool) -> UnitResult {
if strict {
if self.frame > 29 {
Err(Error::invalid("time code frame larger than 29"))
} else if self.seconds > 59 {
Err(Error::invalid("time code seconds larger than 59"))
} else if self.minutes > 59 {
Err(Error::invalid("time code minutes larger than 59"))
} else if self.hours > 23 {
Err(Error::invalid("time code hours larger than 23"))
} else if self.binary_groups.iter().any(|&group| group > 15) {
Err(Error::invalid("time code binary group value too large for 3 bits"))
} else {
Ok(())
}
} else {
Ok(())
}
}
pub fn pack_time_as_tv60_u32(&self) -> Result<u32> {
self.validate(true)?;
Ok(*0_u32
.set_bits(0..6, u8_to_decimal32(self.frame))
.set_bit(6, self.drop_frame)
.set_bit(7, self.color_frame)
.set_bits(8..15, u8_to_decimal32(self.seconds))
.set_bit(15, self.field_phase)
.set_bits(16..23, u8_to_decimal32(self.minutes))
.set_bit(23, self.binary_group_flags[0])
.set_bits(24..30, u8_to_decimal32(self.hours))
.set_bit(30, self.binary_group_flags[1])
.set_bit(31, self.binary_group_flags[2]))
}
pub fn from_tv60_time(tv60_time: u32, user_data: u32) -> Self {
Self {
frame: u8_from_decimal32(tv60_time.get_bits(0..6)),
drop_frame: tv60_time.get_bit(6),
color_frame: tv60_time.get_bit(7),
seconds: u8_from_decimal32(tv60_time.get_bits(8..15)),
field_phase: tv60_time.get_bit(15),
minutes: u8_from_decimal32(tv60_time.get_bits(16..23)),
hours: u8_from_decimal32(tv60_time.get_bits(24..30)),
binary_group_flags: [
tv60_time.get_bit(23),
tv60_time.get_bit(30),
tv60_time.get_bit(31),
],
binary_groups: Self::unpack_user_data_from_u32(user_data),
}
}
pub fn pack_time_as_tv50_u32(&self) -> Result<u32> {
Ok(*self
.pack_time_as_tv60_u32()?
.set_bit(6, false)
.set_bit(15, self.binary_group_flags[0])
.set_bit(30, self.binary_group_flags[1])
.set_bit(23, self.binary_group_flags[2])
.set_bit(31, self.field_phase))
}
pub fn from_tv50_time(tv50_time: u32, user_data: u32) -> Self {
Self {
drop_frame: false,
field_phase: tv50_time.get_bit(31),
binary_group_flags: [
tv50_time.get_bit(15),
tv50_time.get_bit(30),
tv50_time.get_bit(23),
],
..Self::from_tv60_time(tv50_time, user_data)
}
}
pub fn pack_time_as_film24_u32(&self) -> Result<u32> {
Ok(*self.pack_time_as_tv60_u32()?.set_bit(6, false).set_bit(7, false))
}
pub fn from_film24_time(film24_time: u32, user_data: u32) -> Self {
Self {
drop_frame: false, color_frame: false, ..Self::from_tv60_time(film24_time, user_data)
}
}
const fn user_data_bit_indices(group_index: usize) -> std::ops::Range<usize> {
let min_bit = 4 * group_index;
min_bit..min_bit + 4 }
pub fn pack_user_data_as_u32(&self) -> u32 {
let packed = self.binary_groups.iter().enumerate().fold(
0_u32,
|mut packed, (group_index, group_value)| {
*packed.set_bits(
Self::user_data_bit_indices(group_index),
u32::from(*group_value.min(&15)),
)
},
);
debug_assert_eq!(
Self::unpack_user_data_from_u32(packed),
self.binary_groups,
"round trip user data encoding"
);
packed
}
fn unpack_user_data_from_u32(user_data: u32) -> [u8; 8] {
(0..8)
.map(|group_index| user_data.get_bits(Self::user_data_bit_indices(group_index)) as u8)
.collect::<SmallVec<[u8; 8]>>()
.into_inner()
.expect("array index bug")
}
pub fn write<W: Write>(&self, write: &mut W) -> UnitResult {
self.pack_time_as_tv60_u32()?.write_le(write)?; self.pack_user_data_as_u32().write_le(write)?;
Ok(())
}
pub fn read<R: Read>(read: &mut R) -> Result<Self> {
let time_and_flags = u32::read_le(read)?;
let user_data = u32::read_le(read)?;
Ok(Self::from_tv60_time(time_and_flags, user_data))
}
}
impl Chromaticities {
pub const fn byte_size() -> usize {
8 * f32::BYTE_SIZE
}
pub fn write<W: Write>(&self, write: &mut W) -> UnitResult {
self.red.x().write_le(write)?;
self.red.y().write_le(write)?;
self.green.x().write_le(write)?;
self.green.y().write_le(write)?;
self.blue.x().write_le(write)?;
self.blue.y().write_le(write)?;
self.white.x().write_le(write)?;
self.white.y().write_le(write)?;
Ok(())
}
pub fn read<R: Read>(read: &mut R) -> Result<Self> {
Ok(Chromaticities {
red: Vec2(f32::read_le(read)?, f32::read_le(read)?),
green: Vec2(f32::read_le(read)?, f32::read_le(read)?),
blue: Vec2(f32::read_le(read)?, f32::read_le(read)?),
white: Vec2(f32::read_le(read)?, f32::read_le(read)?),
})
}
}
impl Compression {
pub const fn byte_size() -> usize {
u8::BYTE_SIZE
}
pub fn write<W: Write>(self, write: &mut W) -> UnitResult {
use self::Compression::*;
match self {
Uncompressed => 0_u8,
RLE => 1_u8,
ZIP1 => 2_u8,
ZIP16 => 3_u8,
PIZ => 4_u8,
PXR24 => 5_u8,
B44 => 6_u8,
B44A => 7_u8,
DWAA(_) => 8_u8,
DWAB(_) => 9_u8,
HTJ2K256 => 10_u8,
HTJ2K32 => 11_u8,
}
.write_le(write)?;
Ok(())
}
pub fn read<R: Read>(read: &mut R) -> Result<Self> {
use self::Compression::*;
Ok(match u8::read_le(read)? {
0 => Uncompressed,
1 => RLE,
2 => ZIP1,
3 => ZIP16,
4 => PIZ,
5 => PXR24,
6 => B44,
7 => B44A,
8 => DWAA(None),
9 => DWAB(None),
10 => HTJ2K256,
11 => HTJ2K32,
_ => return Err(Error::unsupported("unknown compression method")),
})
}
}
impl EnvironmentMap {
pub const fn byte_size() -> usize {
u8::BYTE_SIZE
}
pub fn write<W: Write>(self, write: &mut W) -> UnitResult {
use self::EnvironmentMap::*;
match self {
LatitudeLongitude => 0_u8,
Cube => 1_u8,
}
.write_le(write)?;
Ok(())
}
pub fn read<R: Read>(read: &mut R) -> Result<Self> {
use self::EnvironmentMap::*;
Ok(match u8::read_le(read)? {
0 => LatitudeLongitude,
1 => Cube,
_ => return Err(Error::invalid("environment map attribute value")),
})
}
}
impl KeyCode {
pub fn byte_size() -> usize {
6 * i32::BYTE_SIZE
}
pub fn write<W: Write>(&self, write: &mut W) -> UnitResult {
self.film_manufacturer_code.write_le(write)?;
self.film_type.write_le(write)?;
self.film_roll_prefix.write_le(write)?;
self.count.write_le(write)?;
self.perforation_offset.write_le(write)?;
self.perforations_per_count.write_le(write)?;
Ok(())
}
pub fn read<R: Read>(read: &mut R) -> Result<Self> {
Ok(Self {
film_manufacturer_code: i32::read_le(read)?,
film_type: i32::read_le(read)?,
film_roll_prefix: i32::read_le(read)?,
count: i32::read_le(read)?,
perforation_offset: i32::read_le(read)?,
perforations_per_frame: i32::read_le(read)?,
perforations_per_count: i32::read_le(read)?,
})
}
}
impl LineOrder {
pub const fn byte_size() -> usize {
u8::BYTE_SIZE
}
pub fn write<W: Write>(self, write: &mut W) -> UnitResult {
use self::LineOrder::*;
match self {
Increasing => 0_u8,
Decreasing => 1_u8,
Unspecified => 2_u8,
}
.write_le(write)?;
Ok(())
}
pub fn read<R: Read>(read: &mut R) -> Result<Self> {
use self::LineOrder::*;
Ok(match u8::read_le(read)? {
0 => Increasing,
1 => Decreasing,
2 => Unspecified,
_ => return Err(Error::invalid("line order attribute value")),
})
}
}
impl Preview {
pub fn byte_size(&self) -> usize {
2 * u32::BYTE_SIZE + self.pixel_data.len()
}
pub fn write<W: Write>(&self, write: &mut W) -> UnitResult {
u32::write_le(self.size.width() as u32, write)?;
u32::write_le(self.size.height() as u32, write)?;
i8::write_slice_le(write, &self.pixel_data)?;
Ok(())
}
pub fn read<R: Read>(read: &mut R) -> Result<Self> {
let width = u32::read_le(read)? as usize;
let height = u32::read_le(read)? as usize;
if let Some(pixel_count) = width.checked_mul(height) {
if let Some(byte_count) = pixel_count.checked_mul(4) {
let pixel_data = i8::read_vec_le(
read,
byte_count,
1024 * 1024 * 4,
None,
"preview attribute pixel count",
)?;
let preview = Self {
size: Vec2(width, height),
pixel_data,
};
return Ok(preview);
}
}
Err(Error::invalid(format!(
"Overflow while calculating preview image Attribute size \
(width: {width}, height: {height})."
)))
}
pub fn validate(&self, strict: bool) -> UnitResult {
if strict && (self.size.area() * 4 != self.pixel_data.len()) {
return Err(Error::invalid("preview dimensions do not match content length"));
}
Ok(())
}
}
impl ::std::fmt::Debug for Preview {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(f, "Preview ({}x{} px)", self.size.width(), self.size.height())
}
}
impl TileDescription {
pub const fn byte_size() -> usize {
2 * u32::BYTE_SIZE + 1 }
pub fn write<W: Write>(&self, write: &mut W) -> UnitResult {
u32::write_le(self.tile_size.width() as u32, write)?;
u32::write_le(self.tile_size.height() as u32, write)?;
let level_mode = match self.level_mode {
LevelMode::Singular => 0_u8,
LevelMode::MipMap => 1_u8,
LevelMode::RipMap => 2_u8,
};
let rounding_mode = match self.rounding_mode {
RoundingMode::Down => 0_u8,
RoundingMode::Up => 1_u8,
};
let mode: u8 = level_mode + (rounding_mode * 16);
mode.write_le(write)?;
Ok(())
}
pub fn read<R: Read>(read: &mut R) -> Result<Self> {
let x_size = u32::read_le(read)? as usize;
let y_size = u32::read_le(read)? as usize;
let mode = u8::read_le(read)?;
let level_mode = mode & 0b00001111; let rounding_mode = mode >> 4;
let level_mode = match level_mode {
0 => LevelMode::Singular,
1 => LevelMode::MipMap,
2 => LevelMode::RipMap,
_ => return Err(Error::invalid("tile description level mode")),
};
let rounding_mode = match rounding_mode {
0 => RoundingMode::Down,
1 => RoundingMode::Up,
_ => return Err(Error::invalid("tile description rounding mode")),
};
Ok(Self {
tile_size: Vec2(x_size, y_size),
level_mode,
rounding_mode,
})
}
pub fn validate(&self) -> UnitResult {
let max = i64::from(i32::MAX) / 2;
if self.tile_size.width() == 0
|| self.tile_size.height() == 0
|| self.tile_size.width() as i64 >= max
|| self.tile_size.height() as i64 >= max
{
return Err(Error::invalid("tile size"));
}
Ok(())
}
}
pub fn byte_size(name: &Text, value: &AttributeValue) -> usize {
name.null_terminated_byte_size()
+ value.kind_name().len() + sequence_end::byte_size()
+ i32::BYTE_SIZE + value.byte_size()
}
pub fn write<W: Write>(name: &TextSlice, value: &AttributeValue, write: &mut W) -> UnitResult {
Text::write_null_terminated_bytes(name, write)?;
Text::write_null_terminated_bytes(value.kind_name(), write)?;
i32::write_le(value.byte_size() as i32, write)?;
value.write(write)
}
pub fn read(
read: &mut PeekRead<impl Read>,
max_size: usize,
) -> Result<(Text, Result<AttributeValue>)> {
let name = Text::read_null_terminated(read, max_size)?;
let kind = Text::read_null_terminated(read, max_size)?;
let size = i32_to_usize(i32::read_le(read)?, "attribute size")?;
let value = AttributeValue::read(read, kind, size)?;
Ok((name, value))
}
pub fn validate(
name: &Text,
value: &AttributeValue,
long_names: &mut bool,
allow_sampling: bool,
data_window: IntegerBounds,
strict: bool,
) -> UnitResult {
name.validate(true, Some(long_names))?; value.validate(allow_sampling, data_window, strict) }
impl AttributeValue {
pub fn byte_size(&self) -> usize {
use self::AttributeValue::*;
match *self {
IntegerBounds(_) => self::IntegerBounds::byte_size(),
FloatRect(_) => self::FloatRect::byte_size(),
I32(_) => i32::BYTE_SIZE,
F32(_) => f32::BYTE_SIZE,
F64(_) => f64::BYTE_SIZE,
Rational(_) => i32::BYTE_SIZE + u32::BYTE_SIZE,
TimeCode(_) => self::TimeCode::BYTE_SIZE,
IntVec2(_) => 2 * i32::BYTE_SIZE,
FloatVec2(_) => 2 * f32::BYTE_SIZE,
IntVec3(_) => 3 * i32::BYTE_SIZE,
FloatVec3(_) => 3 * f32::BYTE_SIZE,
ChannelList(ref channels) => channels.byte_size(),
Chromaticities(_) => self::Chromaticities::byte_size(),
Compression(_) => self::Compression::byte_size(),
EnvironmentMap(_) => self::EnvironmentMap::byte_size(),
KeyCode(_) => self::KeyCode::byte_size(),
LineOrder(_) => self::LineOrder::byte_size(),
Matrix3x3(ref value) => value.len() * f32::BYTE_SIZE,
Matrix4x4(ref value) => value.len() * f32::BYTE_SIZE,
Preview(ref value) => value.byte_size(),
Text(ref value) => value.bytes.len(),
TextVector(ref value) => value.iter().map(self::Text::i32_sized_byte_size).sum(),
TileDescription(_) => self::TileDescription::byte_size(),
Custom {
ref bytes,
..
} => bytes.len(),
BlockType(ref kind) => kind.byte_size(),
Bytes {
ref bytes,
ref type_hint,
} => type_hint.u32_sized_byte_size() + bytes.len(),
}
}
pub fn kind_name(&self) -> &TextSlice {
use self::{type_names as ty, AttributeValue::*};
match *self {
IntegerBounds(_) => ty::I32BOX2,
FloatRect(_) => ty::F32BOX2,
I32(_) => ty::I32,
F32(_) => ty::F32,
F64(_) => ty::F64,
Rational(_) => ty::RATIONAL,
TimeCode(_) => ty::TIME_CODE,
IntVec2(_) => ty::I32VEC2,
FloatVec2(_) => ty::F32VEC2,
IntVec3(_) => ty::I32VEC3,
FloatVec3(_) => ty::F32VEC3,
ChannelList(_) => ty::CHANNEL_LIST,
Chromaticities(_) => ty::CHROMATICITIES,
Compression(_) => ty::COMPRESSION,
EnvironmentMap(_) => ty::ENVIRONMENT_MAP,
KeyCode(_) => ty::KEY_CODE,
LineOrder(_) => ty::LINE_ORDER,
Matrix3x3(_) => ty::F32MATRIX3X3,
Matrix4x4(_) => ty::F32MATRIX4X4,
Preview(_) => ty::PREVIEW,
Text(_) => ty::TEXT,
TextVector(_) => ty::TEXT_VECTOR,
TileDescription(_) => ty::TILES,
BlockType(_) => super::BlockType::TYPE_NAME,
Bytes {
..
} => ty::BYTES,
Custom {
ref kind,
..
} => kind.as_slice(),
}
}
pub fn write<W: Write>(&self, write: &mut W) -> UnitResult {
use self::AttributeValue::*;
match *self {
IntegerBounds(value) => value.write(write)?,
FloatRect(value) => value.write(write)?,
I32(value) => value.write_le(write)?,
F32(value) => value.write_le(write)?,
F64(value) => value.write_le(write)?,
Rational((a, b)) => {
a.write_le(write)?;
b.write_le(write)?;
}
TimeCode(codes) => codes.write(write)?,
IntVec2(Vec2(x, y)) => {
x.write_le(write)?;
y.write_le(write)?;
}
FloatVec2(Vec2(x, y)) => {
x.write_le(write)?;
y.write_le(write)?;
}
IntVec3((x, y, z)) => {
x.write_le(write)?;
y.write_le(write)?;
z.write_le(write)?;
}
FloatVec3((x, y, z)) => {
x.write_le(write)?;
y.write_le(write)?;
z.write_le(write)?;
}
ChannelList(ref channels) => channels.write(write)?,
Chromaticities(ref value) => value.write(write)?,
Compression(value) => value.write(write)?,
EnvironmentMap(value) => value.write(write)?,
KeyCode(value) => value.write(write)?,
LineOrder(value) => value.write(write)?,
Matrix3x3(value) => f32::write_slice_le(write, &value)?,
Matrix4x4(value) => f32::write_slice_le(write, &value)?,
Preview(ref value) => value.write(write)?,
Text(ref value) => u8::write_slice_le(write, value.bytes.as_slice())?,
TextVector(ref value) => self::Text::write_vec_of_i32_sized_texts_le(write, value)?,
TileDescription(ref value) => value.write(write)?,
BlockType(kind) => kind.write(write)?,
Bytes {
ref type_hint,
ref bytes,
} => {
type_hint.write_u32_sized_le(write)?; u8::write_slice_le(write, bytes.as_slice())?;
}
Custom {
ref bytes,
..
} => u8::write_slice_le(write, bytes)?, }
Ok(())
}
pub fn read(
read: &mut PeekRead<impl Read>,
kind: Text,
byte_size: usize,
) -> Result<Result<Self>> {
use self::{type_names as ty, AttributeValue::*};
let mut attribute_bytes = SmallVec::<[u8; 64]>::new();
u8::read_into_vec_le(
read,
&mut attribute_bytes,
byte_size,
64,
None,
"attribute value size",
)?;
let parse_attribute = move || {
let reader = &mut attribute_bytes.as_slice();
Ok(match kind.bytes.as_slice() {
ty::I32BOX2 => IntegerBounds(self::IntegerBounds::read(reader)?),
ty::F32BOX2 => FloatRect(self::FloatRect::read(reader)?),
ty::I32 => I32(i32::read_le(reader)?),
ty::F32 => F32(f32::read_le(reader)?),
ty::F64 => F64(f64::read_le(reader)?),
ty::RATIONAL => Rational({
let a = i32::read_le(reader)?;
let b = u32::read_le(reader)?;
(a, b)
}),
ty::TIME_CODE => TimeCode(self::TimeCode::read(reader)?),
ty::I32VEC2 => IntVec2({
let a = i32::read_le(reader)?;
let b = i32::read_le(reader)?;
Vec2(a, b)
}),
ty::F32VEC2 => FloatVec2({
let a = f32::read_le(reader)?;
let b = f32::read_le(reader)?;
Vec2(a, b)
}),
ty::I32VEC3 => IntVec3({
let a = i32::read_le(reader)?;
let b = i32::read_le(reader)?;
let c = i32::read_le(reader)?;
(a, b, c)
}),
ty::F32VEC3 => FloatVec3({
let a = f32::read_le(reader)?;
let b = f32::read_le(reader)?;
let c = f32::read_le(reader)?;
(a, b, c)
}),
ty::CHANNEL_LIST => ChannelList(self::ChannelList::read(&mut PeekRead::new(
attribute_bytes.as_slice(),
))?),
ty::CHROMATICITIES => Chromaticities(self::Chromaticities::read(reader)?),
ty::COMPRESSION => Compression(self::Compression::read(reader)?),
ty::ENVIRONMENT_MAP => EnvironmentMap(self::EnvironmentMap::read(reader)?),
ty::KEY_CODE => KeyCode(self::KeyCode::read(reader)?),
ty::LINE_ORDER => LineOrder(self::LineOrder::read(reader)?),
ty::F32MATRIX3X3 => Matrix3x3({
let mut result = [0.0_f32; 9];
f32::read_slice_le(reader, &mut result)?;
result
}),
ty::F32MATRIX4X4 => Matrix4x4({
let mut result = [0.0_f32; 16];
f32::read_slice_le(reader, &mut result)?;
result
}),
ty::PREVIEW => Preview(self::Preview::read(reader)?),
ty::TEXT => Text(self::Text::read_sized(reader, byte_size)?),
ty::TEXT_VECTOR => TextVector(self::Text::read_vec_of_i32_sized_texts_le(
&mut PeekRead::new(attribute_bytes.as_slice()),
byte_size,
)?),
ty::TILES => TileDescription(self::TileDescription::read(reader)?),
ty::BYTES => {
let type_hint = self::Text::read_u32_sized_le(reader, reader.len())?;
let bytes = SmallVec::from(*reader);
Bytes {
type_hint,
bytes,
}
}
_ => Custom {
kind: kind.clone(),
bytes: SmallVec::from(*reader),
},
})
};
Ok(parse_attribute())
}
pub fn validate(
&self,
allow_sampling: bool,
data_window: IntegerBounds,
strict: bool,
) -> UnitResult {
use self::AttributeValue::*;
match *self {
ChannelList(ref channels) => channels.validate(allow_sampling, data_window, strict)?,
TileDescription(ref value) => value.validate()?,
Preview(ref value) => value.validate(strict)?,
TimeCode(ref time_code) => time_code.validate(strict)?,
TextVector(ref vec) => {
if strict && vec.is_empty() {
return Err(Error::invalid("text vector may not be empty"));
}
}
_ => {}
}
Ok(())
}
pub fn to_i32(&self) -> Result<i32> {
match *self {
Self::I32(value) => Ok(value),
_ => Err(invalid_type()),
}
}
pub fn to_f32(&self) -> Result<f32> {
match *self {
Self::F32(value) => Ok(value),
_ => Err(invalid_type()),
}
}
pub fn into_text(self) -> Result<Text> {
match self {
Self::Text(value) => Ok(value),
_ => Err(invalid_type()),
}
}
pub fn to_text(&self) -> Result<&Text> {
match self {
Self::Text(value) => Ok(value),
_ => Err(invalid_type()),
}
}
pub fn to_chromaticities(&self) -> Result<Chromaticities> {
match *self {
Self::Chromaticities(value) => Ok(value),
_ => Err(invalid_type()),
}
}
pub fn to_time_code(&self) -> Result<TimeCode> {
match *self {
Self::TimeCode(value) => Ok(value),
_ => Err(invalid_type()),
}
}
}
pub mod type_names {
macro_rules! define_attribute_type_names {
( $($name: ident : $value: expr),* ) => {
$(
pub const $name: &'static [u8] = $value;
)*
};
}
define_attribute_type_names! {
I32BOX2: b"box2i",
F32BOX2: b"box2f",
I32: b"int",
F32: b"float",
F64: b"double",
RATIONAL: b"rational",
TIME_CODE: b"timecode",
I32VEC2: b"v2i",
F32VEC2: b"v2f",
I32VEC3: b"v3i",
F32VEC3: b"v3f",
CHANNEL_LIST: b"chlist",
CHROMATICITIES: b"chromaticities",
COMPRESSION: b"compression",
ENVIRONMENT_MAP:b"envmap",
KEY_CODE: b"keycode",
LINE_ORDER: b"lineOrder",
F32MATRIX3X3: b"m33f",
F32MATRIX4X4: b"m44f",
PREVIEW: b"preview",
TEXT: b"string",
TEXT_VECTOR: b"stringvector",
TILES: b"tiledesc",
BYTES: b"bytes"
}
}
#[cfg(test)]
mod test {
use ::std::io::Cursor;
use rand::{random, thread_rng, Rng};
use super::*;
#[test]
fn text_ord() {
for _ in 0..1024 {
let text1 = Text::from_bytes_unchecked((0..4).map(|_| rand::random::<u8>()).collect());
let text2 = Text::from_bytes_unchecked((0..4).map(|_| rand::random::<u8>()).collect());
assert_eq!(
text1.to_string().cmp(&text2.to_string()),
text1.cmp(&text2),
"in text {text1:?} vs {text2:?}"
);
}
}
#[test]
fn rounding_up() {
let round_up = RoundingMode::Up;
assert_eq!(round_up.divide(10, 10), 1, "divide equal");
assert_eq!(round_up.divide(10, 2), 5, "divide even");
assert_eq!(round_up.divide(10, 5), 2, "divide even");
assert_eq!(round_up.divide(8, 5), 2, "round up");
assert_eq!(round_up.divide(10, 3), 4, "round up");
assert_eq!(round_up.divide(100, 50), 2, "divide even");
assert_eq!(round_up.divide(100, 49), 3, "round up");
}
#[test]
fn rounding_down() {
let round_down = RoundingMode::Down;
assert_eq!(round_down.divide(8, 5), 1, "round down");
assert_eq!(round_down.divide(10, 3), 3, "round down");
assert_eq!(round_down.divide(100, 50), 2, "divide even");
assert_eq!(round_down.divide(100, 49), 2, "round down");
assert_eq!(round_down.divide(100, 51), 1, "round down");
}
#[test]
fn tile_description_write_read_roundtrip() {
let tiles = [
TileDescription {
tile_size: Vec2(31, 7),
level_mode: LevelMode::MipMap,
rounding_mode: RoundingMode::Down,
},
TileDescription {
tile_size: Vec2(0, 0),
level_mode: LevelMode::Singular,
rounding_mode: RoundingMode::Up,
},
TileDescription {
tile_size: Vec2(4294967294, 4294967295),
level_mode: LevelMode::RipMap,
rounding_mode: RoundingMode::Down,
},
];
for tile in &tiles {
let mut bytes = Vec::new();
tile.write(&mut bytes).unwrap();
let new_tile = TileDescription::read(&mut Cursor::new(bytes)).unwrap();
assert_eq!(*tile, new_tile, "tile round trip");
}
}
#[test]
fn attribute_write_read_roundtrip_and_byte_size() {
let attributes = [
(Text::from("greeting"), AttributeValue::Text(Text::from("hello"))),
(Text::from("age"), AttributeValue::I32(923)),
(Text::from("leg count"), AttributeValue::F64(9.114939599234)),
(
Text::from("rabbit area"),
AttributeValue::FloatRect(FloatRect {
min: Vec2(23.4234, 345.23),
max: Vec2(68623.0, 3.124_259_2),
}),
),
(
Text::from("rabbit area int"),
AttributeValue::IntegerBounds(IntegerBounds {
position: Vec2(23, 345),
size: Vec2(68623, 3),
}),
),
(
Text::from("rabbit area int"),
AttributeValue::IntegerBounds(IntegerBounds {
position: Vec2(-(i32::MAX / 2 - 1), -(i32::MAX / 2 - 1)),
size: Vec2(i32::MAX as usize - 2, i32::MAX as usize - 2),
}),
),
(
Text::from("rabbit area int 2"),
AttributeValue::IntegerBounds(IntegerBounds {
position: Vec2(0, 0),
size: Vec2(i32::MAX as usize / 2 - 1, i32::MAX as usize / 2 - 1),
}),
),
(
Text::from("tests are difficult"),
AttributeValue::TextVector(vec![
Text::from("sdoifjpsdv"),
Text::from("sdoifjpsdvxxxx"),
Text::from("sdoifjasd"),
Text::from("sdoifj"),
Text::from("sdoifjddddddddasdasd"),
]),
),
(
Text::from("what should we eat tonight"),
AttributeValue::Preview(Preview {
size: Vec2(10, 30),
pixel_data: vec![31; 10 * 30 * 4],
}),
),
(
Text::from("custom byte sequence: prime numbers single byte"),
AttributeValue::Bytes {
type_hint: Text::from("byte-primes"),
bytes: smallvec![
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73
],
},
),
(
Text::from("leg count, again"),
AttributeValue::ChannelList(ChannelList::new(smallvec![
ChannelDescription {
name: Text::from("Green"),
sample_type: SampleType::F16,
quantize_linearly: false,
sampling: Vec2(1, 2)
},
ChannelDescription {
name: Text::from("Red"),
sample_type: SampleType::F32,
quantize_linearly: true,
sampling: Vec2(1, 2)
},
ChannelDescription {
name: Text::from("Purple"),
sample_type: SampleType::U32,
quantize_linearly: false,
sampling: Vec2(0, 0)
}
])),
),
];
for (name, value) in &attributes {
let mut bytes = Vec::new();
super::write(name.as_slice(), value, &mut bytes).unwrap();
assert_eq!(
super::byte_size(name, value),
bytes.len(),
"attribute.byte_size() for {:?}",
(name, value)
);
let new_attribute = super::read(&mut PeekRead::new(Cursor::new(bytes)), 300).unwrap();
assert_eq!(
(name.clone(), value.clone()),
(new_attribute.0, new_attribute.1.unwrap()),
"attribute round trip"
);
}
{
let (name, value) =
(Text::from("asdkaspfokpaosdkfpaokswdpoakpsfokaposdkf"), AttributeValue::I32(0));
let mut long_names = false;
super::validate(&name, &value, &mut long_names, false, IntegerBounds::zero(), false)
.unwrap();
assert!(long_names);
}
{
let (name, value) = (
Text::from("sdöksadöofkaspdolkpöasolfkcöalsod,kfcöaslodkcpöasolkfposdöksadöofkaspdolkpöasolfkcöalsod,kfcöaslodkcpöasolkfposdöksadöofkaspdolkpöasolfkcöalsod,kfcöaslodkcpöasolkfposdöksadöofkaspdolkpöasolfkcöalsod,kfcöaslodkcpöasolkfposdöksadöofkaspdolkpöasolfkcöalsod,kfcöaslodkcpöasolkfposdöksadöofkaspdolkpöasolfkcöalsod,kfcöaslodkcpöasolkfpo"),
AttributeValue::I32(0),
);
super::validate(&name, &value, &mut false, false, IntegerBounds::zero(), false)
.expect_err("name length check failed");
}
}
#[test]
fn time_code_pack() {
let mut rng = thread_rng();
let codes = std::iter::repeat_with(|| TimeCode {
hours: rng.gen_range(0..24),
minutes: rng.gen_range(0..60),
seconds: rng.gen_range(0..60),
frame: rng.gen_range(0..29),
drop_frame: random(),
color_frame: random(),
field_phase: random(),
binary_group_flags: [random(), random(), random()],
binary_groups: std::iter::repeat_with(|| rng.gen_range(0..16))
.take(8)
.collect::<SmallVec<[u8; 8]>>()
.into_inner()
.unwrap(),
});
for code in codes.take(500) {
code.validate(true).expect("invalid timecode test input");
{
let packed_tv60 =
code.pack_time_as_tv60_u32().expect("invalid timecode test input");
let packed_user = code.pack_user_data_as_u32();
assert_eq!(TimeCode::from_tv60_time(packed_tv60, packed_user), code);
}
{
let mut bytes = Vec::<u8>::new();
code.write(&mut bytes).unwrap();
let decoded = TimeCode::read(&mut bytes.as_slice()).unwrap();
assert_eq!(code, decoded);
}
{
let tv50_code = TimeCode {
drop_frame: false,
..code
};
let packed_tv50 =
code.pack_time_as_tv50_u32().expect("invalid timecode test input");
let packed_user = code.pack_user_data_as_u32();
assert_eq!(TimeCode::from_tv50_time(packed_tv50, packed_user), tv50_code);
}
{
let film24_code = TimeCode {
color_frame: false,
drop_frame: false,
..code
};
let packed_film24 =
code.pack_time_as_film24_u32().expect("invalid timecode test input");
let packed_user = code.pack_user_data_as_u32();
assert_eq!(TimeCode::from_film24_time(packed_film24, packed_user), film24_code);
}
}
}
}