media: expose MXF package identity and timing for FilmCraft component media (#3776)

Expose MXF package identity and material timing for component media. Keep readable descriptor fallback while withholding ambiguous identity, and preserve earlier project data through schema 21.
This commit is contained in:
Whatever Industries authored and GitHub committed 2026-11-29 23:00:06 -06:00
1 parent 5190e08ab8
commit aa7e668ec6
3 files changed
+503 -28

No files matched your search

+31 -2
View File
@@ -15,7 +15,7 @@ pub type Migration = fn(Value) -> Result<Value, String>;
/// edit a shipped one.
pub const MIGRATIONS: &[Migration] = &[
v1_to_v2, v2_to_v3, v3_to_v4, v4_to_v5, v5_to_v6, v6_to_v7, v7_to_v8, v8_to_v9, v9_to_v10, v10_to_v11, v11_to_v12, v12_to_v13, v13_to_v14,
v14_to_v15, v15_to_v16, v16_to_v17, v17_to_v18, v18_to_v19, v19_to_v20,
v14_to_v15, v15_to_v16, v16_to_v17, v17_to_v18, v18_to_v19, v19_to_v20, v20_to_v21,
];
/// The schema version this build writes (and the newest it reads).
@@ -275,6 +275,12 @@ fn v19_to_v20(doc: Value) -> Result<Value, String> {
Ok(doc)
}
/// v20 → v21: MXF audio and picture components may have independent identities and paths.
/// Earlier media references, Script items, RAW settings and mask colour ranges keep their representation.
fn v20_to_v21(doc: Value) -> Result<Value, String> {
Ok(doc)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -364,10 +370,33 @@ mod tests {
assert_eq!(version, 20);
assert_eq!(file.project["effects"][0]["masks"][0]["color"], range);
}
#[test]
fn saving_component_media_preserves_script_and_raw_data_from_v19() {
let project = json!({"items": {
"1": {"kind": {"Script": {"lines":[{"id":1,"text":"Scene one"}]}}},
"2": {"kind": {"Media": {"media":{"File":{"path":"original.mxf"}}, "interpret":{"raw":{"exposure":-0.75}}}}}
}});
let old = json!({"format":FORMAT_ID,"schema_version":19,"project":project,"view":{"active":1}});
let (mut file, _): (EnvelopeIn<Value>, _) = decode(&serde_json::to_vec(&old).unwrap()).unwrap();
assert_eq!(file.project, project);
let components = json!({"Components":{
"picture":{"track":1,"file_package":vec![1;32],"path":"picture.mxf","source_start":0,"length":100},
"channels":[{"track":2,"file_package":vec![2;32],"path":null,"stream":0,"channel":0,"source_start":0,"length":100}]
}});
file.project["items"]["2"]["kind"]["Media"]["media"] = components;
let saved = encode(&file.project, file.view.as_ref(), "FilmCraft test".into(), false);
let (reopened, version): (EnvelopeIn<Value>, _) = decode(&saved).unwrap();
assert!(version > 20);
assert_eq!(reopened.project, file.project);
assert_eq!(reopened.view, Some(old["view"].clone()));
}
#[test]
fn rejects_wrong_future_and_damaged_envelopes() {
assert!(matches!(detect_bytes(br#"{"format":"other","schema_version":1}"#), Err(FormatError::NotAProject(_))));
assert!(matches!(detect_bytes(br#"{"schema_version":21}"#), Err(FormatError::TooNew { found: 21, supported: 20 })));
let future = SCHEMA_VERSION + 1;
let bytes = serde_json::to_vec(&json!({"schema_version": future})).unwrap();
assert!(matches!(detect_bytes(&bytes), Err(FormatError::TooNew { found, supported: SCHEMA_VERSION }) if found == future));
assert!(matches!(detect_bytes(br#"{"schema_version":0}"#), Err(FormatError::TooOld { found: 0, oldest: 1 })));
assert!(matches!(detect_bytes(b"{"), Err(FormatError::Corrupt(_))));
assert!(matches!(migrate_with(MIGRATIONS, json!([]), 1), Err(FormatError::Migration { from: 1, .. })));
+191 -24
View File
@@ -152,6 +152,16 @@ pub enum TrackKind {
Data,
}
impl TrackKind {
fn matches_element(self, number: [u8; 4]) -> bool {
match self {
Self::Picture => matches!(number[0], 0x05 | 0x15),
Self::Sound => matches!(number[0], 0x06 | 0x16),
Self::Data => matches!(number[0], 0x07 | 0x17),
}
}
}
/// Frame wrapping (one element per edit unit) or clip wrapping (one element for the whole clip).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Wrapping {
@@ -187,12 +197,20 @@ pub struct Chunk {
/// package.
#[derive(Clone, Debug)]
pub struct EssenceTrack {
/// MXF File Package PackageID (ST 377-1, tag 0x4401), in stored byte order.
/// Available across MXF dialects. Missing, wrong-length and all-zero values
/// yield `None`; a readable track alone establishes no package identity.
pub file_package_uid: Option<[u8; 32]>,
pub track_id: u32,
pub track_number: u32,
pub kind: TrackKind,
pub name: Option<String>,
/// Edit rate of the file package track.
pub edit_rate: Rational,
/// Original material track clock, before conversion into file-package edit units.
pub material_edit_rate: Option<Rational>,
/// Original material source-clip duration, in `material_edit_rate` units.
pub material_duration: Option<i64>,
/// File package track origin (edit units of pre-charge before the zero point).
pub origin: i64,
/// Material package source clip start position (edit units after the origin).
@@ -370,6 +388,15 @@ impl<S: ByteSource + ?Sized> Window<'_, S> {
}
}
/// A private header packet may be skipped only within the declared metadata region,
/// with room for the standard key that the caller verifies at the returned offset.
fn opaque_header_end(pos: u64, header: &[u8], limit: Option<u64>, file_len: u64) -> Option<u64> {
let limit = limit?.min(file_len);
let (size, width) = ber_length(header.get(16..)?)?;
let end = pos.checked_add(16 + width as u64)?.checked_add(size)?;
(size <= MAX_META_VALUE && end.checked_add(16)? <= limit).then_some(end)
}
fn walk(src: &(impl ByteSource + ?Sized)) -> Result<WalkResult> {
walk_within(src, MAX_META_TOTAL)
}
@@ -383,6 +410,8 @@ pub(super) fn walk_within(src: &(impl ByteSource + ?Sized), mut meta_budget: u64
let mut win = Window { src, off: 0, buf: Vec::new(), refill: WINDOW_LARGE, small_left: 0 };
let mut pos = run_in;
let mut cur_meta: Option<usize> = None;
let mut metadata_end = None;
let mut reported_opaque = false;
let mut resync_budget = 64 << 20;
while pos + 17 <= len {
let mut hdr_buf = [0u8; 25];
@@ -392,6 +421,16 @@ pub(super) fn walk_within(src: &(impl ByteSource + ?Sized), mut meta_budget: u64
let hdr = &hdr_buf[..hdr_len];
let key = Ul(hdr[..16].try_into().unwrap_or([0; 16]));
if !key.is_smpte() {
if let Some(end) = opaque_header_end(pos, hdr, metadata_end.filter(|_| cur_meta.is_some()), len)
&& win.get(end, 16)?.starts_with(&[0x06, 0x0e, 0x2b, 0x34])
{
if !reported_opaque {
w.warnings.push(format!("skipped opaque non-SMPTE header packet at byte {pos}"));
reported_opaque = true;
}
pos = end;
continue;
}
// Lost sync (corrupt data): look for the next partition pack.
match resync(src, pos + 1, len, &mut resync_budget)? {
Some(p) => {
@@ -437,10 +476,14 @@ pub(super) fn walk_within(src: &(impl ByteSource + ?Sized), mut meta_budget: u64
None => w.warnings.push(format!("short partition pack at byte {pos}")),
}
cur_meta = None;
metadata_end = None;
}
KeyClass::Primer => {
let v = read_value()?;
if let Some(pi) = w.partitions.len().checked_sub(1) {
if cur_meta.is_none() && metadata_end.is_none() {
metadata_end = pos.checked_add(w.partitions[pi].header_byte_count);
}
w.metadata.push((pi, Primer::parse(&v), Vec::new()));
cur_meta = Some(w.metadata.len() - 1);
}
@@ -507,6 +550,14 @@ fn resync(src: &(impl ByteSource + ?Sized), from: u64, len: u64, budget: &mut us
/// Data definition labels (ST 377-1 Annex / RP 224): 06 0E 2B 34 04 01 01 01 01 03 02 kk tt 00 00 00.
fn track_kind_of(def: Option<Ul>) -> Option<(bool, TrackKind)> {
let d = def?;
// Legacy AAF DataDefinition AUIDs, encoded in MXF's half-swapped UUID form.
// Picture, sound and timecode respectively.
match d.0 {
[0x80, 0x7d, 0, 0x60, 8, 0x14, 0x3e, 0x6f, 0x6f, 0x3c, 0x8c, 0xe1, 0x6c, 0xef, 0x11, 0xd2] => return Some((false, TrackKind::Picture)),
[0x80, 0x7d, 0, 0x60, 8, 0x14, 0x3e, 0x6f, 0x78, 0xe1, 0xeb, 0xe1, 0x6c, 0xef, 0x11, 0xd2] => return Some((false, TrackKind::Sound)),
[0x80, 0x7f, 0, 0x60, 8, 0x14, 0x3e, 0x6f, 0x7f, 0x27, 0x5e, 0x81, 0x77, 0xe5, 0x11, 0xd2] => return Some((true, TrackKind::Data)),
_ => {}
}
if !d.item_starts_with(&[0x01, 0x03, 0x02]) {
return None;
}
@@ -632,11 +683,15 @@ fn sound_info(d: &Set) -> SoundInfo {
/// Resolved track before the sample tables are built.
struct TrackRef {
require_unclaimed_element: bool,
file_package_uid: Option<[u8; 32]>,
track_id: u32,
track_number: u32,
kind: TrackKind,
name: Option<String>,
edit_rate: Rational,
material_edit_rate: Option<Rational>,
material_duration: Option<i64>,
origin: i64,
start_position: i64,
duration: Option<i64>,
@@ -647,7 +702,8 @@ struct TrackRef {
}
fn umid_of(s: &Set, t: u16) -> Option<[u8; 32]> {
s.get(t).and_then(|v| v.get(..32)).map(|b| b.try_into().unwrap_or([0; 32]))
let uid = <[u8; 32]>::try_from(s.get(t)?).ok()?;
(uid != [0; 32]).then_some(uid)
}
/// Material package tracks → file package tracks with descriptors.
@@ -675,7 +731,7 @@ fn resolve_tracks(md: &Metadata, warnings: &mut Vec<String>) -> (Vec<TrackRef>,
let name = material.and_then(|m| m.string(tag::PACKAGE_NAME));
let mut file_track =
|pkg: &Set, kind: Option<TrackKind>, id: Option<u32>, start: i64, duration: Option<i64>, name: Option<String>| -> Option<TrackRef> {
let umid = umid_of(pkg, tag::PACKAGE_UID).unwrap_or([0; 32]);
let umid = umid_of(pkg, tag::PACKAGE_UID);
for r in pkg.references(tag::PACKAGE_TRACKS) {
let Some(t) = md.get(&r) else { continue };
let tid = t.u(tag::TRACK_ID).unwrap_or(0) as u32;
@@ -705,8 +761,12 @@ fn resolve_tracks(md: &Metadata, warnings: &mut Vec<String>) -> (Vec<TrackRef>,
.collect()
})
.unwrap_or_default();
let (body_sid, index_sid) = sids.get(&umid).copied().unwrap_or((0, 0));
let (body_sid, index_sid) = umid.and_then(|id| sids.get(&id)).copied().unwrap_or((0, 0));
return Some(TrackRef {
require_unclaimed_element: false,
file_package_uid: umid,
material_edit_rate: None,
material_duration: None,
track_id: tid,
track_number: t.u(tag::TRACK_NUMBER).unwrap_or(0) as u32,
kind: tk,
@@ -723,6 +783,7 @@ fn resolve_tracks(md: &Metadata, warnings: &mut Vec<String>) -> (Vec<TrackRef>,
}
None
};
let mut unresolved_package = false;
if let Some(m) = material {
for r in m.references(tag::PACKAGE_TRACKS) {
let Some(t) = md.get(&r) else { continue };
@@ -732,8 +793,12 @@ fn resolve_tracks(md: &Metadata, warnings: &mut Vec<String>) -> (Vec<TrackRef>,
continue;
}
let Some(clip) = comps.iter().find(|c| c.kind() == Some(st::SOURCE_CLIP)) else { continue };
let Some(umid) = umid_of(clip, tag::SOURCE_PACKAGE_ID) else { continue };
let Some(umid) = umid_of(clip, tag::SOURCE_PACKAGE_ID) else {
unresolved_package = true;
continue;
};
let Some(pkg) = file_pkg(&umid) else {
unresolved_package = true;
warnings.push(format!("material track {} refers to a package not in this file", t.u(tag::TRACK_ID).unwrap_or(0)));
continue;
};
@@ -744,6 +809,8 @@ fn resolve_tracks(md: &Metadata, warnings: &mut Vec<String>) -> (Vec<TrackRef>,
if let Some(mut tr) =
file_track(pkg, Some(kind), src_track, clip.i(tag::START_POSITION).unwrap_or(0), duration, t.string(tag::TRACK_NAME))
{
tr.material_edit_rate = mrate.is_valid().then_some(mrate);
tr.material_duration = duration;
if mrate.is_valid() && tr.edit_rate.is_valid() && mrate != tr.edit_rate {
let conv =
|v: i64| (v as i128 * tr.edit_rate.num as i128 * mrate.den as i128 / (tr.edit_rate.den as i128 * mrate.num as i128)) as i64;
@@ -759,8 +826,11 @@ fn resolve_tracks(md: &Metadata, warnings: &mut Vec<String>) -> (Vec<TrackRef>,
}
}
}
if out.is_empty() {
// No usable material package: present the file packages' essence tracks directly.
let partial = !out.is_empty();
if !partial || unresolved_package {
// After partial resolution, recover only directly identifiable, unclaimed local
// essence. An unmatched material reference cannot supply its timing or identity.
let mut candidate_numbers = HashMap::<u32, usize>::new();
for pkg in &sources {
if pkg.reference(tag::SOURCE_PACKAGE_DESCRIPTOR).is_none() {
continue;
@@ -773,14 +843,44 @@ fn resolve_tracks(md: &Metadata, warnings: &mut Vec<String>) -> (Vec<TrackRef>,
if !seen.insert(id) {
continue;
}
if let Some(tr) = file_track(pkg, None, Some(id), 0, None, None) {
if let Some(mut tr) = file_track(pkg, None, Some(id), 0, None, None) {
// Without a material reference, only a local container link can
// associate the stored essence with a particular source package.
// Descriptor-only fallback can still read the samples.
if tr.body_sid == 0 {
if partial && tr.file_package_uid.is_some_and(|uid| sids.contains_key(&uid)) {
continue; // Explicit external package alongside resolved tracks.
}
tr.file_package_uid = None;
}
if partial {
if !tr.kind.matches_element(tr.track_number.to_be_bytes()) {
continue;
}
if tr.kind == TrackKind::Picture {
// This duration belongs to the file track, independently of material timing.
tr.duration = components(md, t).0.and_then(|seq| seq.i(tag::DURATION)).filter(|d| *d >= 0);
}
tr.require_unclaimed_element = true;
*candidate_numbers.entry(tr.track_number).or_default() += 1;
}
out.push(tr);
}
}
if timecode.is_none() {
if !partial && timecode.is_none() {
timecode = package_timecode(md, pkg);
}
}
if partial {
out.retain(|tr| !tr.require_unclaimed_element || candidate_numbers.get(&tr.track_number) == Some(&1));
}
}
// BodySID zero in an explicit link describes external essence. Absent linkage
// is distinct from an explicit contradiction.
for tr in &mut out {
if tr.file_package_uid.and_then(|id| sids.get(&id)).is_some_and(|&(body, _)| body == 0) {
tr.file_package_uid = None;
}
}
(out, timecode, name)
}
@@ -825,18 +925,16 @@ pub fn open(src: &(impl ByteSource + ?Sized)) -> Result<MxfFile> {
v.dedup();
v
};
for r in &refs {
for mut r in refs {
let number = r.track_number.to_be_bytes();
let mut key4 = all_numbers.iter().find(|n| **n == number).copied();
if r.require_unclaimed_element && (key4.is_none() || claimed.contains(&number)) {
continue;
}
if key4.is_none() {
// Track number missing or not matching (some OP-Atom writers): the only unclaimed
// element stream of the right kind.
let kind_items: &[u8] = match r.kind {
TrackKind::Picture => &[0x05, 0x15],
TrackKind::Sound => &[0x06, 0x16],
TrackKind::Data => &[0x07, 0x17],
};
let cands: Vec<[u8; 4]> = all_numbers.iter().filter(|n| kind_items.contains(&n[0]) && !claimed.contains(n)).copied().collect();
let cands: Vec<[u8; 4]> = all_numbers.iter().filter(|n| r.kind.matches_element(**n) && !claimed.contains(n)).copied().collect();
if cands.len() == 1 {
key4 = Some(cands[0]);
}
@@ -845,9 +943,28 @@ pub fn open(src: &(impl ByteSource + ?Sized)) -> Result<MxfFile> {
warnings.push(format!("no essence in this file for track {} (number {:08x})", r.track_id, r.track_number));
continue;
};
let mut elements: Vec<Element> = w.elements.iter().filter(|e| e.key.0[12..16] == key4).copied().collect();
if r.body_sid != 0 {
let belongs_to_package = |e: &Element| {
let end = w.partitions.partition_point(|p| p.offset < e.value_offset);
w.partitions[..end].last().is_some_and(|p| p.body_sid == r.body_sid)
};
if r.require_unclaimed_element {
elements.retain(belongs_to_package);
} else if !elements.iter().all(belongs_to_package) {
// A playable stream number alone cannot authenticate the package.
r.file_package_uid = None;
}
}
if elements.is_empty() {
continue;
}
let track = build_track(src, &r, &elements, key4, &w.index, &mut warnings)?;
if r.require_unclaimed_element && track.kind == TrackKind::Picture && track.samples.is_empty() {
continue;
}
claimed.push(key4);
let elements: Vec<Element> = w.elements.iter().filter(|e| e.key.0[12..16] == key4).copied().collect();
tracks.push(build_track(src, r, &elements, key4, &w.index, &mut warnings)?);
tracks.push(track);
}
if tracks.is_empty() {
return Err(Error::Unsupported("no essence of the material package is stored in this file".into()));
@@ -869,10 +986,13 @@ pub fn open(src: &(impl ByteSource + ?Sized)) -> Result<MxfFile> {
})
}
/// Index entries per stored edit unit for an index SID (all segments when `sid` is 0 or unmatched).
fn index_entries(index: &[IndexSegment], sid: u32) -> (std::collections::BTreeMap<usize, IndexEntry>, u32) {
/// Index entries per stored edit unit. Restricted recovery requires both stream IDs.
fn index_entries(index: &[IndexSegment], sid: u32, required_body: Option<u32>) -> (std::collections::BTreeMap<usize, IndexEntry>, u32) {
let any = index.iter().any(|s| s.index_sid == sid);
let segs: Vec<&IndexSegment> = index.iter().filter(|s| !any || s.index_sid == sid).collect();
let segs = index.iter().filter(|s| match required_body {
Some(body) => body != 0 && sid != 0 && s.body_sid == body && s.index_sid == sid,
None => !any || s.index_sid == sid,
});
// ST 377-1 segments use absolute edit-unit positions, which need not start at zero.
// Keep positions sparse so even hostile gaps allocate only for real (already parsed) entries.
let mut out = std::collections::BTreeMap::new();
@@ -901,11 +1021,14 @@ fn build_track(
let desc = r.descriptor.as_ref();
let container = desc.and_then(|d| d.ul(tag::ESSENCE_CONTAINER));
let mut t = EssenceTrack {
file_package_uid: r.file_package_uid,
track_id: r.track_id,
track_number: u32::from_be_bytes(key4),
kind: r.kind,
name: r.name.clone(),
edit_rate: r.edit_rate,
material_edit_rate: r.material_edit_rate,
material_duration: r.material_duration,
origin: r.origin,
start_position: r.start_position,
duration: r.duration,
@@ -950,7 +1073,7 @@ fn build_track(
}
t.codec = codec;
t.picture = Some(pi);
build_pictures(src, &mut t, elements, index, warnings)?;
build_pictures(src, &mut t, elements, index, r.require_unclaimed_element.then_some(r.body_sid), warnings)?;
}
TrackKind::Sound => {
let si = desc.map(|d| sound_info(d)).unwrap_or(SoundInfo { channels: 1, bits: 16, ..Default::default() });
@@ -988,15 +1111,56 @@ fn build_track(
Ok(t)
}
/// A single KLV can hold a whole clip. Only recover it when every edit unit
/// can be delimited, or file-track metadata identifies exactly one picture.
fn has_recovered_boundaries(
element: &Element,
expected: Option<usize>,
entries: &std::collections::BTreeMap<usize, IndexEntry>,
unit_bytes: u32,
) -> bool {
if element.truncated || element.size == 0 {
return false;
}
if expected == Some(1) {
return u32::try_from(element.size).is_ok();
}
if unit_bytes > 0 {
let width = u64::from(unit_bytes);
return element.size.is_multiple_of(width) && expected.is_none_or(|n| n as u64 == element.size / width);
}
let Some(first) = entries.get(&0) else { return false };
if entries.len() < 2 || expected.is_some_and(|n| n != entries.len()) {
return false;
}
let mut previous = 0;
for (position, (&edit_unit, entry)) in entries.iter().enumerate().skip(1) {
let Some(offset) = entry.stream_offset.checked_sub(first.stream_offset) else { return false };
if edit_unit != position || offset <= previous || offset >= element.size || offset - previous > u64::from(u32::MAX) {
return false;
}
previous = offset;
}
element.size - previous <= u64::from(u32::MAX)
}
fn build_pictures(
src: &(impl ByteSource + ?Sized),
t: &mut EssenceTrack,
elements: &[Element],
index: &[IndexSegment],
required_body: Option<u32>,
warnings: &mut Vec<String>,
) -> Result<()> {
let (entries, eubc) = index_entries(index, t.index_sid);
let (entries, eubc) = index_entries(index, t.index_sid, required_body);
let expected = t.duration.map(|d| d.saturating_add(t.first_edit_unit()).max(0) as usize);
if required_body.is_some()
&& let [element] = elements
&& !has_recovered_boundaries(element, expected, &entries, eubc)
{
warnings.push("recovered picture element has no verified edit-unit boundaries".into());
return Ok(());
}
let clip = elements.len() == 1 && expected.is_none_or(|n| n > 1) && (eubc > 0 || entries.len() > 1);
let mut samples: Vec<Sample> = Vec::new();
if clip {
@@ -1221,7 +1385,7 @@ mod index_bounds_tests {
let entry = IndexEntry { flags: 0x80, stream_offset: 1234, ..Default::default() };
for start_position in [5, 49_999_999, i64::MAX] {
let segment = IndexSegment { start_position, entries: vec![entry, entry], ..Default::default() };
let (entries, _) = index_entries(&[segment], 0);
let (entries, _) = index_entries(&[segment], 0, None);
let start = usize::try_from(start_position).unwrap();
assert_eq!(entries.get(&start), Some(&entry));
assert_eq!(entries.len(), if start_position == i64::MAX { 1 } else { 2 });
@@ -1231,7 +1395,7 @@ mod index_bounds_tests {
#[test]
fn negative_preroll_positions_do_not_drop_later_valid_entries() {
let segment = IndexSegment { start_position: -1, entries: vec![IndexEntry::default(); 3], ..Default::default() };
let (entries, _) = index_entries(&[segment], 0);
let (entries, _) = index_entries(&[segment], 0, None);
assert_eq!(entries.keys().copied().collect::<Vec<_>>(), vec![0, 1]);
}
}
@@ -1268,11 +1432,14 @@ mod aes3_read_tests {
}
let samples = (data.len() as u64 - 4) / 32;
let track = EssenceTrack {
file_package_uid: None,
track_id: 1,
track_number: 0,
kind: TrackKind::Sound,
name: None,
edit_rate: Rational::default(),
material_edit_rate: None,
material_duration: None,
origin: 0,
start_position: 0,
duration: None,
+281 -2
View File
@@ -116,6 +116,17 @@ fn source_clip(uid: u8, def: [u8; 16], dur: i64, pkg: [u8; 32], track: u32) -> V
/// 16-bit stereo sound element of 1920 frames (sample k of the file = k, -k on the channels);
/// a footer index with temporal offsets `to` and flags `flags`.
fn build(n: usize, pic: impl Fn(usize) -> Vec<u8>, to: &[i8], flags: &[u8]) -> Vec<u8> {
build_with_packages(n, pic, to, flags, Some(&umid(2)), false)
}
fn build_with_packages(
n: usize,
pic: impl Fn(usize) -> Vec<u8>,
to: &[i8],
flags: &[u8],
file_package_uid: Option<&[u8]>,
separate_picture: bool,
) -> Vec<u8> {
let mut md = Vec::new();
// primer: no dynamic tags
klv(&mut md, ul(&[0x06, 0x0E, 0x2B, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0D, 0x01, 0x02, 0x01, 0x01, 0x05, 0x01, 0x00]), &batch(&[]));
@@ -137,13 +148,23 @@ fn build(n: usize, pic: impl Fn(usize) -> Vec<u8>, to: &[i8], flags: &[u8]) -> V
klv(&mut md, set_key(0x14), &tc.0);
klv(&mut md, set_key(0x3B), &track(11, 2, 0, 21));
klv(&mut md, set_key(0x0F), &sequence(21, PICTURE_DEF, d, 31));
klv(&mut md, set_key(0x11), &source_clip(31, PICTURE_DEF, d, umid(2), 2));
klv(&mut md, set_key(0x11), &source_clip(31, PICTURE_DEF, d, if separate_picture { umid(3) } else { umid(2) }, 2));
klv(&mut md, set_key(0x3B), &track(12, 3, 0, 22));
klv(&mut md, set_key(0x0F), &sequence(22, SOUND_DEF, d, 32));
klv(&mut md, set_key(0x11), &source_clip(32, SOUND_DEF, d, umid(2), 3));
// file package
let mut fp = LocalSet::new(4);
fp.p(0x4401, &umid(2)).p(0x4403, &batch(&[&uuid(13), &uuid(14)])).p(0x4701, &uuid(40));
if let Some(uid) = file_package_uid {
fp.p(0x4401, uid);
}
if separate_picture {
let mut picture = LocalSet::new(7);
picture.p(0x4401, &umid(3)).p(0x4403, &batch(&[&uuid(13)])).p(0x4701, &uuid(41));
klv(&mut md, set_key(0x37), &picture.0);
fp.p(0x4403, &batch(&[&uuid(14)])).p(0x4701, &uuid(42));
} else {
fp.p(0x4403, &batch(&[&uuid(13), &uuid(14)])).p(0x4701, &uuid(40));
}
klv(&mut md, set_key(0x37), &fp.0);
klv(&mut md, set_key(0x3B), &track(13, 2, 0x1501_0500, 23));
klv(&mut md, set_key(0x0F), &sequence(23, PICTURE_DEF, d, 33));
@@ -393,3 +414,261 @@ fn a_corrupt_index_position_cannot_allocate_a_giant_sparse_table() {
let file = open(&bytes).unwrap();
assert_eq!(file.tracks[file.track_of_kind(TrackKind::Picture).unwrap()].samples.len(), 5);
}
#[test]
fn opaque_header_packet_preserves_following_metadata() {
let original = build(2, prores_like, &[], &[]);
let at = original.windows(16).position(|b| b == set_key(0x2f)).unwrap();
let mut opaque = Vec::new();
klv(&mut opaque, [0x80; 16], &[0; 96]);
let mut data = original.clone();
data.splice(at..at, opaque.iter().copied());
let (_, width) = crate::mxf::klv::ber_length(&data[16..]).unwrap();
let count_at = 16 + width + 32;
let count = u64::from_be_bytes(data[count_at..count_at + 8].try_into().unwrap());
data[count_at..count_at + 8].copy_from_slice(&(count + opaque.len() as u64).to_be_bytes());
let file = open(data.as_slice()).unwrap();
assert_eq!(file.tracks.len(), 2);
assert!(file.warnings.iter().any(|w| w.contains("opaque non-SMPTE")));
let audio = file.track_of_kind(TrackKind::Sound).unwrap();
assert_eq!(
file.read_pcm(data.as_slice(), audio, 0, 100).unwrap(),
open(original.as_slice()).unwrap().read_pcm(original.as_slice(), audio, 0, 100).unwrap()
);
// An unbounded purported private value must not be trusted as a packet boundary.
data[at + 16..at + 20].copy_from_slice(&[0x83, 0xff, 0xff, 0xff]);
assert!(std::panic::catch_unwind(|| open(data.as_slice())).is_ok());
}
#[test]
fn legacy_picture_audio_and_timecode_data_definitions_are_recognized() {
let mut data = build(2, prores_like, &[], &[]);
for (standard, legacy) in [
(PICTURE_DEF, [0x80, 0x7d, 0, 0x60, 8, 0x14, 0x3e, 0x6f, 0x6f, 0x3c, 0x8c, 0xe1, 0x6c, 0xef, 0x11, 0xd2]),
(SOUND_DEF, [0x80, 0x7d, 0, 0x60, 8, 0x14, 0x3e, 0x6f, 0x78, 0xe1, 0xeb, 0xe1, 0x6c, 0xef, 0x11, 0xd2]),
(TC_DEF, [0x80, 0x7f, 0, 0x60, 8, 0x14, 0x3e, 0x6f, 0x7f, 0x27, 0x5e, 0x81, 0x77, 0xe5, 0x11, 0xd2]),
] {
let positions: Vec<_> = data.windows(16).enumerate().filter(|(_, b)| *b == standard).map(|(i, _)| i).collect();
for pos in positions {
data[pos..pos + 16].copy_from_slice(&legacy);
}
}
let file = open(data.as_slice()).unwrap();
assert_eq!(file.tracks[file.track_of_kind(TrackKind::Picture).unwrap()].samples.len(), 2);
assert!(file.track_of_kind(TrackKind::Sound).is_some());
assert!(file.timecode.is_some());
}
#[test]
fn material_clock_and_duration_survive_file_unit_conversion() {
let (offsets, flags) = ipbb();
let mut bytes = build(7, |_| vec![0; 100], &offsets, &flags);
let original = track(14, 3, 0x1601_0300, 24);
let mut changed = original.clone();
let rate = [0x4b, 0x01, 0, 8, 0, 0, 0, 25, 0, 0, 0, 1];
let offset = changed.windows(rate.len()).position(|w| w == rate).unwrap();
changed[offset + 4..offset + 8].copy_from_slice(&48000i32.to_be_bytes());
let offset = bytes.windows(original.len()).position(|w| w == original).unwrap();
bytes[offset..offset + original.len()].copy_from_slice(&changed);
let file = open(&bytes).unwrap();
let sound = &file.tracks[file.track_of_kind(TrackKind::Sound).unwrap()];
assert_eq!(sound.edit_rate, Rational::new(48000, 1));
assert_eq!(sound.duration, Some(13440));
assert_eq!(sound.file_package_uid, Some(umid(2)));
assert_eq!(sound.material_edit_rate, Some(Rational::new(25, 1)));
assert_eq!(sound.material_duration, Some(7));
assert_eq!(sound.stored_sample_frames(), 13440);
}
#[test]
fn readable_essence_without_a_usable_file_package_id_has_no_relink_identity() {
for uid in [None, Some(&[0; 32][..]), Some(&[7; 31][..]), Some(&[7; 33][..])] {
let bytes = build_with_packages(2, prores_like, &[], &[], uid, false);
let mxf = open(&bytes).unwrap();
let audio = mxf.track_of_kind(TrackKind::Sound).unwrap();
assert_eq!(mxf.tracks[audio].file_package_uid, None);
let pcm = mxf.read_pcm(&bytes, audio, 0, 8).unwrap();
assert_eq!(pcm[0].len(), 8);
assert!(pcm[0][7] > 0.0);
}
}
#[test]
fn a_resolved_picture_package_does_not_hide_stored_audio_with_an_unusable_uid() {
let overlong = [umid(2).as_slice(), &[0xff]].concat();
for uid in [Some(overlong.as_slice()), Some(&[7; 31][..]), Some(&[0; 32][..]), None] {
let bytes = build_with_packages(2, prores_like, &[], &[], uid, true);
let file = open(&bytes).unwrap();
let picture = file.track_of_kind(TrackKind::Picture).unwrap();
assert_eq!(file.tracks[picture].file_package_uid, Some(umid(3)));
let sound = file.track_of_kind(TrackKind::Sound).expect("stored audio remains readable");
assert_eq!(file.tracks[sound].file_package_uid, None);
assert!(file.read_pcm(&bytes, sound, 0, 8).unwrap()[0][7] > 0.0);
assert_eq!(file.tracks.len(), 2);
}
}
#[test]
fn an_unidentified_package_cannot_guess_a_stream_or_claim_the_resolved_picture() {
for number in [0, 0x1501_0500] {
let mut bytes = build_with_packages(2, prores_like, &[], &[], None, true);
let original = track(14, 3, 0x1601_0300, 24);
let at = bytes.windows(original.len()).position(|v| v == original).unwrap();
bytes[at..at + original.len()].copy_from_slice(&track(14, 3, number, 24));
let file = open(&bytes).unwrap();
assert_eq!(file.tracks.len(), 1);
assert_eq!(file.tracks[0].kind, TrackKind::Picture);
assert_eq!(file.tracks[0].file_package_uid, Some(umid(3)));
}
}
#[test]
fn partial_recovery_keeps_local_sound_when_its_material_reference_is_empty() {
let uid = umid(2);
let mut bytes = build_with_packages(2, prores_like, &[], &[], Some(&uid), true);
let original = source_clip(32, SOUND_DEF, 2, uid, 3);
let at = bytes.windows(original.len()).position(|v| v == original).unwrap();
bytes[at..at + original.len()].copy_from_slice(&source_clip(32, SOUND_DEF, 2, [0; 32], 3));
let file = open(&bytes).unwrap();
let sound = file.track_of_kind(TrackKind::Sound).expect("stored sound is independently readable");
assert_eq!(file.tracks[sound].file_package_uid, Some(uid));
assert_eq!(file.tracks[sound].material_duration, None);
assert!(file.read_pcm(&bytes, sound, 0, 8).unwrap()[0][7] > 0.0);
assert_eq!(file.tracks.len(), 2);
// Even an exact track number cannot identify an external or different body.
let mut ecd = LocalSet::new(5);
ecd.p(0x2701, &uid).p(0x3F07, &1u32.to_be_bytes()).p(0x3F06, &2u32.to_be_bytes());
let at = bytes.windows(ecd.0.len()).position(|v| v == ecd.0).unwrap();
for sid in [0u32, 2] {
let mut other = LocalSet::new(5);
other.p(0x2701, &uid).p(0x3F07, &sid.to_be_bytes()).p(0x3F06, &2u32.to_be_bytes());
bytes[at..at + other.0.len()].copy_from_slice(&other.0);
assert!(open(&bytes).unwrap().track_of_kind(TrackKind::Sound).is_none());
}
// Missing container linkage still permits local reading, without a relink identity.
let mut unrelated = LocalSet::new(5);
unrelated.p(0x2701, &umid(99)).p(0x3F07, &1u32.to_be_bytes()).p(0x3F06, &2u32.to_be_bytes());
bytes[at..at + unrelated.0.len()].copy_from_slice(&unrelated.0);
let file = open(&bytes).unwrap();
assert_eq!(file.tracks[file.track_of_kind(TrackKind::Sound).unwrap()].file_package_uid, None);
}
#[test]
fn partial_recovery_refuses_sound_metadata_that_points_at_an_unclaimed_picture_element() {
let mut bytes = build_with_packages(2, prores_like, &[], &[], None, true);
let original = track(14, 3, 0x1601_0300, 24);
let at = bytes.windows(original.len()).position(|v| v == original).unwrap();
bytes[at..at + original.len()].copy_from_slice(&track(14, 3, 0x1501_0501, 24));
let mut extra_key = PIC_KEY;
extra_key[15] = 1;
for at in bytes.windows(16).enumerate().filter_map(|(i, k)| (k == SND_KEY).then_some(i)).collect::<Vec<_>>() {
bytes[at..at + 16].copy_from_slice(&extra_key);
}
let file = open(&bytes).unwrap();
assert!(file.track_of_kind(TrackKind::Picture).is_some());
assert!(file.track_of_kind(TrackKind::Sound).is_none());
}
fn replace_fixture_set(bytes: &mut [u8], original: &[u8], replacement: &[u8]) {
let at = bytes.windows(original.len()).position(|v| v == original).unwrap();
bytes[at..at + original.len()].copy_from_slice(replacement);
}
fn container_link(package: [u8; 32], body: u32, index: u32) -> Vec<u8> {
let mut link = LocalSet::new(5);
link.p(0x2701, &package).p(0x3F07, &body.to_be_bytes()).p(0x3F06, &index.to_be_bytes());
link.0
}
#[test]
fn unlinked_packages_cannot_identify_sound_during_full_fallback() {
let mut bytes = build_with_packages(2, prores_like, &[], &[], Some(&umid(2)), true);
for (clip, def, package, track) in [(31, PICTURE_DEF, 3, 2), (32, SOUND_DEF, 2, 3)] {
replace_fixture_set(&mut bytes, &source_clip(clip, def, 2, umid(package), track), &source_clip(clip, def, 2, [0; 32], track));
}
let package = |track, descriptor| {
let mut set = LocalSet::new(7);
set.p(0x4401, &umid(3)).p(0x4403, &batch(&[&uuid(track)])).p(0x4701, &uuid(descriptor));
set.0
};
replace_fixture_set(&mut bytes, &package(13, 41), &package(14, 42));
replace_fixture_set(&mut bytes, &container_link(umid(2), 1, 2), &container_link(umid(99), 1, 2));
let file = open(&bytes).unwrap();
let sound = file.track_of_kind(TrackKind::Sound).unwrap();
assert!(file.read_pcm(&bytes, sound, 0, 8).unwrap()[0][7] > 0.0);
assert!(file.tracks.iter().all(|track| track.file_package_uid.is_none()));
}
#[test]
fn damaged_link_material_track_remains_readable_without_claiming_the_wrong_body() {
let original = build(2, prores_like, &[], &[]);
for body in [0, 7] {
let mut bytes = original.clone();
replace_fixture_set(&mut bytes, &container_link(umid(2), 1, 2), &container_link(umid(2), body, 2));
let file = open(&bytes).unwrap();
let sound = file.track_of_kind(TrackKind::Sound).unwrap();
assert_eq!(file.tracks[sound].file_package_uid, None);
assert!(file.read_pcm(&bytes, sound, 0, 8).unwrap()[0][7] > 0.0);
}
}
#[test]
fn damaged_link_partial_picture_uses_only_its_own_body_and_index_for_display_order() {
let mut base = build_with_packages(2, prores_like, &[1, -1], &[], Some(&umid(2)), true);
replace_fixture_set(&mut base, &source_clip(31, PICTURE_DEF, 2, umid(3), 2), &source_clip(31, PICTURE_DEF, 2, [0; 32], 2));
for (index, segment_body, reordered) in [(2u32, 1u32, true), (7, 1, false), (0, 1, false), (2, 9, false)] {
let mut bytes = base.clone();
replace_fixture_set(&mut bytes, &container_link(umid(2), 1, 2), &container_link(umid(3), 1, index));
// The IndexTableSegment, at the footer, follows the header container link.
let tag = [0x3f, 0x07, 0, 4, 0, 0, 0, 1];
let at = bytes.windows(tag.len()).rposition(|v| v == tag).unwrap();
bytes[at + 4..at + 8].copy_from_slice(&segment_body.to_be_bytes());
let file = open(&bytes).unwrap();
let picture = &file.tracks[file.track_of_kind(TrackKind::Picture).unwrap()];
assert_eq!(picture.samples.len(), 2);
assert_eq!(picture.temporal_offsets, reordered);
assert_eq!(picture.display_order, if reordered { [1, 0] } else { [0, 1] });
}
}
#[test]
fn damaged_link_clip_wrapped_picture_needs_its_own_frame_boundaries() {
// Store two 40-byte pictures in one 80-byte KLV. Leave the other KLV as filler.
let mut base = build_with_packages(2, |_| vec![0; 80], &[], &[], Some(&umid(2)), true);
replace_fixture_set(&mut base, &source_clip(31, PICTURE_DEF, 2, umid(3), 2), &source_clip(31, PICTURE_DEF, 2, [0; 32], 2));
let second_picture = base.windows(16).rposition(|v| v == PIC_KEY).unwrap();
base[second_picture..second_picture + 16].copy_from_slice(&[6, 14, 43, 52, 1, 1, 1, 2, 3, 1, 2, 16, 1, 0, 0, 0]);
let last_offset = base.len() - 8;
base[last_offset..].copy_from_slice(&40u64.to_be_bytes());
for index in [2, 7] {
let mut bytes = base.clone();
replace_fixture_set(&mut bytes, &container_link(umid(2), 1, 2), &container_link(umid(3), 1, index));
let file = open(&bytes).unwrap();
if index == 2 {
let picture = &file.tracks[file.track_of_kind(TrackKind::Picture).unwrap()];
assert_eq!(picture.samples.iter().map(|s| s.size).collect::<Vec<_>>(), [40, 40]);
} else {
assert!(file.track_of_kind(TrackKind::Picture).is_none());
assert!(file.track_of_kind(TrackKind::Sound).is_some());
}
}
}
#[test]
fn partial_picture_a_lone_index_entry_cannot_split_a_two_frame_payload() {
let mut base = build_with_packages(1, |_| vec![0; 80], &[], &[], Some(&umid(2)), true);
replace_fixture_set(&mut base, &source_clip(31, PICTURE_DEF, 1, umid(3), 2), &source_clip(31, PICTURE_DEF, 1, [0; 32], 2));
replace_fixture_set(&mut base, &container_link(umid(2), 1, 2), &container_link(umid(3), 1, 2));
for (duration, position) in [(1, 1i64), (2, 0), (2, 1)] {
let mut bytes = base.clone();
replace_fixture_set(&mut bytes, &sequence(23, PICTURE_DEF, 1, 33), &sequence(23, PICTURE_DEF, duration, 33));
let start_tag = [0x3f, 0x0c, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0];
let start = bytes.windows(start_tag.len()).rposition(|v| v == start_tag).unwrap();
bytes[start + 4..start + 12].copy_from_slice(&position.to_be_bytes());
let file = open(&bytes).unwrap();
assert_eq!(file.track_of_kind(TrackKind::Picture).is_some(), duration == 1);
assert!(file.track_of_kind(TrackKind::Sound).is_some());
}
}