dash-runtime 0.4.0

Sans-IO MPEG-DASH (ISO/IEC 23009-1): MPD model and parser, segment addressing, UTC clock and live-edge arithmetic, and a client for static and dynamic presentations. No I/O, no clock reads.
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
//! Hostile MPD corpus: every bound is a typed error, nothing panics, nothing
//! allocates in proportion to a claimed size.

use crate::common;

use common::Rng;
use dash_runtime::address::{PlanOptions, plan_representation};
use dash_runtime::error::{Limit, MpdError};
use dash_runtime::limits::Limits;
use dash_runtime::mpd::{Mpd, PresentationType};
use dash_runtime::selection::{Policy, RepRef, select};

const NS: &str = "urn:mpeg:dash:schema:mpd:2011";

fn wrap(inner: &str) -> String {
    format!(r#"<MPD xmlns="{NS}" type="static">{inner}</MPD>"#)
}

fn parse(s: &str) -> Result<Mpd, MpdError> {
    Mpd::parse(s.as_bytes())
}

fn too_large(r: Result<Mpd, MpdError>) -> Limit {
    match r {
        Err(MpdError::TooLarge { limit, .. }) => limit,
        other => panic!("expected TooLarge, got {other:?}"),
    }
}

#[test]
fn billion_laughs_is_refused_before_any_expansion() {
    let xml = r#"<?xml version="1.0"?>
<!DOCTYPE lolz [
 <!ENTITY lol "lol">
 <!ENTITY lol2 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">
 <!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">
]>
<MPD xmlns="urn:mpeg:dash:schema:mpd:2011"><BaseURL>&lol3;</BaseURL></MPD>"#;
    match parse(xml) {
        Err(MpdError::Xml { message, .. }) => assert!(message.contains("DOCTYPE"), "{message}"),
        other => panic!("{other:?}"),
    }
    let external =
        r#"<!DOCTYPE MPD SYSTEM "file:///etc/passwd"><MPD xmlns="urn:mpeg:dash:schema:mpd:2011"/>"#;
    assert!(matches!(parse(external), Err(MpdError::Xml { .. })));
    assert!(matches!(
        parse(&wrap("<BaseURL>&undefined;</BaseURL>")),
        Err(MpdError::Xml { .. })
    ));
    assert_eq!(
        parse(&wrap("<BaseURL>a&amp;b&#65;</BaseURL>"))
            .unwrap()
            .base_urls[0]
            .url,
        "a&bA"
    );
}

#[test]
fn element_count_bound() {
    let ok = wrap(&"<Foo/>".repeat(99_998));
    assert!(parse(&ok).is_ok());
    let bad = wrap(&"<Foo/>".repeat(100_000));
    assert_eq!(too_large(parse(&bad)), Limit::Elements);
}

#[test]
fn depth_bound() {
    let nest = |n: usize| {
        let mut s = String::new();
        for _ in 0..n {
            s.push_str("<Foo>");
        }
        for _ in 0..n {
            s.push_str("</Foo>");
        }
        wrap(&s)
    };
    assert!(parse(&nest(30)).is_ok(), "MPD + 30 = depth 31");
    assert!(
        parse(&nest(31)).is_ok(),
        "MPD + 31 = depth 32, exactly the limit"
    );
    assert_eq!(too_large(parse(&nest(32))), Limit::Depth);
    assert_eq!(too_large(parse(&nest(5_000))), Limit::Depth);
}

#[test]
fn caller_limits_override_each_xml_bound() {
    let nest = |n: usize| {
        let mut s = String::new();
        s.push_str(&"<Foo>".repeat(n));
        s.push_str(&"</Foo>".repeat(n));
        wrap(&s)
    };
    let deep = nest(100);
    assert_eq!(too_large(parse(&deep)), Limit::Depth);
    let mut limits = Limits::default();
    limits.max_depth = 200;
    assert!(Mpd::parse_with(deep.as_bytes(), &limits).is_ok());
    limits.max_depth = 5;
    assert_eq!(
        too_large(Mpd::parse_with(nest(5).as_bytes(), &limits)),
        Limit::Depth
    );
    let mut tight = Limits::default();
    tight.max_elements = 2;
    assert_eq!(
        too_large(Mpd::parse_with(wrap("<A/><B/>").as_bytes(), &tight)),
        Limit::Elements
    );
    let mut tight = Limits::default();
    tight.max_attributes = 1;
    assert_eq!(
        too_large(Mpd::parse_with(
            format!(r#"<MPD xmlns="{NS}" type="static" x="1"/>"#).as_bytes(),
            &tight
        )),
        Limit::Attributes
    );
    let mut tight = Limits::default();
    tight.max_attribute_bytes = 3;
    assert_eq!(
        too_large(Mpd::parse_with(
            format!(r#"<MPD xmlns="{NS}" type="static" x="1234"/>"#).as_bytes(),
            &tight
        )),
        Limit::AttributeBytes
    );
}

#[test]
fn attribute_bounds() {
    let long = |n: usize| {
        wrap(&format!(
            r#"<BaseURL serviceLocation="{}">x</BaseURL>"#,
            "a".repeat(n)
        ))
    };
    assert!(parse(&long(8 * 1024)).is_ok());
    assert_eq!(too_large(parse(&long(8 * 1024 + 1))), Limit::AttributeBytes);
    let many = |n: usize| {
        let attrs: String = (0..n).map(|i| format!(r#" a{i}="1""#)).collect();
        wrap(&format!("<Foo{attrs}/>"))
    };
    assert!(parse(&many(256)).is_ok());
    assert_eq!(too_large(parse(&many(257))), Limit::Attributes);
}

#[test]
fn structure_bounds() {
    assert_eq!(
        too_large(parse(&wrap(&"<Period/>".repeat(1_001)))),
        Limit::Periods
    );
    assert!(parse(&wrap(&"<Period/>".repeat(1_000))).is_ok());
    let sets = format!("<Period>{}</Period>", "<AdaptationSet/>".repeat(1_001));
    assert_eq!(too_large(parse(&wrap(&sets))), Limit::AdaptationSets);
    let reps = format!(
        "<Period><AdaptationSet>{}</AdaptationSet></Period>",
        (0..1_001)
            .map(|i| format!(r#"<Representation id="{i}" bandwidth="1"/>"#))
            .collect::<String>()
    );
    assert_eq!(too_large(parse(&wrap(&reps))), Limit::Representations);
    assert_eq!(
        too_large(parse(&wrap(&"<BaseURL>x</BaseURL>".repeat(65)))),
        Limit::BaseUrls
    );
    let tl = format!(
        r#"<Period><AdaptationSet><Representation id="r" bandwidth="1"><SegmentTemplate media="$Number$" duration="1"><SegmentTimeline>{}</SegmentTimeline></SegmentTemplate></Representation></AdaptationSet></Period>"#,
        r#"<S d="1"/>"#.repeat(100_001)
    );
    let r = Mpd::parse_with(wrap(&tl).as_bytes(), &Limits::default());
    assert!(matches!(
        r,
        Err(MpdError::TooLarge {
            limit: Limit::TimelineEntries | Limit::Elements,
            ..
        })
    ));
    let mut loose_elements = Limits::default();
    loose_elements.max_elements = 200_000;
    loose_elements.max_timeline_entries = 100_000;
    assert_eq!(
        too_large(Mpd::parse_with(wrap(&tl).as_bytes(), &loose_elements)),
        Limit::TimelineEntries
    );
    let urls = format!(
        r#"<Period><AdaptationSet><Representation id="r" bandwidth="1"><SegmentList duration="1">{}</SegmentList></Representation></AdaptationSet></Period>"#,
        r#"<SegmentURL media="a"/>"#.repeat(100_001)
    );
    assert!(matches!(
        Mpd::parse(wrap(&urls).as_bytes()),
        Err(MpdError::TooLarge {
            limit: Limit::SegmentUrls | Limit::Elements,
            ..
        })
    ));
    let mut loose_elements = Limits::default();
    loose_elements.max_elements = 200_000;
    loose_elements.max_segment_urls = 100_000;
    assert_eq!(
        too_large(Mpd::parse_with(wrap(&urls).as_bytes(), &loose_elements)),
        Limit::SegmentUrls
    );
}

#[test]
fn input_size_bound_and_custom_limits() {
    let big = vec![b' '; 4 * 1024 * 1024 + 1];
    assert!(matches!(
        Mpd::parse(&big),
        Err(MpdError::TooLarge {
            limit: Limit::InputBytes,
            ..
        })
    ));
    let mut tight = Limits::default();
    tight.max_periods = 1;
    assert!(matches!(
        Mpd::parse_with(wrap("<Period/><Period/>").as_bytes(), &tight),
        Err(MpdError::TooLarge {
            limit: Limit::Periods,
            max: 1
        })
    ));
}

#[test]
fn byte_level_garbage() {
    assert!(matches!(
        Mpd::parse(&[b'<', b'M', 0xff, 0xfe, b'>']),
        Err(MpdError::InvalidUtf8 { valid_up_to: 2 })
    ));
    assert!(matches!(
        parse(&wrap("<BaseURL>a\u{0}b</BaseURL>")),
        Err(MpdError::Xml { .. })
    ));
    assert!(matches!(
        parse(&wrap("<BaseURL serviceLocation=\"a\u{0}b\">x</BaseURL>")),
        Err(MpdError::Xml { .. })
    ));
    assert!(matches!(
        parse(&wrap("<BaseURL>&#0;</BaseURL>")),
        Err(MpdError::Xml { .. })
    ));
    assert!(matches!(parse(""), Err(MpdError::Xml { .. })));
    assert!(matches!(parse("not xml at all"), Err(MpdError::Xml { .. })));
    assert!(matches!(
        parse(&format!(r#"<MPD xmlns="{NS}">"#)),
        Err(MpdError::Xml { .. })
    ));
    assert!(matches!(
        parse(&format!(r#"<MPD xmlns="{NS}"></Foo>"#)),
        Err(MpdError::Xml { .. })
    ));
    assert!(matches!(
        parse(&format!(r#"<MPD xmlns="{NS}"/><MPD xmlns="{NS}"/>"#)),
        Err(MpdError::Xml { .. })
    ));
    assert!(matches!(
        parse(&format!(r#"junk<MPD xmlns="{NS}"/>"#)),
        Err(MpdError::Xml { .. })
    ));
}

#[test]
fn not_an_mpd() {
    assert!(matches!(parse("<html/>"), Err(MpdError::NotMpd { .. })));
    assert!(matches!(
        parse(r#"<MPD xmlns="urn:other"/>"#),
        Err(MpdError::NotMpd { found }) if found == "MPD"
    ));
    assert!(matches!(parse("<MPD/>"), Err(MpdError::NotMpd { .. })));
    assert!(matches!(
        parse(&format!(r#"<Other xmlns="{NS}"/>"#)),
        Err(MpdError::NotMpd { .. })
    ));
}

#[test]
fn schema_violations_are_typed_not_panics() {
    for (what, xml) in [
        (
            "bad duration",
            r#"<MPD xmlns="urn:mpeg:dash:schema:mpd:2011" mediaPresentationDuration="soon"/>"#,
        ),
        (
            "bad type",
            r#"<MPD xmlns="urn:mpeg:dash:schema:mpd:2011" type="live"/>"#,
        ),
        (
            "bad time",
            r#"<MPD xmlns="urn:mpeg:dash:schema:mpd:2011" availabilityStartTime="yesterday"/>"#,
        ),
    ] {
        assert!(
            matches!(parse(xml), Err(MpdError::Invalid { .. })),
            "{what}"
        );
    }
    assert_eq!(
        parse(r#"<MPD xmlns="urn:mpeg:dash:schema:mpd:2011" type="list"/>"#)
            .expect("an ed.6 list MPD is in scope")
            .kind,
        PresentationType::List
    );
    let rep = |attrs: &str| {
        wrap(&format!(
            r#"<Period><AdaptationSet><Representation {attrs}/></AdaptationSet></Period>"#
        ))
    };
    assert!(matches!(
        parse(&rep(r#"bandwidth="1""#)),
        Err(MpdError::Invalid { .. })
    ));
    assert!(matches!(
        parse(&rep(r#"id="x""#)),
        Err(MpdError::Invalid { .. })
    ));
    assert!(matches!(
        parse(&rep(r#"id="x" bandwidth="-1""#)),
        Err(MpdError::Invalid { .. })
    ));
    assert!(matches!(
        parse(&rep(r#"id="x" bandwidth="99999999999999999999999""#)),
        Err(MpdError::Invalid { .. })
    ));
    let seg = |inner: &str| {
        wrap(&format!(
            r#"<Period><AdaptationSet><Representation id="x" bandwidth="1">{inner}</Representation></AdaptationSet></Period>"#
        ))
    };
    assert!(matches!(
        parse(&seg(r#"<SegmentTemplate duration="0"/>"#)),
        Err(MpdError::Invalid { .. })
    ));
    assert!(matches!(
        parse(&seg(r#"<SegmentTemplate timescale="0"/>"#)),
        Err(MpdError::Invalid { .. })
    ));
    assert!(matches!(
        parse(&seg(
            r#"<SegmentTemplate><SegmentTimeline><S d="0"/></SegmentTimeline></SegmentTemplate>"#
        )),
        Err(MpdError::Invalid { .. })
    ));
    assert!(matches!(
        parse(&seg(
            r#"<SegmentTemplate><SegmentTimeline><S/></SegmentTimeline></SegmentTemplate>"#
        )),
        Err(MpdError::Invalid { .. })
    ));
    assert!(matches!(
        parse(&seg(r#"<SegmentBase indexRange="9-3"/>"#)),
        Err(MpdError::Invalid { .. })
    ));
    assert!(matches!(
        parse(&seg(r#"<SegmentBase indexRange="abc"/>"#)),
        Err(MpdError::Invalid { .. })
    ));
    assert!(matches!(
        parse(&seg(r#"<SegmentBase/><SegmentTemplate/>"#)),
        Err(MpdError::Invalid { .. })
    ));
}

#[test]
fn huge_timeline_repeat_is_bounded_lazily() {
    let xml = wrap(
        r#"<Period><AdaptationSet mimeType="video/mp4"><Representation id="r" bandwidth="1">
           <SegmentTemplate timescale="1" media="$Time$"><SegmentTimeline><S t="0" d="1" r="9223372036854775807"/></SegmentTimeline></SegmentTemplate>
           </Representation></AdaptationSet></Period>"#,
    );
    let mpd = parse(&xml).unwrap();
    assert!(matches!(
        plan_representation(&mpd, RepRef::at(0, 0, 0), &PlanOptions::default()),
        Err(dash_runtime::address::representation::PlanError::Address(
            ..
        ))
    ));
}

#[test]
fn foreign_content_is_skipped_but_counted() {
    let xml = format!(
        r#"<MPD xmlns="{NS}" xmlns:x="urn:vendor" type="static"><x:Blob>{}</x:Blob><BaseURL>b/</BaseURL></MPD>"#,
        "<x:i/>".repeat(1_000)
    );
    let m = parse(&xml).unwrap();
    assert_eq!(m.base_urls.len(), 1);
}

#[test]
fn resolve_to_zero_xlink_removes_the_element() {
    let xml = wrap(
        r#"<Period xlink:href="urn:mpeg:dash:resolve-to-zero:2013" xmlns:xlink="http://www.w3.org/1999/xlink"/><Period id="keep"/>"#,
    );
    let m = parse(&xml).unwrap();
    assert_eq!(m.periods.len(), 1);
    assert_eq!(m.periods[0].id.as_deref(), Some("keep"));
    assert!(m.features.xlink_resolve_to_zero);
    let remote = wrap(
        r#"<Period xlink:href="http://x/p.xml" xlink:actuate="onLoad" xmlns:xlink="http://www.w3.org/1999/xlink"/>"#,
    );
    let m = parse(&remote).unwrap();
    assert_eq!(m.periods[0].xlink.as_ref().unwrap().href, "http://x/p.xml");
}

fn mutate(rng: &mut Rng, src: &[u8]) -> Vec<u8> {
    let mut b = src.to_vec();
    for _ in 0..=rng.below(4) {
        if b.is_empty() {
            break;
        }
        let at = usize::try_from(rng.below(b.len() as u64)).unwrap();
        match rng.below(5) {
            0 => b[at] = u8::try_from(rng.below(256)).unwrap(),
            1 => b[at] ^= 1 << rng.below(8),
            2 => {
                b.remove(at);
            }
            3 => b.insert(
                at,
                b"<>&\"'/=$%0123456789"[usize::try_from(rng.below(19)).unwrap()],
            ),
            _ => b.truncate(at.max(1)),
        }
    }
    b
}

#[test]
fn mutated_fixtures_never_panic() {
    let mut rng = Rng(0xDEAD_BEEF);
    let mut files = Vec::new();
    for entry in walkdir(&test_fixtures::path("dash")) {
        files.push(entry);
    }
    let (mut parsed, mut planned) = (0usize, 0usize);
    for f in &files {
        let src = std::fs::read(f).unwrap();
        for _ in 0..400 {
            let m = mutate(&mut rng, &src);
            let Ok(mpd) = Mpd::parse(&m) else { continue };
            parsed += 1;
            for (pi, p) in mpd.periods.iter().enumerate() {
                let _ = select(&mpd, pi, &Policy::default());
                for (si, s) in p.adaptation_sets.iter().enumerate() {
                    for ri in 0..s.representations.len() {
                        if let Ok(pl) = plan_representation(
                            &mpd,
                            RepRef::at(pi, si, ri),
                            &PlanOptions::default(),
                        ) {
                            planned += 1;
                            let _ = pl.plan.get(0);
                            let _ = pl.plan.iter().take(50).count();
                            let _ = pl.plan.init();
                        }
                    }
                }
            }
        }
    }
    eprintln!("mutants: {parsed} parsed, {planned} planned");
    assert!(parsed > 1_000, "only {parsed} mutants parsed");
    assert!(planned > 500, "only {planned} planned");
}

fn walkdir(dir: &std::path::Path) -> Vec<std::path::PathBuf> {
    let mut out = Vec::new();
    for e in std::fs::read_dir(dir).unwrap() {
        let p = e.unwrap().path();
        if p.is_dir() {
            out.extend(walkdir(&p));
        } else if p.extension().is_some_and(|x| x == "mpd") {
            out.push(p);
        }
    }
    out.sort();
    out
}