mediascale-sdk 1.0.5 → 1.0.6

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.
@@ -2,7 +2,7 @@
2
2
 
3
3
  One address talks to Mediascale. The default is `http://localhost:8080`.
4
4
 
5
- A person joins a session, turns on camera and microphone, hears the others, and leaves. Recording is **off by default**. Pass `recording: true` only when the host should start armed on `connect()`, or call `startRecording()` / `stopRecording()` any time during the session. Each start/stop opens a new segment; `end()` combines every segment into one file.
5
+ A person joins a session, turns on camera and microphone, hears the others, and leaves. Recording is **off by default**. Pass `recording: true` to `createClient`, or put `recording: true` on a **host** token (for example from Stream Control → Webinar → Enable recording). Recording then starts on `connect()` — no mic or camera required. You can also call `startRecording()` / `stopRecording()` any time. Each start/stop opens a new segment; `end()` combines every segment into one file.
6
6
 
7
7
  The secret that signs tokens stays on your server. The browser only receives a short-lived token.
8
8
 
@@ -42,9 +42,17 @@ export async function POST(request) {
42
42
  const sessionId = String(body.sessionId || "").trim();
43
43
  const role = body.role === "host" ? "host" : "audience";
44
44
  const name = String(body.name || "Guest").slice(0, 40);
45
+ const recording = body.recording === true || body.recording === "1" || body.recording === 1;
45
46
  if (!sessionId) return Response.json({ error: "sessionId is required" }, { status: 400 });
46
47
 
47
- const payload = { sessionId, role, name, exp: Date.now() + 2 * 60 * 60 * 1000 };
48
+ const payload = {
49
+ sessionId,
50
+ role,
51
+ name,
52
+ // Host-only: when true, createClient starts recording on connect() even if you omit recording: true.
53
+ ...(role === "host" ? { recording } : { recording: false }),
54
+ exp: Date.now() + 2 * 60 * 60 * 1000,
55
+ };
48
56
  const encoded = Buffer.from(JSON.stringify(payload)).toString("base64url");
49
57
  const signature = crypto.createHmac("sha256", secret).update(encoded).digest("base64url");
50
58
  return Response.json({ token: `${encoded}.${signature}` });
@@ -53,19 +61,29 @@ export async function POST(request) {
53
61
 
54
62
  `role` is `host` or `audience`. Both can publish. Only the host should drive recording in the UI.
55
63
 
64
+ Token claims the SDK reads:
65
+
66
+ | Claim | Meaning |
67
+ | --- | --- |
68
+ | `sessionId` | Room / webinar id (required) |
69
+ | `role` | `host` or `audience` (required) |
70
+ | `name` | Display name |
71
+ | `recording` | When `true` on a **host** token, auto-start recording on `connect()` unless `createClient({ recording: false })` |
72
+ | `exp` | Expiry as a Unix timestamp in **milliseconds** |
73
+
56
74
  ## 2. Copy the room page
57
75
 
58
76
  Copy `sdk/react-sdk/sample/app/room.js` into your app. The comments in that file are the steps.
59
77
 
60
78
  1. **Join** asks your server for a token, then calls `connect()` and `subscribe()`. The camera, microphone, and screen stay off.
61
- 2. **Camera** calls `startCamera()` or `stopCamera()`.
62
- 3. **Mic** calls `startMicrophone()` or `stopMicrophone()`.
79
+ 2. **Camera** calls `startCamera()` or `stopCamera()`. Optionally pass your own live video track, or call `replaceCameraTrack(track)` to hot-swap devices without unpublishing.
80
+ 3. **Mic** calls `startMicrophone()` or `stopMicrophone()` (and `replaceMicrophoneTrack` to switch devices smoothly).
63
81
  4. **Screen** calls `startScreenShare()` or `stopScreenShare()`.
64
- 5. **Custom stream** (optional) — see [Custom streams](#custom-streams) (`startCustomStream` / `stopCustomStream`).
65
- 6. **Record** (host) calls `startRecording()` or `stopRecording()` from the toolbar button. You can toggle any time; the final file includes every segment.
82
+ 5. **Custom stream** (optional) — see [Custom streams](#custom-streams) (`startCustomStream` / `stopCustomStream`), for example a whiteboard tab capture.
83
+ 6. **Record** (host) starts automatically when enabled on the token / `createClient`, or from the toolbar via `startRecording()` / `stopRecording()`. You can toggle any time; the final file includes every segment.
66
84
  7. **End** leaves the session and saves the recording if this person was recording.
67
85
 
68
- `recording` defaults to `false`. Set `recording: true` only when the host should already be armed when they join (the sample Record button then starts in the on state). Chunks still wait until camera, mic, or screen is live.
86
+ `recording` defaults to **false**. Set `createClient({ recording: true })` **or** put `recording: true` on the host JWT when the host should already be recording when they join (Stream Control “Enable recording” does this). Chunks start **immediately** on connect / `startRecording()` — mic and camera are not required. Until video is live, the recording canvas shows the same host placeholder as the live stage (magenta background, avatar letter, name).
69
87
 
70
88
  The room must run in the browser. `app/page.js`
71
89
 
@@ -99,12 +117,30 @@ await client.stopScreenShare();
99
117
  `startCamera()` uses the default camera at 1280×720. `startMicrophone()` uses the default microphone. Pass ids from `listDevices()` when the user should pick a device:
100
118
 
101
119
  ```js
102
- await client.startCamera({ cameraId: "device-id", resolution: "720p" });
103
- await client.startMicrophone({ micId: "device-id" });
120
+ const { cameras, microphones } = await client.listDevices();
121
+ await client.startCamera({ cameraId: cameras[0].id, resolution: "720p" });
122
+ await client.startMicrophone({ micId: microphones[0].id });
104
123
  ```
105
124
 
106
125
  `resolution` can be `"480p"`, `"720p"`, `"1080p"`, or `{ width: 1280, height: 720 }`.
107
126
 
127
+ ### Bring your own camera track
128
+
129
+ If your app already owns the camera (effects, virtual background, custom device picker), pass that live track in. The SDK publishes a **clone** and leaves your original track running.
130
+
131
+ ```js
132
+ const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false });
133
+ const track = stream.getVideoTracks()[0];
134
+
135
+ await client.startCamera({ track });
136
+
137
+ // later — swap without republishing (smooth device switch)
138
+ await client.replaceCameraTrack(nextTrack);
139
+ await client.replaceMicrophoneTrack(nextMicTrack);
140
+ ```
141
+
142
+ `replaceCameraTrack` / `replaceMicrophoneTrack` swap media on the **existing producer** (no unpublish). Use these for smooth device switching while live.
143
+
108
144
  The SFU origin caps each publisher’s uplink at **2500 Kbps** (`MAX_PUBLISH_BITRATE_BPS`) via `setMaxIncomingBitrate` on the send transport.
109
145
 
110
146
  Toggle recording during the session:
@@ -120,12 +156,14 @@ await client.end(); // combines every segment into one file
120
156
 
121
157
  | Function | What it does |
122
158
  | --- | --- |
123
- | `createClient({ endpoint, sessionId, token, recording, iceServers, ...callbacks })` | Prepares the client. `sessionId` and `token` are required. `endpoint` defaults to `http://localhost:8080`. `recording` defaults to **false**. |
124
- | `connect()` | Checks the token and joins the session. If `recording` is true and the token role is `host`, recording is armed (same as calling `startRecording()`). |
159
+ | `createClient({ endpoint, sessionId, token, recording, iceServers, ...callbacks })` | Prepares the client. `sessionId` and `token` are required. `endpoint` defaults to `http://localhost:8080`. `recording` defaults to **false**. If you omit `recording` (or pass anything other than `false`) and the host token has `recording: true`, auto-start is still enabled. Pass `recording: false` to force off. |
160
+ | `connect()` | Checks the token and joins the session. If recording is enabled for a **host**, recording starts immediately in the background (same as `startRecording()`). Join does not wait for capture to finish preparing. |
125
161
  | `subscribe()` | Starts playing the other people. Call this once after `connect()`. |
126
- | `startCamera({ cameraId, resolution })` | Publishes the camera. Both arguments are optional. |
127
- | `stopCamera()` | Stops the camera. The person stays in the session. |
162
+ | `startCamera({ cameraId, resolution, track })` | Publishes the camera. Pass `track` to use your own live video track (SDK clones it). |
163
+ | `replaceCameraTrack(track)` | Hot-swaps the live camera producer with a new live video track (SDK clones it). No unpublish. Camera must already be started. |
164
+ | `stopCamera()` | Stops the camera. The person stays in the session. Caller-owned original tracks are not stopped. |
128
165
  | `startMicrophone({ micId })` | Publishes the microphone. `micId` is optional. |
166
+ | `replaceMicrophoneTrack(track)` | Hot-swaps the live mic producer with a new live audio track (SDK clones it). No unpublish. Mic must already be started. |
129
167
  | `stopMicrophone()` | Stops the microphone. |
130
168
  | `startScreenShare()` | Shares the screen. Anyone in the session can call this. |
131
169
  | `stopScreenShare()` | Stops the screen share. |
@@ -133,7 +171,7 @@ await client.end(); // combines every segment into one file
133
171
  | `stopCustomStream(identifier)` | Stops that custom stream. |
134
172
  | `publish({ cameraId, micId, resolution })` | Turns on the camera and the microphone together. |
135
173
  | `stop()` | Turns off the camera and the microphone. The screen share stays on. |
136
- | `startRecording()` | Arms recording for this person (or resumes after `stopRecording()`). Chunks upload only while webcam, mic, or screen is live. Also used when the host left and a cohost should continue the same file. |
174
+ | `startRecording()` | Starts recording for this person (or resumes after `stopRecording()`). Chunks upload immediately — mic/camera not required. Empty stage uses the host placeholder tile until real video is published. Also used when the host left and a cohost should continue the same file. |
137
175
  | `stopRecording()` | Pauses recording without saving. Call `startRecording()` again to continue; `end()` still combines all segments into one file. |
138
176
  | `end()` | Leaves the session. If this person is the one recording, every segment is combined and saved. |
139
177
  | `listDevices()` | Returns `{ cameras, microphones }`. Each item is `{ id, label }`. |
@@ -150,7 +188,7 @@ Pass these to `createClient`.
150
188
  | `onTrackEnded({ producerId })` | That media stopped. Remove the element. |
151
189
  | `onStatus(text)` | `Joining`, `Ready`, `Live`, `Network unstable`, `Ended`, or an error message. |
152
190
  | `onError(error)` | A call failed. `error.message` is the reason. The same call also throws, so `await` can use `try/catch`. |
153
- | `onRecording(state)` | `armed` when recording is on but waiting for live media. `recording` while chunks are uploading. `stopped` after `stopRecording()`, handoff, or `end()`. |
191
+ | `onRecording(state)` | `armed` briefly while capture is preparing. `recording` while chunks are uploading. `stopped` after `stopRecording()`, handoff, or `end()`. |
154
192
  | `onActiveSpeaker({ peerId, displayName, producerId, local })` | Fires when the loudest mic in the room changes. `peerId` is `null` when nobody is speaking. `local` is true when it is this browser. Requires `ACTIVE_SPEAKER_DETECTION=true` on the origin SFU and portal. |
155
193
 
156
194
  ## Active speaker
@@ -191,6 +229,8 @@ Publish any `MediaStreamTrack` under your own id. Subscribers get that same id a
191
229
 
192
230
  Reserved ids (use the dedicated APIs instead): `webcam`, `mic`, `screen`.
193
231
 
232
+ Custom **video** sources (for example `whiteboard`) use the large featured layout slot in the recording compositor, like screen share.
233
+
194
234
  ### Whiteboard example
195
235
 
196
236
  **Publish** — show your whiteboard UI, capture this tab, send the video track:
@@ -231,14 +271,45 @@ Optional: broadcast the publisher’s whiteboard DOM bounds (normalized `x,y,w,h
231
271
 
232
272
  ## Recording
233
273
 
234
- - `recording` defaults to **false**. No recording starts unless you pass `recording: true` or call `startRecording()`.
235
- - The sample host toolbar has a Record button. If the host joined with `recording: true`, that button starts in the on state. The host can turn it off and on any time.
274
+ ### When it starts
275
+
276
+ - `recording` defaults to **false**. Nothing records unless you enable it.
277
+ - Enable with any of:
278
+ - `createClient({ recording: true })` and a host token, or
279
+ - a **host** JWT with `recording: true` (Stream Control Webinar → Enable recording), or
280
+ - a manual `startRecording()` call during the session.
281
+ - Pass `createClient({ recording: false })` to force recording off even if the host token says `recording: true`.
282
+ - On host `connect()`, auto-start runs in the background and does **not** block join.
283
+
284
+ ### What gets recorded
285
+
286
+ - Chunks upload as soon as recording starts — **mic and camera are not required**.
287
+ - With no live video, the canvas matches the live empty stage: magenta radial background, circular avatar with the host’s first letter, and a `Name (You)` label. The recording keeps going on that placeholder until real media appears.
288
+ - When webcam, screen, or a featured custom video (for example whiteboard) is published, those tiles replace the placeholder in the layout (up to four cameras; screen/custom video takes the main area).
289
+ - Local + remote mics (and screen audio) are mixed when available. If the browser leaves `AudioContext` suspended, silence is recorded until the first click/key in the tab unlocks audio mixing.
236
290
  - `stopRecording()` only pauses. It does not upload a finished file. `startRecording()` afterward opens a new segment under the same recording id.
237
291
  - `end()` (or idle finalize when everybody has left) combines every segment into **one** playable file.
238
- - Chunks upload only while webcam, mic, or screen share is live. The red `REC` pill means chunks are flowing; an armed-but-idle session keeps the Record button on without the pill.
292
+ - The sample host toolbar has a Record button. If recording was enabled at join, that button starts in the on state. The red `REC` pill means chunks are flowing (`onRecording("recording")`).
239
293
  - The file keeps going when another person calls `startRecording()` after a handoff. Ask them to start before the previous recorder calls `end()`.
240
294
  - If everybody leaves, the recording is still saved after a few minutes of silence.
241
295
 
296
+ ### Background-safe compositing
297
+
298
+ Recording prefers a **worker / OffscreenCanvas** compositor so frames keep flowing when the tab is backgrounded. If the browser cannot probe that path, it falls back to the foreground canvas compositor.
299
+
300
+ Listen for mode / failure events if your UI needs them:
301
+
302
+ ```js
303
+ window.addEventListener("mediascale:recording-mode", (event) => {
304
+ // event.detail.mode === "worker" | "foreground"
305
+ // event.detail.reason is set when falling back
306
+ });
307
+
308
+ window.addEventListener("mediascale:recording-error", (event) => {
309
+ // event.detail.message — worker stopped or capture failed; call startRecording() again
310
+ });
311
+ ```
312
+
242
313
  ## Run the sample
243
314
 
244
315
  ```bash
@@ -250,3 +321,5 @@ npm run dev
250
321
  Open http://localhost:3200. The page asks your Next.js server for a token, then joins http://localhost:8080.
251
322
 
252
323
  Set `SDK_SECRET` in the environment before `npm run dev`. `MEDASCALE_ENDPOINT` is optional. The sample uses it when it is set, and otherwise uses `http://localhost:8080`.
324
+
325
+ With the full local stack (`deploy/local`), the sample is also served behind the gateway at `/meet`. Stream Control → Webinar can mint host/invite links with `recording` set from the Enable recording toggle.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mediascale-sdk",
3
- "version": "1.0.5",
3
+ "version": "1.0.6",
4
4
  "description": "Mediascale React/browser SDK for live sessions, WebRTC publish/subscribe, and recording",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/client.js CHANGED
@@ -58,7 +58,6 @@ export function createClient(options = {}) {
58
58
  const endpoint = String(options.endpoint || "http://localhost:8080").replace(/\/+$/, "");
59
59
  const sessionId = String(options.sessionId || "").trim();
60
60
  const token = String(options.token || "").trim();
61
- const recording = options.recording === true;
62
61
  const iceOverride = Array.isArray(options.iceServers) ? options.iceServers : null;
63
62
  const onTrack = options.onTrack || (() => {});
64
63
  const onTrackEnded = options.onTrackEnded || (() => {});
@@ -71,6 +70,9 @@ export function createClient(options = {}) {
71
70
  if (!token) throw new Error("token is required");
72
71
  const claims = readToken(token);
73
72
  if (claims.sessionId !== sessionId) throw new Error("token is for a different session");
73
+ // Explicit option wins; otherwise honor recording flag embedded in the host token.
74
+ const recording = options.recording === true
75
+ || (options.recording !== false && claims.recording === true && claims.role === "host");
74
76
 
75
77
  const displayName = String(claims.name || "Guest").slice(0, 40);
76
78
  let socket = null;
@@ -145,11 +147,34 @@ export function createClient(options = {}) {
145
147
  }
146
148
  }
147
149
 
150
+ function requireLiveTrack(track, kind) {
151
+ if (!track || track.kind !== kind || track.readyState !== "live" || typeof track.clone !== "function") {
152
+ throw new Error(`Expected a live ${kind} track`);
153
+ }
154
+ }
155
+
156
+ function detachEnded(entry) {
157
+ entry.track.removeEventListener("ended", entry.onEnded);
158
+ if (entry.original !== entry.track) entry.original.removeEventListener("ended", entry.onEnded);
159
+ }
160
+
161
+ function attachEnded(producerId, entry) {
162
+ const track = entry.track;
163
+ entry.onEnded = () => {
164
+ if (closed || locals.get(producerId) !== entry || entry.track !== track) return;
165
+ if (entry.source === "screen") stopScreenShare().catch(() => {});
166
+ else unpublish(producerId).catch(() => {});
167
+ };
168
+ track.addEventListener("ended", entry.onEnded);
169
+ if (entry.original !== track) entry.original.addEventListener("ended", entry.onEnded);
170
+ }
171
+
148
172
  async function unpublish(producerId) {
149
173
  const entry = locals.get(producerId);
150
174
  if (!entry) return;
151
175
  locals.delete(producerId);
152
176
  tiles.delete(producerId);
177
+ detachEnded(entry);
153
178
  entry.track.stop();
154
179
  entry.producer.close();
155
180
  syncRecording();
@@ -157,10 +182,21 @@ export function createClient(options = {}) {
157
182
  if (socket?.connected) await emit(socket, "closeProducer", { producerId }).catch(() => {});
158
183
  }
159
184
 
160
- async function produce(source, track) {
161
- const producer = await sendTransport.produce({ track, appData: { source } });
185
+ // Camera inputs use an SDK-owned clone. Custom inputs keep upstream direct ownership.
186
+ async function produce(source, track, original = track) {
187
+ let producer;
188
+ try {
189
+ producer = await sendTransport.produce({ track, stopTracks: false, appData: { source } });
190
+ if (closed) throw new Error("The session has ended");
191
+ if (track.readyState === "ended" || original.readyState === "ended") throw new Error("The source track ended");
192
+ } catch (error) {
193
+ producer?.close();
194
+ track.stop();
195
+ throw error;
196
+ }
162
197
  const stream = new MediaStream([track]);
163
- locals.set(producer.id, { producer, track, source });
198
+ const entry = { producer, track, original, source };
199
+ locals.set(producer.id, entry);
164
200
  tiles.set(producer.id, {
165
201
  producerId: producer.id,
166
202
  publisherId: "local",
@@ -170,10 +206,7 @@ export function createClient(options = {}) {
170
206
  stream,
171
207
  local: true,
172
208
  });
173
- track.onended = () => {
174
- if (source === "screen") stopScreenShare().catch(() => {});
175
- else unpublish(producer.id).catch(() => {});
176
- };
209
+ attachEnded(producer.id, entry);
177
210
  syncRecording();
178
211
  return { producerId: producer.id, stream, source };
179
212
  }
@@ -297,13 +330,9 @@ export function createClient(options = {}) {
297
330
  if (joined.waiting) onStatus("Please wait, we will connect you soon");
298
331
  else onStatus("Ready");
299
332
  if (closed) return;
300
- // Recording must not block join — claim/start can fail before media is published.
333
+ // Do not await: AudioContext may need a click in this tab before chunks flow.
301
334
  if (recording && claims.role === "host") {
302
- try {
303
- await startRecording();
304
- } catch (error) {
305
- onError(error);
306
- }
335
+ startRecording().catch((error) => onError(error));
307
336
  }
308
337
  if (closed) return;
309
338
  settleReady?.();
@@ -317,22 +346,60 @@ export function createClient(options = {}) {
317
346
  return readyPromise;
318
347
  }
319
348
 
320
- async function startCamera({ cameraId, resolution } = {}) {
349
+ async function startCamera({ cameraId, resolution, track } = {}) {
350
+ if (track !== undefined) requireLiveTrack(track, "video");
321
351
  await connect();
352
+ if (closed) throw new Error("The session has ended");
322
353
  if (!sendTransport) throw new Error("The session is not ready");
323
354
  await stopCamera();
355
+ if (track !== undefined) return produce("webcam", track.clone(), track);
324
356
  const stream = await navigator.mediaDevices.getUserMedia({
325
357
  video: videoConstraint(cameraId, resolution),
326
358
  audio: false,
327
359
  });
328
- const track = stream.getVideoTracks()[0];
329
- if (!track) throw new Error("No camera was found");
360
+ const captured = stream.getVideoTracks()[0];
361
+ if (!captured) {
362
+ stream.getTracks().forEach((item) => item.stop());
363
+ throw new Error("No camera was found");
364
+ }
365
+ return produce("webcam", captured);
366
+ }
367
+
368
+ async function replaceLocalTrack(source, track, kind) {
369
+ requireLiveTrack(track, kind);
370
+ if (closed) throw new Error("The session has ended");
371
+ const current = [...locals].find(([, entry]) => entry.source === source);
372
+ if (!current) throw new Error(source === "webcam" ? "The camera is not started" : "The microphone is not started");
373
+ const [producerId, entry] = current;
374
+ const replacement = track.clone();
330
375
  try {
331
- return await produce("webcam", track);
376
+ await entry.producer.replaceTrack({ track: replacement });
377
+ if (closed || locals.get(producerId) !== entry) {
378
+ throw new Error(source === "webcam" ? "The camera is not started" : "The microphone is not started");
379
+ }
332
380
  } catch (error) {
333
- track.stop();
381
+ replacement.stop();
334
382
  throw error;
335
383
  }
384
+ const previous = entry.track;
385
+ const previousOriginal = entry.original;
386
+ detachEnded(entry);
387
+ entry.track = replacement;
388
+ entry.original = track;
389
+ const stream = tiles.get(producerId).stream;
390
+ stream.removeTrack(previous);
391
+ stream.addTrack(replacement);
392
+ attachEnded(producerId, entry);
393
+ syncRecording();
394
+ previous.stop();
395
+ if (previousOriginal && previousOriginal !== previous && previousOriginal !== track) {
396
+ previousOriginal.stop();
397
+ }
398
+ return { producerId, stream, source };
399
+ }
400
+
401
+ async function replaceCameraTrack(track) {
402
+ return replaceLocalTrack("webcam", track, "video");
336
403
  }
337
404
 
338
405
  async function stopCamera() {
@@ -350,12 +417,11 @@ export function createClient(options = {}) {
350
417
  const stream = await navigator.mediaDevices.getUserMedia({ audio, video: false });
351
418
  const track = stream.getAudioTracks()[0];
352
419
  if (!track) throw new Error("No microphone was found");
353
- try {
354
- return await produce("mic", track);
355
- } catch (error) {
356
- track.stop();
357
- throw error;
358
- }
420
+ return produce("mic", track);
421
+ }
422
+
423
+ async function replaceMicrophoneTrack(track) {
424
+ return replaceLocalTrack("mic", track, "audio");
359
425
  }
360
426
 
361
427
  async function stopMicrophone() {
@@ -466,7 +532,7 @@ export function createClient(options = {}) {
466
532
  onRecording("stopped");
467
533
  return;
468
534
  }
469
- // "recording" while chunks flow; "armed" while enabled but waiting for live A/V/screen.
535
+ // "recording" while chunks flow; "armed" briefly while prepare/beginCapture catches up.
470
536
  onRecording(next.capturing ? "recording" : "armed");
471
537
  }
472
538
 
@@ -489,18 +555,26 @@ export function createClient(options = {}) {
489
555
  recordingId: await recordingIdFor(sessionId),
490
556
  endpoint,
491
557
  token,
492
- // Chunks only flow while webcam / mic / screenshare is live.
558
+ selfName: displayName,
559
+ // Chunks start immediately; empty stage uses the same host placeholder as live UI.
493
560
  onCaptureChange: () => notifyRecording(next),
561
+ onFailure: (error) => {
562
+ if (recorder !== next) return;
563
+ recorder = null;
564
+ onRecording("stopped");
565
+ onError(error);
566
+ },
494
567
  });
495
568
  recorder = next;
496
569
  next.wanted = true;
570
+ notifyRecording(next);
497
571
  next.sync(tracksFromTiles([...tiles.values()]));
498
572
  try {
499
573
  await next.start();
500
- } catch {
574
+ } catch (error) {
501
575
  if (recorder === next) recorder = null;
502
576
  onRecording("stopped");
503
- return;
577
+ throw error instanceof Error ? error : new Error(String(error));
504
578
  }
505
579
  if (recorder !== next) return;
506
580
  notifyRecording(next);
@@ -524,27 +598,35 @@ export function createClient(options = {}) {
524
598
  settleReady?.(new Error("Ended"));
525
599
  const current = recorder;
526
600
  recorder = null;
527
- if (current) {
528
- let handoff = false;
529
- if (socket?.connected) {
530
- try {
531
- const result = await emit(socket, "leaveRecording", {});
532
- handoff = Boolean(result?.handoff);
533
- } catch {
534
- handoff = false;
601
+ try {
602
+ if (current) {
603
+ let handoff = false;
604
+ if (socket?.connected) {
605
+ try {
606
+ const result = await emit(socket, "leaveRecording", {});
607
+ handoff = Boolean(result?.handoff);
608
+ } catch {
609
+ handoff = false;
610
+ }
535
611
  }
612
+ // Cohost continues the same recordingId; only finalize when nobody else can take over.
613
+ if (handoff) await current.handoff();
614
+ else await current.finish();
615
+ onRecording("stopped");
536
616
  }
537
- // Cohost continues the same recordingId; only finalize when nobody else can take over.
538
- if (handoff) await current.handoff();
539
- else await current.finish();
540
- onRecording("stopped");
617
+ } finally {
618
+ for (const entry of locals.values()) {
619
+ detachEnded(entry);
620
+ entry.track.stop();
621
+ entry.producer.close();
622
+ }
623
+ locals.clear();
624
+ sendTransport?.close();
625
+ recvTransport?.close();
626
+ socket?.close();
627
+ onStatus("Ended");
628
+ tiles.clear();
541
629
  }
542
- for (const entry of locals.values()) entry.track.stop();
543
- locals.clear();
544
- sendTransport?.close();
545
- recvTransport?.close();
546
- socket?.close();
547
- onStatus("Ended");
548
630
  }
549
631
 
550
632
  async function listDevices() {
@@ -572,8 +654,10 @@ export function createClient(options = {}) {
572
654
  publish: guard(publish),
573
655
  stop: guard(stop),
574
656
  startCamera: guard(startCamera),
657
+ replaceCameraTrack: guard(replaceCameraTrack),
575
658
  stopCamera: guard(stopCamera),
576
659
  startMicrophone: guard(startMicrophone),
660
+ replaceMicrophoneTrack: guard(replaceMicrophoneTrack),
577
661
  stopMicrophone: guard(stopMicrophone),
578
662
  startScreenShare: guard(startScreenShare),
579
663
  stopScreenShare: guard(stopScreenShare),
package/src/index.js CHANGED
@@ -1 +1,2 @@
1
1
  export { createClient } from "./client.js";
2
+ export { FrameCompositor } from "./record-frame-compositor.js";
@@ -0,0 +1,137 @@
1
+ let nextRequest = 0;
2
+
3
+ function request(worker, message, transfer = [], timeoutMs = 3000) {
4
+ return new Promise((resolve, reject) => {
5
+ const requestId = ++nextRequest;
6
+ const finish = (failure, data) => {
7
+ clearTimeout(timer);
8
+ worker.removeEventListener("message", receive);
9
+ worker.removeEventListener("error", failed);
10
+ failure ? reject(failure) : resolve(data);
11
+ };
12
+ const receive = ({ data }) => {
13
+ if (data.type === "error") finish(new Error(data.message));
14
+ else if (data.requestId === requestId) finish(null, data);
15
+ };
16
+ const failed = () => finish(new Error("Recording worker could not start"));
17
+ const timer = setTimeout(() => finish(new Error("Recording frame transfer probe timed out")), timeoutMs);
18
+ worker.addEventListener("message", receive);
19
+ worker.addEventListener("error", failed);
20
+ try { worker.postMessage({ ...message, requestId }, transfer); }
21
+ catch (failure) { finish(failure); }
22
+ });
23
+ }
24
+
25
+ function bounded(promise, timeoutMs) {
26
+ let timer;
27
+ return Promise.race([promise, new Promise((_, reject) => {
28
+ timer = setTimeout(() => reject(new Error("Recording frame transfer probe timed out")), timeoutMs);
29
+ })]).finally(() => clearTimeout(timer));
30
+ }
31
+
32
+ /** Probe real frame transfer before selecting the background-capable compositor. */
33
+ export async function createWorkerCompositor({ width, height, fps, onError = () => {} }) {
34
+ let worker, output, probeInput, probeClone, outputProbe, reader, inputWriter, probeFrame;
35
+ const deadline = Date.now() + 3000;
36
+ const remaining = () => Math.max(1, deadline - Date.now());
37
+ const ask = (message, transfer = []) => request(worker, message, transfer, remaining());
38
+ try {
39
+ if (typeof Worker !== "function" || typeof OffscreenCanvas !== "function" || typeof VideoFrame !== "function") throw new Error("Native recording frame APIs are unavailable");
40
+ worker = new Worker(new URL("./record-worker.js", import.meta.url), { type: "module" });
41
+ const { standard } = await ask({ type: "capabilities" });
42
+ if (standard) {
43
+ const ready = await ask({ type: "init", standard: true, width, height, fps });
44
+ output = ready.track;
45
+ const canvas = document.createElement("canvas");
46
+ canvas.width = canvas.height = 2;
47
+ probeInput = canvas.captureStream(0).getVideoTracks()[0];
48
+ const probing = ask({ type: "probe", track: probeInput }, [probeInput]);
49
+ canvas.getContext("2d").fillRect(0, 0, 2, 2);
50
+ probeInput.requestFrame?.();
51
+ await probing;
52
+ } else {
53
+ if (typeof MediaStreamTrackProcessor !== "function" || typeof MediaStreamTrackGenerator !== "function") throw new Error("Native recording track processor/generator are unavailable");
54
+ output = new MediaStreamTrackGenerator({ kind: "video" });
55
+ await ask({ type: "init", width, height, fps, writable: output.writable }, [output.writable]);
56
+ outputProbe = output.clone();
57
+ reader = new MediaStreamTrackProcessor({ track: outputProbe, maxBufferSize: 1 }).readable.getReader();
58
+ const received = reader.read();
59
+ probeInput = new MediaStreamTrackGenerator({ kind: "video" });
60
+ probeClone = probeInput.clone();
61
+ const readable = new MediaStreamTrackProcessor({ track: probeClone, maxBufferSize: 1 }).readable;
62
+ const probing = ask({ type: "probe", readable }, [readable]);
63
+ // Construction/write failures must still consume the outstanding probe rejection.
64
+ void probing.catch(() => {});
65
+ inputWriter = probeInput.writable.getWriter();
66
+ const surface = new OffscreenCanvas(2, 2);
67
+ surface.getContext("2d").fillRect(0, 0, 2, 2);
68
+ probeFrame = new VideoFrame(surface, { timestamp: 0 });
69
+ await bounded(Promise.all([inputWriter.write(probeFrame), probing]), remaining());
70
+ probeFrame.close();
71
+ probeFrame = null;
72
+ inputWriter.releaseLock();
73
+ inputWriter = null;
74
+ const { value, done } = await bounded(received, remaining());
75
+ if (done || !value?.displayWidth) throw new Error("Recording output frame probe produced no video");
76
+ value.close();
77
+ }
78
+ let active = false, closed = false, sources = [];
79
+ const owned = new Map();
80
+ const release = (entry) => { try { entry.clone.stop(); } catch {} };
81
+ const sync = () => {
82
+ const desired = active ? sources : [];
83
+ const keys = new Set(desired.map((source) => source.key));
84
+ for (const [key, entry] of owned) if (!keys.has(key)) { release(entry); owned.delete(key); }
85
+ const transfer = [];
86
+ const updates = desired.map(({ key, track, rect }) => {
87
+ const previous = owned.get(key);
88
+ if (previous?.original === track) return { key, rect };
89
+ if (previous) release(previous);
90
+ const clone = track.clone();
91
+ owned.set(key, { clone, original: track });
92
+ if (standard) { transfer.push(clone); return { key, rect, track: clone }; }
93
+ const readable = new MediaStreamTrackProcessor({ track: clone, maxBufferSize: 1 }).readable;
94
+ transfer.push(readable);
95
+ return { key, rect, readable };
96
+ });
97
+ worker.postMessage({ type: "sources", sources: updates }, transfer);
98
+ };
99
+ worker.addEventListener("message", ({ data }) => { if (!closed && data.type === "error") onError(new Error(data.message)); });
100
+ worker.addEventListener("error", () => { if (!closed) onError(new Error("Recording worker stopped unexpectedly")); });
101
+ const compositor = {
102
+ track: output,
103
+ setSources(next) {
104
+ if (closed) return;
105
+ sources = next;
106
+ try { sync(); } catch (failure) { onError(failure); }
107
+ },
108
+ setActive(next) {
109
+ if (closed || active === next) return;
110
+ active = next;
111
+ worker.postMessage({ type: "active", active });
112
+ try { sync(); } catch (failure) { onError(failure); }
113
+ },
114
+ close() {
115
+ if (closed) return;
116
+ closed = true;
117
+ for (const entry of owned.values()) release(entry);
118
+ owned.clear();
119
+ // Give the standard worker ownership cleanup before termination.
120
+ worker.postMessage({ type: "close" });
121
+ setTimeout(() => worker.terminate(), 100);
122
+ output.stop();
123
+ },
124
+ };
125
+ return { compositor, reason: null };
126
+ } catch (failure) {
127
+ worker?.terminate();
128
+ output?.stop();
129
+ return { compositor: null, reason: failure?.message || "Native recording frame transfer is unavailable" };
130
+ } finally {
131
+ probeFrame?.close();
132
+ try { void inputWriter?.abort().catch(() => {}); inputWriter?.releaseLock(); } catch {}
133
+ try { void reader?.cancel().then(() => reader.releaseLock()).catch(() => {}); } catch {}
134
+ outputProbe?.stop();
135
+ try { probeInput?.stop(); probeClone?.stop(); } catch {}
136
+ }
137
+ }