oximedia-net 0.1.8

Network streaming for OxiMedia
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
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
//! DASH MPD (Media Presentation Description) parsing.
//!
//! This module provides types for parsing and representing MPEG-DASH manifests.

#![allow(dead_code)]
#![allow(clippy::doc_markdown)]
#![allow(clippy::similar_names)]
#![allow(clippy::unreadable_literal)]
#![allow(clippy::cast_possible_truncation)]
#![allow(clippy::cast_precision_loss)]
#![allow(clippy::cast_lossless)]
#![allow(clippy::cast_sign_loss)]
#![allow(clippy::match_same_arms)]
#![allow(clippy::many_single_char_names)]
#![allow(clippy::unnecessary_wraps)]
#![allow(clippy::range_plus_one)]
#![allow(clippy::needless_pass_by_value)]
#![allow(clippy::manual_div_ceil)]
#![allow(clippy::comparison_chain)]
#![allow(clippy::unused_self)]
#![allow(clippy::trivially_copy_pass_by_ref)]
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::struct_excessive_bools)]
#![allow(clippy::needless_range_loop)]
#![allow(clippy::redundant_closure_for_method_calls)]
#![allow(clippy::must_use_candidate)]
#![allow(clippy::should_implement_trait)]
#![allow(clippy::items_after_statements)]
#![allow(clippy::if_not_else)]
#![allow(clippy::format_push_string)]
#![allow(clippy::single_match_else)]
#![allow(clippy::redundant_slicing)]
#![allow(clippy::uninlined_format_args)]
#![allow(clippy::map_unwrap_or)]
#![allow(clippy::derivable_impls)]
#![allow(clippy::assigning_clones)]
#![allow(clippy::if_same_then_else)]
#![allow(clippy::format_collect)]
#![allow(clippy::useless_conversion)]
#![allow(clippy::unused_async)]
#![allow(clippy::identity_op)]
use crate::error::{NetError, NetResult};
use std::time::Duration;

/// MPD presentation type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum MpdType {
    /// Static (VOD) presentation.
    #[default]
    Static,
    /// Dynamic (live) presentation.
    Dynamic,
}

impl MpdType {
    /// Parses from string.
    #[must_use]
    pub fn from_str(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "dynamic" => Self::Dynamic,
            _ => Self::Static,
        }
    }

    /// Returns true if this is a live presentation.
    #[must_use]
    pub const fn is_live(&self) -> bool {
        matches!(self, Self::Dynamic)
    }
}

/// URL type for base URLs and initialization segments.
#[derive(Debug, Clone, Default)]
pub struct UrlType {
    /// URL source.
    pub source_url: Option<String>,
    /// Byte range.
    pub range: Option<(u64, u64)>,
}

impl UrlType {
    /// Creates a new URL type.
    #[must_use]
    pub fn new(source_url: impl Into<String>) -> Self {
        Self {
            source_url: Some(source_url.into()),
            range: None,
        }
    }

    /// Sets the byte range.
    #[must_use]
    pub const fn with_range(mut self, start: u64, end: u64) -> Self {
        self.range = Some((start, end));
        self
    }
}

/// Program information element.
#[derive(Debug, Clone, Default)]
pub struct ProgramInformation {
    /// Language.
    pub lang: Option<String>,
    /// More information URL.
    pub more_info_url: Option<String>,
    /// Title.
    pub title: Option<String>,
    /// Source.
    pub source: Option<String>,
    /// Copyright.
    pub copyright: Option<String>,
}

/// Generic descriptor element.
#[derive(Debug, Clone)]
pub struct Descriptor {
    /// Scheme ID URI.
    pub scheme_id_uri: String,
    /// Value.
    pub value: Option<String>,
    /// ID.
    pub id: Option<String>,
}

impl Descriptor {
    /// Creates a new descriptor.
    #[must_use]
    pub fn new(scheme_id_uri: impl Into<String>) -> Self {
        Self {
            scheme_id_uri: scheme_id_uri.into(),
            value: None,
            id: None,
        }
    }
}

/// Content protection element.
#[derive(Debug, Clone)]
pub struct ContentProtection {
    /// Scheme ID URI.
    pub scheme_id_uri: String,
    /// Value.
    pub value: Option<String>,
    /// Default key ID.
    pub default_kid: Option<String>,
    /// PSSH data (base64).
    pub pssh: Option<String>,
}

impl ContentProtection {
    /// Creates a new content protection element.
    #[must_use]
    pub fn new(scheme_id_uri: impl Into<String>) -> Self {
        Self {
            scheme_id_uri: scheme_id_uri.into(),
            value: None,
            default_kid: None,
            pssh: None,
        }
    }

    /// Returns true if this is Widevine DRM.
    #[must_use]
    pub fn is_widevine(&self) -> bool {
        self.scheme_id_uri
            .contains("edef8ba9-79d6-4ace-a3c8-27dcd51d21ed")
    }

    /// Returns true if this is PlayReady DRM.
    #[must_use]
    pub fn is_playready(&self) -> bool {
        self.scheme_id_uri
            .contains("9a04f079-9840-4286-ab92-e65be0885f95")
    }
}

/// Segment timeline entry (S element).
#[derive(Debug, Clone, Copy)]
pub struct SegmentTimelineEntry {
    /// Start time (t attribute).
    pub start: Option<u64>,
    /// Duration (d attribute).
    pub duration: u64,
    /// Repeat count (r attribute, -1 means repeat until end).
    pub repeat: i32,
}

impl SegmentTimelineEntry {
    /// Creates a new timeline entry.
    #[must_use]
    pub const fn new(duration: u64) -> Self {
        Self {
            start: None,
            duration,
            repeat: 0,
        }
    }

    /// Sets the start time.
    #[must_use]
    pub const fn with_start(mut self, start: u64) -> Self {
        self.start = Some(start);
        self
    }

    /// Sets the repeat count.
    #[must_use]
    pub const fn with_repeat(mut self, repeat: i32) -> Self {
        self.repeat = repeat;
        self
    }

    /// Returns the number of segments this entry represents.
    #[must_use]
    pub const fn segment_count(&self) -> u32 {
        if self.repeat < 0 {
            u32::MAX
        } else {
            (self.repeat + 1) as u32
        }
    }
}

/// Segment timeline (SegmentTimeline element).
#[derive(Debug, Clone, Default)]
pub struct SegmentTimeline {
    /// Timeline entries.
    pub entries: Vec<SegmentTimelineEntry>,
}

impl SegmentTimeline {
    /// Creates a new empty timeline.
    #[must_use]
    pub fn new() -> Self {
        Self {
            entries: Vec::new(),
        }
    }

    /// Adds an entry to the timeline.
    pub fn add_entry(&mut self, entry: SegmentTimelineEntry) {
        self.entries.push(entry);
    }

    /// Returns the total duration in timescale units.
    #[must_use]
    pub fn total_duration(&self) -> u64 {
        let mut total = 0u64;
        for entry in &self.entries {
            let count = if entry.repeat < 0 {
                1
            } else {
                (entry.repeat + 1) as u64
            };
            total += entry.duration * count;
        }
        total
    }

    /// Iterates over all segment start times and durations.
    pub fn iter_segments(&self) -> impl Iterator<Item = (u64, u64)> + '_ {
        SegmentTimelineIterator {
            entries: &self.entries,
            entry_idx: 0,
            repeat_idx: 0,
            current_time: 0,
        }
    }
}

struct SegmentTimelineIterator<'a> {
    entries: &'a [SegmentTimelineEntry],
    entry_idx: usize,
    repeat_idx: i32,
    current_time: u64,
}

impl Iterator for SegmentTimelineIterator<'_> {
    type Item = (u64, u64);

    fn next(&mut self) -> Option<Self::Item> {
        while self.entry_idx < self.entries.len() {
            let entry = &self.entries[self.entry_idx];

            // Set start time from entry if this is the first segment of this entry
            if self.repeat_idx == 0 {
                if let Some(start) = entry.start {
                    self.current_time = start;
                }
            }

            if entry.repeat < 0 || self.repeat_idx <= entry.repeat {
                let start = self.current_time;
                let duration = entry.duration;
                self.current_time += duration;
                self.repeat_idx += 1;

                if entry.repeat >= 0 && self.repeat_idx > entry.repeat {
                    self.entry_idx += 1;
                    self.repeat_idx = 0;
                }

                return Some((start, duration));
            }

            self.entry_idx += 1;
            self.repeat_idx = 0;
        }
        None
    }
}

/// Segment base information.
#[derive(Debug, Clone, Default)]
pub struct SegmentBase {
    /// Timescale.
    pub timescale: Option<u32>,
    /// Presentation time offset.
    pub presentation_time_offset: Option<u64>,
    /// Index range.
    pub index_range: Option<(u64, u64)>,
    /// Initialization URL.
    pub initialization: Option<UrlType>,
    /// Representation index URL.
    pub representation_index: Option<UrlType>,
}

/// Segment list element.
#[derive(Debug, Clone, Default)]
pub struct SegmentList {
    /// Timescale.
    pub timescale: Option<u32>,
    /// Duration per segment.
    pub duration: Option<u64>,
    /// Start number.
    pub start_number: Option<u64>,
    /// Initialization URL.
    pub initialization: Option<UrlType>,
    /// Segment URLs.
    pub segment_urls: Vec<UrlType>,
}

/// Segment template element.
#[derive(Debug, Clone, Default)]
pub struct SegmentTemplate {
    /// Timescale.
    pub timescale: u32,
    /// Duration per segment.
    pub duration: Option<u64>,
    /// Start number.
    pub start_number: u64,
    /// Presentation time offset.
    pub presentation_time_offset: Option<u64>,
    /// Media URL template.
    pub media: Option<String>,
    /// Initialization URL template.
    pub initialization: Option<String>,
    /// Segment timeline.
    pub segment_timeline: Option<SegmentTimeline>,
}

impl SegmentTemplate {
    /// Creates a new segment template.
    #[must_use]
    pub fn new(timescale: u32) -> Self {
        Self {
            timescale,
            start_number: 1,
            ..Default::default()
        }
    }

    /// Sets the media template.
    #[must_use]
    pub fn with_media(mut self, media: impl Into<String>) -> Self {
        self.media = Some(media.into());
        self
    }

    /// Sets the initialization template.
    #[must_use]
    pub fn with_initialization(mut self, init: impl Into<String>) -> Self {
        self.initialization = Some(init.into());
        self
    }

    /// Generates a media URL for a given segment.
    #[must_use]
    pub fn media_url(
        &self,
        representation_id: &str,
        number: u64,
        time: Option<u64>,
    ) -> Option<String> {
        let template = self.media.as_ref()?;
        let url = substitute_template(template, representation_id, number, time, self.timescale);
        Some(url)
    }

    /// Generates an initialization URL.
    #[must_use]
    pub fn initialization_url(&self, representation_id: &str) -> Option<String> {
        let template = self.initialization.as_ref()?;
        let url = substitute_template(template, representation_id, 0, None, self.timescale);
        Some(url)
    }

    /// Returns the segment duration in seconds.
    #[must_use]
    pub fn segment_duration_secs(&self) -> Option<f64> {
        self.duration.map(|d| d as f64 / self.timescale as f64)
    }
}

/// Substitutes template variables.
fn substitute_template(
    template: &str,
    representation_id: &str,
    number: u64,
    time: Option<u64>,
    bandwidth: u32,
) -> String {
    let mut result = template.to_string();

    // Simple substitution (without format specifiers)
    result = result.replace("$RepresentationID$", representation_id);
    result = result.replace("$Number$", &number.to_string());
    result = result.replace("$Bandwidth$", &bandwidth.to_string());

    if let Some(t) = time {
        result = result.replace("$Time$", &t.to_string());
    }

    // Handle format specifiers like $Number%05d$
    result = substitute_with_format(&result, "Number", number);
    result = substitute_with_format(&result, "Time", time.unwrap_or(0));

    result
}

fn substitute_with_format(s: &str, var: &str, value: u64) -> String {
    let pattern = format!("${var}%");
    let mut result = s.to_string();
    let mut search_start = 0;

    while let Some(start) = result[search_start..].find(&pattern) {
        let abs_start = search_start + start;
        if let Some(end) = result[abs_start..].find("d$") {
            let format_spec = &result[abs_start + pattern.len()..abs_start + end + 1];
            // Parse width from format spec (e.g., "05" from "%05d")
            let width: usize = format_spec.trim_start_matches('0').parse().unwrap_or(0);
            let pad_char = if format_spec.starts_with('0') {
                '0'
            } else {
                ' '
            };

            let formatted = if pad_char == '0' && width > 0 {
                format!("{value:0>width$}")
            } else {
                format!("{value:>width$}")
            };

            let full_pattern = format!("${var}%{format_spec}d$");
            result = result.replace(&full_pattern, &formatted);
        } else {
            search_start = abs_start + 1;
        }
    }

    result
}

/// Content component element.
#[derive(Debug, Clone, Default)]
pub struct ContentComponent {
    /// ID.
    pub id: Option<String>,
    /// Content type.
    pub content_type: Option<String>,
    /// Language.
    pub lang: Option<String>,
}

/// Representation element.
#[derive(Debug, Clone, Default)]
pub struct Representation {
    /// ID.
    pub id: String,
    /// Bandwidth in bits per second.
    pub bandwidth: u64,
    /// Width (video).
    pub width: Option<u32>,
    /// Height (video).
    pub height: Option<u32>,
    /// Frame rate.
    pub frame_rate: Option<String>,
    /// Sample rate (audio).
    pub audio_sampling_rate: Option<u32>,
    /// Codecs string.
    pub codecs: Option<String>,
    /// MIME type.
    pub mime_type: Option<String>,
    /// Segment base.
    pub segment_base: Option<SegmentBase>,
    /// Segment list.
    pub segment_list: Option<SegmentList>,
    /// Segment template.
    pub segment_template: Option<SegmentTemplate>,
    /// Base URLs.
    pub base_urls: Vec<String>,
    /// Content protection.
    pub content_protection: Vec<ContentProtection>,
}

impl Representation {
    /// Creates a new representation.
    #[must_use]
    pub fn new(id: impl Into<String>, bandwidth: u64) -> Self {
        Self {
            id: id.into(),
            bandwidth,
            ..Default::default()
        }
    }

    /// Returns the resolution if available.
    #[must_use]
    pub fn resolution(&self) -> Option<(u32, u32)> {
        match (self.width, self.height) {
            (Some(w), Some(h)) => Some((w, h)),
            _ => None,
        }
    }

    /// Returns true if this is a video representation.
    #[must_use]
    pub fn is_video(&self) -> bool {
        self.mime_type
            .as_ref()
            .is_some_and(|m| m.starts_with("video/"))
            || self.width.is_some()
    }

    /// Returns true if this is an audio representation.
    #[must_use]
    pub fn is_audio(&self) -> bool {
        self.mime_type
            .as_ref()
            .is_some_and(|m| m.starts_with("audio/"))
            || self.audio_sampling_rate.is_some()
    }
}

/// Adaptation set element.
#[derive(Debug, Clone, Default)]
pub struct AdaptationSet {
    /// ID.
    pub id: Option<u32>,
    /// Group.
    pub group: Option<u32>,
    /// Content type.
    pub content_type: Option<String>,
    /// Language.
    pub lang: Option<String>,
    /// MIME type.
    pub mime_type: Option<String>,
    /// Codecs.
    pub codecs: Option<String>,
    /// Width (video).
    pub width: Option<u32>,
    /// Height (video).
    pub height: Option<u32>,
    /// Frame rate.
    pub frame_rate: Option<String>,
    /// Audio sampling rate.
    pub audio_sampling_rate: Option<u32>,
    /// Segment alignment.
    pub segment_alignment: bool,
    /// Subsegment alignment.
    pub subsegment_alignment: bool,
    /// Bitstream switching.
    pub bitstream_switching: bool,
    /// Segment base.
    pub segment_base: Option<SegmentBase>,
    /// Segment list.
    pub segment_list: Option<SegmentList>,
    /// Segment template.
    pub segment_template: Option<SegmentTemplate>,
    /// Content components.
    pub content_components: Vec<ContentComponent>,
    /// Representations.
    pub representations: Vec<Representation>,
    /// Content protection.
    pub content_protection: Vec<ContentProtection>,
    /// Accessibility descriptors.
    pub accessibility: Vec<Descriptor>,
    /// Role descriptors.
    pub role: Vec<Descriptor>,
}

impl AdaptationSet {
    /// Creates a new adaptation set.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns true if this is a video adaptation set.
    #[must_use]
    pub fn is_video(&self) -> bool {
        self.content_type.as_deref() == Some("video")
            || self
                .mime_type
                .as_ref()
                .is_some_and(|m| m.starts_with("video/"))
            || self.representations.iter().any(Representation::is_video)
    }

    /// Returns true if this is an audio adaptation set.
    #[must_use]
    pub fn is_audio(&self) -> bool {
        self.content_type.as_deref() == Some("audio")
            || self
                .mime_type
                .as_ref()
                .is_some_and(|m| m.starts_with("audio/"))
            || self.representations.iter().any(Representation::is_audio)
    }

    /// Returns true if this is a text/subtitle adaptation set.
    #[must_use]
    pub fn is_text(&self) -> bool {
        self.content_type.as_deref() == Some("text")
            || self
                .mime_type
                .as_ref()
                .is_some_and(|m| m.starts_with("text/"))
    }

    /// Returns representations sorted by bandwidth.
    #[must_use]
    pub fn representations_by_bandwidth(&self) -> Vec<&Representation> {
        let mut reps: Vec<_> = self.representations.iter().collect();
        reps.sort_by_key(|r| r.bandwidth);
        reps
    }
}

/// Period element.
#[derive(Debug, Clone, Default)]
pub struct Period {
    /// ID.
    pub id: Option<String>,
    /// Start time.
    pub start: Option<Duration>,
    /// Duration.
    pub duration: Option<Duration>,
    /// Bitstream switching.
    pub bitstream_switching: bool,
    /// Segment base.
    pub segment_base: Option<SegmentBase>,
    /// Segment list.
    pub segment_list: Option<SegmentList>,
    /// Segment template.
    pub segment_template: Option<SegmentTemplate>,
    /// Adaptation sets.
    pub adaptation_sets: Vec<AdaptationSet>,
    /// Base URLs.
    pub base_urls: Vec<String>,
}

impl Period {
    /// Creates a new period.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns video adaptation sets.
    #[must_use]
    pub fn video_adaptation_sets(&self) -> Vec<&AdaptationSet> {
        self.adaptation_sets
            .iter()
            .filter(|a| a.is_video())
            .collect()
    }

    /// Returns audio adaptation sets.
    #[must_use]
    pub fn audio_adaptation_sets(&self) -> Vec<&AdaptationSet> {
        self.adaptation_sets
            .iter()
            .filter(|a| a.is_audio())
            .collect()
    }

    /// Returns text/subtitle adaptation sets.
    #[must_use]
    pub fn text_adaptation_sets(&self) -> Vec<&AdaptationSet> {
        self.adaptation_sets
            .iter()
            .filter(|a| a.is_text())
            .collect()
    }
}

/// Media Presentation Description (MPD).
#[derive(Debug, Clone, Default)]
pub struct Mpd {
    /// MPD type (static/dynamic).
    pub mpd_type: MpdType,
    /// Minimum buffer time.
    pub min_buffer_time: Duration,
    /// Media presentation duration.
    pub media_presentation_duration: Option<Duration>,
    /// Availability start time (ISO 8601).
    pub availability_start_time: Option<String>,
    /// Availability end time (ISO 8601).
    pub availability_end_time: Option<String>,
    /// Publish time (ISO 8601).
    pub publish_time: Option<String>,
    /// Minimum update period.
    pub minimum_update_period: Option<Duration>,
    /// Suggested presentation delay.
    pub suggested_presentation_delay: Option<Duration>,
    /// Time shift buffer depth.
    pub time_shift_buffer_depth: Option<Duration>,
    /// Profiles.
    pub profiles: Vec<String>,
    /// Base URLs.
    pub base_urls: Vec<String>,
    /// Program information.
    pub program_information: Option<ProgramInformation>,
    /// Periods.
    pub periods: Vec<Period>,
}

impl Mpd {
    /// Creates a new empty MPD.
    #[must_use]
    pub fn new() -> Self {
        Self {
            min_buffer_time: Duration::from_secs(2),
            ..Default::default()
        }
    }

    /// Parses an MPD from XML string.
    ///
    /// # Errors
    ///
    /// Returns an error if the XML is malformed.
    ///
    /// Note: This is a skeleton implementation. Full XML parsing would
    /// require an XML library like quick-xml.
    pub fn parse(xml: &str) -> NetResult<Self> {
        // Basic validation
        if !xml.contains("<MPD") {
            return Err(NetError::parse(0, "Missing MPD root element"));
        }

        let mut mpd = Self::new();

        // Parse type attribute
        if let Some(type_value) = extract_attribute(xml, "MPD", "type") {
            mpd.mpd_type = MpdType::from_str(&type_value);
        }

        // Parse minBufferTime
        if let Some(mbt) = extract_attribute(xml, "MPD", "minBufferTime") {
            if let Some(dur) = parse_iso8601_duration(&mbt) {
                mpd.min_buffer_time = dur;
            }
        }

        // Parse mediaPresentationDuration
        if let Some(mpd_dur) = extract_attribute(xml, "MPD", "mediaPresentationDuration") {
            mpd.media_presentation_duration = parse_iso8601_duration(&mpd_dur);
        }

        // Parse profiles
        if let Some(profiles) = extract_attribute(xml, "MPD", "profiles") {
            mpd.profiles = profiles.split(',').map(|s| s.trim().to_string()).collect();
        }

        Ok(mpd)
    }

    /// Returns true if this is a live presentation.
    #[must_use]
    pub const fn is_live(&self) -> bool {
        self.mpd_type.is_live()
    }

    /// Returns the total duration if known.
    #[must_use]
    pub fn duration(&self) -> Option<Duration> {
        self.media_presentation_duration
    }

    /// Returns the first period.
    #[must_use]
    pub fn first_period(&self) -> Option<&Period> {
        self.periods.first()
    }
}

/// Extracts an attribute value from a simple XML element (basic implementation).
fn extract_attribute(xml: &str, element: &str, attr: &str) -> Option<String> {
    let element_start = xml.find(&format!("<{element}"))?;
    let element_end = xml[element_start..].find('>')? + element_start;
    let element_str = &xml[element_start..element_end];

    let attr_pattern = format!("{attr}=\"");
    let attr_start = element_str.find(&attr_pattern)? + attr_pattern.len();
    let attr_end = element_str[attr_start..].find('"')? + attr_start;

    Some(element_str[attr_start..attr_end].to_string())
}

/// Parses an ISO 8601 duration string (e.g., "PT10S", "PT1H30M").
///
/// Supports: P[nY][nM][nD][T[nH][nM][nS]]
#[must_use]
pub fn parse_iso8601_duration(s: &str) -> Option<Duration> {
    let s = s.trim();
    if !s.starts_with('P') {
        return None;
    }

    let s = &s[1..];
    let mut total_secs = 0.0;
    let mut in_time = false;
    let mut num_str = String::new();

    for ch in s.chars() {
        match ch {
            'T' => in_time = true,
            'Y' if !in_time => {
                if let Ok(n) = num_str.parse::<f64>() {
                    total_secs += n * 365.25 * 24.0 * 60.0 * 60.0;
                }
                num_str.clear();
            }
            'M' if !in_time => {
                if let Ok(n) = num_str.parse::<f64>() {
                    total_secs += n * 30.0 * 24.0 * 60.0 * 60.0;
                }
                num_str.clear();
            }
            'D' => {
                if let Ok(n) = num_str.parse::<f64>() {
                    total_secs += n * 24.0 * 60.0 * 60.0;
                }
                num_str.clear();
            }
            'H' => {
                if let Ok(n) = num_str.parse::<f64>() {
                    total_secs += n * 60.0 * 60.0;
                }
                num_str.clear();
            }
            'M' if in_time => {
                if let Ok(n) = num_str.parse::<f64>() {
                    total_secs += n * 60.0;
                }
                num_str.clear();
            }
            'S' => {
                if let Ok(n) = num_str.parse::<f64>() {
                    total_secs += n;
                }
                num_str.clear();
            }
            c if c.is_ascii_digit() || c == '.' => num_str.push(c),
            _ => {}
        }
    }

    if total_secs > 0.0 {
        Some(Duration::from_secs_f64(total_secs))
    } else {
        None
    }
}

/// Formats a duration as ISO 8601.
#[must_use]
#[allow(dead_code)]
pub fn format_iso8601_duration(dur: Duration) -> String {
    let total_secs = dur.as_secs_f64();

    if total_secs < 60.0 {
        return format!("PT{total_secs:.3}S");
    }

    let hours = (total_secs / 3600.0).floor() as u64;
    let minutes = ((total_secs % 3600.0) / 60.0).floor() as u64;
    let seconds = total_secs % 60.0;

    let mut result = String::from("PT");
    if hours > 0 {
        result.push_str(&format!("{hours}H"));
    }
    if minutes > 0 {
        result.push_str(&format!("{minutes}M"));
    }
    if seconds > 0.0 || result == "PT" {
        result.push_str(&format!("{seconds:.3}S"));
    }

    result
}

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

    #[test]
    fn test_mpd_type() {
        assert!(!MpdType::Static.is_live());
        assert!(MpdType::Dynamic.is_live());
        assert_eq!(MpdType::from_str("dynamic"), MpdType::Dynamic);
        assert_eq!(MpdType::from_str("static"), MpdType::Static);
    }

    #[test]
    fn test_parse_iso8601_duration() {
        assert_eq!(
            parse_iso8601_duration("PT10S"),
            Some(Duration::from_secs(10))
        );
        assert_eq!(
            parse_iso8601_duration("PT1M30S"),
            Some(Duration::from_secs(90))
        );
        assert_eq!(
            parse_iso8601_duration("PT1H"),
            Some(Duration::from_secs(3600))
        );
        assert_eq!(
            parse_iso8601_duration("PT1H30M45S"),
            Some(Duration::from_secs(5445))
        );
        assert_eq!(
            parse_iso8601_duration("P1D"),
            Some(Duration::from_secs(86400))
        );

        // Fractional seconds
        let dur = parse_iso8601_duration("PT10.5S").expect("should succeed in test");
        assert!((dur.as_secs_f64() - 10.5).abs() < 0.001);
    }

    #[test]
    fn test_format_iso8601_duration() {
        assert_eq!(
            format_iso8601_duration(Duration::from_secs(10)),
            "PT10.000S"
        );
        assert_eq!(
            format_iso8601_duration(Duration::from_secs(90)),
            "PT1M30.000S"
        );
        // 3600 seconds = 1 hour with 0 minutes and 0 seconds
        assert_eq!(format_iso8601_duration(Duration::from_secs(3600)), "PT1H");
    }

    #[test]
    fn test_segment_template() {
        let template = SegmentTemplate::new(90000)
            .with_media("video_$RepresentationID$_$Number$.m4s")
            .with_initialization("video_$RepresentationID$_init.mp4");

        let media_url = template
            .media_url("720p", 1, None)
            .expect("should succeed in test");
        assert_eq!(media_url, "video_720p_1.m4s");

        let init_url = template
            .initialization_url("720p")
            .expect("should succeed in test");
        assert_eq!(init_url, "video_720p_init.mp4");
    }

    #[test]
    fn test_segment_template_with_time() {
        let template = SegmentTemplate::new(90000).with_media("segment_$Time$.m4s");

        let url = template
            .media_url("v1", 1, Some(900000))
            .expect("should succeed in test");
        assert_eq!(url, "segment_900000.m4s");
    }

    #[test]
    fn test_segment_timeline() {
        let mut timeline = SegmentTimeline::new();
        timeline.add_entry(SegmentTimelineEntry::new(90000).with_start(0));
        timeline.add_entry(SegmentTimelineEntry::new(90000).with_repeat(2));

        let segments: Vec<_> = timeline.iter_segments().collect();
        assert_eq!(segments.len(), 4);
        assert_eq!(segments[0], (0, 90000));
        assert_eq!(segments[1], (90000, 90000));
    }

    #[test]
    fn test_representation() {
        let rep = Representation::new("720p", 1_500_000);
        assert_eq!(rep.id, "720p");
        assert_eq!(rep.bandwidth, 1_500_000);
    }

    #[test]
    fn test_adaptation_set_type() {
        let mut video_as = AdaptationSet::new();
        video_as.content_type = Some("video".to_string());
        assert!(video_as.is_video());
        assert!(!video_as.is_audio());

        let mut audio_as = AdaptationSet::new();
        audio_as.mime_type = Some("audio/mp4".to_string());
        assert!(audio_as.is_audio());
        assert!(!audio_as.is_video());
    }

    #[test]
    fn test_mpd_parse_basic() {
        let xml = r#"<?xml version="1.0"?>
            <MPD type="static" minBufferTime="PT2S" mediaPresentationDuration="PT1H30M">
            </MPD>"#;

        let mpd = Mpd::parse(xml).expect("should succeed in test");
        assert_eq!(mpd.mpd_type, MpdType::Static);
        assert_eq!(mpd.min_buffer_time, Duration::from_secs(2));
        assert_eq!(
            mpd.media_presentation_duration,
            Some(Duration::from_secs(5400))
        );
    }

    #[test]
    fn test_mpd_parse_live() {
        let xml = r#"<MPD type="dynamic" minBufferTime="PT4S"></MPD>"#;

        let mpd = Mpd::parse(xml).expect("should succeed in test");
        assert!(mpd.is_live());
        assert_eq!(mpd.min_buffer_time, Duration::from_secs(4));
    }

    #[test]
    fn test_url_type() {
        let url = UrlType::new("init.mp4").with_range(0, 999);
        assert_eq!(url.source_url, Some("init.mp4".to_string()));
        assert_eq!(url.range, Some((0, 999)));
    }

    #[test]
    fn test_content_protection() {
        let cp = ContentProtection::new("urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed");
        assert!(cp.is_widevine());
        assert!(!cp.is_playready());
    }
}