oximedia-aaf 0.1.2

Advanced Authoring Format (AAF) support for OxiMedia - SMPTE ST 377-1 compliant
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
//! AAF Object Model
//!
//! This module implements the AAF object model including:
//! - Header
//! - Mobs (Master Mob, Source Mob, Composition Mob)
//! - Mob Slots (Timeline, Event)
//! - Segments and Components
//! - Transitions and Effects
//! - Parameters
//! - Object reference resolution
//! - Property traversal

use crate::dictionary::{Auid, Dictionary, TypeDefinition};
use crate::structured_storage::StorageReader;
use crate::timeline::{EditRate, Position};
use crate::{ContentStorage, Result};
use byteorder::{LittleEndian, ReadBytesExt};
use std::collections::HashMap;
use std::io::{Cursor, Read, Seek};
use uuid::Uuid;

/// AAF file header
#[derive(Debug, Clone)]
pub struct Header {
    /// File version
    pub major_version: u16,
    pub minor_version: u16,
    /// Byte order (0xFFFE for little-endian)
    pub byte_order: u16,
    /// Last modified timestamp
    pub last_modified: u64,
    /// Object model version
    pub object_model_version: u32,
    /// Operational pattern
    pub operational_pattern: Auid,
    /// Essence containers
    pub essence_containers: Vec<Auid>,
}

impl Header {
    /// Create a new header with default values
    #[must_use]
    pub fn new() -> Self {
        Self {
            major_version: 1,
            minor_version: 1,
            byte_order: 0xFFFE,
            last_modified: 0,
            object_model_version: 1,
            operational_pattern: Auid::null(),
            essence_containers: Vec::new(),
        }
    }

    /// Get the AAF version as a string
    #[must_use]
    pub fn version_string(&self) -> String {
        format!("{}.{}", self.major_version, self.minor_version)
    }
}

impl Default for Header {
    fn default() -> Self {
        Self::new()
    }
}

/// AAF Mob (Master, Source, or Composition)
#[derive(Debug, Clone)]
pub struct Mob {
    /// Mob ID (UUID)
    pub mob_id: Uuid,
    /// Mob name
    pub name: String,
    /// Mob slots
    pub slots: Vec<MobSlot>,
    /// Mob type
    pub mob_type: MobType,
    /// Creation time
    pub creation_time: Option<u64>,
    /// Modified time
    pub modified_time: Option<u64>,
    /// User comments
    pub comments: HashMap<String, String>,
    /// Attributes
    pub attributes: HashMap<String, PropertyValue>,
}

impl Mob {
    /// Create a new mob
    #[must_use]
    pub fn new(mob_id: Uuid, name: String, mob_type: MobType) -> Self {
        Self {
            mob_id,
            name,
            slots: Vec::new(),
            mob_type,
            creation_time: None,
            modified_time: None,
            comments: HashMap::new(),
            attributes: HashMap::new(),
        }
    }

    /// Get mob ID
    #[must_use]
    pub fn mob_id(&self) -> Uuid {
        self.mob_id
    }

    /// Get mob name
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get a mutable reference to the mob ID.
    ///
    /// Useful for reassigning the ID when deep-cloning a mob.
    pub fn mob_id_mut(&mut self) -> &mut Uuid {
        &mut self.mob_id
    }

    /// Get mob type
    #[must_use]
    pub fn mob_type(&self) -> MobType {
        self.mob_type
    }

    /// Check if this is a master mob
    #[must_use]
    pub fn is_master_mob(&self) -> bool {
        matches!(self.mob_type, MobType::Master)
    }

    /// Check if this is a source mob
    #[must_use]
    pub fn is_source_mob(&self) -> bool {
        matches!(self.mob_type, MobType::Source)
    }

    /// Check if this is a composition mob
    #[must_use]
    pub fn is_composition_mob(&self) -> bool {
        matches!(self.mob_type, MobType::Composition)
    }

    /// Get all slots
    #[must_use]
    pub fn slots(&self) -> &[MobSlot] {
        &self.slots
    }

    /// Get slot by ID
    #[must_use]
    pub fn get_slot(&self, slot_id: u32) -> Option<&MobSlot> {
        self.slots.iter().find(|s| s.slot_id == slot_id)
    }

    /// Add a slot
    pub fn add_slot(&mut self, slot: MobSlot) {
        self.slots.push(slot);
    }
}

/// Mob type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MobType {
    /// Master mob
    Master,
    /// Source mob (file or recording)
    Source,
    /// Composition mob
    Composition,
}

/// Mob slot (timeline or event)
#[derive(Debug, Clone)]
pub struct MobSlot {
    /// Slot ID
    pub slot_id: u32,
    /// Slot name
    pub name: String,
    /// Physical track number
    pub physical_track_number: Option<u32>,
    /// Edit rate
    pub edit_rate: EditRate,
    /// Origin (start position)
    pub origin: Position,
    /// Segment
    pub segment: Option<Box<Segment>>,
    /// Slot type
    pub slot_type: SlotType,
}

impl MobSlot {
    /// Create a new timeline mob slot
    #[must_use]
    pub fn new_timeline(slot_id: u32, name: String, edit_rate: EditRate, origin: Position) -> Self {
        Self {
            slot_id,
            name,
            physical_track_number: None,
            edit_rate,
            origin,
            segment: None,
            slot_type: SlotType::Timeline,
        }
    }

    /// Create a new event mob slot
    #[must_use]
    pub fn new_event(slot_id: u32, name: String, edit_rate: EditRate) -> Self {
        Self {
            slot_id,
            name,
            physical_track_number: None,
            edit_rate,
            origin: Position::zero(),
            segment: None,
            slot_type: SlotType::Event,
        }
    }

    /// Get the segment
    #[must_use]
    pub fn segment(&self) -> Option<&Segment> {
        self.segment.as_deref()
    }

    /// Set the segment
    pub fn set_segment(&mut self, segment: Segment) {
        self.segment = Some(Box::new(segment));
    }
}

/// Slot type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SlotType {
    /// Timeline slot
    Timeline,
    /// Event slot
    Event,
    /// Static slot
    Static,
}

/// AAF Segment
#[derive(Debug, Clone)]
pub enum Segment {
    /// Sequence of components
    Sequence(SequenceSegment),
    /// Source clip
    SourceClip(SourceClipSegment),
    /// Filler
    Filler(FillerSegment),
    /// Transition
    Transition(TransitionSegment),
    /// Selector
    Selector(SelectorSegment),
    /// Nested scope
    NestedScope(NestedScopeSegment),
    /// Effect invocation
    OperationGroup(OperationGroupSegment),
}

impl Segment {
    /// Get the length of the segment
    #[must_use]
    pub fn length(&self) -> Option<i64> {
        match self {
            Segment::Sequence(s) => s.length,
            Segment::SourceClip(s) => Some(s.length),
            Segment::Filler(s) => Some(s.length),
            Segment::Transition(s) => Some(s.length),
            Segment::Selector(s) => s.length,
            Segment::NestedScope(s) => s.length,
            Segment::OperationGroup(s) => s.length,
        }
    }

    /// Check if this is a sequence
    #[must_use]
    pub fn is_sequence(&self) -> bool {
        matches!(self, Segment::Sequence(_))
    }

    /// Check if this is a source clip
    #[must_use]
    pub fn is_source_clip(&self) -> bool {
        matches!(self, Segment::SourceClip(_))
    }
}

/// Sequence segment
#[derive(Debug, Clone)]
pub struct SequenceSegment {
    /// Components in the sequence
    pub components: Vec<Component>,
    /// Length (optional, may be calculated)
    pub length: Option<i64>,
}

impl SequenceSegment {
    /// Create a new sequence
    #[must_use]
    pub fn new() -> Self {
        Self {
            components: Vec::new(),
            length: None,
        }
    }

    /// Add a component
    pub fn add_component(&mut self, component: Component) {
        self.components.push(component);
    }

    /// Calculate total length
    #[must_use]
    pub fn calculate_length(&self) -> Option<i64> {
        let mut total = 0i64;
        for comp in &self.components {
            total += comp.length()?;
        }
        Some(total)
    }
}

impl Default for SequenceSegment {
    fn default() -> Self {
        Self::new()
    }
}

/// Source clip segment
#[derive(Debug, Clone)]
pub struct SourceClipSegment {
    /// Length
    pub length: i64,
    /// Start time in source
    pub start_time: Position,
    /// Source mob ID
    pub source_mob_id: Uuid,
    /// Source mob slot ID
    pub source_mob_slot_id: u32,
}

impl SourceClipSegment {
    /// Create a new source clip
    #[must_use]
    pub fn new(
        length: i64,
        start_time: Position,
        source_mob_id: Uuid,
        source_mob_slot_id: u32,
    ) -> Self {
        Self {
            length,
            start_time,
            source_mob_id,
            source_mob_slot_id,
        }
    }
}

/// Filler segment
#[derive(Debug, Clone)]
pub struct FillerSegment {
    /// Length
    pub length: i64,
}

impl FillerSegment {
    /// Create a new filler
    #[must_use]
    pub fn new(length: i64) -> Self {
        Self { length }
    }
}

/// Transition segment
#[derive(Debug, Clone)]
pub struct TransitionSegment {
    /// Length
    pub length: i64,
    /// Cut point
    pub cut_point: Position,
    /// Effect
    pub effect: Option<Box<OperationGroupSegment>>,
}

impl TransitionSegment {
    /// Create a new transition
    #[must_use]
    pub fn new(length: i64, cut_point: Position) -> Self {
        Self {
            length,
            cut_point,
            effect: None,
        }
    }
}

/// Selector segment
#[derive(Debug, Clone)]
pub struct SelectorSegment {
    /// Selected track
    pub selected: u32,
    /// Alternate tracks
    pub alternates: Vec<Segment>,
    /// Length
    pub length: Option<i64>,
}

impl SelectorSegment {
    /// Create a new selector
    #[must_use]
    pub fn new(selected: u32) -> Self {
        Self {
            selected,
            alternates: Vec::new(),
            length: None,
        }
    }
}

/// Nested scope segment
#[derive(Debug, Clone)]
pub struct NestedScopeSegment {
    /// Slots
    pub slots: Vec<MobSlot>,
    /// Length
    pub length: Option<i64>,
}

impl NestedScopeSegment {
    /// Create a new nested scope
    #[must_use]
    pub fn new() -> Self {
        Self {
            slots: Vec::new(),
            length: None,
        }
    }
}

impl Default for NestedScopeSegment {
    fn default() -> Self {
        Self::new()
    }
}

/// Operation group segment (effect invocation)
#[derive(Debug, Clone)]
pub struct OperationGroupSegment {
    /// Operation definition ID
    pub operation_id: Auid,
    /// Input segments
    pub input_segments: Vec<Segment>,
    /// Parameters
    pub parameters: Vec<Parameter>,
    /// Length
    pub length: Option<i64>,
}

impl OperationGroupSegment {
    /// Create a new operation group
    #[must_use]
    pub fn new(operation_id: Auid) -> Self {
        Self {
            operation_id,
            input_segments: Vec::new(),
            parameters: Vec::new(),
            length: None,
        }
    }
}

/// Component (wrapper for segments with data definition)
#[derive(Debug, Clone)]
pub struct Component {
    /// Data definition (picture, sound, timecode, etc.)
    pub data_definition: Auid,
    /// Segment
    pub segment: Segment,
}

impl Component {
    /// Create a new component
    #[must_use]
    pub fn new(data_definition: Auid, segment: Segment) -> Self {
        Self {
            data_definition,
            segment,
        }
    }

    /// Get component length
    #[must_use]
    pub fn length(&self) -> Option<i64> {
        self.segment.length()
    }

    /// Check if this is a picture component
    #[must_use]
    pub fn is_picture(&self) -> bool {
        self.data_definition.is_picture()
    }

    /// Check if this is a sound component
    #[must_use]
    pub fn is_sound(&self) -> bool {
        self.data_definition.is_sound()
    }

    /// Check if this is a timecode component
    #[must_use]
    pub fn is_timecode(&self) -> bool {
        self.data_definition.is_timecode()
    }
}

/// Effect parameter
#[derive(Debug, Clone)]
pub struct Parameter {
    /// Parameter definition ID
    pub definition_id: Auid,
    /// Parameter name
    pub name: String,
    /// Parameter value
    pub value: ParameterValue,
}

impl Parameter {
    /// Create a new parameter
    #[must_use]
    pub fn new(definition_id: Auid, name: String, value: ParameterValue) -> Self {
        Self {
            definition_id,
            name,
            value,
        }
    }
}

/// Parameter value types
#[derive(Debug, Clone)]
pub enum ParameterValue {
    /// Constant value
    Constant(PropertyValue),
    /// Varying value (keyframes)
    Varying(Vec<Keyframe>),
}

/// Keyframe for varying parameter
#[derive(Debug, Clone)]
pub struct Keyframe {
    /// Time position
    pub time: Position,
    /// Value at this time
    pub value: PropertyValue,
    /// Interpolation type
    pub interpolation: InterpolationType,
}

/// Interpolation type for keyframes
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InterpolationType {
    /// No interpolation (step)
    None,
    /// Linear interpolation
    Linear,
    /// Bezier interpolation
    Bezier,
    /// Cubic interpolation
    Cubic,
}

/// Property value types
#[derive(Debug, Clone)]
pub enum PropertyValue {
    /// Boolean
    Boolean(bool),
    /// 8-bit signed integer
    Int8(i8),
    /// 8-bit unsigned integer
    UInt8(u8),
    /// 16-bit signed integer
    Int16(i16),
    /// 16-bit unsigned integer
    UInt16(u16),
    /// 32-bit signed integer
    Int32(i32),
    /// 32-bit unsigned integer
    UInt32(u32),
    /// 64-bit signed integer
    Int64(i64),
    /// 64-bit unsigned integer
    UInt64(u64),
    /// 32-bit float
    Float(f32),
    /// 64-bit float
    Double(f64),
    /// String (UTF-16)
    String(String),
    /// Raw bytes
    Bytes(Vec<u8>),
    /// AUID
    Auid(Auid),
    /// UUID
    Uuid(Uuid),
    /// Strong reference
    StrongRef(Uuid),
    /// Weak reference
    WeakRef(Uuid),
    /// Array of values
    Array(Vec<PropertyValue>),
    /// Record (struct)
    Record(HashMap<String, PropertyValue>),
    /// Set
    Set(Vec<PropertyValue>),
}

impl PropertyValue {
    /// Read property value from bytes
    pub fn read_from_bytes(data: &[u8], type_def: &TypeDefinition) -> Result<Self> {
        let mut cursor = Cursor::new(data);

        match type_def.name() {
            "Boolean" | "bool" => {
                let val = cursor.read_u8()? != 0;
                Ok(PropertyValue::Boolean(val))
            }
            "Int8" | "i8" => {
                let val = cursor.read_i8()?;
                Ok(PropertyValue::Int8(val))
            }
            "UInt8" | "u8" => {
                let val = cursor.read_u8()?;
                Ok(PropertyValue::UInt8(val))
            }
            "Int16" | "i16" => {
                let val = cursor.read_i16::<LittleEndian>()?;
                Ok(PropertyValue::Int16(val))
            }
            "UInt16" | "u16" => {
                let val = cursor.read_u16::<LittleEndian>()?;
                Ok(PropertyValue::UInt16(val))
            }
            "Int32" | "i32" => {
                let val = cursor.read_i32::<LittleEndian>()?;
                Ok(PropertyValue::Int32(val))
            }
            "UInt32" | "u32" => {
                let val = cursor.read_u32::<LittleEndian>()?;
                Ok(PropertyValue::UInt32(val))
            }
            "Int64" | "i64" | "Length" | "Position" => {
                let val = cursor.read_i64::<LittleEndian>()?;
                Ok(PropertyValue::Int64(val))
            }
            "UInt64" | "u64" => {
                let val = cursor.read_u64::<LittleEndian>()?;
                Ok(PropertyValue::UInt64(val))
            }
            "Float" | "f32" => {
                let val = cursor.read_f32::<LittleEndian>()?;
                Ok(PropertyValue::Float(val))
            }
            "Double" | "f64" => {
                let val = cursor.read_f64::<LittleEndian>()?;
                Ok(PropertyValue::Double(val))
            }
            "String" | "UTF16String" => {
                let mut utf16_chars = Vec::new();
                while let Ok(ch) = cursor.read_u16::<LittleEndian>() {
                    if ch == 0 {
                        break;
                    }
                    utf16_chars.push(ch);
                }
                let string = String::from_utf16_lossy(&utf16_chars);
                Ok(PropertyValue::String(string))
            }
            "AUID" => {
                let mut auid_bytes = [0u8; 16];
                cursor.read_exact(&mut auid_bytes)?;
                let auid = Auid::from_bytes(&auid_bytes);
                Ok(PropertyValue::Auid(auid))
            }
            "MobID" | "UUID" => {
                let mut uuid_bytes = [0u8; 16];
                cursor.read_exact(&mut uuid_bytes)?;
                let uuid = Uuid::from_bytes(uuid_bytes);
                Ok(PropertyValue::Uuid(uuid))
            }
            _ => {
                // Return raw bytes for unknown types
                Ok(PropertyValue::Bytes(data.to_vec()))
            }
        }
    }

    /// Convert to integer if possible
    #[must_use]
    pub fn as_int(&self) -> Option<i64> {
        match self {
            PropertyValue::Int8(v) => Some(i64::from(*v)),
            PropertyValue::UInt8(v) => Some(i64::from(*v)),
            PropertyValue::Int16(v) => Some(i64::from(*v)),
            PropertyValue::UInt16(v) => Some(i64::from(*v)),
            PropertyValue::Int32(v) => Some(i64::from(*v)),
            PropertyValue::UInt32(v) => Some(i64::from(*v)),
            PropertyValue::Int64(v) => Some(*v),
            PropertyValue::UInt64(v) => Some(*v as i64),
            _ => None,
        }
    }

    /// Convert to string if possible
    #[must_use]
    pub fn as_string(&self) -> Option<&str> {
        match self {
            PropertyValue::String(s) => Some(s),
            _ => None,
        }
    }

    /// Convert to UUID if possible
    #[must_use]
    pub fn as_uuid(&self) -> Option<Uuid> {
        match self {
            PropertyValue::Uuid(u) => Some(*u),
            PropertyValue::StrongRef(u) => Some(*u),
            PropertyValue::WeakRef(u) => Some(*u),
            _ => None,
        }
    }
}

/// Object reference resolver
pub struct ObjectResolver {
    objects: HashMap<Uuid, ObjectData>,
}

impl ObjectResolver {
    /// Create a new resolver
    #[must_use]
    pub fn new() -> Self {
        Self {
            objects: HashMap::new(),
        }
    }

    /// Register an object
    pub fn register(&mut self, id: Uuid, data: ObjectData) {
        self.objects.insert(id, data);
    }

    /// Resolve a reference
    #[must_use]
    pub fn resolve(&self, id: &Uuid) -> Option<&ObjectData> {
        self.objects.get(id)
    }

    /// Resolve a strong reference
    #[must_use]
    pub fn resolve_strong_ref(&self, value: &PropertyValue) -> Option<&ObjectData> {
        if let PropertyValue::StrongRef(id) = value {
            self.resolve(id)
        } else {
            None
        }
    }

    /// Resolve a weak reference
    #[must_use]
    pub fn resolve_weak_ref(&self, value: &PropertyValue) -> Option<&ObjectData> {
        if let PropertyValue::WeakRef(id) = value {
            self.resolve(id)
        } else {
            None
        }
    }
}

impl Default for ObjectResolver {
    fn default() -> Self {
        Self::new()
    }
}

/// Generic object data
#[derive(Debug, Clone)]
pub struct ObjectData {
    /// Object ID
    pub id: Uuid,
    /// Class ID
    pub class_id: Auid,
    /// Properties
    pub properties: HashMap<String, PropertyValue>,
}

impl ObjectData {
    /// Create a new object data
    #[must_use]
    pub fn new(id: Uuid, class_id: Auid) -> Self {
        Self {
            id,
            class_id,
            properties: HashMap::new(),
        }
    }

    /// Get a property
    #[must_use]
    pub fn get_property(&self, name: &str) -> Option<&PropertyValue> {
        self.properties.get(name)
    }

    /// Set a property
    pub fn set_property(&mut self, name: String, value: PropertyValue) {
        self.properties.insert(name, value);
    }

    /// Get property as integer
    #[must_use]
    pub fn get_int(&self, name: &str) -> Option<i64> {
        self.get_property(name).and_then(PropertyValue::as_int)
    }

    /// Get property as string
    #[must_use]
    pub fn get_string(&self, name: &str) -> Option<&str> {
        self.get_property(name).and_then(|v| v.as_string())
    }

    /// Get property as UUID
    #[must_use]
    pub fn get_uuid(&self, name: &str) -> Option<Uuid> {
        self.get_property(name).and_then(PropertyValue::as_uuid)
    }
}

/// Read header from storage
pub fn read_header<R: Read + Seek>(_storage: &mut StorageReader<R>) -> Result<Header> {
    // In a real implementation, we would read from the "Header" stream
    // For now, return a default header
    Ok(Header::new())
}

/// Read content storage from AAF file
pub fn read_content_storage<R: Read + Seek>(
    _storage: &mut StorageReader<R>,
    _dictionary: &Dictionary,
) -> Result<ContentStorage> {
    // In a real implementation, we would:
    // 1. Read the "Content Storage" object
    // 2. Parse all mobs
    // 3. Parse mob slots and segments
    // 4. Resolve references
    // For now, return an empty content storage
    Ok(ContentStorage::new())
}

/// Property visitor trait
pub trait PropertyVisitor {
    /// Visit a property
    fn visit_property(&mut self, name: &str, value: &PropertyValue) -> Result<()>;

    /// Visit an object
    fn visit_object(&mut self, obj: &ObjectData) -> Result<()> {
        for (name, value) in &obj.properties {
            self.visit_property(name, value)?;
        }
        Ok(())
    }
}

/// Property traversal helper
pub struct PropertyTraverser<'a> {
    resolver: &'a ObjectResolver,
}

impl<'a> PropertyTraverser<'a> {
    /// Create a new traverser
    #[must_use]
    pub fn new(resolver: &'a ObjectResolver) -> Self {
        Self { resolver }
    }

    /// Traverse an object and its references
    pub fn traverse<V: PropertyVisitor>(&self, obj: &ObjectData, visitor: &mut V) -> Result<()> {
        visitor.visit_object(obj)?;

        // Traverse strong references
        for value in obj.properties.values() {
            if let Some(ref_obj) = self.resolver.resolve_strong_ref(value) {
                self.traverse(ref_obj, visitor)?;
            }
        }

        Ok(())
    }
}

/// Weak reference map for resolving mob references
pub struct WeakReferenceMap {
    references: HashMap<Uuid, Uuid>,
}

impl WeakReferenceMap {
    /// Create a new weak reference map
    #[must_use]
    pub fn new() -> Self {
        Self {
            references: HashMap::new(),
        }
    }

    /// Add a reference
    pub fn add(&mut self, target_id: Uuid, mob_id: Uuid) {
        self.references.insert(target_id, mob_id);
    }

    /// Resolve a reference
    #[must_use]
    pub fn resolve(&self, target_id: &Uuid) -> Option<Uuid> {
        self.references.get(target_id).copied()
    }
}

impl Default for WeakReferenceMap {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_header_creation() {
        let header = Header::new();
        assert_eq!(header.major_version, 1);
        assert_eq!(header.minor_version, 1);
        assert_eq!(header.version_string(), "1.1");
    }

    #[test]
    fn test_mob_creation() {
        let mob_id = Uuid::new_v4();
        let mob = Mob::new(mob_id, "Test Mob".to_string(), MobType::Master);
        assert_eq!(mob.mob_id(), mob_id);
        assert_eq!(mob.name(), "Test Mob");
        assert!(mob.is_master_mob());
        assert!(!mob.is_source_mob());
    }

    #[test]
    fn test_mob_slot_creation() {
        let slot = MobSlot::new_timeline(
            1,
            "Video".to_string(),
            EditRate::new(24, 1),
            Position::zero(),
        );
        assert_eq!(slot.slot_id, 1);
        assert_eq!(slot.name, "Video");
        assert_eq!(slot.slot_type, SlotType::Timeline);
    }

    #[test]
    fn test_sequence_segment() {
        let seq = SequenceSegment::new();
        assert!(seq.components.is_empty());
        assert_eq!(seq.calculate_length(), Some(0));
    }

    #[test]
    fn test_source_clip() {
        let clip = SourceClipSegment::new(100, Position::zero(), Uuid::new_v4(), 1);
        assert_eq!(clip.length, 100);
    }

    #[test]
    fn test_filler_segment() {
        let filler = FillerSegment::new(50);
        assert_eq!(filler.length, 50);
    }

    #[test]
    fn test_property_value_int() {
        let val = PropertyValue::Int32(42);
        assert_eq!(val.as_int(), Some(42));
    }

    #[test]
    fn test_property_value_string() {
        let val = PropertyValue::String("test".to_string());
        assert_eq!(val.as_string(), Some("test"));
    }

    #[test]
    fn test_object_data() {
        let obj = ObjectData::new(Uuid::new_v4(), Auid::null());
        assert!(obj.properties.is_empty());
    }

    #[test]
    fn test_object_resolver() {
        let resolver = ObjectResolver::new();
        let id = Uuid::new_v4();
        assert!(resolver.resolve(&id).is_none());
    }

    #[test]
    fn test_weak_reference_map() {
        let mut map = WeakReferenceMap::new();
        let target_id = Uuid::new_v4();
        let mob_id = Uuid::new_v4();
        map.add(target_id, mob_id);
        assert_eq!(map.resolve(&target_id), Some(mob_id));
    }
}