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
use std::borrow::Cow;
use std::collections::HashSet;
use std::convert::TryFrom;
use std::fmt;

use derive_builder::Builder;

use crate::line::{Line, Lines, Tag};
use crate::tags::{
    ExtM3u, ExtXIndependentSegments, ExtXMedia, ExtXSessionData, ExtXSessionKey, ExtXStart,
    ExtXVersion, VariantStream,
};
use crate::types::{ClosedCaptions, MediaType, ProtocolVersion};
use crate::utils::{tag, BoolExt};
use crate::{Error, RequiredVersion};

/// The master playlist describes all of the available variants for your
/// content.
///
/// Each variant is a version of the stream at a particular bitrate and is
/// contained in a separate playlist called [`MediaPlaylist`].
///
/// # Examples
///
/// A [`MasterPlaylist`] can be parsed from a `str`:
///
/// ```
/// use core::convert::TryFrom;
/// use hls_m3u8::MasterPlaylist;
///
/// // the concat! macro joins multiple `&'static str`.
/// let master_playlist = MasterPlaylist::try_from(concat!(
///     "#EXTM3U\n",
///     "#EXT-X-STREAM-INF:",
///     "BANDWIDTH=150000,CODECS=\"avc1.42e00a,mp4a.40.2\",RESOLUTION=416x234\n",
///     "http://example.com/low/index.m3u8\n",
///     "#EXT-X-STREAM-INF:",
///     "BANDWIDTH=240000,CODECS=\"avc1.42e00a,mp4a.40.2\",RESOLUTION=416x234\n",
///     "http://example.com/lo_mid/index.m3u8\n",
///     "#EXT-X-STREAM-INF:",
///     "BANDWIDTH=440000,CODECS=\"avc1.42e00a,mp4a.40.2\",RESOLUTION=416x234\n",
///     "http://example.com/hi_mid/index.m3u8\n",
///     "#EXT-X-STREAM-INF:",
///     "BANDWIDTH=640000,CODECS=\"avc1.42e00a,mp4a.40.2\",RESOLUTION=640x360\n",
///     "http://example.com/high/index.m3u8\n",
///     "#EXT-X-STREAM-INF:BANDWIDTH=64000,CODECS=\"mp4a.40.5\"\n",
///     "http://example.com/audio/index.m3u8\n"
/// ))?;
///
/// println!("{}", master_playlist.has_independent_segments);
/// # Ok::<(), hls_m3u8::Error>(())
/// ```
///
/// or it can be constructed through a builder
///
/// ```
/// # use hls_m3u8::MasterPlaylist;
/// use hls_m3u8::tags::{ExtXStart, VariantStream};
/// use hls_m3u8::types::{Float, StreamData};
///
/// MasterPlaylist::builder()
///     .variant_streams(vec![
///         VariantStream::ExtXStreamInf {
///             uri: "http://example.com/low/index.m3u8".into(),
///             frame_rate: None,
///             audio: None,
///             subtitles: None,
///             closed_captions: None,
///             stream_data: StreamData::builder()
///                 .bandwidth(150000)
///                 .codecs(&["avc1.42e00a", "mp4a.40.2"])
///                 .resolution((416, 234))
///                 .build()
///                 .unwrap(),
///         },
///         VariantStream::ExtXStreamInf {
///             uri: "http://example.com/lo_mid/index.m3u8".into(),
///             frame_rate: None,
///             audio: None,
///             subtitles: None,
///             closed_captions: None,
///             stream_data: StreamData::builder()
///                 .bandwidth(240000)
///                 .codecs(&["avc1.42e00a", "mp4a.40.2"])
///                 .resolution((416, 234))
///                 .build()
///                 .unwrap(),
///         },
///     ])
///     .has_independent_segments(true)
///     .start(ExtXStart::new(Float::new(1.23)))
///     .build()?;
/// # Ok::<(), Box<dyn ::std::error::Error>>(())
/// ```
///
/// [`MediaPlaylist`]: crate::MediaPlaylist
#[derive(Builder, Default, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[builder(build_fn(validate = "Self::validate"))]
#[builder(setter(into, strip_option))]
#[non_exhaustive]
pub struct MasterPlaylist<'a> {
    /// Indicates that all media samples in a [`MediaSegment`] can be
    /// decoded without information from other segments.
    ///
    /// ### Note
    ///
    /// This field is optional and by default `false`. If the field is `true`,
    /// it applies to every [`MediaSegment`] in every [`MediaPlaylist`] of this
    /// [`MasterPlaylist`].
    ///
    /// [`MediaSegment`]: crate::MediaSegment
    /// [`MediaPlaylist`]: crate::MediaPlaylist
    #[builder(default)]
    pub has_independent_segments: bool,
    /// A preferred point at which to start playing a playlist.
    ///
    /// ### Note
    ///
    /// This field is optional and by default the playlist should be played from
    /// the start.
    #[builder(default)]
    pub start: Option<ExtXStart>,
    /// A list of all [`ExtXMedia`] tags, which describe an alternative
    /// rendition.
    ///
    /// For example, three [`ExtXMedia`] tags can be used to identify audio-only
    /// [`MediaPlaylist`]s, that contain English, French, and Spanish
    /// renditions of the same presentation. Or, two [`ExtXMedia`] tags can
    /// be used to identify video-only [`MediaPlaylist`]s that show two
    /// different camera angles.
    ///
    /// ### Note
    ///
    /// This field is optional.
    ///
    /// [`MediaPlaylist`]: crate::MediaPlaylist
    #[builder(default)]
    pub media: Vec<ExtXMedia<'a>>,
    /// A list of all streams of this [`MasterPlaylist`].
    ///
    /// ### Note
    ///
    /// This field is optional.
    #[builder(default)]
    pub variant_streams: Vec<VariantStream<'a>>,
    /// The [`ExtXSessionData`] tag allows arbitrary session data to be
    /// carried in a [`MasterPlaylist`].
    ///
    /// ### Note
    ///
    /// This field is optional.
    #[builder(default)]
    pub session_data: Vec<ExtXSessionData<'a>>,
    /// A list of [`ExtXSessionKey`]s, that allows the client to preload
    /// these keys without having to read the [`MediaPlaylist`]s first.
    ///
    /// ### Note
    ///
    /// This field is optional.
    ///
    /// [`MediaPlaylist`]: crate::MediaPlaylist
    #[builder(default)]
    pub session_keys: Vec<ExtXSessionKey<'a>>,
    /// A list of all tags that could not be identified while parsing the input.
    ///
    /// ### Note
    ///
    /// This field is optional.
    #[builder(default)]
    pub unknown_tags: Vec<Cow<'a, str>>,
}

impl<'a> MasterPlaylist<'a> {
    /// Returns a builder for a [`MasterPlaylist`].
    ///
    /// # Example
    ///
    /// ```
    /// # use hls_m3u8::MasterPlaylist;
    /// use hls_m3u8::tags::{ExtXStart, VariantStream};
    /// use hls_m3u8::types::{Float, StreamData};
    ///
    /// MasterPlaylist::builder()
    ///     .variant_streams(vec![
    ///         VariantStream::ExtXStreamInf {
    ///             uri: "http://example.com/low/index.m3u8".into(),
    ///             frame_rate: None,
    ///             audio: None,
    ///             subtitles: None,
    ///             closed_captions: None,
    ///             stream_data: StreamData::builder()
    ///                 .bandwidth(150000)
    ///                 .codecs(&["avc1.42e00a", "mp4a.40.2"])
    ///                 .resolution((416, 234))
    ///                 .build()
    ///                 .unwrap(),
    ///         },
    ///         VariantStream::ExtXStreamInf {
    ///             uri: "http://example.com/lo_mid/index.m3u8".into(),
    ///             frame_rate: None,
    ///             audio: None,
    ///             subtitles: None,
    ///             closed_captions: None,
    ///             stream_data: StreamData::builder()
    ///                 .bandwidth(240000)
    ///                 .codecs(&["avc1.42e00a", "mp4a.40.2"])
    ///                 .resolution((416, 234))
    ///                 .build()
    ///                 .unwrap(),
    ///         },
    ///     ])
    ///     .has_independent_segments(true)
    ///     .start(ExtXStart::new(Float::new(1.23)))
    ///     .build()?;
    /// # Ok::<(), Box<dyn ::std::error::Error>>(())
    /// ```
    #[must_use]
    #[inline]
    pub fn builder() -> MasterPlaylistBuilder<'a> { MasterPlaylistBuilder::default() }

    /// Returns all streams, which have an audio group id.
    pub fn audio_streams(&self) -> impl Iterator<Item = &VariantStream<'a>> {
        self.variant_streams.iter().filter(|stream| {
            if let VariantStream::ExtXStreamInf { audio: Some(_), .. } = stream {
                true
            } else {
                false
            }
        })
    }

    /// Returns all streams, which have a video group id.
    pub fn video_streams(&self) -> impl Iterator<Item = &VariantStream<'a>> {
        self.variant_streams.iter().filter(|stream| {
            if let VariantStream::ExtXStreamInf { stream_data, .. } = stream {
                stream_data.video().is_some()
            } else if let VariantStream::ExtXIFrame { stream_data, .. } = stream {
                stream_data.video().is_some()
            } else {
                false
            }
        })
    }

    /// Returns all streams, which have no group id.
    pub fn unassociated_streams(&self) -> impl Iterator<Item = &VariantStream<'a>> {
        self.variant_streams.iter().filter(|stream| {
            if let VariantStream::ExtXStreamInf {
                stream_data,
                audio: None,
                subtitles: None,
                closed_captions: None,
                ..
            } = stream
            {
                stream_data.video().is_none()
            } else if let VariantStream::ExtXIFrame { stream_data, .. } = stream {
                stream_data.video().is_none()
            } else {
                false
            }
        })
    }

    /// Returns all `ExtXMedia` tags, associated with the provided stream.
    pub fn associated_with<'b>(
        &'b self,
        stream: &'b VariantStream<'_>,
    ) -> impl Iterator<Item = &ExtXMedia<'a>> + 'b {
        self.media
            .iter()
            .filter(move |media| stream.is_associated(media))
    }

    /// Makes the struct independent of its lifetime, by taking ownership of all
    /// internal [`Cow`]s.
    ///
    /// # Note
    ///
    /// This is a relatively expensive operation.
    #[must_use]
    #[allow(clippy::redundant_closure_for_method_calls)]
    pub fn into_owned(self) -> MasterPlaylist<'static> {
        MasterPlaylist {
            has_independent_segments: self.has_independent_segments,
            start: self.start,
            media: self.media.into_iter().map(|v| v.into_owned()).collect(),
            variant_streams: self
                .variant_streams
                .into_iter()
                .map(|v| v.into_owned())
                .collect(),
            session_data: self
                .session_data
                .into_iter()
                .map(|v| v.into_owned())
                .collect(),
            session_keys: self
                .session_keys
                .into_iter()
                .map(|v| v.into_owned())
                .collect(),
            unknown_tags: self
                .unknown_tags
                .into_iter()
                .map(|v| Cow::Owned(v.into_owned()))
                .collect(),
        }
    }
}

impl<'a> RequiredVersion for MasterPlaylist<'a> {
    fn required_version(&self) -> ProtocolVersion {
        required_version![
            self.has_independent_segments
                .athen_some(ExtXIndependentSegments),
            self.start,
            self.media,
            self.variant_streams,
            self.session_data,
            self.session_keys
        ]
    }
}

impl<'a> MasterPlaylistBuilder<'a> {
    fn validate(&self) -> Result<(), String> {
        if let Some(variant_streams) = &self.variant_streams {
            self.validate_variants(variant_streams)
                .map_err(|e| e.to_string())?;
        }

        self.validate_session_data_tags()
            .map_err(|e| e.to_string())?;

        Ok(())
    }

    fn validate_variants(&self, variant_streams: &[VariantStream<'_>]) -> crate::Result<()> {
        let mut closed_captions_none = false;

        for variant in variant_streams {
            match &variant {
                VariantStream::ExtXStreamInf {
                    audio,
                    subtitles,
                    closed_captions,
                    stream_data,
                    ..
                } => {
                    if let Some(group_id) = &audio {
                        if !self.check_media_group(MediaType::Audio, group_id) {
                            return Err(Error::unmatched_group(group_id));
                        }
                    }

                    if let Some(group_id) = &stream_data.video() {
                        if !self.check_media_group(MediaType::Video, group_id) {
                            return Err(Error::unmatched_group(group_id));
                        }
                    }

                    if let Some(group_id) = &subtitles {
                        if !self.check_media_group(MediaType::Subtitles, group_id) {
                            return Err(Error::unmatched_group(group_id));
                        }
                    }

                    if let Some(closed_captions) = &closed_captions {
                        match &closed_captions {
                            ClosedCaptions::GroupId(group_id) => {
                                if closed_captions_none {
                                    return Err(Error::custom("ClosedCaptions has to be `None`"));
                                }

                                if !self.check_media_group(MediaType::ClosedCaptions, group_id) {
                                    return Err(Error::unmatched_group(group_id));
                                }
                            }
                            _ => {
                                if !closed_captions_none {
                                    closed_captions_none = true;
                                }
                            }
                        }
                    }
                }

                VariantStream::ExtXIFrame { stream_data, .. } => {
                    if let Some(group_id) = stream_data.video() {
                        if !self.check_media_group(MediaType::Video, group_id) {
                            return Err(Error::unmatched_group(group_id));
                        }
                    }
                }
            }
        }

        Ok(())
    }

    fn validate_session_data_tags(&self) -> crate::Result<()> {
        let mut set = HashSet::new();

        if let Some(values) = &self.session_data {
            set.reserve(values.len());

            for tag in values {
                if !set.insert((tag.data_id(), tag.language())) {
                    return Err(Error::custom(format!("conflict: {}", tag)));
                }
            }
        }

        Ok(())
    }

    fn check_media_group<T: AsRef<str>>(&self, media_type: MediaType, group_id: T) -> bool {
        if let Some(value) = &self.media {
            value.iter().any(|media| {
                media.media_type == media_type && media.group_id().as_ref() == group_id.as_ref()
            })
        } else {
            false
        }
    }
}

impl<'a> RequiredVersion for MasterPlaylistBuilder<'a> {
    fn required_version(&self) -> ProtocolVersion {
        // TODO: the .flatten() can be removed as soon as `recursive traits` are
        //       supported. (RequiredVersion is implemented for Option<T>, but
        //       not for Option<Option<T>>)
        // https://github.com/rust-lang/chalk/issues/12
        required_version![
            self.has_independent_segments
                .unwrap_or(false)
                .athen_some(ExtXIndependentSegments),
            self.start.flatten(),
            self.media,
            self.variant_streams,
            self.session_data,
            self.session_keys
        ]
    }
}

impl<'a> fmt::Display for MasterPlaylist<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "{}", ExtM3u)?;

        if self.required_version() != ProtocolVersion::V1 {
            writeln!(f, "{}", ExtXVersion::new(self.required_version()))?;
        }

        for value in &self.media {
            writeln!(f, "{}", value)?;
        }

        for value in &self.variant_streams {
            writeln!(f, "{}", value)?;
        }

        for value in &self.session_data {
            writeln!(f, "{}", value)?;
        }

        for value in &self.session_keys {
            writeln!(f, "{}", value)?;
        }

        if self.has_independent_segments {
            writeln!(f, "{}", ExtXIndependentSegments)?;
        }

        if let Some(value) = &self.start {
            writeln!(f, "{}", value)?;
        }

        for value in &self.unknown_tags {
            writeln!(f, "{}", value)?;
        }

        Ok(())
    }
}

impl<'a> TryFrom<&'a str> for MasterPlaylist<'a> {
    type Error = Error;

    fn try_from(input: &'a str) -> Result<Self, Self::Error> {
        let input = tag(input, ExtM3u::PREFIX)?;
        let mut builder = Self::builder();

        let mut media = vec![];
        let mut variant_streams = vec![];
        let mut session_data = vec![];
        let mut session_keys = vec![];
        let mut unknown_tags = vec![];

        for line in Lines::from(input) {
            match line? {
                Line::Tag(tag) => {
                    match tag {
                        Tag::ExtXVersion(_) => {
                            // This tag can be ignored, because the
                            // MasterPlaylist will automatically set the
                            // ExtXVersion tag to the minimum required version
                            // TODO: this might be verified?
                        }
                        Tag::ExtInf(_)
                        | Tag::ExtXByteRange(_)
                        | Tag::ExtXDiscontinuity(_)
                        | Tag::ExtXKey(_)
                        | Tag::ExtXMap(_)
                        | Tag::ExtXProgramDateTime(_)
                        | Tag::ExtXDateRange(_)
                        | Tag::ExtXTargetDuration(_)
                        | Tag::ExtXMediaSequence(_)
                        | Tag::ExtXDiscontinuitySequence(_)
                        | Tag::ExtXEndList(_)
                        | Tag::PlaylistType(_)
                        | Tag::ExtXIFramesOnly(_) => {
                            return Err(Error::unexpected_tag(tag));
                        }
                        Tag::ExtXMedia(t) => {
                            media.push(t);
                        }
                        Tag::VariantStream(t) => {
                            variant_streams.push(t);
                        }
                        Tag::ExtXSessionData(t) => {
                            session_data.push(t);
                        }
                        Tag::ExtXSessionKey(t) => {
                            session_keys.push(t);
                        }
                        Tag::ExtXIndependentSegments(_) => {
                            builder.has_independent_segments(true);
                        }
                        Tag::ExtXStart(t) => {
                            builder.start(t);
                        }
                        Tag::Unknown(value) => {
                            // [6.3.1. General Client Responsibilities]
                            // > ignore any unrecognized tags.
                            unknown_tags.push(Cow::Borrowed(value));
                        }
                    }
                }
                Line::Uri(uri) => {
                    return Err(Error::custom(format!("unexpected uri: {:?}", uri)));
                }
                Line::Comment(_) => {}
            }
        }

        builder.media(media);
        builder.variant_streams(variant_streams);
        builder.session_data(session_data);
        builder.session_keys(session_keys);
        builder.unknown_tags(unknown_tags);

        builder.build().map_err(Error::builder)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::StreamData;
    use pretty_assertions::assert_eq;

    #[test]
    fn test_audio_streams() {
        let astreams = vec![
            VariantStream::ExtXStreamInf {
                uri: "http://example.com/low/index.m3u8".into(),
                frame_rate: None,
                audio: Some("ag0".into()),
                subtitles: None,
                closed_captions: None,
                stream_data: StreamData::builder()
                    .bandwidth(150_000)
                    .codecs(&["avc1.42e00a", "mp4a.40.2"])
                    .resolution((416, 234))
                    .build()
                    .unwrap(),
            },
            VariantStream::ExtXStreamInf {
                uri: "http://example.com/lo_mid/index.m3u8".into(),
                frame_rate: None,
                audio: Some("ag1".into()),
                subtitles: None,
                closed_captions: None,
                stream_data: StreamData::builder()
                    .bandwidth(240_000)
                    .codecs(&["avc1.42e00a", "mp4a.40.2"])
                    .resolution((416, 234))
                    .build()
                    .unwrap(),
            },
        ];

        let master_playlist = MasterPlaylist::builder()
            .variant_streams(astreams.clone())
            .media(vec![
                ExtXMedia::builder()
                    .media_type(MediaType::Audio)
                    .uri("https://www.example.com/ag0.m3u8")
                    .group_id("ag0")
                    .language("english")
                    .name("alternative rendition for ag0")
                    .build()
                    .unwrap(),
                ExtXMedia::builder()
                    .media_type(MediaType::Audio)
                    .uri("https://www.example.com/ag1.m3u8")
                    .group_id("ag1")
                    .language("english")
                    .name("alternative rendition for ag1")
                    .build()
                    .unwrap(),
            ])
            .build()
            .unwrap();

        assert_eq!(
            master_playlist.variant_streams,
            master_playlist.audio_streams().collect::<Vec<_>>()
        );

        let mut audio_streams = master_playlist.audio_streams();

        assert_eq!(audio_streams.next(), Some(&astreams[0]));
        assert_eq!(audio_streams.next(), Some(&astreams[1]));
        assert_eq!(audio_streams.next(), None);
    }

    #[test]
    fn test_parser() {
        assert_eq!(
            MasterPlaylist::try_from(concat!(
                "#EXTM3U\n",
                "#EXT-X-STREAM-INF:",
                "BANDWIDTH=150000,CODECS=\"avc1.42e00a,mp4a.40.2\",RESOLUTION=416x234\n",
                "http://example.com/low/index.m3u8\n",
                "#EXT-X-STREAM-INF:",
                "BANDWIDTH=240000,CODECS=\"avc1.42e00a,mp4a.40.2\",RESOLUTION=416x234\n",
                "http://example.com/lo_mid/index.m3u8\n",
                "#EXT-X-STREAM-INF:",
                "BANDWIDTH=440000,CODECS=\"avc1.42e00a,mp4a.40.2\",RESOLUTION=416x234\n",
                "http://example.com/hi_mid/index.m3u8\n",
                "#EXT-X-STREAM-INF:",
                "BANDWIDTH=640000,CODECS=\"avc1.42e00a,mp4a.40.2\",RESOLUTION=640x360\n",
                "http://example.com/high/index.m3u8\n",
                "#EXT-X-STREAM-INF:BANDWIDTH=64000,CODECS=\"mp4a.40.5\"\n",
                "http://example.com/audio/index.m3u8\n"
            ))
            .unwrap(),
            MasterPlaylist::builder()
                .variant_streams(vec![
                    VariantStream::ExtXStreamInf {
                        uri: "http://example.com/low/index.m3u8".into(),
                        frame_rate: None,
                        audio: None,
                        subtitles: None,
                        closed_captions: None,
                        stream_data: StreamData::builder()
                            .bandwidth(150_000)
                            .codecs(&["avc1.42e00a", "mp4a.40.2"])
                            .resolution((416, 234))
                            .build()
                            .unwrap()
                    },
                    VariantStream::ExtXStreamInf {
                        uri: "http://example.com/lo_mid/index.m3u8".into(),
                        frame_rate: None,
                        audio: None,
                        subtitles: None,
                        closed_captions: None,
                        stream_data: StreamData::builder()
                            .bandwidth(240_000)
                            .codecs(&["avc1.42e00a", "mp4a.40.2"])
                            .resolution((416, 234))
                            .build()
                            .unwrap()
                    },
                    VariantStream::ExtXStreamInf {
                        uri: "http://example.com/hi_mid/index.m3u8".into(),
                        frame_rate: None,
                        audio: None,
                        subtitles: None,
                        closed_captions: None,
                        stream_data: StreamData::builder()
                            .bandwidth(440_000)
                            .codecs(&["avc1.42e00a", "mp4a.40.2"])
                            .resolution((416, 234))
                            .build()
                            .unwrap()
                    },
                    VariantStream::ExtXStreamInf {
                        uri: "http://example.com/high/index.m3u8".into(),
                        frame_rate: None,
                        audio: None,
                        subtitles: None,
                        closed_captions: None,
                        stream_data: StreamData::builder()
                            .bandwidth(640_000)
                            .codecs(&["avc1.42e00a", "mp4a.40.2"])
                            .resolution((640, 360))
                            .build()
                            .unwrap()
                    },
                    VariantStream::ExtXStreamInf {
                        uri: "http://example.com/audio/index.m3u8".into(),
                        frame_rate: None,
                        audio: None,
                        subtitles: None,
                        closed_captions: None,
                        stream_data: StreamData::builder()
                            .bandwidth(64000)
                            .codecs(&["mp4a.40.5"])
                            .build()
                            .unwrap()
                    },
                ])
                .build()
                .unwrap()
        );
    }

    #[test]
    fn test_display() {
        assert_eq!(
            MasterPlaylist::builder()
                .variant_streams(vec![
                    VariantStream::ExtXStreamInf {
                        uri: "http://example.com/low/index.m3u8".into(),
                        frame_rate: None,
                        audio: None,
                        subtitles: None,
                        closed_captions: None,
                        stream_data: StreamData::builder()
                            .bandwidth(150_000)
                            .codecs(&["avc1.42e00a", "mp4a.40.2"])
                            .resolution((416, 234))
                            .build()
                            .unwrap()
                    },
                    VariantStream::ExtXStreamInf {
                        uri: "http://example.com/lo_mid/index.m3u8".into(),
                        frame_rate: None,
                        audio: None,
                        subtitles: None,
                        closed_captions: None,
                        stream_data: StreamData::builder()
                            .bandwidth(240_000)
                            .codecs(&["avc1.42e00a", "mp4a.40.2"])
                            .resolution((416, 234))
                            .build()
                            .unwrap()
                    },
                    VariantStream::ExtXStreamInf {
                        uri: "http://example.com/hi_mid/index.m3u8".into(),
                        frame_rate: None,
                        audio: None,
                        subtitles: None,
                        closed_captions: None,
                        stream_data: StreamData::builder()
                            .bandwidth(440_000)
                            .codecs(&["avc1.42e00a", "mp4a.40.2"])
                            .resolution((416, 234))
                            .build()
                            .unwrap()
                    },
                    VariantStream::ExtXStreamInf {
                        uri: "http://example.com/high/index.m3u8".into(),
                        frame_rate: None,
                        audio: None,
                        subtitles: None,
                        closed_captions: None,
                        stream_data: StreamData::builder()
                            .bandwidth(640_000)
                            .codecs(&["avc1.42e00a", "mp4a.40.2"])
                            .resolution((640, 360))
                            .build()
                            .unwrap()
                    },
                    VariantStream::ExtXStreamInf {
                        uri: "http://example.com/audio/index.m3u8".into(),
                        frame_rate: None,
                        audio: None,
                        subtitles: None,
                        closed_captions: None,
                        stream_data: StreamData::builder()
                            .bandwidth(64000)
                            .codecs(&["mp4a.40.5"])
                            .build()
                            .unwrap()
                    },
                ])
                .build()
                .unwrap()
                .to_string(),
            concat!(
                "#EXTM3U\n",
                //
                "#EXT-X-STREAM-INF:",
                "BANDWIDTH=150000,CODECS=\"avc1.42e00a,mp4a.40.2\",RESOLUTION=416x234\n",
                "http://example.com/low/index.m3u8\n",
                //
                "#EXT-X-STREAM-INF:",
                "BANDWIDTH=240000,CODECS=\"avc1.42e00a,mp4a.40.2\",RESOLUTION=416x234\n",
                "http://example.com/lo_mid/index.m3u8\n",
                //
                "#EXT-X-STREAM-INF:",
                "BANDWIDTH=440000,CODECS=\"avc1.42e00a,mp4a.40.2\",RESOLUTION=416x234\n",
                "http://example.com/hi_mid/index.m3u8\n",
                //
                "#EXT-X-STREAM-INF:",
                "BANDWIDTH=640000,CODECS=\"avc1.42e00a,mp4a.40.2\",RESOLUTION=640x360\n",
                "http://example.com/high/index.m3u8\n",
                //
                "#EXT-X-STREAM-INF:BANDWIDTH=64000,CODECS=\"mp4a.40.5\"\n",
                "http://example.com/audio/index.m3u8\n"
            )
            .to_string()
        );
    }
}