# Validate HLS and DASH Manifests Before Any Player Opens Them

> Much of what breaks a stream is visible in its manifests before playback starts. Build a Node validator that quotes the failing line for target durations, rendition groups, codecs, misaligned discontinuities, DASH timeline gaps and live segments deleted before the spec allows, tested against ffmpeg fixtures.

- Author: [Shashank Rawlani](https://shashank.rawlani.com)

- Published: 2026-11-22T13:30:00.000Z

- Updated: 2026-11-22T13:30:00.000Z

- Category: Automation Tutorials

- Canonical source: https://automationtester.in/blog/automation-tutorials/validate-hls-dash-manifests-before-playback

- Tags: streaming, hls, mpeg-dash, ffmpeg, playwright, test-automation

**Quick answer:** From the manifests and plain HTTP requests alone, before any player starts, you can prove that every playlist and segment URI answers 200, that each `EXTINF` rounds to no more than `EXT-X-TARGETDURATION`, that renditions in a group have unique `NAME`s and at most one default, that every `CODECS` string is one your target browser's `MediaSource` accepts, that discontinuities fall at the same media time in every rendition, that a DASH `SegmentTimeline` has no gaps, and that a live manifest both advances on time and keeps the segments it announced fetchable for as long as the specification promises. Decoding, timing and adaptation stay out of reach. Parse line by line so each failure quotes its line; a player-oriented parser can drop a duplicate rendition silently.

A live event goes out with English and Hindi audio. At the first break the programme cuts to a slate, and the packager writes an `EXT-X-DISCONTINUITY` into every media playlist. In the video playlists the tag sits at 12.000 seconds. In the Hindi playlist it sits one segment later, at 16.043 seconds. RFC 8216 gives every segment a Discontinuity Sequence Number so that clients can line up renditions across a join, and it requires matching content to carry matching numbers. Here the first slate segment of video and the first slate segment of Hindi audio carry different ones.

No playback test was needed to find this. A validator that knows the rule reports the file, the line and both media times in under a second. This article builds one against ffmpeg fixtures, breaks them one defect at a time, and quotes what each check printed.

This is part 2 of the streaming quality series. [Part 1](/blog/automation-tutorials/streaming-quality-model-beyond-video-starts) split a viewing session into separate contracts, each observed at its own layer. This part covers the layer below the player: the manifests and the origin that serves them. Player behaviour, startup timing and bitrate switching come later.

**Versions checked on 2026-11-18:** ffmpeg 9.0.1 (Homebrew, libx264 and the native AAC encoder), Node.js 26.12.1, Playwright 1.62.1 with its bundled Chromium 151.0.7922.34, `m3u8-parser` 7.2.1 and `mpd-parser` 1.4.1, pinned with `npm install --save-exact`. The lab ran on macOS arm64 against a local Node static server on `http://localhost:8080`. All media is synthetic (`testsrc2`, `smptebars`, `sine` and `anullsrc`). The RFC 8216bis text cited is Internet-Draft revision 22, dated 1 May 2026, which is a draft and not a standard.

## What the manifest text can settle

Each check maps to a rule you can open and read, so when a packager vendor disputes a failure, the argument is with a section number rather than your code.

| Check | Rule | Source |
| --- | --- | --- |
| Segment length | `EXTINF` rounded to the nearest integer must be at most the target duration; every media playlist in a variant must share one target duration, except subtitle and I-frame playlists of type VOD | RFC 8216 4.3.3.1, 6.2.4 |
| Rendition groups | Members of one group have different `NAME`s; at most one has `DEFAULT=YES` | RFC 8216 4.3.4.1.1 |
| Codecs | Every `EXT-X-STREAM-INF` should carry `CODECS`; when present it must list every format in any segment of any rendition of that variant | RFC 8216 4.3.4.2, 6.2.4 |
| Discontinuities | Matching content in different variants must have matching Discontinuity Sequence Numbers | RFC 8216 6.2.4 |
| Live HLS window | A new playlist with at least one new segment within 1.5 times the target duration; the window never shorter than three target durations; a removed segment stays available for its own duration plus the longest playlist that contained it | RFC 8216 6.2.1, 6.2.2 |
| DASH timeline | When an `S` element ends before the next one starts, the Representation has a gap and no media is present for it | DASH-IF IOP 4.3, 4.3.2.2.5 |
| DASH live window | Every segment an MPD announces must be available from its availability start time until its availability end time | DASH-IF IOP 4.3, 4.3.3.1 |

The codec row has a limit worth stating precisely. The W3C Media Source Extensions draft says a `true` from `isTypeSupported()` only means the implementation can create a `SourceBuffer` for that type. It does not promise the device decodes that profile and level in real time. It also allows a browser to treat a codec that was not declared in the type passed to `addSourceBuffer()` as unsupported when the initialization segment arrives, which is the browser-side cost of an incomplete `CODECS` attribute.

## A two-language event with a slate break

The fixture is a 12-second programme and a 4-second slate, each encoded as a two-rung video ladder with English and Hindi audio renditions, then stitched into one event with a discontinuity at the join. The DASH fixture carries the same programme as one video Representation and two audio Adaptation Sets.

```
#!/usr/bin/env bash
# Builds every fixture from ffmpeg's synthetic sources. No downloaded media.
set -euo pipefail
cd "$(dirname "$0")"
rm -rf www && mkdir -p www/parts www/dash

ladder() { # $1 = video source, $2 = eng audio, $3 = hin audio, $4 = seconds, $5 = out dir
  mkdir -p "$5"
  ffmpeg -hide_banner -loglevel error -f lavfi -i "$1" -f lavfi -i "$2" -f lavfi -i "$3" -t "$4" \
    -map 0:v -map 0:v -map 1:a -map 2:a \
    -c:v libx264 -profile:v main -preset veryfast -g 50 -keyint_min 50 -sc_threshold 0 \
    -filter:v:0 scale=640:360 -b:v:0 800k -b:v:1 2500k \
    -c:a aac -b:a 96k -ac 2 -ar 48000 \
    -f hls -hls_time 4 -hls_playlist_type vod -hls_segment_filename "$5/%v/seg%03d.ts" \
    -master_pl_name master.m3u8 \
    -var_stream_map "v:0,agroup:aud,name:360p v:1,agroup:aud,name:720p a:0,agroup:aud,language:eng,name:eng,default:yes a:1,agroup:aud,language:hin,name:hin" \
    "$5/%v/index.m3u8"
}

# 12 s of programme, then a 4 s slate with silent audio (the break filler).
ladder "testsrc2=size=1280x720:rate=25" "sine=frequency=440:sample_rate=48000" "sine=frequency=660:sample_rate=48000" 12 www/parts/programme
ladder "smptebars=size=1280x720:rate=25" "anullsrc=r=48000:cl=stereo" "anullsrc=r=48000:cl=stereo" 4 www/parts/slate

# DASH: one video Representation, two audio Adaptation Sets, SegmentTimeline addressing.
ffmpeg -hide_banner -loglevel error -f lavfi -i "testsrc2=size=1280x720:rate=25" \
  -f lavfi -i "sine=frequency=440:sample_rate=48000" -f lavfi -i "sine=frequency=660:sample_rate=48000" -t 12 \
  -map 0:v -map 1:a -map 2:a \
  -c:v libx264 -profile:v main -preset veryfast -g 50 -keyint_min 50 -sc_threshold 0 -b:v 1500k \
  -c:a aac -b:a 96k -ac 2 -metadata:s:a:0 language=eng -metadata:s:a:1 language=hin \
  -f dash -seg_duration 4 -use_timeline 1 -use_template 1 \
  -adaptation_sets "id=0,streams=v id=1,streams=1 id=2,streams=2" www/dash/manifest.mpd

node stitch.mjs
node mutate.mjs
echo '<!doctype html><title>codec probe</title>' > www/blank.html
echo "built: $(find www -type f | wc -l | tr -d ' ') files"
```

`stitch.mjs` then writes each event playlist as programme segments, one `#EXT-X-DISCONTINUITY`, and slate segments. The Hindi result:

```
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:4
#EXT-X-MEDIA-SEQUENCE:0
#EXT-X-PLAYLIST-TYPE:VOD
#EXTINF:4.010667,
../../parts/programme/hin/seg000.ts
#EXTINF:3.989333,
../../parts/programme/hin/seg001.ts
#EXTINF:4.010667,
../../parts/programme/hin/seg002.ts
#EXTINF:0.021333,
../../parts/programme/hin/seg003.ts
#EXT-X-DISCONTINUITY
#EXTINF:4.010667,
../../parts/slate/hin/seg000.ts
#EXTINF:0.021333,
../../parts/slate/hin/seg001.ts
#EXT-X-ENDLIST
```

Two details shape the checks. The audio segments are 4.010667 and 3.989333 seconds, and each part ends with a 0.021333-second segment, exactly 1,024 samples at 48 kHz. Audio boundaries therefore never land exactly on video boundaries, and in this clean fixture the audio join sits 0.032 seconds after the video join. A discontinuity check with zero tolerance fails a correct stream. And ffmpeg 9.0.1 wrote the renditions as `NAME="audio_2"` and `NAME="audio_3"`, generated names rather than the language labels a viewer would see in a track menu.

## Why the validator reads lines itself

A player-oriented parser turns a playlist into the object a player needs. That object is not built to keep defects. `m3u8-parser` 7.2.1 stores each rendition with `mediaGroup[entry.attributes.NAME] = rendition`, so two renditions that share a `NAME` become one key, and the later one wins.

```
// What a general-purpose parser keeps when two renditions share a NAME.
import { Parser } from 'm3u8-parser';
import fs from 'node:fs';

const parser = new Parser();
parser.push(fs.readFileSync(process.argv[2], 'utf8'));
parser.end();
const group = parser.manifest.mediaGroups.AUDIO.group_aud;
console.log(Object.entries(group).map(([name, r]) => `${name}: ${r.language} default=${r.default}`));
```

```
$ node collapse.mjs www/event/master.m3u8
[ 'audio_2: eng default=true', 'audio_3: hin default=false' ]
$ node collapse.mjs www/mut-dup-name/master.m3u8
[ 'audio_2: hin default=false' ]
```

Against the copy with a duplicated name, the English rendition and its `DEFAULT=YES` are gone, and the parser raised no warning. A validator built on that object would report one healthy Hindi track. The validator here reads the HLS text line by line, keeps line numbers so every finding can quote its source, and computes each segment's Discontinuity Sequence Number the way RFC 8216 defines it: the `EXT-X-DISCONTINUITY-SEQUENCE` value, or zero, plus the discontinuity tags before that segment.

```
function parseMedia(text, base) {
  const lines = text.split('\n');
  const pl = { lines, td: null, msn: 0, dsn: 0, endList: false, segments: [], syntax: [] };
  if (lines[0].trim() !== '#EXTM3U') pl.syntax.push([1, lines[0], 'first line is not #EXTM3U']);
  let pending = null; let disc = 0; let t = 0; let pdt = null;
  lines.forEach((raw, i) => {
    const l = raw.trim();
    if (l.startsWith('#EXT-X-TARGETDURATION:')) pl.td = { value: Number(l.split(':')[1]), line: i + 1, raw: l };
    else if (l.startsWith('#EXT-X-MEDIA-SEQUENCE:')) pl.msn = Number(l.split(':')[1]);
    else if (l.startsWith('#EXT-X-DISCONTINUITY-SEQUENCE:')) pl.dsn = Number(l.split(':')[1]);
    else if (l === '#EXT-X-DISCONTINUITY') disc++;
    else if (l === '#EXT-X-ENDLIST') pl.endList = true;
    else if (l.startsWith('#EXT-X-PROGRAM-DATE-TIME:')) pdt = Date.parse(l.slice(25));
    else if (l.startsWith('#EXTINF:')) pending = { dur: parseFloat(l.slice(8)), line: i + 1, raw: l };
    else if (l && !l.startsWith('#')) {
      if (!pending) { pl.syntax.push([i + 1, l, 'URI with no #EXTINF before it']); return; }
      pl.segments.push({ ...pending, uri: new URL(l, base).href, msn: pl.msn + pl.segments.length,
        dsn: pl.dsn + disc, start: t, pdt });
      t += pending.dur; pending = null; pdt = null;
    }
  });
  if (!pl.td) pl.syntax.push([0, '', 'EXT-X-TARGETDURATION is missing (REQUIRED)']);
  return pl;
}
```

For DASH the validator uses `mpd-parser` 1.4.1, because hand-parsing XML with regular expressions breaks on the first reformatted file. It still keeps the raw MPD text, so a timeline failure can quote the exact `S` element.

## The checks, one rule at a time

### Rendition groups and the target duration

Groups are keyed by `TYPE` and `GROUP-ID`, as RFC 8216 defines a Group of Renditions. Durations are rounded with `Math.round` before the comparison because the rule is about the rounded value: a 4.4-second segment under a 4-second target is legal, and a 4.6-second one is not.

```
  // Rendition groups: NAME unique inside a group, at most one DEFAULT=YES, every AUDIO= reference resolves.
  const groups = Map.groupBy(media, (m) => `${m.TYPE}/${m['GROUP-ID']}`);
  for (const [g, members] of groups) {
    const seen = new Map();
    for (const m of members) {
      if (seen.has(m.NAME)) report('FAIL', 'groups', `master:${m.line}`, `${m.raw}  NAME already used on line ${seen.get(m.NAME)}`);
      seen.set(m.NAME, m.line);
    }
    const defaults = members.filter((m) => m.DEFAULT === 'YES');
    if (defaults.length > 1) report('FAIL', 'groups', `master:${defaults[1].line}`, `${g} has ${defaults.length} DEFAULT=YES members`);
  }

  for (const pl of playlists) {
    for (const [n, l, why] of pl.syntax) report('FAIL', 'syntax', `${pl.name}:${n}`, `${l}  ${why}`);
    if (!pl.td) continue;
    for (const s of pl.segments) {
      if (Math.round(s.dur) > pl.td.value) {
        report('FAIL', 'duration', `${pl.name}:${s.line}`, `${s.raw}  rounds to ${Math.round(s.dur)} > EXT-X-TARGETDURATION ${pl.td.value}`);
      }
    }
  }
  const tds = new Set(playlists.filter((p) => p.td && p.type !== 'SUBTITLES').map((p) => p.td.value));
  if (tds.size > 1) report('FAIL', 'duration', 'all', `target durations differ across renditions: ${[...tds].join(', ')}`);
```

### Discontinuities at the same media time

Media time in a playlist is the running sum of `EXTINF` values. The check finds each segment whose Discontinuity Sequence Number changes and compares that media time with the first variant's. The 0.1-second tolerance is a policy chosen to absorb the 0.032-second audio offset above. It is not a number from the RFC, and the comment says so.

```
  // Discontinuities: same boundaries, at the same media time, in every rendition.
  const TOLERANCE = 0.1; // seconds; a policy, not an RFC number
  const boundaries = (pl) => pl.segments.filter((s, i) => i > 0 && s.dsn !== pl.segments[i - 1].dsn)
    .map((s) => ({ dsn: s.dsn, at: s.start, line: s.line - 1 }));
  const ref = playlists[0];
  for (const pl of playlists.slice(1)) {
    const a = boundaries(ref); const b = boundaries(pl);
    if (a.length !== b.length) { report('FAIL', 'discontinuity', pl.name, `${b.length} boundaries, ${ref.name} has ${a.length}`); continue; }
    a.forEach((x, i) => {
      if (Math.abs(x.at - b[i].at) > TOLERANCE) {
        report('FAIL', 'discontinuity', `${pl.name}:${b[i].line}`, `#EXT-X-DISCONTINUITY at ${b[i].at.toFixed(3)} s, ${ref.name} at ${x.at.toFixed(3)} s`);
      }
    });
  }
```

### Codec strings, asked of the browser

A string such as `avc1.4d401f` encodes a profile and level, and whether it is acceptable belongs to the browser engine, not to the stream. The check loads a page from `localhost` in Playwright's Chromium and asks `MediaSource.isTypeSupported()` directly. The HLS fixture uses MPEG-TS segments, which hls.js transmuxes into fragmented MP4 before they reach MSE, so the check asks about `video/mp4` and `audio/mp4`.

```
// ---------- Codecs, asked of the browser that will play them ----------
async function checkCodecs(types) {
  if (!types.length) return;
  const browser = await chromium.launch();
  const page = await browser.newPage();
  await page.goto('http://localhost:8080/blank.html'); // a secure context, like the real player page
  const answers = await page.evaluate((ts) => ts.map((t) => [t, MediaSource.isTypeSupported(t)]), types);
  const version = browser.version();
  await browser.close();
  for (const [t, ok] of answers) report(ok ? 'PASS' : 'FAIL', 'codecs', `Chromium ${version}`, `isTypeSupported('${t}') = ${ok}`);
}
```

Against the clean fixtures, both formats pass:

```
$ node validate.mjs http://localhost:8080/event/master.m3u8
PASS codecs        Chromium 151.0.7922.34 isTypeSupported('video/mp4; codecs="avc1.4d401e"') = true
PASS codecs        Chromium 151.0.7922.34 isTypeSupported('audio/mp4; codecs="mp4a.40.2"') = true
PASS codecs        Chromium 151.0.7922.34 isTypeSupported('video/mp4; codecs="avc1.4d401f"') = true
PASS all           master.m3u8            4 playlists, 20 segments
exit 0
$ node validate.mjs http://localhost:8080/dash/manifest.mpd
PASS codecs        Chromium 151.0.7922.34 isTypeSupported('video/mp4; codecs="avc1.4d401f"') = true
PASS codecs        Chromium 151.0.7922.34 isTypeSupported('audio/mp4; codecs="mp4a.40.2"') = true
PASS all           manifest.mpd           3 representations, 14 URIs
exit 0
```

## Five broken copies and the lines they quote

Each mutation copies a good fixture and changes exactly one thing, so a failure can only have one cause.

```
// Each mutation is a copy of a good fixture with exactly one defect.
import fs from 'node:fs';

function mutate(name, from, file, find, replace) {
  const dir = `www/mut-${name}`;
  fs.cpSync(`www/${from}`, dir, { recursive: true });
  const p = `${dir}/${file}`;
  const before = fs.readFileSync(p, 'utf8');
  const after = before.replace(find, replace);
  if (after === before) throw new Error(`${name}: pattern not found in ${file}`);
  fs.writeFileSync(p, after);
}

// A packager cut one 720p segment at 6.16 s while still declaring a 4 s target.
mutate('overlong', 'event', '720p/index.m3u8', '#EXTINF:4.000000,', '#EXTINF:6.160000,');
// The Hindi rendition was renamed at the origin; the master still points at the old path.
mutate('missing-audio', 'event', 'master.m3u8', 'URI="hin/index.m3u8"', 'URI="hin/index-v2.m3u8"');
// The break inserter put the Hindi discontinuity one segment late.
mutate('late-disc', 'event', 'hin/index.m3u8',
  '#EXT-X-DISCONTINUITY\n#EXTINF:4.010667,\n../../parts/slate/hin/seg000.ts\n',
  '#EXTINF:4.010667,\n../../parts/slate/hin/seg000.ts\n#EXT-X-DISCONTINUITY\n');
// Two audio renditions in one group share a NAME.
mutate('dup-name', 'event', 'master.m3u8', 'NAME="audio_3"', 'NAME="audio_2"');
// The Hindi Adaptation Set skips one segment's worth of media time.
mutate('gap', 'dash', 'manifest.mpd', /(lang="hin"[\s\S]*?)<S d="192512" r="1" \/>/, '$1<S t="380928" d="192512" r="1" />');
```

```
$ node validate.mjs http://localhost:8080/mut-overlong/master.m3u8 | grep -v 'PASS codecs'
FAIL duration      720p/index.m3u8:6      #EXTINF:6.160000,  rounds to 6 > EXT-X-TARGETDURATION 4
FAIL discontinuity 720p/index.m3u8:12     #EXT-X-DISCONTINUITY at 14.160 s, 360p/index.m3u8 at 12.000 s
$ node validate.mjs http://localhost:8080/mut-missing-audio/master.m3u8 | grep -v 'PASS codecs'
FAIL uri           master:4               #EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="group_aud",NAME="audio_3",... -> hin/index-v2.m3u8 HTTP 404
$ node validate.mjs http://localhost:8080/mut-late-disc/master.m3u8 | grep -v 'PASS codecs'
FAIL discontinuity hin/index.m3u8:16      #EXT-X-DISCONTINUITY at 16.043 s, 360p/index.m3u8 at 12.000 s
$ node validate.mjs http://localhost:8080/mut-dup-name/master.m3u8 | grep -v 'PASS codecs'
FAIL groups        master:4               #EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="group_aud",NAME="audio_2",DEFAULT=NO,LANGUAGE="hin",CHANNELS="2",URI="hin/index.m3u8"  NAME already used on line 3
$ node validate.mjs http://localhost:8080/mut-gap/manifest.mpd | grep -v 'PASS codecs'
FAIL timeline      Representation 2, mpd:43 <S t="380928" d="192512" r="1" />  gap of 4.011 s before segment chunk-stream2-00002.m4s
```

The overlong segment produced two findings from one defect. A 6.16-second segment shifts every later media time in that playlist by 2.16 seconds, so the 720p join now reads 14.160 seconds. Fix the first finding in a list and re-run before chasing the rest. The missing audio rendition passes every text rule; only the request to `hin/index-v2.m3u8` shows nothing is there. The duplicate name is reported at line 4 with a pointer to line 3, the input the parser above reduced to one track.

## Live HLS: the window has to move, and old copies have to keep working

A live playlist adds two promises a VOD playlist does not make. The server must publish a new version with at least one new segment no later than 1.5 times the target duration after the previous one. And a segment that leaves the playlist must stay fetchable for its own duration plus the duration of the longest playlist that contained it, because a client may still be working through an older copy. The fixture runs ffmpeg at wall-clock speed into four outputs that differ only in how long old segments stay on disk.

```
#!/usr/bin/env bash
# A real live packager: ffmpeg at wall-clock speed (-re) writing four outputs
# that differ only in how long old segments are kept on disk.
set -euo pipefail
cd "$(dirname "$0")"
rm -rf www/live-* && mkdir -p www/live-hls www/live-hls-kept www/live-dash www/live-dash-tight
enc=(-c:v libx264 -preset veryfast -g 50 -keyint_min 50 -sc_threshold 0 -b:v 800k -c:a aac -b:a 96k)
hls=(-f hls -hls_time 2 -hls_list_size 6 -hls_flags delete_segments+program_date_time)
dash=(-f dash -seg_duration 2 -window_size 6 -use_timeline 1 -use_template 1)
ffmpeg -hide_banner -loglevel error -re -f lavfi -i "testsrc2=size=640x360:rate=25" \
  -re -f lavfi -i "sine=frequency=440:sample_rate=48000" \
  -map 0:v -map 1:a "${enc[@]}" "${hls[@]}" -hls_segment_filename "www/live-hls/s%05d.ts" www/live-hls/index.m3u8 \
  -map 0:v -map 1:a "${enc[@]}" "${hls[@]}" -hls_delete_threshold 7 -hls_segment_filename "www/live-hls-kept/s%05d.ts" www/live-hls-kept/index.m3u8 \
  -map 0:v -map 1:a "${enc[@]}" "${dash[@]}" www/live-dash/manifest.mpd \
  -map 0:v -map 1:a "${enc[@]}" "${dash[@]}" -extra_window_size 0 www/live-dash-tight/manifest.mpd &
echo "$!" > live.pid
echo "packager pid $(cat live.pid)"
```

The live check reloads after 1.5 times the target duration, which also keeps it inside the client reload limits of RFC 8216 section 6.3.4: no sooner than one target duration after a changed playlist, or half of one after an unchanged playlist. It then compares Media Sequence Numbers and, once the original playlist's duration has passed, requests every segment of the copy it fetched first.

```
async function checkHlsLive(pl) {
  const td = pl.td.value;
  const last = pl.segments.at(-1);
  const span = pl.segments.reduce((a, s) => a + s.dur, 0);
  if (span < 3 * td) report('FAIL', 'live', pl.name, `window is ${span.toFixed(1)} s, under 3 x target duration (${3 * td} s)`);
  if (last.pdt) report('INFO', 'live', pl.name, `edge age ${((Date.now() - (last.pdt + last.dur * 1000)) / 1000).toFixed(1)} s (PROGRAM-DATE-TIME of last segment + EXTINF)`);
  await pause(1.5 * td);
  const again = parseMedia((await fetchText(pl.url)).text, pl.url);
  const newest = again.segments.at(-1)?.msn ?? -1;
  if (newest <= last.msn) report('FAIL', 'live', pl.name, `no new segment after ${1.5 * td} s (1.5 x target duration); last MSN still ${last.msn}`);
  else report('PASS', 'live', pl.name, `window moved: last MSN ${last.msn} -> ${newest}`);
  if (again.msn < pl.msn) report('FAIL', 'live', pl.name, `EXT-X-MEDIA-SEQUENCE went backwards: ${pl.msn} -> ${again.msn}`);
  for (const s of again.segments) {
    const old = pl.segments.find((o) => o.msn === s.msn);
    if (old && old.uri !== s.uri) report('FAIL', 'live', pl.name, `MSN ${s.msn} was ${short(old.uri)}, now ${short(s.uri)}`);
  }
  // RFC 8216 6.2.2: a removed segment stays available for its duration plus the playlist's duration.
  const hold = span;
  await pause(Math.max(0, hold - 1.5 * td));
  const gone = [];
  for (const s of pl.segments) if ((await head(s.uri)) !== 200) gone.push(short(s.uri).split('/').at(-1));
  if (gone.length) report('FAIL', 'retention', pl.name, `${hold.toFixed(0)} s after fetch, ${gone.length}/${pl.segments.length} segments of that playlist are gone: ${gone.join(' ')}`);
  else report('PASS', 'retention', pl.name, `all ${pl.segments.length} segments still 200 after ${hold.toFixed(0)} s`);
}
```

```
$ node validate.mjs http://localhost:8080/live-hls/index.m3u8
INFO live          index.m3u8             edge age 2.2 s (PROGRAM-DATE-TIME of last segment + EXTINF)
PASS live          index.m3u8             window moved: last MSN 8 -> 10
FAIL retention     index.m3u8             12 s after fetch, 5/6 segments of that playlist are gone: s00003.ts s00004.ts s00005.ts s00006.ts s00007.ts
exit 1
$ node validate.mjs http://localhost:8080/live-hls-kept/index.m3u8
INFO live          index.m3u8             edge age 2.5 s (PROGRAM-DATE-TIME of last segment + EXTINF)
PASS live          index.m3u8             window moved: last MSN 14 -> 16
PASS retention     index.m3u8             all 6 segments still 200 after 12 s
PASS all           index.m3u8             1 playlists, 6 segments
exit 0
```

The first output uses ffmpeg's defaults with `delete_segments`. The ffmpeg documentation gives `hls_delete_threshold` a default of 1, meaning segments older than `hls_list_size` plus one are deleted. With 2-second segments in a 12-second playlist, RFC 8216 asks for each removed segment to stay available for 14 seconds; 12 seconds after the fetch, five of the six segments in that copy were gone. A client that loaded the playlist and then stalled briefly would have requested segments the server no longer had. Setting `-hls_delete_threshold 7` keeps 14 seconds of removed segments, and the same check passes.

The second live failure is a packager that stops without exiting. Freezing ffmpeg with `SIGSTOP` leaves a playlist that looks current:

```
$ kill -STOP $(cat live.pid)
$ node validate.mjs http://localhost:8080/live-hls-kept/index.m3u8
INFO live          index.m3u8             edge age 1.6 s (PROGRAM-DATE-TIME of last segment + EXTINF)
FAIL live          index.m3u8             no new segment after 3 s (1.5 x target duration); last MSN still 23
PASS retention     index.m3u8             all 6 segments still 200 after 12 s
exit 1
```

The edge age, measured from the last `EXT-X-PROGRAM-DATE-TIME` plus its `EXTINF`, read 1.6 seconds and looked healthy. Only the reload proved that the playlist had stopped moving. The 8216bis draft states the client side of the same rule: once a playlist has stayed unchanged for at least 1.5 target durations, a client may conclude the server is misbehaving and should consider switching variant or reporting the impairment. A single fetch cannot tell a frozen live playlist from a fresh one; two fetches can.

## DASH: timeline gaps and the availability window

A `SegmentTimeline` lists runs of segments as `S` elements with a start time `t`, a duration `d` and a repeat count `r`. DASH-IF IOP 4.3 says that if a run ends before the next element's `t`, the Representation contains a gap and no media is present for it. It also discourages varying segment durations, reserving the timeline for occasional shorter segments and gaps. The validator compares each segment's start with the end of the one before it:

```
  // SegmentTimeline continuity: each segment starts where the previous one ended.
  const sLines = raw.split('\n').map((l, i) => ({ l: l.trim(), n: i + 1 })).filter((x) => x.l.startsWith('<S '));
  const scales = [...raw.matchAll(/timescale="(\d+)"/g)].map((x) => Number(x[1]));
  for (const { p } of reps) {
    p.segments.forEach((s, i) => {
      if (i === 0) return;
      const prev = p.segments[i - 1];
      const gap = s.presentationTime - (prev.presentationTime + prev.duration);
      if (Math.abs(gap) > 0.001) {
        const at = sLines.find((x) => scales.some((ts) => Math.abs(Number(x.l.match(/t="(\d+)"/)?.[1]) / ts - s.presentationTime) < 0.001));
        report('FAIL', 'timeline', `Representation ${p.attributes.NAME}${at ? `, mpd:${at.n}` : ''}`,
          `${at ? at.l + '  ' : ''}${gap > 0 ? 'gap' : 'overlap'} of ${Math.abs(gap).toFixed(3)} s before segment ${s.uri}`);
      }
    });
  }
```

The gap mutation moved one Hindi `S@t` forward by a segment's worth of timescale units. The finding quotes MPD line 43 and measures the hole at 4.011 seconds, a stretch with no Hindi audio while video plays on.

For a dynamic MPD, IOP 4.3 derives each segment's availability start time as the availability start time of the MPD, plus the Period start, plus the end of the segment in media time. Its availability end time is that value plus `timeShiftBufferDepth` plus the segment's duration. Every segment the MPD announced must be fetchable between the two. The check waits one `minimumUpdatePeriod`, roughly the age of the copy a client holds just before it refreshes, and requests every segment still inside its window. The Period start is zero in these MPDs, so the code leaves it out.

```
  if (dynamic) {
    const ast = mpdAttr('availabilityStartTime'); const tsb = mpdAttr('timeShiftBufferDepth');
    if (!ast) report('FAIL', 'live', short(mpdUrl), 'dynamic MPD without availabilityStartTime');
    if (!tsb) report('WARN', 'live', short(mpdUrl), 'no timeShiftBufferDepth (recommended)');
    const secs = (d) => Number(d?.match(/PT([\d.]+)S/)?.[1] ?? 0);
    const TSB = secs(tsb); const mup = secs(mpdAttr('minimumUpdatePeriod'));
    // DASH-IF IOP 4.3.2.2.5: SAST = AST + period start + segment end; SAET = SAST + TSB + duration.
    const window = (s) => {
      const sast = Date.parse(ast) + (s.presentationTime + s.duration) * 1000;
      return { sast, saet: sast + (TSB + s.duration) * 1000 };
    };
    const edge = Math.max(...reps.map(({ p }) => window(p.segments.at(-1)).sast));
    report('INFO', 'live', short(mpdUrl), `edge age ${((fetchedAt - edge) / 1000).toFixed(1)} s, timeShiftBufferDepth ${TSB} s, minimumUpdatePeriod ${mup} s`);
    // Check the copy a client fetched one update period ago: everything still inside its window must answer.
    await pause(mup);
    const now = Date.now(); const missing = [];
    for (const { p } of reps) {
      for (const s of p.segments) {
        const w = window(s);
        if (w.sast <= now && now <= w.saet && (await head(s.resolvedUri)) !== 200) {
          missing.push(`${s.uri} (window ends in ${((w.saet - now) / 1000).toFixed(1)} s)`);
        }
      }
    }
    if (missing.length) report('FAIL', 'retention', short(mpdUrl), `${mup} s after fetch, inside the availability window but 404: ${missing.join(', ')}`);
    else report('PASS', 'retention', short(mpdUrl), `every segment inside its availability window answers 200 after ${mup} s`);
```

```
$ node validate.mjs http://localhost:8080/live-dash/manifest.mpd
INFO live          manifest.mpd           edge age 0.2 s, timeShiftBufferDepth 12 s, minimumUpdatePeriod 2 s
PASS retention     manifest.mpd           every segment inside its availability window answers 200 after 2 s
PASS codecs        Chromium 151.0.7922.34 isTypeSupported('video/mp4; codecs="avc1.64001e"') = true
PASS codecs        Chromium 151.0.7922.34 isTypeSupported('audio/mp4; codecs="mp4a.40.2"') = true
PASS all           manifest.mpd           2 representations, 14 URIs
exit 0
$ node validate.mjs http://localhost:8080/live-dash-tight/manifest.mpd
INFO live          manifest.mpd           edge age 0.7 s, timeShiftBufferDepth 12 s, minimumUpdatePeriod 2 s
FAIL retention     manifest.mpd           2 s after fetch, inside the availability window but 404: chunk-stream0-00018.m4s (window ends in 1.3 s), chunk-stream1-00018.m4s (window ends in 1.2 s)
PASS codecs        Chromium 151.0.7922.34 isTypeSupported('video/mp4; codecs="avc1.64001e"') = true
PASS codecs        Chromium 151.0.7922.34 isTypeSupported('audio/mp4; codecs="mp4a.40.2"') = true
exit 1
```

With the default `extra_window_size`, which `ffmpeg -h muxer=dash` lists as 5 in version 9.0.1, segments outlive their window and the check passes. With `-extra_window_size 0`, segment 18 was deleted the moment it left the manifest, while the MPD fetched two seconds earlier still promised it for another 1.3 seconds. The manifest alone could not show this; only the requests did.

## What it costs, and where it stops

The static checks are cheap. Building every fixture took 1.1 seconds of wall time, and one HLS validation, including a headless Chromium launch for the codec questions, took 0.4 seconds. The whole lab ran in 65 seconds, and nearly all of that was waiting on live clocks: 1.5 target durations for the reload and one playlist duration for retention, per live playlist. That makes the live checks a poor fit for a pull request job and a good fit for a scheduled job against a staging channel that is actually running.

The maintenance cost sits in the policies: the 0.1-second tolerance, the retention wait and the reference variant are decisions. Keep each next to the section number it approximates.

Three limits are easy to forget. The validator checks what this machine was served, and a CDN edge can serve an older manifest than the origin, so point it at the viewers' hostname too. A pass says nothing about decoding, startup time or rendition choice. And the codec answer belongs to one browser build; a television's engine has to be asked on the television.

## Questions about manifest validation

### Is validating the MPD against the DASH XML schema enough?

No. A schema confirms structure and types. The gap in the lab is a valid integer in a valid attribute, a missing segment is a 404, and retention is a property of the origin over time. A schema catches none of the defects in this article.

### Why not open each stream in a headless player instead?

A player is built to tolerate imperfect input, so a session that plays does not tell you which rule broke or where. A manifest check names the line in under a second; a playback check costs a full session per stream. Run both, at different stages.

### Do VOD playlists need the live checks?

No. A playlist with `EXT-X-ENDLIST` has no window to move or expire, so the validator skips the live checks. A stitched VOD asset still inherits every discontinuity and duration defect of its sources, so the static checks stay.

## Specifications and source behind each manifest rule

- [RFC 8216: HTTP Live Streaming](https://www.rfc-editor.org/rfc/rfc8216). The rounded `EXTINF` rule, Rendition Group constraints, `CODECS` requirements, Discontinuity Sequence Numbers, variant constraints, live playlist publication and retention rules, and client reload limits.

- [draft-pantos-hls-rfc8216bis-22: HTTP Live Streaming 2nd Edition](https://www.ietf.org/archive/id/draft-pantos-hls-rfc8216bis-22.txt). An Internet-Draft. A client may treat a playlist unchanged for 1.5 target durations as server misbehaviour and should consider switching variant or reporting it.

- [DASH-IF Interoperability Points v4.3](https://dash-industry-forum.github.io/docs/DASH-IF-IOP-v4.3.pdf). Segment availability start and end time derivation, the gap semantics of `S` elements, the availability obligations of a dynamic service, and the recommendation to provide `timeShiftBufferDepth`.

- [W3C Media Source Extensions](https://www.w3.org/TR/media-source-2/). What a `true` from `isTypeSupported()` does and does not promise, and codecs not declared to `addSourceBuffer()` being treated as unsupported.

- [FFmpeg formats documentation](https://ffmpeg.org/ffmpeg-formats.html). The `hls_delete_threshold` default of 1 and what the DASH muxer's `extra_window_size` controls: segments kept outside the manifest before removal from disk.

- [hls.js README at v1.7.4](https://github.com/video-dev/hls.js/blob/v1.7.4/README.md). MPEG-2 TS segments are transmuxed into fMP4 before reaching MSE, while fMP4 segments pass through.

- [m3u8-parser source at v7.2.1](https://github.com/videojs/m3u8-parser/blob/v7.2.1/src/parser.js). Renditions stored under their `NAME`, so a duplicate overwrites the earlier entry.

## Run these manifest checks this week

- Run a line-level pass over one production master playlist today: duplicate `NAME`s per group, more than one `DEFAULT=YES`, and rounded `EXTINF` values above the target. Record the playlist URL, the fetch time and every finding with its line number.

- Fetch one live media playlist, wait for its total duration, then request every segment in the copy you saved. Any 404 is a retention defect at the packager or origin. On ffmpeg the settings to inspect are `hls_delete_threshold` for HLS and `extra_window_size` for DASH.

- Fetch the same live playlist twice, 1.5 target durations apart, and fail if the newest Media Sequence Number did not move.

- Keep the manifest snapshots beside the validator output as build artifacts, as described in [retaining CI artifacts that explain failures](/blog/automation-tutorials/retain-ci-artifacts-explain-failures), and compare a release's manifests with the previous release's in the [diff checker](/tools/diff-checker) before you open a player.

## Continue reading on AutomationTester.in

- [Retain CI Artifacts That Explain a Failure on Their Own](https://automationtester.in/blog/automation-tutorials/retain-ci-artifacts-explain-failures)
- [Size CI Parallelism From Dependency Capacity, Not Runners](https://automationtester.in/blog/automation-tutorials/control-ci-parallelism-dependency-capacity)
- [Place CI Tests by Feedback Time, Cost and Solo Catches](https://automationtester.in/blog/automation-tutorials/ci-test-pyramid-feedback-cost)
- [Test React Server and Client Boundaries in Next.js](https://automationtester.in/blog/automation-tutorials/test-nextjs-server-client-component-boundaries)
- [Choose Vitest, Browser Mode, or Playwright by Risk](https://automationtester.in/blog/automation-tutorials/choose-vitest-browser-mode-playwright-by-risk)

Source: [Validate HLS and DASH Manifests Before Any Player Opens Them](https://automationtester.in/blog/automation-tutorials/validate-hls-dash-manifests-before-playback) by Shashank Rawlani.
