use super::{Audio, Frame, ImageInfo, Layout, Movie, Params, Sprite, Transform, decode_shape};
use crate::{
Document, Limits,
document::{AUDIOS, PARAMS, SPRITES, VERSION},
error::{Error, Result},
wire::{self, Item},
};
use std::{cell::Cell, collections::HashMap};
const MIN_FRAME_BYTES: usize = 2;
pub(super) struct Budget(Cell<usize>);
impl Budget {
fn remaining(&self) -> usize {
self.0.get()
}
pub fn spend(&self) -> Result<()> {
let left = self.0.get().checked_sub(1);
self.0
.set(left.ok_or(Error::limit("svga_too_many_elements"))?);
Ok(())
}
}
pub(super) fn fold<'a, T>(
payload: &'a [u8],
initial: T,
mut apply: impl FnMut(T, Item<'a>) -> Result<T>,
) -> Result<T> {
wire::values(payload).try_fold(initial, |value, field| apply(value, field?))
}
pub(crate) fn movie(document: &Document, limits: &Limits) -> Result<Movie> {
let budget = Budget(Cell::new(limits.max_elements));
let header = Movie {
images: images(document, &budget)?,
..Movie::default()
};
document.fields().try_fold(header, |movie, field| {
Ok(match field.number {
VERSION => Movie {
version: field.str()?.to_owned(),
..movie
},
PARAMS => Movie {
params: params(movie.params, field.bytes()?)?,
..movie
},
SPRITES => {
let sprite = sprite(field.bytes()?, movie.params.frames, &budget)?;
Movie {
sprites: pushed(movie.sprites, sprite),
..movie
}
}
AUDIOS => {
let audio = audio(field.bytes()?, &budget)?;
Movie {
audios: pushed(movie.audios, audio),
..movie
}
}
_ => movie,
})
})
}
pub(super) fn pushed<T>(mut items: Vec<T>, item: T) -> Vec<T> {
items.push(item);
items
}
fn images(document: &Document, budget: &Budget) -> Result<Vec<ImageInfo>> {
let mut slots: HashMap<String, usize> = HashMap::new();
let mut infos: Vec<ImageInfo> = Vec::new();
for image in document.images() {
budget.spend()?;
let info = ImageInfo {
key: String::from_utf8_lossy(image.key_bytes()).into_owned(),
byte_len: image.value().len(),
kind: image.kind(),
};
let slot = *slots.entry(info.key.clone()).or_insert(infos.len());
match infos.get_mut(slot) {
Some(seen) => *seen = info,
None => infos.push(info),
}
}
Ok(infos)
}
fn params(initial: Params, payload: &[u8]) -> Result<Params> {
fold(payload, initial, |params, field| {
Ok(match field.number {
1 => Params {
view_box_width: field.f32()?,
..params
},
2 => Params {
view_box_height: field.f32()?,
..params
},
3 => Params {
fps: field.i32()?,
..params
},
4 => Params {
frames: field.i32()?,
..params
},
_ => params,
})
})
}
fn sprite(payload: &[u8], expected_frames: i32, budget: &Budget) -> Result<Sprite> {
budget.spend()?;
let capacity = usize::try_from(expected_frames)
.unwrap_or(0)
.min(payload.len() / MIN_FRAME_BYTES)
.min(budget.remaining());
let mut sprite = Sprite {
frames: Vec::with_capacity(capacity),
..Sprite::default()
};
for field in wire::values(payload) {
let field = field?;
match field.number {
1 => sprite.image_key = field.str()?.to_owned(),
2 => {
sprite.frames.push(Frame::default());
if let Some(slot) = sprite.frames.last_mut() {
frame(slot, field.bytes()?, budget)?;
}
}
3 => sprite.matte_key = field.str()?.to_owned(),
_ => {}
}
}
Ok(sprite)
}
fn frame(frame: &mut Frame, payload: &[u8], budget: &Budget) -> Result<()> {
budget.spend()?;
for field in wire::values(payload) {
let field = field?;
match field.number {
1 => frame.alpha = field.f32()?,
2 => frame.layout = layout(frame.layout, field.bytes()?)?,
3 => frame.transform = Some(transform(frame.transform, field.bytes()?)?),
4 => frame.clip_path = field.str()?.to_owned(),
5 => frame
.shapes
.push(decode_shape::shape(field.bytes()?, budget)?),
_ => {}
}
}
Ok(())
}
fn layout(initial: Layout, payload: &[u8]) -> Result<Layout> {
if let Some([width, height]) = fixed_floats(payload, [0x1d, 0x25]) {
return Ok(Layout {
width,
height,
..initial
});
}
let mut layout = initial;
for field in wire::values(payload) {
let field = field?;
match field.number {
1 => layout.x = field.f32()?,
2 => layout.y = field.f32()?,
3 => layout.width = field.f32()?,
4 => layout.height = field.f32()?,
_ => {}
}
}
Ok(layout)
}
pub(super) fn transform(initial: Option<Transform>, payload: &[u8]) -> Result<Transform> {
let mut matrix = initial.unwrap_or_default();
if let Some([a, d, tx, ty]) = fixed_floats(payload, [0x0d, 0x25, 0x2d, 0x35]) {
return Ok(Transform {
a,
d,
tx,
ty,
..matrix
});
}
if let Some([a, b, c, d, tx, ty]) = fixed_floats(payload, [0x0d, 0x15, 0x1d, 0x25, 0x2d, 0x35])
{
return Ok(Transform { a, b, c, d, tx, ty });
}
for field in wire::values(payload) {
let field = field?;
match field.number {
1 => matrix.a = field.f32()?,
2 => matrix.b = field.f32()?,
3 => matrix.c = field.f32()?,
4 => matrix.d = field.f32()?,
5 => matrix.tx = field.f32()?,
6 => matrix.ty = field.f32()?,
_ => {}
}
}
Ok(matrix)
}
fn audio(payload: &[u8], budget: &Budget) -> Result<Audio> {
budget.spend()?;
fold(payload, Audio::default(), |audio, field| {
Ok(match field.number {
1 => Audio {
audio_key: field.str()?.to_owned(),
..audio
},
2 => Audio {
start_frame: field.i32()?,
..audio
},
3 => Audio {
end_frame: field.i32()?,
..audio
},
4 => Audio {
start_time: field.i32()?,
..audio
},
5 => Audio {
total_time: field.i32()?,
..audio
},
_ => audio,
})
})
}
fn fixed_floats<const N: usize>(bytes: &[u8], tags: [u8; N]) -> Option<[f32; N]> {
if bytes.len() != N * 5 {
return None;
}
let mut values = [0.0; N];
for ((chunk, expected), value) in bytes.as_chunks::<5>().0.iter().zip(tags).zip(&mut values) {
if chunk[0] != expected {
return None;
}
*value = f32::from_le_bytes([chunk[1], chunk[2], chunk[3], chunk[4]]);
}
Some(values)
}
#[cfg(test)]
mod fast_field_tests {
use super::*;
#[test]
fn exact_float_records_preserve_bits_and_previous_components() {
let initial = Layout {
x: 3.0,
y: 4.0,
width: 5.0,
height: 6.0,
};
let matrix = Transform {
a: 1.0,
b: 2.0,
c: 3.0,
d: 4.0,
tx: 5.0,
ty: 6.0,
};
for bits in [
0,
0x8000_0000,
1,
0x7f80_0000,
0xff80_0000,
0x7fc0_1234,
0x7f80_0001,
] {
let value = f32::from_bits(bits);
let payload = [wire::float(3, value), wire::float(4, value)].concat();
let decoded = layout(initial, &payload).unwrap();
assert_eq!((decoded.x, decoded.y), (initial.x, initial.y));
assert_eq!(
(decoded.width.to_bits(), decoded.height.to_bits()),
(bits, bits)
);
let payload = [1, 4, 5, 6]
.into_iter()
.flat_map(|n| wire::float(n, value))
.collect::<Vec<_>>();
let decoded = transform(Some(matrix), &payload).unwrap();
assert_eq!((decoded.b, decoded.c), (matrix.b, matrix.c));
for v in [decoded.a, decoded.d, decoded.tx, decoded.ty] {
assert_eq!(v.to_bits(), bits);
}
let payload = (1..=6)
.flat_map(|n| wire::float(n, value))
.collect::<Vec<_>>();
let decoded = transform(None, &payload).unwrap();
for v in [
decoded.a, decoded.b, decoded.c, decoded.d, decoded.tx, decoded.ty,
] {
assert_eq!(v.to_bits(), bits);
}
}
}
#[test]
fn uncommon_and_malformed_records_keep_general_wire_behavior() {
let payload = [
wire::float(4, 2.0),
wire::float(3, 1.0),
wire::float(3, 3.0),
wire::float(7, 9.0),
]
.concat();
let decoded = layout(Layout::default(), &payload).unwrap();
assert_eq!((decoded.width, decoded.height), (3.0, 2.0));
let payload = [
wire::float(6, 2.0),
wire::float(1, 1.0),
wire::float(1, 3.0),
wire::float(7, 9.0),
]
.concat();
let decoded = transform(None, &payload).unwrap();
assert_eq!((decoded.a, decoded.ty), (3.0, 2.0));
let wrong = [wire::int32(3, 1), wire::float(4, 2.0)].concat();
assert_eq!(
layout(Layout::default(), &wrong).unwrap_err().code(),
"svga_unexpected_wire_type"
);
let valid = [wire::float(3, 1.0), wire::float(4, 2.0)].concat();
assert_eq!(
layout(Layout::default(), &valid[..valid.len() - 1])
.unwrap_err()
.code(),
"svga_truncated_field"
);
}
}