#![doc = include_str!("README.md")]
use std::sync::Arc;
use crate::{
container_api::{
BoxFuture, ContainerHandler, FormatSpec, Io, ItemInfo, MetadataUpdate, PlanBuilder,
StructureBuilder, WritePlan,
},
jumbf::{superbox_type, C2PA_STORE_TYPE},
Error, Item, ItemKind, Name, Result, SegmentId, SegmentKind, Structure, Updates,
};
pub const ID: &str = "c2pa";
#[derive(Debug)]
pub struct C2paHandler;
pub fn handler() -> Arc<dyn ContainerHandler> {
Arc::new(C2paHandler)
}
impl ContainerHandler for C2paHandler {
fn c2pa_data_hash_exclusions(
&self,
_structure: &Structure,
_item: &Item,
) -> Result<Vec<crate::ByteRange>> {
Err(Error::UnsupportedFeature(
"C2PA data-hash exclusions for a sidecar",
))
}
fn id(&self) -> &'static str {
ID
}
fn formats(&self) -> &[FormatSpec] {
const FORMATS: &[FormatSpec] = &[FormatSpec::new("application/c2pa", "c2pa")
.media_type_aliases(&["application/x-c2pa-manifest-store"])];
FORMATS
}
fn detect(&self, header: &[u8]) -> bool {
superbox_type(header) == Some(C2PA_STORE_TYPE)
}
fn parse_async(self: Arc<Self>, io: Io) -> BoxFuture<'static, Result<Structure>> {
Box::pin(async move {
let total = io.len();
let mut builder = StructureBuilder::new(self, "application/c2pa", total);
if total != 0 {
builder.push_item(
SegmentKind::Metadata,
Name::None,
0,
total,
0,
ItemInfo::c2pa(),
)?;
}
builder.finish()
})
}
fn write_plan_async<'f, 'a: 'f>(
&'f self,
source: &'f Structure,
_io: Io,
updates: &'a Updates,
) -> BoxFuture<'f, Result<WritePlan<'a>>> {
Box::pin(async move { plan(source, updates) })
}
fn compose(&self, kind: ItemKind, data: &[u8]) -> Result<Vec<u8>> {
if kind != ItemKind::C2pa {
return Err(Error::UnsupportedFormat);
}
Ok(data.to_vec())
}
fn check_patch(&self, _structure: &Structure, item: &Item, len: usize) -> Result<()> {
if len as u64 != item.len() {
return Err(Error::InvalidFormat(
"C2PA sidecar in-place updates require exact-length payloads".into(),
));
}
Ok(())
}
}
fn plan<'a>(source: &Structure, updates: &'a Updates) -> Result<WritePlan<'a>> {
match updates.xmp() {
MetadataUpdate::Keep | MetadataUpdate::Remove => {}
_ => return Err(Error::UnsupportedItem(ItemKind::Xmp)),
}
let mut builder = PlanBuilder::new(source);
let keep = match updates.c2pa() {
MetadataUpdate::Keep => true,
MetadataUpdate::Remove => false,
MetadataUpdate::Set(data) => {
if !data.is_empty() {
let id = builder.put_segment(
SegmentKind::Metadata,
Name::None,
&[][..],
data.as_slice(),
&[][..],
)?;
builder.item(ItemInfo::c2pa(), &[id])?;
}
false
}
};
if keep {
for i in 0..source.segments().len() {
builder.copy_segment(SegmentId::from_index(i)?)?;
}
builder.carry_items(|_| true);
}
builder.finish()
}