use std::{borrow::Cow, sync::Arc};
use crate::{
container_api,
container_api::{
BoxFuture, ContainerHandler, Existing, FormatSpec, Io, ItemInfo, MetadataSlot,
MetadataUpdate, PlanBuilder, StructureBuilder, WritePlan,
},
Error, ItemKind, Name, Result, Role, Segment, SegmentId, SegmentKind, Structure, Updates,
};
const RIFF: [u8; 4] = *b"RIFF";
const LIST: [u8; 4] = *b"LIST";
const MOVI: [u8; 4] = *b"movi";
const C2PA: [u8; 4] = *b"C2PA";
const XMP: [u8; 4] = *b"XMP ";
const EXIF: [u8; 4] = *b"EXIF";
const DATA: [u8; 4] = *b"data";
const VP8X: [u8; 4] = *b"VP8X";
const VP8: [u8; 4] = *b"VP8 ";
const VP8L: [u8; 4] = *b"VP8L";
const ALPH: [u8; 4] = *b"ALPH";
const ANMF: [u8; 4] = *b"ANMF";
const FORM_WEBP: [u8; 4] = *b"WEBP";
const FORM_WAVE: [u8; 4] = *b"WAVE";
const FORM_AVI: [u8; 4] = *b"AVI ";
const VP8X_XMP_FLAG: u32 = 4;
const VP8X_LEN: u64 = 10;
fn media_type_of(form: &[u8]) -> Option<&'static str> {
match <[u8; 4]>::try_from(form).ok()? {
FORM_WEBP => Some("image/webp"),
FORM_WAVE => Some("audio/wav"),
FORM_AVI => Some("video/avi"),
_ => None,
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct RiffHandler;
pub fn handler() -> Arc<dyn ContainerHandler> {
Arc::new(RiffHandler)
}
pub const ID: &str = "riff";
#[derive(Debug, Default)]
struct ChunkTypes(Vec<Option<[u8; 4]>>);
impl ChunkTypes {
fn set(&mut self, id: SegmentId, ty: [u8; 4]) {
if self.0.len() <= id.index() {
self.0.resize(id.index() + 1, None);
}
self.0[id.index()] = Some(ty);
}
fn get(&self, id: SegmentId) -> Option<[u8; 4]> {
self.0.get(id.index()).copied().flatten()
}
}
impl ContainerHandler for RiffHandler {
fn box_name(
&self,
structure: &Structure,
segment: SegmentId,
element: &Segment,
) -> Option<Cow<'static, str>> {
let ty = container_api::attachment::<ChunkTypes>(structure).and_then(|t| t.get(segment));
match ty.map_or(element.name(), Name::FourCC) {
Name::None => None,
Name::FourCC(cc) => Some(Cow::Owned(String::from_utf8_lossy(&cc).into_owned())),
Name::Id(n) => Some(Cow::Owned(n.to_string())),
name @ Name::Marker(_) => Some(Cow::Owned(name.to_string())),
}
}
fn c2pa_data_hash_exclusions(
&self,
structure: &Structure,
item: &crate::Item,
) -> Result<Vec<crate::ByteRange>> {
item.extents()
.map(|extent| {
let segment = structure.segment(extent.segment())?;
segment
.range()
.sub(0, segment.range().len() - segment.trailer().len())
})
.collect()
}
fn id(&self) -> &'static str {
ID
}
fn formats(&self) -> &[FormatSpec] {
const F: &[FormatSpec] = &[
FormatSpec::new("image/webp", "webp").media_type_aliases(&["image/x-webp"]),
FormatSpec::new("audio/wav", "wav").media_type_aliases(&[
"audio/wave",
"audio/x-wav",
"audio/vnd.wave",
]),
FormatSpec::new("video/avi", "avi").media_type_aliases(&[
"application/x-troff-msvideo",
"video/msvideo",
"video/x-msvideo",
]),
];
F
}
fn detect(&self, header: &[u8]) -> bool {
header.len() >= 12 && header.starts_with(&RIFF) && media_type_of(&header[8..12]).is_some()
}
fn parse_async(self: Arc<Self>, io: Io) -> BoxFuture<'static, Result<Structure>> {
Box::pin(parse_with(self, io))
}
fn write_plan_async<'f, 'a: 'f>(
&'f self,
src_structure: &'f Structure,
mut io: Io,
updates: &'a Updates,
) -> BoxFuture<'f, Result<WritePlan<'a>>> {
Box::pin(async move { plan(src_structure, &mut io, updates).await })
}
}
#[cfg(test)]
fn parse<R: std::io::Read + std::io::Seek>(src: &mut R) -> Result<Structure> {
handler().parse(src)
}
fn le32(b: &[u8]) -> u32 {
u32::from_le_bytes([b[0], b[1], b[2], b[3]])
}
async fn parse_with(handler: Arc<dyn ContainerHandler>, mut io: Io) -> Result<Structure> {
let total = io.len();
if total < 12 {
return Err(Error::InvalidFormat("RIFF too small".into()));
}
let mut head = [0u8; 12];
io.read_at(0, &mut head).await?;
if head[..4] != RIFF {
return Err(Error::InvalidFormat("Not a RIFF file".into()));
}
let media = media_type_of(&head[8..12]).ok_or(Error::UnsupportedFormat)?;
let webp = head[8..12] == FORM_WEBP;
let mut b = StructureBuilder::new(handler, media, total);
let mut types = ChunkTypes::default();
let mut at = 0u64;
let mut first = true;
while at < total {
let remaining = total - at;
if remaining < 8 {
b.push_tail()?;
break;
}
let mut h = [0u8; 8];
io.read_at(at, &mut h).await?;
let id = [h[0], h[1], h[2], h[3]];
let size = le32(&h[4..8]) as u64;
if id == RIFF {
if remaining < 12 {
return Err(Error::invalid_segment(at, "RIFF chunk has no form type"));
}
let end = at + 8 + size;
if size < 4 {
return Err(Error::invalid_segment(
at,
"RIFF chunk too small for its form type",
));
}
if end > total {
return Err(Error::invalid_segment(
at,
"RIFF chunk declared size exceeds file size",
));
}
let id = b.push_span(SegmentKind::Preamble, Name::FourCC(RIFF), 12, 0, 0)?;
let mut form = [0u8; 4];
io.read_at(at + 8, &mut form).await?;
types.set(id, form);
parse_children(&mut b, &mut io, &mut types, at + 12, end, first, webp).await?;
at = end;
first = false;
} else {
let next = parse_chunk(&mut b, &mut io, &mut types, at, total, false, false).await?;
at = next;
}
}
b.attach(types);
b.finish()
}
async fn parse_children(
b: &mut StructureBuilder,
io: &mut Io,
types: &mut ChunkTypes,
start: u64,
end: u64,
first: bool,
webp: bool,
) -> Result<()> {
let mut at = start;
while at < end {
at = parse_chunk(b, io, types, at, end, first, webp).await?;
}
Ok(())
}
async fn parse_chunk(
b: &mut StructureBuilder,
io: &mut Io,
types: &mut ChunkTypes,
at: u64,
end: u64,
classify: bool,
webp: bool,
) -> Result<u64> {
if end - at < 8 {
return Err(Error::invalid_segment(at, "truncated chunk header"));
}
let mut h = [0u8; 8];
io.read_at(at, &mut h).await?;
let id = [h[0], h[1], h[2], h[3]];
let size = le32(&h[4..8]) as u64;
let data_end = at + 8 + size;
if data_end > end {
return Err(Error::invalid_segment(
at,
"chunk extends past the end of its container",
));
}
let pad = u16::from(size & 1 == 1 && data_end < end);
let item = match id {
C2PA if classify => Some(ItemKind::C2pa),
XMP if classify => Some(ItemKind::Xmp),
EXIF if classify && webp => Some(ItemKind::Exif),
_ => None,
};
if let Some(kind) = item {
let info = item_info(kind);
b.push_item(SegmentKind::Metadata, Name::FourCC(id), 8, size, pad, info)?;
return Ok(data_end + pad as u64);
}
let list_type = if id == LIST && size >= 4 {
let mut t = [0u8; 4];
io.read_at(at + 8, &mut t).await?;
Some(t)
} else {
None
};
let kind = match id {
_ if !classify => SegmentKind::Other,
DATA | VP8 | VP8L | ALPH | ANMF => SegmentKind::MediaData,
LIST if list_type == Some(MOVI) => SegmentKind::MediaData,
_ => SegmentKind::Other,
};
let segment = b.push_span(kind, Name::FourCC(id), 8, size, pad)?;
if let Some(t) = list_type {
types.set(segment, t);
}
Ok(data_end + pad as u64)
}
fn item_info(kind: ItemKind) -> ItemInfo {
match kind {
ItemKind::Xmp => ItemInfo::xmp(),
ItemKind::C2pa => ItemInfo::c2pa(),
_ => ItemInfo::exif(),
}
}
enum Op<'a> {
Copy(SegmentId),
Flags { id: SegmentId, flags: u32 },
Chunk {
item: Option<ItemKind>,
id: [u8; 4],
payload: Cow<'a, [u8]>,
},
}
fn new_chunk(item: Option<ItemKind>, id: [u8; 4], payload: Cow<'_, [u8]>) -> Result<Op<'_>> {
if payload.len() as u64 > u32::MAX as u64 {
return Err(Error::LimitExceeded {
what: "RIFF chunk size",
limit: u32::MAX as u64,
});
}
Ok(Op::Chunk { item, id, payload })
}
async fn webp_size(io: &mut Io, segs: &[Segment]) -> Result<(u32, u32)> {
let find = |id: [u8; 4]| segs.iter().find(|s| s.name() == Name::FourCC(id));
if let Some(s) = find(VP8L) {
let mut d = [0u8; 5];
if s.payload().len() < d.len() as u64 {
return Err(Error::invalid_segment(
s.range().offset(),
"VP8L chunk too small",
));
}
io.read_at(s.payload().offset(), &mut d).await?;
let first = u16::from_le_bytes([d[1], d[2]]) as u32;
let second = u16::from_le_bytes([d[3], d[4]]) as u32;
let width = 1 + (first & 0x3fff);
let height = 1 + (((second & 0xfff) << 2) | ((first & 0xc000) >> 14));
return Ok((width, height));
}
if let Some(s) = find(VP8) {
let mut d = [0u8; 10];
if s.payload().len() < d.len() as u64 {
return Err(Error::invalid_segment(
s.range().offset(),
"VP8 chunk too small",
));
}
io.read_at(s.payload().offset(), &mut d).await?;
let width = (u16::from_le_bytes([d[6], d[7]]) & 0x3fff) as u32;
let height = (u16::from_le_bytes([d[8], d[9]]) & 0x3fff) as u32;
return Ok((width, height));
}
Err(Error::InvalidFormat(
"WebP has no VP8 or VP8L chunk to take its size from".into(),
))
}
fn new_vp8x<'a>(width: u32, height: u32, flags: u32) -> Result<Op<'a>> {
let (w, h) = match (width.checked_sub(1), height.checked_sub(1)) {
(Some(w), Some(h)) if w < 1 << 24 && h < 1 << 24 => (w, h),
_ => return Err(Error::InvalidFormat("WebP size does not fit VP8X".into())),
};
let mut d = Vec::with_capacity(VP8X_LEN as usize);
d.extend_from_slice(&flags.to_le_bytes());
d.extend_from_slice(&w.to_le_bytes()[..3]);
d.extend_from_slice(&h.to_le_bytes()[..3]);
new_chunk(None, VP8X, Cow::Owned(d))
}
fn lacks_pad(op: &Op<'_>, src: &Structure) -> Result<bool> {
Ok(match op {
Op::Copy(id) | Op::Flags { id, .. } => {
let s = src.segment(*id)?;
s.payload().len() & 1 == 1 && s.trailer().is_empty()
}
_ => false,
})
}
async fn plan<'a>(src: &Structure, io: &mut Io, updates: &'a Updates) -> Result<WritePlan<'a>> {
let segs = src.segments();
let mut head = [0u8; 12];
io.read_at(0, &mut head).await?;
let riff_end = 8 + le32(&head[4..8]) as u64;
let form = [head[8], head[9], head[10], head[11]];
let kids_end = segs
.iter()
.position(|s| s.range().offset() >= riff_end)
.unwrap_or(segs.len());
let webp = src.media_type() == "image/webp";
let mut ops: Vec<Op<'a>> = Vec::with_capacity(segs.len() + 3);
let mut xmp = MetadataSlot::new(updates.xmp());
let mut jumbf = MetadataSlot::new(updates.c2pa());
let mut saw_vp8x = false;
for (i, seg) in segs.iter().enumerate().take(kids_end).skip(1) {
let id = SegmentId::from_index(i)?;
match src.items_in(id).next().map(|e| e.kind()) {
Some(ItemKind::Xmp) => match xmp.existing() {
Existing::Keep => ops.push(Op::Copy(id)),
Existing::Replace(d) => {
ops.push(new_chunk(Some(ItemKind::Xmp), XMP, Cow::Borrowed(d))?)
}
_ => {}
},
Some(ItemKind::C2pa) => match jumbf.existing() {
Existing::Keep => ops.push(Op::Copy(id)),
Existing::Replace(d) => {
ops.push(new_chunk(Some(ItemKind::C2pa), C2PA, Cow::Borrowed(d))?)
}
_ => {}
},
_ if webp && seg.name() == Name::FourCC(VP8X) => {
saw_vp8x = true;
let want = match updates.xmp() {
MetadataUpdate::Keep => None,
MetadataUpdate::Set(_) => Some(true),
MetadataUpdate::Remove => Some(false),
};
let mut op = Op::Copy(id);
if let Some(want) = want {
if seg.payload().len() < 4 {
return Err(Error::invalid_segment(
seg.range().offset(),
"VP8X chunk too small",
));
}
let mut f = [0u8; 4];
io.read_at(seg.payload().offset(), &mut f).await?;
let flags = u32::from_le_bytes(f);
let new = if want {
flags | VP8X_XMP_FLAG
} else {
flags & !VP8X_XMP_FLAG
};
if new != flags {
op = Op::Flags { id, flags: new };
}
}
ops.push(op);
}
_ => ops.push(Op::Copy(id)),
}
}
let mut tail: Vec<Op<'a>> = Vec::new();
if let Some(d) = xmp.pending() {
tail.push(new_chunk(Some(ItemKind::Xmp), XMP, Cow::Borrowed(d))?);
}
if let Some(d) = jumbf.pending() {
tail.push(new_chunk(Some(ItemKind::C2pa), C2PA, Cow::Borrowed(d))?);
}
if webp && matches!(updates.xmp(), MetadataUpdate::Set(_)) && !saw_vp8x {
let (w, h) = webp_size(io, &segs[1..kids_end]).await?;
ops.insert(0, new_vp8x(w, h, VP8X_XMP_FLAG)?);
}
let mut unpadded = None;
if !tail.is_empty() {
if let Some(last) = ops.last() {
if lacks_pad(last, src)? {
unpadded = Some(ops.len() - 1);
}
}
ops.extend(tail);
}
let mut b = PlanBuilder::new(src);
let source_types = container_api::attachment::<ChunkTypes>(src);
let mut types = ChunkTypes::default();
let riff = b.put_segment(
SegmentKind::Preamble,
Name::FourCC(RIFF),
riff_header(0, form),
&[][..],
&[][..],
)?;
types.set(riff, form);
for (i, op) in ops.iter().enumerate() {
let id = emit(&mut b, op, unpadded == Some(i))?;
if let Op::Copy(sid) | Op::Flags { id: sid, .. } = op {
if let Some(t) = source_types.and_then(|t| t.get(*sid)) {
types.set(id, t);
}
}
let info = match op {
Op::Chunk { item, .. } => item.map(item_info),
Op::Copy(sid) | Op::Flags { id: sid, .. } => src
.items_in(*sid)
.next()
.map(|e| container_api::item_info(e).clone()),
};
if let Some(info) = info {
b.item(info, &[id])?;
}
}
let size = u32::try_from(b.len() - 8).map_err(|_| Error::LimitExceeded {
what: "RIFF chunk size",
limit: u32::MAX as u64,
})?;
for i in kids_end..segs.len() {
let sid = SegmentId::from_index(i)?;
let id = b.copy_segment(sid)?;
if let Some(t) = source_types.and_then(|t| t.get(sid)) {
types.set(id, t);
}
}
b.attach(types);
let mut plan = b.finish()?;
plan.replace(riff, Role::Header, riff_header(size, form))?;
Ok(plan)
}
fn riff_header(size: u32, form: [u8; 4]) -> Vec<u8> {
let mut h = Vec::with_capacity(12);
h.extend_from_slice(&RIFF);
h.extend_from_slice(&size.to_le_bytes());
h.extend_from_slice(&form);
h
}
fn emit<'a>(b: &mut PlanBuilder<'_, 'a>, op: &Op<'a>, pad: bool) -> Result<SegmentId> {
let src = b.source();
match op {
Op::Copy(sid) if !pad => b.copy_segment(*sid),
Op::Copy(sid) | Op::Flags { id: sid, .. } => {
let s = src.segment(*sid)?;
let id = b.shape(
s.kind(),
s.name(),
s.header().len() as u32,
s.payload().len(),
s.trailer().len() as u16 + pad as u16,
)?;
b.copy(id, Role::Header, s.header());
match op {
Op::Flags { flags, .. } => {
b.put(id, Role::Payload, flags.to_le_bytes().to_vec());
b.copy(
id,
Role::Payload,
s.payload().sub(4, s.payload().len() - 4)?,
);
}
_ => {
b.copy(id, Role::Payload, s.payload());
}
}
b.copy(id, Role::Trailer, s.trailer());
if pad {
b.put(id, Role::Trailer, vec![0]);
}
Ok(id)
}
Op::Chunk { item, id, payload } => {
let mut h = Vec::with_capacity(8);
h.extend_from_slice(id);
h.extend_from_slice(&(payload.len() as u32).to_le_bytes()); let trailer: &[u8] = if payload.len() & 1 == 1 { &[0] } else { &[] };
let kind = match item {
Some(_) => SegmentKind::Metadata,
None => SegmentKind::Other,
};
b.put_segment(kind, Name::FourCC(*id), h, payload.clone(), trailer)
}
}
}
#[cfg(test)]
mod tests {
use std::io::Cursor;
use super::*;
use crate::{testing::Conformance, NullSink};
fn chunk(id: &[u8; 4], data: &[u8]) -> Vec<u8> {
let mut v = id.to_vec();
v.extend_from_slice(&(data.len() as u32).to_le_bytes());
v.extend_from_slice(data);
if data.len() % 2 == 1 {
v.push(0);
}
v
}
fn riff(form: &[u8; 4], kids: &[Vec<u8>]) -> Vec<u8> {
let body: Vec<u8> = kids.concat();
let mut v = b"RIFF".to_vec();
v.extend_from_slice(&((body.len() + 4) as u32).to_le_bytes());
v.extend_from_slice(form);
v.extend_from_slice(&body);
v
}
fn wav(extra: &[Vec<u8>]) -> Vec<u8> {
let mut kids = vec![chunk(b"fmt ", &[1; 16]), chunk(b"data", b"abcde")];
kids.extend_from_slice(extra);
riff(b"WAVE", &kids)
}
#[test]
fn inspection_and_walk_use_box_hash_names() {
let bytes = riff(
b"WAVE",
&[
chunk(
b"LIST",
&[b"INFO".as_slice(), &chunk(b"INAM", b"abc")].concat(),
),
chunk(b"data", &[1, 2, 3]),
],
);
let s = parse(&mut Cursor::new(&bytes)).unwrap();
let mut elements = Vec::new();
s.elements(|id, element| {
elements.push((
s.box_name(id, element).unwrap().into_owned(),
element.range(),
));
Ok(())
})
.unwrap();
assert_eq!(
elements
.iter()
.map(|(name, _)| name.as_str())
.collect::<Vec<_>>(),
["WAVE", "INFO", "data"]
);
let boxes = s.c2pa_boxes().unwrap();
assert_eq!(
elements,
boxes
.into_iter()
.map(|b| (b.name.unwrap().into_owned(), b.range))
.collect::<Vec<_>>()
);
let mut paths = Vec::new();
s.walk(&mut Cursor::new(&bytes), |node| {
paths.push(node.path.to_owned());
Ok(())
})
.unwrap();
assert_eq!(paths, ["/WAVE", "/INFO", "/data"]);
}
fn rewrite(src: &[u8], u: &Updates) -> Result<Vec<u8>> {
let (out, _) = crate::testing::rewrite(handler(), src, u)?;
assert_eq!(le32(&out[4..8]) as usize, out.len() - 8);
Ok(out)
}
fn payload(bytes: &[u8], kind: ItemKind) -> Option<Vec<u8>> {
let s = parse(&mut Cursor::new(bytes)).unwrap();
let found = s
.items_of(kind)
.next()
.map(|e| s.read_item(&mut Cursor::new(bytes), e).unwrap());
found
}
fn vp8x_flags(bytes: &[u8]) -> Option<u32> {
let s = parse(&mut Cursor::new(bytes)).unwrap();
let seg = s
.segments()
.iter()
.find(|g| g.name() == Name::FourCC(VP8X))?;
let at = seg.payload().offset() as usize;
Some(le32(&bytes[at..at + 4]))
}
#[test]
fn media_types_follow_the_form_type() {
for (form, mt) in [
(b"WEBP", "image/webp"),
(b"WAVE", "audio/wav"),
(b"AVI ", "video/avi"),
] {
let f = riff(form, &[chunk(b"junk", b"x")]);
let s = parse(&mut Cursor::new(&f)).unwrap();
assert_eq!(s.media_type(), mt);
assert!(RiffHandler.detect(&f));
}
let other = riff(b"ACON", &[]);
assert!(!RiffHandler.detect(&other));
assert!(matches!(
parse(&mut Cursor::new(&other)),
Err(Error::UnsupportedFormat)
));
}
#[test]
fn tiles_and_finds_items() {
let f = wav(&[chunk(b"XMP ", b"<x/>"), chunk(b"C2PA", b"STORE")]);
let s = parse(&mut Cursor::new(&f)).unwrap();
let covered: u64 = s.regions().map(|r| r.range.len()).sum();
assert_eq!(covered, f.len() as u64);
assert_eq!(s.segments().len(), 5);
assert_eq!(s.segments()[0].header().len(), 12);
assert_eq!(s.segments()[2].payload().len(), 5);
assert_eq!(s.segments()[2].trailer().len(), 1);
assert_eq!(s.segments()[2].kind(), SegmentKind::MediaData);
assert_eq!(payload(&f, ItemKind::C2pa).unwrap(), b"STORE");
assert_eq!(payload(&f, ItemKind::Xmp).unwrap(), b"<x/>");
}
#[test]
fn exif_is_an_item_in_webp_only() {
let exif = chunk(b"EXIF", b"II*\0\x08\0\0\0");
let webp = riff(
b"WEBP",
&[chunk(b"VP8L", &[0x2f, 0, 0, 0, 0, 0]), exif.clone()],
);
let s = parse(&mut Cursor::new(&webp)).unwrap();
assert_eq!(payload(&webp, ItemKind::Exif).unwrap(), b"II*\0\x08\0\0\0");
assert_eq!(rewrite(&webp, &Updates::new()).unwrap(), webp);
assert_eq!(s.items_of(ItemKind::Exif).count(), 1);
let wav = wav(&[exif]);
assert!(payload(&wav, ItemKind::Exif).is_none());
}
#[test]
fn conforms() {
let c = Conformance::new(handler()).c2pa(Some(crate::testing::c2pa_store_of_len(64)));
c.check(
"wav",
&wav(&[chunk(b"XMP ", b"<x/>"), chunk(b"C2PA", b"STORE")]),
);
let mut unpadded = wav(&[chunk(b"junk", b"abc")]);
unpadded.pop();
let n = unpadded.len() as u32 - 8;
unpadded[4..8].copy_from_slice(&n.to_le_bytes());
c.check("unpadded", &unpadded);
let lossless = chunk(b"VP8L", &[0x2f, 0, 0, 0, 0, 0]);
c.check("webp", &riff(b"WEBP", std::slice::from_ref(&lossless)));
let vp8x = chunk(b"VP8X", &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
c.check("webp with VP8X", &riff(b"WEBP", &[vp8x, lossless]));
let more = [
riff(b"AVI ", &[chunk(b"junk", b"x")]),
riff(b"AVIX", &[chunk(b"junk", b"y")]),
];
c.check("avi with AVIX", &more.concat());
}
#[test]
fn a_manifest_is_appended_replaced_and_removed() {
let f = wav(&[]);
let one = rewrite(&f, &Updates::new().set_c2pa(b"STORE".to_vec())).unwrap();
assert_eq!(payload(&one, ItemKind::C2pa).unwrap(), b"STORE");
let s = parse(&mut Cursor::new(&one)).unwrap();
assert_eq!(s.segments().last().unwrap().name(), Name::FourCC(C2PA));
let longer = rewrite(&one, &Updates::new().set_c2pa(vec![7u8; 100])).unwrap();
assert_eq!(payload(&longer, ItemKind::C2pa).unwrap(), vec![7u8; 100]);
let shorter = rewrite(&one, &Updates::new().set_c2pa(b"S".to_vec())).unwrap();
assert_eq!(payload(&shorter, ItemKind::C2pa).unwrap(), b"S");
assert_eq!(rewrite(&one, &Updates::new().remove_c2pa()).unwrap(), f);
}
#[test]
fn xmp_goes_before_the_manifest() {
let f = wav(&[]);
let u = Updates::new()
.set_c2pa(b"STORE".to_vec())
.set_xmp(b"<x/>".to_vec());
let out = rewrite(&f, &u).unwrap();
let s = parse(&mut Cursor::new(&out)).unwrap();
let names: Vec<_> = s.segments().iter().map(|g| g.name()).collect();
assert_eq!(
&names[names.len() - 2..],
&[Name::FourCC(XMP), Name::FourCC(C2PA)]
);
assert_eq!(payload(&out, ItemKind::Xmp).unwrap(), b"<x/>");
assert_eq!(rewrite(&out, &Updates::remove_all()).unwrap(), f);
}
#[test]
fn a_missing_final_pad_is_supplied_before_appending() {
let mut f = wav(&[chunk(b"junk", b"abc")]);
f.pop();
let n = f.len() as u32 - 8;
f[4..8].copy_from_slice(&n.to_le_bytes());
let s = parse(&mut Cursor::new(&f)).unwrap();
assert_eq!(s.segments().last().unwrap().trailer().len(), 0);
assert_eq!(rewrite(&f, &Updates::new()).unwrap(), f);
let out = rewrite(&f, &Updates::new().set_c2pa(b"STORE".to_vec())).unwrap();
assert_eq!(payload(&out, ItemKind::C2pa).unwrap(), b"STORE");
let s = parse(&mut Cursor::new(&out)).unwrap();
assert!(s.segments().iter().all(|g| g.range().offset() % 2 == 0));
}
#[test]
fn the_plan_tiles_its_structure_and_borrows_the_new_metadata() {
let mut f = wav(&[chunk(b"junk", b"abc")]);
f.pop();
let n = f.len() as u32 - 8;
f[4..8].copy_from_slice(&n.to_le_bytes());
let s = parse(&mut Cursor::new(&f)).unwrap();
let u = Updates::new().set_xmp(b"<x/>".to_vec());
let plan = s.write_plan(&mut Cursor::new(&f), &u).unwrap();
crate::plan::validate(&plan, f.len() as u64).unwrap();
assert!(plan.steps().iter().any(|st| matches!(
st,
container_api::Step::Put { data: Cow::Borrowed(d), .. } if *d == b"<x/>"
)));
}
#[test]
fn webp_xmp_maintains_the_vp8x_flag() {
let vp8l = chunk(b"VP8L", &[0x2f, 0x02, 0x40, 0, 0, 0]);
let bare = riff(b"WEBP", std::slice::from_ref(&vp8l));
let out = rewrite(&bare, &Updates::new().set_xmp(b"<x/>".to_vec())).unwrap();
let s = parse(&mut Cursor::new(&out)).unwrap();
assert_eq!(s.segments()[1].name(), Name::FourCC(VP8X));
assert_eq!(vp8x_flags(&out), Some(VP8X_XMP_FLAG));
let at = s.segments()[1].payload().offset() as usize;
assert_eq!(&out[at + 4..at + 7], &[2, 0, 0]); assert_eq!(&out[at + 7..at + 10], &[1, 0, 0]);
let back = rewrite(&out, &Updates::new().remove_xmp()).unwrap();
assert_eq!(vp8x_flags(&back), Some(0));
assert!(payload(&back, ItemKind::Xmp).is_none());
let mut d = vec![0u8; 10];
d[0] = 0x10; let with = riff(b"WEBP", &[chunk(b"VP8X", &d), vp8l]);
let out = rewrite(&with, &Updates::new().set_xmp(b"<x/>".to_vec())).unwrap();
assert_eq!(vp8x_flags(&out), Some(0x14));
let out = rewrite(&with, &Updates::new().set_c2pa(b"S".to_vec())).unwrap();
assert_eq!(vp8x_flags(&out), Some(0x10));
}
#[test]
fn webp_size_from_a_lossy_chunk_and_the_missing_case() {
let mut d = vec![0u8; 10];
d[6..8].copy_from_slice(&640u16.to_le_bytes());
d[8..10].copy_from_slice(&480u16.to_le_bytes());
let f = riff(b"WEBP", &[chunk(b"VP8 ", &d)]);
let out = rewrite(&f, &Updates::new().set_xmp(b"<x/>".to_vec())).unwrap();
let s = parse(&mut Cursor::new(&out)).unwrap();
let at = s.segments()[1].payload().offset() as usize;
assert_eq!(&out[at + 4..at + 7], &639u32.to_le_bytes()[..3]);
assert_eq!(&out[at + 7..at + 10], &479u32.to_le_bytes()[..3]);
let none = riff(b"WEBP", &[chunk(b"ICCP", b"x")]);
assert!(rewrite(&none, &Updates::new().set_xmp(b"<x/>".to_vec())).is_err());
assert!(rewrite(&none, &Updates::new().set_c2pa(b"S".to_vec())).is_ok());
}
#[test]
fn avix_chunks_hold_no_items_and_keep_their_size() {
let avix = riff(
b"AVIX",
&[chunk(b"C2PA", b"NOT MINE"), chunk(b"junk", b"zz")],
);
let mut f = riff(b"AVI ", &[chunk(b"hdrl", b"abcd")]);
let first_len = f.len();
f.extend_from_slice(&avix);
let s = parse(&mut Cursor::new(&f)).unwrap();
assert!(s.items_of(ItemKind::C2pa).next().is_none());
let mut out = Cursor::new(Vec::new());
container_api::handler(&s)
.write(
&s,
&mut Cursor::new(&f),
&mut out,
&Updates::new().set_c2pa(b"STORE".to_vec()),
&mut NullSink,
)
.unwrap();
let out = out.into_inner();
let grown = 8 + 6; assert_eq!(le32(&out[4..8]) as usize, first_len - 8 + grown);
assert_eq!(&out[first_len + grown..], &avix[..]);
assert_eq!(payload(&out, ItemKind::C2pa).unwrap(), b"STORE");
}
#[test]
fn only_the_first_riff_size_changes_with_avix() {
let avix = riff(b"AVIX", &[chunk(b"junk", b"zz")]);
let mut f = riff(b"AVI ", &[chunk(b"hdrl", b"abcd")]);
let first_len = f.len();
f.extend_from_slice(&avix);
let s = parse(&mut Cursor::new(&f)).unwrap();
let mut out = Cursor::new(Vec::new());
container_api::handler(&s)
.write(
&s,
&mut Cursor::new(&f),
&mut out,
&Updates::new().set_c2pa(b"STORE".to_vec()),
&mut NullSink,
)
.unwrap();
let out = out.into_inner();
let grown = 8 + 6; assert_eq!(le32(&out[4..8]) as usize, first_len - 8 + grown);
assert_eq!(&out[first_len + grown..], &avix[..]);
assert_eq!(payload(&out, ItemKind::C2pa).unwrap(), b"STORE");
}
#[test]
fn hostile_input_is_an_error() {
let mut f = wav(&[]);
let at = f.len() - 14; f[at + 4..at + 8].copy_from_slice(&u32::MAX.to_le_bytes());
assert!(parse(&mut Cursor::new(&f)).is_err());
let mut f = wav(&[]);
f[4..8].copy_from_slice(&u32::MAX.to_le_bytes());
assert!(parse(&mut Cursor::new(&f)).is_err());
let mut f = wav(&[]);
f[4..8].copy_from_slice(&2u32.to_le_bytes());
assert!(parse(&mut Cursor::new(&f)).is_err());
let mut f = riff(b"WAVE", &[]);
f.extend_from_slice(&[1, 2, 3]);
let n = f.len() as u32 - 8;
f[4..8].copy_from_slice(&n.to_le_bytes());
assert!(parse(&mut Cursor::new(&f)).is_err());
assert!(parse(&mut Cursor::new(b"RIFF")).is_err());
assert!(parse(&mut Cursor::new(b"RIFX\0\0\0\0WAVE")).is_err());
}
}