@portalshq/capability-video-delivery 0.1.10 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  **Reusable agent module:** [integration guide](../../docs/package-agents/video-delivery.md)
4
4
 
5
- HLS playback health checks, browser playback helpers, sidecar captions, and optional application-policy programming. It does not provision an origin, sign manifests, or decide live/VOD product rules.
5
+ HLS playback health checks, browser playback helpers, sidecar captions, WebRTC player for Reactor, and optional application-policy programming. It does not provision an origin, sign manifests, or decide live/VOD product rules.
6
6
 
7
7
  ```ts
8
8
  import { LiveDelivery } from "@portalshq/capability-video-delivery";
@@ -15,13 +15,67 @@ await delivery.stop();
15
15
 
16
16
  ## Exports
17
17
 
18
- - Root: `LiveDelivery`, `HlsPlaybackSession`, caption types/helpers, and programming pipeline types.
18
+ - Root: `LiveDelivery`, `HlsPlaybackSession`, `WebRTCPlayer`, caption types/helpers, and programming pipeline types.
19
19
  - `@portalshq/capability-video-delivery/browser`: `HlsPlaybackController`, `mountPlaybackCaptions`, and `createLiveCaptionController`.
20
20
  - `@portalshq/capability-video-delivery/react`: `VideoDeliveryPlayer`.
21
21
 
22
+ ## WebRTC Player for Reactor
23
+
24
+ The `VideoDeliveryPlayer` React component supports both HLS playback and Reactor WebRTC streaming. Reactor mode is activated by providing `reactorToken`, `reactorSessionId`, and `reactorModelName` props.
25
+
26
+ **Note:** Reactor WebRTC requires the `@reactor-team/js-sdk` package to be installed (optional peer dependency). The component dynamically imports the SDK when Reactor mode is requested.
27
+
28
+ ```tsx
29
+ import { VideoDeliveryPlayer } from "@portalshq/capability-video-delivery/react";
30
+
31
+ // HLS mode (default)
32
+ <VideoDeliveryPlayer
33
+ playback={playbackSession}
34
+ onPlaybackObservation={(obs) => console.log("State:", obs.state)}
35
+ />
36
+
37
+ // Reactor WebRTC mode
38
+ <VideoDeliveryPlayer
39
+ playback={playbackSession}
40
+ reactorToken={reactorJwtToken}
41
+ reactorSessionId={reactorSessionId}
42
+ reactorModelName="reactor/helios"
43
+ onPlaybackObservation={(obs) => console.log("State:", obs.state)}
44
+ />
45
+ ```
46
+
47
+ ### Reactor Integration
48
+
49
+ The Reactor WebRTC wrapper:
50
+ - Dynamically imports `@reactor-team/js-sdk` when Reactor mode is activated
51
+ - Creates Reactor instance with provided model name
52
+ - Connects to Reactor via WebRTC using the provided token
53
+ - Supports session adoption via `sessionId` option
54
+ - Automatically disconnects on component unmount
55
+ - Maps Reactor connection states to VideoDeliveryPlayer observation states
56
+ - Falls back gracefully if Reactor SDK is not installed
57
+
58
+ **Current Status:**
59
+ - ✅ React component structure with Reactor props
60
+ - ✅ Dynamic import of Reactor SDK (optional peer dependency)
61
+ - ✅ Production-ready Reactor SDK integration (connect, disconnect, error handling)
62
+ - ✅ Session adoption support (connect to existing session)
63
+ - ✅ Automatic cleanup on unmount
64
+
65
+ **Recommended:** Install `@reactor-team/js-sdk` in your application to enable Reactor WebRTC mode. The component provides production-ready SDK integration with proper lifecycle management.
66
+
22
67
  ## Usage notes
23
68
 
24
69
  - `LiveDelivery.start()` retries manifest access (three attempts by default), then performs periodic health checks. Inspect `getStatus()` for health and the last failure.
25
70
  - Call browser-caption `remove()` or live-caption `dispose()` when replacing a player/session.
26
71
  - Native HLS is used where available; `hls.js` is an optional peer dependency for other browsers. React is required only for the `/react` entry point.
27
72
  - The manifest URL must be public/unlisted or otherwise playable by the browser. Do not expose origin/control-plane credentials.
73
+ - WebRTC player is a stub; use `@reactor-team/js-sdk` for production Reactor WebRTC connections.
74
+
75
+ ## Program openings
76
+
77
+ `useProgramOpening(live, startsAt)` from the React export provides `idle`,
78
+ `fade-out`, `title`, and `fade-in` phases for an observed scheduled start or
79
+ an off-air-to-live transition. Render the treatment over the video stage and
80
+ keep chat outside that layer. The hook does not replay on a mid-session join;
81
+ applications own the title, styling, and playback readiness.
package/dist/index.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  export * from "./captions.js";
2
2
  export * from "./live-session.js";
3
3
  export * from "./live-programming.js";
4
+ export * from "./webrtc-player.js";
4
5
  export * from "./buffered-programming-pipeline.js";
6
+ export * from "./program-opening.js";
package/dist/index.js CHANGED
@@ -1,4 +1,6 @@
1
1
  export * from "./captions.js";
2
2
  export * from "./live-session.js";
3
3
  export * from "./live-programming.js";
4
+ export * from "./webrtc-player.js";
4
5
  export * from "./buffered-programming-pipeline.js";
6
+ export * from "./program-opening.js";
@@ -0,0 +1,23 @@
1
+ /** Presentation phases for a program's scheduled opening. Applications own the visuals. */
2
+ export type ProgramOpeningPhase = "idle" | "fade-out" | "title" | "fade-in";
3
+ export interface ProgramOpeningOptions {
4
+ onPhaseChange(phase: ProgramOpeningPhase): void;
5
+ fadeMs?: number;
6
+ titleMs?: number;
7
+ }
8
+ /** Runs once for an observed upcoming start, or for an observed off-air to live transition. */
9
+ export declare class ProgramOpeningSequence {
10
+ private readonly options;
11
+ private readonly fadeMs;
12
+ private readonly titleMs;
13
+ private scheduleTimer;
14
+ private phaseTimers;
15
+ private scheduledStart;
16
+ private previousLive;
17
+ private lastOpeningAt;
18
+ private running;
19
+ constructor(options: ProgramOpeningOptions);
20
+ update(live: boolean, startsAt?: string | null): void;
21
+ private open;
22
+ dispose(): void;
23
+ }
@@ -0,0 +1,59 @@
1
+ /** Runs once for an observed upcoming start, or for an observed off-air to live transition. */
2
+ export class ProgramOpeningSequence {
3
+ options;
4
+ fadeMs;
5
+ titleMs;
6
+ scheduleTimer;
7
+ phaseTimers = [];
8
+ scheduledStart = null;
9
+ previousLive = null;
10
+ lastOpeningAt = -Infinity;
11
+ running = false;
12
+ constructor(options) {
13
+ this.options = options;
14
+ this.fadeMs = options.fadeMs ?? 1000;
15
+ this.titleMs = options.titleMs ?? 2500;
16
+ }
17
+ update(live, startsAt) {
18
+ const parsed = startsAt ? Date.parse(startsAt) : NaN;
19
+ const upcoming = Number.isFinite(parsed) && parsed > Date.now() ? parsed : null;
20
+ if (upcoming !== this.scheduledStart) {
21
+ if (this.scheduleTimer)
22
+ clearTimeout(this.scheduleTimer);
23
+ this.scheduleTimer = undefined;
24
+ this.scheduledStart = upcoming;
25
+ if (upcoming !== null && upcoming > this.lastOpeningAt) {
26
+ this.scheduleTimer = setTimeout(() => {
27
+ this.scheduleTimer = undefined;
28
+ if (Date.now() - upcoming < 60_000)
29
+ this.open(upcoming);
30
+ }, Math.max(0, upcoming - Date.now() - this.fadeMs));
31
+ }
32
+ }
33
+ if (this.previousLive === false && live && upcoming === null && Date.now() - this.lastOpeningAt > 60_000) {
34
+ this.open(Date.now());
35
+ }
36
+ this.previousLive = live;
37
+ }
38
+ open(start) {
39
+ if (this.running)
40
+ return;
41
+ this.running = true;
42
+ this.lastOpeningAt = start;
43
+ this.options.onPhaseChange("fade-out");
44
+ this.phaseTimers.push(setTimeout(() => this.options.onPhaseChange("title"), this.fadeMs));
45
+ this.phaseTimers.push(setTimeout(() => this.options.onPhaseChange("fade-in"), this.fadeMs + this.titleMs));
46
+ this.phaseTimers.push(setTimeout(() => {
47
+ this.running = false;
48
+ this.phaseTimers = [];
49
+ this.options.onPhaseChange("idle");
50
+ }, this.fadeMs * 2 + this.titleMs));
51
+ }
52
+ dispose() {
53
+ if (this.scheduleTimer)
54
+ clearTimeout(this.scheduleTimer);
55
+ for (const timer of this.phaseTimers)
56
+ clearTimeout(timer);
57
+ this.phaseTimers = [];
58
+ }
59
+ }
package/dist/react.d.ts CHANGED
@@ -12,6 +12,14 @@ export interface VideoDeliveryPlayerProps extends Omit<React.VideoHTMLAttributes
12
12
  externalPlayer?: ComponentType<ExternalVideoPlayerProps>;
13
13
  renderOverlay?: (observation: PlaybackObservation) => ReactNode;
14
14
  onPlaybackObservation?: (observation: PlaybackObservation) => void;
15
+ /** Reactor token for WebRTC mode (optional - if provided, uses WebRTC instead of HLS) */
16
+ reactorToken?: string;
17
+ /** Reactor session ID for WebRTC mode (optional - creates new session if not provided) */
18
+ reactorSessionId?: string;
19
+ /** Reactor model name for WebRTC mode */
20
+ reactorModelName?: string;
15
21
  }
16
22
  /** 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;
23
+ export declare function VideoDeliveryPlayer({ playback, maxReconnectAttempts, reconnectDelayMs, externalPlayer: ExternalPlayer, renderOverlay, onPlaybackObservation, reactorToken, reactorSessionId, reactorModelName, ...videoProps }: VideoDeliveryPlayerProps): React.ReactElement;
24
+ export { useProgramOpening } from "./use-program-opening.js";
25
+ export type { ProgramOpeningPhase } from "./program-opening.js";
package/dist/react.js CHANGED
@@ -2,13 +2,22 @@ import React, { useEffect, useRef, useState } from "react";
2
2
  import { mountPlaybackCaptions } from "./browser.js";
3
3
  import { HlsPlaybackController } from "./hls-playback-controller.js";
4
4
  /** Base Portals player; applications provide presentation and optional external video rendering. */
5
- export function VideoDeliveryPlayer({ playback, maxReconnectAttempts, reconnectDelayMs, externalPlayer: ExternalPlayer, renderOverlay, onPlaybackObservation, ...videoProps }) {
5
+ export function VideoDeliveryPlayer({ playback, maxReconnectAttempts, reconnectDelayMs, externalPlayer: ExternalPlayer, renderOverlay, onPlaybackObservation, reactorToken, reactorSessionId, reactorModelName, ...videoProps }) {
6
6
  const media = useRef(null);
7
7
  const observationCallback = useRef(onPlaybackObservation);
8
8
  const [observation, setObservation] = useState({ state: "idle", attempt: 0 });
9
9
  const [heldFrame, setHeldFrame] = useState();
10
+ const [useReactor, setUseReactor] = useState(false);
10
11
  observationCallback.current = onPlaybackObservation;
12
+ // Determine if we should use Reactor WebRTC
13
+ const shouldUseReactor = Boolean(reactorToken && reactorModelName);
11
14
  useEffect(() => {
15
+ setUseReactor(shouldUseReactor);
16
+ }, [shouldUseReactor]);
17
+ // HLS mode (existing logic)
18
+ useEffect(() => {
19
+ if (useReactor)
20
+ return; // Skip HLS if using Reactor
12
21
  const element = media.current;
13
22
  if (!element)
14
23
  return;
@@ -30,7 +39,7 @@ export function VideoDeliveryPlayer({ playback, maxReconnectAttempts, reconnectD
30
39
  return () => {
31
40
  controller.destroy();
32
41
  };
33
- }, [playback.playbackManifestUrl, playback.sessionId, maxReconnectAttempts, reconnectDelayMs, ExternalPlayer]);
42
+ }, [useReactor, playback.playbackManifestUrl, playback.sessionId, maxReconnectAttempts, reconnectDelayMs, ExternalPlayer]);
34
43
  useEffect(() => {
35
44
  const element = media.current;
36
45
  if (!element)
@@ -38,6 +47,30 @@ export function VideoDeliveryPlayer({ playback, maxReconnectAttempts, reconnectD
38
47
  return mountPlaybackCaptions(element, playback).remove;
39
48
  }, [playback.captionTracks, ExternalPlayer]);
40
49
  const sharedProps = { ...videoProps, "data-video-delivery-player": playback.sessionId };
50
+ // Reactor WebRTC mode
51
+ if (useReactor && shouldUseReactor) {
52
+ return React.createElement(ReactorWebRTCWrapper, {
53
+ token: reactorToken,
54
+ sessionId: reactorSessionId,
55
+ modelName: reactorModelName,
56
+ mediaRef: media,
57
+ onStatusChange: (status) => {
58
+ const stateMap = {
59
+ connecting: "loading",
60
+ ready: "playing",
61
+ disconnected: "idle",
62
+ failed: "error",
63
+ };
64
+ setObservation({ state: stateMap[status] || "idle", attempt: 0 });
65
+ observationCallback.current?.({ state: stateMap[status] || "idle", attempt: 0 });
66
+ },
67
+ onError: (error) => {
68
+ setObservation({ state: "error", attempt: 0, error });
69
+ observationCallback.current?.({ state: "error", attempt: 0, error });
70
+ },
71
+ });
72
+ }
73
+ // HLS mode (existing)
41
74
  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
75
  ? React.createElement(ExternalPlayer, { ...sharedProps, playback, mediaRef: (element) => { media.current = element; } })
43
76
  : React.createElement("video", { ...sharedProps, ref: media }), renderOverlay?.(observation));
@@ -56,3 +89,100 @@ function captureFrame(media) {
56
89
  return undefined;
57
90
  }
58
91
  }
92
+ function ReactorWebRTCWrapper({ token, sessionId, modelName, mediaRef, onStatusChange, onError, }) {
93
+ // Use dynamic import to avoid bundling Reactor SDK if not needed
94
+ // The @reactor-team/js-sdk is an optional peer dependency
95
+ const [isLoaded, setIsLoaded] = useState(false);
96
+ const [loadError, setLoadError] = useState(null);
97
+ const [reactorInstance, setReactorInstance] = useState(null);
98
+ useEffect(() => {
99
+ let mounted = true;
100
+ let reactor = null;
101
+ async function loadReactorSDK() {
102
+ try {
103
+ // Try to import Reactor SDK (optional peer dependency)
104
+ // @ts-ignore - Optional peer dependency
105
+ const reactorModule = await import("@reactor-team/js-sdk");
106
+ const { Reactor } = reactorModule;
107
+ if (mounted) {
108
+ setIsLoaded(true);
109
+ onStatusChange("connecting");
110
+ // Get the video element
111
+ const videoElement = mediaRef.current;
112
+ if (!videoElement) {
113
+ throw new Error("Video element not available");
114
+ }
115
+ // Create Reactor instance
116
+ reactor = new Reactor({
117
+ modelName: modelName,
118
+ });
119
+ // Connect to Reactor
120
+ await reactor.connect(token, {
121
+ sessionId: sessionId, // Adopt existing session if provided
122
+ autoResumeTracks: true,
123
+ });
124
+ if (mounted) {
125
+ setReactorInstance(reactor);
126
+ onStatusChange("ready");
127
+ console.log("[VideoDeliveryPlayer] Reactor connected successfully to session:", sessionId || "new session");
128
+ }
129
+ }
130
+ }
131
+ catch (error) {
132
+ if (mounted) {
133
+ const err = error instanceof Error ? error : new Error(String(error));
134
+ setLoadError(err);
135
+ onError(err);
136
+ onStatusChange("failed");
137
+ console.warn("[VideoDeliveryPlayer] Reactor SDK error:", err.message);
138
+ }
139
+ }
140
+ }
141
+ loadReactorSDK();
142
+ return () => {
143
+ mounted = false;
144
+ // Disconnect from Reactor on cleanup
145
+ if (reactor) {
146
+ reactor.disconnect().catch((err) => {
147
+ console.warn("[VideoDeliveryPlayer] Reactor disconnect error:", err);
148
+ });
149
+ }
150
+ };
151
+ }, [token, sessionId, modelName, mediaRef, onStatusChange, onError]);
152
+ if (loadError) {
153
+ return React.createElement("div", {
154
+ style: {
155
+ display: "flex",
156
+ alignItems: "center",
157
+ justifyContent: "center",
158
+ height: "100%",
159
+ background: "#000",
160
+ color: "#fff",
161
+ textAlign: "center",
162
+ padding: "20px",
163
+ },
164
+ }, `Reactor WebRTC: ${loadError.message}`);
165
+ }
166
+ if (!isLoaded) {
167
+ return React.createElement("div", {
168
+ style: {
169
+ display: "flex",
170
+ alignItems: "center",
171
+ justifyContent: "center",
172
+ height: "100%",
173
+ background: "#000",
174
+ color: "#fff",
175
+ },
176
+ }, "Loading Reactor WebRTC...");
177
+ }
178
+ // Video element for Reactor stream
179
+ // The Reactor SDK will attach the media stream to this element
180
+ return React.createElement("video", {
181
+ ref: mediaRef,
182
+ autoPlay: true,
183
+ playsInline: true,
184
+ muted: false,
185
+ style: { width: "100%", height: "100%", objectFit: "contain" },
186
+ });
187
+ }
188
+ export { useProgramOpening } from "./use-program-opening.js";
@@ -0,0 +1,3 @@
1
+ import { type ProgramOpeningPhase } from "./program-opening.js";
2
+ /** Observe a schedule and playback without replaying the opening on a mid-session join. */
3
+ export declare function useProgramOpening(live: boolean | null, startsAt?: string | null): ProgramOpeningPhase;
@@ -0,0 +1,15 @@
1
+ import { useEffect, useRef, useState } from "react";
2
+ import { ProgramOpeningSequence } from "./program-opening.js";
3
+ /** Observe a schedule and playback without replaying the opening on a mid-session join. */
4
+ export function useProgramOpening(live, startsAt) {
5
+ const [phase, setPhase] = useState("idle");
6
+ const sequence = useRef(null);
7
+ useEffect(() => {
8
+ const controller = new ProgramOpeningSequence({ onPhaseChange: setPhase });
9
+ sequence.current = controller;
10
+ return () => { controller.dispose(); sequence.current = null; };
11
+ }, []);
12
+ useEffect(() => { if (live !== null)
13
+ sequence.current?.update(live, startsAt); }, [live, startsAt]);
14
+ return phase;
15
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * WebRTC player for Reactor live streaming.
3
+ *
4
+ * This package provides React components for Reactor WebRTC playback.
5
+ * The WebRTCPlayer class is not implemented because Reactor's SDK is React-specific.
6
+ * Use ReactorWebRTCPlayer component in React applications instead.
7
+ */
8
+ export type WebRTCPlaybackState = "idle" | "connecting" | "connected" | "reconnecting" | "error" | "destroyed";
9
+ export interface WebRTCPlaybackObservation {
10
+ state: WebRTCPlaybackState;
11
+ attempt: number;
12
+ error?: unknown;
13
+ }
14
+ export interface ReactorSignalingConfig {
15
+ /** JWT token for authentication */
16
+ token: string;
17
+ /** Session ID to connect to (from backend) */
18
+ sessionId: string;
19
+ /** Model name being used */
20
+ modelName: string;
21
+ }
22
+ export interface WebRTCPlayerOptions {
23
+ media: HTMLVideoElement;
24
+ signaling: ReactorSignalingConfig;
25
+ maxReconnectAttempts?: number;
26
+ reconnectDelayMs?: number;
27
+ iceServers?: RTCIceServer[];
28
+ onObservation?: (observation: WebRTCPlaybackObservation) => void;
29
+ }
30
+ /**
31
+ * WebRTC player class - NOT IMPLEMENTED.
32
+ *
33
+ * Reactor's SDK (@reactor-team/js-sdk) is React-specific and requires React context.
34
+ * Use ReactorWebRTCPlayer component from ./react.tsx instead.
35
+ */
36
+ export declare class WebRTCPlayer {
37
+ private readonly options;
38
+ constructor(options: WebRTCPlayerOptions);
39
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * WebRTC player for Reactor live streaming.
3
+ *
4
+ * This package provides React components for Reactor WebRTC playback.
5
+ * The WebRTCPlayer class is not implemented because Reactor's SDK is React-specific.
6
+ * Use ReactorWebRTCPlayer component in React applications instead.
7
+ */
8
+ /**
9
+ * WebRTC player class - NOT IMPLEMENTED.
10
+ *
11
+ * Reactor's SDK (@reactor-team/js-sdk) is React-specific and requires React context.
12
+ * Use ReactorWebRTCPlayer component from ./react.tsx instead.
13
+ */
14
+ export class WebRTCPlayer {
15
+ options;
16
+ constructor(options) {
17
+ this.options = options;
18
+ throw new Error("WebRTCPlayer class is not implemented. " +
19
+ "Reactor's SDK is React-specific. " +
20
+ "Use ReactorWebRTCPlayer component from './react.tsx' instead. " +
21
+ "This component wraps @reactor-team/js-sdk for React applications.");
22
+ }
23
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@portalshq/capability-video-delivery",
3
- "version": "0.1.10",
3
+ "version": "0.3.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/portalshq/portals-cloud.git",
@@ -38,11 +38,15 @@
38
38
  },
39
39
  "peerDependencies": {
40
40
  "hls.js": ">=1.5.0",
41
- "react": ">=18.0.0"
41
+ "react": ">=18.0.0",
42
+ "@reactor-team/js-sdk": ">=1.0.0"
42
43
  },
43
44
  "peerDependenciesMeta": {
44
45
  "hls.js": {
45
46
  "optional": true
47
+ },
48
+ "@reactor-team/js-sdk": {
49
+ "optional": true
46
50
  }
47
51
  },
48
52
  "devDependencies": {