Skip to main content

postproject_core/
content.rs

1//! Structure and membership values for compound representations.
2
3use std::collections::BTreeSet;
4
5use crate::{Error, ErrorKind, RationalRate, ResourceId, Result};
6
7/// Maximum encoded length of an extensible resource-role identifier.
8pub const MAX_RESOURCE_ROLE_BYTES: usize = 128;
9/// Maximum combined UTF-8 length of a sequence naming's prefix and suffix.
10pub const MAX_SEQUENCE_NAMING_BYTES: usize = 1_024;
11/// Maximum supported zero-padding width for an image-sequence frame number.
12pub const MAX_FRAME_PADDING: u8 = 32;
13/// Maximum number of sparse frame exceptions stored in one sequence descriptor.
14pub const MAX_SEQUENCE_EXCEPTIONS: usize = 100_000;
15/// Maximum number of materialized resource members in one content structure.
16pub const MAX_CONTENT_MEMBERS: usize = 100_000;
17
18/// An inclusive, regularly stepped frame domain.
19#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
20pub struct FrameRange {
21    start: i64,
22    end: i64,
23    step: u32,
24}
25
26impl FrameRange {
27    /// Creates an inclusive range whose end is aligned to its step.
28    ///
29    /// # Errors
30    ///
31    /// Returns [`ErrorKind::InvalidArgument`] for a reversed range, zero step,
32    /// or an end frame not reachable from the start by whole steps.
33    pub fn new(start: i64, end: i64, step: u32) -> Result<Self> {
34        if step == 0 || end < start {
35            return Err(Error::new(
36                ErrorKind::InvalidArgument,
37                "frame range must be ascending with a non-zero step",
38            ));
39        }
40        let distance = i128::from(end) - i128::from(start);
41        if distance % i128::from(step) != 0 {
42            return Err(Error::new(
43                ErrorKind::InvalidArgument,
44                "frame range end must be aligned to its step",
45            ));
46        }
47        Ok(Self { start, end, step })
48    }
49
50    /// Returns the first frame number.
51    #[must_use]
52    pub const fn start(self) -> i64 {
53        self.start
54    }
55
56    /// Returns the last frame number.
57    #[must_use]
58    pub const fn end(self) -> i64 {
59        self.end
60    }
61
62    /// Returns the positive frame-number increment.
63    #[must_use]
64    pub const fn step(self) -> u32 {
65        self.step
66    }
67
68    /// Returns the exact number of frames in the regular domain.
69    #[must_use]
70    pub fn frame_count(self) -> u128 {
71        let distance = i128::from(self.end) - i128::from(self.start);
72        distance.unsigned_abs() / u128::from(self.step) + 1
73    }
74
75    /// Returns whether the frame belongs to the stepped domain.
76    #[must_use]
77    pub fn contains(self, frame: i64) -> bool {
78        if frame < self.start || frame > self.end {
79            return false;
80        }
81        let distance = i128::from(frame) - i128::from(self.start);
82        distance % i128::from(self.step) == 0
83    }
84}
85
86/// How the files of an image sequence are named in one place.
87///
88/// The prefix, suffix, and frame-number padding belong to a locator, not to
89/// the sequence's content (ADR 0038): copies of one sequence may name their
90/// files differently.
91#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
92pub struct SequenceNaming {
93    prefix: String,
94    suffix: String,
95    padding: u8,
96}
97
98impl SequenceNaming {
99    /// Creates a bounded file naming without directory separators.
100    ///
101    /// # Errors
102    ///
103    /// Returns [`ErrorKind::InvalidArgument`] when the naming is empty, too
104    /// long, contains a path separator or NUL, or requests excessive padding.
105    pub fn new(prefix: impl Into<String>, suffix: impl Into<String>, padding: u8) -> Result<Self> {
106        let prefix = prefix.into();
107        let suffix = suffix.into();
108        let invalid_character = |character| matches!(character, '/' | '\\' | '\0');
109        if (prefix.is_empty() && suffix.is_empty())
110            || prefix.len().saturating_add(suffix.len()) > MAX_SEQUENCE_NAMING_BYTES
111            || prefix.chars().any(invalid_character)
112            || suffix.chars().any(invalid_character)
113            || padding > MAX_FRAME_PADDING
114        {
115            return Err(Error::new(
116                ErrorKind::InvalidArgument,
117                "invalid image-sequence file naming",
118            ));
119        }
120        Ok(Self {
121            prefix,
122            suffix,
123            padding,
124        })
125    }
126
127    /// Returns the text before the frame number.
128    #[must_use]
129    pub fn prefix(&self) -> &str {
130        &self.prefix
131    }
132
133    /// Returns the text after the frame number.
134    #[must_use]
135    pub fn suffix(&self) -> &str {
136        &self.suffix
137    }
138
139    /// Returns the minimum frame-number width.
140    #[must_use]
141    pub const fn padding(&self) -> u8 {
142        self.padding
143    }
144
145    /// Formats the file name of `frame` without joining it to a directory.
146    #[must_use]
147    pub fn filename(&self, frame: i64) -> String {
148        let frame = format!("{frame:0width$}", width = usize::from(self.padding));
149        format!("{}{frame}{}", self.prefix, self.suffix)
150    }
151}
152
153/// A compact description of one regular or sparse image sequence.
154///
155/// The descriptor holds what the sequence is: its frames, rate, and known
156/// gaps. How its files are named is part of each locator.
157#[derive(Clone, Debug, Eq, PartialEq)]
158pub struct ImageSequenceDescriptor {
159    resource_id: ResourceId,
160    frames: FrameRange,
161    rate: RationalRate,
162    known_missing_frames: Vec<i64>,
163}
164
165impl ImageSequenceDescriptor {
166    /// Creates a sequence descriptor and canonicalizes its sparse exceptions.
167    ///
168    /// # Errors
169    ///
170    /// Returns [`ErrorKind::InvalidArgument`] when there are too many missing
171    /// frames or an exception does not belong to the regular frame domain.
172    pub fn new(
173        resource_id: ResourceId,
174        frames: FrameRange,
175        rate: RationalRate,
176        mut known_missing_frames: Vec<i64>,
177    ) -> Result<Self> {
178        if known_missing_frames.len() > MAX_SEQUENCE_EXCEPTIONS {
179            return Err(Error::new(
180                ErrorKind::InvalidArgument,
181                format!("image sequence has more than {MAX_SEQUENCE_EXCEPTIONS} sparse exceptions"),
182            ));
183        }
184        if known_missing_frames
185            .iter()
186            .any(|frame| !frames.contains(*frame))
187        {
188            return Err(Error::new(
189                ErrorKind::InvalidArgument,
190                "missing image-sequence frame is outside the regular frame domain",
191            ));
192        }
193        known_missing_frames.sort_unstable();
194        known_missing_frames.dedup();
195        Ok(Self {
196            resource_id,
197            frames,
198            rate,
199            known_missing_frames,
200        })
201    }
202
203    /// Returns the compact patterned resource identity.
204    #[must_use]
205    pub const fn resource_id(&self) -> ResourceId {
206        self.resource_id
207    }
208
209    /// Returns the regular frame domain before sparse exceptions.
210    #[must_use]
211    pub const fn frames(&self) -> FrameRange {
212        self.frames
213    }
214
215    /// Returns the exact playback or capture rate.
216    #[must_use]
217    pub const fn rate(&self) -> RationalRate {
218        self.rate
219    }
220
221    /// Returns sorted, unique frames known to be absent.
222    #[must_use]
223    pub fn known_missing_frames(&self) -> &[i64] {
224        &self.known_missing_frames
225    }
226
227    /// Returns whether a frame is recorded as missing.
228    #[must_use]
229    pub fn is_known_missing(&self, frame: i64) -> bool {
230        self.known_missing_frames.binary_search(&frame).is_ok()
231    }
232}
233
234/// A namespaced, open-world role for a resource within a representation.
235#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
236pub struct ResourceRole(String);
237
238impl ResourceRole {
239    /// Creates a role such as `org.postproject:essence` or `vendor:playlist`.
240    ///
241    /// # Errors
242    ///
243    /// Returns [`ErrorKind::InvalidArgument`] when the role is empty, too long,
244    /// is not namespaced, or contains unsupported bytes.
245    pub fn new(value: impl Into<String>) -> Result<Self> {
246        let value = value.into();
247        let valid_bytes = value
248            .bytes()
249            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b':'));
250        let valid_namespace = value
251            .split_once(':')
252            .is_some_and(|(namespace, local)| !namespace.is_empty() && !local.is_empty());
253        if value.len() > MAX_RESOURCE_ROLE_BYTES || !valid_bytes || !valid_namespace {
254            return Err(Error::new(
255                ErrorKind::InvalidArgument,
256                format!(
257                    "resource role must be a namespaced identifier of at most {MAX_RESOURCE_ROLE_BYTES} ASCII bytes"
258                ),
259            ));
260        }
261        Ok(Self(value))
262    }
263
264    /// Returns the exact role identifier.
265    #[must_use]
266    pub fn as_str(&self) -> &str {
267        &self.0
268    }
269}
270
271/// One resource's role and requiredness within a content structure.
272#[derive(Clone, Debug, Eq, PartialEq)]
273pub struct ResourceMember {
274    resource_id: ResourceId,
275    role: ResourceRole,
276    required: bool,
277}
278
279impl ResourceMember {
280    /// Creates a resource membership.
281    #[must_use]
282    pub const fn new(resource_id: ResourceId, role: ResourceRole, required: bool) -> Self {
283        Self {
284            resource_id,
285            role,
286            required,
287        }
288    }
289
290    /// Returns the participating resource.
291    #[must_use]
292    pub const fn resource_id(&self) -> ResourceId {
293        self.resource_id
294    }
295
296    /// Returns the member's extensible semantic role.
297    #[must_use]
298    pub const fn role(&self) -> &ResourceRole {
299        &self.role
300    }
301
302    /// Returns whether availability of this member is required for completeness.
303    #[must_use]
304    pub const fn is_required(&self) -> bool {
305        self.required
306    }
307}
308
309/// The structural shape used to realize a representation.
310#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
311#[non_exhaustive]
312pub enum ContentStructureKind {
313    /// One concrete resource.
314    SingleResource,
315    /// One compact patterned image-sequence resource.
316    ImageSequence,
317    /// Several required resources consumed in stable order.
318    OrderedParts,
319    /// A role-bearing collection of required and optional resources.
320    Package,
321}
322
323#[derive(Clone, Debug, Eq, PartialEq)]
324enum ContentStructureData {
325    SingleResource(ResourceId),
326    ImageSequence(ImageSequenceDescriptor),
327    OrderedParts(Vec<ResourceMember>),
328    Package(Vec<ResourceMember>),
329}
330
331/// A validated description of how resources realize one representation.
332#[derive(Clone, Debug, Eq, PartialEq)]
333pub struct ContentStructure(ContentStructureData);
334
335impl ContentStructure {
336    /// Creates a representation backed by one required resource.
337    #[must_use]
338    pub const fn single_resource(resource_id: ResourceId) -> Self {
339        Self(ContentStructureData::SingleResource(resource_id))
340    }
341
342    /// Creates a representation backed by one compact image sequence.
343    #[must_use]
344    pub const fn image_sequence(descriptor: ImageSequenceDescriptor) -> Self {
345        Self(ContentStructureData::ImageSequence(descriptor))
346    }
347
348    /// Creates an ordered span whose members are all required.
349    ///
350    /// # Errors
351    ///
352    /// Returns [`ErrorKind::InvalidArgument`] when the membership is empty,
353    /// unbounded, duplicated, or contains an optional member.
354    pub fn ordered_parts(members: Vec<ResourceMember>) -> Result<Self> {
355        validate_members(&members)?;
356        if members.iter().any(|member| !member.is_required()) {
357            return Err(Error::new(
358                ErrorKind::InvalidArgument,
359                "ordered content parts must all be required",
360            ));
361        }
362        Ok(Self(ContentStructureData::OrderedParts(members)))
363    }
364
365    /// Creates a package with at least one required member.
366    ///
367    /// # Errors
368    ///
369    /// Returns [`ErrorKind::InvalidArgument`] when the membership is empty,
370    /// unbounded, duplicated, or has no required member.
371    pub fn package(members: Vec<ResourceMember>) -> Result<Self> {
372        validate_members(&members)?;
373        if !members.iter().any(ResourceMember::is_required) {
374            return Err(Error::new(
375                ErrorKind::InvalidArgument,
376                "a content package must have at least one required member",
377            ));
378        }
379        Ok(Self(ContentStructureData::Package(members)))
380    }
381
382    /// Returns the structure discriminator.
383    #[must_use]
384    pub const fn kind(&self) -> ContentStructureKind {
385        match self.0 {
386            ContentStructureData::SingleResource(_) => ContentStructureKind::SingleResource,
387            ContentStructureData::ImageSequence(_) => ContentStructureKind::ImageSequence,
388            ContentStructureData::OrderedParts(_) => ContentStructureKind::OrderedParts,
389            ContentStructureData::Package(_) => ContentStructureKind::Package,
390        }
391    }
392
393    /// Returns the resource when this is a single-resource structure.
394    #[must_use]
395    pub const fn single_resource_id(&self) -> Option<ResourceId> {
396        match self.0 {
397            ContentStructureData::SingleResource(resource_id) => Some(resource_id),
398            _ => None,
399        }
400    }
401
402    /// Returns the descriptor when this is an image sequence.
403    #[must_use]
404    pub const fn image_sequence_descriptor(&self) -> Option<&ImageSequenceDescriptor> {
405        match &self.0 {
406            ContentStructureData::ImageSequence(descriptor) => Some(descriptor),
407            _ => None,
408        }
409    }
410
411    /// Returns members for an ordered or package structure.
412    #[must_use]
413    pub fn members(&self) -> Option<&[ResourceMember]> {
414        match &self.0 {
415            ContentStructureData::OrderedParts(members)
416            | ContentStructureData::Package(members) => Some(members),
417            _ => None,
418        }
419    }
420
421    /// Returns referenced resources in structural order.
422    #[must_use]
423    pub fn resource_ids(&self) -> Vec<ResourceId> {
424        match &self.0 {
425            ContentStructureData::SingleResource(resource_id) => vec![*resource_id],
426            ContentStructureData::ImageSequence(descriptor) => vec![descriptor.resource_id()],
427            ContentStructureData::OrderedParts(members)
428            | ContentStructureData::Package(members) => {
429                members.iter().map(ResourceMember::resource_id).collect()
430            }
431        }
432    }
433}
434
435fn validate_members(members: &[ResourceMember]) -> Result<()> {
436    if members.is_empty() || members.len() > MAX_CONTENT_MEMBERS {
437        return Err(Error::new(
438            ErrorKind::InvalidArgument,
439            format!("content structure must have 1-{MAX_CONTENT_MEMBERS} members"),
440        ));
441    }
442    let unique: BTreeSet<_> = members.iter().map(ResourceMember::resource_id).collect();
443    if unique.len() != members.len() {
444        return Err(Error::new(
445            ErrorKind::InvalidArgument,
446            "content structure contains a duplicate resource",
447        ));
448    }
449    Ok(())
450}
451
452#[cfg(test)]
453mod tests {
454    use super::*;
455
456    #[test]
457    fn frame_ranges_are_inclusive_and_stepped() {
458        let frames = FrameRange::new(-2, 4, 2).expect("valid range");
459
460        assert_eq!(frames.frame_count(), 4);
461        assert!(frames.contains(-2));
462        assert!(frames.contains(4));
463        assert!(!frames.contains(1));
464        assert!(FrameRange::new(1, 0, 1).is_err());
465        assert!(FrameRange::new(0, 5, 2).is_err());
466    }
467
468    #[test]
469    fn sequence_namings_format_frames_without_paths() {
470        let naming = SequenceNaming::new("shot.", ".exr", 4).expect("valid naming");
471
472        assert_eq!(naming.filename(12), "shot.0012.exr");
473        assert_eq!(naming.filename(-2), "shot.-002.exr");
474        assert!(SequenceNaming::new("directory/shot.", ".exr", 4).is_err());
475        assert!(SequenceNaming::new("", "", 0).is_err());
476    }
477
478    #[test]
479    fn sequence_descriptor_is_compact_and_canonical() {
480        let frames = FrameRange::new(1_001, 1_010, 1).expect("valid range");
481        let rate = RationalRate::new(24_000, 1_001).expect("valid rate");
482        let descriptor = ImageSequenceDescriptor::new(
483            ResourceId::new(),
484            frames,
485            rate,
486            vec![1_007, 1_003, 1_007],
487        )
488        .expect("valid sequence");
489
490        assert_eq!(descriptor.known_missing_frames(), [1_003, 1_007]);
491        assert!(descriptor.is_known_missing(1_003));
492        assert!(!descriptor.is_known_missing(1_004));
493        assert!(ImageSequenceDescriptor::new(ResourceId::new(), frames, rate, vec![999],).is_err());
494    }
495
496    #[test]
497    fn resource_roles_are_namespaced_and_open_world() {
498        let standard = ResourceRole::new("org.postproject:essence").expect("valid role");
499        let vendor = ResourceRole::new("example.camera:playlist-v2").expect("valid role");
500
501        assert_eq!(standard.as_str(), "org.postproject:essence");
502        assert_eq!(vendor.as_str(), "example.camera:playlist-v2");
503        assert!(ResourceRole::new("essence").is_err());
504        assert!(ResourceRole::new("vendor:").is_err());
505        assert!(ResourceRole::new("vendor:side car").is_err());
506    }
507
508    #[test]
509    fn membership_preserves_role_and_requiredness() {
510        let resource_id = ResourceId::new();
511        let role = ResourceRole::new("org.postproject:thumbnail").expect("valid role");
512        let member = ResourceMember::new(resource_id, role, false);
513
514        assert_eq!(member.resource_id(), resource_id);
515        assert_eq!(member.role().as_str(), "org.postproject:thumbnail");
516        assert!(!member.is_required());
517    }
518
519    #[test]
520    fn compound_structures_enforce_membership_invariants() {
521        let essence = ResourceRole::new("org.postproject:essence").expect("valid role");
522        let thumbnail = ResourceRole::new("org.postproject:thumbnail").expect("valid role");
523        let required = ResourceMember::new(ResourceId::new(), essence, true);
524        let optional = ResourceMember::new(ResourceId::new(), thumbnail, false);
525
526        let ordered =
527            ContentStructure::ordered_parts(vec![required.clone()]).expect("valid ordered parts");
528        let package = ContentStructure::package(vec![required.clone(), optional.clone()])
529            .expect("valid package");
530
531        assert_eq!(ordered.kind(), ContentStructureKind::OrderedParts);
532        assert_eq!(package.members().expect("package members").len(), 2);
533        assert_eq!(
534            package.resource_ids(),
535            vec![required.resource_id(), optional.resource_id()]
536        );
537        assert!(ContentStructure::ordered_parts(vec![optional.clone()]).is_err());
538        assert!(ContentStructure::package(vec![optional]).is_err());
539        assert!(ContentStructure::package(vec![required.clone(), required]).is_err());
540    }
541}