mediascale-sdk 1.0.3 → 1.0.5

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. If `recording` is true and that person is the host, recording starts by itself. Anyone else can call `startRecording()` if the host leaves and the recording should continue.
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.
6
6
 
7
7
  The secret that signs tokens stays on your server. The browser only receives a short-lived token.
8
8
 
@@ -51,7 +51,7 @@ export async function POST(request) {
51
51
  }
52
52
  ```
53
53
 
54
- `role` is `host` or `audience`. Both can publish. Only the host records automatically.
54
+ `role` is `host` or `audience`. Both can publish. Only the host should drive recording in the UI.
55
55
 
56
56
  ## 2. Copy the room page
57
57
 
@@ -61,10 +61,11 @@ Copy `sdk/react-sdk/sample/app/room.js` into your app. The comments in that file
61
61
  2. **Camera** calls `startCamera()` or `stopCamera()`.
62
62
  3. **Mic** calls `startMicrophone()` or `stopMicrophone()`.
63
63
  4. **Screen** calls `startScreenShare()` or `stopScreenShare()`.
64
- 5. **Start recording** is optional. Use it when the host has left and someone else should continue.
65
- 6. **End** leaves the session.
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.
66
+ 7. **End** leaves the session and saves the recording if this person was recording.
66
67
 
67
- Host is unchecked. Tick it only for the person who should record. When it is ticked, `recording` is true and recording starts on `connect()`.
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.
68
69
 
69
70
  The room must run in the browser. `app/page.js`
70
71
 
@@ -104,12 +105,23 @@ await client.startMicrophone({ micId: "device-id" });
104
105
 
105
106
  `resolution` can be `"480p"`, `"720p"`, `"1080p"`, or `{ width: 1280, height: 720 }`.
106
107
 
108
+ The SFU origin caps each publisher’s uplink at **2500 Kbps** (`MAX_PUBLISH_BITRATE_BPS`) via `setMaxIncomingBitrate` on the send transport.
109
+
110
+ Toggle recording during the session:
111
+
112
+ ```js
113
+ await client.startRecording();
114
+ await client.stopRecording(); // pauses; does not save yet
115
+ await client.startRecording(); // new segment, same recording id
116
+ await client.end(); // combines every segment into one file
117
+ ```
118
+
107
119
  ## Functions
108
120
 
109
121
  | Function | What it does |
110
122
  | --- | --- |
111
- | `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. |
112
- | `connect()` | Checks the token and joins the session. If `recording` is true and the token role is `host`, recording starts. |
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()`). |
113
125
  | `subscribe()` | Starts playing the other people. Call this once after `connect()`. |
114
126
  | `startCamera({ cameraId, resolution })` | Publishes the camera. Both arguments are optional. |
115
127
  | `stopCamera()` | Stops the camera. The person stays in the session. |
@@ -117,13 +129,16 @@ await client.startMicrophone({ micId: "device-id" });
117
129
  | `stopMicrophone()` | Stops the microphone. |
118
130
  | `startScreenShare()` | Shares the screen. Anyone in the session can call this. |
119
131
  | `stopScreenShare()` | Stops the screen share. |
132
+ | `startCustomStream(identifier, track, type)` | Publishes a custom `MediaStreamTrack`. `type` is `"audio"` or `"video"`. Reserved ids: `webcam`, `mic`, `screen`. |
133
+ | `stopCustomStream(identifier)` | Stops that custom stream. |
120
134
  | `publish({ cameraId, micId, resolution })` | Turns on the camera and the microphone together. |
121
135
  | `stop()` | Turns off the camera and the microphone. The screen share stays on. |
122
- | `startRecording()` | Starts recording for this person. Call it when the host has left and someone else should keep the same recording going. |
123
- | `end()` | Leaves the session. If this person is the one recording, the recording is saved. |
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. |
137
+ | `stopRecording()` | Pauses recording without saving. Call `startRecording()` again to continue; `end()` still combines all segments into one file. |
138
+ | `end()` | Leaves the session. If this person is the one recording, every segment is combined and saved. |
124
139
  | `listDevices()` | Returns `{ cameras, microphones }`. Each item is `{ id, label }`. |
125
140
 
126
- Call `connect`, then `subscribe`. Call `startCamera`, `startMicrophone`, or `startScreenShare` only when that button is pressed. Call the matching stop function to turn that input off. Call `end` when the person leaves.
141
+ 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.
127
142
 
128
143
  ## Callbacks
129
144
 
@@ -131,17 +146,97 @@ Pass these to `createClient`.
131
146
 
132
147
  | Callback | When it runs |
133
148
  | --- | --- |
134
- | `onTrack({ producerId, peerId, source, kind, displayName, stream })` | Another person's camera, microphone, or screen is ready. Set `srcObject` on a `<video>` or `<audio>` element. `source` is `webcam`, `mic`, or `screen`. |
149
+ | `onTrack({ producerId, peerId, source, kind, displayName, stream })` | Remote media ready. `source` is `webcam`, `mic`, `screen`, or a custom id (e.g. `whiteboard`). |
135
150
  | `onTrackEnded({ producerId })` | That media stopped. Remove the element. |
136
151
  | `onStatus(text)` | `Joining`, `Ready`, `Live`, `Network unstable`, `Ended`, or an error message. |
137
152
  | `onError(error)` | A call failed. `error.message` is the reason. The same call also throws, so `await` can use `try/catch`. |
138
- | `onRecording(state)` | `recording` when this browser is recording. `stopped` when it stops or hands the recording to someone else. |
153
+ | `onRecording(state)` | `armed` when recording is on but waiting for live media. `recording` while chunks are uploading. `stopped` after `stopRecording()`, handoff, or `end()`. |
154
+ | `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
+
156
+ ## Active speaker
157
+
158
+ Enable on the media stack (origin + portal):
159
+
160
+ ```bash
161
+ ACTIVE_SPEAKER_DETECTION=true
162
+ ```
163
+
164
+ Optional tuning on the origin SFU:
165
+
166
+ ```bash
167
+ ACTIVE_SPEAKER_THRESHOLD=-45
168
+ ACTIVE_SPEAKER_INTERVAL_MS=500
169
+ ```
170
+
171
+ When the flag is on, the origin watches mic producers with mediasoup `AudioLevelObserver` and the portal emits `activeSpeaker` to every peer in the session. The SDK surfaces that as `onActiveSpeaker`.
172
+
173
+ ```js
174
+ const client = createClient({
175
+ endpoint,
176
+ sessionId,
177
+ token,
178
+ onActiveSpeaker: ({ peerId, displayName, local }) => {
179
+ // peerId null → clear the speaking highlight
180
+ // local true → this person is the active speaker
181
+ highlightSpeaker({ peerId, displayName, local });
182
+ },
183
+ });
184
+ ```
185
+
186
+ The sample room highlights the speaking camera tile (and strip card) with a cyan border. Screen-share tiles are not marked as speaking.
187
+
188
+ ## Custom streams
189
+
190
+ Publish any `MediaStreamTrack` under your own id. Subscribers get that same id as `onTrack.source`.
191
+
192
+ Reserved ids (use the dedicated APIs instead): `webcam`, `mic`, `screen`.
193
+
194
+ ### Whiteboard example
195
+
196
+ **Publish** — show your whiteboard UI, capture this tab, send the video track:
197
+
198
+ ```js
199
+ const capture = await navigator.mediaDevices.getDisplayMedia({
200
+ video: true,
201
+ audio: false,
202
+ preferCurrentTab: true,
203
+ selfBrowserSurface: "include",
204
+ });
205
+ const track = capture.getVideoTracks()[0];
206
+ await client.startCustomStream("whiteboard", track, "video");
207
+
208
+ // later
209
+ await client.stopCustomStream("whiteboard");
210
+ ```
211
+
212
+ **Receive** — treat `source === "whiteboard"` like a screen-share tile:
213
+
214
+ ```js
215
+ const client = createClient({
216
+ endpoint,
217
+ sessionId,
218
+ token,
219
+ onTrack: ({ source, kind, stream }) => {
220
+ if (source === "whiteboard" && kind === "video") {
221
+ whiteboardVideo.srcObject = stream;
222
+ }
223
+ },
224
+ onTrackEnded: ({ producerId }) => {
225
+ // remove that video element
226
+ },
227
+ });
228
+ ```
229
+
230
+ 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.
139
231
 
140
232
  ## Recording
141
233
 
142
- - Set `recording: true` only for the host. `connect()` then records without an extra call. The red `[ rec ]` label shows while that recording is active. If recording does not start, the label stays hidden and the person can still publish.
143
- - The file keeps going when another person calls `startRecording()`. Ask them to start before the host calls `end()`.
144
- - `end()` saves the file only for the person who is recording at that moment.
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.
236
+ - `stopRecording()` only pauses. It does not upload a finished file. `startRecording()` afterward opens a new segment under the same recording id.
237
+ - `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.
239
+ - The file keeps going when another person calls `startRecording()` after a handoff. Ask them to start before the previous recorder calls `end()`.
145
240
  - If everybody leaves, the recording is still saved after a few minutes of silence.
146
241
 
147
242
  ## Run the sample
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mediascale-sdk",
3
- "version": "1.0.3",
3
+ "version": "1.0.5",
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
@@ -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");
@@ -62,6 +65,7 @@ export function createClient(options = {}) {
62
65
  const onStatus = options.onStatus || (() => {});
63
66
  const onError = options.onError || (() => {});
64
67
  const onRecording = options.onRecording || (() => {});
68
+ const onActiveSpeaker = options.onActiveSpeaker || (() => {});
65
69
 
66
70
  if (!sessionId) throw new Error("sessionId is required");
67
71
  if (!token) throw new Error("token is required");
@@ -78,6 +82,7 @@ export function createClient(options = {}) {
78
82
  let subscribed = false;
79
83
  let recorder = null;
80
84
  let startingRecorder = null;
85
+ let selfPeerId = null;
81
86
  const locals = new Map();
82
87
  const tiles = new Map();
83
88
  const pending = [];
@@ -229,6 +234,16 @@ export function createClient(options = {}) {
229
234
  .then(() => onRecording("stopped"))
230
235
  .catch((error) => onError(error));
231
236
  });
237
+ socket.on("activeSpeaker", (payload = {}) => {
238
+ if (closed) return;
239
+ const peerId = payload.peerId || null;
240
+ onActiveSpeaker({
241
+ peerId,
242
+ displayName: payload.displayName || null,
243
+ producerId: payload.producerId || null,
244
+ local: Boolean(peerId && selfPeerId && peerId === selfPeerId),
245
+ });
246
+ });
232
247
  socket.on("connect", async () => {
233
248
  try {
234
249
  if (closed) return;
@@ -239,6 +254,7 @@ export function createClient(options = {}) {
239
254
  displayName,
240
255
  ...clientHints(),
241
256
  });
257
+ selfPeerId = joined.peerId || null;
242
258
  iceServers = iceOverride || joined.iceServers || [];
243
259
  device = new Device();
244
260
  await device.load({ routerRtpCapabilities: joined.rtpCapabilities });
@@ -397,16 +413,72 @@ export function createClient(options = {}) {
397
413
  }
398
414
  }
399
415
 
416
+ /**
417
+ * Publish any caller-owned MediaStreamTrack under a custom stream identifier.
418
+ * Subscribers receive it via onTrack with `source` set to that identifier and
419
+ * `kind` set to audio or video.
420
+ *
421
+ * @param {string} identifier e.g. "whiteboard"
422
+ * @param {MediaStreamTrack} track
423
+ * @param {"audio"|"video"} type must match track.kind
424
+ */
425
+ async function startCustomStream(identifier, track, type) {
426
+ await connect();
427
+ if (!sendTransport) throw new Error("The session is not ready");
428
+ const source = String(identifier || "").trim();
429
+ if (!source) throw new Error("stream identifier is required");
430
+ if (RESERVED_SOURCES.has(source)) {
431
+ throw new Error(`"${source}" is reserved; use the dedicated camera, mic, or screen APIs`);
432
+ }
433
+ if (!track || typeof track !== "object" || typeof track.kind !== "string") {
434
+ throw new Error("track is required");
435
+ }
436
+ const kind = String(type || track.kind || "").toLowerCase();
437
+ if (kind !== "audio" && kind !== "video") throw new Error("type must be audio or video");
438
+ if (track.kind !== kind) throw new Error(`track kind is ${track.kind}, expected ${kind}`);
439
+
440
+ // Replace an existing publish of the same identifier + kind.
441
+ for (const [id, entry] of [...locals]) {
442
+ if (entry.source === source && entry.track.kind === kind) await unpublish(id);
443
+ }
444
+ return produce(source, track);
445
+ }
446
+
447
+ async function stopCustomStream(identifier) {
448
+ const source = String(identifier || "").trim();
449
+ if (!source) return;
450
+ if (RESERVED_SOURCES.has(source)) {
451
+ throw new Error(`"${source}" is reserved; use the dedicated stop API`);
452
+ }
453
+ for (const [id, entry] of [...locals]) {
454
+ if (entry.source === source) await unpublish(id);
455
+ }
456
+ }
457
+
400
458
  async function subscribe() {
401
459
  await connect();
402
460
  subscribed = true;
403
461
  await flush();
404
462
  }
405
463
 
464
+ function notifyRecording(next) {
465
+ if (!next?.wanted) {
466
+ onRecording("stopped");
467
+ return;
468
+ }
469
+ // "recording" while chunks flow; "armed" while enabled but waiting for live A/V/screen.
470
+ onRecording(next.capturing ? "recording" : "armed");
471
+ }
472
+
406
473
  async function startRecording() {
407
474
  if (closed) throw new Error("The session has ended");
408
475
  if (!sendTransport) await connect();
409
- if (closed || recorder) return;
476
+ if (closed) return;
477
+ if (recorder) {
478
+ await recorder.setWanted(true);
479
+ notifyRecording(recorder);
480
+ return;
481
+ }
410
482
  if (startingRecorder) return startingRecorder;
411
483
  startingRecorder = (async () => {
412
484
  await emit(socket, "claimRecording", {});
@@ -418,9 +490,10 @@ export function createClient(options = {}) {
418
490
  endpoint,
419
491
  token,
420
492
  // Chunks only flow while webcam / mic / screenshare is live.
421
- onCaptureChange: (active) => onRecording(active ? "recording" : "stopped"),
493
+ onCaptureChange: () => notifyRecording(next),
422
494
  });
423
495
  recorder = next;
496
+ next.wanted = true;
424
497
  next.sync(tracksFromTiles([...tiles.values()]));
425
498
  try {
426
499
  await next.start();
@@ -430,8 +503,7 @@ export function createClient(options = {}) {
430
503
  return;
431
504
  }
432
505
  if (recorder !== next) return;
433
- // Keep "stopped" until the first live track; sync() will arm capture then.
434
- if (!tracksFromTiles([...tiles.values()]).length) onRecording("stopped");
506
+ notifyRecording(next);
435
507
  })();
436
508
  try {
437
509
  await startingRecorder;
@@ -440,6 +512,12 @@ export function createClient(options = {}) {
440
512
  }
441
513
  }
442
514
 
515
+ async function stopRecording() {
516
+ if (closed || !recorder) return;
517
+ await recorder.setWanted(false);
518
+ onRecording("stopped");
519
+ }
520
+
443
521
  async function end() {
444
522
  if (closed) return;
445
523
  closed = true;
@@ -499,8 +577,11 @@ export function createClient(options = {}) {
499
577
  stopMicrophone: guard(stopMicrophone),
500
578
  startScreenShare: guard(startScreenShare),
501
579
  stopScreenShare: guard(stopScreenShare),
580
+ startCustomStream: guard(startCustomStream),
581
+ stopCustomStream: guard(stopCustomStream),
502
582
  subscribe: guard(subscribe),
503
583
  startRecording: guard(startRecording),
584
+ stopRecording: guard(stopRecording),
504
585
  end: guard(end),
505
586
  listDevices: guard(listDevices),
506
587
  };
package/src/record.js CHANGED
@@ -66,15 +66,21 @@ export function tracksFromTiles(tiles) {
66
66
  return out;
67
67
  }
68
68
 
69
- /** True when at least one live webcam / mic / screenshare track is present. */
69
+ /** Screen share and custom video (e.g. whiteboard) use the large featured slot. */
70
+ function isFeaturedVideoSource(source) {
71
+ return source === "screen" || (source && source !== "webcam");
72
+ }
73
+
74
+ /** True when at least one live webcam / mic / screenshare / custom track is present. */
70
75
  export function hasActiveMedia(tracks) {
71
76
  return (tracks || []).some((item) => {
72
77
  const track = item?.track;
73
78
  if (!track || track.readyState === "ended" || track.enabled === false) return false;
74
- return item.source === "webcam"
75
- || item.source === "mic"
76
- || item.source === "screen"
77
- || item.source === "screen-audio";
79
+ if (item.source === "webcam" || item.source === "mic" || item.source === "screen" || item.source === "screen-audio") {
80
+ return true;
81
+ }
82
+ // Custom streams (whiteboard, etc.) also keep recording alive.
83
+ return Boolean(item.source);
78
84
  });
79
85
  }
80
86
 
@@ -104,6 +110,8 @@ export class CanvasRecorder {
104
110
  this.finishing = false;
105
111
  this.prepared = false;
106
112
  this.capturing = false;
113
+ /** Host/app wants chunks; false pauses without finalizing so start can open a new segment. */
114
+ this.wanted = true;
107
115
  this.captureGate = Promise.resolve();
108
116
  this.untilStop = new Promise((resolve) => {
109
117
  this.release = resolve;
@@ -164,16 +172,23 @@ export class CanvasRecorder {
164
172
  const run = this.captureGate.then(async () => {
165
173
  if (this.finishing || !this.prepared) return;
166
174
  const live = hasActiveMedia(this.tracks);
167
- if (live && !this.capturing) await this.beginCapture();
168
- else if (!live && this.capturing) await this.pauseCapture();
175
+ if (this.wanted && live && !this.capturing) await this.beginCapture();
176
+ else if ((!this.wanted || !live) && this.capturing) await this.pauseCapture();
169
177
  });
170
178
  this.captureGate = run.catch(() => undefined);
171
179
  return run;
172
180
  }
173
181
 
182
+ /** Pause or resume capture without finalizing. New segments are combined on finish(). */
183
+ async setWanted(wanted) {
184
+ this.wanted = Boolean(wanted);
185
+ await this.updateCapture();
186
+ }
187
+
174
188
  async finish(options = {}) {
175
189
  if (this.finishing) return;
176
190
  this.finishing = true;
191
+ this.wanted = false;
177
192
  await this.captureGate.catch(() => undefined);
178
193
  const didCapture = Boolean(this.startedAt);
179
194
  if (this.capturing) {
@@ -369,9 +384,10 @@ export class CanvasRecorder {
369
384
  continue;
370
385
  }
371
386
  if (item.kind !== "video") continue;
372
- if (item.source !== "webcam" && item.source !== "screen") continue;
373
387
  if (disabled) continue;
374
- const kind = item.source === "screen" ? "screen" : "camera";
388
+ const featured = isFeaturedVideoSource(item.source);
389
+ if (!featured && item.source !== "webcam") continue;
390
+ const kind = featured ? "screen" : "camera";
375
391
  const key = `${item.participantKey}|${kind}`;
376
392
  const slot = {
377
393
  key,