imferno-core 2.2.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
//! SMPTE ST 2067-201 IAB Level 0 Plug-in validator.
//!
//! Implements the IAB (Immersive Audio Bitstream) plug-in constraints for
//! SMPTE ST 2067-201:2019 and ST 2067-201:2021.
//!
//! Both plug-in validators run App2E base validation (ST 2067-21) internally,
//! then apply IAB-specific descriptor and sequence constraints.

// codes live in iab_codes.rs (declared from validation/mod.rs)

use std::collections::HashSet;

use crate::cpl::{CompositionPlaylist, McaTagSymbol};
use crate::diagnostics::{Category, Location, Severity, ValidationIssue};
use crate::validation::{App2E2021, ConstraintsValidator};

use crate::validation::iab_codes::{self as iab_codes, IabCode};

// ── Public API ───────────────────────────────────────────────────────────────

/// ST 2067-201:2019 IAB Level 0 Plug-in validator.
///
/// Runs App2E base validation plus ST 2067-201:2019-specific IAB constraints.
/// In the 2019 edition ChannelCount shall be the distinguished value 0.
pub struct AppIabPlugin2019;

impl ConstraintsValidator for AppIabPlugin2019 {
    fn spec_id(&self) -> &str {
        "ST 2067-201:2019 (IAB Level 0 Plug-in)"
    }

    fn validate_cpl(&self, cpl: &CompositionPlaylist) -> Vec<ValidationIssue> {
        let mut issues = Vec::new();
        App2E2021.validate_all(cpl, true, &mut issues);
        validate_iab_descriptors(cpl, iab_codes::St2067_201_2019::for_code, true, &mut issues);
        validate_iab_sequences(cpl, iab_codes::St2067_201_2019::for_code, &mut issues);
        issues
    }
}

/// ST 2067-201:2021 IAB Level 0 Plug-in validator.
///
/// Runs App2E base validation plus ST 2067-201:2021-specific IAB constraints.
/// In the 2021 edition ChannelCount is ignored (not checked).
pub struct AppIabPlugin2021;

impl ConstraintsValidator for AppIabPlugin2021 {
    fn spec_id(&self) -> &str {
        "ST 2067-201:2021 (IAB Level 0 Plug-in)"
    }

    fn validate_cpl(&self, cpl: &CompositionPlaylist) -> Vec<ValidationIssue> {
        let mut issues = Vec::new();
        App2E2021.validate_all(cpl, true, &mut issues);
        validate_iab_descriptors(
            cpl,
            iab_codes::St2067_201_2021::for_code,
            false,
            &mut issues,
        );
        validate_iab_sequences(cpl, iab_codes::St2067_201_2021::for_code, &mut issues);
        issues
    }
}

// ── Namespace URIs ────────────────────────────────────────────────────────────

pub const URI_2019: &str = "http://www.smpte-ra.org/ns/2067-201/2019";
pub const URI_2019_SCHEMAS: &str = "http://www.smpte-ra.org/schemas/2067-201/2019";
pub const URI_2021: &str = "http://www.smpte-ra.org/ns/2067-201/2021";
pub const URI_2021_SCHEMAS: &str = "http://www.smpte-ra.org/schemas/2067-201/2021";

// ── Internal helpers ──────────────────────────────────────────────────────────

/// Normalize a SMPTE UL by zeroing byte 8 (ST 298M version byte) before comparison.
fn ul_matches(provided: &str, canonical: &str) -> bool {
    fn parse_ul(s: &str) -> Option<[u8; 16]> {
        let hex = s.strip_prefix("urn:smpte:ul:")?;
        let groups: Vec<&str> = hex.split('.').collect();
        if groups.len() != 4 {
            return None;
        }
        let mut bytes = [0u8; 16];
        let mut idx = 0;
        for group in &groups {
            if group.len() != 8 {
                return None;
            }
            for i in (0..8).step_by(2) {
                bytes[idx] = u8::from_str_radix(&group[i..i + 2], 16).ok()?;
                idx += 1;
            }
        }
        bytes[7] = 0; // zero byte 8 (ST 298M: version byte shall be ignored)
        Some(bytes)
    }
    match (parse_ul(provided), parse_ul(canonical)) {
        (Some(a), Some(b)) => a == b,
        _ => false,
    }
}

/// ST 2067-201 §5.9: Validate IABEssenceDescriptor constraints.
///
/// `code`: edition dispatch function (e.g. `St2067_201_2019::for_code`).
/// `check_channel_count`: true for 2019 (ChannelCount shall be 0);
///                        false for 2021 (ChannelCount is ignored).
fn validate_iab_descriptors(
    cpl: &CompositionPlaylist,
    code: fn(IabCode) -> &'static str,
    check_channel_count: bool,
    issues: &mut Vec<ValidationIssue>,
) {
    const IAB_CONTAINER_FORMAT: &str = "urn:smpte:ul:060e2b34.0401010d.0d010301.021d0101";
    const IAB_SOUND_COMPRESSION: &str = "urn:smpte:ul:060e2b34.04010105.0e090604.00000000";
    const IAB_MCA_LABEL_DICT_ID: &str = "urn:smpte:ul:060e2b34.0401010d.03020221.00000000";

    let edl = match &cpl.essence_descriptor_list {
        Some(edl) => edl,
        None => return,
    };

    for ed in &edl.essence_descriptors {
        let iab = match &ed.iab_essence_descriptor {
            Some(iab) => iab,
            None => continue,
        };

        let ed_loc = Location::new()
            .with_cpl(cpl.id)
            .with_path(format!("EssenceDescriptor/{}", ed.id));

        // §5.9: Codec item shall NOT be present.
        if iab.codec.is_some() {
            issues.push(
                ValidationIssue::new(
                    Severity::Error,
                    Category::Audio,
                    code(IabCode::CodecForbidden),
                    format!(
                        "IABEssenceDescriptor {}: Codec item shall not be present \
                         (ST 2067-201 §5.9)",
                        ed.id,
                    ),
                )
                .with_location(ed_loc.clone()),
            );
        }

        // §5.9: ElectrospatialFormulation shall NOT be present.
        if iab.electrospatial_formulation.is_some() {
            issues.push(
                ValidationIssue::new(
                    Severity::Error,
                    Category::Audio,
                    code(IabCode::ElectrospatialFormulationForbidden),
                    format!(
                        "IABEssenceDescriptor {}: ElectrospatialFormulation shall not be \
                         present (ST 2067-201 §5.9)",
                        ed.id,
                    ),
                )
                .with_location(ed_loc.clone()),
            );
        }

        // §5.9: QuantizationBits shall be 24.
        match iab.quantization_bits {
            None => {
                issues.push(
                    ValidationIssue::new(
                        Severity::Warning,
                        Category::Audio,
                        code(IabCode::QuantizationBitsMissing),
                        format!(
                            "IABEssenceDescriptor {}: QuantizationBits is missing; \
                             ST 2067-201 §5.9 requires 24",
                            ed.id,
                        ),
                    )
                    .with_location(ed_loc.clone()),
                );
            }
            Some(qb) if qb != 24 => {
                issues.push(
                    ValidationIssue::new(
                        Severity::Error,
                        Category::Audio,
                        code(IabCode::QuantizationBitsInvalid),
                        format!(
                            "IABEssenceDescriptor {}: QuantizationBits {} shall be 24 \
                             (ST 2067-201 §5.9)",
                            ed.id, qb,
                        ),
                    )
                    .with_location(ed_loc.clone()),
                );
            }
            _ => {}
        }

        // §5.3: ContainerFormat shall be the IAB essence container UL.
        match &iab.container_format {
            None => {
                issues.push(
                    ValidationIssue::new(
                        Severity::Warning,
                        Category::Audio,
                        code(IabCode::ContainerFormatMissing),
                        format!(
                            "IABEssenceDescriptor {}: ContainerFormat is missing; \
                             should be {IAB_CONTAINER_FORMAT}",
                            ed.id,
                        ),
                    )
                    .with_location(ed_loc.clone()),
                );
            }
            Some(cf) if !ul_matches(cf, IAB_CONTAINER_FORMAT) => {
                issues.push(
                    ValidationIssue::new(
                        Severity::Error,
                        Category::Audio,
                        code(IabCode::EssenceContainerInvalid),
                        format!(
                            "IABEssenceDescriptor {}: ContainerFormat `{cf}` is not the \
                             required IAB container UL {IAB_CONTAINER_FORMAT} \
                             (ST 2067-201 §5.3)",
                            ed.id,
                        ),
                    )
                    .with_location(ed_loc.clone()),
                );
            }
            _ => {}
        }

        // §5.9: AudioSampleRate shall be 48000/1.
        match &iab.audio_sample_rate {
            None => {
                issues.push(
                    ValidationIssue::new(
                        Severity::Warning,
                        Category::Audio,
                        code(IabCode::AudioSamplingRateMissing),
                        format!(
                            "IABEssenceDescriptor {}: AudioSampleRate is missing; \
                             ST 2067-201 §5.9 requires 48000/1",
                            ed.id,
                        ),
                    )
                    .with_location(ed_loc.clone()),
                );
            }
            Some(rate) if rate.numerator != 48000 || rate.denominator != 1 => {
                issues.push(
                    ValidationIssue::new(
                        Severity::Error,
                        Category::Audio,
                        code(IabCode::AudioSamplingRateInvalid),
                        format!(
                            "IABEssenceDescriptor {}: AudioSampleRate {}/{} is not 48000/1 \
                             (ST 2067-201 §5.9)",
                            ed.id, rate.numerator, rate.denominator,
                        ),
                    )
                    .with_location(ed_loc.clone()),
                );
            }
            _ => {}
        }

        // §5.9: SoundCompression shall be the IAB compression UL.
        match &iab.sound_compression {
            None => {
                issues.push(
                    ValidationIssue::new(
                        Severity::Warning,
                        Category::Audio,
                        code(IabCode::SoundCompressionMissing),
                        format!(
                            "IABEssenceDescriptor {}: SoundCompression is missing; \
                             should be {IAB_SOUND_COMPRESSION}",
                            ed.id,
                        ),
                    )
                    .with_location(ed_loc.clone()),
                );
            }
            Some(sc) if !ul_matches(sc, IAB_SOUND_COMPRESSION) => {
                issues.push(
                    ValidationIssue::new(
                        Severity::Error,
                        Category::Audio,
                        code(IabCode::SoundCompressionInvalid),
                        format!(
                            "IABEssenceDescriptor {}: SoundCompression `{sc}` is not the \
                             required IAB UL {IAB_SOUND_COMPRESSION} (ST 2067-201 §5.9)",
                            ed.id,
                        ),
                    )
                    .with_location(ed_loc.clone()),
                );
            }
            _ => {}
        }

        // §5.9: ChannelCount shall be the distinguished value 0 (2019 only).
        if check_channel_count {
            match iab.channel_count {
                Some(cc) if cc != 0 => {
                    issues.push(
                        ValidationIssue::new(
                            Severity::Error,
                            Category::Audio,
                            code(IabCode::ChannelCountNotZero),
                            format!(
                                "IABEssenceDescriptor {}: ChannelCount {cc} shall be the \
                                 distinguished value 0 (ST 2067-201 §5.9, ST 377-1 Annex F.5)",
                                ed.id,
                            ),
                        )
                        .with_location(ed_loc.clone()),
                    );
                }
                _ => {}
            }
        }

        // §5.9: IABSoundfieldLabelSubDescriptor shall be present.
        let soundfield = iab
            .sub_descriptors
            .as_ref()
            .and_then(|sd| sd.iab_soundfield_label_sub_descriptor.as_ref());

        if soundfield.is_none() {
            issues.push(
                ValidationIssue::new(
                    Severity::Error,
                    Category::Audio,
                    code(IabCode::SubDescriptorMissing),
                    format!(
                        "IABEssenceDescriptor {}: IABSoundfieldLabelSubDescriptor shall be \
                         present (ST 2067-201 §5.9)",
                        ed.id,
                    ),
                )
                .with_location(ed_loc.clone()),
            );
            continue; // remaining sub-descriptor checks not applicable
        }

        let sf = soundfield.unwrap();
        let sub_loc = Location::new().with_cpl(cpl.id).with_path(format!(
            "EssenceDescriptor/{}/IABSoundfieldLabelSubDescriptor",
            ed.id
        ));

        // §5.9: MCATagSymbol shall be "IAB".
        match &sf.mca_tag_symbol {
            None => {
                issues.push(
                    ValidationIssue::new(
                        Severity::Error,
                        Category::Audio,
                        code(IabCode::MCATagSymbolMissing),
                        format!(
                            "IABEssenceDescriptor {}: IABSoundfieldLabelSubDescriptor \
                             MCATagSymbol shall be \"IAB\" (ST 2067-201 §5.9)",
                            ed.id,
                        ),
                    )
                    .with_location(sub_loc.clone()),
                );
            }
            Some(sym) if *sym != McaTagSymbol::Iab => {
                issues.push(
                    ValidationIssue::new(
                        Severity::Error,
                        Category::Audio,
                        code(IabCode::MCATagSymbolInvalid),
                        format!(
                            "IABEssenceDescriptor {}: IABSoundfieldLabelSubDescriptor \
                             MCATagSymbol shall be \"IAB\", got \"{sym:?}\" \
                             (ST 2067-201 §5.9)",
                            ed.id,
                        ),
                    )
                    .with_location(sub_loc.clone()),
                );
            }
            _ => {}
        }

        // §5.9: MCATagName shall be "IAB".
        match sf.mca_tag_name.as_deref() {
            None => {
                issues.push(
                    ValidationIssue::new(
                        Severity::Error,
                        Category::Audio,
                        code(IabCode::MCATagNameMissing),
                        format!(
                            "IABEssenceDescriptor {}: IABSoundfieldLabelSubDescriptor \
                             MCATagName shall be \"IAB\" (ST 2067-201 §5.9)",
                            ed.id,
                        ),
                    )
                    .with_location(sub_loc.clone()),
                );
            }
            Some(name) if name != "IAB" => {
                issues.push(
                    ValidationIssue::new(
                        Severity::Error,
                        Category::Audio,
                        code(IabCode::MCATagNameInvalid),
                        format!(
                            "IABEssenceDescriptor {}: IABSoundfieldLabelSubDescriptor \
                             MCATagName shall be \"IAB\", got \"{name}\" \
                             (ST 2067-201 §5.9)",
                            ed.id,
                        ),
                    )
                    .with_location(sub_loc.clone()),
                );
            }
            _ => {}
        }

        // §5.9: MCALabelDictionaryID shall be the IAB label UL.
        match sf.mca_label_dictionary_id.as_deref() {
            None => {
                issues.push(
                    ValidationIssue::new(
                        Severity::Error,
                        Category::Audio,
                        code(IabCode::MCALabelDictionaryIDMissing),
                        format!(
                            "IABEssenceDescriptor {}: IABSoundfieldLabelSubDescriptor \
                             MCALabelDictionaryID is missing; shall be {IAB_MCA_LABEL_DICT_ID} \
                             (ST 2067-201 §5.9)",
                            ed.id,
                        ),
                    )
                    .with_location(sub_loc.clone()),
                );
            }
            Some(id) if !ul_matches(id, IAB_MCA_LABEL_DICT_ID) => {
                issues.push(
                    ValidationIssue::new(
                        Severity::Error,
                        Category::Audio,
                        code(IabCode::MCALabelDictionaryIDInvalid),
                        format!(
                            "IABEssenceDescriptor {}: IABSoundfieldLabelSubDescriptor \
                             MCALabelDictionaryID `{id}` shall be {IAB_MCA_LABEL_DICT_ID} \
                             (ST 2067-201 §5.9)",
                            ed.id,
                        ),
                    )
                    .with_location(sub_loc.clone()),
                );
            }
            _ => {}
        }
    }
}

/// ST 2067-201 §6.2: Validate IABSequence constraints at the CPL timeline level.
///
/// - Each segment with an IABSequence shall also have a MainAudioSequence.
/// - Each IABSequence shall contain at least one Resource.
/// - Each IABSequence Resource.SourceEncoding shall reference an IABEssenceDescriptor.
fn validate_iab_sequences(
    cpl: &CompositionPlaylist,
    code: fn(IabCode) -> &'static str,
    issues: &mut Vec<ValidationIssue>,
) {
    let iab_ed_ids: HashSet<String> = cpl
        .essence_descriptor_list
        .as_ref()
        .map(|edl| {
            edl.essence_descriptors
                .iter()
                .filter(|ed| ed.iab_essence_descriptor.is_some())
                .map(|ed| ed.id.to_string())
                .collect()
        })
        .unwrap_or_default();

    for segment in &cpl.segment_list.segments {
        let sl = &segment.sequence_list;

        if sl.iab_sequences.is_empty() {
            continue;
        }

        let seg_loc = Location::new()
            .with_cpl(cpl.id)
            .with_path(format!("Segment/{}", segment.id));

        // §6.2: MainAudioSequence shall accompany IABSequence in the same segment.
        if sl.main_audio_sequences.is_empty() {
            issues.push(
                ValidationIssue::new(
                    Severity::Error,
                    Category::Audio,
                    code(IabCode::MainAudioMissing),
                    format!(
                        "Segment {}: IABSequence present but no MainAudioSequence found; \
                         ST 2067-201 §6.2 requires a MainAudioSequence alongside IABSequence",
                        segment.id,
                    ),
                )
                .with_location(seg_loc.clone()),
            );
        }

        for iab_seq in &sl.iab_sequences {
            let seq_loc = Location::new()
                .with_cpl(cpl.id)
                .with_path(format!("Segment/{}/IABSequence/{}", segment.id, iab_seq.id));

            // §6.2: IABSequence shall contain at least one Resource.
            if iab_seq.resource_list.resources.is_empty() {
                issues.push(
                    ValidationIssue::new(
                        Severity::Error,
                        Category::Audio,
                        code(IabCode::IABSequenceNoResources),
                        format!(
                            "IABSequence {}: shall contain at least one Resource \
                             (ST 2067-201 §6.2)",
                            iab_seq.id,
                        ),
                    )
                    .with_location(seq_loc.clone()),
                );
            }

            // §6.2: Each Resource.SourceEncoding shall reference an IABEssenceDescriptor.
            for resource in &iab_seq.resource_list.resources {
                if let Some(ref se) = resource.source_encoding {
                    let se_str = se.to_string();
                    if !iab_ed_ids.contains(&se_str) {
                        issues.push(
                            ValidationIssue::new(
                                Severity::Error,
                                Category::Audio,
                                code(IabCode::IABSequenceSourceEncodingInvalid),
                                format!(
                                    "IABSequence {}: Resource {} SourceEncoding {se_str} \
                                     does not reference an IABEssenceDescriptor \
                                     (ST 2067-201 §6.2)",
                                    iab_seq.id, resource.id,
                                ),
                            )
                            .with_location(seq_loc.clone()),
                        );
                    }
                }
            }
        }
    }
}