mediascale-sdk 1.0.5 → 1.0.7
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 +100 -19
- package/package.json +1 -1
- package/src/client.js +164 -50
- package/src/index.js +1 -0
- package/src/record-compositor.js +137 -0
- package/src/record-frame-compositor.js +97 -0
- package/src/record-worker.js +89 -0
- package/src/record.js +358 -91
package/docs/integration.md
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
# Use the SDK in Next.js
|
|
1
|
+
# Use the SDK in Next.js ( v1.0.6 )
|
|
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,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)
|
|
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
|
|
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
|
-
|
|
103
|
-
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 });
|
|
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
|
|
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.
|
|
127
|
-
| `
|
|
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,8 +171,9 @@ 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()` |
|
|
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. |
|
|
176
|
+
| `setRecordingCrop(source, crop)` | Crops a video source in the recording layout. `crop` is `{ x, y, w, h }` in 0..1 (same as subscriber whiteboard crop). Pass `null` to clear. |
|
|
138
177
|
| `end()` | Leaves the session. If this person is the one recording, every segment is combined and saved. |
|
|
139
178
|
| `listDevices()` | Returns `{ cameras, microphones }`. Each item is `{ id, label }`. |
|
|
140
179
|
|
|
@@ -150,7 +189,7 @@ Pass these to `createClient`.
|
|
|
150
189
|
| `onTrackEnded({ producerId })` | That media stopped. Remove the element. |
|
|
151
190
|
| `onStatus(text)` | `Joining`, `Ready`, `Live`, `Network unstable`, `Ended`, or an error message. |
|
|
152
191
|
| `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`
|
|
192
|
+
| `onRecording(state)` | `armed` briefly while capture is preparing. `recording` while chunks are uploading. `stopped` after `stopRecording()`, handoff, or `end()`. |
|
|
154
193
|
| `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
194
|
|
|
156
195
|
## Active speaker
|
|
@@ -191,6 +230,8 @@ Publish any `MediaStreamTrack` under your own id. Subscribers get that same id a
|
|
|
191
230
|
|
|
192
231
|
Reserved ids (use the dedicated APIs instead): `webcam`, `mic`, `screen`.
|
|
193
232
|
|
|
233
|
+
Custom **video** sources (for example `whiteboard`) use the large featured layout slot in the recording compositor, like screen share.
|
|
234
|
+
|
|
194
235
|
### Whiteboard example
|
|
195
236
|
|
|
196
237
|
**Publish** — show your whiteboard UI, capture this tab, send the video track:
|
|
@@ -229,16 +270,54 @@ const client = createClient({
|
|
|
229
270
|
|
|
230
271
|
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.
|
|
231
272
|
|
|
273
|
+
Pass the same crop into the recorder so the recording file matches what subscribers see (not the full browser tab):
|
|
274
|
+
|
|
275
|
+
```js
|
|
276
|
+
client.setRecordingCrop("whiteboard", { x, y, w, h }); // 0..1 vs captured frame
|
|
277
|
+
client.setRecordingCrop("whiteboard", null); // clear
|
|
278
|
+
```
|
|
279
|
+
|
|
232
280
|
## Recording
|
|
233
281
|
|
|
234
|
-
|
|
235
|
-
|
|
282
|
+
### When it starts
|
|
283
|
+
|
|
284
|
+
- `recording` defaults to **false**. Nothing records unless you enable it.
|
|
285
|
+
- Enable with any of:
|
|
286
|
+
- `createClient({ recording: true })` and a host token, or
|
|
287
|
+
- a **host** JWT with `recording: true` (Stream Control Webinar → Enable recording), or
|
|
288
|
+
- a manual `startRecording()` call during the session.
|
|
289
|
+
- Pass `createClient({ recording: false })` to force recording off even if the host token says `recording: true`.
|
|
290
|
+
- On host `connect()`, auto-start runs in the background and does **not** block join.
|
|
291
|
+
|
|
292
|
+
### What gets recorded
|
|
293
|
+
|
|
294
|
+
- Chunks upload as soon as recording starts — **mic and camera are not required**.
|
|
295
|
+
- 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.
|
|
296
|
+
- 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).
|
|
297
|
+
- 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
298
|
- `stopRecording()` only pauses. It does not upload a finished file. `startRecording()` afterward opens a new segment under the same recording id.
|
|
237
299
|
- `end()` (or idle finalize when everybody has left) combines every segment into **one** playable file.
|
|
238
|
-
-
|
|
300
|
+
- 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
301
|
- The file keeps going when another person calls `startRecording()` after a handoff. Ask them to start before the previous recorder calls `end()`.
|
|
240
302
|
- If everybody leaves, the recording is still saved after a few minutes of silence.
|
|
241
303
|
|
|
304
|
+
### Background-safe compositing
|
|
305
|
+
|
|
306
|
+
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.
|
|
307
|
+
|
|
308
|
+
Listen for mode / failure events if your UI needs them:
|
|
309
|
+
|
|
310
|
+
```js
|
|
311
|
+
window.addEventListener("mediascale:recording-mode", (event) => {
|
|
312
|
+
// event.detail.mode === "worker" | "foreground"
|
|
313
|
+
// event.detail.reason is set when falling back
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
window.addEventListener("mediascale:recording-error", (event) => {
|
|
317
|
+
// event.detail.message — worker stopped or capture failed; call startRecording() again
|
|
318
|
+
});
|
|
319
|
+
```
|
|
320
|
+
|
|
242
321
|
## Run the sample
|
|
243
322
|
|
|
244
323
|
```bash
|
|
@@ -250,3 +329,5 @@ npm run dev
|
|
|
250
329
|
Open http://localhost:3200. The page asks your Next.js server for a token, then joins http://localhost:8080.
|
|
251
330
|
|
|
252
331
|
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`.
|
|
332
|
+
|
|
333
|
+
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
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Device } from "mediasoup-client";
|
|
2
2
|
import { io } from "socket.io-client";
|
|
3
|
-
import { CanvasRecorder, recordingWebinarId, tracksFromTiles } from "./record.js";
|
|
3
|
+
import { CanvasRecorder, normalizeVideoCrop, recordingWebinarId, tracksFromTiles } from "./record.js";
|
|
4
4
|
|
|
5
5
|
const SIZES = {
|
|
6
6
|
"480p": { width: 854, height: 480 },
|
|
@@ -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;
|
|
@@ -85,6 +87,8 @@ export function createClient(options = {}) {
|
|
|
85
87
|
let selfPeerId = null;
|
|
86
88
|
const locals = new Map();
|
|
87
89
|
const tiles = new Map();
|
|
90
|
+
/** source id → normalized crop for recording compositor (e.g. whiteboard). */
|
|
91
|
+
const recordingCrops = new Map();
|
|
88
92
|
const pending = [];
|
|
89
93
|
let readyPromise = null;
|
|
90
94
|
let settleReady = null;
|
|
@@ -98,8 +102,34 @@ export function createClient(options = {}) {
|
|
|
98
102
|
return { userAgent: ua, mobile, desktop: !mobile, chrome };
|
|
99
103
|
}
|
|
100
104
|
|
|
105
|
+
function tracksForRecording() {
|
|
106
|
+
const tracks = tracksFromTiles([...tiles.values()]);
|
|
107
|
+
for (const item of tracks) {
|
|
108
|
+
if (item.kind !== "video") continue;
|
|
109
|
+
const crop = recordingCrops.get(item.source);
|
|
110
|
+
if (crop) item.crop = crop;
|
|
111
|
+
}
|
|
112
|
+
return tracks;
|
|
113
|
+
}
|
|
114
|
+
|
|
101
115
|
function syncRecording() {
|
|
102
|
-
recorder?.sync(
|
|
116
|
+
recorder?.sync(tracksForRecording());
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Crop a video source in the recording layout (same `{ x, y, w, h }` 0..1 bounds the
|
|
121
|
+
* sample app uses for subscriber whiteboard CSS crop). Pass null to clear.
|
|
122
|
+
*/
|
|
123
|
+
function setRecordingCrop(source, crop) {
|
|
124
|
+
const id = String(source || "").trim();
|
|
125
|
+
if (!id) return;
|
|
126
|
+
const next = normalizeVideoCrop(crop);
|
|
127
|
+
if (!next) recordingCrops.delete(id);
|
|
128
|
+
else recordingCrops.set(id, next);
|
|
129
|
+
if (recorder) {
|
|
130
|
+
recorder.setVideoCrop(id, next);
|
|
131
|
+
syncRecording();
|
|
132
|
+
}
|
|
103
133
|
}
|
|
104
134
|
|
|
105
135
|
async function consume(params) {
|
|
@@ -145,11 +175,34 @@ export function createClient(options = {}) {
|
|
|
145
175
|
}
|
|
146
176
|
}
|
|
147
177
|
|
|
178
|
+
function requireLiveTrack(track, kind) {
|
|
179
|
+
if (!track || track.kind !== kind || track.readyState !== "live" || typeof track.clone !== "function") {
|
|
180
|
+
throw new Error(`Expected a live ${kind} track`);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function detachEnded(entry) {
|
|
185
|
+
entry.track.removeEventListener("ended", entry.onEnded);
|
|
186
|
+
if (entry.original !== entry.track) entry.original.removeEventListener("ended", entry.onEnded);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function attachEnded(producerId, entry) {
|
|
190
|
+
const track = entry.track;
|
|
191
|
+
entry.onEnded = () => {
|
|
192
|
+
if (closed || locals.get(producerId) !== entry || entry.track !== track) return;
|
|
193
|
+
if (entry.source === "screen") stopScreenShare().catch(() => {});
|
|
194
|
+
else unpublish(producerId).catch(() => {});
|
|
195
|
+
};
|
|
196
|
+
track.addEventListener("ended", entry.onEnded);
|
|
197
|
+
if (entry.original !== track) entry.original.addEventListener("ended", entry.onEnded);
|
|
198
|
+
}
|
|
199
|
+
|
|
148
200
|
async function unpublish(producerId) {
|
|
149
201
|
const entry = locals.get(producerId);
|
|
150
202
|
if (!entry) return;
|
|
151
203
|
locals.delete(producerId);
|
|
152
204
|
tiles.delete(producerId);
|
|
205
|
+
detachEnded(entry);
|
|
153
206
|
entry.track.stop();
|
|
154
207
|
entry.producer.close();
|
|
155
208
|
syncRecording();
|
|
@@ -157,10 +210,21 @@ export function createClient(options = {}) {
|
|
|
157
210
|
if (socket?.connected) await emit(socket, "closeProducer", { producerId }).catch(() => {});
|
|
158
211
|
}
|
|
159
212
|
|
|
160
|
-
|
|
161
|
-
|
|
213
|
+
// Camera inputs use an SDK-owned clone. Custom inputs keep upstream direct ownership.
|
|
214
|
+
async function produce(source, track, original = track) {
|
|
215
|
+
let producer;
|
|
216
|
+
try {
|
|
217
|
+
producer = await sendTransport.produce({ track, stopTracks: false, appData: { source } });
|
|
218
|
+
if (closed) throw new Error("The session has ended");
|
|
219
|
+
if (track.readyState === "ended" || original.readyState === "ended") throw new Error("The source track ended");
|
|
220
|
+
} catch (error) {
|
|
221
|
+
producer?.close();
|
|
222
|
+
track.stop();
|
|
223
|
+
throw error;
|
|
224
|
+
}
|
|
162
225
|
const stream = new MediaStream([track]);
|
|
163
|
-
|
|
226
|
+
const entry = { producer, track, original, source };
|
|
227
|
+
locals.set(producer.id, entry);
|
|
164
228
|
tiles.set(producer.id, {
|
|
165
229
|
producerId: producer.id,
|
|
166
230
|
publisherId: "local",
|
|
@@ -170,10 +234,7 @@ export function createClient(options = {}) {
|
|
|
170
234
|
stream,
|
|
171
235
|
local: true,
|
|
172
236
|
});
|
|
173
|
-
|
|
174
|
-
if (source === "screen") stopScreenShare().catch(() => {});
|
|
175
|
-
else unpublish(producer.id).catch(() => {});
|
|
176
|
-
};
|
|
237
|
+
attachEnded(producer.id, entry);
|
|
177
238
|
syncRecording();
|
|
178
239
|
return { producerId: producer.id, stream, source };
|
|
179
240
|
}
|
|
@@ -297,13 +358,9 @@ export function createClient(options = {}) {
|
|
|
297
358
|
if (joined.waiting) onStatus("Please wait, we will connect you soon");
|
|
298
359
|
else onStatus("Ready");
|
|
299
360
|
if (closed) return;
|
|
300
|
-
//
|
|
361
|
+
// Do not await: AudioContext may need a click in this tab before chunks flow.
|
|
301
362
|
if (recording && claims.role === "host") {
|
|
302
|
-
|
|
303
|
-
await startRecording();
|
|
304
|
-
} catch (error) {
|
|
305
|
-
onError(error);
|
|
306
|
-
}
|
|
363
|
+
startRecording().catch((error) => onError(error));
|
|
307
364
|
}
|
|
308
365
|
if (closed) return;
|
|
309
366
|
settleReady?.();
|
|
@@ -317,22 +374,60 @@ export function createClient(options = {}) {
|
|
|
317
374
|
return readyPromise;
|
|
318
375
|
}
|
|
319
376
|
|
|
320
|
-
async function startCamera({ cameraId, resolution } = {}) {
|
|
377
|
+
async function startCamera({ cameraId, resolution, track } = {}) {
|
|
378
|
+
if (track !== undefined) requireLiveTrack(track, "video");
|
|
321
379
|
await connect();
|
|
380
|
+
if (closed) throw new Error("The session has ended");
|
|
322
381
|
if (!sendTransport) throw new Error("The session is not ready");
|
|
323
382
|
await stopCamera();
|
|
383
|
+
if (track !== undefined) return produce("webcam", track.clone(), track);
|
|
324
384
|
const stream = await navigator.mediaDevices.getUserMedia({
|
|
325
385
|
video: videoConstraint(cameraId, resolution),
|
|
326
386
|
audio: false,
|
|
327
387
|
});
|
|
328
|
-
const
|
|
329
|
-
if (!
|
|
388
|
+
const captured = stream.getVideoTracks()[0];
|
|
389
|
+
if (!captured) {
|
|
390
|
+
stream.getTracks().forEach((item) => item.stop());
|
|
391
|
+
throw new Error("No camera was found");
|
|
392
|
+
}
|
|
393
|
+
return produce("webcam", captured);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
async function replaceLocalTrack(source, track, kind) {
|
|
397
|
+
requireLiveTrack(track, kind);
|
|
398
|
+
if (closed) throw new Error("The session has ended");
|
|
399
|
+
const current = [...locals].find(([, entry]) => entry.source === source);
|
|
400
|
+
if (!current) throw new Error(source === "webcam" ? "The camera is not started" : "The microphone is not started");
|
|
401
|
+
const [producerId, entry] = current;
|
|
402
|
+
const replacement = track.clone();
|
|
330
403
|
try {
|
|
331
|
-
|
|
404
|
+
await entry.producer.replaceTrack({ track: replacement });
|
|
405
|
+
if (closed || locals.get(producerId) !== entry) {
|
|
406
|
+
throw new Error(source === "webcam" ? "The camera is not started" : "The microphone is not started");
|
|
407
|
+
}
|
|
332
408
|
} catch (error) {
|
|
333
|
-
|
|
409
|
+
replacement.stop();
|
|
334
410
|
throw error;
|
|
335
411
|
}
|
|
412
|
+
const previous = entry.track;
|
|
413
|
+
const previousOriginal = entry.original;
|
|
414
|
+
detachEnded(entry);
|
|
415
|
+
entry.track = replacement;
|
|
416
|
+
entry.original = track;
|
|
417
|
+
const stream = tiles.get(producerId).stream;
|
|
418
|
+
stream.removeTrack(previous);
|
|
419
|
+
stream.addTrack(replacement);
|
|
420
|
+
attachEnded(producerId, entry);
|
|
421
|
+
syncRecording();
|
|
422
|
+
previous.stop();
|
|
423
|
+
if (previousOriginal && previousOriginal !== previous && previousOriginal !== track) {
|
|
424
|
+
previousOriginal.stop();
|
|
425
|
+
}
|
|
426
|
+
return { producerId, stream, source };
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
async function replaceCameraTrack(track) {
|
|
430
|
+
return replaceLocalTrack("webcam", track, "video");
|
|
336
431
|
}
|
|
337
432
|
|
|
338
433
|
async function stopCamera() {
|
|
@@ -350,12 +445,11 @@ export function createClient(options = {}) {
|
|
|
350
445
|
const stream = await navigator.mediaDevices.getUserMedia({ audio, video: false });
|
|
351
446
|
const track = stream.getAudioTracks()[0];
|
|
352
447
|
if (!track) throw new Error("No microphone was found");
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
}
|
|
448
|
+
return produce("mic", track);
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
async function replaceMicrophoneTrack(track) {
|
|
452
|
+
return replaceLocalTrack("mic", track, "audio");
|
|
359
453
|
}
|
|
360
454
|
|
|
361
455
|
async function stopMicrophone() {
|
|
@@ -466,7 +560,7 @@ export function createClient(options = {}) {
|
|
|
466
560
|
onRecording("stopped");
|
|
467
561
|
return;
|
|
468
562
|
}
|
|
469
|
-
// "recording" while chunks flow; "armed" while
|
|
563
|
+
// "recording" while chunks flow; "armed" briefly while prepare/beginCapture catches up.
|
|
470
564
|
onRecording(next.capturing ? "recording" : "armed");
|
|
471
565
|
}
|
|
472
566
|
|
|
@@ -489,18 +583,27 @@ export function createClient(options = {}) {
|
|
|
489
583
|
recordingId: await recordingIdFor(sessionId),
|
|
490
584
|
endpoint,
|
|
491
585
|
token,
|
|
492
|
-
|
|
586
|
+
selfName: displayName,
|
|
587
|
+
// Chunks start immediately; empty stage uses the same host placeholder as live UI.
|
|
493
588
|
onCaptureChange: () => notifyRecording(next),
|
|
589
|
+
onFailure: (error) => {
|
|
590
|
+
if (recorder !== next) return;
|
|
591
|
+
recorder = null;
|
|
592
|
+
onRecording("stopped");
|
|
593
|
+
onError(error);
|
|
594
|
+
},
|
|
494
595
|
});
|
|
495
596
|
recorder = next;
|
|
496
597
|
next.wanted = true;
|
|
497
|
-
next
|
|
598
|
+
notifyRecording(next);
|
|
599
|
+
for (const [source, crop] of recordingCrops) next.setVideoCrop(source, crop);
|
|
600
|
+
next.sync(tracksForRecording());
|
|
498
601
|
try {
|
|
499
602
|
await next.start();
|
|
500
|
-
} catch {
|
|
603
|
+
} catch (error) {
|
|
501
604
|
if (recorder === next) recorder = null;
|
|
502
605
|
onRecording("stopped");
|
|
503
|
-
|
|
606
|
+
throw error instanceof Error ? error : new Error(String(error));
|
|
504
607
|
}
|
|
505
608
|
if (recorder !== next) return;
|
|
506
609
|
notifyRecording(next);
|
|
@@ -524,27 +627,35 @@ export function createClient(options = {}) {
|
|
|
524
627
|
settleReady?.(new Error("Ended"));
|
|
525
628
|
const current = recorder;
|
|
526
629
|
recorder = null;
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
630
|
+
try {
|
|
631
|
+
if (current) {
|
|
632
|
+
let handoff = false;
|
|
633
|
+
if (socket?.connected) {
|
|
634
|
+
try {
|
|
635
|
+
const result = await emit(socket, "leaveRecording", {});
|
|
636
|
+
handoff = Boolean(result?.handoff);
|
|
637
|
+
} catch {
|
|
638
|
+
handoff = false;
|
|
639
|
+
}
|
|
535
640
|
}
|
|
641
|
+
// Cohost continues the same recordingId; only finalize when nobody else can take over.
|
|
642
|
+
if (handoff) await current.handoff();
|
|
643
|
+
else await current.finish();
|
|
644
|
+
onRecording("stopped");
|
|
536
645
|
}
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
646
|
+
} finally {
|
|
647
|
+
for (const entry of locals.values()) {
|
|
648
|
+
detachEnded(entry);
|
|
649
|
+
entry.track.stop();
|
|
650
|
+
entry.producer.close();
|
|
651
|
+
}
|
|
652
|
+
locals.clear();
|
|
653
|
+
sendTransport?.close();
|
|
654
|
+
recvTransport?.close();
|
|
655
|
+
socket?.close();
|
|
656
|
+
onStatus("Ended");
|
|
657
|
+
tiles.clear();
|
|
541
658
|
}
|
|
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
659
|
}
|
|
549
660
|
|
|
550
661
|
async function listDevices() {
|
|
@@ -572,8 +683,10 @@ export function createClient(options = {}) {
|
|
|
572
683
|
publish: guard(publish),
|
|
573
684
|
stop: guard(stop),
|
|
574
685
|
startCamera: guard(startCamera),
|
|
686
|
+
replaceCameraTrack: guard(replaceCameraTrack),
|
|
575
687
|
stopCamera: guard(stopCamera),
|
|
576
688
|
startMicrophone: guard(startMicrophone),
|
|
689
|
+
replaceMicrophoneTrack: guard(replaceMicrophoneTrack),
|
|
577
690
|
stopMicrophone: guard(stopMicrophone),
|
|
578
691
|
startScreenShare: guard(startScreenShare),
|
|
579
692
|
stopScreenShare: guard(stopScreenShare),
|
|
@@ -582,6 +695,7 @@ export function createClient(options = {}) {
|
|
|
582
695
|
subscribe: guard(subscribe),
|
|
583
696
|
startRecording: guard(startRecording),
|
|
584
697
|
stopRecording: guard(stopRecording),
|
|
698
|
+
setRecordingCrop,
|
|
585
699
|
end: guard(end),
|
|
586
700
|
listDevices: guard(listDevices),
|
|
587
701
|
};
|
package/src/index.js
CHANGED