imferno-core 2.0.0

SMPTE ST 2067 IMF parser and validator
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! Unified IMF report — the single JSON document for UI consumption
//!
//! Combines package metadata, validation, and structural analysis into one structure.
//! Also provides `format_report()` for pretty-printing to a terminal.

use crate::cpl::SequenceAccess;
use crate::diagnostics::{Severity, ValidationReport};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt::Write;
#[cfg(feature = "typescript")]
use ts_rs::TS;

// ── Report structs ───────────────────────────────────────────────────────────

#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export, rename_all = "camelCase"))]
pub struct ImfReport {
    pub package: PackageSummary,
    pub cpls: Vec<CplReport>,
    pub validation: ValidationReport,
}

#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export, rename_all = "camelCase"))]
pub struct CplReport {
    pub id: String,
    pub title: String,
    /// Application profile, e.g. "App2E_2021", "App2E_2014", "App5"
    pub application_profile: Option<String>,
    /// CPL-level edit rate, e.g. "24000/1001"
    pub edit_rate: Option<String>,
    /// Number of segments in this CPL
    pub segment_count: usize,
    /// Timecode start address, e.g. "01:00:00:00"
    pub timecode_start: Option<String>,
    /// True if this CPL references track files not present in the current package (supplemental IMP)
    pub is_supplemental: bool,
    /// Track file UUIDs referenced in this CPL that are not in the current package's AssetMap.
    /// These must be resolved from an ancestor package.
    pub unresolved_ancestor_asset_ids: Vec<String>,
    pub markers: Vec<CplMarker>,
    /// Virtual tracks (sequences) merged across all segments
    pub sequences: Vec<CplSequence>,
}

#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export, rename_all = "camelCase"))]
pub struct CplMarker {
    pub label: String,
    pub offset: u64,
    pub annotation: Option<String>,
}

#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export, rename_all = "camelCase"))]
pub struct CplSequence {
    /// Sequence type: "MainImage", "MainAudio", "Subtitles", etc.
    pub r#type: String,
    pub id: String,
    pub track_id: String,
    pub resources: Vec<CplResource>,
}

#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export, rename_all = "camelCase"))]
pub struct CplResource {
    pub id: String,
    /// Edit rate as "N/D" string, e.g. "24000/1001"
    pub edit_rate: Option<String>,
    pub intrinsic_duration: u64,
    pub source_duration: Option<u64>,
    pub entry_point: Option<u64>,
    pub source_encoding: Option<String>,
    pub track_file_id: Option<String>,
}

#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export, rename_all = "camelCase"))]
pub struct PackageSummary {
    pub asset_map_id: String,
    pub volume_index: u32,
    pub asset_count: usize,
    pub cpl_count: usize,
    pub issue_date: String,
    pub issuer: Option<String>,
    pub creator: Option<String>,
    pub pkl_count: usize,
    pub scm_count: usize,
    pub sidecar_count: usize,
    pub unreferenced_assets: Vec<UnreferencedAsset>,
}

#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "typescript", derive(TS))]
#[cfg_attr(feature = "typescript", ts(export, rename_all = "camelCase"))]
pub struct UnreferencedAsset {
    pub id: String,
    pub path: String,
}

// ── build_report ─────────────────────────────────────────────────────────────

/// Map an ApplicationIdentification URL to a friendly profile name
fn parse_application_profile(url: &str) -> String {
    // SMPTE ST 2067-21 Application #2 Extended profiles
    if url.contains("2067-21") {
        if url.ends_with("2021") || url.contains("/2021") {
            return "App2E_2021".to_string();
        }
        if url.ends_with("2020") || url.contains("/2020") {
            return "App2E_2020".to_string();
        }
        if url.ends_with("2014") || url.contains("/2014") {
            return "App2E_2014".to_string();
        }
        return "App2E".to_string();
    }
    // SMPTE ST 2067-20 Application #2
    if url.contains("2067-20") {
        return "App2".to_string();
    }
    // SMPTE ST 2067-50 Application #5
    if url.contains("2067-50") || url.contains("2067-5/") {
        return "App5".to_string();
    }
    // Fallback: return the URL tail after the last '/'
    url.rsplit('/').next().unwrap_or(url).to_string()
}

/// Map a single resource to a CplResource, falling back to the CPL edit rate
fn map_resource(r: &crate::cpl::Resource, cpl_er: &Option<String>) -> CplResource {
    CplResource {
        id: r.id.to_string(),
        edit_rate: r
            .edit_rate
            .as_ref()
            .map(|er| format!("{}/{}", er.numerator, er.denominator))
            .or_else(|| cpl_er.clone()),
        intrinsic_duration: r.intrinsic_duration,
        source_duration: r.source_duration,
        entry_point: r.entry_point,
        source_encoding: r.source_encoding.as_ref().map(|u| u.to_string()),
        track_file_id: r.track_file_id.as_ref().map(|u| u.to_string()),
    }
}

/// Merge sequences of one type into the track map, accumulating resources by track_id
fn merge_sequences(
    track_map: &mut HashMap<String, CplSequence>,
    type_name: &str,
    sequences: &[impl SequenceAccess],
    cpl_er: &Option<String>,
) {
    for seq in sequences {
        let tid = seq.track_id().to_string();
        let resources: Vec<CplResource> = seq
            .resource_list()
            .resources
            .iter()
            .map(|r| map_resource(r, cpl_er))
            .collect();
        if let Some(existing) = track_map.get_mut(&tid) {
            existing.resources.extend(resources);
        } else {
            track_map.insert(
                tid.clone(),
                CplSequence {
                    r#type: type_name.to_string(),
                    id: seq.id().to_string(),
                    track_id: tid,
                    resources,
                },
            );
        }
    }
}

/// Extract all virtual tracks from a CPL, merged across segments
fn extract_sequences(cpl: &crate::cpl::CompositionPlaylist) -> (Option<String>, Vec<CplSequence>) {
    let edit_rate = cpl
        .edit_rate
        .as_ref()
        .map(|er| format!("{}/{}", er.numerator, er.denominator));

    let mut track_map: HashMap<String, CplSequence> = HashMap::new();

    for seg in &cpl.segment_list.segments {
        let sl = &seg.sequence_list;
        merge_sequences(
            &mut track_map,
            "MainImage",
            &sl.main_image_sequences,
            &edit_rate,
        );
        merge_sequences(
            &mut track_map,
            "MainAudio",
            &sl.main_audio_sequences,
            &edit_rate,
        );
        merge_sequences(
            &mut track_map,
            "Subtitles",
            &sl.subtitles_sequences,
            &edit_rate,
        );
        merge_sequences(
            &mut track_map,
            "HearingImpairedCaptions",
            &sl.hearing_impaired_captions_sequences,
            &edit_rate,
        );
        merge_sequences(
            &mut track_map,
            "ForcedNarrative",
            &sl.forced_narrative_sequences,
            &edit_rate,
        );
        merge_sequences(&mut track_map, "IAB", &sl.iab_sequences, &edit_rate);
        merge_sequences(&mut track_map, "ISXD", &sl.isxd_sequences, &edit_rate);
    }

    (edit_rate, track_map.into_values().collect())
}

/// Collect all TrackFileIds referenced in a CPL across all sequence types
fn collect_track_file_ids(cpl: &crate::cpl::CompositionPlaylist) -> Vec<String> {
    let mut ids = Vec::new();
    for seg in &cpl.segment_list.segments {
        let sl = &seg.sequence_list;
        for seq in &sl.main_image_sequences {
            for r in &seq.resource_list.resources {
                if let Some(ref id) = r.track_file_id {
                    ids.push(id.to_string());
                }
            }
        }
        for seq in &sl.main_audio_sequences {
            for r in &seq.resource_list.resources {
                if let Some(ref id) = r.track_file_id {
                    ids.push(id.to_string());
                }
            }
        }
        for seq in &sl.iab_sequences {
            for r in &seq.resource_list.resources {
                if let Some(ref id) = r.track_file_id {
                    ids.push(id.to_string());
                }
            }
        }
        for seq in &sl.isxd_sequences {
            for r in &seq.resource_list.resources {
                if let Some(ref id) = r.track_file_id {
                    ids.push(id.to_string());
                }
            }
        }
        for seq in &sl.subtitles_sequences {
            for r in &seq.resource_list.resources {
                if let Some(ref id) = r.track_file_id {
                    ids.push(id.to_string());
                }
            }
        }
        for seq in &sl.hearing_impaired_captions_sequences {
            for r in &seq.resource_list.resources {
                if let Some(ref id) = r.track_file_id {
                    ids.push(id.to_string());
                }
            }
        }
        for seq in &sl.forced_narrative_sequences {
            for r in &seq.resource_list.resources {
                if let Some(ref id) = r.track_file_id {
                    ids.push(id.to_string());
                }
            }
        }
    }
    ids
}

/// Build a full ImfReport from a package, with optional ancestor package for supplemental IMPs
pub fn build_report(
    package: &super::Imferno,
    options: &super::ValidationOptions,
    ancestor: Option<&super::Imferno>,
) -> Result<ImfReport, String> {
    // Unreferenced assets
    let unreferenced_assets: Vec<UnreferencedAsset> = package
        .unreferenced_assets()
        .iter()
        .map(|a| {
            let path = a
                .chunk_list
                .chunks
                .first()
                .map(|c| c.path.as_str())
                .unwrap_or("")
                .to_string();
            UnreferencedAsset {
                id: a.id.to_string(),
                path,
            }
        })
        .collect();

    // SCM counts
    let scm_count = package.sidecar_composition_maps.len();
    let sidecar_count: usize = package
        .sidecar_composition_maps
        .values()
        .map(|s| s.sidecar_assets.len())
        .sum();

    let pkg_summary = PackageSummary {
        asset_map_id: package.asset_map.id.to_string(),
        volume_index: package.volume_index.index,
        asset_count: package.asset_map.asset_list.assets.len(),
        cpl_count: package.composition_playlists.len(),
        issue_date: package.asset_map.issue_date.clone(),
        issuer: package.asset_map.issuer.clone(),
        creator: package.asset_map.creator.clone(),
        pkl_count: package.packing_lists.len(),
        scm_count,
        sidecar_count,
        unreferenced_assets,
    };

    // CPL reports
    let mut cpls = Vec::new();
    for cpl in package.composition_playlists.values() {
        let cpl_track_ids = collect_track_file_ids(cpl);
        let unresolved_ancestor_asset_ids: Vec<String> = cpl_track_ids
            .iter()
            .filter(|id| {
                package.get_asset_path_str(id).is_none()
                    && ancestor.is_none_or(|a| a.get_asset_path_str(id).is_none())
            })
            .cloned()
            .collect();
        let is_supplemental = cpl_track_ids
            .iter()
            .any(|id| package.get_asset_path_str(id).is_none());

        let markers: Vec<CplMarker> = cpl
            .segment_list
            .segments
            .iter()
            .flat_map(|seg| seg.sequence_list.marker_sequences.iter())
            .flat_map(|ms| ms.resource_list.resources.iter())
            .flat_map(|res| res.markers.iter())
            .map(|m| CplMarker {
                label: m.label.to_string(),
                offset: m.offset,
                annotation: m.annotation.clone().filter(|a| !a.is_empty()),
            })
            .collect();

        let application_profile = cpl
            .extension_properties
            .as_ref()
            .and_then(|ep| ep.application_identification.as_ref())
            .map(|url| parse_application_profile(url));

        let segment_count = cpl.segment_list.segments.len();

        let timecode_start = cpl
            .composition_timecode
            .as_ref()
            .and_then(|tc| tc.timecode_start_address.clone());

        let (edit_rate, sequences) = extract_sequences(cpl);

        cpls.push(CplReport {
            id: cpl.id.to_string(),
            title: cpl.content_title.text.clone(),
            application_profile,
            edit_rate,
            segment_count,
            timecode_start,
            is_supplemental,
            unresolved_ancestor_asset_ids,
            markers,
            sequences,
        });
    }

    // Validation
    let validation = package.validate(options);

    Ok(ImfReport {
        package: pkg_summary,
        cpls,
        validation,
    })
}

// ── ANSI colour helpers ──────────────────────────────────────────────────────

fn c_red(s: &str, on: bool) -> String {
    if on {
        format!("\x1b[31m{}\x1b[0m", s)
    } else {
        s.to_string()
    }
}
fn c_yellow(s: &str, on: bool) -> String {
    if on {
        format!("\x1b[33m{}\x1b[0m", s)
    } else {
        s.to_string()
    }
}
fn c_cyan(s: &str, on: bool) -> String {
    if on {
        format!("\x1b[36m{}\x1b[0m", s)
    } else {
        s.to_string()
    }
}
fn c_green(s: &str, on: bool) -> String {
    if on {
        format!("\x1b[32m{}\x1b[0m", s)
    } else {
        s.to_string()
    }
}
fn c_bold(s: &str, on: bool) -> String {
    if on {
        format!("\x1b[1m{}\x1b[0m", s)
    } else {
        s.to_string()
    }
}
fn c_dim(s: &str, on: bool) -> String {
    if on {
        format!("\x1b[2m{}\x1b[0m", s)
    } else {
        s.to_string()
    }
}

// ── format_report ────────────────────────────────────────────────────────────

/// Render an `ImfReport` as a human-readable, optionally ANSI-coloured string.
pub fn format_report(report: &ImfReport, color: bool) -> String {
    let mut out = String::new();
    let pkg = &report.package;

    // Package structure
    let _ = writeln!(out, "  {}  VOLINDEX.xml found", c_green("ok", color));
    let _ = writeln!(out, "  {}  ASSETMAP.xml found", c_green("ok", color));
    let _ = writeln!(
        out,
        "  {}  {} assets mapped",
        c_green("ok", color),
        pkg.asset_count
    );
    let _ = writeln!(
        out,
        "  {}  {} CPL(s) parsed",
        c_green("ok", color),
        pkg.cpl_count
    );

    // SCMs
    if pkg.scm_count > 0 {
        let _ = writeln!(
            out,
            "  {}  {} SCM(s) parsed, {} sidecar asset(s) declared",
            c_green("ok", color),
            pkg.scm_count,
            pkg.sidecar_count
        );
    }

    // Unreferenced assets
    if !pkg.unreferenced_assets.is_empty() {
        let _ = writeln!(
            out,
            "  {}  {} unreferenced asset(s)",
            c_yellow("info", color),
            pkg.unreferenced_assets.len()
        );
        for asset in &pkg.unreferenced_assets {
            let _ = writeln!(out, "        {}", c_dim(&asset.path, color));
        }
    }

    // Validation findings
    let all_issues: Vec<_> = report
        .validation
        .critical
        .iter()
        .chain(report.validation.errors.iter())
        .chain(report.validation.warnings.iter())
        .chain(report.validation.info.iter())
        .collect();

    if !all_issues.is_empty() {
        let _ = writeln!(out, "{}", c_bold("Validation findings:", color));

        for issue in &all_issues {
            let (label, colorize): (&str, fn(&str, bool) -> String) = match issue.severity {
                Severity::Critical => ("error", c_red),
                Severity::Error => ("error", c_red),
                Severity::Warning => ("warning", c_yellow),
                Severity::Info => ("info", c_cyan),
            };
            let location = if let Some(ref c) = issue.location.cpl_id {
                c_dim(&format!(" [CPL:{}]", &c[..c.len().min(8)]), color)
            } else if let Some(ref f) = issue.location.file {
                let fname = f.file_name().and_then(|n| n.to_str()).unwrap_or("?");
                c_dim(&format!(" [{}]", fname), color)
            } else {
                String::new()
            };
            let _ = writeln!(
                out,
                "  {} {}{} {}",
                colorize(&format!("{:<7}", label), color),
                c_bold(&issue.code, color),
                location,
                issue.message,
            );
            if let Some(ref s) = issue.suggestion {
                let _ = writeln!(out, "          {} {}", c_dim("", color), c_dim(s, color));
            }
        }
    }

    // Summary line
    let total_errors = report.validation.critical.len() + report.validation.errors.len();
    let total_warnings = report.validation.warnings.len();
    if total_errors > 0 {
        let mut reasons = Vec::new();
        reasons.push(format!("{} error(s)", total_errors));
        if total_warnings > 0 {
            reasons.push(format!("{} warning(s)", total_warnings));
        }
        let _ = writeln!(
            out,
            "{} {}",
            c_red("failed", color),
            c_bold(&reasons.join(", "), color)
        );
    } else if total_warnings > 0 {
        let _ = writeln!(
            out,
            "{}",
            c_yellow(&format!("valid  {} warning(s)", total_warnings), color)
        );
    } else {
        let _ = writeln!(out, "{}", c_green("valid", color));
    }

    out
}