@portalshq/capability-video-delivery 0.1.4 → 0.1.8

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.
@@ -0,0 +1,406 @@
1
+ const DEFAULT_MAX_READY_SECONDS = 60;
2
+ const DEFAULT_MAX_PREPARED_BYTES = 50 * 1024 * 1024;
3
+ // Two in-flight generations overlap text/media of N+1 with staging of N.
4
+ // Raise only after verifying provider quota supports overlapping calls.
5
+ const DEFAULT_MAX_IN_FLIGHT_GENERATION = 2;
6
+ const DEFAULT_SAFETY_MARGIN_MS = 2_000;
7
+ /** Distinct visuals buffered staged-or-released ahead of playout (2-3 total). */
8
+ const DEFAULT_BUFFERED_SLOTS = 3;
9
+ const ESTIMATED_TURN_SECONDS = 15;
10
+ /**
11
+ * Generates ambient turns ahead of playout, stages them remotely, and only
12
+ * releases FIFO work when doing so cannot delay the next scheduled episode.
13
+ * The class owns all background promises so a coordinator can abort and join
14
+ * them during stop, restart, and mode changes.
15
+ */
16
+ export class BufferedProgrammingPipeline {
17
+ options;
18
+ generatedTurns = new Map();
19
+ stagedTurns = new Map();
20
+ releasedTurns = new Map();
21
+ skippedSequences = new Set();
22
+ inFlightGeneration = new Set();
23
+ metrics = new Map();
24
+ monitorPromises = new Set();
25
+ maxReadySeconds;
26
+ maxPreparedBytes;
27
+ maxInFlightGeneration;
28
+ maxBufferedSlots;
29
+ safetyMarginMs;
30
+ controller;
31
+ refillPromise;
32
+ nextGenerationSequence;
33
+ nextStageSequence;
34
+ nextReleaseSequence;
35
+ preparedBytes = 0;
36
+ nextGenerationAt = 0;
37
+ revision = 0;
38
+ waiters = new Set();
39
+ constructor(options) {
40
+ this.options = options;
41
+ this.maxReadySeconds = boundedOption(options.maxReadySeconds ?? DEFAULT_MAX_READY_SECONDS, "maxReadySeconds", 1, 300);
42
+ this.maxPreparedBytes = boundedOption(options.maxPreparedBytes ?? DEFAULT_MAX_PREPARED_BYTES, "maxPreparedBytes", 1_024, 512 * 1024 * 1024);
43
+ this.maxInFlightGeneration = boundedOption(options.maxInFlightGeneration ?? DEFAULT_MAX_IN_FLIGHT_GENERATION, "maxInFlightGeneration", 1, 4);
44
+ this.safetyMarginMs = boundedOption(options.safetyMarginMs ?? DEFAULT_SAFETY_MARGIN_MS, "safetyMarginMs", 0, 30_000);
45
+ this.maxBufferedSlots = boundedOption(options.maxBufferedSlots ?? DEFAULT_BUFFERED_SLOTS, "maxBufferedSlots", 1, 5);
46
+ this.nextGenerationSequence = options.initialSequence;
47
+ this.nextStageSequence = options.initialSequence;
48
+ this.nextReleaseSequence = options.initialSequence;
49
+ }
50
+ getStatus() {
51
+ return {
52
+ inFlightGeneration: this.inFlightGeneration.size,
53
+ preparedBytes: this.preparedBytes,
54
+ readySeconds: this.readySeconds(),
55
+ stagedTurns: this.stagedTurns.size,
56
+ releasedTurns: this.releasedTurns.size,
57
+ nextReleaseSequence: this.nextReleaseSequence,
58
+ };
59
+ }
60
+ start(signal) {
61
+ if (this.refillPromise)
62
+ return;
63
+ const controller = new AbortController();
64
+ this.controller = controller;
65
+ const abort = () => controller.abort(signal.reason);
66
+ signal.addEventListener("abort", abort, { once: true });
67
+ this.refillPromise = this.refill(controller.signal)
68
+ .finally(() => signal.removeEventListener("abort", abort));
69
+ }
70
+ async releaseNextSafe(nextEpisodeStart, signal) {
71
+ signal.throwIfAborted();
72
+ // A released item remains outstanding until the Streamer reports its
73
+ // terminal state (played out). Keep up to maxBufferedSlots *distinct
74
+ // visuals* outstanding so the next image is already queued when the
75
+ // current duration completes. A split narration shares one contentId
76
+ // across its segments, so three slots of the same picture count as one.
77
+ // Only released (FIFO-eligible) visuals block further releases — staged
78
+ // work must always be releasable, otherwise a full staged buffer
79
+ // deadlocks. The Streamer plays FIFO, each for its own imageDuration —
80
+ // queue time never shortens playback. Video-safe: contentKey is
81
+ // media-agnostic (image today, video tomorrow), never image-byte-specific.
82
+ if (this.releasedDistinctCount() >= this.maxBufferedSlots)
83
+ return { state: "pending" };
84
+ const turn = this.stagedTurns.get(this.nextReleaseSequence);
85
+ if (!turn)
86
+ return { state: "pending" };
87
+ if (!this.canReleaseTurn(Date.now(), nextEpisodeStart)) {
88
+ return { state: "blocked", episodeStart: nextEpisodeStart };
89
+ }
90
+ const metrics = this.metricsFor(turn.sequence);
91
+ try {
92
+ const jobs = await this.options.releaseTurn(turn, this.workerSignal());
93
+ if (jobs.length === 0)
94
+ throw new Error("Streamer released an empty ambient turn");
95
+ metrics.releasedAt = Date.now();
96
+ this.stagedTurns.delete(turn.sequence);
97
+ this.preparedBytes -= turn.totalBytes;
98
+ this.releasedTurns.set(turn.sequence, {
99
+ durationSeconds: turn.totalDurationSeconds,
100
+ jobIds: jobs.map((job) => job.id),
101
+ contentKey: contentKeyForTurn(turn),
102
+ });
103
+ this.nextReleaseSequence += 1;
104
+ this.publishMetrics(metrics);
105
+ this.notify();
106
+ this.startMonitoring(turn.sequence, jobs, metrics);
107
+ this.publishActiveJobs();
108
+ return { state: "released", sequence: turn.sequence, jobIds: jobs.map((job) => job.id) };
109
+ }
110
+ catch (cause) {
111
+ this.options.onError(cause, "release", turn.sequence);
112
+ throw cause;
113
+ }
114
+ }
115
+ async waitForProgress(afterRevision, signal) {
116
+ if (this.revision !== afterRevision)
117
+ return;
118
+ if (signal.aborted)
119
+ throw signal.reason;
120
+ await new Promise((resolve, reject) => {
121
+ const wake = () => {
122
+ cleanup();
123
+ resolve();
124
+ };
125
+ const abort = () => {
126
+ cleanup();
127
+ reject(signal.reason);
128
+ };
129
+ const cleanup = () => {
130
+ this.waiters.delete(wake);
131
+ signal.removeEventListener("abort", abort);
132
+ };
133
+ this.waiters.add(wake);
134
+ signal.addEventListener("abort", abort, { once: true });
135
+ if (this.revision !== afterRevision)
136
+ wake();
137
+ });
138
+ }
139
+ currentRevision() {
140
+ return this.revision;
141
+ }
142
+ async abortAndAwaitAll(reason = new Error("Ambient pipeline stopped")) {
143
+ this.controller?.abort(reason);
144
+ this.notify();
145
+ await this.refillPromise?.catch(() => undefined);
146
+ await Promise.allSettled([...this.monitorPromises]);
147
+ this.controller = undefined;
148
+ this.refillPromise = undefined;
149
+ }
150
+ async refill(signal) {
151
+ while (!signal.aborted) {
152
+ await this.stageGeneratedTurns(signal);
153
+ let launched = false;
154
+ while (!signal.aborted
155
+ && Date.now() >= this.nextGenerationAt
156
+ && this.inFlightGeneration.size < this.maxInFlightGeneration
157
+ && this.hasGenerationCapacity()) {
158
+ this.launchGeneration(this.nextGenerationSequence++, signal);
159
+ launched = true;
160
+ }
161
+ if (launched)
162
+ continue;
163
+ const revision = this.revision;
164
+ const progress = this.waitForProgress(revision, signal);
165
+ const cooldown = this.nextGenerationAt > Date.now()
166
+ ? wait(this.nextGenerationAt - Date.now(), signal)
167
+ : undefined;
168
+ await (cooldown ? Promise.race([progress, cooldown]) : progress).catch((cause) => {
169
+ if (!signal.aborted)
170
+ throw cause;
171
+ });
172
+ }
173
+ }
174
+ launchGeneration(sequence, signal) {
175
+ this.inFlightGeneration.add(sequence);
176
+ const metrics = this.metricsFor(sequence);
177
+ metrics.generationStartedAt = Date.now();
178
+ void this.options.generateTurn(sequence, signal)
179
+ .then((turn) => {
180
+ metrics.generationEndedAt = Date.now();
181
+ metrics.generationMs = metrics.generationEndedAt - metrics.generationStartedAt;
182
+ if (!turn) {
183
+ this.skippedSequences.add(sequence);
184
+ this.nextGenerationAt = Date.now() + 2_000;
185
+ this.publishMetrics(metrics);
186
+ return;
187
+ }
188
+ if (!this.hasPreparedCapacity(turn)) {
189
+ this.skippedSequences.add(sequence);
190
+ this.options.onError(new Error(`Ambient turn ${sequence} exceeded configured pipeline bounds`), "generation", sequence);
191
+ this.publishMetrics(metrics);
192
+ return;
193
+ }
194
+ this.generatedTurns.set(sequence, turn);
195
+ this.preparedBytes += turn.totalBytes;
196
+ this.publishMetrics(metrics);
197
+ })
198
+ .catch((cause) => {
199
+ if (!signal.aborted)
200
+ this.options.onError(cause, "generation", sequence);
201
+ this.skippedSequences.add(sequence);
202
+ this.nextGenerationAt = Date.now() + 2_000;
203
+ })
204
+ .finally(() => {
205
+ this.inFlightGeneration.delete(sequence);
206
+ this.notify();
207
+ });
208
+ }
209
+ async stageGeneratedTurns(signal) {
210
+ while (!signal.aborted) {
211
+ // `staged` uploads reserve Streamer capacity too. Cap distinct visuals
212
+ // (not delivery slots) at the buffer depth so one split narration that
213
+ // shares a single image cannot fill the buffer and starve the next
214
+ // distinct image. A failed later segment then cannot strand an
215
+ // arbitrary prefix of an ambient narration in the remote queue.
216
+ if (this.bufferedDistinctCount() >= this.maxBufferedSlots)
217
+ return;
218
+ if (this.skippedSequences.delete(this.nextStageSequence)) {
219
+ this.nextStageSequence += 1;
220
+ if (this.nextReleaseSequence < this.nextStageSequence && !this.stagedTurns.has(this.nextReleaseSequence)) {
221
+ this.nextReleaseSequence += 1;
222
+ }
223
+ this.notify();
224
+ continue;
225
+ }
226
+ const turn = this.generatedTurns.get(this.nextStageSequence);
227
+ if (!turn)
228
+ return;
229
+ const metrics = this.metricsFor(turn.sequence);
230
+ metrics.stagingStartedAt = Date.now();
231
+ try {
232
+ await this.options.stageTurn(turn, signal);
233
+ metrics.stagingEndedAt = Date.now();
234
+ metrics.stagingMs = metrics.stagingEndedAt - metrics.stagingStartedAt;
235
+ this.generatedTurns.delete(turn.sequence);
236
+ this.stagedTurns.set(turn.sequence, turn);
237
+ this.nextStageSequence += 1;
238
+ this.publishMetrics(metrics);
239
+ this.notify();
240
+ }
241
+ catch (cause) {
242
+ if (!signal.aborted)
243
+ this.options.onError(cause, "staging", turn.sequence);
244
+ this.generatedTurns.delete(turn.sequence);
245
+ this.preparedBytes -= turn.totalBytes;
246
+ this.skippedSequences.add(turn.sequence);
247
+ this.notify();
248
+ return;
249
+ }
250
+ }
251
+ }
252
+ startMonitoring(sequence, jobs, metrics) {
253
+ const jobStates = new Map();
254
+ const recordJobUpdate = (job) => {
255
+ const previous = jobStates.get(job.id);
256
+ if (previous === job.status)
257
+ return;
258
+ jobStates.set(job.id, job.status);
259
+ metrics.jobStateTransitions.push({
260
+ timestamp: Date.now(),
261
+ jobId: job.id,
262
+ ...(previous ? { from: previous } : {}),
263
+ to: job.status,
264
+ });
265
+ };
266
+ jobs.forEach(recordJobUpdate);
267
+ const monitor = this.options.monitorJobs(jobs, this.workerSignal(), recordJobUpdate)
268
+ .catch((cause) => {
269
+ if (!this.workerSignal().aborted)
270
+ this.options.onError(cause, "monitoring", sequence);
271
+ })
272
+ .finally(() => {
273
+ metrics.monitoringEndedAt = Date.now();
274
+ if (metrics.generationStartedAt)
275
+ metrics.pipelineMs = metrics.monitoringEndedAt - metrics.generationStartedAt;
276
+ this.releasedTurns.delete(sequence);
277
+ this.publishMetrics(metrics);
278
+ this.metrics.delete(sequence);
279
+ this.publishActiveJobs();
280
+ this.notify();
281
+ this.monitorPromises.delete(monitor);
282
+ });
283
+ this.monitorPromises.add(monitor);
284
+ }
285
+ canReleaseTurn(now, nextEpisodeStart) {
286
+ if (nextEpisodeStart === null)
287
+ return true;
288
+ // `turn` is already part of stagedTurns. Count all staged work so a
289
+ // sequence-ordered release cannot make an episode late after this call.
290
+ const reservedMs = (this.releasedDurationSeconds() + this.stagedDurationSeconds()) * 1_000;
291
+ return now + reservedMs + this.safetyMarginMs < nextEpisodeStart;
292
+ }
293
+ hasGenerationCapacity() {
294
+ // Keep the next image(s) generating while the buffer plays out: staging
295
+ // consumes in sequence order, so a fast provider just fills the generated
296
+ // map instead of creating skipped sequences. Memory stays bounded by the
297
+ // ready-seconds and prepared-bytes caps below.
298
+ if (this.generatedTurns.size + this.inFlightGeneration.size >= Math.max(this.maxInFlightGeneration, this.maxBufferedSlots))
299
+ return false;
300
+ const reservedSeconds = this.readySeconds() + this.inFlightGeneration.size * ESTIMATED_TURN_SECONDS;
301
+ return reservedSeconds < this.maxReadySeconds && this.preparedBytes < this.maxPreparedBytes;
302
+ }
303
+ hasPreparedCapacity(turn) {
304
+ return this.readySeconds() + turn.totalDurationSeconds <= this.maxReadySeconds
305
+ && this.preparedBytes + turn.totalBytes <= this.maxPreparedBytes;
306
+ }
307
+ readySeconds() {
308
+ return this.releasedDurationSeconds() + this.stagedDurationSeconds()
309
+ + [...this.generatedTurns.values()].reduce((total, turn) => total + turn.totalDurationSeconds, 0);
310
+ }
311
+ releasedDurationSeconds() {
312
+ return [...this.releasedTurns.values()].reduce((total, turn) => total + turn.durationSeconds, 0);
313
+ }
314
+ stagedDurationSeconds() {
315
+ return [...this.stagedTurns.values()].reduce((total, turn) => total + turn.totalDurationSeconds, 0);
316
+ }
317
+ /**
318
+ * Distinct visuals currently reserving remote capacity (staged + released).
319
+ * Split siblings share one contentKey, so N slots of the same picture count
320
+ * as one — the buffer guarantees distinct images, not delivery slots.
321
+ * Staging gate only: releases are gated on released visuals alone so a
322
+ * full staged buffer can always drain.
323
+ */
324
+ bufferedDistinctCount() {
325
+ const keys = new Set();
326
+ for (const turn of this.stagedTurns.values())
327
+ keys.add(contentKeyForTurn(turn));
328
+ for (const turn of this.releasedTurns.values())
329
+ keys.add(turn.contentKey);
330
+ return keys.size;
331
+ }
332
+ /** Distinct visuals already released and still outstanding (playing/monitored). */
333
+ releasedDistinctCount() {
334
+ return new Set([...this.releasedTurns.values()].map((turn) => turn.contentKey)).size;
335
+ }
336
+ workerSignal() {
337
+ if (!this.controller)
338
+ throw new Error("Ambient pipeline has not started");
339
+ return this.controller.signal;
340
+ }
341
+ metricsFor(sequence) {
342
+ let metrics = this.metrics.get(sequence);
343
+ if (!metrics) {
344
+ if (this.metrics.size >= 100)
345
+ this.metrics.delete(this.metrics.keys().next().value);
346
+ metrics = { sequence, jobStateTransitions: [] };
347
+ this.metrics.set(sequence, metrics);
348
+ }
349
+ return metrics;
350
+ }
351
+ publishMetrics(metrics) {
352
+ this.options.onMetrics({ ...metrics });
353
+ }
354
+ publishActiveJobs() {
355
+ this.options.onActiveJobsChanged([...this.releasedTurns.values()].flatMap((turn) => turn.jobIds));
356
+ }
357
+ notify() {
358
+ this.revision += 1;
359
+ for (const wake of this.waiters)
360
+ wake();
361
+ this.waiters.clear();
362
+ }
363
+ }
364
+ function boundedOption(value, name, minimum, maximum) {
365
+ if (!Number.isFinite(value) || !Number.isInteger(value) || value < minimum || value > maximum) {
366
+ throw new TypeError(`${name} must be an integer between ${minimum} and ${maximum}`);
367
+ }
368
+ return value;
369
+ }
370
+ /**
371
+ * Media-agnostic visual identity for buffer accounting. Prefers the explicit
372
+ * contentId (set per AI generation, shared across its split segments),
373
+ * falls back to the generation idempotency prefix, then image/video bytes,
374
+ * then sequence. Image/audio/video share this key space equally — a future
375
+ * video turn counts as one distinct visual exactly like an image turn.
376
+ */
377
+ function contentKeyForTurn(turn) {
378
+ if (typeof turn.contentId === "string" && turn.contentId.length > 0)
379
+ return turn.contentId;
380
+ const prefix = turn.idempotencyPrefix.split(":segment:")[0];
381
+ if (prefix && prefix !== turn.idempotencyPrefix)
382
+ return prefix;
383
+ if (turn.idempotencyPrefix)
384
+ return turn.idempotencyPrefix;
385
+ const imageSha = turn.image?.sha256;
386
+ if (typeof imageSha === "string" && imageSha.length > 0)
387
+ return `sha:${imageSha}`;
388
+ const videoSha = turn.video?.sha256;
389
+ if (typeof videoSha === "string" && videoSha.length > 0)
390
+ return `sha:${videoSha}`;
391
+ return `sequence:${turn.sequence}`;
392
+ }
393
+ function wait(durationMs, signal) {
394
+ return new Promise((resolve, reject) => {
395
+ const timer = setTimeout(done, durationMs);
396
+ const abort = () => done(signal.reason ?? new Error("Aborted"));
397
+ function done(error) {
398
+ clearTimeout(timer);
399
+ signal.removeEventListener("abort", abort);
400
+ error === undefined ? resolve() : reject(error);
401
+ }
402
+ signal.addEventListener("abort", abort, { once: true });
403
+ if (signal.aborted)
404
+ abort();
405
+ });
406
+ }
@@ -0,0 +1,39 @@
1
+ /** A timed text item that can be encoded as a WebVTT sidecar file. */
2
+ export interface CaptionCue {
3
+ id?: string;
4
+ startTimeSeconds: number;
5
+ endTimeSeconds: number;
6
+ text: string;
7
+ }
8
+ interface CaptionTrackDetails {
9
+ /** Stable, application-owned identifier for the track. */
10
+ id: string;
11
+ /** Human-readable picker label, for example "English". */
12
+ label: string;
13
+ /** BCP 47 language tag, passed to the viewer as `srclang`. */
14
+ language: string;
15
+ /** HTML track kind. Defaults to `captions`. */
16
+ kind?: "captions" | "subtitles";
17
+ /** Whether the viewer should select this track initially. At most one may be true. */
18
+ default?: boolean;
19
+ }
20
+ /**
21
+ * Sidecar captions rendered by this package into native `<track>` elements.
22
+ * Provide a hosted VTT URL or directly supply timed cues for the package to
23
+ * turn into a temporary browser-local VTT source.
24
+ */
25
+ export type CaptionTrack = CaptionTrackDetails & ({
26
+ src: string;
27
+ cues?: never;
28
+ } | {
29
+ cues: readonly CaptionCue[];
30
+ src?: never;
31
+ });
32
+ /**
33
+ * Validates and copies caption metadata for safe transport in a playback
34
+ * descriptor. Caption media remains outside the video stream.
35
+ */
36
+ export declare function normalizeCaptionTracks(tracks: readonly CaptionTrack[]): CaptionTrack[];
37
+ /** Creates a standards-compliant WebVTT document when an app owns cue generation. */
38
+ export declare function createWebVtt(cues: readonly CaptionCue[]): string;
39
+ export {};
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Validates and copies caption metadata for safe transport in a playback
3
+ * descriptor. Caption media remains outside the video stream.
4
+ */
5
+ export function normalizeCaptionTracks(tracks) {
6
+ const ids = new Set();
7
+ let defaultCount = 0;
8
+ return tracks.map((track, index) => {
9
+ const id = requiredText(track.id, `captionTracks[${index}].id`);
10
+ if (ids.has(id))
11
+ throw new TypeError(`captionTracks contains duplicate id: ${id}`);
12
+ ids.add(id);
13
+ const label = requiredText(track.label, `captionTracks[${index}].label`);
14
+ const language = requiredText(track.language, `captionTracks[${index}].language`);
15
+ const hasSrc = track.src !== undefined;
16
+ const hasCues = track.cues !== undefined;
17
+ if (hasSrc === hasCues) {
18
+ throw new TypeError(`captionTracks[${index}] must contain exactly one of src or cues`);
19
+ }
20
+ const kind = track.kind ?? "captions";
21
+ if (kind !== "captions" && kind !== "subtitles") {
22
+ throw new TypeError(`captionTracks[${index}].kind must be captions or subtitles`);
23
+ }
24
+ if (track.default)
25
+ defaultCount += 1;
26
+ if (defaultCount > 1)
27
+ throw new TypeError("captionTracks can contain at most one default track");
28
+ const details = { id, label, language, kind, ...(track.default ? { default: true } : {}) };
29
+ return hasSrc
30
+ ? { ...details, src: normalizeVttUrl(track.src, `captionTracks[${index}].src`) }
31
+ : { ...details, cues: normalizeCaptionCues(track.cues, `captionTracks[${index}].cues`) };
32
+ });
33
+ }
34
+ /** Creates a standards-compliant WebVTT document when an app owns cue generation. */
35
+ export function createWebVtt(cues) {
36
+ return `WEBVTT\n\n${normalizeCaptionCues(cues, "cues").map((cue) => {
37
+ const id = cue.id === undefined ? "" : `${cue.id}\n`;
38
+ return `${id}${formatTimestamp(cue.startTimeSeconds)} --> ${formatTimestamp(cue.endTimeSeconds)}\n${cue.text}`;
39
+ }).join("\n\n")}\n`;
40
+ }
41
+ function normalizeCaptionCues(cues, field) {
42
+ if (cues.length === 0)
43
+ throw new TypeError(`${field} must contain at least one cue`);
44
+ let previousEnd = 0;
45
+ return cues.map((cue, index) => {
46
+ if (!Number.isFinite(cue.startTimeSeconds) || cue.startTimeSeconds < 0) {
47
+ throw new TypeError(`${field}[${index}].startTimeSeconds must be a non-negative finite number`);
48
+ }
49
+ if (!Number.isFinite(cue.endTimeSeconds) || cue.endTimeSeconds <= cue.startTimeSeconds) {
50
+ throw new TypeError(`${field}[${index}].endTimeSeconds must be after startTimeSeconds`);
51
+ }
52
+ if (cue.startTimeSeconds < previousEnd) {
53
+ throw new TypeError("cues must be ordered without overlapping");
54
+ }
55
+ previousEnd = cue.endTimeSeconds;
56
+ const text = requiredText(cue.text, `${field}[${index}].text`);
57
+ const id = cue.id === undefined ? undefined : requiredText(cue.id, `${field}[${index}].id`);
58
+ return { startTimeSeconds: cue.startTimeSeconds, endTimeSeconds: cue.endTimeSeconds, text, ...(id === undefined ? {} : { id }) };
59
+ });
60
+ }
61
+ function normalizeVttUrl(value, field) {
62
+ const url = new URL(value);
63
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
64
+ throw new TypeError(`${field} must use http or https`);
65
+ }
66
+ if (url.username || url.password || url.hash) {
67
+ throw new TypeError(`${field} cannot include credentials or a fragment`);
68
+ }
69
+ return url.toString();
70
+ }
71
+ function requiredText(value, field) {
72
+ const normalized = value.trim();
73
+ if (!normalized)
74
+ throw new TypeError(`${field} is required`);
75
+ return normalized;
76
+ }
77
+ function formatTimestamp(totalSeconds) {
78
+ const milliseconds = Math.round(totalSeconds * 1_000);
79
+ const hours = Math.floor(milliseconds / 3_600_000);
80
+ const minutes = Math.floor((milliseconds % 3_600_000) / 60_000);
81
+ const seconds = Math.floor((milliseconds % 60_000) / 1_000);
82
+ const remainder = milliseconds % 1_000;
83
+ return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}.${String(remainder).padStart(3, "0")}`;
84
+ }
@@ -0,0 +1,56 @@
1
+ import type { HlsPlaybackSession } from "./live-session.js";
2
+ export type PlaybackState = "idle" | "loading" | "playing" | "buffering" | "reconnecting" | "error" | "destroyed";
3
+ export interface PlaybackObservation {
4
+ state: PlaybackState;
5
+ attempt: number;
6
+ error?: unknown;
7
+ }
8
+ interface HlsLike {
9
+ loadSource(source: string): void;
10
+ attachMedia(media: HTMLMediaElement): void;
11
+ startLoad?(): void;
12
+ recoverMediaError?(): void;
13
+ on?(event: string, handler: (...args: unknown[]) => void): void;
14
+ destroy(): void;
15
+ }
16
+ interface HlsConstructor {
17
+ new (config?: Record<string, unknown>): HlsLike;
18
+ isSupported(): boolean;
19
+ Events?: {
20
+ ERROR?: string;
21
+ };
22
+ ErrorTypes?: {
23
+ NETWORK_ERROR?: string;
24
+ MEDIA_ERROR?: string;
25
+ };
26
+ }
27
+ export interface HlsPlaybackControllerOptions {
28
+ media: HTMLMediaElement;
29
+ session: Pick<HlsPlaybackSession, "playbackManifestUrl">;
30
+ maxReconnectAttempts?: number;
31
+ reconnectDelayMs?: number;
32
+ hlsConfig?: Record<string, unknown>;
33
+ loadHls?: () => Promise<HlsConstructor>;
34
+ onObservation?: (observation: PlaybackObservation) => void;
35
+ }
36
+ /** Owns native HLS/hls.js attachment and bounded recovery for one media element. */
37
+ export declare class HlsPlaybackController {
38
+ private readonly options;
39
+ private hls;
40
+ private timer;
41
+ private generation;
42
+ private attempts;
43
+ private destroyed;
44
+ private readonly maxAttempts;
45
+ private readonly delayMs;
46
+ private readonly loadHls;
47
+ constructor(options: HlsPlaybackControllerOptions);
48
+ attach(): Promise<void>;
49
+ replace(session: Pick<HlsPlaybackSession, "playbackManifestUrl">): Promise<void>;
50
+ reconnect(error?: unknown): void;
51
+ destroy(): void;
52
+ private bindNative;
53
+ private cleanupSource;
54
+ private observe;
55
+ }
56
+ export {};