@portalshq/capability-video-delivery 0.1.6 → 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.
package/README.md CHANGED
@@ -1,10 +1,10 @@
1
1
  # @portalshq/capability-video-delivery
2
2
 
3
3
  `LiveDelivery` connects one configured HLS playback stream per instance. It
4
- does not create an origin, schedule programs, or define whether content is
5
- "live" or "VOD"; those are application business decisions. It verifies the
6
- configured manifest on start, retries connection failures, and continues to
7
- monitor its health while active.
4
+ does not create an origin or define whether content is "live" or "VOD"; those
5
+ are application decisions. It verifies the configured manifest on start,
6
+ retries connection failures, monitors health, and can run the package-owned
7
+ release scheduler from an injected application programming policy.
8
8
 
9
9
  `HlsPlaybackSession` is the common, token-free descriptor for an HLS-capable
10
10
  application player. Queue Broadcast returns this descriptor after its trusted
@@ -49,6 +49,29 @@ Use `src` instead of `cues` when the consuming app already hosts a `.vtt` file.
49
49
  `createWebVtt(cues)` is also available when it needs VTT content for a custom
50
50
  storage flow.
51
51
 
52
+ ## Realtime live captions
53
+
54
+ For a live HLS timeline, use `createLiveCaptionController` rather than a fixed
55
+ VTT cue list. It creates a native browser text track, forces it visible, and
56
+ timestamps each supplied event at the player's current media time.
57
+
58
+ ```ts
59
+ import { createLiveCaptionController } from "@portalshq/capability-video-delivery/browser";
60
+
61
+ const captions = createLiveCaptionController(video, {
62
+ id: "en-live",
63
+ label: "English",
64
+ language: "en",
65
+ });
66
+
67
+ captionEvents.subscribe(({ text, durationSeconds }) => {
68
+ captions.publish({ text, durationSeconds });
69
+ });
70
+
71
+ // Call when replacing the player/session.
72
+ captions.dispose();
73
+ ```
74
+
52
75
  ## Scheduled and dual-format programming
53
76
 
54
77
  Create separate delivery objects for independent stream windows. For example,
@@ -68,5 +91,20 @@ const afternoon = new LiveDelivery({
68
91
  });
69
92
 
70
93
  await morning.start();
71
- // Application-owned scheduler later calls morning.stop() and afternoon.start().
94
+ // Application routing later calls morning.stop() and afternoon.start().
72
95
  ```
96
+
97
+ For queue-backed programming, pass `programming` to `LiveDelivery`, or use
98
+ `BufferedProgrammingPipeline` directly. The application provides candidates,
99
+ generation/staging callbacks, release policy, limits, and configuration.
100
+ Video Delivery owns single-flight scheduling, FIFO commit/release, safe
101
+ canonical boundaries, shared-visual buffer accounting, monitoring, and stop.
102
+
103
+ ## Browser playback
104
+
105
+ `HlsPlaybackController` in the `/browser` export owns native HLS selection,
106
+ optional hls.js attachment, media recovery, bounded reconnects, replacement,
107
+ and cleanup. `VideoDeliveryPlayer` in the `/react` export combines that
108
+ controller with captions and a held frame. Pass `externalPlayer` when an app
109
+ needs its own video element component; return the element through `mediaRef`
110
+ and the package retains the HLS/reconnect state machine.
package/dist/browser.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { type CaptionTrack } from "./captions.js";
2
2
  import type { HlsPlaybackSession } from "./live-session.js";
3
+ export * from "./live-captions.js";
4
+ export * from "./hls-playback-controller.js";
3
5
  export interface MountedCaptionTracks {
4
6
  /** The exact native elements added to the player. */
5
7
  readonly elements: readonly HTMLTrackElement[];
package/dist/browser.js CHANGED
@@ -1,4 +1,6 @@
1
1
  import { createWebVtt, normalizeCaptionTracks } from "./captions.js";
2
+ export * from "./live-captions.js";
3
+ export * from "./hls-playback-controller.js";
2
4
  /**
3
5
  * Adds sidecar captions to a browser media element. This deliberately uses
4
6
  * native HTML track rendering, so captions stay selectable and never become
@@ -0,0 +1,139 @@
1
+ export interface BufferedProgrammingContent {
2
+ sequence: number;
3
+ totalBytes: number;
4
+ totalDurationSeconds: number;
5
+ idempotencyPrefix: string;
6
+ contentId?: string;
7
+ image?: {
8
+ sha256?: string;
9
+ };
10
+ video?: {
11
+ sha256?: string;
12
+ };
13
+ }
14
+ export interface ProgrammingDeliveryJob {
15
+ id: string;
16
+ status: string;
17
+ }
18
+ export interface ProgrammingPipelineMetrics {
19
+ sequence: number;
20
+ generationStartedAt?: number;
21
+ generationEndedAt?: number;
22
+ stagingStartedAt?: number;
23
+ stagingEndedAt?: number;
24
+ releasedAt?: number;
25
+ monitoringEndedAt?: number;
26
+ generationMs?: number;
27
+ stagingMs?: number;
28
+ pipelineMs?: number;
29
+ jobStateTransitions: Array<{
30
+ timestamp: number;
31
+ jobId: string;
32
+ from?: string;
33
+ to: string;
34
+ }>;
35
+ }
36
+ export interface ProgrammingPipelineStatus {
37
+ inFlightGeneration: number;
38
+ preparedBytes: number;
39
+ readySeconds: number;
40
+ stagedTurns: number;
41
+ releasedTurns: number;
42
+ nextReleaseSequence: number;
43
+ }
44
+ export interface BufferedProgrammingPipelineOptions<TPrepared extends BufferedProgrammingContent, TJob extends ProgrammingDeliveryJob> {
45
+ initialSequence: number;
46
+ generateTurn: (sequence: number, signal: AbortSignal) => Promise<TPrepared | undefined>;
47
+ stageTurn: (turn: TPrepared, signal: AbortSignal) => Promise<void>;
48
+ releaseTurn: (turn: TPrepared, signal: AbortSignal) => Promise<TJob[]>;
49
+ monitorJobs: (jobs: TJob[], signal: AbortSignal, onJobUpdate: (job: TJob) => void) => Promise<void>;
50
+ onError: (cause: unknown, phase: "generation" | "staging" | "release" | "monitoring", sequence: number) => void;
51
+ onActiveJobsChanged: (jobIds: string[]) => void;
52
+ onMetrics: (metrics: ProgrammingPipelineMetrics) => void;
53
+ maxReadySeconds?: number;
54
+ maxPreparedBytes?: number;
55
+ maxInFlightGeneration?: number;
56
+ safetyMarginMs?: number;
57
+ /**
58
+ * How many *distinct visuals* may sit staged-or-released (queued at the
59
+ * Streamer) ahead of playout. 2-3 keeps the next image(s) ready so queue
60
+ * time never eats into per-image playback duration. Split narration
61
+ * segments share one contentId and count as one visual. The Streamer plays
62
+ * FIFO, each slot for its own imageDuration; releases are immediate, never
63
+ * paced to playout. Video-safe: a future video turn counts as one visual
64
+ * exactly like an image turn.
65
+ */
66
+ maxBufferedSlots?: number;
67
+ }
68
+ export type ProgrammingReleaseResult = {
69
+ state: "released";
70
+ sequence: number;
71
+ jobIds: string[];
72
+ } | {
73
+ state: "pending";
74
+ } | {
75
+ state: "blocked";
76
+ episodeStart: number;
77
+ };
78
+ /**
79
+ * Generates ambient turns ahead of playout, stages them remotely, and only
80
+ * releases FIFO work when doing so cannot delay the next scheduled episode.
81
+ * The class owns all background promises so a coordinator can abort and join
82
+ * them during stop, restart, and mode changes.
83
+ */
84
+ export declare class BufferedProgrammingPipeline<TPrepared extends BufferedProgrammingContent, TJob extends ProgrammingDeliveryJob> {
85
+ private readonly options;
86
+ private readonly generatedTurns;
87
+ private readonly stagedTurns;
88
+ private readonly releasedTurns;
89
+ private readonly skippedSequences;
90
+ private readonly inFlightGeneration;
91
+ private readonly metrics;
92
+ private readonly monitorPromises;
93
+ private readonly maxReadySeconds;
94
+ private readonly maxPreparedBytes;
95
+ private readonly maxInFlightGeneration;
96
+ private readonly maxBufferedSlots;
97
+ private readonly safetyMarginMs;
98
+ private controller;
99
+ private refillPromise;
100
+ private nextGenerationSequence;
101
+ private nextStageSequence;
102
+ private nextReleaseSequence;
103
+ private preparedBytes;
104
+ private nextGenerationAt;
105
+ private revision;
106
+ private waiters;
107
+ constructor(options: BufferedProgrammingPipelineOptions<TPrepared, TJob>);
108
+ getStatus(): ProgrammingPipelineStatus;
109
+ start(signal: AbortSignal): void;
110
+ releaseNextSafe(nextEpisodeStart: number | null, signal: AbortSignal): Promise<ProgrammingReleaseResult>;
111
+ waitForProgress(afterRevision: number, signal: AbortSignal): Promise<void>;
112
+ currentRevision(): number;
113
+ abortAndAwaitAll(reason?: Error): Promise<void>;
114
+ private refill;
115
+ private launchGeneration;
116
+ private stageGeneratedTurns;
117
+ private startMonitoring;
118
+ private canReleaseTurn;
119
+ private hasGenerationCapacity;
120
+ private hasPreparedCapacity;
121
+ private readySeconds;
122
+ private releasedDurationSeconds;
123
+ private stagedDurationSeconds;
124
+ /**
125
+ * Distinct visuals currently reserving remote capacity (staged + released).
126
+ * Split siblings share one contentKey, so N slots of the same picture count
127
+ * as one — the buffer guarantees distinct images, not delivery slots.
128
+ * Staging gate only: releases are gated on released visuals alone so a
129
+ * full staged buffer can always drain.
130
+ */
131
+ private bufferedDistinctCount;
132
+ /** Distinct visuals already released and still outstanding (playing/monitored). */
133
+ private releasedDistinctCount;
134
+ private workerSignal;
135
+ private metricsFor;
136
+ private publishMetrics;
137
+ private publishActiveJobs;
138
+ private notify;
139
+ }
@@ -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,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 {};
@@ -0,0 +1,119 @@
1
+ /** Owns native HLS/hls.js attachment and bounded recovery for one media element. */
2
+ export class HlsPlaybackController {
3
+ options;
4
+ hls;
5
+ timer;
6
+ generation = 0;
7
+ attempts = 0;
8
+ destroyed = false;
9
+ maxAttempts;
10
+ delayMs;
11
+ loadHls;
12
+ constructor(options) {
13
+ this.options = options;
14
+ this.maxAttempts = options.maxReconnectAttempts ?? 5;
15
+ this.delayMs = options.reconnectDelayMs ?? 2_000;
16
+ if (!Number.isInteger(this.maxAttempts) || this.maxAttempts < 0)
17
+ throw new TypeError("maxReconnectAttempts must be non-negative");
18
+ if (!Number.isInteger(this.delayMs) || this.delayMs < 0)
19
+ throw new TypeError("reconnectDelayMs must be non-negative");
20
+ this.loadHls = options.loadHls ?? defaultHlsLoader;
21
+ }
22
+ async attach() {
23
+ if (this.destroyed)
24
+ throw new Error("HlsPlaybackController is destroyed");
25
+ const generation = ++this.generation;
26
+ this.cleanupSource();
27
+ this.observe("loading");
28
+ const { media } = this.options;
29
+ if (media.canPlayType("application/vnd.apple.mpegurl")) {
30
+ media.src = this.options.session.playbackManifestUrl;
31
+ media.load();
32
+ this.bindNative(generation);
33
+ return;
34
+ }
35
+ const Hls = await this.loadHls();
36
+ if (generation !== this.generation || this.destroyed)
37
+ return;
38
+ if (!Hls.isSupported())
39
+ throw new Error("HLS playback is not supported by this browser");
40
+ const hls = new Hls(this.options.hlsConfig);
41
+ this.hls = hls;
42
+ hls.on?.(Hls.Events?.ERROR ?? "hlsError", (...args) => {
43
+ const data = args.at(-1);
44
+ if (!data?.fatal)
45
+ return;
46
+ if (data.type === Hls.ErrorTypes?.MEDIA_ERROR) {
47
+ hls.recoverMediaError?.();
48
+ return;
49
+ }
50
+ if (data.type === Hls.ErrorTypes?.NETWORK_ERROR)
51
+ hls.startLoad?.();
52
+ this.reconnect(data);
53
+ });
54
+ hls.loadSource(this.options.session.playbackManifestUrl);
55
+ hls.attachMedia(media);
56
+ this.bindNative(generation);
57
+ }
58
+ async replace(session) {
59
+ this.options.session = session;
60
+ this.attempts = 0;
61
+ await this.attach();
62
+ }
63
+ reconnect(error) {
64
+ if (this.destroyed || this.timer)
65
+ return;
66
+ if (this.attempts >= this.maxAttempts) {
67
+ this.observe("error", error);
68
+ return;
69
+ }
70
+ this.attempts += 1;
71
+ this.observe("reconnecting", error);
72
+ const delay = this.delayMs * Math.max(1, 2 ** (this.attempts - 1));
73
+ this.timer = setTimeout(() => {
74
+ this.timer = undefined;
75
+ void this.attach().catch((caught) => this.reconnect(caught));
76
+ }, delay);
77
+ }
78
+ destroy() {
79
+ if (this.destroyed)
80
+ return;
81
+ this.destroyed = true;
82
+ this.generation += 1;
83
+ if (this.timer)
84
+ clearTimeout(this.timer);
85
+ this.timer = undefined;
86
+ this.cleanupSource();
87
+ this.observe("destroyed");
88
+ }
89
+ bindNative(generation) {
90
+ const { media } = this.options;
91
+ const guard = (callback) => () => {
92
+ if (generation === this.generation && !this.destroyed)
93
+ callback();
94
+ };
95
+ media.onplaying = guard(() => { this.attempts = 0; this.observe("playing"); });
96
+ media.onwaiting = guard(() => this.observe("buffering"));
97
+ media.onstalled = guard(() => this.reconnect(new Error("media stalled")));
98
+ media.onerror = guard(() => this.reconnect(media.error ?? new Error("media playback failed")));
99
+ }
100
+ cleanupSource() {
101
+ this.hls?.destroy();
102
+ this.hls = undefined;
103
+ const { media } = this.options;
104
+ media.onplaying = null;
105
+ media.onwaiting = null;
106
+ media.onstalled = null;
107
+ media.onerror = null;
108
+ media.removeAttribute("src");
109
+ media.load();
110
+ }
111
+ observe(state, error) {
112
+ this.options.onObservation?.({ state, attempt: this.attempts, ...(error === undefined ? {} : { error }) });
113
+ }
114
+ }
115
+ async function defaultHlsLoader() {
116
+ const moduleName = "hls.js";
117
+ const loaded = await import(moduleName);
118
+ return loaded.default;
119
+ }
package/dist/index.d.ts CHANGED
@@ -1,2 +1,4 @@
1
1
  export * from "./captions.js";
2
2
  export * from "./live-session.js";
3
+ export * from "./live-programming.js";
4
+ export * from "./buffered-programming-pipeline.js";
package/dist/index.js CHANGED
@@ -1,2 +1,4 @@
1
1
  export * from "./captions.js";
2
2
  export * from "./live-session.js";
3
+ export * from "./live-programming.js";
4
+ export * from "./buffered-programming-pipeline.js";
@@ -0,0 +1,41 @@
1
+ export interface LiveCaptionTrackOptions {
2
+ /** Stable application identifier for this live caption stream. */
3
+ id: string;
4
+ /** Viewer-facing caption picker label. */
5
+ label: string;
6
+ /** BCP 47 language tag passed to the native text track. */
7
+ language: string;
8
+ kind?: "captions" | "subtitles";
9
+ /** Fallback visibility duration when an event does not provide an end time. */
10
+ defaultDurationSeconds?: number;
11
+ /** Remove cues older than this amount of media time. Defaults to two minutes. */
12
+ retentionSeconds?: number;
13
+ /** Test or browser-compatibility injection point for native text-track cues. */
14
+ createCue?: LiveCaptionCueFactory;
15
+ }
16
+ export interface LiveCaptionEvent {
17
+ text: string;
18
+ /** Defaults to the player's current media time. */
19
+ startTimeSeconds?: number;
20
+ /** Use this when the caption source knows an exact end time. */
21
+ endTimeSeconds?: number;
22
+ /** Used with `startTimeSeconds` when no exact end time is available. */
23
+ durationSeconds?: number;
24
+ }
25
+ export type LiveCaptionCueFactory = (startTimeSeconds: number, endTimeSeconds: number, text: string) => TextTrackCue;
26
+ export interface LiveCaptionController {
27
+ /** The native track that the browser renders over the video. */
28
+ readonly track: TextTrack;
29
+ /** Adds one realtime caption, aligned to the current media timeline. */
30
+ publish(event: LiveCaptionEvent): TextTrackCue;
31
+ /** Removes expired cues using the current player timeline (or a supplied time). */
32
+ prune(currentTimeSeconds?: number): void;
33
+ /** Removes all package-managed cues and disables this track. Idempotent. */
34
+ dispose(): void;
35
+ }
36
+ /**
37
+ * Creates an always-visible native caption track for a live player. Unlike a
38
+ * static VTT file, each event is timestamped as it arrives against the media
39
+ * element's current HLS timeline.
40
+ */
41
+ export declare function createLiveCaptionController(player: HTMLMediaElement, options: LiveCaptionTrackOptions): LiveCaptionController;
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Creates an always-visible native caption track for a live player. Unlike a
3
+ * static VTT file, each event is timestamped as it arrives against the media
4
+ * element's current HLS timeline.
5
+ */
6
+ export function createLiveCaptionController(player, options) {
7
+ const id = requiredText(options.id, "id");
8
+ const label = requiredText(options.label, "label");
9
+ const language = requiredText(options.language, "language");
10
+ const kind = options.kind ?? "captions";
11
+ if (kind !== "captions" && kind !== "subtitles")
12
+ throw new TypeError("kind must be captions or subtitles");
13
+ const defaultDurationSeconds = options.defaultDurationSeconds ?? 5;
14
+ const retentionSeconds = options.retentionSeconds ?? 120;
15
+ assertPositiveFinite("defaultDurationSeconds", defaultDurationSeconds);
16
+ assertNonNegativeFinite("retentionSeconds", retentionSeconds);
17
+ const track = player.addTextTrack(kind, label, language);
18
+ track.mode = "showing";
19
+ const createCue = options.createCue ?? createNativeCue;
20
+ const managedCues = new Set();
21
+ let disposed = false;
22
+ return {
23
+ track,
24
+ publish(event) {
25
+ if (disposed)
26
+ throw new Error(`Live caption track ${id} has been disposed`);
27
+ const text = requiredText(event.text, "event.text");
28
+ const startTimeSeconds = event.startTimeSeconds ?? player.currentTime;
29
+ assertNonNegativeFinite("event.startTimeSeconds", startTimeSeconds);
30
+ const endTimeSeconds = event.endTimeSeconds
31
+ ?? startTimeSeconds + (event.durationSeconds ?? defaultDurationSeconds);
32
+ if (!Number.isFinite(endTimeSeconds) || endTimeSeconds <= startTimeSeconds) {
33
+ throw new TypeError("event.endTimeSeconds must be after startTimeSeconds");
34
+ }
35
+ track.mode = "showing";
36
+ const cue = createCue(startTimeSeconds, endTimeSeconds, text);
37
+ track.addCue(cue);
38
+ managedCues.add(cue);
39
+ pruneExpired(track, managedCues, startTimeSeconds - retentionSeconds);
40
+ return cue;
41
+ },
42
+ prune(currentTimeSeconds = player.currentTime) {
43
+ if (disposed)
44
+ return;
45
+ assertNonNegativeFinite("currentTimeSeconds", currentTimeSeconds);
46
+ pruneExpired(track, managedCues, currentTimeSeconds - retentionSeconds);
47
+ },
48
+ dispose() {
49
+ if (disposed)
50
+ return;
51
+ disposed = true;
52
+ for (const cue of managedCues)
53
+ track.removeCue(cue);
54
+ managedCues.clear();
55
+ track.mode = "disabled";
56
+ },
57
+ };
58
+ }
59
+ function pruneExpired(track, managedCues, cutoffSeconds) {
60
+ for (const cue of managedCues) {
61
+ if (cue.endTime < cutoffSeconds) {
62
+ track.removeCue(cue);
63
+ managedCues.delete(cue);
64
+ }
65
+ }
66
+ }
67
+ function createNativeCue(startTimeSeconds, endTimeSeconds, text) {
68
+ if (typeof VTTCue !== "undefined")
69
+ return new VTTCue(startTimeSeconds, endTimeSeconds, text);
70
+ const webkit = globalThis;
71
+ if (webkit.WebKitVTTCue)
72
+ return new webkit.WebKitVTTCue(startTimeSeconds, endTimeSeconds, text);
73
+ throw new Error("This browser does not support WebVTT cues");
74
+ }
75
+ function requiredText(value, field) {
76
+ const normalized = value.trim();
77
+ if (!normalized)
78
+ throw new TypeError(`${field} is required`);
79
+ return normalized;
80
+ }
81
+ function assertPositiveFinite(field, value) {
82
+ if (!Number.isFinite(value) || value <= 0)
83
+ throw new TypeError(`${field} must be a positive finite number`);
84
+ }
85
+ function assertNonNegativeFinite(field, value) {
86
+ if (!Number.isFinite(value) || value < 0)
87
+ throw new TypeError(`${field} must be a non-negative finite number`);
88
+ }
@@ -0,0 +1,49 @@
1
+ export interface DeliveryCandidate {
2
+ id: string;
3
+ kind: "canonical" | "ambient" | (string & {});
4
+ eligibleAt: Date;
5
+ expiresAt?: Date;
6
+ estimatedDurationMs: number;
7
+ priority: number;
8
+ metadata?: Readonly<Record<string, unknown>>;
9
+ }
10
+ export interface DeliveryScheduleContext {
11
+ now: Date;
12
+ sessionId: string;
13
+ isHealthy: boolean;
14
+ lastReleased?: DeliveryCandidate;
15
+ }
16
+ export interface LiveProgrammingPolicy {
17
+ nextCandidates(context: DeliveryScheduleContext): Promise<readonly DeliveryCandidate[]>;
18
+ canRelease(candidate: DeliveryCandidate, context: DeliveryScheduleContext): boolean;
19
+ }
20
+ export interface LiveReleaseAdapter {
21
+ release(candidate: DeliveryCandidate, signal: AbortSignal): Promise<void>;
22
+ }
23
+ export interface LiveProgrammingOptions {
24
+ policy: LiveProgrammingPolicy;
25
+ release: LiveReleaseAdapter;
26
+ intervalMs?: number;
27
+ now?: () => Date;
28
+ onError?: (error: unknown) => void;
29
+ onReleased?: (candidate: DeliveryCandidate) => void;
30
+ }
31
+ /** Single-flight scheduler used by LiveDelivery after manifest health is established. */
32
+ export declare class LiveProgrammingScheduler {
33
+ private readonly sessionId;
34
+ private readonly options;
35
+ private readonly healthy;
36
+ private readonly intervalMs;
37
+ private readonly now;
38
+ private timer;
39
+ private controller;
40
+ private tickPromise;
41
+ private running;
42
+ private lastReleased;
43
+ private released;
44
+ constructor(sessionId: string, options: LiveProgrammingOptions, healthy: () => boolean);
45
+ start(): void;
46
+ stop(): Promise<void>;
47
+ private schedule;
48
+ private tick;
49
+ }
@@ -0,0 +1,106 @@
1
+ /** Single-flight scheduler used by LiveDelivery after manifest health is established. */
2
+ export class LiveProgrammingScheduler {
3
+ sessionId;
4
+ options;
5
+ healthy;
6
+ intervalMs;
7
+ now;
8
+ timer;
9
+ controller;
10
+ tickPromise;
11
+ running = false;
12
+ lastReleased;
13
+ released = new Set();
14
+ constructor(sessionId, options, healthy) {
15
+ this.sessionId = sessionId;
16
+ this.options = options;
17
+ this.healthy = healthy;
18
+ this.intervalMs = options.intervalMs ?? 1_000;
19
+ if (!Number.isInteger(this.intervalMs) || this.intervalMs < 1)
20
+ throw new TypeError("programming intervalMs must be positive");
21
+ this.now = options.now ?? (() => new Date());
22
+ }
23
+ start() {
24
+ if (this.running)
25
+ return;
26
+ this.running = true;
27
+ this.schedule(0);
28
+ }
29
+ async stop() {
30
+ this.running = false;
31
+ if (this.timer)
32
+ clearTimeout(this.timer);
33
+ this.timer = undefined;
34
+ this.controller?.abort(new Error("Live programming stopped"));
35
+ this.controller = undefined;
36
+ await this.tickPromise;
37
+ }
38
+ schedule(delay) {
39
+ if (!this.running)
40
+ return;
41
+ this.timer = setTimeout(() => {
42
+ this.timer = undefined;
43
+ const pending = this.tick();
44
+ this.tickPromise = pending;
45
+ void pending.finally(() => {
46
+ if (this.tickPromise === pending)
47
+ this.tickPromise = undefined;
48
+ });
49
+ }, delay);
50
+ this.timer.unref?.();
51
+ }
52
+ async tick() {
53
+ if (!this.running)
54
+ return;
55
+ try {
56
+ const now = this.now();
57
+ const context = {
58
+ now, sessionId: this.sessionId, isHealthy: this.healthy(),
59
+ ...(this.lastReleased ? { lastReleased: this.lastReleased } : {}),
60
+ };
61
+ if (context.isHealthy) {
62
+ const candidates = [...await this.options.policy.nextCandidates(context)]
63
+ .map(normalizeCandidate)
64
+ .filter((candidate) => !this.released.has(candidate.id))
65
+ .filter((candidate) => candidate.eligibleAt.getTime() <= now.getTime())
66
+ .filter((candidate) => !candidate.expiresAt || candidate.expiresAt.getTime() > now.getTime())
67
+ .filter((candidate) => this.options.policy.canRelease(candidate, context))
68
+ .sort((a, b) => b.priority - a.priority || a.eligibleAt.getTime() - b.eligibleAt.getTime());
69
+ const candidate = candidates[0];
70
+ if (candidate) {
71
+ const controller = new AbortController();
72
+ this.controller = controller;
73
+ await this.options.release.release(candidate, controller.signal);
74
+ if (!controller.signal.aborted) {
75
+ this.released.add(candidate.id);
76
+ this.lastReleased = candidate;
77
+ this.options.onReleased?.(candidate);
78
+ }
79
+ if (this.controller === controller)
80
+ this.controller = undefined;
81
+ }
82
+ }
83
+ }
84
+ catch (error) {
85
+ if (this.running)
86
+ this.options.onError?.(error);
87
+ }
88
+ finally {
89
+ this.schedule(this.intervalMs);
90
+ }
91
+ }
92
+ }
93
+ function normalizeCandidate(candidate) {
94
+ const id = candidate.id.trim();
95
+ if (!id)
96
+ throw new TypeError("delivery candidate id is required");
97
+ if (!Number.isFinite(candidate.eligibleAt.getTime()))
98
+ throw new TypeError("eligibleAt must be valid");
99
+ if (candidate.expiresAt && !Number.isFinite(candidate.expiresAt.getTime()))
100
+ throw new TypeError("expiresAt must be valid");
101
+ if (!Number.isFinite(candidate.estimatedDurationMs) || candidate.estimatedDurationMs < 0)
102
+ throw new TypeError("estimatedDurationMs must be non-negative");
103
+ if (!Number.isFinite(candidate.priority))
104
+ throw new TypeError("priority must be finite");
105
+ return { ...candidate, id };
106
+ }
@@ -1,4 +1,5 @@
1
1
  import { type CaptionTrack } from "./captions.js";
2
+ import { type LiveProgrammingOptions } from "./live-programming.js";
2
3
  /** A token-free HLS source that an application can hand to its player. */
3
4
  export interface HlsPlaybackSession {
4
5
  sessionId: string;
@@ -17,6 +18,8 @@ export interface LiveDeliveryOptions extends HlsPlaybackSession {
17
18
  requestTimeoutMs?: number;
18
19
  /** Injectable for non-browser server runtimes and tests. */
19
20
  fetch?: typeof fetch;
21
+ /** Optional package-owned live release scheduling using an application policy. */
22
+ programming?: LiveProgrammingOptions;
20
23
  }
21
24
  export interface LiveDeliveryStatus extends HlsPlaybackSession {
22
25
  isRunning: boolean;
@@ -25,8 +28,9 @@ export interface LiveDeliveryStatus extends HlsPlaybackSession {
25
28
  lastError?: string;
26
29
  }
27
30
  /**
28
- * Connects one configured HLS playback stream. It never provisions an origin,
29
- * schedules programming, or distinguishes live from on-demand business flows.
31
+ * Connects one configured HLS playback stream and optionally runs release
32
+ * scheduling from an injected application policy. It never provisions an
33
+ * origin or decides live-versus-on-demand business rules.
30
34
  */
31
35
  export declare class LiveDelivery {
32
36
  private readonly session;
@@ -43,6 +47,7 @@ export declare class LiveDelivery {
43
47
  private isHealthy;
44
48
  private lastCheckedAt;
45
49
  private lastError;
50
+ private readonly programming;
46
51
  constructor(options: LiveDeliveryOptions);
47
52
  start(): Promise<HlsPlaybackSession>;
48
53
  stop(): Promise<void>;
@@ -1,7 +1,9 @@
1
1
  import { normalizeCaptionTracks } from "./captions.js";
2
+ import { LiveProgrammingScheduler } from "./live-programming.js";
2
3
  /**
3
- * Connects one configured HLS playback stream. It never provisions an origin,
4
- * schedules programming, or distinguishes live from on-demand business flows.
4
+ * Connects one configured HLS playback stream and optionally runs release
5
+ * scheduling from an injected application policy. It never provisions an
6
+ * origin or decides live-versus-on-demand business rules.
5
7
  */
6
8
  export class LiveDelivery {
7
9
  session;
@@ -18,6 +20,7 @@ export class LiveDelivery {
18
20
  isHealthy = false;
19
21
  lastCheckedAt;
20
22
  lastError;
23
+ programming;
21
24
  constructor(options) {
22
25
  this.session = {
23
26
  sessionId: assertSessionId(options.sessionId),
@@ -31,6 +34,9 @@ export class LiveDelivery {
31
34
  this.healthCheckIntervalMs = options.healthCheckIntervalMs ?? 30_000;
32
35
  this.requestTimeoutMs = options.requestTimeoutMs ?? 10_000;
33
36
  this.requestFetch = options.fetch ?? fetch;
37
+ this.programming = options.programming
38
+ ? new LiveProgrammingScheduler(this.session.sessionId, options.programming, () => this.isHealthy)
39
+ : undefined;
34
40
  assertPositiveInteger("retryAttempts", this.retryAttempts);
35
41
  assertNonNegativeInteger("retryDelayMs", this.retryDelayMs);
36
42
  assertPositiveInteger("healthCheckIntervalMs", this.healthCheckIntervalMs);
@@ -62,6 +68,7 @@ export class LiveDelivery {
62
68
  if (this.healthCheckTimer)
63
69
  clearTimeout(this.healthCheckTimer);
64
70
  this.healthCheckTimer = null;
71
+ await this.programming?.stop();
65
72
  }
66
73
  getStatus() {
67
74
  return {
@@ -76,6 +83,7 @@ export class LiveDelivery {
76
83
  await this.checkHealthWithRetry(generation);
77
84
  this.assertCurrent(generation);
78
85
  this.isRunning = true;
86
+ this.programming?.start();
79
87
  this.scheduleHealthCheck(generation);
80
88
  return this.session;
81
89
  }
@@ -0,0 +1,17 @@
1
+ import React, { type ComponentType, type ReactNode } from "react";
2
+ import { type PlaybackObservation } from "./hls-playback-controller.js";
3
+ import type { HlsPlaybackSession } from "./live-session.js";
4
+ export interface ExternalVideoPlayerProps extends React.VideoHTMLAttributes<HTMLVideoElement> {
5
+ mediaRef(element: HTMLVideoElement | null): void;
6
+ playback: HlsPlaybackSession;
7
+ }
8
+ export interface VideoDeliveryPlayerProps extends Omit<React.VideoHTMLAttributes<HTMLVideoElement>, "src"> {
9
+ playback: HlsPlaybackSession;
10
+ maxReconnectAttempts?: number;
11
+ reconnectDelayMs?: number;
12
+ externalPlayer?: ComponentType<ExternalVideoPlayerProps>;
13
+ renderOverlay?: (observation: PlaybackObservation) => ReactNode;
14
+ onPlaybackObservation?: (observation: PlaybackObservation) => void;
15
+ }
16
+ /** Base Portals player; applications provide presentation and optional external video rendering. */
17
+ export declare function VideoDeliveryPlayer({ playback, maxReconnectAttempts, reconnectDelayMs, externalPlayer: ExternalPlayer, renderOverlay, onPlaybackObservation, ...videoProps }: VideoDeliveryPlayerProps): React.ReactElement;
package/dist/react.js ADDED
@@ -0,0 +1,58 @@
1
+ import React, { useEffect, useRef, useState } from "react";
2
+ import { mountPlaybackCaptions } from "./browser.js";
3
+ import { HlsPlaybackController } from "./hls-playback-controller.js";
4
+ /** Base Portals player; applications provide presentation and optional external video rendering. */
5
+ export function VideoDeliveryPlayer({ playback, maxReconnectAttempts, reconnectDelayMs, externalPlayer: ExternalPlayer, renderOverlay, onPlaybackObservation, ...videoProps }) {
6
+ const media = useRef(null);
7
+ const observationCallback = useRef(onPlaybackObservation);
8
+ const [observation, setObservation] = useState({ state: "idle", attempt: 0 });
9
+ const [heldFrame, setHeldFrame] = useState();
10
+ observationCallback.current = onPlaybackObservation;
11
+ useEffect(() => {
12
+ const element = media.current;
13
+ if (!element)
14
+ return;
15
+ const controller = new HlsPlaybackController({
16
+ media: element,
17
+ session: playback,
18
+ ...(maxReconnectAttempts === undefined ? {} : { maxReconnectAttempts }),
19
+ ...(reconnectDelayMs === undefined ? {} : { reconnectDelayMs }),
20
+ onObservation: (next) => {
21
+ if (next.state === "buffering" || next.state === "reconnecting")
22
+ setHeldFrame(captureFrame(element));
23
+ if (next.state === "playing")
24
+ setHeldFrame(undefined);
25
+ setObservation(next);
26
+ observationCallback.current?.(next);
27
+ },
28
+ });
29
+ void controller.attach().catch((error) => controller.reconnect(error));
30
+ return () => {
31
+ controller.destroy();
32
+ };
33
+ }, [playback.playbackManifestUrl, playback.sessionId, maxReconnectAttempts, reconnectDelayMs, ExternalPlayer]);
34
+ useEffect(() => {
35
+ const element = media.current;
36
+ if (!element)
37
+ return;
38
+ return mountPlaybackCaptions(element, playback).remove;
39
+ }, [playback.captionTracks, ExternalPlayer]);
40
+ const sharedProps = { ...videoProps, "data-video-delivery-player": playback.sessionId };
41
+ return React.createElement(React.Fragment, null, heldFrame ? React.createElement("img", { src: heldFrame, alt: "", "aria-hidden": true, "data-video-delivery-held-frame": true }) : null, ExternalPlayer
42
+ ? React.createElement(ExternalPlayer, { ...sharedProps, playback, mediaRef: (element) => { media.current = element; } })
43
+ : React.createElement("video", { ...sharedProps, ref: media }), renderOverlay?.(observation));
44
+ }
45
+ function captureFrame(media) {
46
+ if (!media.videoWidth || !media.videoHeight)
47
+ return undefined;
48
+ try {
49
+ const canvas = media.ownerDocument.createElement("canvas");
50
+ canvas.width = media.videoWidth;
51
+ canvas.height = media.videoHeight;
52
+ canvas.getContext("2d")?.drawImage(media, 0, 0, canvas.width, canvas.height);
53
+ return canvas.toDataURL("image/jpeg", 0.82);
54
+ }
55
+ catch {
56
+ return undefined;
57
+ }
58
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@portalshq/capability-video-delivery",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/portalshq/portals-cloud.git",
@@ -18,6 +18,10 @@
18
18
  "./browser": {
19
19
  "types": "./dist/browser.d.ts",
20
20
  "default": "./dist/browser.js"
21
+ },
22
+ "./react": {
23
+ "types": "./dist/react.d.ts",
24
+ "default": "./dist/react.js"
21
25
  }
22
26
  },
23
27
  "files": [
@@ -30,7 +34,16 @@
30
34
  "test:coverage": "vitest run --coverage"
31
35
  },
32
36
  "dependencies": {
33
- "@portalshq/contracts": "^0.0.4"
37
+ "@portalshq/contracts": "^0.0.5"
38
+ },
39
+ "peerDependencies": {
40
+ "hls.js": ">=1.5.0",
41
+ "react": ">=18.0.0"
42
+ },
43
+ "peerDependenciesMeta": {
44
+ "hls.js": {
45
+ "optional": true
46
+ }
34
47
  },
35
48
  "devDependencies": {
36
49
  "@types/node": "^20.0.0",