@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,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 +1,4 @@
1
+ export * from "./captions.js";
1
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 +1,4 @@
1
+ export * from "./captions.js";
1
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,7 +1,11 @@
1
+ import { type CaptionTrack } from "./captions.js";
2
+ import { type LiveProgrammingOptions } from "./live-programming.js";
1
3
  /** A token-free HLS source that an application can hand to its player. */
2
4
  export interface HlsPlaybackSession {
3
5
  sessionId: string;
4
6
  playbackManifestUrl: string;
7
+ /** Optional application-owned sidecar WebVTT tracks for the viewer. */
8
+ captionTracks?: readonly CaptionTrack[];
5
9
  }
6
10
  export interface LiveDeliveryOptions extends HlsPlaybackSession {
7
11
  /** Number of immediate connection attempts before start fails. */
@@ -14,6 +18,8 @@ export interface LiveDeliveryOptions extends HlsPlaybackSession {
14
18
  requestTimeoutMs?: number;
15
19
  /** Injectable for non-browser server runtimes and tests. */
16
20
  fetch?: typeof fetch;
21
+ /** Optional package-owned live release scheduling using an application policy. */
22
+ programming?: LiveProgrammingOptions;
17
23
  }
18
24
  export interface LiveDeliveryStatus extends HlsPlaybackSession {
19
25
  isRunning: boolean;
@@ -22,8 +28,9 @@ export interface LiveDeliveryStatus extends HlsPlaybackSession {
22
28
  lastError?: string;
23
29
  }
24
30
  /**
25
- * Connects one configured HLS playback stream. It never provisions an origin,
26
- * 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.
27
34
  */
28
35
  export declare class LiveDelivery {
29
36
  private readonly session;
@@ -40,6 +47,7 @@ export declare class LiveDelivery {
40
47
  private isHealthy;
41
48
  private lastCheckedAt;
42
49
  private lastError;
50
+ private readonly programming;
43
51
  constructor(options: LiveDeliveryOptions);
44
52
  start(): Promise<HlsPlaybackSession>;
45
53
  stop(): Promise<void>;
@@ -1,6 +1,9 @@
1
+ import { normalizeCaptionTracks } from "./captions.js";
2
+ import { LiveProgrammingScheduler } from "./live-programming.js";
1
3
  /**
2
- * Connects one configured HLS playback stream. It never provisions an origin,
3
- * 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.
4
7
  */
5
8
  export class LiveDelivery {
6
9
  session;
@@ -17,16 +20,23 @@ export class LiveDelivery {
17
20
  isHealthy = false;
18
21
  lastCheckedAt;
19
22
  lastError;
23
+ programming;
20
24
  constructor(options) {
21
25
  this.session = {
22
26
  sessionId: assertSessionId(options.sessionId),
23
27
  playbackManifestUrl: normalizeManifestUrl(options.playbackManifestUrl),
28
+ ...(options.captionTracks === undefined
29
+ ? {}
30
+ : { captionTracks: normalizeCaptionTracks(options.captionTracks) }),
24
31
  };
25
32
  this.retryAttempts = options.retryAttempts ?? 3;
26
33
  this.retryDelayMs = options.retryDelayMs ?? 1_000;
27
34
  this.healthCheckIntervalMs = options.healthCheckIntervalMs ?? 30_000;
28
35
  this.requestTimeoutMs = options.requestTimeoutMs ?? 10_000;
29
36
  this.requestFetch = options.fetch ?? fetch;
37
+ this.programming = options.programming
38
+ ? new LiveProgrammingScheduler(this.session.sessionId, options.programming, () => this.isHealthy)
39
+ : undefined;
30
40
  assertPositiveInteger("retryAttempts", this.retryAttempts);
31
41
  assertNonNegativeInteger("retryDelayMs", this.retryDelayMs);
32
42
  assertPositiveInteger("healthCheckIntervalMs", this.healthCheckIntervalMs);
@@ -58,6 +68,7 @@ export class LiveDelivery {
58
68
  if (this.healthCheckTimer)
59
69
  clearTimeout(this.healthCheckTimer);
60
70
  this.healthCheckTimer = null;
71
+ await this.programming?.stop();
61
72
  }
62
73
  getStatus() {
63
74
  return {
@@ -72,6 +83,7 @@ export class LiveDelivery {
72
83
  await this.checkHealthWithRetry(generation);
73
84
  this.assertCurrent(generation);
74
85
  this.isRunning = true;
86
+ this.programming?.start();
75
87
  this.scheduleHealthCheck(generation);
76
88
  return this.session;
77
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,31 +1,58 @@
1
1
  {
2
2
  "name": "@portalshq/capability-video-delivery",
3
- "version": "0.1.4",
3
+ "version": "0.1.8",
4
4
  "repository": {
5
5
  "type": "git",
6
- "url": "git+https://github.com/portalshq/portals-cloud.git"
6
+ "url": "git+https://github.com/portalshq/portals-cloud.git",
7
+ "directory": "packages/video-delivery"
7
8
  },
8
9
  "description": "Configured HLS stream delivery for application-owned programming and scheduling.",
9
10
  "type": "module",
10
11
  "main": "dist/index.js",
11
12
  "types": "dist/index.d.ts",
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "default": "./dist/index.js"
17
+ },
18
+ "./browser": {
19
+ "types": "./dist/browser.d.ts",
20
+ "default": "./dist/browser.js"
21
+ },
22
+ "./react": {
23
+ "types": "./dist/react.d.ts",
24
+ "default": "./dist/react.js"
25
+ }
26
+ },
12
27
  "files": [
13
28
  "dist"
14
29
  ],
15
30
  "scripts": {
16
31
  "build": "rm -rf dist && tsc -p tsconfig.json",
17
- "publish": "node ../../scripts/publish-workspace.mjs",
18
32
  "typecheck": "tsc -p tsconfig.json --noEmit",
19
33
  "test": "vitest run",
20
34
  "test:coverage": "vitest run --coverage"
21
35
  },
22
36
  "dependencies": {
23
- "@portalshq/contracts": "^0.0.3"
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
+ }
24
47
  },
25
48
  "devDependencies": {
26
49
  "@types/node": "^20.0.0",
27
50
  "@vitest/coverage-v8": "^3.2.7",
28
51
  "typescript": "^5.5.0",
29
52
  "vitest": "^3.2.7"
53
+ },
54
+ "publishConfig": {
55
+ "access": "public",
56
+ "registry": "https://registry.npmjs.org/"
30
57
  }
31
58
  }