@bsky.app/hls 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +93 -2
- package/dist/abr.d.ts +25 -0
- package/dist/abr.d.ts.map +1 -0
- package/dist/abr.js +67 -0
- package/dist/abr.js.map +1 -0
- package/dist/bandwidth.d.ts +8 -0
- package/dist/bandwidth.d.ts.map +1 -0
- package/dist/bandwidth.js +48 -0
- package/dist/bandwidth.js.map +1 -0
- package/dist/errors.d.ts +30 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +38 -0
- package/dist/errors.js.map +1 -0
- package/dist/fmp4.d.ts +3 -0
- package/dist/fmp4.d.ts.map +1 -0
- package/dist/fmp4.js +224 -0
- package/dist/fmp4.js.map +1 -0
- package/dist/gaps.d.ts +16 -0
- package/dist/gaps.d.ts.map +1 -0
- package/dist/gaps.js +40 -0
- package/dist/gaps.js.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -0
- package/dist/loader.d.ts +26 -0
- package/dist/loader.d.ts.map +1 -0
- package/dist/loader.js +94 -0
- package/dist/loader.js.map +1 -0
- package/dist/mse.d.ts +18 -0
- package/dist/mse.d.ts.map +1 -0
- package/dist/mse.js +123 -0
- package/dist/mse.js.map +1 -0
- package/dist/player.d.ts +3 -0
- package/dist/player.d.ts.map +1 -0
- package/dist/player.js +715 -0
- package/dist/player.js.map +1 -0
- package/dist/playlist.d.ts +7 -0
- package/dist/playlist.d.ts.map +1 -0
- package/dist/playlist.js +151 -0
- package/dist/playlist.js.map +1 -0
- package/dist/scheduler.d.ts +24 -0
- package/dist/scheduler.d.ts.map +1 -0
- package/dist/scheduler.js +79 -0
- package/dist/scheduler.js.map +1 -0
- package/dist/subtitles.d.ts +5 -0
- package/dist/subtitles.d.ts.map +1 -0
- package/dist/subtitles.js +29 -0
- package/dist/subtitles.js.map +1 -0
- package/dist/ts/aac.d.ts +18 -0
- package/dist/ts/aac.d.ts.map +1 -0
- package/dist/ts/aac.js +55 -0
- package/dist/ts/aac.js.map +1 -0
- package/dist/ts/demux.d.ts +19 -0
- package/dist/ts/demux.d.ts.map +1 -0
- package/dist/ts/demux.js +91 -0
- package/dist/ts/demux.js.map +1 -0
- package/dist/ts/h264.d.ts +25 -0
- package/dist/ts/h264.d.ts.map +1 -0
- package/dist/ts/h264.js +171 -0
- package/dist/ts/h264.js.map +1 -0
- package/dist/ts/index.d.ts +3 -0
- package/dist/ts/index.d.ts.map +1 -0
- package/dist/ts/index.js +117 -0
- package/dist/ts/index.js.map +1 -0
- package/dist/ts/mp4.d.ts +32 -0
- package/dist/ts/mp4.d.ts.map +1 -0
- package/dist/ts/mp4.js +76 -0
- package/dist/ts/mp4.js.map +1 -0
- package/dist/types.d.ts +153 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +23 -0
- package/dist/types.js.map +1 -0
- package/package.json +45 -4
- package/src/abr.ts +114 -0
- package/src/bandwidth.ts +57 -0
- package/src/errors.ts +73 -0
- package/src/fmp4.ts +228 -0
- package/src/gaps.ts +50 -0
- package/src/index.ts +10 -0
- package/src/loader.ts +111 -0
- package/src/mse.ts +141 -0
- package/src/player.ts +834 -0
- package/src/playlist.ts +157 -0
- package/src/scheduler.ts +114 -0
- package/src/subtitles.ts +39 -0
- package/src/ts/aac.ts +63 -0
- package/src/ts/demux.ts +93 -0
- package/src/ts/h264.ts +172 -0
- package/src/ts/index.ts +131 -0
- package/src/ts/mp4.ts +242 -0
- package/src/types.ts +216 -0
package/package.json
CHANGED
|
@@ -1,6 +1,47 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bsky.app/hls",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"description": "A minimal HLS player for Bluesky's video profile, built on Media Source Extensions.",
|
|
6
|
+
"repository": "https://github.com/bluesky-social/toolbox",
|
|
7
|
+
"author": "Bluesky Social PBC <hello@blueskyweb.xyz>",
|
|
8
|
+
"homepage": "https://github.com/bluesky-social/toolbox/tree/main/packages/hls",
|
|
9
|
+
"type": "module",
|
|
10
|
+
"main": "dist/index.js",
|
|
11
|
+
"types": "dist/index.d.ts",
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./dist/index.d.ts",
|
|
15
|
+
"default": "./dist/index.js"
|
|
16
|
+
},
|
|
17
|
+
"./package.json": "./package.json"
|
|
18
|
+
},
|
|
19
|
+
"sideEffects": false,
|
|
20
|
+
"files": [
|
|
21
|
+
"dist",
|
|
22
|
+
"src",
|
|
23
|
+
"!src/__tests__",
|
|
24
|
+
"package.json"
|
|
25
|
+
],
|
|
26
|
+
"scripts": {
|
|
27
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json",
|
|
28
|
+
"typecheck": "tsc --noEmit",
|
|
29
|
+
"test": "vitest run",
|
|
30
|
+
"fixtures": "bash scripts/make-fixtures.sh",
|
|
31
|
+
"size": "node scripts/size.mjs",
|
|
32
|
+
"format": "prettier --write ."
|
|
33
|
+
},
|
|
34
|
+
"keywords": [
|
|
35
|
+
"bluesky",
|
|
36
|
+
"hls",
|
|
37
|
+
"video",
|
|
38
|
+
"mse",
|
|
39
|
+
"media-source"
|
|
40
|
+
],
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"esbuild": "^0.28.0",
|
|
43
|
+
"prettier": "^3.6.2",
|
|
44
|
+
"typescript": "^6.0.3",
|
|
45
|
+
"vitest": "^3.1.1"
|
|
46
|
+
}
|
|
47
|
+
}
|
package/src/abr.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import type {Level} from './types.js'
|
|
2
|
+
|
|
3
|
+
const bitrate = (l: Level) => l.averageBandwidth ?? l.bandwidth
|
|
4
|
+
|
|
5
|
+
/** Drops levels the browser can't decode and re-indexes the rest. */
|
|
6
|
+
export function filterLevels(
|
|
7
|
+
levels: Level[],
|
|
8
|
+
isTypeSupported: (mime: string) => boolean,
|
|
9
|
+
): Level[] {
|
|
10
|
+
return levels
|
|
11
|
+
.filter(
|
|
12
|
+
l => !l.codecs || isTypeSupported(`video/mp4; codecs="${l.codecs}"`),
|
|
13
|
+
)
|
|
14
|
+
.map((l, index) => ({...l, index}))
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/*
|
|
18
|
+
* Levels are sorted by bandwidth. Without an estimate we start at the top
|
|
19
|
+
* level and let shouldAbandonProbe fall back if the connection can't sustain
|
|
20
|
+
* it: a slower first frame beats a grainy one, and unlike hls.js's probe the
|
|
21
|
+
* measured download is kept rather than thrown away.
|
|
22
|
+
*/
|
|
23
|
+
export function chooseLevel(
|
|
24
|
+
levels: Level[],
|
|
25
|
+
current: number,
|
|
26
|
+
estimate: number | undefined,
|
|
27
|
+
): number {
|
|
28
|
+
if (estimate === undefined) {
|
|
29
|
+
return current >= 0 ? current : Math.max(levels.length - 1, 0)
|
|
30
|
+
}
|
|
31
|
+
let fit = 0
|
|
32
|
+
levels.forEach((l, i) => {
|
|
33
|
+
if (bitrate(l) <= estimate * 0.7) fit = i
|
|
34
|
+
})
|
|
35
|
+
const cur = levels[current]
|
|
36
|
+
return !cur || fit > current || bitrate(cur) > estimate * 0.95 ? fit : current
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/*
|
|
40
|
+
* Whether to give up on an in-flight download in favour of the level below:
|
|
41
|
+
* it won't finish before the buffer runs dry, and the lower level would be
|
|
42
|
+
* meaningfully quicker.
|
|
43
|
+
*/
|
|
44
|
+
export function shouldAbandon({
|
|
45
|
+
levels,
|
|
46
|
+
level,
|
|
47
|
+
elapsedMs,
|
|
48
|
+
loadedBytes,
|
|
49
|
+
totalBytes,
|
|
50
|
+
segmentDuration,
|
|
51
|
+
bufferRemaining,
|
|
52
|
+
}: {
|
|
53
|
+
levels: Level[]
|
|
54
|
+
level: number
|
|
55
|
+
elapsedMs: number
|
|
56
|
+
loadedBytes: number
|
|
57
|
+
totalBytes: number | undefined
|
|
58
|
+
segmentDuration: number
|
|
59
|
+
/** Seconds of media playable before a stall; Infinity when paused. */
|
|
60
|
+
bufferRemaining: number
|
|
61
|
+
}): boolean {
|
|
62
|
+
const cur = levels[level]
|
|
63
|
+
const lower = levels[level - 1]
|
|
64
|
+
if (!cur || !lower || elapsedMs < 500) return false
|
|
65
|
+
const bps = (Math.max(loadedBytes, 1) * 8000) / elapsedMs
|
|
66
|
+
const total = totalBytes || (bitrate(cur) * segmentDuration) / 8
|
|
67
|
+
const remaining = (Math.max(total - loadedBytes, 0) * 8) / bps
|
|
68
|
+
const lowerTime = (bitrate(lower) * segmentDuration) / bps
|
|
69
|
+
return remaining > bufferRemaining && remaining > lowerTime * 1.5
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const PROBE_MIN_MS = 300
|
|
73
|
+
const PROBE_MIN_BYTES = 64 * 1024
|
|
74
|
+
/** Longest we'll wait for the first segment before settling for a lower level. */
|
|
75
|
+
const PROBE_MAX_MS = 6000
|
|
76
|
+
|
|
77
|
+
/*
|
|
78
|
+
* The first download with no bandwidth estimate doubles as the probe. Give up
|
|
79
|
+
* on it once the throughput since its first byte shows the level can't be
|
|
80
|
+
* sustained (the same 70% rule as switching up), or it would take too long.
|
|
81
|
+
*/
|
|
82
|
+
export function shouldAbandonProbe({
|
|
83
|
+
levels,
|
|
84
|
+
level,
|
|
85
|
+
elapsedMs,
|
|
86
|
+
sinceFirstByteMs,
|
|
87
|
+
loadedBytes,
|
|
88
|
+
totalBytes,
|
|
89
|
+
segmentDuration,
|
|
90
|
+
}: {
|
|
91
|
+
levels: Level[]
|
|
92
|
+
level: number
|
|
93
|
+
elapsedMs: number
|
|
94
|
+
/** undefined until the first byte arrives. */
|
|
95
|
+
sinceFirstByteMs: number | undefined
|
|
96
|
+
loadedBytes: number
|
|
97
|
+
totalBytes: number | undefined
|
|
98
|
+
segmentDuration: number
|
|
99
|
+
}): boolean {
|
|
100
|
+
const cur = levels[level]
|
|
101
|
+
if (!cur || !levels[level - 1]) return false
|
|
102
|
+
if (elapsedMs >= PROBE_MAX_MS) return true
|
|
103
|
+
if (
|
|
104
|
+
sinceFirstByteMs === undefined ||
|
|
105
|
+
sinceFirstByteMs < PROBE_MIN_MS ||
|
|
106
|
+
loadedBytes < PROBE_MIN_BYTES
|
|
107
|
+
) {
|
|
108
|
+
return false
|
|
109
|
+
}
|
|
110
|
+
const bps = (loadedBytes * 8000) / sinceFirstByteMs
|
|
111
|
+
const total = totalBytes || (bitrate(cur) * segmentDuration) / 8
|
|
112
|
+
const projectedMs = elapsedMs + ((total - loadedBytes) * 8000) / bps
|
|
113
|
+
return bitrate(cur) > bps * 0.7 || projectedMs > PROBE_MAX_MS
|
|
114
|
+
}
|
package/src/bandwidth.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Shared by every player on the page, like hls.js's EWMA estimator: a fast
|
|
3
|
+
* (3 s half-life) and a slow (9 s) average, weighted by download duration in
|
|
4
|
+
* seconds, and the estimate is the lower of the two.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
type Ewma = {halfLife: number; estimate: number; weight: number}
|
|
8
|
+
|
|
9
|
+
const ewma = (halfLife: number): Ewma => ({halfLife, estimate: 0, weight: 0})
|
|
10
|
+
|
|
11
|
+
let fast = ewma(3)
|
|
12
|
+
let slow = ewma(9)
|
|
13
|
+
|
|
14
|
+
/*
|
|
15
|
+
* Weight given to a seeded value: one fast half-life, so the first real
|
|
16
|
+
* download moves the estimate but doesn't replace it outright (hls.js seeds
|
|
17
|
+
* with zero weight, which throws the persisted value away on first sample).
|
|
18
|
+
*/
|
|
19
|
+
const SEED_WEIGHT = 3
|
|
20
|
+
|
|
21
|
+
function sample(e: Ewma, weight: number, value: number) {
|
|
22
|
+
const alpha = Math.pow(0.5, weight / e.halfLife)
|
|
23
|
+
e.estimate = value * (1 - alpha) + alpha * e.estimate
|
|
24
|
+
e.weight += weight
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Zero-bias correction, since both averages start at 0.
|
|
28
|
+
const read = (e: Ewma) =>
|
|
29
|
+
e.estimate / (1 - Math.pow(0.5, e.weight / e.halfLife))
|
|
30
|
+
|
|
31
|
+
/** Feeds one download. Ignores tiny or near-instant (cached) responses. */
|
|
32
|
+
export function sampleBandwidth(ms: number, bytes: number) {
|
|
33
|
+
if (bytes < 16000 || ms < 20) return
|
|
34
|
+
const seconds = ms / 1000
|
|
35
|
+
const bps = (bytes * 8) / seconds
|
|
36
|
+
sample(fast, seconds, bps)
|
|
37
|
+
sample(slow, seconds, bps)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Bits per second, or undefined before the first download or seed. */
|
|
41
|
+
export function getBandwidthEstimate(): number | undefined {
|
|
42
|
+
return fast.weight ? Math.min(read(fast), read(slow)) : undefined
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Seeds the estimate, e.g. with a value persisted from a previous page load. */
|
|
46
|
+
export function setBandwidthEstimate(bps: number) {
|
|
47
|
+
if (!(bps > 0) || !isFinite(bps)) return
|
|
48
|
+
fast = ewma(3)
|
|
49
|
+
slow = ewma(9)
|
|
50
|
+
sample(fast, SEED_WEIGHT, bps)
|
|
51
|
+
sample(slow, SEED_WEIGHT, bps)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function resetBandwidthEstimate() {
|
|
55
|
+
fast = ewma(3)
|
|
56
|
+
slow = ewma(9)
|
|
57
|
+
}
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* `detail` reuses hls.js's error detail names so existing dashboards and
|
|
3
|
+
* Sentry groupings carry over.
|
|
4
|
+
*/
|
|
5
|
+
export type HlsErrorDetail =
|
|
6
|
+
| 'manifestLoadError'
|
|
7
|
+
| 'manifestParseError'
|
|
8
|
+
| 'levelLoadError'
|
|
9
|
+
| 'levelParseError'
|
|
10
|
+
| 'fragLoadError'
|
|
11
|
+
| 'fragParsingError'
|
|
12
|
+
| 'bufferAppendError'
|
|
13
|
+
| 'bufferStalledError'
|
|
14
|
+
| 'mediaError'
|
|
15
|
+
| 'processorLoadError'
|
|
16
|
+
| 'unsupported'
|
|
17
|
+
|
|
18
|
+
export class HlsError extends Error {
|
|
19
|
+
readonly detail: HlsErrorDetail
|
|
20
|
+
readonly fatal: boolean
|
|
21
|
+
/** HTTP status, for load errors. */
|
|
22
|
+
readonly status?: number
|
|
23
|
+
readonly url?: string
|
|
24
|
+
readonly diagnostics: Record<string, unknown>
|
|
25
|
+
|
|
26
|
+
constructor({
|
|
27
|
+
detail,
|
|
28
|
+
message,
|
|
29
|
+
fatal = true,
|
|
30
|
+
status,
|
|
31
|
+
url,
|
|
32
|
+
cause,
|
|
33
|
+
diagnostics = {},
|
|
34
|
+
}: {
|
|
35
|
+
detail: HlsErrorDetail
|
|
36
|
+
message: string
|
|
37
|
+
fatal?: boolean
|
|
38
|
+
status?: number
|
|
39
|
+
url?: string
|
|
40
|
+
cause?: unknown
|
|
41
|
+
diagnostics?: Record<string, unknown>
|
|
42
|
+
}) {
|
|
43
|
+
super(message, cause === undefined ? undefined : {cause})
|
|
44
|
+
this.name = 'HlsError'
|
|
45
|
+
this.detail = detail
|
|
46
|
+
this.fatal = fatal
|
|
47
|
+
this.status = status
|
|
48
|
+
this.url = url
|
|
49
|
+
this.diagnostics = diagnostics
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The multivariant playlist returned 404. */
|
|
54
|
+
export class VideoNotFoundError extends HlsError {
|
|
55
|
+
constructor({url, cause}: {url: string; cause?: unknown}) {
|
|
56
|
+
super({
|
|
57
|
+
detail: 'manifestLoadError',
|
|
58
|
+
message: 'Video not found',
|
|
59
|
+
status: 404,
|
|
60
|
+
url,
|
|
61
|
+
cause,
|
|
62
|
+
})
|
|
63
|
+
this.name = 'VideoNotFoundError'
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** No MediaSource, or it can't play the playlist's codecs. */
|
|
68
|
+
export class HlsUnsupportedError extends HlsError {
|
|
69
|
+
constructor(message = 'HLS is not supported') {
|
|
70
|
+
super({detail: 'unsupported', message})
|
|
71
|
+
this.name = 'HlsUnsupportedError'
|
|
72
|
+
}
|
|
73
|
+
}
|
package/src/fmp4.ts
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import type {CreateSegmentProcessor} from './types.js'
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
* Passthrough processor for fMP4: the bytes go to the SourceBuffer untouched,
|
|
5
|
+
* we only read enough of the boxes to know the segment's timing.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
type Track = {
|
|
9
|
+
id: number
|
|
10
|
+
timescale: number
|
|
11
|
+
handler: string
|
|
12
|
+
/** Seconds added to media time, from the edit list (<= 0). */
|
|
13
|
+
shift: number
|
|
14
|
+
defaultDuration: number
|
|
15
|
+
defaultFlags: number
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
type Visit = (type: string, start: number, end: number) => boolean | void
|
|
19
|
+
|
|
20
|
+
const CONTAINERS = /^(moov|trak|mdia|minf|stbl|mvex|edts|moof|traf)$/
|
|
21
|
+
|
|
22
|
+
function walk(d: DataView, start: number, end: number, visit: Visit) {
|
|
23
|
+
while (start + 8 <= end) {
|
|
24
|
+
let size = d.getUint32(start)
|
|
25
|
+
let header = 8
|
|
26
|
+
if (size === 1) {
|
|
27
|
+
size = Number(d.getBigUint64(start + 8))
|
|
28
|
+
header = 16
|
|
29
|
+
} else if (size === 0) {
|
|
30
|
+
size = end - start
|
|
31
|
+
}
|
|
32
|
+
if (size < header) throw new Error('Bad MP4 box size')
|
|
33
|
+
const type = String.fromCharCode(
|
|
34
|
+
...new Uint8Array(d.buffer, d.byteOffset + start + 4, 4),
|
|
35
|
+
)
|
|
36
|
+
const s = start + header
|
|
37
|
+
const e = Math.min(start + size, end)
|
|
38
|
+
if (visit(type, s, e) || CONTAINERS.test(type)) walk(d, s, e, visit)
|
|
39
|
+
start += size
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const view = (b: Uint8Array) =>
|
|
44
|
+
new DataView(b.buffer, b.byteOffset, b.byteLength)
|
|
45
|
+
const hex = (n: number) => n.toString(16).padStart(2, '0')
|
|
46
|
+
|
|
47
|
+
function parseInit(init: Uint8Array) {
|
|
48
|
+
const d = view(init)
|
|
49
|
+
const tracks: Track[] = []
|
|
50
|
+
const trex = new Map<number, [duration: number, flags: number]>()
|
|
51
|
+
let movieTimescale = 1000
|
|
52
|
+
let track: Track | undefined
|
|
53
|
+
// [leading empty edits in movie timescale, first media time]
|
|
54
|
+
let edit: [number, number] = [0, 0]
|
|
55
|
+
const edits: Array<[number, number]> = []
|
|
56
|
+
let avc: string | undefined
|
|
57
|
+
// Version 1 full boxes widen the creation/modification times before these fields.
|
|
58
|
+
const v1 = (s: number, v0: number, v1: number) =>
|
|
59
|
+
s + (d.getUint8(s) ? v1 : v0)
|
|
60
|
+
walk(d, 0, init.length, (type, s, e) => {
|
|
61
|
+
if (type === 'mvhd') movieTimescale = d.getUint32(v1(s, 12, 20))
|
|
62
|
+
else if (type === 'trak') {
|
|
63
|
+
tracks.push(
|
|
64
|
+
(track = {
|
|
65
|
+
id: 0,
|
|
66
|
+
timescale: 1,
|
|
67
|
+
handler: '',
|
|
68
|
+
shift: 0,
|
|
69
|
+
defaultDuration: 0,
|
|
70
|
+
defaultFlags: 0,
|
|
71
|
+
}),
|
|
72
|
+
)
|
|
73
|
+
edits.push((edit = [0, 0]))
|
|
74
|
+
} else if (track && type === 'tkhd') track.id = d.getUint32(v1(s, 12, 20))
|
|
75
|
+
else if (track && type === 'mdhd')
|
|
76
|
+
track.timescale = d.getUint32(v1(s, 12, 20))
|
|
77
|
+
else if (track && type === 'hdlr') {
|
|
78
|
+
track.handler = String.fromCharCode(...init.subarray(s + 8, s + 12))
|
|
79
|
+
} else if (type === 'elst') {
|
|
80
|
+
const wide = d.getUint8(s)
|
|
81
|
+
let p = s + 8
|
|
82
|
+
for (let n = d.getUint32(s + 4); n--; p += wide ? 20 : 12) {
|
|
83
|
+
const duration = wide ? Number(d.getBigUint64(p)) : d.getUint32(p)
|
|
84
|
+
const mediaTime = wide
|
|
85
|
+
? Number(d.getBigInt64(p + 8))
|
|
86
|
+
: d.getInt32(p + 4)
|
|
87
|
+
if (mediaTime >= 0) {
|
|
88
|
+
edit[1] = mediaTime
|
|
89
|
+
break
|
|
90
|
+
}
|
|
91
|
+
edit[0] += duration
|
|
92
|
+
}
|
|
93
|
+
} else if (type === 'stsd') {
|
|
94
|
+
walk(d, s + 8, e, visit)
|
|
95
|
+
} else if (type === 'trex') {
|
|
96
|
+
trex.set(d.getUint32(s + 4), [d.getUint32(s + 12), d.getUint32(s + 20)])
|
|
97
|
+
}
|
|
98
|
+
// Sample entries: avcC sits after the 78-byte visual sample entry header.
|
|
99
|
+
function visit(t: string, cs: number, ce: number) {
|
|
100
|
+
if (t === 'avc1' || t === 'avc3') {
|
|
101
|
+
walk(d, cs + 78, ce, (t2, as) => {
|
|
102
|
+
if (t2 === 'avcC') {
|
|
103
|
+
avc = `avc1.${hex(init[as + 1]!)}${hex(init[as + 2]!)}${hex(init[as + 3]!)}`
|
|
104
|
+
}
|
|
105
|
+
})
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
})
|
|
109
|
+
tracks.forEach((t, i) => {
|
|
110
|
+
const [empty, mediaTime] = edits[i]!
|
|
111
|
+
/*
|
|
112
|
+
* Browsers disagree on edit lists in MSE: Chrome only honours a
|
|
113
|
+
* non-empty first entry, Firefox and Safari apply all of it. Use
|
|
114
|
+
* whichever timeline is earlier so the first keyframe can't land below
|
|
115
|
+
* 0 after the player's timestampOffset (a small start gap is jumped).
|
|
116
|
+
*/
|
|
117
|
+
t.shift = Math.min(0, empty / movieTimescale - mediaTime / t.timescale)
|
|
118
|
+
const [dur, flags] = trex.get(t.id) ?? [0, 0]
|
|
119
|
+
t.defaultDuration = dur
|
|
120
|
+
t.defaultFlags = flags
|
|
121
|
+
})
|
|
122
|
+
const video = tracks.find(t => t.handler === 'vide')
|
|
123
|
+
const audio = tracks.find(t => t.handler === 'soun')
|
|
124
|
+
return {tracks, video, audio, avc}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function fnv(b: Uint8Array) {
|
|
128
|
+
let h = 0x811c9dc5
|
|
129
|
+
for (const x of b) h = Math.imul(h ^ x, 16777619)
|
|
130
|
+
return (h >>> 0).toString(36)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export const createFmp4Processor: CreateSegmentProcessor = () => {
|
|
134
|
+
let lastInit: Uint8Array | undefined
|
|
135
|
+
let info: ReturnType<typeof parseInit>
|
|
136
|
+
let initKey = ''
|
|
137
|
+
let mimeType = ''
|
|
138
|
+
return {
|
|
139
|
+
process({data, init, level, codecs}) {
|
|
140
|
+
if (!init) throw new Error('fMP4 segment without an init segment')
|
|
141
|
+
if (init !== lastInit) {
|
|
142
|
+
info = parseInit(init)
|
|
143
|
+
lastInit = init
|
|
144
|
+
initKey = `${level}:${init.length}:${fnv(init)}`
|
|
145
|
+
const declared = codecs?.split(',').map(c => c.trim()) ?? []
|
|
146
|
+
// Only declare tracks the init really has, or the append fails.
|
|
147
|
+
const list = [
|
|
148
|
+
info.video && (declared.find(c => !c.startsWith('mp4a')) ?? info.avc),
|
|
149
|
+
info.audio &&
|
|
150
|
+
(declared.find(c => c.startsWith('mp4a')) ?? 'mp4a.40.2'),
|
|
151
|
+
].filter(Boolean)
|
|
152
|
+
mimeType = `video/mp4; codecs="${list.join(',')}"`
|
|
153
|
+
}
|
|
154
|
+
const main = info.video ?? info.audio
|
|
155
|
+
if (!main) throw new Error('No audio or video track in init segment')
|
|
156
|
+
const d = view(data)
|
|
157
|
+
let start = Infinity
|
|
158
|
+
let end = -Infinity
|
|
159
|
+
const keyframes: number[] = []
|
|
160
|
+
let trackId = 0
|
|
161
|
+
let baseTime = 0
|
|
162
|
+
let defaultDuration = 0
|
|
163
|
+
let defaultFlags = 0
|
|
164
|
+
walk(d, 0, data.length, (type, s) => {
|
|
165
|
+
if (type === 'tfhd') {
|
|
166
|
+
const flags = d.getUint32(s) & 0xffffff
|
|
167
|
+
trackId = d.getUint32(s + 4)
|
|
168
|
+
const t = info.tracks.find(t => t.id === trackId)
|
|
169
|
+
defaultDuration = t?.defaultDuration ?? 0
|
|
170
|
+
defaultFlags = t?.defaultFlags ?? 0
|
|
171
|
+
let p = s + 8
|
|
172
|
+
if (flags & 1) p += 8
|
|
173
|
+
if (flags & 2) p += 4
|
|
174
|
+
if (flags & 8) defaultDuration = d.getUint32((p += 4) - 4)
|
|
175
|
+
if (flags & 0x10) p += 4
|
|
176
|
+
if (flags & 0x20) defaultFlags = d.getUint32(p)
|
|
177
|
+
} else if (type === 'tfdt') {
|
|
178
|
+
baseTime = d.getUint8(s)
|
|
179
|
+
? Number(d.getBigUint64(s + 4))
|
|
180
|
+
: d.getUint32(s + 4)
|
|
181
|
+
} else if (type === 'trun' && trackId === main.id) {
|
|
182
|
+
const version = d.getUint8(s)
|
|
183
|
+
const flags = d.getUint32(s) & 0xffffff
|
|
184
|
+
let p = s + 8
|
|
185
|
+
if (flags & 1) p += 4
|
|
186
|
+
let firstFlags: number | undefined
|
|
187
|
+
if (flags & 4) firstFlags = d.getUint32((p += 4) - 4)
|
|
188
|
+
let dts = baseTime
|
|
189
|
+
for (let i = 0, n = d.getUint32(s + 4); i < n; i++) {
|
|
190
|
+
let duration = defaultDuration
|
|
191
|
+
let sampleFlags =
|
|
192
|
+
i === 0 && firstFlags !== undefined ? firstFlags : defaultFlags
|
|
193
|
+
let cts = 0
|
|
194
|
+
if (flags & 0x100) duration = d.getUint32((p += 4) - 4)
|
|
195
|
+
if (flags & 0x200) p += 4
|
|
196
|
+
if (flags & 0x400) sampleFlags = d.getUint32((p += 4) - 4)
|
|
197
|
+
if (flags & 0x800) {
|
|
198
|
+
cts = version ? d.getInt32(p) : d.getUint32(p)
|
|
199
|
+
p += 4
|
|
200
|
+
}
|
|
201
|
+
const pts = (dts + cts) / main.timescale + main.shift
|
|
202
|
+
start = Math.min(start, pts)
|
|
203
|
+
end = Math.max(end, pts + duration / main.timescale)
|
|
204
|
+
// sample_is_non_sync_sample
|
|
205
|
+
if (!(sampleFlags & 0x10000)) keyframes.push(pts)
|
|
206
|
+
dts += duration
|
|
207
|
+
}
|
|
208
|
+
baseTime = dts
|
|
209
|
+
}
|
|
210
|
+
})
|
|
211
|
+
if (start === Infinity) throw new Error('No samples in fMP4 segment')
|
|
212
|
+
return {
|
|
213
|
+
init,
|
|
214
|
+
initKey,
|
|
215
|
+
data,
|
|
216
|
+
mimeType,
|
|
217
|
+
hasVideo: !!info.video,
|
|
218
|
+
hasAudio: !!info.audio,
|
|
219
|
+
startTime: start,
|
|
220
|
+
endTime: end,
|
|
221
|
+
keyframes: keyframes.sort((a, b) => a - b),
|
|
222
|
+
}
|
|
223
|
+
},
|
|
224
|
+
reset() {
|
|
225
|
+
lastInit = undefined
|
|
226
|
+
},
|
|
227
|
+
}
|
|
228
|
+
}
|
package/src/gaps.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
export type Ranges = Array<[number, number]>
|
|
2
|
+
|
|
3
|
+
export function toRanges(r: TimeRanges): Ranges {
|
|
4
|
+
const out: Ranges = []
|
|
5
|
+
for (let i = 0; i < r.length; i++) out.push([r.start(i), r.end(i)])
|
|
6
|
+
return out
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export const inRanges = (ranges: Ranges, t: number) =>
|
|
10
|
+
ranges.some(([s, e]) => t >= s && t < e)
|
|
11
|
+
|
|
12
|
+
/*
|
|
13
|
+
* Where to jump if the playhead sits in a hole shorter than 2 s before the
|
|
14
|
+
* next buffered range: the start gap left by media that begins a few frames
|
|
15
|
+
* after 0, or a hole between segments. Lands slightly inside the range,
|
|
16
|
+
* since some browsers won't resume exactly on its boundary.
|
|
17
|
+
*/
|
|
18
|
+
export function gapJump(ranges: Ranges, t: number): number | undefined {
|
|
19
|
+
if (inRanges(ranges, t)) return
|
|
20
|
+
const next = ranges.find(([s]) => s > t)
|
|
21
|
+
if (next && next[0] - t < 2) return Math.min(next[0] + 0.05, next[1])
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type StallState = {time: number; since: number; nudges: number}
|
|
25
|
+
|
|
26
|
+
/*
|
|
27
|
+
* Called on every tick. A stall is the playhead not moving for 1.25 s while
|
|
28
|
+
* playing with data buffered ahead of it, which usually means the decoder is
|
|
29
|
+
* stuck on a tiny hole or a broken frame. Returns how far to nudge, or
|
|
30
|
+
* 'fatal' once three increasing nudges haven't helped.
|
|
31
|
+
*/
|
|
32
|
+
export function checkStall(
|
|
33
|
+
state: StallState,
|
|
34
|
+
{
|
|
35
|
+
now,
|
|
36
|
+
time,
|
|
37
|
+
playing,
|
|
38
|
+
bufferedAhead,
|
|
39
|
+
}: {now: number; time: number; playing: boolean; bufferedAhead: boolean},
|
|
40
|
+
): number | 'fatal' | undefined {
|
|
41
|
+
if (!playing || time !== state.time) {
|
|
42
|
+
if (time !== state.time) state.nudges = 0
|
|
43
|
+
state.time = time
|
|
44
|
+
state.since = now
|
|
45
|
+
return
|
|
46
|
+
}
|
|
47
|
+
if (!bufferedAhead || now - state.since < 1250) return
|
|
48
|
+
state.since = now
|
|
49
|
+
return ++state.nudges > 3 ? 'fatal' : state.nudges * 0.1
|
|
50
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export {
|
|
2
|
+
getBandwidthEstimate,
|
|
3
|
+
resetBandwidthEstimate,
|
|
4
|
+
setBandwidthEstimate,
|
|
5
|
+
} from './bandwidth.js'
|
|
6
|
+
export {HlsError, HlsUnsupportedError, VideoNotFoundError} from './errors.js'
|
|
7
|
+
export type {HlsErrorDetail} from './errors.js'
|
|
8
|
+
export {canPlayHls} from './mse.js'
|
|
9
|
+
export {createHlsPlayer} from './player.js'
|
|
10
|
+
export type * from './types.js'
|
package/src/loader.ts
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import {HlsError, type HlsErrorDetail} from './errors.js'
|
|
2
|
+
|
|
3
|
+
export type LoadResult = {
|
|
4
|
+
data: Uint8Array
|
|
5
|
+
/** Response URL after redirects, for resolving relative URIs. */
|
|
6
|
+
url: string
|
|
7
|
+
/** Request start to last byte, of the attempt that succeeded. */
|
|
8
|
+
ms: number
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export type LoadOptions = {
|
|
12
|
+
fetch: typeof fetch
|
|
13
|
+
detail: HlsErrorDetail
|
|
14
|
+
retries: number
|
|
15
|
+
signal?: AbortSignal
|
|
16
|
+
onRetry?: (error: HlsError) => void
|
|
17
|
+
onProgress?: (loaded: number, total: number | undefined) => void
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const sleep = (ms: number, signal?: AbortSignal) =>
|
|
21
|
+
new Promise<void>((resolve, reject) => {
|
|
22
|
+
if (signal?.aborted) return reject(signal.reason)
|
|
23
|
+
const onAbort = () => {
|
|
24
|
+
clearTimeout(id)
|
|
25
|
+
reject(signal!.reason)
|
|
26
|
+
}
|
|
27
|
+
const id = setTimeout(() => {
|
|
28
|
+
signal?.removeEventListener('abort', onAbort)
|
|
29
|
+
resolve()
|
|
30
|
+
}, ms)
|
|
31
|
+
signal?.addEventListener('abort', onAbort, {once: true})
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
/*
|
|
35
|
+
* fetch() with a 10 s time-to-headers and 30 s total timeout, and retries
|
|
36
|
+
* with exponential backoff (1, 2, 4, 8 s). 4xx responses are never retried.
|
|
37
|
+
* Aborting `signal` rejects with the signal's reason, untouched.
|
|
38
|
+
*/
|
|
39
|
+
export async function load(
|
|
40
|
+
url: string,
|
|
41
|
+
{fetch, detail, retries, signal, onRetry, onProgress}: LoadOptions,
|
|
42
|
+
): Promise<LoadResult> {
|
|
43
|
+
for (let attempt = 0; ; attempt++) {
|
|
44
|
+
const controller = new AbortController()
|
|
45
|
+
const abort = () => controller.abort()
|
|
46
|
+
signal?.addEventListener('abort', abort)
|
|
47
|
+
let timeout: string | undefined
|
|
48
|
+
const timer = (ms: number, what: string) =>
|
|
49
|
+
setTimeout(() => {
|
|
50
|
+
timeout = what
|
|
51
|
+
controller.abort()
|
|
52
|
+
}, ms)
|
|
53
|
+
const firstByte = timer(10000, 'first byte')
|
|
54
|
+
const total = timer(30000, 'total')
|
|
55
|
+
let status: number | undefined
|
|
56
|
+
try {
|
|
57
|
+
const start = performance.now()
|
|
58
|
+
const res = await fetch(url, {signal: controller.signal})
|
|
59
|
+
clearTimeout(firstByte)
|
|
60
|
+
status = res.status
|
|
61
|
+
if (!res.ok) throw new Error(`HTTP ${status}`)
|
|
62
|
+
const length = Number(res.headers.get('content-length')) || undefined
|
|
63
|
+
const reader = res.body?.getReader()
|
|
64
|
+
let data: Uint8Array
|
|
65
|
+
if (reader) {
|
|
66
|
+
const chunks: Uint8Array[] = []
|
|
67
|
+
let loaded = 0
|
|
68
|
+
for (let r; !(r = await reader.read()).done; ) {
|
|
69
|
+
chunks.push(r.value)
|
|
70
|
+
loaded += r.value.length
|
|
71
|
+
onProgress?.(loaded, length)
|
|
72
|
+
}
|
|
73
|
+
data = new Uint8Array(loaded)
|
|
74
|
+
loaded = 0
|
|
75
|
+
for (const c of chunks) {
|
|
76
|
+
data.set(c, loaded)
|
|
77
|
+
loaded += c.length
|
|
78
|
+
}
|
|
79
|
+
} else {
|
|
80
|
+
data = new Uint8Array(await res.arrayBuffer())
|
|
81
|
+
}
|
|
82
|
+
return {data, url: res.url || url, ms: performance.now() - start}
|
|
83
|
+
} catch (cause) {
|
|
84
|
+
if (signal?.aborted) throw signal.reason
|
|
85
|
+
const clientError = status !== undefined && status >= 400 && status < 500
|
|
86
|
+
const error = new HlsError({
|
|
87
|
+
detail,
|
|
88
|
+
message: timeout
|
|
89
|
+
? `Timed out waiting for ${timeout}`
|
|
90
|
+
: `Failed to load (${(cause as Error)?.message ?? cause})`,
|
|
91
|
+
fatal: clientError || attempt >= retries,
|
|
92
|
+
status,
|
|
93
|
+
url,
|
|
94
|
+
cause,
|
|
95
|
+
diagnostics: {attempt},
|
|
96
|
+
})
|
|
97
|
+
if (error.fatal) throw error
|
|
98
|
+
onRetry?.(error)
|
|
99
|
+
} finally {
|
|
100
|
+
clearTimeout(firstByte)
|
|
101
|
+
clearTimeout(total)
|
|
102
|
+
signal?.removeEventListener('abort', abort)
|
|
103
|
+
}
|
|
104
|
+
await sleep(Math.min(1000 * 2 ** attempt, 8000), signal)
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export const loadText = async (url: string, options: LoadOptions) => {
|
|
109
|
+
const res = await load(url, options)
|
|
110
|
+
return {...res, text: new TextDecoder().decode(res.data)}
|
|
111
|
+
}
|