@clipmux/player 0.1.2 → 0.6.1

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/src/refresh.ts ADDED
@@ -0,0 +1,246 @@
1
+ // Token refresh for ClipMux playback, independent of any player UI.
2
+ //
3
+ // A signed playback URL carries its token in the path:
4
+ // {base_url}/v/{token}/{playback_id}/…
5
+ // and every playlist, segment and key URI below it is relative, so the token
6
+ // rides along. When it expires, delivery answers 401 token_expired; the
7
+ // loader here asks the app for a new token once, swaps it into the path of
8
+ // that request and every later one, and retries, so the player never sees
9
+ // the error and keeps its position.
10
+
11
+ /** A ClipMux playback token: an ES256 JWT. */
12
+ const jwt = /^[\w-]+\.[\w-]+\.[\w-]+$/
13
+
14
+ function escapeRegExp(s: string): string {
15
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
16
+ }
17
+
18
+ /**
19
+ * Puts token into a signed playback URL of playbackId on mediaOrigin. Any
20
+ * other URL (another origin, another playback ID, a public /p/ URL) is
21
+ * returned unchanged.
22
+ */
23
+ export function rewriteTokenUrl(url: string, mediaOrigin: string, playbackId: string, token: string): string {
24
+ let u: URL
25
+ try {
26
+ u = new URL(url)
27
+ } catch {
28
+ return url
29
+ }
30
+ if (u.origin !== new URL(mediaOrigin).origin) return url
31
+ const path = u.pathname.replace(new RegExp(`^/v/[^/]+/(?=${escapeRegExp(playbackId)}/)`), `/v/${token}/`)
32
+ if (path === u.pathname) return url
33
+ u.pathname = path
34
+ return u.toString()
35
+ }
36
+
37
+ /** What the player asks getToken for. */
38
+ export interface TokenRequest {
39
+ playbackId: string
40
+ /**
41
+ * The browser plays HLS itself (iOS before 17.1, AirPlay), so the token
42
+ * can't be refreshed: sign it for the whole session, as
43
+ * `clipmux.playback.token(id, { native: true })` does.
44
+ */
45
+ native: boolean
46
+ }
47
+
48
+ /**
49
+ * Your callback for a fresh token; null means this viewer may not watch.
50
+ * A callback that takes no arguments still fits.
51
+ */
52
+ export type GetToken = (request: TokenRequest) => Promise<string | null>
53
+
54
+ export interface SessionOptions {
55
+ delay?: (ms: number) => Promise<void>
56
+ onToken?: (token: string) => void
57
+ onDenied?: () => void
58
+ }
59
+
60
+ /**
61
+ * The current token of one playback. refresh() calls getToken at most once
62
+ * however many requests failed together, and a request that failed with an
63
+ * older token simply retries with the newer one.
64
+ */
65
+ export class TokenSession {
66
+ #current: string
67
+ #getToken: (() => Promise<string | null>) | undefined
68
+ #pending: Promise<string | null> | null = null
69
+ #denied = false
70
+ readonly #opts: SessionOptions
71
+
72
+ constructor(token: string, getToken?: () => Promise<string | null>, options: SessionOptions = {}) {
73
+ this.#current = token
74
+ this.#getToken = getToken
75
+ this.#opts = options
76
+ }
77
+
78
+ get current(): string {
79
+ return this.#current
80
+ }
81
+
82
+ get denied(): boolean {
83
+ return this.#denied
84
+ }
85
+
86
+ /** Stops refreshing: delivery said 403, or the app said no. */
87
+ deny(): void {
88
+ if (this.#denied) return
89
+ this.#denied = true
90
+ this.#opts.onDenied?.()
91
+ }
92
+
93
+ /**
94
+ * A new token to retry with after one that was rejected (seen), or null
95
+ * when there is none: the app denied it, or there is no getToken.
96
+ */
97
+ refresh(seen: string): Promise<string | null> {
98
+ if (this.#denied || !this.#getToken) return Promise.resolve(null)
99
+ if (seen !== this.#current) return Promise.resolve(this.#current)
100
+ this.#pending ??= this.#fetch().finally(() => {
101
+ this.#pending = null
102
+ })
103
+ return this.#pending
104
+ }
105
+
106
+ async #fetch(): Promise<string | null> {
107
+ const delay = this.#opts.delay ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)))
108
+ const getToken = this.#getToken as () => Promise<string | null>
109
+ let failure: unknown
110
+ for (const wait of [0, 1000, 2000, 4000]) {
111
+ if (wait) await delay(wait)
112
+ let token: string | null
113
+ try {
114
+ token = await getToken()
115
+ } catch (err) {
116
+ failure = err // a transient failure: try again
117
+ continue
118
+ }
119
+ if (token === null) {
120
+ this.deny()
121
+ return null
122
+ }
123
+ if (!jwt.test(token)) throw new Error('getToken must return a ClipMux playback token (a JWT) or null')
124
+ this.#current = token
125
+ this.#opts.onToken?.(token)
126
+ return token
127
+ }
128
+ throw failure
129
+ }
130
+ }
131
+
132
+ // The slice of hls.js's loader interface the wrapper needs, so this module
133
+ // type-checks without hls.js and tests can use a fake.
134
+ export interface LoaderContextLike {
135
+ url: string
136
+ }
137
+ export interface LoaderError {
138
+ code: number
139
+ text: string
140
+ }
141
+ export interface LoaderCallbacksLike<C extends LoaderContextLike> {
142
+ onSuccess: (response: unknown, stats: unknown, context: C, networkDetails: unknown) => void
143
+ onError: (error: LoaderError, context: C, networkDetails: unknown, stats: unknown) => void
144
+ onTimeout: (stats: unknown, context: C, networkDetails: unknown) => void
145
+ onAbort?: (stats: unknown, context: C, networkDetails: unknown) => void
146
+ onProgress?: (stats: unknown, context: C, data: unknown, networkDetails: unknown) => void
147
+ }
148
+ export interface LoaderLike<C extends LoaderContextLike> {
149
+ context: C | null
150
+ stats: unknown
151
+ load(context: C, config: unknown, callbacks: LoaderCallbacksLike<C>): void
152
+ abort(): void
153
+ destroy(): void
154
+ getCacheAge?: (() => number | null) | undefined
155
+ getResponseHeader?: ((name: string) => string | null) | undefined
156
+ }
157
+ export type LoaderClass<C extends LoaderContextLike> = new (config: unknown) => LoaderLike<C>
158
+
159
+ /**
160
+ * Wraps a loader class (hls.js's DefaultConfig.loader) so every request
161
+ * carries the session's current token, and a 401 is answered with a fresh
162
+ * token and a retry instead of an error. hls.js loads playlists, segments
163
+ * and AES-128 keys through the same loader, so this covers them all.
164
+ */
165
+ export function createRefreshLoader<C extends LoaderContextLike>(
166
+ Base: LoaderClass<C>,
167
+ session: TokenSession,
168
+ mediaOrigin: string,
169
+ playbackId: string,
170
+ ): LoaderClass<C> {
171
+ return class RefreshLoader implements LoaderLike<C> {
172
+ readonly #config: unknown
173
+ #inner: LoaderLike<C>
174
+ #aborted = false
175
+
176
+ constructor(config: unknown) {
177
+ this.#config = config
178
+ this.#inner = new Base(config)
179
+ }
180
+
181
+ get context(): C | null {
182
+ return this.#inner.context
183
+ }
184
+
185
+ set context(c: C | null) {
186
+ this.#inner.context = c
187
+ }
188
+
189
+ get stats(): unknown {
190
+ return this.#inner.stats
191
+ }
192
+
193
+ get getCacheAge() {
194
+ return this.#inner.getCacheAge?.bind(this.#inner)
195
+ }
196
+
197
+ get getResponseHeader() {
198
+ return this.#inner.getResponseHeader?.bind(this.#inner)
199
+ }
200
+
201
+ load(context: C, config: unknown, callbacks: LoaderCallbacksLike<C>): void {
202
+ this.#aborted = false
203
+ if (session.denied) {
204
+ callbacks.onError({ code: 403, text: 'denied' }, context, null, this.stats)
205
+ return
206
+ }
207
+ const send = (token: string, retried: boolean) => {
208
+ context.url = rewriteTokenUrl(context.url, mediaOrigin, playbackId, token)
209
+ this.#inner.load(context, config, {
210
+ ...callbacks,
211
+ onError: (error, ctx, details, stats) => {
212
+ if (error.code === 401 && !retried && !this.#aborted) {
213
+ session.refresh(token).then(
214
+ (next) => {
215
+ if (this.#aborted) return
216
+ if (!next) return callbacks.onError(error, ctx, details, stats)
217
+ // A fresh inner loader: the failed one is spent.
218
+ this.#inner.destroy()
219
+ this.#inner = new Base(this.#config)
220
+ send(next, true)
221
+ },
222
+ () => {
223
+ if (!this.#aborted) callbacks.onError(error, ctx, details, stats)
224
+ },
225
+ )
226
+ return
227
+ }
228
+ if (error.code === 403) session.deny()
229
+ callbacks.onError(error, ctx, details, stats)
230
+ },
231
+ })
232
+ }
233
+ send(session.current, false)
234
+ }
235
+
236
+ abort(): void {
237
+ this.#aborted = true
238
+ this.#inner.abort()
239
+ }
240
+
241
+ destroy(): void {
242
+ this.#aborted = true
243
+ this.#inner.destroy()
244
+ }
245
+ }
246
+ }
package/src/session.ts ADDED
@@ -0,0 +1,101 @@
1
+ // Playback sessions from the app's backend (session-url).
2
+ //
3
+ // The element POSTs {playback_id, native} to a URL of the app (for example
4
+ // the @clipmux/node handler's /playback route), which checks the viewer
5
+ // and answers with everything the player needs, in the shape of
6
+ // POST /s/{secret}/playback:
7
+ //
8
+ // {playback_id, base_url, token, expires_at, poster_url, tracks}
9
+ //
10
+ // The browser then needs neither the ClipMux URL nor a token of its own.
11
+ // native says the browser will play HLS itself, so the backend signs a
12
+ // token that outlives the session (refresh can't reach native playback).
13
+
14
+ /** A track of the playback, as GET /v1/assets/{id} lists it. */
15
+ export interface SessionTrack {
16
+ id: string
17
+ kind: 'subtitles' | 'chapters' | (string & {})
18
+ status: 'preparing' | 'ready' | 'errored' | (string & {})
19
+ language?: string
20
+ [field: string]: unknown
21
+ }
22
+
23
+ /**
24
+ * What the session URL answers: `@clipmux/node`'s `playback.session()`
25
+ * and POST /s/{secret}/playback both fit it.
26
+ */
27
+ export interface PlaybackSession {
28
+ playback_id: string
29
+ base_url: string
30
+ /** The playback token; empty for a public playback ID. */
31
+ token: string
32
+ /** When the token expires; null or absent for a public playback ID. */
33
+ expires_at?: string | null
34
+ poster_url?: string
35
+ title?: string
36
+ duration_seconds?: number | null
37
+ tracks?: SessionTrack[]
38
+ }
39
+
40
+ /** The session URL answered something other than a session or a denial. */
41
+ export class SessionError extends Error {
42
+ readonly status: number
43
+ constructor(status: number, message: string) {
44
+ super(message)
45
+ this.name = 'SessionError'
46
+ this.status = status
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Asks the app's session URL for a playback session. Resolves null when the
52
+ * app denies this viewer (401 or 403), and rejects with a SessionError on
53
+ * anything else that isn't a session, which TokenSession treats as
54
+ * transient and retries.
55
+ */
56
+ export async function fetchSession(
57
+ url: string,
58
+ playbackId: string,
59
+ native: boolean,
60
+ fetchFn: typeof fetch = fetch,
61
+ ): Promise<PlaybackSession | null> {
62
+ let res: Response
63
+ try {
64
+ res = await fetchFn(url, {
65
+ method: 'POST',
66
+ headers: { 'Content-Type': 'application/json' },
67
+ body: JSON.stringify({ playback_id: playbackId, native }),
68
+ cache: 'no-store',
69
+ })
70
+ } catch {
71
+ throw new SessionError(0, 'the session URL could not be reached')
72
+ }
73
+ if (res.status === 401 || res.status === 403) {
74
+ await res.body?.cancel()
75
+ return null
76
+ }
77
+ if (!res.ok) {
78
+ await res.body?.cancel()
79
+ throw new SessionError(res.status, `session: HTTP ${res.status}`)
80
+ }
81
+ let body: Partial<PlaybackSession>
82
+ try {
83
+ body = (await res.json()) as Partial<PlaybackSession>
84
+ } catch {
85
+ throw new SessionError(res.status, 'session: the response is not JSON')
86
+ }
87
+ if (typeof body.base_url !== 'string' || !body.base_url || typeof body.token !== 'string') {
88
+ throw new SessionError(res.status, 'session: the response has no base_url or token')
89
+ }
90
+ return {
91
+ ...body,
92
+ playback_id: typeof body.playback_id === 'string' && body.playback_id ? body.playback_id : playbackId,
93
+ base_url: body.base_url,
94
+ token: body.token,
95
+ }
96
+ }
97
+
98
+ /** The first ready chapters track of a session, if any. */
99
+ export function chaptersTrackOf(session: PlaybackSession | null): string {
100
+ return session?.tracks?.find((t) => t.kind === 'chapters' && t.status === 'ready')?.id ?? ''
101
+ }
package/src/source.ts ADDED
@@ -0,0 +1,58 @@
1
+ import Hls from 'hls.js'
2
+ import { createRefreshLoader, type GetToken, type LoaderClass, type TokenSession } from './refresh.ts'
3
+
4
+ export interface SourceOptions {
5
+ /** base_url from the asset, e.g. https://media.example.net. */
6
+ baseUrl: string
7
+ playbackId: string
8
+ /** A playback token (aud v) for a signed ID; omit for a public one. */
9
+ token?: string | undefined
10
+ /** Extra hls.js options, applied once. */
11
+ hls?: Record<string, unknown> | undefined
12
+ }
13
+
14
+ /** The structured source for Video.js's <hlsjs-video>. */
15
+ export interface ClipMuxSource {
16
+ src: string
17
+ type: string
18
+ preferPlayback: 'mse' | 'native'
19
+ engine: { hlsJs: Record<string, unknown> }
20
+ }
21
+
22
+ /** The master playlist URL of a playback ID. */
23
+ export function playbackUrl(o: Pick<SourceOptions, 'baseUrl' | 'playbackId' | 'token'>): string {
24
+ const base = o.baseUrl.replace(/\/+$/, '')
25
+ const pid = encodeURIComponent(o.playbackId)
26
+ return o.token ? `${base}/v/${o.token}/${pid}/master.m3u8` : `${base}/p/${pid}/master.m3u8`
27
+ }
28
+
29
+ /**
30
+ * Builds the source for <hlsjs-video>. With a session, hls.js (on MSE, and
31
+ * on iOS 17.1+ ManagedMediaSource) loads through the refresh loader. A
32
+ * browser playing HLS natively can't be refreshed: it relies on the token's
33
+ * lifetime (2 × duration or 4 h).
34
+ */
35
+ export function clipmuxSource(o: SourceOptions, session?: TokenSession): ClipMuxSource {
36
+ const hlsJs: Record<string, unknown> = { ...o.hls }
37
+ if (session) {
38
+ const Base = Hls.DefaultConfig.loader as unknown as LoaderClass<{ url: string }>
39
+ hlsJs.loader = createRefreshLoader(Base, session, o.baseUrl, o.playbackId)
40
+ }
41
+ return {
42
+ src: playbackUrl({ ...o, token: session?.current ?? o.token }),
43
+ type: 'application/vnd.apple.mpegurl',
44
+ preferPlayback: 'mse',
45
+ engine: { hlsJs },
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Whether <hlsjs-video> will hand the source to the browser's own HLS
51
+ * player (no MediaSource or ManagedMediaSource), where tokens can't be
52
+ * refreshed. It decides with the same check.
53
+ */
54
+ export function playsNatively(): boolean {
55
+ return !Hls.isSupported()
56
+ }
57
+
58
+ export type { GetToken }
package/src/tracks.ts ADDED
@@ -0,0 +1,91 @@
1
+ // Subtitles and chapters of a ClipMux video (docs/api.md, "Tracks").
2
+ //
3
+ // Subtitles are in the master playlist, so hls.js lists them and loads
4
+ // their playlist and VTT through the same refresh loader as the video. The
5
+ // chapters VTT is never listed there: the app names its track, and it is
6
+ // fetched here with the session's token (refreshed on a 401, like any
7
+ // other request) and parsed into chapters in seconds.
8
+ import type { TokenSession } from './refresh.ts'
9
+
10
+ /**
11
+ * One chapter as the player uses it: start and end in seconds, parsed from
12
+ * the chapters VTT. (`@clipmux/node`'s `Chapter` is the API's, in
13
+ * milliseconds.)
14
+ */
15
+ export interface PlayerChapter {
16
+ startTime: number
17
+ endTime: number
18
+ title: string
19
+ }
20
+
21
+ /** @deprecated Use PlayerChapter; this name clashes with `@clipmux/node`'s API Chapter. */
22
+ export type Chapter = PlayerChapter
23
+
24
+ /** The URL of a track's VTT: the sidecar URL, private or public. */
25
+ export function trackUrl(baseUrl: string, playbackId: string, trackId: string, token?: string): string {
26
+ const base = baseUrl.replace(/\/+$/, '')
27
+ const pid = encodeURIComponent(playbackId)
28
+ const trk = encodeURIComponent(trackId)
29
+ return token ? `${base}/v/${token}/${pid}/tracks/${trk}.vtt` : `${base}/p/${pid}/tracks/${trk}.vtt`
30
+ }
31
+
32
+ const timing = /^(\d{2,}):(\d{2}):(\d{2})\.(\d{3}) --> (\d{2,}):(\d{2}):(\d{2})\.(\d{3})/
33
+ const entities: Record<string, string> = { '&amp;': '&', '&lt;': '<', '&gt;': '>' }
34
+
35
+ // seconds reads the four numbers of a timing match from index at.
36
+ function seconds(m: RegExpExecArray, at: number): number {
37
+ const [h, min, s, ms] = [m[at], m[at + 1], m[at + 2], m[at + 3]].map(Number) as [
38
+ number,
39
+ number,
40
+ number,
41
+ number,
42
+ ]
43
+ return (h * 3600_000 + min * 60_000 + s * 1000 + ms) / 1000
44
+ }
45
+
46
+ /**
47
+ * Parses the chapters VTT ClipMux writes: one cue per chapter, its title on
48
+ * one line with &, < and > escaped.
49
+ */
50
+ export function parseChapters(vtt: string): PlayerChapter[] {
51
+ const out: PlayerChapter[] = []
52
+ const lines = vtt.replace(/\r\n?/g, '\n').split('\n')
53
+ if (!lines[0]?.startsWith('WEBVTT')) throw new Error('not a WebVTT file')
54
+ for (let i = 0; i < lines.length; i++) {
55
+ const m = timing.exec(lines[i] ?? '')
56
+ if (!m) continue
57
+ const text: string[] = []
58
+ while (i + 1 < lines.length && lines[i + 1] !== '') text.push(lines[++i] ?? '')
59
+ out.push({
60
+ startTime: seconds(m, 1),
61
+ endTime: seconds(m, 5),
62
+ title: text.join(' ').replace(/&(amp|lt|gt);/g, (e) => entities[e] ?? e),
63
+ })
64
+ }
65
+ return out
66
+ }
67
+
68
+ /**
69
+ * Fetches a track's VTT with the session's current token. A 401 gets one
70
+ * fresh token and a retry, as the refresh loader does for the video.
71
+ */
72
+ export async function fetchTrack(
73
+ url: (token: string | undefined) => string,
74
+ session: TokenSession | null,
75
+ token: string | undefined,
76
+ fetchFn: typeof fetch = fetch,
77
+ ): Promise<string> {
78
+ let current = session?.current ?? token
79
+ for (let retried = false; ; retried = true) {
80
+ const res = await fetchFn(url(current), { credentials: 'omit' })
81
+ if (res.ok) return res.text()
82
+ if (res.status === 401 && session && current && !retried) {
83
+ const next = await session.refresh(current)
84
+ if (next) {
85
+ current = next
86
+ continue
87
+ }
88
+ }
89
+ throw new Error(`track: HTTP ${res.status}`)
90
+ }
91
+ }