@furious.luke/argus-js 0.3.1 → 0.4.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
@@ -10,7 +10,8 @@ Argus is a distributed video ingestion service. A stream flows through three par
10
10
 
11
11
  - **Your server** mints a short-lived **join token** using its secret API key (see the [Go client](https://github.com/furious-luke/go-projects/tree/main/argus/client), published as the `github.com/furious-luke/argus-go` module, or the control-plane HTTP API).
12
12
  - **The browser** (this library) uses that token to publish video to the nearest Argus media server. It never sees the API key.
13
- - **Your server** later fetches frames from the stream on demand.
13
+ - **The browser** relays the winning gateway URL and its region-scoped read token
14
+ back to your server, which uses that pair for frame reads and notifications.
14
15
 
15
16
  This library is only the browser publishing half. It deliberately does **not** talk to the control plane or mint tokens — that requires your secret API key and must stay server-side.
16
17
 
@@ -21,6 +22,7 @@ This library is only the browser publishing half. It deliberately does **not** t
21
22
  │ argus-js │ 2. token + gateway_urls └────────────┘
22
23
  │ │
23
24
  │ │ 3. publish WebRTC video ────────────────▶ Argus media server
25
+ │ │ 4. frameReadToken + selectedGatewayURL ─▶ your server
24
26
  └──────────┘
25
27
  ```
26
28
 
@@ -42,7 +44,19 @@ const publisher = new Publisher({
42
44
  gatewayURLs: join.gateway_urls,
43
45
  token: join.token,
44
46
  callbacks: {
45
- onConnected: () => console.log("streaming live"),
47
+ onConnected: async () => {
48
+ console.log("streaming live");
49
+ // Relay these as a pair; the read token is valid in the selected region.
50
+ await fetch("/api/stream-credentials", {
51
+ method: "POST",
52
+ headers: { "Content-Type": "application/json" },
53
+ body: JSON.stringify({
54
+ stream_id: join.stream_id,
55
+ read_token: publisher.frameReadToken,
56
+ gateway_url: publisher.selectedGatewayURL,
57
+ }),
58
+ });
59
+ },
46
60
  onConnectionStateChange: (state) => console.log("state:", state),
47
61
  onRecoveryStateChange: (event) => console.log("media recovery:", event),
48
62
  // Show a button or prompt. From its click handler, call captureScreen()
@@ -55,9 +69,6 @@ const publisher = new Publisher({
55
69
  // captureCamera() applies sensible capture defaults; any MediaStream works too.
56
70
  const stream = await captureCamera();
57
71
  await publisher.start(stream);
58
-
59
- // After start() resolves, this token lets your server fetch frames for the stream.
60
- console.log("read token:", publisher.frameReadToken);
61
72
  ```
62
73
 
63
74
  ### Capture helpers
@@ -108,6 +119,7 @@ publisher.stop(); // stops all tracks and tears down the peer connection
108
119
  | `replaceStream(stream)` | Replaces the published tracks and renegotiates in place. |
109
120
  | `stop()` | Stops all local tracks and closes the peer connection. |
110
121
  | `frameReadToken` | The one-hour read token from the gateway's `ready` message, or `null` before connecting. The publisher uses it internally to resume signaling; hand it to your server to fetch frames. |
122
+ | `selectedGatewayURL` | The signaling URL that won the regional race, or `null` before connecting. Relay it with `frameReadToken` so your server uses the same region for frame reads and notifications. |
111
123
  | `peerConnection` | The underlying `RTCPeerConnection`, or `null` if not started. |
112
124
  | `isConnected` | `true` when the peer connection state is `"connected"`. |
113
125
 
package/dist/index.cjs CHANGED
@@ -87,7 +87,7 @@ var Publisher = class {
87
87
  pendingRemoteCandidates = [];
88
88
  localStream = null;
89
89
  readToken = null;
90
- selectedGatewayURL = null;
90
+ gatewayURL = null;
91
91
  stopped = true;
92
92
  reconnecting = false;
93
93
  reconnectGeneration = 0;
@@ -104,6 +104,14 @@ var Publisher = class {
104
104
  get frameReadToken() {
105
105
  return this.readToken;
106
106
  }
107
+ /**
108
+ * The signaling gateway URL that won the initial race, or null before start.
109
+ * Relay this with frameReadToken so the application server can reach the same
110
+ * region for frame reads and change-notification subscriptions.
111
+ */
112
+ get selectedGatewayURL() {
113
+ return this.gatewayURL;
114
+ }
107
115
  /**
108
116
  * Starts the publisher: races all gateways to find the fastest, completes
109
117
  * the two-phase handshake, creates the peer connection, and sends the SDP
@@ -116,7 +124,7 @@ var Publisher = class {
116
124
  this.localStream = stream;
117
125
  this.watchStreamTracks(stream);
118
126
  const { ws, readyInfo, gatewayURL } = await this.raceGateways();
119
- this.selectedGatewayURL = gatewayURL;
127
+ this.gatewayURL = gatewayURL;
120
128
  if (readyInfo.read_token) {
121
129
  this.readToken = readyInfo.read_token;
122
130
  }
@@ -193,7 +201,7 @@ var Publisher = class {
193
201
  this.hasAnswer = false;
194
202
  this.pendingRemoteCandidates = [];
195
203
  this.readToken = null;
196
- this.selectedGatewayURL = null;
204
+ this.gatewayURL = null;
197
205
  }
198
206
  /** Returns the current RTCPeerConnection, or null if not started. */
199
207
  get peerConnection() {
@@ -273,7 +281,7 @@ var Publisher = class {
273
281
  }
274
282
  async resumeSignaling() {
275
283
  if (this.reconnecting || this.stopped) return;
276
- if (!this.selectedGatewayURL || !this.readToken) {
284
+ if (!this.gatewayURL || !this.readToken) {
277
285
  this.terminateWithError(new Error("signaling closed and cannot be resumed"));
278
286
  return;
279
287
  }
@@ -312,7 +320,7 @@ var Publisher = class {
312
320
  }
313
321
  openResumeSocket(timeoutMs) {
314
322
  return new Promise((resolve, reject) => {
315
- const u = new URL(this.selectedGatewayURL);
323
+ const u = new URL(this.gatewayURL);
316
324
  u.searchParams.set("token", this.readToken);
317
325
  const ws = new WebSocket(u.toString());
318
326
  this.resumeSocket = ws;
@@ -362,7 +370,7 @@ var Publisher = class {
362
370
  this.hasAnswer = false;
363
371
  this.pendingRemoteCandidates = [];
364
372
  this.readToken = null;
365
- this.selectedGatewayURL = null;
373
+ this.gatewayURL = null;
366
374
  this.opts.callbacks?.onError?.(err);
367
375
  }
368
376
  handleSignal(msg) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/signaling.ts","../src/publisher.ts","../src/capture.ts"],"sourcesContent":["export { Publisher } from \"./publisher\";\nexport type {\n SignalMessage,\n PublisherCallbacks,\n PublisherOptions,\n GatewayReadyInfo,\n PublisherRecoveryEvent,\n PublisherRecoveryState,\n PublisherRecoveryAction,\n PublisherRecoveryFailureReason,\n} from \"./types\";\nexport { captureCamera, captureScreen } from \"./capture\";\nexport type {\n CaptureCameraOptions,\n CaptureScreenOptions,\n} from \"./capture\";\n","import type { SignalMessage } from \"./types\";\n\n/**\n * Wraps an open WebSocket to the Argus gateway and handles the JSON message\n * envelope: incoming text frames are parsed into {@link SignalMessage}s and\n * outgoing messages are serialised.\n *\n * This is an internal helper. The {@link Publisher} opens the socket itself\n * (racing all candidate gateways) and hands the winner here, so this class only\n * ever adopts an already-open socket rather than dialing one.\n *\n * @internal\n */\nexport class SignalingChannel {\n private ws: WebSocket;\n\n /** Fired for every incoming JSON message. */\n onMessage: ((msg: SignalMessage) => void) | null = null;\n /** Fired when the underlying WebSocket closes. */\n onClose: (() => void) | null = null;\n /** Fired when an error occurs on the WebSocket. */\n onError: ((err: Error) => void) | null = null;\n\n private constructor(ws: WebSocket) {\n this.ws = ws;\n }\n\n /**\n * Adopts an already-open WebSocket (e.g. the winner of a gateway race),\n * routing its events through the channel's callbacks. Any handlers previously\n * attached to the socket are replaced.\n */\n static wrap(ws: WebSocket): SignalingChannel {\n const ch = new SignalingChannel(ws);\n ws.onmessage = (ev: MessageEvent) => {\n const msg = parseSignal(ev.data);\n if (msg) ch.onMessage?.(msg);\n };\n ws.onerror = () => ch.onError?.(new Error(\"WebSocket error\"));\n ws.onclose = () => ch.onClose?.();\n return ch;\n }\n\n /** Sends a JSON message if the socket is open; a no-op otherwise. */\n send(msg: SignalMessage): void {\n if (this.ws.readyState === WebSocket.OPEN) {\n this.ws.send(JSON.stringify(msg));\n }\n }\n\n /** Closes the underlying WebSocket. */\n close(): void {\n this.ws.close();\n }\n}\n\n/** Parses a WebSocket text frame into a SignalMessage, or null if malformed. */\nfunction parseSignal(data: unknown): SignalMessage | null {\n try {\n return JSON.parse(data as string) as SignalMessage;\n } catch {\n return null;\n }\n}\n","import { SignalingChannel } from \"./signaling\";\nimport type {\n GatewayReadyInfo,\n PublisherOptions,\n PublisherRecoveryAction,\n PublisherRecoveryEvent,\n SignalMessage,\n} from \"./types\";\n\nconst defaultSignalingReconnectTimeoutMs = 20_000;\nconst signalingResumeAttemptTimeoutMs = 3_000;\nconst signalingResumeMaxBackoffMs = 3_000;\nconst senderRestartPauseMs = 100;\nconst senderRecoveryWaitMs = 4_000;\nconst iceRecoveryWaitMs = 8_000;\n\n/**\n * Publisher streams a browser {@link MediaStream} to an Argus media server over\n * WebRTC. Given the `gateway_urls` and `token` from a join-token response, it\n * races the candidate gateways to the fastest one, completes the two-phase\n * signaling handshake, and manages the peer connection — offer/answer exchange,\n * ICE candidate trickling, and track (re)negotiation.\n *\n * After {@link Publisher.start} resolves, {@link Publisher.frameReadToken} holds\n * the token your application server needs to fetch frames for this stream.\n *\n * @example Publish the default camera:\n * ```ts\n * const pub = new Publisher({\n * gatewayURLs: joinResp.gateway_urls,\n * token: joinResp.token,\n * callbacks: { onConnected: () => console.log(\"live!\") },\n * });\n *\n * const stream = await navigator.mediaDevices.getUserMedia({ video: true });\n * await pub.start(stream);\n * ```\n */\nexport class Publisher {\n private opts: PublisherOptions;\n private sig: SignalingChannel | null = null;\n private pc: RTCPeerConnection | null = null;\n private hasAnswer = false;\n private pendingRemoteCandidates: RTCIceCandidateInit[] = [];\n private localStream: MediaStream | null = null;\n private readToken: string | null = null;\n private selectedGatewayURL: string | null = null;\n private stopped = true;\n private reconnecting = false;\n private reconnectGeneration = 0;\n private resumeSocket: WebSocket | null = null;\n private recoveryGeneration = 0;\n private recoveringMedia = false;\n private recoveryRequired = false;\n private recoveryAction: PublisherRecoveryAction | null = null;\n private trackEndHandlers = new Map<MediaStreamTrack, EventListener>();\n\n constructor(opts: PublisherOptions) {\n this.opts = opts;\n }\n\n /** The read token used for frame fetches and signaling resume in the selected region. */\n get frameReadToken(): string | null { return this.readToken; }\n\n /**\n * Starts the publisher: races all gateways to find the fastest, completes\n * the two-phase handshake, creates the peer connection, and sends the SDP\n * offer. Resolves when the offer has been sent (not when ICE completes —\n * use onConnected for that).\n */\n async start(stream: MediaStream): Promise<void> {\n this.stopped = false;\n this.recoveryRequired = false;\n this.localStream = stream;\n this.watchStreamTracks(stream);\n\n // Race all gateways; returns winning WebSocket + TURN/read-token info\n const { ws, readyInfo, gatewayURL } = await this.raceGateways();\n this.selectedGatewayURL = gatewayURL;\n\n // Store read token for caller\n if (readyInfo.read_token) {\n this.readToken = readyInfo.read_token;\n }\n\n // Build ICE servers: extra servers from opts + TURN from gateway. The\n // gateway supplies multi-transport turn_urls (UDP + TCP) so relay can fall\n // back to TCP on UDP-blocking networks. A single credential is valid for\n // every transport.\n const iceServers: RTCIceServer[] = [...(this.opts.iceServers ?? [])];\n if (readyInfo.turn_urls && readyInfo.turn_urls.length > 0) {\n iceServers.push({\n urls: readyInfo.turn_urls,\n username: readyInfo.turn_username,\n credential: readyInfo.turn_credential,\n });\n }\n\n this.pc = new RTCPeerConnection({ iceServers });\n\n this.pc.onicecandidate = (ev) => {\n if (!ev.candidate || !this.sig) return;\n const c = ev.candidate;\n this.sig.send({\n type: \"ice_candidate\",\n candidate: c.candidate,\n sdp_mid: c.sdpMid ?? undefined,\n sdp_mline_index: c.sdpMLineIndex ?? undefined,\n username_fragment: c.usernameFragment ?? undefined,\n });\n };\n\n this.pc.onconnectionstatechange = () => {\n const state = this.pc?.connectionState;\n if (state) this.opts.callbacks?.onConnectionStateChange?.(state);\n if (state === \"connected\") this.opts.callbacks?.onConnected?.();\n };\n\n for (const track of stream.getTracks()) {\n this.pc.addTrack(track, stream);\n }\n\n const offer = await this.pc.createOffer();\n await this.pc.setLocalDescription(offer);\n await this.gatherComplete();\n\n // Wrap winning WebSocket in SignalingChannel\n const signaling = this.installSignaling(ws);\n\n const local = this.pc.localDescription;\n if (!local) throw new Error(\"local description missing after gather\");\n signaling.send({ type: \"offer\", sdp: local.sdp, sdp_type: \"offer\" });\n }\n\n /** Replaces the currently published stream with a new one. */\n async replaceStream(stream: MediaStream): Promise<void> {\n if (!this.pc) throw new Error(\"publisher not started\");\n\n this.cancelMediaRecovery();\n this.recoveryRequired = false;\n this.unwatchStreamTracks();\n\n // Remove old tracks.\n const senders = this.pc.getSenders();\n for (const sender of senders) {\n if (sender.track) {\n this.pc.removeTrack(sender);\n }\n }\n\n // Add new tracks.\n for (const track of stream.getTracks()) {\n this.pc.addTrack(track, stream);\n }\n this.localStream = stream;\n this.watchStreamTracks(stream);\n\n await this.renegotiate(false);\n }\n\n /** Stops publishing and tears down the peer connection. */\n stop(): void {\n this.stopped = true;\n this.cancelMediaRecovery();\n this.reconnectGeneration++;\n this.reconnecting = false;\n this.resumeSocket?.close();\n this.resumeSocket = null;\n this.sig?.close();\n this.sig = null;\n\n this.unwatchStreamTracks();\n this.localStream?.getTracks().forEach((t) => t.stop());\n this.localStream = null;\n\n this.pc?.close();\n this.pc = null;\n this.hasAnswer = false;\n this.pendingRemoteCandidates = [];\n this.readToken = null;\n this.selectedGatewayURL = null;\n }\n\n /** Returns the current RTCPeerConnection, or null if not started. */\n get peerConnection(): RTCPeerConnection | null {\n return this.pc;\n }\n\n /** Returns true if the peer connection is in the \"connected\" state. */\n get isConnected(): boolean {\n return this.pc?.connectionState === \"connected\";\n }\n\n // -------------------------------------------------------------------------\n // Private helpers\n // -------------------------------------------------------------------------\n\n private raceGateways(): Promise<{ ws: WebSocket; readyInfo: GatewayReadyInfo; gatewayURL: string }> {\n return new Promise((resolve, reject) => {\n const { gatewayURLs, token } = this.opts;\n if (gatewayURLs.length === 0) {\n reject(new Error(\"no gateway URLs provided\"));\n return;\n }\n\n const sockets: WebSocket[] = [];\n let settled = false;\n\n const closeAll = (except?: WebSocket) => {\n for (const s of sockets) {\n if (s !== except) {\n s.onmessage = null;\n s.onerror = null;\n s.onclose = null;\n s.close();\n }\n }\n };\n\n const checkAllFailed = () => {\n if (settled) return;\n if (sockets.every(s => s.readyState === WebSocket.CLOSED || s.readyState === WebSocket.CLOSING)) {\n settled = true;\n reject(new Error(\"all gateways failed to connect\"));\n }\n };\n\n for (const gatewayURL of gatewayURLs) {\n const u = new URL(gatewayURL);\n u.searchParams.set(\"token\", token);\n const ws = new WebSocket(u.toString());\n sockets.push(ws);\n\n let accepted = false;\n\n ws.onmessage = (ev: MessageEvent) => {\n if (settled) return;\n try {\n const msg = JSON.parse(ev.data as string);\n if (!accepted && msg.type === \"accepted\") {\n accepted = true;\n ws.send(JSON.stringify({ type: \"proceed\" }));\n } else if (accepted && msg.type === \"ready\") {\n settled = true;\n closeAll(ws);\n resolve({ ws, readyInfo: msg as GatewayReadyInfo, gatewayURL });\n }\n } catch {\n /* ignore malformed */\n }\n };\n\n ws.onerror = () => checkAllFailed();\n ws.onclose = () => checkAllFailed();\n }\n });\n }\n\n private installSignaling(ws: WebSocket): SignalingChannel {\n const channel = SignalingChannel.wrap(ws);\n this.sig = channel;\n channel.onMessage = (msg) => this.handleSignal(msg);\n channel.onClose = () => {\n if (this.sig !== channel || this.stopped) return;\n this.sig = null;\n void this.resumeSignaling();\n };\n // Browsers normally follow an error event with close. Recovery begins from\n // close so a single transport failure cannot start two retry loops.\n channel.onError = () => {};\n return channel;\n }\n\n private async resumeSignaling(): Promise<void> {\n if (this.reconnecting || this.stopped) return;\n if (!this.selectedGatewayURL || !this.readToken) {\n this.terminateWithError(new Error(\"signaling closed and cannot be resumed\"));\n return;\n }\n\n this.reconnecting = true;\n const generation = ++this.reconnectGeneration;\n const timeout = this.opts.signalingReconnectTimeoutMs ?? defaultSignalingReconnectTimeoutMs;\n const deadline = Date.now() + Math.max(0, timeout);\n let backoffMs = 0;\n\n while (!this.stopped && generation === this.reconnectGeneration && Date.now() <= deadline) {\n if (backoffMs > 0) {\n const waitMs = Math.min(backoffMs, Math.max(0, deadline - Date.now()));\n if (waitMs === 0) break;\n await this.wait(waitMs);\n if (this.stopped || generation !== this.reconnectGeneration) return;\n }\n\n const remaining = deadline - Date.now();\n if (remaining < 0) break;\n try {\n const ws = await this.openResumeSocket(Math.min(signalingResumeAttemptTimeoutMs, Math.max(1, remaining)));\n if (this.stopped || generation !== this.reconnectGeneration) {\n ws.close();\n return;\n }\n this.resumeSocket = null;\n this.reconnecting = false;\n this.installSignaling(ws);\n return;\n } catch {\n backoffMs = backoffMs === 0 ? 250 : Math.min(backoffMs * 2, signalingResumeMaxBackoffMs);\n }\n }\n\n if (!this.stopped && generation === this.reconnectGeneration) {\n this.reconnecting = false;\n this.terminateWithError(new Error(\"unable to resume signaling with the selected gateway\"));\n }\n }\n\n private openResumeSocket(timeoutMs: number): Promise<WebSocket> {\n return new Promise((resolve, reject) => {\n const u = new URL(this.selectedGatewayURL!);\n u.searchParams.set(\"token\", this.readToken!);\n const ws = new WebSocket(u.toString());\n this.resumeSocket = ws;\n let settled = false;\n const timer = setTimeout(() => fail(), timeoutMs);\n\n const fail = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n if (this.resumeSocket === ws) this.resumeSocket = null;\n ws.onmessage = null;\n ws.onerror = null;\n ws.onclose = null;\n ws.close();\n reject(new Error(\"signaling resume attempt failed\"));\n };\n\n ws.onmessage = (ev: MessageEvent) => {\n try {\n const msg = JSON.parse(ev.data as string);\n if (msg.type !== \"resumed\" || settled) return;\n settled = true;\n clearTimeout(timer);\n resolve(ws);\n } catch {\n // Ignore malformed messages while waiting for the resume acknowledgement.\n }\n };\n ws.onerror = fail;\n ws.onclose = fail;\n });\n }\n\n private wait(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n private terminateWithError(err: Error): void {\n this.stopped = true;\n this.cancelMediaRecovery();\n this.reconnectGeneration++;\n this.resumeSocket?.close();\n this.resumeSocket = null;\n this.sig?.close();\n this.sig = null;\n this.pc?.close();\n this.pc = null;\n this.unwatchStreamTracks();\n this.localStream?.getTracks().forEach((track) => track.stop());\n this.localStream = null;\n this.hasAnswer = false;\n this.pendingRemoteCandidates = [];\n this.readToken = null;\n this.selectedGatewayURL = null;\n this.opts.callbacks?.onError?.(err);\n }\n\n private handleSignal(msg: SignalMessage): void {\n switch (msg.type) {\n case \"answer\": {\n if (!this.pc) return;\n this.pc\n .setRemoteDescription(\n new RTCSessionDescription({ type: \"answer\", sdp: msg.sdp }),\n )\n .then(() => {\n this.hasAnswer = true;\n // Flush any ICE candidates that arrived before the answer.\n for (const init of this.pendingRemoteCandidates) {\n this.pc?.addIceCandidate(init).catch(() => {\n /* ignore stale candidates */\n });\n }\n this.pendingRemoteCandidates = [];\n })\n .catch((err) => {\n this.opts.callbacks?.onError?.(\n new Error(`failed to set remote description: ${err}`),\n );\n });\n break;\n }\n\n case \"ice_candidate\": {\n if (!this.pc) return;\n const init: RTCIceCandidateInit = {\n candidate: msg.candidate,\n sdpMid: msg.sdp_mid ?? null,\n sdpMLineIndex: msg.sdp_mline_index ?? null,\n usernameFragment: msg.username_fragment ?? null,\n };\n if (this.hasAnswer) {\n this.pc.addIceCandidate(init).catch(() => {\n /* ignore stale candidates */\n });\n } else {\n this.pendingRemoteCandidates.push(init);\n }\n break;\n }\n\n case \"connection_state\": {\n // The server echoes the peer connection state; the onconnectionstatechange\n // handler above already covers this, but callers can also react via\n // onConnectionStateChange.\n break;\n }\n\n case \"media_stall\":\n case \"media_track_ended\": {\n void this.beginMediaRecovery(msg.track);\n break;\n }\n\n case \"media_resumed\": {\n this.completeMediaRecovery(msg.track);\n break;\n }\n\n case \"error\": {\n this.opts.callbacks?.onError?.(new Error(msg.error));\n break;\n }\n\n case \"resumed\":\n break;\n }\n }\n\n private async beginMediaRecovery(trackType: string): Promise<void> {\n if (this.stopped || this.recoveringMedia || this.recoveryRequired) return;\n\n const tracks = this.localStream?.getVideoTracks() ?? [];\n const liveTracks = tracks.filter((track) => track.readyState !== \"ended\");\n if (liveTracks.length === 0) {\n this.failMediaRecovery(trackType, \"capture_ended\");\n return;\n }\n\n this.recoveringMedia = true;\n const generation = ++this.recoveryGeneration;\n this.recoveryAction = \"sender_restart\";\n this.emitRecoveryTransition({ state: \"recovering\", track: trackType, action: \"sender_restart\" });\n this.sendRecoveryDiagnostic(\"recovery_started\", trackType, \"sender_restart\");\n\n await this.restartSenders(liveTracks, generation);\n if (!this.isCurrentRecovery(generation)) return;\n\n await this.wait(senderRecoveryWaitMs);\n if (!this.isCurrentRecovery(generation)) return;\n\n this.recoveryAction = \"ice_restart\";\n this.emitRecoveryTransition({ state: \"recovering\", track: trackType, action: \"ice_restart\" });\n this.sendRecoveryDiagnostic(\"recovery_retry\", trackType, \"ice_restart\");\n try {\n await this.renegotiate(true);\n } catch {\n // The fixed recovery window below still gives signaling-resume a chance.\n // If media does not recover, the host receives onRecoveryRequired.\n }\n\n await this.wait(iceRecoveryWaitMs);\n if (!this.isCurrentRecovery(generation)) return;\n this.failMediaRecovery(trackType, \"automatic_recovery_failed\");\n }\n\n private async restartSenders(tracks: MediaStreamTrack[], generation: number): Promise<void> {\n const live = new Set(tracks);\n const senders = this.pc?.getSenders().filter(\n (sender) => sender.track && live.has(sender.track),\n ) ?? [];\n if (senders.length === 0) return;\n\n const originals = senders.map((sender) => ({ sender, track: sender.track! }));\n try {\n await Promise.all(originals.map(({ sender }) => sender.replaceTrack(null)));\n await this.wait(senderRestartPauseMs);\n if (!this.isCurrentRecovery(generation)) return;\n await Promise.all(originals.map(({ sender, track }) => sender.replaceTrack(track)));\n await this.renegotiate(false);\n } catch {\n // ICE restart is the second stage and may still recover a sender reset or\n // renegotiation failure, so do not fail the stream at this stage.\n }\n }\n\n private async renegotiate(iceRestart: boolean): Promise<void> {\n const pc = this.pc;\n const signaling = this.sig;\n if (!pc || !signaling) throw new Error(\"publisher signaling is unavailable\");\n\n if (iceRestart) pc.restartIce?.();\n const offer = await pc.createOffer(iceRestart ? { iceRestart: true } : undefined);\n await pc.setLocalDescription(offer);\n await this.gatherComplete();\n\n const local = pc.localDescription;\n if (!local) throw new Error(\"local description missing\");\n this.hasAnswer = false;\n this.pendingRemoteCandidates = [];\n signaling.send({ type: \"offer\", sdp: local.sdp, sdp_type: \"offer\" });\n }\n\n private completeMediaRecovery(trackType: string): void {\n if (!this.recoveringMedia) return;\n const action = this.recoveryAction ?? undefined;\n this.cancelMediaRecovery();\n this.emitRecoveryTransition({ state: \"recovered\", track: trackType, action });\n }\n\n private failMediaRecovery(\n trackType: string,\n reason: \"capture_ended\" | \"automatic_recovery_failed\",\n ): void {\n if (this.stopped || this.recoveryRequired) return;\n this.recoveryRequired = true;\n const action = this.recoveryAction ?? undefined;\n this.cancelMediaRecovery();\n const event: PublisherRecoveryEvent = { state: \"failed\", track: trackType, action, reason };\n this.emitRecoveryTransition(event);\n this.opts.callbacks?.onRecoveryRequired?.(event);\n this.sendRecoveryDiagnostic(\"recovery_failed\", trackType, action, reason);\n }\n\n private cancelMediaRecovery(): void {\n this.recoveryGeneration++;\n this.recoveringMedia = false;\n this.recoveryAction = null;\n }\n\n private isCurrentRecovery(generation: number): boolean {\n return !this.stopped && this.recoveringMedia && generation === this.recoveryGeneration;\n }\n\n private emitRecoveryTransition(event: PublisherRecoveryEvent): void {\n this.opts.callbacks?.onRecoveryStateChange?.(event);\n }\n\n private sendRecoveryDiagnostic(\n event: \"recovery_started\" | \"recovery_retry\" | \"recovery_failed\",\n track: string,\n action?: PublisherRecoveryAction,\n reason?: \"capture_ended\" | \"automatic_recovery_failed\",\n ): void {\n this.sig?.send({ type: \"recovery_event\", event, track, action, reason });\n }\n\n private watchStreamTracks(stream: MediaStream): void {\n for (const track of stream.getVideoTracks()) {\n const handler: EventListener = () => this.failMediaRecovery(\"screen\", \"capture_ended\");\n track.addEventListener(\"ended\", handler);\n this.trackEndHandlers.set(track, handler);\n }\n }\n\n private unwatchStreamTracks(): void {\n for (const [track, handler] of this.trackEndHandlers) {\n track.removeEventListener(\"ended\", handler);\n }\n this.trackEndHandlers.clear();\n }\n\n /** Waits for ICE gathering to reach the \"complete\" state. */\n private gatherComplete(): Promise<void> {\n return new Promise((resolve) => {\n const pc = this.pc;\n if (!pc) {\n resolve();\n return;\n }\n if (pc.iceGatheringState === \"complete\") {\n resolve();\n return;\n }\n const handler = () => {\n if (pc.iceGatheringState === \"complete\") {\n pc.removeEventListener(\"icegatheringstatechange\", handler);\n resolve();\n }\n };\n pc.addEventListener(\"icegatheringstatechange\", handler);\n });\n }\n}\n","/**\n * Options for {@link captureCamera}.\n *\n * These are merged shallowly over the library defaults: any field you provide\n * replaces the default for that field entirely (e.g. passing `video` overrides\n * the default video constraints rather than merging into them). Omit a field to\n * keep its default.\n */\nexport interface CaptureCameraOptions {\n /**\n * Video constraints, or `true`/`false`. Defaults to a modest resolution and\n * frame rate (see {@link captureCamera}). Set `false` to disable video.\n */\n video?: MediaTrackConstraints | boolean;\n /**\n * Audio constraints, or `true`/`false`. Defaults to `false` — Argus is a\n * video-frame streaming system, so audio is off unless you ask for it.\n */\n audio?: MediaTrackConstraints | boolean;\n /**\n * The `MediaDevices` instance to capture from. Defaults to the global\n * `navigator.mediaDevices`. Pass another window's `navigator.mediaDevices`\n * (e.g. a Document Picture-in-Picture window's) so the browser's permission\n * prompt and transient-activation check are anchored to that window rather\n * than the one holding the global `navigator`.\n */\n mediaDevices?: MediaDevices;\n}\n\n/**\n * Options for {@link captureScreen}.\n *\n * These are merged shallowly over the library defaults: any field you provide\n * replaces the default for that field entirely. Omit a field to keep its\n * default.\n */\nexport interface CaptureScreenOptions {\n /**\n * Video constraints, or `true`. Defaults to a capped width and a low frame\n * rate (see {@link captureScreen}).\n */\n video?: MediaTrackConstraints | boolean;\n /**\n * Audio constraints, or `true`/`false`. Defaults to `false` — screen shares\n * rarely need audio for a video-frame streaming system.\n */\n audio?: MediaTrackConstraints | boolean;\n /**\n * The `MediaDevices` instance to capture from. Defaults to the global\n * `navigator.mediaDevices`. Pass another window's `navigator.mediaDevices`\n * (e.g. a Document Picture-in-Picture window's) so the screen picker and its\n * transient-activation check are anchored to that window rather than the one\n * holding the global `navigator`.\n */\n mediaDevices?: MediaDevices;\n}\n\n/**\n * Captures the user's camera via `navigator.mediaDevices.getUserMedia`,\n * applying sensible defaults for a video-frame streaming system.\n *\n * Defaults:\n * - `video`: `{ width: { ideal: 1280 }, height: { ideal: 720 }, frameRate: { ideal: 30 } }`\n * — a modest resolution that keeps upload bandwidth reasonable. Cameras are\n * rarely the 4k bandwidth problem that screen capture is, so this is an\n * `ideal` (a hint) rather than a hard cap.\n * - `audio`: `false` — this is a video-frame streaming system.\n *\n * Any option you pass replaces the corresponding default outright (shallow\n * merge), so pass a full `video` constraints object if you want to tweak it.\n *\n * @example\n * ```ts\n * const stream = await captureCamera();\n * await publisher.start(stream);\n * ```\n *\n * @example Front camera with audio:\n * ```ts\n * const stream = await captureCamera({\n * video: { facingMode: \"user\" },\n * audio: true,\n * });\n * ```\n */\nexport async function captureCamera(\n opts: CaptureCameraOptions = {},\n): Promise<MediaStream> {\n const constraints: MediaStreamConstraints = {\n video: opts.video ?? {\n width: { ideal: 1280 },\n height: { ideal: 720 },\n frameRate: { ideal: 30 },\n },\n audio: opts.audio ?? false,\n };\n const mediaDevices = opts.mediaDevices ?? navigator.mediaDevices;\n return mediaDevices.getUserMedia(constraints);\n}\n\n/**\n * Captures a screen / window / tab via\n * `navigator.mediaDevices.getDisplayMedia`, applying sensible defaults tuned to\n * avoid the HiDPI/Retina bandwidth trap.\n *\n * Defaults:\n * - `video`: `{ width: { max: 1920 }, frameRate: { ideal: 5, max: 10 } }`.\n * The `width` is a **`max`, not an `ideal`**: on a 2x-Retina display the\n * browser would otherwise capture at native resolution (often 3456px+ /\n * effectively 4k), wasting upload bandwidth and downstream decode cost for no\n * visible benefit. Capping the max roughly halves a 2x-Retina share while\n * leaving smaller displays untouched. Screen content is mostly static, so the\n * low frame rate saves further bandwidth.\n * - `audio`: `false`.\n *\n * IMPORTANT — do NOT add `resizeMode: \"none\"` here. That value forbids the\n * browser from downscaling the source, which turns the `width: { max: 1920 }`\n * cap into a no-op on exactly the Retina displays it targets. By omitting\n * `resizeMode` we let the user agent scale to satisfy the constraint (its\n * default behaviour), which is the entire point of this helper. It is tempting\n * to add `resizeMode: \"none\"` back for \"sharpness\" — don't.\n *\n * Any option you pass replaces the corresponding default outright (shallow\n * merge), so pass a full `video` constraints object if you want to tweak it.\n *\n * @example\n * ```ts\n * const stream = await captureScreen();\n * await publisher.start(stream);\n * ```\n */\nexport async function captureScreen(\n opts: CaptureScreenOptions = {},\n): Promise<MediaStream> {\n const constraints: MediaStreamConstraints = {\n video: opts.video ?? {\n width: { max: 1920 },\n frameRate: { ideal: 5, max: 10 },\n },\n audio: opts.audio ?? false,\n };\n const mediaDevices = opts.mediaDevices ?? navigator.mediaDevices;\n return mediaDevices.getDisplayMedia(constraints);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaO,IAAM,mBAAN,MAAM,kBAAiB;AAAA,EACpB;AAAA;AAAA,EAGR,YAAmD;AAAA;AAAA,EAEnD,UAA+B;AAAA;AAAA,EAE/B,UAAyC;AAAA,EAEjC,YAAY,IAAe;AACjC,SAAK,KAAK;AAAA,EACZ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,OAAO,KAAK,IAAiC;AAC3C,UAAM,KAAK,IAAI,kBAAiB,EAAE;AAClC,OAAG,YAAY,CAAC,OAAqB;AACnC,YAAM,MAAM,YAAY,GAAG,IAAI;AAC/B,UAAI,IAAK,IAAG,YAAY,GAAG;AAAA,IAC7B;AACA,OAAG,UAAU,MAAM,GAAG,UAAU,IAAI,MAAM,iBAAiB,CAAC;AAC5D,OAAG,UAAU,MAAM,GAAG,UAAU;AAChC,WAAO;AAAA,EACT;AAAA;AAAA,EAGA,KAAK,KAA0B;AAC7B,QAAI,KAAK,GAAG,eAAe,UAAU,MAAM;AACzC,WAAK,GAAG,KAAK,KAAK,UAAU,GAAG,CAAC;AAAA,IAClC;AAAA,EACF;AAAA;AAAA,EAGA,QAAc;AACZ,SAAK,GAAG,MAAM;AAAA,EAChB;AACF;AAGA,SAAS,YAAY,MAAqC;AACxD,MAAI;AACF,WAAO,KAAK,MAAM,IAAc;AAAA,EAClC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;;;ACtDA,IAAM,qCAAqC;AAC3C,IAAM,kCAAkC;AACxC,IAAM,8BAA8B;AACpC,IAAM,uBAAuB;AAC7B,IAAM,u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B,OAA6B,CAAC,GACR;AACtB,QAAM,cAAsC;AAAA,IAC1C,OAAO,KAAK,SAAS;AAAA,MACnB,OAAO,EAAE,OAAO,KAAK;AAAA,MACrB,QAAQ,EAAE,OAAO,IAAI;AAAA,MACrB,WAAW,EAAE,OAAO,GAAG;AAAA,IACzB;AAAA,IACA,OAAO,KAAK,SAAS;AAAA,EACvB;AACA,QAAM,eAAe,KAAK,gBAAgB,UAAU;AACpD,SAAO,aAAa,aAAa,WAAW;AAC9C;AAiCA,eAAsB,cACpB,OAA6B,CAAC,GACR;AACtB,QAAM,cAAsC;AAAA,IAC1C,OAAO,KAAK,SAAS;AAAA,MACnB,OAAO,EAAE,KAAK,KAAK;AAAA,MACnB,WAAW,EAAE,OAAO,GAAG,KAAK,GAAG;AAAA,IACjC;AAAA,IACA,OAAO,KAAK,SAAS;AAAA,EACvB;AACA,QAAM,eAAe,KAAK,gBAAgB,UAAU;AACpD,SAAO,aAAa,gBAAgB,WAAW;AACjD;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts","../src/signaling.ts","../src/publisher.ts","../src/capture.ts"],"sourcesContent":["export { Publisher } from \"./publisher\";\nexport type {\n SignalMessage,\n PublisherCallbacks,\n PublisherOptions,\n GatewayReadyInfo,\n PublisherRecoveryEvent,\n PublisherRecoveryState,\n PublisherRecoveryAction,\n PublisherRecoveryFailureReason,\n} from \"./types\";\nexport { captureCamera, captureScreen } from \"./capture\";\nexport type {\n CaptureCameraOptions,\n CaptureScreenOptions,\n} from \"./capture\";\n","import type { SignalMessage } from \"./types\";\n\n/**\n * Wraps an open WebSocket to the Argus gateway and handles the JSON message\n * envelope: incoming text frames are parsed into {@link SignalMessage}s and\n * outgoing messages are serialised.\n *\n * This is an internal helper. The {@link Publisher} opens the socket itself\n * (racing all candidate gateways) and hands the winner here, so this class only\n * ever adopts an already-open socket rather than dialing one.\n *\n * @internal\n */\nexport class SignalingChannel {\n private ws: WebSocket;\n\n /** Fired for every incoming JSON message. */\n onMessage: ((msg: SignalMessage) => void) | null = null;\n /** Fired when the underlying WebSocket closes. */\n onClose: (() => void) | null = null;\n /** Fired when an error occurs on the WebSocket. */\n onError: ((err: Error) => void) | null = null;\n\n private constructor(ws: WebSocket) {\n this.ws = ws;\n }\n\n /**\n * Adopts an already-open WebSocket (e.g. the winner of a gateway race),\n * routing its events through the channel's callbacks. Any handlers previously\n * attached to the socket are replaced.\n */\n static wrap(ws: WebSocket): SignalingChannel {\n const ch = new SignalingChannel(ws);\n ws.onmessage = (ev: MessageEvent) => {\n const msg = parseSignal(ev.data);\n if (msg) ch.onMessage?.(msg);\n };\n ws.onerror = () => ch.onError?.(new Error(\"WebSocket error\"));\n ws.onclose = () => ch.onClose?.();\n return ch;\n }\n\n /** Sends a JSON message if the socket is open; a no-op otherwise. */\n send(msg: SignalMessage): void {\n if (this.ws.readyState === WebSocket.OPEN) {\n this.ws.send(JSON.stringify(msg));\n }\n }\n\n /** Closes the underlying WebSocket. */\n close(): void {\n this.ws.close();\n }\n}\n\n/** Parses a WebSocket text frame into a SignalMessage, or null if malformed. */\nfunction parseSignal(data: unknown): SignalMessage | null {\n try {\n return JSON.parse(data as string) as SignalMessage;\n } catch {\n return null;\n }\n}\n","import { SignalingChannel } from \"./signaling\";\nimport type {\n GatewayReadyInfo,\n PublisherOptions,\n PublisherRecoveryAction,\n PublisherRecoveryEvent,\n SignalMessage,\n} from \"./types\";\n\nconst defaultSignalingReconnectTimeoutMs = 20_000;\nconst signalingResumeAttemptTimeoutMs = 3_000;\nconst signalingResumeMaxBackoffMs = 3_000;\nconst senderRestartPauseMs = 100;\nconst senderRecoveryWaitMs = 4_000;\nconst iceRecoveryWaitMs = 8_000;\n\n/**\n * Publisher streams a browser {@link MediaStream} to an Argus media server over\n * WebRTC. Given the `gateway_urls` and `token` from a join-token response, it\n * races the candidate gateways to the fastest one, completes the two-phase\n * signaling handshake, and manages the peer connection — offer/answer exchange,\n * ICE candidate trickling, and track (re)negotiation.\n *\n * After {@link Publisher.start} resolves, {@link Publisher.frameReadToken} holds\n * the token your application server needs to fetch frames for this stream.\n *\n * @example Publish the default camera:\n * ```ts\n * const pub = new Publisher({\n * gatewayURLs: joinResp.gateway_urls,\n * token: joinResp.token,\n * callbacks: { onConnected: () => console.log(\"live!\") },\n * });\n *\n * const stream = await navigator.mediaDevices.getUserMedia({ video: true });\n * await pub.start(stream);\n * ```\n */\nexport class Publisher {\n private opts: PublisherOptions;\n private sig: SignalingChannel | null = null;\n private pc: RTCPeerConnection | null = null;\n private hasAnswer = false;\n private pendingRemoteCandidates: RTCIceCandidateInit[] = [];\n private localStream: MediaStream | null = null;\n private readToken: string | null = null;\n private gatewayURL: string | null = null;\n private stopped = true;\n private reconnecting = false;\n private reconnectGeneration = 0;\n private resumeSocket: WebSocket | null = null;\n private recoveryGeneration = 0;\n private recoveringMedia = false;\n private recoveryRequired = false;\n private recoveryAction: PublisherRecoveryAction | null = null;\n private trackEndHandlers = new Map<MediaStreamTrack, EventListener>();\n\n constructor(opts: PublisherOptions) {\n this.opts = opts;\n }\n\n /** The read token used for frame fetches and signaling resume in the selected region. */\n get frameReadToken(): string | null { return this.readToken; }\n\n /**\n * The signaling gateway URL that won the initial race, or null before start.\n * Relay this with frameReadToken so the application server can reach the same\n * region for frame reads and change-notification subscriptions.\n */\n get selectedGatewayURL(): string | null { return this.gatewayURL; }\n\n /**\n * Starts the publisher: races all gateways to find the fastest, completes\n * the two-phase handshake, creates the peer connection, and sends the SDP\n * offer. Resolves when the offer has been sent (not when ICE completes —\n * use onConnected for that).\n */\n async start(stream: MediaStream): Promise<void> {\n this.stopped = false;\n this.recoveryRequired = false;\n this.localStream = stream;\n this.watchStreamTracks(stream);\n\n // Race all gateways; returns winning WebSocket + TURN/read-token info\n const { ws, readyInfo, gatewayURL } = await this.raceGateways();\n this.gatewayURL = gatewayURL;\n\n // Store read token for caller\n if (readyInfo.read_token) {\n this.readToken = readyInfo.read_token;\n }\n\n // Build ICE servers: extra servers from opts + TURN from gateway. The\n // gateway supplies multi-transport turn_urls (UDP + TCP) so relay can fall\n // back to TCP on UDP-blocking networks. A single credential is valid for\n // every transport.\n const iceServers: RTCIceServer[] = [...(this.opts.iceServers ?? [])];\n if (readyInfo.turn_urls && readyInfo.turn_urls.length > 0) {\n iceServers.push({\n urls: readyInfo.turn_urls,\n username: readyInfo.turn_username,\n credential: readyInfo.turn_credential,\n });\n }\n\n this.pc = new RTCPeerConnection({ iceServers });\n\n this.pc.onicecandidate = (ev) => {\n if (!ev.candidate || !this.sig) return;\n const c = ev.candidate;\n this.sig.send({\n type: \"ice_candidate\",\n candidate: c.candidate,\n sdp_mid: c.sdpMid ?? undefined,\n sdp_mline_index: c.sdpMLineIndex ?? undefined,\n username_fragment: c.usernameFragment ?? undefined,\n });\n };\n\n this.pc.onconnectionstatechange = () => {\n const state = this.pc?.connectionState;\n if (state) this.opts.callbacks?.onConnectionStateChange?.(state);\n if (state === \"connected\") this.opts.callbacks?.onConnected?.();\n };\n\n for (const track of stream.getTracks()) {\n this.pc.addTrack(track, stream);\n }\n\n const offer = await this.pc.createOffer();\n await this.pc.setLocalDescription(offer);\n await this.gatherComplete();\n\n // Wrap winning WebSocket in SignalingChannel\n const signaling = this.installSignaling(ws);\n\n const local = this.pc.localDescription;\n if (!local) throw new Error(\"local description missing after gather\");\n signaling.send({ type: \"offer\", sdp: local.sdp, sdp_type: \"offer\" });\n }\n\n /** Replaces the currently published stream with a new one. */\n async replaceStream(stream: MediaStream): Promise<void> {\n if (!this.pc) throw new Error(\"publisher not started\");\n\n this.cancelMediaRecovery();\n this.recoveryRequired = false;\n this.unwatchStreamTracks();\n\n // Remove old tracks.\n const senders = this.pc.getSenders();\n for (const sender of senders) {\n if (sender.track) {\n this.pc.removeTrack(sender);\n }\n }\n\n // Add new tracks.\n for (const track of stream.getTracks()) {\n this.pc.addTrack(track, stream);\n }\n this.localStream = stream;\n this.watchStreamTracks(stream);\n\n await this.renegotiate(false);\n }\n\n /** Stops publishing and tears down the peer connection. */\n stop(): void {\n this.stopped = true;\n this.cancelMediaRecovery();\n this.reconnectGeneration++;\n this.reconnecting = false;\n this.resumeSocket?.close();\n this.resumeSocket = null;\n this.sig?.close();\n this.sig = null;\n\n this.unwatchStreamTracks();\n this.localStream?.getTracks().forEach((t) => t.stop());\n this.localStream = null;\n\n this.pc?.close();\n this.pc = null;\n this.hasAnswer = false;\n this.pendingRemoteCandidates = [];\n this.readToken = null;\n this.gatewayURL = null;\n }\n\n /** Returns the current RTCPeerConnection, or null if not started. */\n get peerConnection(): RTCPeerConnection | null {\n return this.pc;\n }\n\n /** Returns true if the peer connection is in the \"connected\" state. */\n get isConnected(): boolean {\n return this.pc?.connectionState === \"connected\";\n }\n\n // -------------------------------------------------------------------------\n // Private helpers\n // -------------------------------------------------------------------------\n\n private raceGateways(): Promise<{ ws: WebSocket; readyInfo: GatewayReadyInfo; gatewayURL: string }> {\n return new Promise((resolve, reject) => {\n const { gatewayURLs, token } = this.opts;\n if (gatewayURLs.length === 0) {\n reject(new Error(\"no gateway URLs provided\"));\n return;\n }\n\n const sockets: WebSocket[] = [];\n let settled = false;\n\n const closeAll = (except?: WebSocket) => {\n for (const s of sockets) {\n if (s !== except) {\n s.onmessage = null;\n s.onerror = null;\n s.onclose = null;\n s.close();\n }\n }\n };\n\n const checkAllFailed = () => {\n if (settled) return;\n if (sockets.every(s => s.readyState === WebSocket.CLOSED || s.readyState === WebSocket.CLOSING)) {\n settled = true;\n reject(new Error(\"all gateways failed to connect\"));\n }\n };\n\n for (const gatewayURL of gatewayURLs) {\n const u = new URL(gatewayURL);\n u.searchParams.set(\"token\", token);\n const ws = new WebSocket(u.toString());\n sockets.push(ws);\n\n let accepted = false;\n\n ws.onmessage = (ev: MessageEvent) => {\n if (settled) return;\n try {\n const msg = JSON.parse(ev.data as string);\n if (!accepted && msg.type === \"accepted\") {\n accepted = true;\n ws.send(JSON.stringify({ type: \"proceed\" }));\n } else if (accepted && msg.type === \"ready\") {\n settled = true;\n closeAll(ws);\n resolve({ ws, readyInfo: msg as GatewayReadyInfo, gatewayURL });\n }\n } catch {\n /* ignore malformed */\n }\n };\n\n ws.onerror = () => checkAllFailed();\n ws.onclose = () => checkAllFailed();\n }\n });\n }\n\n private installSignaling(ws: WebSocket): SignalingChannel {\n const channel = SignalingChannel.wrap(ws);\n this.sig = channel;\n channel.onMessage = (msg) => this.handleSignal(msg);\n channel.onClose = () => {\n if (this.sig !== channel || this.stopped) return;\n this.sig = null;\n void this.resumeSignaling();\n };\n // Browsers normally follow an error event with close. Recovery begins from\n // close so a single transport failure cannot start two retry loops.\n channel.onError = () => {};\n return channel;\n }\n\n private async resumeSignaling(): Promise<void> {\n if (this.reconnecting || this.stopped) return;\n if (!this.gatewayURL || !this.readToken) {\n this.terminateWithError(new Error(\"signaling closed and cannot be resumed\"));\n return;\n }\n\n this.reconnecting = true;\n const generation = ++this.reconnectGeneration;\n const timeout = this.opts.signalingReconnectTimeoutMs ?? defaultSignalingReconnectTimeoutMs;\n const deadline = Date.now() + Math.max(0, timeout);\n let backoffMs = 0;\n\n while (!this.stopped && generation === this.reconnectGeneration && Date.now() <= deadline) {\n if (backoffMs > 0) {\n const waitMs = Math.min(backoffMs, Math.max(0, deadline - Date.now()));\n if (waitMs === 0) break;\n await this.wait(waitMs);\n if (this.stopped || generation !== this.reconnectGeneration) return;\n }\n\n const remaining = deadline - Date.now();\n if (remaining < 0) break;\n try {\n const ws = await this.openResumeSocket(Math.min(signalingResumeAttemptTimeoutMs, Math.max(1, remaining)));\n if (this.stopped || generation !== this.reconnectGeneration) {\n ws.close();\n return;\n }\n this.resumeSocket = null;\n this.reconnecting = false;\n this.installSignaling(ws);\n return;\n } catch {\n backoffMs = backoffMs === 0 ? 250 : Math.min(backoffMs * 2, signalingResumeMaxBackoffMs);\n }\n }\n\n if (!this.stopped && generation === this.reconnectGeneration) {\n this.reconnecting = false;\n this.terminateWithError(new Error(\"unable to resume signaling with the selected gateway\"));\n }\n }\n\n private openResumeSocket(timeoutMs: number): Promise<WebSocket> {\n return new Promise((resolve, reject) => {\n const u = new URL(this.gatewayURL!);\n u.searchParams.set(\"token\", this.readToken!);\n const ws = new WebSocket(u.toString());\n this.resumeSocket = ws;\n let settled = false;\n const timer = setTimeout(() => fail(), timeoutMs);\n\n const fail = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n if (this.resumeSocket === ws) this.resumeSocket = null;\n ws.onmessage = null;\n ws.onerror = null;\n ws.onclose = null;\n ws.close();\n reject(new Error(\"signaling resume attempt failed\"));\n };\n\n ws.onmessage = (ev: MessageEvent) => {\n try {\n const msg = JSON.parse(ev.data as string);\n if (msg.type !== \"resumed\" || settled) return;\n settled = true;\n clearTimeout(timer);\n resolve(ws);\n } catch {\n // Ignore malformed messages while waiting for the resume acknowledgement.\n }\n };\n ws.onerror = fail;\n ws.onclose = fail;\n });\n }\n\n private wait(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n private terminateWithError(err: Error): void {\n this.stopped = true;\n this.cancelMediaRecovery();\n this.reconnectGeneration++;\n this.resumeSocket?.close();\n this.resumeSocket = null;\n this.sig?.close();\n this.sig = null;\n this.pc?.close();\n this.pc = null;\n this.unwatchStreamTracks();\n this.localStream?.getTracks().forEach((track) => track.stop());\n this.localStream = null;\n this.hasAnswer = false;\n this.pendingRemoteCandidates = [];\n this.readToken = null;\n this.gatewayURL = null;\n this.opts.callbacks?.onError?.(err);\n }\n\n private handleSignal(msg: SignalMessage): void {\n switch (msg.type) {\n case \"answer\": {\n if (!this.pc) return;\n this.pc\n .setRemoteDescription(\n new RTCSessionDescription({ type: \"answer\", sdp: msg.sdp }),\n )\n .then(() => {\n this.hasAnswer = true;\n // Flush any ICE candidates that arrived before the answer.\n for (const init of this.pendingRemoteCandidates) {\n this.pc?.addIceCandidate(init).catch(() => {\n /* ignore stale candidates */\n });\n }\n this.pendingRemoteCandidates = [];\n })\n .catch((err) => {\n this.opts.callbacks?.onError?.(\n new Error(`failed to set remote description: ${err}`),\n );\n });\n break;\n }\n\n case \"ice_candidate\": {\n if (!this.pc) return;\n const init: RTCIceCandidateInit = {\n candidate: msg.candidate,\n sdpMid: msg.sdp_mid ?? null,\n sdpMLineIndex: msg.sdp_mline_index ?? null,\n usernameFragment: msg.username_fragment ?? null,\n };\n if (this.hasAnswer) {\n this.pc.addIceCandidate(init).catch(() => {\n /* ignore stale candidates */\n });\n } else {\n this.pendingRemoteCandidates.push(init);\n }\n break;\n }\n\n case \"connection_state\": {\n // The server echoes the peer connection state; the onconnectionstatechange\n // handler above already covers this, but callers can also react via\n // onConnectionStateChange.\n break;\n }\n\n case \"media_stall\":\n case \"media_track_ended\": {\n void this.beginMediaRecovery(msg.track);\n break;\n }\n\n case \"media_resumed\": {\n this.completeMediaRecovery(msg.track);\n break;\n }\n\n case \"error\": {\n this.opts.callbacks?.onError?.(new Error(msg.error));\n break;\n }\n\n case \"resumed\":\n break;\n }\n }\n\n private async beginMediaRecovery(trackType: string): Promise<void> {\n if (this.stopped || this.recoveringMedia || this.recoveryRequired) return;\n\n const tracks = this.localStream?.getVideoTracks() ?? [];\n const liveTracks = tracks.filter((track) => track.readyState !== \"ended\");\n if (liveTracks.length === 0) {\n this.failMediaRecovery(trackType, \"capture_ended\");\n return;\n }\n\n this.recoveringMedia = true;\n const generation = ++this.recoveryGeneration;\n this.recoveryAction = \"sender_restart\";\n this.emitRecoveryTransition({ state: \"recovering\", track: trackType, action: \"sender_restart\" });\n this.sendRecoveryDiagnostic(\"recovery_started\", trackType, \"sender_restart\");\n\n await this.restartSenders(liveTracks, generation);\n if (!this.isCurrentRecovery(generation)) return;\n\n await this.wait(senderRecoveryWaitMs);\n if (!this.isCurrentRecovery(generation)) return;\n\n this.recoveryAction = \"ice_restart\";\n this.emitRecoveryTransition({ state: \"recovering\", track: trackType, action: \"ice_restart\" });\n this.sendRecoveryDiagnostic(\"recovery_retry\", trackType, \"ice_restart\");\n try {\n await this.renegotiate(true);\n } catch {\n // The fixed recovery window below still gives signaling-resume a chance.\n // If media does not recover, the host receives onRecoveryRequired.\n }\n\n await this.wait(iceRecoveryWaitMs);\n if (!this.isCurrentRecovery(generation)) return;\n this.failMediaRecovery(trackType, \"automatic_recovery_failed\");\n }\n\n private async restartSenders(tracks: MediaStreamTrack[], generation: number): Promise<void> {\n const live = new Set(tracks);\n const senders = this.pc?.getSenders().filter(\n (sender) => sender.track && live.has(sender.track),\n ) ?? [];\n if (senders.length === 0) return;\n\n const originals = senders.map((sender) => ({ sender, track: sender.track! }));\n try {\n await Promise.all(originals.map(({ sender }) => sender.replaceTrack(null)));\n await this.wait(senderRestartPauseMs);\n if (!this.isCurrentRecovery(generation)) return;\n await Promise.all(originals.map(({ sender, track }) => sender.replaceTrack(track)));\n await this.renegotiate(false);\n } catch {\n // ICE restart is the second stage and may still recover a sender reset or\n // renegotiation failure, so do not fail the stream at this stage.\n }\n }\n\n private async renegotiate(iceRestart: boolean): Promise<void> {\n const pc = this.pc;\n const signaling = this.sig;\n if (!pc || !signaling) throw new Error(\"publisher signaling is unavailable\");\n\n if (iceRestart) pc.restartIce?.();\n const offer = await pc.createOffer(iceRestart ? { iceRestart: true } : undefined);\n await pc.setLocalDescription(offer);\n await this.gatherComplete();\n\n const local = pc.localDescription;\n if (!local) throw new Error(\"local description missing\");\n this.hasAnswer = false;\n this.pendingRemoteCandidates = [];\n signaling.send({ type: \"offer\", sdp: local.sdp, sdp_type: \"offer\" });\n }\n\n private completeMediaRecovery(trackType: string): void {\n if (!this.recoveringMedia) return;\n const action = this.recoveryAction ?? undefined;\n this.cancelMediaRecovery();\n this.emitRecoveryTransition({ state: \"recovered\", track: trackType, action });\n }\n\n private failMediaRecovery(\n trackType: string,\n reason: \"capture_ended\" | \"automatic_recovery_failed\",\n ): void {\n if (this.stopped || this.recoveryRequired) return;\n this.recoveryRequired = true;\n const action = this.recoveryAction ?? undefined;\n this.cancelMediaRecovery();\n const event: PublisherRecoveryEvent = { state: \"failed\", track: trackType, action, reason };\n this.emitRecoveryTransition(event);\n this.opts.callbacks?.onRecoveryRequired?.(event);\n this.sendRecoveryDiagnostic(\"recovery_failed\", trackType, action, reason);\n }\n\n private cancelMediaRecovery(): void {\n this.recoveryGeneration++;\n this.recoveringMedia = false;\n this.recoveryAction = null;\n }\n\n private isCurrentRecovery(generation: number): boolean {\n return !this.stopped && this.recoveringMedia && generation === this.recoveryGeneration;\n }\n\n private emitRecoveryTransition(event: PublisherRecoveryEvent): void {\n this.opts.callbacks?.onRecoveryStateChange?.(event);\n }\n\n private sendRecoveryDiagnostic(\n event: \"recovery_started\" | \"recovery_retry\" | \"recovery_failed\",\n track: string,\n action?: PublisherRecoveryAction,\n reason?: \"capture_ended\" | \"automatic_recovery_failed\",\n ): void {\n this.sig?.send({ type: \"recovery_event\", event, track, action, reason });\n }\n\n private watchStreamTracks(stream: MediaStream): void {\n for (const track of stream.getVideoTracks()) {\n const handler: EventListener = () => this.failMediaRecovery(\"screen\", \"capture_ended\");\n track.addEventListener(\"ended\", handler);\n this.trackEndHandlers.set(track, handler);\n }\n }\n\n private unwatchStreamTracks(): void {\n for (const [track, handler] of this.trackEndHandlers) {\n track.removeEventListener(\"ended\", handler);\n }\n this.trackEndHandlers.clear();\n }\n\n /** Waits for ICE gathering to reach the \"complete\" state. */\n private gatherComplete(): Promise<void> {\n return new Promise((resolve) => {\n const pc = this.pc;\n if (!pc) {\n resolve();\n return;\n }\n if (pc.iceGatheringState === \"complete\") {\n resolve();\n return;\n }\n const handler = () => {\n if (pc.iceGatheringState === \"complete\") {\n pc.removeEventListener(\"icegatheringstatechange\", handler);\n resolve();\n }\n };\n pc.addEventListener(\"icegatheringstatechange\", handler);\n });\n }\n}\n","/**\n * Options for {@link captureCamera}.\n *\n * These are merged shallowly over the library defaults: any field you provide\n * replaces the default for that field entirely (e.g. passing `video` overrides\n * the default video constraints rather than merging into them). Omit a field to\n * keep its default.\n */\nexport interface CaptureCameraOptions {\n /**\n * Video constraints, or `true`/`false`. Defaults to a modest resolution and\n * frame rate (see {@link captureCamera}). Set `false` to disable video.\n */\n video?: MediaTrackConstraints | boolean;\n /**\n * Audio constraints, or `true`/`false`. Defaults to `false` — Argus is a\n * video-frame streaming system, so audio is off unless you ask for it.\n */\n audio?: MediaTrackConstraints | boolean;\n /**\n * The `MediaDevices` instance to capture from. Defaults to the global\n * `navigator.mediaDevices`. Pass another window's `navigator.mediaDevices`\n * (e.g. a Document Picture-in-Picture window's) so the browser's permission\n * prompt and transient-activation check are anchored to that window rather\n * than the one holding the global `navigator`.\n */\n mediaDevices?: MediaDevices;\n}\n\n/**\n * Options for {@link captureScreen}.\n *\n * These are merged shallowly over the library defaults: any field you provide\n * replaces the default for that field entirely. Omit a field to keep its\n * default.\n */\nexport interface CaptureScreenOptions {\n /**\n * Video constraints, or `true`. Defaults to a capped width and a low frame\n * rate (see {@link captureScreen}).\n */\n video?: MediaTrackConstraints | boolean;\n /**\n * Audio constraints, or `true`/`false`. Defaults to `false` — screen shares\n * rarely need audio for a video-frame streaming system.\n */\n audio?: MediaTrackConstraints | boolean;\n /**\n * The `MediaDevices` instance to capture from. Defaults to the global\n * `navigator.mediaDevices`. Pass another window's `navigator.mediaDevices`\n * (e.g. a Document Picture-in-Picture window's) so the screen picker and its\n * transient-activation check are anchored to that window rather than the one\n * holding the global `navigator`.\n */\n mediaDevices?: MediaDevices;\n}\n\n/**\n * Captures the user's camera via `navigator.mediaDevices.getUserMedia`,\n * applying sensible defaults for a video-frame streaming system.\n *\n * Defaults:\n * - `video`: `{ width: { ideal: 1280 }, height: { ideal: 720 }, frameRate: { ideal: 30 } }`\n * — a modest resolution that keeps upload bandwidth reasonable. Cameras are\n * rarely the 4k bandwidth problem that screen capture is, so this is an\n * `ideal` (a hint) rather than a hard cap.\n * - `audio`: `false` — this is a video-frame streaming system.\n *\n * Any option you pass replaces the corresponding default outright (shallow\n * merge), so pass a full `video` constraints object if you want to tweak it.\n *\n * @example\n * ```ts\n * const stream = await captureCamera();\n * await publisher.start(stream);\n * ```\n *\n * @example Front camera with audio:\n * ```ts\n * const stream = await captureCamera({\n * video: { facingMode: \"user\" },\n * audio: true,\n * });\n * ```\n */\nexport async function captureCamera(\n opts: CaptureCameraOptions = {},\n): Promise<MediaStream> {\n const constraints: MediaStreamConstraints = {\n video: opts.video ?? {\n width: { ideal: 1280 },\n height: { ideal: 720 },\n frameRate: { ideal: 30 },\n },\n audio: opts.audio ?? false,\n };\n const mediaDevices = opts.mediaDevices ?? navigator.mediaDevices;\n return mediaDevices.getUserMedia(constraints);\n}\n\n/**\n * Captures a screen / window / tab via\n * `navigator.mediaDevices.getDisplayMedia`, applying sensible defaults tuned to\n * avoid the HiDPI/Retina bandwidth trap.\n *\n * Defaults:\n * - `video`: `{ width: { max: 1920 }, frameRate: { ideal: 5, max: 10 } }`.\n * The `width` is a **`max`, not an `ideal`**: on a 2x-Retina display the\n * browser would otherwise capture at native resolution (often 3456px+ /\n * effectively 4k), wasting upload bandwidth and downstream decode cost for no\n * visible benefit. Capping the max roughly halves a 2x-Retina share while\n * leaving smaller displays untouched. Screen content is mostly static, so the\n * low frame rate saves further bandwidth.\n * - `audio`: `false`.\n *\n * IMPORTANT — do NOT add `resizeMode: \"none\"` here. That value forbids the\n * browser from downscaling the source, which turns the `width: { max: 1920 }`\n * cap into a no-op on exactly the Retina displays it targets. By omitting\n * `resizeMode` we let the user agent scale to satisfy the constraint (its\n * default behaviour), which is the entire point of this helper. It is tempting\n * to add `resizeMode: \"none\"` back for \"sharpness\" — don't.\n *\n * Any option you pass replaces the corresponding default outright (shallow\n * merge), so pass a full `video` constraints object if you want to tweak it.\n *\n * @example\n * ```ts\n * const stream = await captureScreen();\n * await publisher.start(stream);\n * ```\n */\nexport async function captureScreen(\n opts: CaptureScreenOptions = {},\n): Promise<MediaStream> {\n const constraints: MediaStreamConstraints = {\n video: opts.video ?? {\n width: { max: 1920 },\n frameRate: { ideal: 5, max: 10 },\n },\n audio: opts.audio ?? false,\n };\n const mediaDevices = opts.mediaDevices ?? navigator.mediaDevices;\n return mediaDevices.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AAQ,EAAE,OAAO,IAAI;AAAA,MACrB,WAAW,EAAE,OAAO,GAAG;AAAA,IACzB;AAAA,IACA,OAAO,KAAK,SAAS;AAAA,EACvB;AACA,QAAM,eAAe,KAAK,gBAAgB,UAAU;AACpD,SAAO,aAAa,aAAa,WAAW;AAC9C;AAiCA,eAAsB,cACpB,OAA6B,CAAC,GACR;AACtB,QAAM,cAAsC;AAAA,IAC1C,OAAO,KAAK,SAAS;AAAA,MACnB,OAAO,EAAE,KAAK,KAAK;AAAA,MACnB,WAAW,EAAE,OAAO,GAAG,KAAK,GAAG;AAAA,IACjC;AAAA,IACA,OAAO,KAAK,SAAS;AAAA,EACvB;AACA,QAAM,eAAe,KAAK,gBAAgB,UAAU;AACpD,SAAO,aAAa,gBAAgB,WAAW;AACjD;","names":[]}
package/dist/index.d.cts CHANGED
@@ -134,7 +134,7 @@ declare class Publisher {
134
134
  private pendingRemoteCandidates;
135
135
  private localStream;
136
136
  private readToken;
137
- private selectedGatewayURL;
137
+ private gatewayURL;
138
138
  private stopped;
139
139
  private reconnecting;
140
140
  private reconnectGeneration;
@@ -147,6 +147,12 @@ declare class Publisher {
147
147
  constructor(opts: PublisherOptions);
148
148
  /** The read token used for frame fetches and signaling resume in the selected region. */
149
149
  get frameReadToken(): string | null;
150
+ /**
151
+ * The signaling gateway URL that won the initial race, or null before start.
152
+ * Relay this with frameReadToken so the application server can reach the same
153
+ * region for frame reads and change-notification subscriptions.
154
+ */
155
+ get selectedGatewayURL(): string | null;
150
156
  /**
151
157
  * Starts the publisher: races all gateways to find the fastest, completes
152
158
  * the two-phase handshake, creates the peer connection, and sends the SDP
package/dist/index.d.ts CHANGED
@@ -134,7 +134,7 @@ declare class Publisher {
134
134
  private pendingRemoteCandidates;
135
135
  private localStream;
136
136
  private readToken;
137
- private selectedGatewayURL;
137
+ private gatewayURL;
138
138
  private stopped;
139
139
  private reconnecting;
140
140
  private reconnectGeneration;
@@ -147,6 +147,12 @@ declare class Publisher {
147
147
  constructor(opts: PublisherOptions);
148
148
  /** The read token used for frame fetches and signaling resume in the selected region. */
149
149
  get frameReadToken(): string | null;
150
+ /**
151
+ * The signaling gateway URL that won the initial race, or null before start.
152
+ * Relay this with frameReadToken so the application server can reach the same
153
+ * region for frame reads and change-notification subscriptions.
154
+ */
155
+ get selectedGatewayURL(): string | null;
150
156
  /**
151
157
  * Starts the publisher: races all gateways to find the fastest, completes
152
158
  * the two-phase handshake, creates the peer connection, and sends the SDP
package/dist/index.js CHANGED
@@ -59,7 +59,7 @@ var Publisher = class {
59
59
  pendingRemoteCandidates = [];
60
60
  localStream = null;
61
61
  readToken = null;
62
- selectedGatewayURL = null;
62
+ gatewayURL = null;
63
63
  stopped = true;
64
64
  reconnecting = false;
65
65
  reconnectGeneration = 0;
@@ -76,6 +76,14 @@ var Publisher = class {
76
76
  get frameReadToken() {
77
77
  return this.readToken;
78
78
  }
79
+ /**
80
+ * The signaling gateway URL that won the initial race, or null before start.
81
+ * Relay this with frameReadToken so the application server can reach the same
82
+ * region for frame reads and change-notification subscriptions.
83
+ */
84
+ get selectedGatewayURL() {
85
+ return this.gatewayURL;
86
+ }
79
87
  /**
80
88
  * Starts the publisher: races all gateways to find the fastest, completes
81
89
  * the two-phase handshake, creates the peer connection, and sends the SDP
@@ -88,7 +96,7 @@ var Publisher = class {
88
96
  this.localStream = stream;
89
97
  this.watchStreamTracks(stream);
90
98
  const { ws, readyInfo, gatewayURL } = await this.raceGateways();
91
- this.selectedGatewayURL = gatewayURL;
99
+ this.gatewayURL = gatewayURL;
92
100
  if (readyInfo.read_token) {
93
101
  this.readToken = readyInfo.read_token;
94
102
  }
@@ -165,7 +173,7 @@ var Publisher = class {
165
173
  this.hasAnswer = false;
166
174
  this.pendingRemoteCandidates = [];
167
175
  this.readToken = null;
168
- this.selectedGatewayURL = null;
176
+ this.gatewayURL = null;
169
177
  }
170
178
  /** Returns the current RTCPeerConnection, or null if not started. */
171
179
  get peerConnection() {
@@ -245,7 +253,7 @@ var Publisher = class {
245
253
  }
246
254
  async resumeSignaling() {
247
255
  if (this.reconnecting || this.stopped) return;
248
- if (!this.selectedGatewayURL || !this.readToken) {
256
+ if (!this.gatewayURL || !this.readToken) {
249
257
  this.terminateWithError(new Error("signaling closed and cannot be resumed"));
250
258
  return;
251
259
  }
@@ -284,7 +292,7 @@ var Publisher = class {
284
292
  }
285
293
  openResumeSocket(timeoutMs) {
286
294
  return new Promise((resolve, reject) => {
287
- const u = new URL(this.selectedGatewayURL);
295
+ const u = new URL(this.gatewayURL);
288
296
  u.searchParams.set("token", this.readToken);
289
297
  const ws = new WebSocket(u.toString());
290
298
  this.resumeSocket = ws;
@@ -334,7 +342,7 @@ var Publisher = class {
334
342
  this.hasAnswer = false;
335
343
  this.pendingRemoteCandidates = [];
336
344
  this.readToken = null;
337
- this.selectedGatewayURL = null;
345
+ this.gatewayURL = null;
338
346
  this.opts.callbacks?.onError?.(err);
339
347
  }
340
348
  handleSignal(msg) {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/signaling.ts","../src/publisher.ts","../src/capture.ts"],"sourcesContent":["import type { SignalMessage } from \"./types\";\n\n/**\n * Wraps an open WebSocket to the Argus gateway and handles the JSON message\n * envelope: incoming text frames are parsed into {@link SignalMessage}s and\n * outgoing messages are serialised.\n *\n * This is an internal helper. The {@link Publisher} opens the socket itself\n * (racing all candidate gateways) and hands the winner here, so this class only\n * ever adopts an already-open socket rather than dialing one.\n *\n * @internal\n */\nexport class SignalingChannel {\n private ws: WebSocket;\n\n /** Fired for every incoming JSON message. */\n onMessage: ((msg: SignalMessage) => void) | null = null;\n /** Fired when the underlying WebSocket closes. */\n onClose: (() => void) | null = null;\n /** Fired when an error occurs on the WebSocket. */\n onError: ((err: Error) => void) | null = null;\n\n private constructor(ws: WebSocket) {\n this.ws = ws;\n }\n\n /**\n * Adopts an already-open WebSocket (e.g. the winner of a gateway race),\n * routing its events through the channel's callbacks. Any handlers previously\n * attached to the socket are replaced.\n */\n static wrap(ws: WebSocket): SignalingChannel {\n const ch = new SignalingChannel(ws);\n ws.onmessage = (ev: MessageEvent) => {\n const msg = parseSignal(ev.data);\n if (msg) ch.onMessage?.(msg);\n };\n ws.onerror = () => ch.onError?.(new Error(\"WebSocket error\"));\n ws.onclose = () => ch.onClose?.();\n return ch;\n }\n\n /** Sends a JSON message if the socket is open; a no-op otherwise. */\n send(msg: SignalMessage): void {\n if (this.ws.readyState === WebSocket.OPEN) {\n this.ws.send(JSON.stringify(msg));\n }\n }\n\n /** Closes the underlying WebSocket. */\n close(): void {\n this.ws.close();\n }\n}\n\n/** Parses a WebSocket text frame into a SignalMessage, or null if malformed. */\nfunction parseSignal(data: unknown): SignalMessage | null {\n try {\n return JSON.parse(data as string) as SignalMessage;\n } catch {\n return null;\n }\n}\n","import { SignalingChannel } from \"./signaling\";\nimport type {\n GatewayReadyInfo,\n PublisherOptions,\n PublisherRecoveryAction,\n PublisherRecoveryEvent,\n SignalMessage,\n} from \"./types\";\n\nconst defaultSignalingReconnectTimeoutMs = 20_000;\nconst signalingResumeAttemptTimeoutMs = 3_000;\nconst signalingResumeMaxBackoffMs = 3_000;\nconst senderRestartPauseMs = 100;\nconst senderRecoveryWaitMs = 4_000;\nconst iceRecoveryWaitMs = 8_000;\n\n/**\n * Publisher streams a browser {@link MediaStream} to an Argus media server over\n * WebRTC. Given the `gateway_urls` and `token` from a join-token response, it\n * races the candidate gateways to the fastest one, completes the two-phase\n * signaling handshake, and manages the peer connection — offer/answer exchange,\n * ICE candidate trickling, and track (re)negotiation.\n *\n * After {@link Publisher.start} resolves, {@link Publisher.frameReadToken} holds\n * the token your application server needs to fetch frames for this stream.\n *\n * @example Publish the default camera:\n * ```ts\n * const pub = new Publisher({\n * gatewayURLs: joinResp.gateway_urls,\n * token: joinResp.token,\n * callbacks: { onConnected: () => console.log(\"live!\") },\n * });\n *\n * const stream = await navigator.mediaDevices.getUserMedia({ video: true });\n * await pub.start(stream);\n * ```\n */\nexport class Publisher {\n private opts: PublisherOptions;\n private sig: SignalingChannel | null = null;\n private pc: RTCPeerConnection | null = null;\n private hasAnswer = false;\n private pendingRemoteCandidates: RTCIceCandidateInit[] = [];\n private localStream: MediaStream | null = null;\n private readToken: string | null = null;\n private selectedGatewayURL: string | null = null;\n private stopped = true;\n private reconnecting = false;\n private reconnectGeneration = 0;\n private resumeSocket: WebSocket | null = null;\n private recoveryGeneration = 0;\n private recoveringMedia = false;\n private recoveryRequired = false;\n private recoveryAction: PublisherRecoveryAction | null = null;\n private trackEndHandlers = new Map<MediaStreamTrack, EventListener>();\n\n constructor(opts: PublisherOptions) {\n this.opts = opts;\n }\n\n /** The read token used for frame fetches and signaling resume in the selected region. */\n get frameReadToken(): string | null { return this.readToken; }\n\n /**\n * Starts the publisher: races all gateways to find the fastest, completes\n * the two-phase handshake, creates the peer connection, and sends the SDP\n * offer. Resolves when the offer has been sent (not when ICE completes —\n * use onConnected for that).\n */\n async start(stream: MediaStream): Promise<void> {\n this.stopped = false;\n this.recoveryRequired = false;\n this.localStream = stream;\n this.watchStreamTracks(stream);\n\n // Race all gateways; returns winning WebSocket + TURN/read-token info\n const { ws, readyInfo, gatewayURL } = await this.raceGateways();\n this.selectedGatewayURL = gatewayURL;\n\n // Store read token for caller\n if (readyInfo.read_token) {\n this.readToken = readyInfo.read_token;\n }\n\n // Build ICE servers: extra servers from opts + TURN from gateway. The\n // gateway supplies multi-transport turn_urls (UDP + TCP) so relay can fall\n // back to TCP on UDP-blocking networks. A single credential is valid for\n // every transport.\n const iceServers: RTCIceServer[] = [...(this.opts.iceServers ?? [])];\n if (readyInfo.turn_urls && readyInfo.turn_urls.length > 0) {\n iceServers.push({\n urls: readyInfo.turn_urls,\n username: readyInfo.turn_username,\n credential: readyInfo.turn_credential,\n });\n }\n\n this.pc = new RTCPeerConnection({ iceServers });\n\n this.pc.onicecandidate = (ev) => {\n if (!ev.candidate || !this.sig) return;\n const c = ev.candidate;\n this.sig.send({\n type: \"ice_candidate\",\n candidate: c.candidate,\n sdp_mid: c.sdpMid ?? undefined,\n sdp_mline_index: c.sdpMLineIndex ?? undefined,\n username_fragment: c.usernameFragment ?? undefined,\n });\n };\n\n this.pc.onconnectionstatechange = () => {\n const state = this.pc?.connectionState;\n if (state) this.opts.callbacks?.onConnectionStateChange?.(state);\n if (state === \"connected\") this.opts.callbacks?.onConnected?.();\n };\n\n for (const track of stream.getTracks()) {\n this.pc.addTrack(track, stream);\n }\n\n const offer = await this.pc.createOffer();\n await this.pc.setLocalDescription(offer);\n await this.gatherComplete();\n\n // Wrap winning WebSocket in SignalingChannel\n const signaling = this.installSignaling(ws);\n\n const local = this.pc.localDescription;\n if (!local) throw new Error(\"local description missing after gather\");\n signaling.send({ type: \"offer\", sdp: local.sdp, sdp_type: \"offer\" });\n }\n\n /** Replaces the currently published stream with a new one. */\n async replaceStream(stream: MediaStream): Promise<void> {\n if (!this.pc) throw new Error(\"publisher not started\");\n\n this.cancelMediaRecovery();\n this.recoveryRequired = false;\n this.unwatchStreamTracks();\n\n // Remove old tracks.\n const senders = this.pc.getSenders();\n for (const sender of senders) {\n if (sender.track) {\n this.pc.removeTrack(sender);\n }\n }\n\n // Add new tracks.\n for (const track of stream.getTracks()) {\n this.pc.addTrack(track, stream);\n }\n this.localStream = stream;\n this.watchStreamTracks(stream);\n\n await this.renegotiate(false);\n }\n\n /** Stops publishing and tears down the peer connection. */\n stop(): void {\n this.stopped = true;\n this.cancelMediaRecovery();\n this.reconnectGeneration++;\n this.reconnecting = false;\n this.resumeSocket?.close();\n this.resumeSocket = null;\n this.sig?.close();\n this.sig = null;\n\n this.unwatchStreamTracks();\n this.localStream?.getTracks().forEach((t) => t.stop());\n this.localStream = null;\n\n this.pc?.close();\n this.pc = null;\n this.hasAnswer = false;\n this.pendingRemoteCandidates = [];\n this.readToken = null;\n this.selectedGatewayURL = null;\n }\n\n /** Returns the current RTCPeerConnection, or null if not started. */\n get peerConnection(): RTCPeerConnection | null {\n return this.pc;\n }\n\n /** Returns true if the peer connection is in the \"connected\" state. */\n get isConnected(): boolean {\n return this.pc?.connectionState === \"connected\";\n }\n\n // -------------------------------------------------------------------------\n // Private helpers\n // -------------------------------------------------------------------------\n\n private raceGateways(): Promise<{ ws: WebSocket; readyInfo: GatewayReadyInfo; gatewayURL: string }> {\n return new Promise((resolve, reject) => {\n const { gatewayURLs, token } = this.opts;\n if (gatewayURLs.length === 0) {\n reject(new Error(\"no gateway URLs provided\"));\n return;\n }\n\n const sockets: WebSocket[] = [];\n let settled = false;\n\n const closeAll = (except?: WebSocket) => {\n for (const s of sockets) {\n if (s !== except) {\n s.onmessage = null;\n s.onerror = null;\n s.onclose = null;\n s.close();\n }\n }\n };\n\n const checkAllFailed = () => {\n if (settled) return;\n if (sockets.every(s => s.readyState === WebSocket.CLOSED || s.readyState === WebSocket.CLOSING)) {\n settled = true;\n reject(new Error(\"all gateways failed to connect\"));\n }\n };\n\n for (const gatewayURL of gatewayURLs) {\n const u = new URL(gatewayURL);\n u.searchParams.set(\"token\", token);\n const ws = new WebSocket(u.toString());\n sockets.push(ws);\n\n let accepted = false;\n\n ws.onmessage = (ev: MessageEvent) => {\n if (settled) return;\n try {\n const msg = JSON.parse(ev.data as string);\n if (!accepted && msg.type === \"accepted\") {\n accepted = true;\n ws.send(JSON.stringify({ type: \"proceed\" }));\n } else if (accepted && msg.type === \"ready\") {\n settled = true;\n closeAll(ws);\n resolve({ ws, readyInfo: msg as GatewayReadyInfo, gatewayURL });\n }\n } catch {\n /* ignore malformed */\n }\n };\n\n ws.onerror = () => checkAllFailed();\n ws.onclose = () => checkAllFailed();\n }\n });\n }\n\n private installSignaling(ws: WebSocket): SignalingChannel {\n const channel = SignalingChannel.wrap(ws);\n this.sig = channel;\n channel.onMessage = (msg) => this.handleSignal(msg);\n channel.onClose = () => {\n if (this.sig !== channel || this.stopped) return;\n this.sig = null;\n void this.resumeSignaling();\n };\n // Browsers normally follow an error event with close. Recovery begins from\n // close so a single transport failure cannot start two retry loops.\n channel.onError = () => {};\n return channel;\n }\n\n private async resumeSignaling(): Promise<void> {\n if (this.reconnecting || this.stopped) return;\n if (!this.selectedGatewayURL || !this.readToken) {\n this.terminateWithError(new Error(\"signaling closed and cannot be resumed\"));\n return;\n }\n\n this.reconnecting = true;\n const generation = ++this.reconnectGeneration;\n const timeout = this.opts.signalingReconnectTimeoutMs ?? defaultSignalingReconnectTimeoutMs;\n const deadline = Date.now() + Math.max(0, timeout);\n let backoffMs = 0;\n\n while (!this.stopped && generation === this.reconnectGeneration && Date.now() <= deadline) {\n if (backoffMs > 0) {\n const waitMs = Math.min(backoffMs, Math.max(0, deadline - Date.now()));\n if (waitMs === 0) break;\n await this.wait(waitMs);\n if (this.stopped || generation !== this.reconnectGeneration) return;\n }\n\n const remaining = deadline - Date.now();\n if (remaining < 0) break;\n try {\n const ws = await this.openResumeSocket(Math.min(signalingResumeAttemptTimeoutMs, Math.max(1, remaining)));\n if (this.stopped || generation !== this.reconnectGeneration) {\n ws.close();\n return;\n }\n this.resumeSocket = null;\n this.reconnecting = false;\n this.installSignaling(ws);\n return;\n } catch {\n backoffMs = backoffMs === 0 ? 250 : Math.min(backoffMs * 2, signalingResumeMaxBackoffMs);\n }\n }\n\n if (!this.stopped && generation === this.reconnectGeneration) {\n this.reconnecting = false;\n this.terminateWithError(new Error(\"unable to resume signaling with the selected gateway\"));\n }\n }\n\n private openResumeSocket(timeoutMs: number): Promise<WebSocket> {\n return new Promise((resolve, reject) => {\n const u = new URL(this.selectedGatewayURL!);\n u.searchParams.set(\"token\", this.readToken!);\n const ws = new WebSocket(u.toString());\n this.resumeSocket = ws;\n let settled = false;\n const timer = setTimeout(() => fail(), timeoutMs);\n\n const fail = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n if (this.resumeSocket === ws) this.resumeSocket = null;\n ws.onmessage = null;\n ws.onerror = null;\n ws.onclose = null;\n ws.close();\n reject(new Error(\"signaling resume attempt failed\"));\n };\n\n ws.onmessage = (ev: MessageEvent) => {\n try {\n const msg = JSON.parse(ev.data as string);\n if (msg.type !== \"resumed\" || settled) return;\n settled = true;\n clearTimeout(timer);\n resolve(ws);\n } catch {\n // Ignore malformed messages while waiting for the resume acknowledgement.\n }\n };\n ws.onerror = fail;\n ws.onclose = fail;\n });\n }\n\n private wait(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n private terminateWithError(err: Error): void {\n this.stopped = true;\n this.cancelMediaRecovery();\n this.reconnectGeneration++;\n this.resumeSocket?.close();\n this.resumeSocket = null;\n this.sig?.close();\n this.sig = null;\n this.pc?.close();\n this.pc = null;\n this.unwatchStreamTracks();\n this.localStream?.getTracks().forEach((track) => track.stop());\n this.localStream = null;\n this.hasAnswer = false;\n this.pendingRemoteCandidates = [];\n this.readToken = null;\n this.selectedGatewayURL = null;\n this.opts.callbacks?.onError?.(err);\n }\n\n private handleSignal(msg: SignalMessage): void {\n switch (msg.type) {\n case \"answer\": {\n if (!this.pc) return;\n this.pc\n .setRemoteDescription(\n new RTCSessionDescription({ type: \"answer\", sdp: msg.sdp }),\n )\n .then(() => {\n this.hasAnswer = true;\n // Flush any ICE candidates that arrived before the answer.\n for (const init of this.pendingRemoteCandidates) {\n this.pc?.addIceCandidate(init).catch(() => {\n /* ignore stale candidates */\n });\n }\n this.pendingRemoteCandidates = [];\n })\n .catch((err) => {\n this.opts.callbacks?.onError?.(\n new Error(`failed to set remote description: ${err}`),\n );\n });\n break;\n }\n\n case \"ice_candidate\": {\n if (!this.pc) return;\n const init: RTCIceCandidateInit = {\n candidate: msg.candidate,\n sdpMid: msg.sdp_mid ?? null,\n sdpMLineIndex: msg.sdp_mline_index ?? null,\n usernameFragment: msg.username_fragment ?? null,\n };\n if (this.hasAnswer) {\n this.pc.addIceCandidate(init).catch(() => {\n /* ignore stale candidates */\n });\n } else {\n this.pendingRemoteCandidates.push(init);\n }\n break;\n }\n\n case \"connection_state\": {\n // The server echoes the peer connection state; the onconnectionstatechange\n // handler above already covers this, but callers can also react via\n // onConnectionStateChange.\n break;\n }\n\n case \"media_stall\":\n case \"media_track_ended\": {\n void this.beginMediaRecovery(msg.track);\n break;\n }\n\n case \"media_resumed\": {\n this.completeMediaRecovery(msg.track);\n break;\n }\n\n case \"error\": {\n this.opts.callbacks?.onError?.(new Error(msg.error));\n break;\n }\n\n case \"resumed\":\n break;\n }\n }\n\n private async beginMediaRecovery(trackType: string): Promise<void> {\n if (this.stopped || this.recoveringMedia || this.recoveryRequired) return;\n\n const tracks = this.localStream?.getVideoTracks() ?? [];\n const liveTracks = tracks.filter((track) => track.readyState !== \"ended\");\n if (liveTracks.length === 0) {\n this.failMediaRecovery(trackType, \"capture_ended\");\n return;\n }\n\n this.recoveringMedia = true;\n const generation = ++this.recoveryGeneration;\n this.recoveryAction = \"sender_restart\";\n this.emitRecoveryTransition({ state: \"recovering\", track: trackType, action: \"sender_restart\" });\n this.sendRecoveryDiagnostic(\"recovery_started\", trackType, \"sender_restart\");\n\n await this.restartSenders(liveTracks, generation);\n if (!this.isCurrentRecovery(generation)) return;\n\n await this.wait(senderRecoveryWaitMs);\n if (!this.isCurrentRecovery(generation)) return;\n\n this.recoveryAction = \"ice_restart\";\n this.emitRecoveryTransition({ state: \"recovering\", track: trackType, action: \"ice_restart\" });\n this.sendRecoveryDiagnostic(\"recovery_retry\", trackType, \"ice_restart\");\n try {\n await this.renegotiate(true);\n } catch {\n // The fixed recovery window below still gives signaling-resume a chance.\n // If media does not recover, the host receives onRecoveryRequired.\n }\n\n await this.wait(iceRecoveryWaitMs);\n if (!this.isCurrentRecovery(generation)) return;\n this.failMediaRecovery(trackType, \"automatic_recovery_failed\");\n }\n\n private async restartSenders(tracks: MediaStreamTrack[], generation: number): Promise<void> {\n const live = new Set(tracks);\n const senders = this.pc?.getSenders().filter(\n (sender) => sender.track && live.has(sender.track),\n ) ?? [];\n if (senders.length === 0) return;\n\n const originals = senders.map((sender) => ({ sender, track: sender.track! }));\n try {\n await Promise.all(originals.map(({ sender }) => sender.replaceTrack(null)));\n await this.wait(senderRestartPauseMs);\n if (!this.isCurrentRecovery(generation)) return;\n await Promise.all(originals.map(({ sender, track }) => sender.replaceTrack(track)));\n await this.renegotiate(false);\n } catch {\n // ICE restart is the second stage and may still recover a sender reset or\n // renegotiation failure, so do not fail the stream at this stage.\n }\n }\n\n private async renegotiate(iceRestart: boolean): Promise<void> {\n const pc = this.pc;\n const signaling = this.sig;\n if (!pc || !signaling) throw new Error(\"publisher signaling is unavailable\");\n\n if (iceRestart) pc.restartIce?.();\n const offer = await pc.createOffer(iceRestart ? { iceRestart: true } : undefined);\n await pc.setLocalDescription(offer);\n await this.gatherComplete();\n\n const local = pc.localDescription;\n if (!local) throw new Error(\"local description missing\");\n this.hasAnswer = false;\n this.pendingRemoteCandidates = [];\n signaling.send({ type: \"offer\", sdp: local.sdp, sdp_type: \"offer\" });\n }\n\n private completeMediaRecovery(trackType: string): void {\n if (!this.recoveringMedia) return;\n const action = this.recoveryAction ?? undefined;\n this.cancelMediaRecovery();\n this.emitRecoveryTransition({ state: \"recovered\", track: trackType, action });\n }\n\n private failMediaRecovery(\n trackType: string,\n reason: \"capture_ended\" | \"automatic_recovery_failed\",\n ): void {\n if (this.stopped || this.recoveryRequired) return;\n this.recoveryRequired = true;\n const action = this.recoveryAction ?? undefined;\n this.cancelMediaRecovery();\n const event: PublisherRecoveryEvent = { state: \"failed\", track: trackType, action, reason };\n this.emitRecoveryTransition(event);\n this.opts.callbacks?.onRecoveryRequired?.(event);\n this.sendRecoveryDiagnostic(\"recovery_failed\", trackType, action, reason);\n }\n\n private cancelMediaRecovery(): void {\n this.recoveryGeneration++;\n this.recoveringMedia = false;\n this.recoveryAction = null;\n }\n\n private isCurrentRecovery(generation: number): boolean {\n return !this.stopped && this.recoveringMedia && generation === this.recoveryGeneration;\n }\n\n private emitRecoveryTransition(event: PublisherRecoveryEvent): void {\n this.opts.callbacks?.onRecoveryStateChange?.(event);\n }\n\n private sendRecoveryDiagnostic(\n event: \"recovery_started\" | \"recovery_retry\" | \"recovery_failed\",\n track: string,\n action?: PublisherRecoveryAction,\n reason?: \"capture_ended\" | \"automatic_recovery_failed\",\n ): void {\n this.sig?.send({ type: \"recovery_event\", event, track, action, reason });\n }\n\n private watchStreamTracks(stream: MediaStream): void {\n for (const track of stream.getVideoTracks()) {\n const handler: EventListener = () => this.failMediaRecovery(\"screen\", \"capture_ended\");\n track.addEventListener(\"ended\", handler);\n this.trackEndHandlers.set(track, handler);\n }\n }\n\n private unwatchStreamTracks(): void {\n for (const [track, handler] of this.trackEndHandlers) {\n track.removeEventListener(\"ended\", handler);\n }\n this.trackEndHandlers.clear();\n }\n\n /** Waits for ICE gathering to reach the \"complete\" state. */\n private gatherComplete(): Promise<void> {\n return new Promise((resolve) => {\n const pc = this.pc;\n if (!pc) {\n resolve();\n return;\n }\n if (pc.iceGatheringState === \"complete\") {\n resolve();\n return;\n }\n const handler = () => {\n if (pc.iceGatheringState === \"complete\") {\n pc.removeEventListener(\"icegatheringstatechange\", handler);\n resolve();\n }\n };\n pc.addEventListener(\"icegatheringstatechange\", handler);\n });\n }\n}\n","/**\n * Options for {@link captureCamera}.\n *\n * These are merged shallowly over the library defaults: any field you provide\n * replaces the default for that field entirely (e.g. passing `video` overrides\n * the default video constraints rather than merging into them). Omit a field to\n * keep its default.\n */\nexport interface CaptureCameraOptions {\n /**\n * Video constraints, or `true`/`false`. Defaults to a modest resolution and\n * frame rate (see {@link captureCamera}). Set `false` to disable video.\n */\n video?: MediaTrackConstraints | boolean;\n /**\n * Audio constraints, or `true`/`false`. Defaults to `false` — Argus is a\n * video-frame streaming system, so audio is off unless you ask for it.\n */\n audio?: MediaTrackConstraints | boolean;\n /**\n * The `MediaDevices` instance to capture from. Defaults to the global\n * `navigator.mediaDevices`. Pass another window's `navigator.mediaDevices`\n * (e.g. a Document Picture-in-Picture window's) so the browser's permission\n * prompt and transient-activation check are anchored to that window rather\n * than the one holding the global `navigator`.\n */\n mediaDevices?: MediaDevices;\n}\n\n/**\n * Options for {@link captureScreen}.\n *\n * These are merged shallowly over the library defaults: any field you provide\n * replaces the default for that field entirely. Omit a field to keep its\n * default.\n */\nexport interface CaptureScreenOptions {\n /**\n * Video constraints, or `true`. Defaults to a capped width and a low frame\n * rate (see {@link captureScreen}).\n */\n video?: MediaTrackConstraints | boolean;\n /**\n * Audio constraints, or `true`/`false`. Defaults to `false` — screen shares\n * rarely need audio for a video-frame streaming system.\n */\n audio?: MediaTrackConstraints | boolean;\n /**\n * The `MediaDevices` instance to capture from. Defaults to the global\n * `navigator.mediaDevices`. Pass another window's `navigator.mediaDevices`\n * (e.g. a Document Picture-in-Picture window's) so the screen picker and its\n * transient-activation check are anchored to that window rather than the one\n * holding the global `navigator`.\n */\n mediaDevices?: MediaDevices;\n}\n\n/**\n * Captures the user's camera via `navigator.mediaDevices.getUserMedia`,\n * applying sensible defaults for a video-frame streaming system.\n *\n * Defaults:\n * - `video`: `{ width: { ideal: 1280 }, height: { ideal: 720 }, frameRate: { ideal: 30 } }`\n * — a modest resolution that keeps upload bandwidth reasonable. Cameras are\n * rarely the 4k bandwidth problem that screen capture is, so this is an\n * `ideal` (a hint) rather than a hard cap.\n * - `audio`: `false` — this is a video-frame streaming system.\n *\n * Any option you pass replaces the corresponding default outright (shallow\n * merge), so pass a full `video` constraints object if you want to tweak it.\n *\n * @example\n * ```ts\n * const stream = await captureCamera();\n * await publisher.start(stream);\n * ```\n *\n * @example Front camera with audio:\n * ```ts\n * const stream = await captureCamera({\n * video: { facingMode: \"user\" },\n * audio: true,\n * });\n * ```\n */\nexport async function captureCamera(\n opts: CaptureCameraOptions = {},\n): Promise<MediaStream> {\n const constraints: MediaStreamConstraints = {\n video: opts.video ?? {\n width: { ideal: 1280 },\n height: { ideal: 720 },\n frameRate: { ideal: 30 },\n },\n audio: opts.audio ?? false,\n };\n const mediaDevices = opts.mediaDevices ?? navigator.mediaDevices;\n return mediaDevices.getUserMedia(constraints);\n}\n\n/**\n * Captures a screen / window / tab via\n * `navigator.mediaDevices.getDisplayMedia`, applying sensible defaults tuned to\n * avoid the HiDPI/Retina bandwidth trap.\n *\n * Defaults:\n * - `video`: `{ width: { max: 1920 }, frameRate: { ideal: 5, max: 10 } }`.\n * The `width` is a **`max`, not an `ideal`**: on a 2x-Retina display the\n * browser would otherwise capture at native resolution (often 3456px+ /\n * effectively 4k), wasting upload bandwidth and downstream decode cost for no\n * visible benefit. Capping the max roughly halves a 2x-Retina share while\n * leaving smaller displays untouched. Screen content is mostly static, so the\n * low frame rate saves further bandwidth.\n * - `audio`: `false`.\n *\n * IMPORTANT — do NOT add `resizeMode: \"none\"` here. That value forbids the\n * browser from downscaling the source, which turns the `width: { max: 1920 }`\n * cap into a no-op on exactly the Retina displays it targets. By omitting\n * `resizeMode` we let the user agent scale to satisfy the constraint (its\n * default behaviour), which is the entire point of this helper. It is tempting\n * to add `resizeMode: \"none\"` back for \"sharpness\" — don't.\n *\n * Any option you pass replaces the corresponding default outright (shallow\n * merge), so pass a full `video` constraints object if you want to tweak it.\n *\n * @example\n * ```ts\n * const stream = await captureScreen();\n * await publisher.start(stream);\n * ```\n */\nexport async function captureScreen(\n opts: CaptureScreenOptions = {},\n): Promise<MediaStream> {\n const constraints: MediaStreamConstraints = {\n video: opts.video ?? {\n width: { max: 1920 },\n frameRate: { ideal: 5, max: 10 },\n },\n audio: opts.audio ?? false,\n };\n const mediaDevices = opts.mediaDevices ?? navigator.mediaDevices;\n return mediaDevices.getDisplayMedia(constraints);\n}\n"],"mappings":";AAaO,IAAM,mBAAN,MAAM,kBAAiB;AAAA,EACpB;AAAA;AAAA,EAGR,YAAmD;AAAA;AAAA,EAEnD,UAA+B;AAAA;AAAA,EAE/B,UAAyC;AAAA,EAEjC,YAAY,IAAe;AACjC,SAAK,KAAK;AAAA,EACZ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,OAAO,KAAK,IAAiC;AAC3C,UAAM,KAAK,IAAI,kBAAiB,EAAE;AAClC,OAAG,YAAY,CAAC,OAAqB;AACnC,YAAM,MA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]}
1
+ {"version":3,"sources":["../src/signaling.ts","../src/publisher.ts","../src/capture.ts"],"sourcesContent":["import type { SignalMessage } from \"./types\";\n\n/**\n * Wraps an open WebSocket to the Argus gateway and handles the JSON message\n * envelope: incoming text frames are parsed into {@link SignalMessage}s and\n * outgoing messages are serialised.\n *\n * This is an internal helper. The {@link Publisher} opens the socket itself\n * (racing all candidate gateways) and hands the winner here, so this class only\n * ever adopts an already-open socket rather than dialing one.\n *\n * @internal\n */\nexport class SignalingChannel {\n private ws: WebSocket;\n\n /** Fired for every incoming JSON message. */\n onMessage: ((msg: SignalMessage) => void) | null = null;\n /** Fired when the underlying WebSocket closes. */\n onClose: (() => void) | null = null;\n /** Fired when an error occurs on the WebSocket. */\n onError: ((err: Error) => void) | null = null;\n\n private constructor(ws: WebSocket) {\n this.ws = ws;\n }\n\n /**\n * Adopts an already-open WebSocket (e.g. the winner of a gateway race),\n * routing its events through the channel's callbacks. Any handlers previously\n * attached to the socket are replaced.\n */\n static wrap(ws: WebSocket): SignalingChannel {\n const ch = new SignalingChannel(ws);\n ws.onmessage = (ev: MessageEvent) => {\n const msg = parseSignal(ev.data);\n if (msg) ch.onMessage?.(msg);\n };\n ws.onerror = () => ch.onError?.(new Error(\"WebSocket error\"));\n ws.onclose = () => ch.onClose?.();\n return ch;\n }\n\n /** Sends a JSON message if the socket is open; a no-op otherwise. */\n send(msg: SignalMessage): void {\n if (this.ws.readyState === WebSocket.OPEN) {\n this.ws.send(JSON.stringify(msg));\n }\n }\n\n /** Closes the underlying WebSocket. */\n close(): void {\n this.ws.close();\n }\n}\n\n/** Parses a WebSocket text frame into a SignalMessage, or null if malformed. */\nfunction parseSignal(data: unknown): SignalMessage | null {\n try {\n return JSON.parse(data as string) as SignalMessage;\n } catch {\n return null;\n }\n}\n","import { SignalingChannel } from \"./signaling\";\nimport type {\n GatewayReadyInfo,\n PublisherOptions,\n PublisherRecoveryAction,\n PublisherRecoveryEvent,\n SignalMessage,\n} from \"./types\";\n\nconst defaultSignalingReconnectTimeoutMs = 20_000;\nconst signalingResumeAttemptTimeoutMs = 3_000;\nconst signalingResumeMaxBackoffMs = 3_000;\nconst senderRestartPauseMs = 100;\nconst senderRecoveryWaitMs = 4_000;\nconst iceRecoveryWaitMs = 8_000;\n\n/**\n * Publisher streams a browser {@link MediaStream} to an Argus media server over\n * WebRTC. Given the `gateway_urls` and `token` from a join-token response, it\n * races the candidate gateways to the fastest one, completes the two-phase\n * signaling handshake, and manages the peer connection — offer/answer exchange,\n * ICE candidate trickling, and track (re)negotiation.\n *\n * After {@link Publisher.start} resolves, {@link Publisher.frameReadToken} holds\n * the token your application server needs to fetch frames for this stream.\n *\n * @example Publish the default camera:\n * ```ts\n * const pub = new Publisher({\n * gatewayURLs: joinResp.gateway_urls,\n * token: joinResp.token,\n * callbacks: { onConnected: () => console.log(\"live!\") },\n * });\n *\n * const stream = await navigator.mediaDevices.getUserMedia({ video: true });\n * await pub.start(stream);\n * ```\n */\nexport class Publisher {\n private opts: PublisherOptions;\n private sig: SignalingChannel | null = null;\n private pc: RTCPeerConnection | null = null;\n private hasAnswer = false;\n private pendingRemoteCandidates: RTCIceCandidateInit[] = [];\n private localStream: MediaStream | null = null;\n private readToken: string | null = null;\n private gatewayURL: string | null = null;\n private stopped = true;\n private reconnecting = false;\n private reconnectGeneration = 0;\n private resumeSocket: WebSocket | null = null;\n private recoveryGeneration = 0;\n private recoveringMedia = false;\n private recoveryRequired = false;\n private recoveryAction: PublisherRecoveryAction | null = null;\n private trackEndHandlers = new Map<MediaStreamTrack, EventListener>();\n\n constructor(opts: PublisherOptions) {\n this.opts = opts;\n }\n\n /** The read token used for frame fetches and signaling resume in the selected region. */\n get frameReadToken(): string | null { return this.readToken; }\n\n /**\n * The signaling gateway URL that won the initial race, or null before start.\n * Relay this with frameReadToken so the application server can reach the same\n * region for frame reads and change-notification subscriptions.\n */\n get selectedGatewayURL(): string | null { return this.gatewayURL; }\n\n /**\n * Starts the publisher: races all gateways to find the fastest, completes\n * the two-phase handshake, creates the peer connection, and sends the SDP\n * offer. Resolves when the offer has been sent (not when ICE completes —\n * use onConnected for that).\n */\n async start(stream: MediaStream): Promise<void> {\n this.stopped = false;\n this.recoveryRequired = false;\n this.localStream = stream;\n this.watchStreamTracks(stream);\n\n // Race all gateways; returns winning WebSocket + TURN/read-token info\n const { ws, readyInfo, gatewayURL } = await this.raceGateways();\n this.gatewayURL = gatewayURL;\n\n // Store read token for caller\n if (readyInfo.read_token) {\n this.readToken = readyInfo.read_token;\n }\n\n // Build ICE servers: extra servers from opts + TURN from gateway. The\n // gateway supplies multi-transport turn_urls (UDP + TCP) so relay can fall\n // back to TCP on UDP-blocking networks. A single credential is valid for\n // every transport.\n const iceServers: RTCIceServer[] = [...(this.opts.iceServers ?? [])];\n if (readyInfo.turn_urls && readyInfo.turn_urls.length > 0) {\n iceServers.push({\n urls: readyInfo.turn_urls,\n username: readyInfo.turn_username,\n credential: readyInfo.turn_credential,\n });\n }\n\n this.pc = new RTCPeerConnection({ iceServers });\n\n this.pc.onicecandidate = (ev) => {\n if (!ev.candidate || !this.sig) return;\n const c = ev.candidate;\n this.sig.send({\n type: \"ice_candidate\",\n candidate: c.candidate,\n sdp_mid: c.sdpMid ?? undefined,\n sdp_mline_index: c.sdpMLineIndex ?? undefined,\n username_fragment: c.usernameFragment ?? undefined,\n });\n };\n\n this.pc.onconnectionstatechange = () => {\n const state = this.pc?.connectionState;\n if (state) this.opts.callbacks?.onConnectionStateChange?.(state);\n if (state === \"connected\") this.opts.callbacks?.onConnected?.();\n };\n\n for (const track of stream.getTracks()) {\n this.pc.addTrack(track, stream);\n }\n\n const offer = await this.pc.createOffer();\n await this.pc.setLocalDescription(offer);\n await this.gatherComplete();\n\n // Wrap winning WebSocket in SignalingChannel\n const signaling = this.installSignaling(ws);\n\n const local = this.pc.localDescription;\n if (!local) throw new Error(\"local description missing after gather\");\n signaling.send({ type: \"offer\", sdp: local.sdp, sdp_type: \"offer\" });\n }\n\n /** Replaces the currently published stream with a new one. */\n async replaceStream(stream: MediaStream): Promise<void> {\n if (!this.pc) throw new Error(\"publisher not started\");\n\n this.cancelMediaRecovery();\n this.recoveryRequired = false;\n this.unwatchStreamTracks();\n\n // Remove old tracks.\n const senders = this.pc.getSenders();\n for (const sender of senders) {\n if (sender.track) {\n this.pc.removeTrack(sender);\n }\n }\n\n // Add new tracks.\n for (const track of stream.getTracks()) {\n this.pc.addTrack(track, stream);\n }\n this.localStream = stream;\n this.watchStreamTracks(stream);\n\n await this.renegotiate(false);\n }\n\n /** Stops publishing and tears down the peer connection. */\n stop(): void {\n this.stopped = true;\n this.cancelMediaRecovery();\n this.reconnectGeneration++;\n this.reconnecting = false;\n this.resumeSocket?.close();\n this.resumeSocket = null;\n this.sig?.close();\n this.sig = null;\n\n this.unwatchStreamTracks();\n this.localStream?.getTracks().forEach((t) => t.stop());\n this.localStream = null;\n\n this.pc?.close();\n this.pc = null;\n this.hasAnswer = false;\n this.pendingRemoteCandidates = [];\n this.readToken = null;\n this.gatewayURL = null;\n }\n\n /** Returns the current RTCPeerConnection, or null if not started. */\n get peerConnection(): RTCPeerConnection | null {\n return this.pc;\n }\n\n /** Returns true if the peer connection is in the \"connected\" state. */\n get isConnected(): boolean {\n return this.pc?.connectionState === \"connected\";\n }\n\n // -------------------------------------------------------------------------\n // Private helpers\n // -------------------------------------------------------------------------\n\n private raceGateways(): Promise<{ ws: WebSocket; readyInfo: GatewayReadyInfo; gatewayURL: string }> {\n return new Promise((resolve, reject) => {\n const { gatewayURLs, token } = this.opts;\n if (gatewayURLs.length === 0) {\n reject(new Error(\"no gateway URLs provided\"));\n return;\n }\n\n const sockets: WebSocket[] = [];\n let settled = false;\n\n const closeAll = (except?: WebSocket) => {\n for (const s of sockets) {\n if (s !== except) {\n s.onmessage = null;\n s.onerror = null;\n s.onclose = null;\n s.close();\n }\n }\n };\n\n const checkAllFailed = () => {\n if (settled) return;\n if (sockets.every(s => s.readyState === WebSocket.CLOSED || s.readyState === WebSocket.CLOSING)) {\n settled = true;\n reject(new Error(\"all gateways failed to connect\"));\n }\n };\n\n for (const gatewayURL of gatewayURLs) {\n const u = new URL(gatewayURL);\n u.searchParams.set(\"token\", token);\n const ws = new WebSocket(u.toString());\n sockets.push(ws);\n\n let accepted = false;\n\n ws.onmessage = (ev: MessageEvent) => {\n if (settled) return;\n try {\n const msg = JSON.parse(ev.data as string);\n if (!accepted && msg.type === \"accepted\") {\n accepted = true;\n ws.send(JSON.stringify({ type: \"proceed\" }));\n } else if (accepted && msg.type === \"ready\") {\n settled = true;\n closeAll(ws);\n resolve({ ws, readyInfo: msg as GatewayReadyInfo, gatewayURL });\n }\n } catch {\n /* ignore malformed */\n }\n };\n\n ws.onerror = () => checkAllFailed();\n ws.onclose = () => checkAllFailed();\n }\n });\n }\n\n private installSignaling(ws: WebSocket): SignalingChannel {\n const channel = SignalingChannel.wrap(ws);\n this.sig = channel;\n channel.onMessage = (msg) => this.handleSignal(msg);\n channel.onClose = () => {\n if (this.sig !== channel || this.stopped) return;\n this.sig = null;\n void this.resumeSignaling();\n };\n // Browsers normally follow an error event with close. Recovery begins from\n // close so a single transport failure cannot start two retry loops.\n channel.onError = () => {};\n return channel;\n }\n\n private async resumeSignaling(): Promise<void> {\n if (this.reconnecting || this.stopped) return;\n if (!this.gatewayURL || !this.readToken) {\n this.terminateWithError(new Error(\"signaling closed and cannot be resumed\"));\n return;\n }\n\n this.reconnecting = true;\n const generation = ++this.reconnectGeneration;\n const timeout = this.opts.signalingReconnectTimeoutMs ?? defaultSignalingReconnectTimeoutMs;\n const deadline = Date.now() + Math.max(0, timeout);\n let backoffMs = 0;\n\n while (!this.stopped && generation === this.reconnectGeneration && Date.now() <= deadline) {\n if (backoffMs > 0) {\n const waitMs = Math.min(backoffMs, Math.max(0, deadline - Date.now()));\n if (waitMs === 0) break;\n await this.wait(waitMs);\n if (this.stopped || generation !== this.reconnectGeneration) return;\n }\n\n const remaining = deadline - Date.now();\n if (remaining < 0) break;\n try {\n const ws = await this.openResumeSocket(Math.min(signalingResumeAttemptTimeoutMs, Math.max(1, remaining)));\n if (this.stopped || generation !== this.reconnectGeneration) {\n ws.close();\n return;\n }\n this.resumeSocket = null;\n this.reconnecting = false;\n this.installSignaling(ws);\n return;\n } catch {\n backoffMs = backoffMs === 0 ? 250 : Math.min(backoffMs * 2, signalingResumeMaxBackoffMs);\n }\n }\n\n if (!this.stopped && generation === this.reconnectGeneration) {\n this.reconnecting = false;\n this.terminateWithError(new Error(\"unable to resume signaling with the selected gateway\"));\n }\n }\n\n private openResumeSocket(timeoutMs: number): Promise<WebSocket> {\n return new Promise((resolve, reject) => {\n const u = new URL(this.gatewayURL!);\n u.searchParams.set(\"token\", this.readToken!);\n const ws = new WebSocket(u.toString());\n this.resumeSocket = ws;\n let settled = false;\n const timer = setTimeout(() => fail(), timeoutMs);\n\n const fail = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n if (this.resumeSocket === ws) this.resumeSocket = null;\n ws.onmessage = null;\n ws.onerror = null;\n ws.onclose = null;\n ws.close();\n reject(new Error(\"signaling resume attempt failed\"));\n };\n\n ws.onmessage = (ev: MessageEvent) => {\n try {\n const msg = JSON.parse(ev.data as string);\n if (msg.type !== \"resumed\" || settled) return;\n settled = true;\n clearTimeout(timer);\n resolve(ws);\n } catch {\n // Ignore malformed messages while waiting for the resume acknowledgement.\n }\n };\n ws.onerror = fail;\n ws.onclose = fail;\n });\n }\n\n private wait(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n private terminateWithError(err: Error): void {\n this.stopped = true;\n this.cancelMediaRecovery();\n this.reconnectGeneration++;\n this.resumeSocket?.close();\n this.resumeSocket = null;\n this.sig?.close();\n this.sig = null;\n this.pc?.close();\n this.pc = null;\n this.unwatchStreamTracks();\n this.localStream?.getTracks().forEach((track) => track.stop());\n this.localStream = null;\n this.hasAnswer = false;\n this.pendingRemoteCandidates = [];\n this.readToken = null;\n this.gatewayURL = null;\n this.opts.callbacks?.onError?.(err);\n }\n\n private handleSignal(msg: SignalMessage): void {\n switch (msg.type) {\n case \"answer\": {\n if (!this.pc) return;\n this.pc\n .setRemoteDescription(\n new RTCSessionDescription({ type: \"answer\", sdp: msg.sdp }),\n )\n .then(() => {\n this.hasAnswer = true;\n // Flush any ICE candidates that arrived before the answer.\n for (const init of this.pendingRemoteCandidates) {\n this.pc?.addIceCandidate(init).catch(() => {\n /* ignore stale candidates */\n });\n }\n this.pendingRemoteCandidates = [];\n })\n .catch((err) => {\n this.opts.callbacks?.onError?.(\n new Error(`failed to set remote description: ${err}`),\n );\n });\n break;\n }\n\n case \"ice_candidate\": {\n if (!this.pc) return;\n const init: RTCIceCandidateInit = {\n candidate: msg.candidate,\n sdpMid: msg.sdp_mid ?? null,\n sdpMLineIndex: msg.sdp_mline_index ?? null,\n usernameFragment: msg.username_fragment ?? null,\n };\n if (this.hasAnswer) {\n this.pc.addIceCandidate(init).catch(() => {\n /* ignore stale candidates */\n });\n } else {\n this.pendingRemoteCandidates.push(init);\n }\n break;\n }\n\n case \"connection_state\": {\n // The server echoes the peer connection state; the onconnectionstatechange\n // handler above already covers this, but callers can also react via\n // onConnectionStateChange.\n break;\n }\n\n case \"media_stall\":\n case \"media_track_ended\": {\n void this.beginMediaRecovery(msg.track);\n break;\n }\n\n case \"media_resumed\": {\n this.completeMediaRecovery(msg.track);\n break;\n }\n\n case \"error\": {\n this.opts.callbacks?.onError?.(new Error(msg.error));\n break;\n }\n\n case \"resumed\":\n break;\n }\n }\n\n private async beginMediaRecovery(trackType: string): Promise<void> {\n if (this.stopped || this.recoveringMedia || this.recoveryRequired) return;\n\n const tracks = this.localStream?.getVideoTracks() ?? [];\n const liveTracks = tracks.filter((track) => track.readyState !== \"ended\");\n if (liveTracks.length === 0) {\n this.failMediaRecovery(trackType, \"capture_ended\");\n return;\n }\n\n this.recoveringMedia = true;\n const generation = ++this.recoveryGeneration;\n this.recoveryAction = \"sender_restart\";\n this.emitRecoveryTransition({ state: \"recovering\", track: trackType, action: \"sender_restart\" });\n this.sendRecoveryDiagnostic(\"recovery_started\", trackType, \"sender_restart\");\n\n await this.restartSenders(liveTracks, generation);\n if (!this.isCurrentRecovery(generation)) return;\n\n await this.wait(senderRecoveryWaitMs);\n if (!this.isCurrentRecovery(generation)) return;\n\n this.recoveryAction = \"ice_restart\";\n this.emitRecoveryTransition({ state: \"recovering\", track: trackType, action: \"ice_restart\" });\n this.sendRecoveryDiagnostic(\"recovery_retry\", trackType, \"ice_restart\");\n try {\n await this.renegotiate(true);\n } catch {\n // The fixed recovery window below still gives signaling-resume a chance.\n // If media does not recover, the host receives onRecoveryRequired.\n }\n\n await this.wait(iceRecoveryWaitMs);\n if (!this.isCurrentRecovery(generation)) return;\n this.failMediaRecovery(trackType, \"automatic_recovery_failed\");\n }\n\n private async restartSenders(tracks: MediaStreamTrack[], generation: number): Promise<void> {\n const live = new Set(tracks);\n const senders = this.pc?.getSenders().filter(\n (sender) => sender.track && live.has(sender.track),\n ) ?? [];\n if (senders.length === 0) return;\n\n const originals = senders.map((sender) => ({ sender, track: sender.track! }));\n try {\n await Promise.all(originals.map(({ sender }) => sender.replaceTrack(null)));\n await this.wait(senderRestartPauseMs);\n if (!this.isCurrentRecovery(generation)) return;\n await Promise.all(originals.map(({ sender, track }) => sender.replaceTrack(track)));\n await this.renegotiate(false);\n } catch {\n // ICE restart is the second stage and may still recover a sender reset or\n // renegotiation failure, so do not fail the stream at this stage.\n }\n }\n\n private async renegotiate(iceRestart: boolean): Promise<void> {\n const pc = this.pc;\n const signaling = this.sig;\n if (!pc || !signaling) throw new Error(\"publisher signaling is unavailable\");\n\n if (iceRestart) pc.restartIce?.();\n const offer = await pc.createOffer(iceRestart ? { iceRestart: true } : undefined);\n await pc.setLocalDescription(offer);\n await this.gatherComplete();\n\n const local = pc.localDescription;\n if (!local) throw new Error(\"local description missing\");\n this.hasAnswer = false;\n this.pendingRemoteCandidates = [];\n signaling.send({ type: \"offer\", sdp: local.sdp, sdp_type: \"offer\" });\n }\n\n private completeMediaRecovery(trackType: string): void {\n if (!this.recoveringMedia) return;\n const action = this.recoveryAction ?? undefined;\n this.cancelMediaRecovery();\n this.emitRecoveryTransition({ state: \"recovered\", track: trackType, action });\n }\n\n private failMediaRecovery(\n trackType: string,\n reason: \"capture_ended\" | \"automatic_recovery_failed\",\n ): void {\n if (this.stopped || this.recoveryRequired) return;\n this.recoveryRequired = true;\n const action = this.recoveryAction ?? undefined;\n this.cancelMediaRecovery();\n const event: PublisherRecoveryEvent = { state: \"failed\", track: trackType, action, reason };\n this.emitRecoveryTransition(event);\n this.opts.callbacks?.onRecoveryRequired?.(event);\n this.sendRecoveryDiagnostic(\"recovery_failed\", trackType, action, reason);\n }\n\n private cancelMediaRecovery(): void {\n this.recoveryGeneration++;\n this.recoveringMedia = false;\n this.recoveryAction = null;\n }\n\n private isCurrentRecovery(generation: number): boolean {\n return !this.stopped && this.recoveringMedia && generation === this.recoveryGeneration;\n }\n\n private emitRecoveryTransition(event: PublisherRecoveryEvent): void {\n this.opts.callbacks?.onRecoveryStateChange?.(event);\n }\n\n private sendRecoveryDiagnostic(\n event: \"recovery_started\" | \"recovery_retry\" | \"recovery_failed\",\n track: string,\n action?: PublisherRecoveryAction,\n reason?: \"capture_ended\" | \"automatic_recovery_failed\",\n ): void {\n this.sig?.send({ type: \"recovery_event\", event, track, action, reason });\n }\n\n private watchStreamTracks(stream: MediaStream): void {\n for (const track of stream.getVideoTracks()) {\n const handler: EventListener = () => this.failMediaRecovery(\"screen\", \"capture_ended\");\n track.addEventListener(\"ended\", handler);\n this.trackEndHandlers.set(track, handler);\n }\n }\n\n private unwatchStreamTracks(): void {\n for (const [track, handler] of this.trackEndHandlers) {\n track.removeEventListener(\"ended\", handler);\n }\n this.trackEndHandlers.clear();\n }\n\n /** Waits for ICE gathering to reach the \"complete\" state. */\n private gatherComplete(): Promise<void> {\n return new Promise((resolve) => {\n const pc = this.pc;\n if (!pc) {\n resolve();\n return;\n }\n if (pc.iceGatheringState === \"complete\") {\n resolve();\n return;\n }\n const handler = () => {\n if (pc.iceGatheringState === \"complete\") {\n pc.removeEventListener(\"icegatheringstatechange\", handler);\n resolve();\n }\n };\n pc.addEventListener(\"icegatheringstatechange\", handler);\n });\n }\n}\n","/**\n * Options for {@link captureCamera}.\n *\n * These are merged shallowly over the library defaults: any field you provide\n * replaces the default for that field entirely (e.g. passing `video` overrides\n * the default video constraints rather than merging into them). Omit a field to\n * keep its default.\n */\nexport interface CaptureCameraOptions {\n /**\n * Video constraints, or `true`/`false`. Defaults to a modest resolution and\n * frame rate (see {@link captureCamera}). Set `false` to disable video.\n */\n video?: MediaTrackConstraints | boolean;\n /**\n * Audio constraints, or `true`/`false`. Defaults to `false` — Argus is a\n * video-frame streaming system, so audio is off unless you ask for it.\n */\n audio?: MediaTrackConstraints | boolean;\n /**\n * The `MediaDevices` instance to capture from. Defaults to the global\n * `navigator.mediaDevices`. Pass another window's `navigator.mediaDevices`\n * (e.g. a Document Picture-in-Picture window's) so the browser's permission\n * prompt and transient-activation check are anchored to that window rather\n * than the one holding the global `navigator`.\n */\n mediaDevices?: MediaDevices;\n}\n\n/**\n * Options for {@link captureScreen}.\n *\n * These are merged shallowly over the library defaults: any field you provide\n * replaces the default for that field entirely. Omit a field to keep its\n * default.\n */\nexport interface CaptureScreenOptions {\n /**\n * Video constraints, or `true`. Defaults to a capped width and a low frame\n * rate (see {@link captureScreen}).\n */\n video?: MediaTrackConstraints | boolean;\n /**\n * Audio constraints, or `true`/`false`. Defaults to `false` — screen shares\n * rarely need audio for a video-frame streaming system.\n */\n audio?: MediaTrackConstraints | boolean;\n /**\n * The `MediaDevices` instance to capture from. Defaults to the global\n * `navigator.mediaDevices`. Pass another window's `navigator.mediaDevices`\n * (e.g. a Document Picture-in-Picture window's) so the screen picker and its\n * transient-activation check are anchored to that window rather than the one\n * holding the global `navigator`.\n */\n mediaDevices?: MediaDevices;\n}\n\n/**\n * Captures the user's camera via `navigator.mediaDevices.getUserMedia`,\n * applying sensible defaults for a video-frame streaming system.\n *\n * Defaults:\n * - `video`: `{ width: { ideal: 1280 }, height: { ideal: 720 }, frameRate: { ideal: 30 } }`\n * — a modest resolution that keeps upload bandwidth reasonable. Cameras are\n * rarely the 4k bandwidth problem that screen capture is, so this is an\n * `ideal` (a hint) rather than a hard cap.\n * - `audio`: `false` — this is a video-frame streaming system.\n *\n * Any option you pass replaces the corresponding default outright (shallow\n * merge), so pass a full `video` constraints object if you want to tweak it.\n *\n * @example\n * ```ts\n * const stream = await captureCamera();\n * await publisher.start(stream);\n * ```\n *\n * @example Front camera with audio:\n * ```ts\n * const stream = await captureCamera({\n * video: { facingMode: \"user\" },\n * audio: true,\n * });\n * ```\n */\nexport async function captureCamera(\n opts: CaptureCameraOptions = {},\n): Promise<MediaStream> {\n const constraints: MediaStreamConstraints = {\n video: opts.video ?? {\n width: { ideal: 1280 },\n height: { ideal: 720 },\n frameRate: { ideal: 30 },\n },\n audio: opts.audio ?? false,\n };\n const mediaDevices = opts.mediaDevices ?? navigator.mediaDevices;\n return mediaDevices.getUserMedia(constraints);\n}\n\n/**\n * Captures a screen / window / tab via\n * `navigator.mediaDevices.getDisplayMedia`, applying sensible defaults tuned to\n * avoid the HiDPI/Retina bandwidth trap.\n *\n * Defaults:\n * - `video`: `{ width: { max: 1920 }, frameRate: { ideal: 5, max: 10 } }`.\n * The `width` is a **`max`, not an `ideal`**: on a 2x-Retina display the\n * browser would otherwise capture at native resolution (often 3456px+ /\n * effectively 4k), wasting upload bandwidth and downstream decode cost for no\n * visible benefit. Capping the max roughly halves a 2x-Retina share while\n * leaving smaller displays untouched. Screen content is mostly static, so the\n * low frame rate saves further bandwidth.\n * - `audio`: `false`.\n *\n * IMPORTANT — do NOT add `resizeMode: \"none\"` here. That value forbids the\n * browser from downscaling the source, which turns the `width: { max: 1920 }`\n * cap into a no-op on exactly the Retina displays it targets. By omitting\n * `resizeMode` we let the user agent scale to satisfy the constraint (its\n * default behaviour), which is the entire point of this helper. It is tempting\n * to add `resizeMode: \"none\"` back for \"sharpness\" — don't.\n *\n * Any option you pass replaces the corresponding default outright (shallow\n * merge), so pass a full `video` constraints object if you want to tweak it.\n *\n * @example\n * ```ts\n * const stream = await captureScreen();\n * await publisher.start(stream);\n * ```\n */\nexport async function captureScreen(\n opts: CaptureScreenOptions = {},\n): Promise<MediaStream> {\n const constraints: MediaStreamConstraints = {\n video: opts.video ?? {\n width: { max: 1920 },\n frameRate: { ideal: 5, max: 10 },\n },\n audio: opts.audio ?? false,\n };\n const mediaDevices = opts.mediaDevices ?? navigator.mediaDevices;\n return mediaDevices.getDisplayMedia(constraints);\n}\n"],"mappings":";AAaO,IAAM,mBAAN,MAAM,kBAAiB;AAAA,EACpB;AAAA;AAAA,EAGR,YAAmD;AAAA;AAAA,EAEnD,UAA+B;AAAA;AAAA,EAE/B,UAAyC;AAAA,EAEjC,YAAY,IAAe;AACjC,SAAK,KAAK;AAAA,EACZ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,OAAO,KAAK,IAAiC;AAC3C,UAAM,KAAK,IAAI,kBAAiB,EAAE;AAClC,OAAG,YAAY,CAAC,OAAqB;AACnC,YAAM,MAAM,YAAY,GAAG,IAAI;AAC/B,UAAI,IAAK,IAAG,YAAY,GAAG;AAAA,IAC7B;AACA,OAAG,UAAU,MAAM,GAAG,UAAU,IAAI,MAAM,iBAAiB,CAAC;AAC5D,OAAG,UAAU,MAAM,GAAG,UAAU;AAChC,WAAO;AAAA,EACT;AAAA;AAAA,EAGA,KAAK,KAA0B;AAC7B,QAAI,KAAK,GAAG,eAAe,UAAU,MAAM;AACzC,WAAK,GAAG,KAAK,KAAK,UAAU,GAAG,CAAC;AAAA,IAClC;AAAA,EACF;AAAA;AAAA,EAGA,QAAc;AACZ,SAAK,GAAG,MAAM;AAAA,EAChB;AACF;AAGA,SAAS,YAAY,MAAqC;AACxD,MAAI;AACF,WAAO,KAAK,MAAM,IAAc;AAAA,EAClC,QAAQ;AACN,WAAO;AAAA,EACT;AACF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AAsB,YAAY;AACvC,aAAG,oBAAoB,2BAA2B,OAAO;AACzD,kBAAQ;AAAA,QACV;AAAA,MACF;AACA,SAAG,iBAAiB,2BAA2B,OAAO;AAAA,IACxD,CAAC;AAAA,EACH;AACF;;;AC9gBA,eAAsB,cACpB,OAA6B,CAAC,GACR;AACtB,QAAM,cAAsC;AAAA,IAC1C,OAAO,KAAK,SAAS;AAAA,MACnB,OAAO,EAAE,OAAO,KAAK;AAAA,MACrB,QAAQ,EAAE,OAAO,IAAI;AAAA,MACrB,WAAW,EAAE,OAAO,GAAG;AAAA,IACzB;AAAA,IACA,OAAO,KAAK,SAAS;AAAA,EACvB;AACA,QAAM,eAAe,KAAK,gBAAgB,UAAU;AACpD,SAAO,aAAa,aAAa,WAAW;AAC9C;AAiCA,eAAsB,cACpB,OAA6B,CAAC,GACR;AACtB,QAAM,cAAsC;AAAA,IAC1C,OAAO,KAAK,SAAS;AAAA,MACnB,OAAO,EAAE,KAAK,KAAK;AAAA,MACnB,WAAW,EAAE,OAAO,GAAG,KAAK,GAAG;AAAA,IACjC;AAAA,IACA,OAAO,KAAK,SAAS;AAAA,EACvB;AACA,QAAM,eAAe,KAAK,gBAAgB,UAAU;AACpD,SAAO,aAAa,gBAAgB,WAAW;AACjD;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@furious.luke/argus-js",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "description": "Browser client for the Argus video streaming platform — publish WebRTC video to Argus media servers.",
5
5
  "keywords": [
6
6
  "argus",