mediascale-sdk 1.0.4 → 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.
- package/docs/integration.md +140 -20
- package/package.json +1 -1
- package/src/client.js +178 -47
- package/src/index.js +1 -0
- package/src/record-compositor.js +137 -0
- package/src/record-frame-compositor.js +83 -0
- package/src/record-worker.js +89 -0
- package/src/record.js +300 -90
package/docs/integration.md
CHANGED
|
@@ -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`
|
|
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 = {
|
|
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,18 +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. **
|
|
65
|
-
6. **
|
|
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.
|
|
84
|
+
7. **End** leaves the session and saves the recording if this person was recording.
|
|
66
85
|
|
|
67
|
-
`recording` defaults to
|
|
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).
|
|
68
87
|
|
|
69
88
|
The room must run in the browser. `app/page.js`
|
|
70
89
|
|
|
@@ -98,12 +117,30 @@ await client.stopScreenShare();
|
|
|
98
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:
|
|
99
118
|
|
|
100
119
|
```js
|
|
101
|
-
|
|
102
|
-
await client.
|
|
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 });
|
|
103
123
|
```
|
|
104
124
|
|
|
105
125
|
`resolution` can be `"480p"`, `"720p"`, `"1080p"`, or `{ width: 1280, height: 720 }`.
|
|
106
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
|
+
|
|
107
144
|
The SFU origin caps each publisher’s uplink at **2500 Kbps** (`MAX_PUBLISH_BITRATE_BPS`) via `setMaxIncomingBitrate` on the send transport.
|
|
108
145
|
|
|
109
146
|
Toggle recording during the session:
|
|
@@ -119,23 +156,27 @@ await client.end(); // combines every segment into one file
|
|
|
119
156
|
|
|
120
157
|
| Function | What it does |
|
|
121
158
|
| --- | --- |
|
|
122
|
-
| `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**. |
|
|
123
|
-
| `connect()` | Checks the token and joins the session. If
|
|
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. |
|
|
124
161
|
| `subscribe()` | Starts playing the other people. Call this once after `connect()`. |
|
|
125
|
-
| `startCamera({ cameraId, resolution })` | Publishes the camera.
|
|
126
|
-
| `
|
|
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. |
|
|
127
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. |
|
|
128
167
|
| `stopMicrophone()` | Stops the microphone. |
|
|
129
168
|
| `startScreenShare()` | Shares the screen. Anyone in the session can call this. |
|
|
130
169
|
| `stopScreenShare()` | Stops the screen share. |
|
|
170
|
+
| `startCustomStream(identifier, track, type)` | Publishes a custom `MediaStreamTrack`. `type` is `"audio"` or `"video"`. Reserved ids: `webcam`, `mic`, `screen`. |
|
|
171
|
+
| `stopCustomStream(identifier)` | Stops that custom stream. |
|
|
131
172
|
| `publish({ cameraId, micId, resolution })` | Turns on the camera and the microphone together. |
|
|
132
173
|
| `stop()` | Turns off the camera and the microphone. The screen share stays on. |
|
|
133
|
-
| `startRecording()` |
|
|
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. |
|
|
134
175
|
| `stopRecording()` | Pauses recording without saving. Call `startRecording()` again to continue; `end()` still combines all segments into one file. |
|
|
135
176
|
| `end()` | Leaves the session. If this person is the one recording, every segment is combined and saved. |
|
|
136
177
|
| `listDevices()` | Returns `{ cameras, microphones }`. Each item is `{ id, label }`. |
|
|
137
178
|
|
|
138
|
-
Call `connect`, then `subscribe`. Call `startCamera`, `startMicrophone`, or `
|
|
179
|
+
Call `connect`, then `subscribe`. Call `startCamera`, `startMicrophone`, `startScreenShare`, or `startCustomStream` only when that button is pressed. Call the matching stop function to turn that input off. Call `end` when the person leaves.
|
|
139
180
|
|
|
140
181
|
## Callbacks
|
|
141
182
|
|
|
@@ -143,11 +184,11 @@ Pass these to `createClient`.
|
|
|
143
184
|
|
|
144
185
|
| Callback | When it runs |
|
|
145
186
|
| --- | --- |
|
|
146
|
-
| `onTrack({ producerId, peerId, source, kind, displayName, stream })` |
|
|
187
|
+
| `onTrack({ producerId, peerId, source, kind, displayName, stream })` | Remote media ready. `source` is `webcam`, `mic`, `screen`, or a custom id (e.g. `whiteboard`). |
|
|
147
188
|
| `onTrackEnded({ producerId })` | That media stopped. Remove the element. |
|
|
148
189
|
| `onStatus(text)` | `Joining`, `Ready`, `Live`, `Network unstable`, `Ended`, or an error message. |
|
|
149
190
|
| `onError(error)` | A call failed. `error.message` is the reason. The same call also throws, so `await` can use `try/catch`. |
|
|
150
|
-
| `onRecording(state)` | `armed`
|
|
191
|
+
| `onRecording(state)` | `armed` briefly while capture is preparing. `recording` while chunks are uploading. `stopped` after `stopRecording()`, handoff, or `end()`. |
|
|
151
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. |
|
|
152
193
|
|
|
153
194
|
## Active speaker
|
|
@@ -182,16 +223,93 @@ const client = createClient({
|
|
|
182
223
|
|
|
183
224
|
The sample room highlights the speaking camera tile (and strip card) with a cyan border. Screen-share tiles are not marked as speaking.
|
|
184
225
|
|
|
226
|
+
## Custom streams
|
|
227
|
+
|
|
228
|
+
Publish any `MediaStreamTrack` under your own id. Subscribers get that same id as `onTrack.source`.
|
|
229
|
+
|
|
230
|
+
Reserved ids (use the dedicated APIs instead): `webcam`, `mic`, `screen`.
|
|
231
|
+
|
|
232
|
+
Custom **video** sources (for example `whiteboard`) use the large featured layout slot in the recording compositor, like screen share.
|
|
233
|
+
|
|
234
|
+
### Whiteboard example
|
|
235
|
+
|
|
236
|
+
**Publish** — show your whiteboard UI, capture this tab, send the video track:
|
|
237
|
+
|
|
238
|
+
```js
|
|
239
|
+
const capture = await navigator.mediaDevices.getDisplayMedia({
|
|
240
|
+
video: true,
|
|
241
|
+
audio: false,
|
|
242
|
+
preferCurrentTab: true,
|
|
243
|
+
selfBrowserSurface: "include",
|
|
244
|
+
});
|
|
245
|
+
const track = capture.getVideoTracks()[0];
|
|
246
|
+
await client.startCustomStream("whiteboard", track, "video");
|
|
247
|
+
|
|
248
|
+
// later
|
|
249
|
+
await client.stopCustomStream("whiteboard");
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
**Receive** — treat `source === "whiteboard"` like a screen-share tile:
|
|
253
|
+
|
|
254
|
+
```js
|
|
255
|
+
const client = createClient({
|
|
256
|
+
endpoint,
|
|
257
|
+
sessionId,
|
|
258
|
+
token,
|
|
259
|
+
onTrack: ({ source, kind, stream }) => {
|
|
260
|
+
if (source === "whiteboard" && kind === "video") {
|
|
261
|
+
whiteboardVideo.srcObject = stream;
|
|
262
|
+
}
|
|
263
|
+
},
|
|
264
|
+
onTrackEnded: ({ producerId }) => {
|
|
265
|
+
// remove that video element
|
|
266
|
+
},
|
|
267
|
+
});
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
Optional: broadcast the publisher’s whiteboard DOM bounds (normalized `x,y,w,h` vs the viewport) over your own channel so viewers can crop the full-tab capture to only the whiteboard area. See the sample app for that pattern.
|
|
271
|
+
|
|
185
272
|
## Recording
|
|
186
273
|
|
|
187
|
-
|
|
188
|
-
|
|
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.
|
|
189
290
|
- `stopRecording()` only pauses. It does not upload a finished file. `startRecording()` afterward opens a new segment under the same recording id.
|
|
190
291
|
- `end()` (or idle finalize when everybody has left) combines every segment into **one** playable file.
|
|
191
|
-
-
|
|
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")`).
|
|
192
293
|
- The file keeps going when another person calls `startRecording()` after a handoff. Ask them to start before the previous recorder calls `end()`.
|
|
193
294
|
- If everybody leaves, the recording is still saved after a few minutes of silence.
|
|
194
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
|
+
|
|
195
313
|
## Run the sample
|
|
196
314
|
|
|
197
315
|
```bash
|
|
@@ -203,3 +321,5 @@ npm run dev
|
|
|
203
321
|
Open http://localhost:3200. The page asks your Next.js server for a token, then joins http://localhost:8080.
|
|
204
322
|
|
|
205
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
package/src/client.js
CHANGED
|
@@ -8,6 +8,9 @@ const SIZES = {
|
|
|
8
8
|
"1080p": { width: 1920, height: 1080 },
|
|
9
9
|
};
|
|
10
10
|
|
|
11
|
+
/** Built-in sources that have dedicated start/stop helpers. */
|
|
12
|
+
const RESERVED_SOURCES = new Set(["webcam", "mic", "screen", "screen-audio"]);
|
|
13
|
+
|
|
11
14
|
function readToken(token) {
|
|
12
15
|
const body = String(token || "").split(".")[0];
|
|
13
16
|
if (!body) throw new Error("token is required");
|
|
@@ -55,7 +58,6 @@ export function createClient(options = {}) {
|
|
|
55
58
|
const endpoint = String(options.endpoint || "http://localhost:8080").replace(/\/+$/, "");
|
|
56
59
|
const sessionId = String(options.sessionId || "").trim();
|
|
57
60
|
const token = String(options.token || "").trim();
|
|
58
|
-
const recording = options.recording === true;
|
|
59
61
|
const iceOverride = Array.isArray(options.iceServers) ? options.iceServers : null;
|
|
60
62
|
const onTrack = options.onTrack || (() => {});
|
|
61
63
|
const onTrackEnded = options.onTrackEnded || (() => {});
|
|
@@ -68,6 +70,9 @@ export function createClient(options = {}) {
|
|
|
68
70
|
if (!token) throw new Error("token is required");
|
|
69
71
|
const claims = readToken(token);
|
|
70
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");
|
|
71
76
|
|
|
72
77
|
const displayName = String(claims.name || "Guest").slice(0, 40);
|
|
73
78
|
let socket = null;
|
|
@@ -142,11 +147,34 @@ export function createClient(options = {}) {
|
|
|
142
147
|
}
|
|
143
148
|
}
|
|
144
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
|
+
|
|
145
172
|
async function unpublish(producerId) {
|
|
146
173
|
const entry = locals.get(producerId);
|
|
147
174
|
if (!entry) return;
|
|
148
175
|
locals.delete(producerId);
|
|
149
176
|
tiles.delete(producerId);
|
|
177
|
+
detachEnded(entry);
|
|
150
178
|
entry.track.stop();
|
|
151
179
|
entry.producer.close();
|
|
152
180
|
syncRecording();
|
|
@@ -154,10 +182,21 @@ export function createClient(options = {}) {
|
|
|
154
182
|
if (socket?.connected) await emit(socket, "closeProducer", { producerId }).catch(() => {});
|
|
155
183
|
}
|
|
156
184
|
|
|
157
|
-
|
|
158
|
-
|
|
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
|
+
}
|
|
159
197
|
const stream = new MediaStream([track]);
|
|
160
|
-
|
|
198
|
+
const entry = { producer, track, original, source };
|
|
199
|
+
locals.set(producer.id, entry);
|
|
161
200
|
tiles.set(producer.id, {
|
|
162
201
|
producerId: producer.id,
|
|
163
202
|
publisherId: "local",
|
|
@@ -167,10 +206,7 @@ export function createClient(options = {}) {
|
|
|
167
206
|
stream,
|
|
168
207
|
local: true,
|
|
169
208
|
});
|
|
170
|
-
|
|
171
|
-
if (source === "screen") stopScreenShare().catch(() => {});
|
|
172
|
-
else unpublish(producer.id).catch(() => {});
|
|
173
|
-
};
|
|
209
|
+
attachEnded(producer.id, entry);
|
|
174
210
|
syncRecording();
|
|
175
211
|
return { producerId: producer.id, stream, source };
|
|
176
212
|
}
|
|
@@ -294,13 +330,9 @@ export function createClient(options = {}) {
|
|
|
294
330
|
if (joined.waiting) onStatus("Please wait, we will connect you soon");
|
|
295
331
|
else onStatus("Ready");
|
|
296
332
|
if (closed) return;
|
|
297
|
-
//
|
|
333
|
+
// Do not await: AudioContext may need a click in this tab before chunks flow.
|
|
298
334
|
if (recording && claims.role === "host") {
|
|
299
|
-
|
|
300
|
-
await startRecording();
|
|
301
|
-
} catch (error) {
|
|
302
|
-
onError(error);
|
|
303
|
-
}
|
|
335
|
+
startRecording().catch((error) => onError(error));
|
|
304
336
|
}
|
|
305
337
|
if (closed) return;
|
|
306
338
|
settleReady?.();
|
|
@@ -314,22 +346,60 @@ export function createClient(options = {}) {
|
|
|
314
346
|
return readyPromise;
|
|
315
347
|
}
|
|
316
348
|
|
|
317
|
-
async function startCamera({ cameraId, resolution } = {}) {
|
|
349
|
+
async function startCamera({ cameraId, resolution, track } = {}) {
|
|
350
|
+
if (track !== undefined) requireLiveTrack(track, "video");
|
|
318
351
|
await connect();
|
|
352
|
+
if (closed) throw new Error("The session has ended");
|
|
319
353
|
if (!sendTransport) throw new Error("The session is not ready");
|
|
320
354
|
await stopCamera();
|
|
355
|
+
if (track !== undefined) return produce("webcam", track.clone(), track);
|
|
321
356
|
const stream = await navigator.mediaDevices.getUserMedia({
|
|
322
357
|
video: videoConstraint(cameraId, resolution),
|
|
323
358
|
audio: false,
|
|
324
359
|
});
|
|
325
|
-
const
|
|
326
|
-
if (!
|
|
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();
|
|
327
375
|
try {
|
|
328
|
-
|
|
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
|
+
}
|
|
329
380
|
} catch (error) {
|
|
330
|
-
|
|
381
|
+
replacement.stop();
|
|
331
382
|
throw error;
|
|
332
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");
|
|
333
403
|
}
|
|
334
404
|
|
|
335
405
|
async function stopCamera() {
|
|
@@ -347,12 +417,11 @@ export function createClient(options = {}) {
|
|
|
347
417
|
const stream = await navigator.mediaDevices.getUserMedia({ audio, video: false });
|
|
348
418
|
const track = stream.getAudioTracks()[0];
|
|
349
419
|
if (!track) throw new Error("No microphone was found");
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
}
|
|
420
|
+
return produce("mic", track);
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
async function replaceMicrophoneTrack(track) {
|
|
424
|
+
return replaceLocalTrack("mic", track, "audio");
|
|
356
425
|
}
|
|
357
426
|
|
|
358
427
|
async function stopMicrophone() {
|
|
@@ -410,6 +479,48 @@ export function createClient(options = {}) {
|
|
|
410
479
|
}
|
|
411
480
|
}
|
|
412
481
|
|
|
482
|
+
/**
|
|
483
|
+
* Publish any caller-owned MediaStreamTrack under a custom stream identifier.
|
|
484
|
+
* Subscribers receive it via onTrack with `source` set to that identifier and
|
|
485
|
+
* `kind` set to audio or video.
|
|
486
|
+
*
|
|
487
|
+
* @param {string} identifier e.g. "whiteboard"
|
|
488
|
+
* @param {MediaStreamTrack} track
|
|
489
|
+
* @param {"audio"|"video"} type must match track.kind
|
|
490
|
+
*/
|
|
491
|
+
async function startCustomStream(identifier, track, type) {
|
|
492
|
+
await connect();
|
|
493
|
+
if (!sendTransport) throw new Error("The session is not ready");
|
|
494
|
+
const source = String(identifier || "").trim();
|
|
495
|
+
if (!source) throw new Error("stream identifier is required");
|
|
496
|
+
if (RESERVED_SOURCES.has(source)) {
|
|
497
|
+
throw new Error(`"${source}" is reserved; use the dedicated camera, mic, or screen APIs`);
|
|
498
|
+
}
|
|
499
|
+
if (!track || typeof track !== "object" || typeof track.kind !== "string") {
|
|
500
|
+
throw new Error("track is required");
|
|
501
|
+
}
|
|
502
|
+
const kind = String(type || track.kind || "").toLowerCase();
|
|
503
|
+
if (kind !== "audio" && kind !== "video") throw new Error("type must be audio or video");
|
|
504
|
+
if (track.kind !== kind) throw new Error(`track kind is ${track.kind}, expected ${kind}`);
|
|
505
|
+
|
|
506
|
+
// Replace an existing publish of the same identifier + kind.
|
|
507
|
+
for (const [id, entry] of [...locals]) {
|
|
508
|
+
if (entry.source === source && entry.track.kind === kind) await unpublish(id);
|
|
509
|
+
}
|
|
510
|
+
return produce(source, track);
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
async function stopCustomStream(identifier) {
|
|
514
|
+
const source = String(identifier || "").trim();
|
|
515
|
+
if (!source) return;
|
|
516
|
+
if (RESERVED_SOURCES.has(source)) {
|
|
517
|
+
throw new Error(`"${source}" is reserved; use the dedicated stop API`);
|
|
518
|
+
}
|
|
519
|
+
for (const [id, entry] of [...locals]) {
|
|
520
|
+
if (entry.source === source) await unpublish(id);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
|
|
413
524
|
async function subscribe() {
|
|
414
525
|
await connect();
|
|
415
526
|
subscribed = true;
|
|
@@ -421,7 +532,7 @@ export function createClient(options = {}) {
|
|
|
421
532
|
onRecording("stopped");
|
|
422
533
|
return;
|
|
423
534
|
}
|
|
424
|
-
// "recording" while chunks flow; "armed" while
|
|
535
|
+
// "recording" while chunks flow; "armed" briefly while prepare/beginCapture catches up.
|
|
425
536
|
onRecording(next.capturing ? "recording" : "armed");
|
|
426
537
|
}
|
|
427
538
|
|
|
@@ -444,18 +555,26 @@ export function createClient(options = {}) {
|
|
|
444
555
|
recordingId: await recordingIdFor(sessionId),
|
|
445
556
|
endpoint,
|
|
446
557
|
token,
|
|
447
|
-
|
|
558
|
+
selfName: displayName,
|
|
559
|
+
// Chunks start immediately; empty stage uses the same host placeholder as live UI.
|
|
448
560
|
onCaptureChange: () => notifyRecording(next),
|
|
561
|
+
onFailure: (error) => {
|
|
562
|
+
if (recorder !== next) return;
|
|
563
|
+
recorder = null;
|
|
564
|
+
onRecording("stopped");
|
|
565
|
+
onError(error);
|
|
566
|
+
},
|
|
449
567
|
});
|
|
450
568
|
recorder = next;
|
|
451
569
|
next.wanted = true;
|
|
570
|
+
notifyRecording(next);
|
|
452
571
|
next.sync(tracksFromTiles([...tiles.values()]));
|
|
453
572
|
try {
|
|
454
573
|
await next.start();
|
|
455
|
-
} catch {
|
|
574
|
+
} catch (error) {
|
|
456
575
|
if (recorder === next) recorder = null;
|
|
457
576
|
onRecording("stopped");
|
|
458
|
-
|
|
577
|
+
throw error instanceof Error ? error : new Error(String(error));
|
|
459
578
|
}
|
|
460
579
|
if (recorder !== next) return;
|
|
461
580
|
notifyRecording(next);
|
|
@@ -479,27 +598,35 @@ export function createClient(options = {}) {
|
|
|
479
598
|
settleReady?.(new Error("Ended"));
|
|
480
599
|
const current = recorder;
|
|
481
600
|
recorder = null;
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
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
|
+
}
|
|
490
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");
|
|
491
616
|
}
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
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();
|
|
496
629
|
}
|
|
497
|
-
for (const entry of locals.values()) entry.track.stop();
|
|
498
|
-
locals.clear();
|
|
499
|
-
sendTransport?.close();
|
|
500
|
-
recvTransport?.close();
|
|
501
|
-
socket?.close();
|
|
502
|
-
onStatus("Ended");
|
|
503
630
|
}
|
|
504
631
|
|
|
505
632
|
async function listDevices() {
|
|
@@ -527,11 +654,15 @@ export function createClient(options = {}) {
|
|
|
527
654
|
publish: guard(publish),
|
|
528
655
|
stop: guard(stop),
|
|
529
656
|
startCamera: guard(startCamera),
|
|
657
|
+
replaceCameraTrack: guard(replaceCameraTrack),
|
|
530
658
|
stopCamera: guard(stopCamera),
|
|
531
659
|
startMicrophone: guard(startMicrophone),
|
|
660
|
+
replaceMicrophoneTrack: guard(replaceMicrophoneTrack),
|
|
532
661
|
stopMicrophone: guard(stopMicrophone),
|
|
533
662
|
startScreenShare: guard(startScreenShare),
|
|
534
663
|
stopScreenShare: guard(stopScreenShare),
|
|
664
|
+
startCustomStream: guard(startCustomStream),
|
|
665
|
+
stopCustomStream: guard(stopCustomStream),
|
|
535
666
|
subscribe: guard(subscribe),
|
|
536
667
|
startRecording: guard(startRecording),
|
|
537
668
|
stopRecording: guard(stopRecording),
|
package/src/index.js
CHANGED