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
use crate::;
use PhantomData;
/// A reader that parses lines of input HLS playlist data.
///
/// The `Reader` is the primary intended structure provided by the library for parsing HLS playlist
/// data. The user has the flexibility to define which of the library provided HLS tags should be
/// parsed as well as define a custom tag type to be extracted during parsing.
///
/// ## Basic usage
///
/// A reader can take an input `&str` (or `&[u8]`) and sequentially parse information about HLS
/// lines. For example, you could use the `Reader` to build up a media playlist:
/// ```
/// # use quick_m3u8::{HlsLine, Reader};
/// # use quick_m3u8::config::ParsingOptions;
/// # use quick_m3u8::tag::{
/// # hls::{self, DiscontinuitySequence, MediaSequence, Targetduration, Version, M3u},
/// # KnownTag,
/// # };
/// # let playlist = r#"#EXTM3U
/// # #EXT-X-TARGETDURATION:4
/// # #EXT-X-MEDIA-SEQUENCE:541647
/// # #EXT-X-VERSION:6
/// # "#;
/// #[derive(Debug, PartialEq)]
/// struct MediaPlaylist<'a> {
/// version: u64,
/// targetduration: u64,
/// media_sequence: u64,
/// discontinuity_sequence: u64,
/// // etc.
/// lines: Vec<HlsLine<'a>>,
/// }
/// let mut reader = Reader::from_str(playlist, ParsingOptions::default());
///
/// let mut version = None;
/// let mut targetduration = None;
/// let mut media_sequence = 0;
/// let mut discontinuity_sequence = 0;
/// // etc.
/// let mut lines = Vec::new();
///
/// // Validate playlist header
/// match reader.read_line() {
/// Ok(Some(HlsLine::KnownTag(KnownTag::Hls(hls::Tag::M3u(tag))))) => {
/// lines.push(HlsLine::from(tag))
/// }
/// _ => return Err(format!("missing playlist header").into()),
/// }
///
/// loop {
/// match reader.read_line() {
/// Ok(Some(line)) => match line {
/// HlsLine::KnownTag(KnownTag::Hls(hls::Tag::Version(tag))) => {
/// version = Some(tag.version());
/// lines.push(HlsLine::from(tag));
/// }
/// HlsLine::KnownTag(KnownTag::Hls(hls::Tag::Targetduration(tag))) => {
/// targetduration = Some(tag.target_duration());
/// lines.push(HlsLine::from(tag));
/// }
/// HlsLine::KnownTag(KnownTag::Hls(hls::Tag::MediaSequence(tag))) => {
/// media_sequence = tag.media_sequence();
/// lines.push(HlsLine::from(tag));
/// }
/// HlsLine::KnownTag(KnownTag::Hls(hls::Tag::DiscontinuitySequence(tag))) => {
/// discontinuity_sequence = tag.discontinuity_sequence();
/// lines.push(HlsLine::from(tag));
/// }
/// // etc.
/// _ => lines.push(line),
/// },
/// Ok(None) => break, // End of playlist
/// Err(e) => return Err(format!("problem reading line: {e}").into()),
/// }
/// }
///
/// let version = version.unwrap_or(1);
/// let Some(targetduration) = targetduration else {
/// return Err("missing required EXT-X-TARGETDURATION".into());
/// };
/// let media_playlist = MediaPlaylist {
/// version,
/// targetduration,
/// media_sequence,
/// discontinuity_sequence,
/// lines,
/// };
///
/// assert_eq!(
/// media_playlist,
/// MediaPlaylist {
/// version: 6,
/// targetduration: 4,
/// media_sequence: 541647,
/// discontinuity_sequence: 0,
/// lines: vec![
/// // --snip--
/// # HlsLine::from(M3u),
/// # HlsLine::from(Targetduration::new(4)),
/// # HlsLine::from(MediaSequence::new(541647)),
/// # HlsLine::from(Version::new(6)),
/// ],
/// }
/// );
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// ## Configuring known tags
///
/// It is quite common that a user does not need to support parsing of all HLS tags for their use-
/// case. To support this better the `Reader` allows for configuration of what HLS tags are
/// considered "known" by the library. While it may sound strange to configure for less information
/// to be parsed, doing so can have significant performance benefits, and at no loss if the
/// information is not needed anyway. Unknown tags make no attempt to parse or validate the value
/// portion of the tag (the part after `:`) and just provide the name of the tag along with the line
/// up to (and not including) the new line characters. To provide some indication of the performance
/// difference, running locally (as of commit `6fcc38a67bf0eee0769b7e85f82599d1da6eb56d`), the
/// benchmarks show that on a very large media playlist parsing with all tags can be around 2x
/// slower than parsing with no tags (`2.3842 ms` vs `1.1364 ms`):
/// ```sh
/// Large playlist, all tags, using Reader::from_str, no writing
/// time: [2.3793 ms 2.3842 ms 2.3891 ms]
/// Large playlist, no tags, using Reader::from_str, no writing
/// time: [1.1357 ms 1.1364 ms 1.1372 ms]
/// ```
///
/// For example, let's say that we are updating a playlist to add in HLS interstitial daterange,
/// based on SCTE35-OUT information in an upstream playlist. The only tag we need to know about for
/// this is EXT-X-DATERANGE, so we can configure our reader to only consider this tag during parsing
/// which provides a benefit in terms of processing time.
/// ```
/// # use quick_m3u8::{
/// # Reader, HlsLine, Writer,
/// # config::ParsingOptionsBuilder,
/// # tag::KnownTag,
/// # tag::hls::{self, Cue, Daterange, ExtensionAttributeValue},
/// # };
/// # use std::{borrow::Cow, error::Error, io::Write};
/// # fn advert_id_from_scte35_out(_: &str) -> Option<String> { None }
/// # fn advert_uri_from_id(_: &str) -> String { String::new() }
/// # fn duration_from_daterange(_: &Daterange) -> f64 { 0.0 }
/// # let output = Vec::new();
/// # let upstream_playlist = b"";
/// let mut reader = Reader::from_bytes(
/// upstream_playlist,
/// ParsingOptionsBuilder::new()
/// .with_parsing_for_daterange()
/// .build(),
/// );
/// let mut writer = Writer::new(output);
///
/// loop {
/// match reader.read_line() {
/// Ok(Some(HlsLine::KnownTag(KnownTag::Hls(hls::Tag::Daterange(tag))))) => {
/// if let Some(advert_id) = tag.scte35_out().and_then(advert_id_from_scte35_out) {
/// let id = format!("ADVERT:{}", tag.id());
/// let builder = Daterange::builder()
/// .with_id(id)
/// .with_class("com.apple.hls.interstitial")
/// .with_cue(Cue::Once)
/// .with_extension_attribute(
/// "X-ASSET-URI",
/// ExtensionAttributeValue::QuotedString(Cow::Owned(
/// advert_uri_from_id(&advert_id),
/// )),
/// )
/// .with_extension_attribute(
/// "X-RESTRICT",
/// ExtensionAttributeValue::QuotedString(Cow::Borrowed("SKIP,JUMP")),
/// );
/// // START-DATE has been clarified to be optional as of draft 18, so we need to
/// // check for existence. In reality, I should store the start dates of all found
/// // dateranges, to properly set the correct START-DATE on this interstitial tag;
/// // however, this is just a basic example and that's not the point I'm trying to
/// // illustrate, so leaving that out for now.
/// let builder = if let Some(start_date) = tag.start_date() {
/// builder.with_start_date(start_date)
/// } else {
/// builder
/// };
/// let interstitial_daterange = if duration_from_daterange(&tag) == 0.0 {
/// builder
/// .with_extension_attribute(
/// "X-RESUME-OFFSET",
/// ExtensionAttributeValue::SignedDecimalFloatingPoint(0.0),
/// )
/// .finish()
/// } else {
/// builder.finish()
/// };
/// writer.write_line(HlsLine::from(interstitial_daterange))?;
/// } else {
/// writer.write_line(HlsLine::from(tag))?;
/// }
/// }
/// Ok(Some(line)) => {
/// writer.write_line(line)?;
/// }
/// Ok(None) => break, // End of playlist
/// Err(e) => {
/// writer.get_mut().write_all(e.errored_line)?;
/// }
/// };
/// }
///
/// writer.into_inner().flush()?;
/// # Ok::<(), Box<dyn Error>>(())
/// ```
///
/// ## Custom tag reading
///
/// We can also configure the `Reader` to accept parsing of custom defined tags. Using the same idea
/// as above, we can imagine that instead of EXT-X-DATERANGE in the upstream playlist, we want to
/// depend on the EXT-X-SCTE35 tag that is defined within the SCTE35 specification. This tag is not
/// defined in the HLS specification; however, we can define it here, and use it when it comes to
/// parsing and utilizing that data. Below is a modified version of the above HLS interstitials
/// example that instead relies on a custom defined `Scte35Tag` (though I leave the details of
/// `TryFrom<ParsedTag>` unfilled for sake of simplicity in this example). Note, when defining a
/// that the reader should use a custom tag, utilize `std::marker::PhantomData` to specify what the
/// type of the custom tag is.
/// ```
/// # use quick_m3u8::{
/// # Reader, HlsLine, Writer,
/// # config::ParsingOptionsBuilder,
/// # tag::{KnownTag, UnknownTag, CustomTag, WritableCustomTag, WritableTag},
/// # tag::hls::{self, Cue, Daterange, ExtensionAttributeValue},
/// # tag::hls::{DaterangeIdHasBeenSet, DaterangeBuilder},
/// # error::ValidationError,
/// # };
/// # use std::{borrow::Cow, error::Error, io::Write, marker::PhantomData};
/// # fn advert_id_from_scte35_out(_: &str) -> Option<String> { None }
/// # fn advert_uri_from_id(_: &str) -> String { String::new() }
/// # fn generate_uuid() -> &'static str { "" }
/// # fn with_start_date_based_on_inf_durations(
/// # builder: DaterangeBuilder<'_, DaterangeIdHasBeenSet>
/// # ) -> DaterangeBuilder<'_, DaterangeIdHasBeenSet> {
/// # todo!();
/// # }
/// # let output: Vec<u8> = Vec::new();
/// # let upstream_playlist = b"";
/// #[derive(Debug, PartialEq, Clone)]
/// struct Scte35Tag<'a> {
/// cue: &'a str,
/// duration: Option<f64>,
/// elapsed: Option<f64>,
/// id: Option<&'a str>,
/// time: Option<f64>,
/// type_id: Option<u64>,
/// upid: Option<&'a str>,
/// blackout: Option<BlackoutValue>,
/// cue_out: Option<CueOutValue>,
/// cue_in: bool,
/// segne: Option<(u64, u64)>,
/// }
/// #[derive(Debug, PartialEq, Clone)]
/// enum BlackoutValue {
/// Yes,
/// No,
/// Maybe,
/// }
/// #[derive(Debug, PartialEq, Clone)]
/// enum CueOutValue {
/// Yes,
/// No,
/// Cont,
/// }
/// impl<'a> TryFrom<UnknownTag<'a>> for Scte35Tag<'a> { // --snip--
/// # type Error = ValidationError;
/// # fn try_from(value: UnknownTag<'a>) -> Result<Self, Self::Error> {
/// # todo!()
/// # }
/// }
/// impl<'a> CustomTag<'a> for Scte35Tag<'a> {
/// fn is_known_name(name: &str) -> bool {
/// name == "-X-SCTE35"
/// }
/// }
/// impl<'a> WritableCustomTag<'a> for Scte35Tag<'a> { // --snip--
/// # fn into_writable_tag(self) -> WritableTag<'a> {
/// # todo!()
/// # }
/// }
/// #
/// # let output: Vec<u8> = Vec::new();
/// # let upstream_playlist = b"";
///
/// let mut reader = Reader::with_custom_from_bytes(
/// upstream_playlist,
/// ParsingOptionsBuilder::new().build(),
/// PhantomData::<Scte35Tag>,
/// );
/// let mut writer = Writer::new(output);
///
/// loop {
/// match reader.read_line() {
/// Ok(Some(HlsLine::KnownTag(KnownTag::Custom(tag)))) => {
/// if let Some(advert_id) = advert_id_from_scte35_out(tag.as_ref().cue) {
/// let tag_ref = tag.as_ref();
/// let id = format!("ADVERT:{}", tag_ref.id.unwrap_or(generate_uuid()));
/// let builder = Daterange::builder()
/// .with_id(id)
/// .with_class("com.apple.hls.interstitial")
/// .with_cue(Cue::Once)
/// .with_extension_attribute(
/// "X-ASSET-URI",
/// ExtensionAttributeValue::QuotedString(Cow::Owned(
/// advert_uri_from_id(&advert_id),
/// )),
/// )
/// .with_extension_attribute(
/// "X-RESTRICT",
/// ExtensionAttributeValue::QuotedString(Cow::Borrowed("SKIP,JUMP")),
/// );
/// let builder = with_start_date_based_on_inf_durations(builder);
/// let interstitial_daterange = if tag_ref.duration == Some(0.0) {
/// builder
/// .with_extension_attribute(
/// "X-RESUME-OFFSET",
/// ExtensionAttributeValue::SignedDecimalFloatingPoint(0.0),
/// )
/// .finish()
/// } else {
/// builder.finish()
/// };
/// writer.write_line(HlsLine::from(interstitial_daterange))?;
/// } else {
/// writer.write_custom_line(HlsLine::from(tag))?;
/// }
/// }
/// Ok(Some(line)) => {
/// writer.write_custom_line(line)?;
/// }
/// Ok(None) => break, // End of playlist
/// Err(e) => {
/// writer.get_mut().write_all(e.errored_line)?;
/// }
/// };
/// }
///
/// writer.into_inner().flush()?;
///
/// # Ok::<(), Box<dyn Error>>(())
/// ```
impl_reader!;
impl_reader!;
// Example taken from HLS specification with one custom tag added.
// https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-18#section-9.1
const EXAMPLE_MANIFEST: &str = r#"#EXTM3U
#EXT-X-TARGETDURATION:10
#EXT-X-VERSION:3
#EXT-X-EXAMPLE-TAG:MEANING-OF-LIFE=42,QUESTION="UNKNOWN"
#EXTINF:9.009,
http://media.example.com/first.ts
#EXTINF:9.009,
http://media.example.com/second.ts
#EXTINF:3.003,
http://media.example.com/third.ts
#EXT-X-ENDLIST
"#;