mediascale-sdk 1.0.0 → 1.0.2

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.
Files changed (3) hide show
  1. package/package.json +1 -1
  2. package/src/client.js +72 -19
  3. package/src/record.js +149 -52
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mediascale-sdk",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
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
@@ -77,12 +77,22 @@ export function createClient(options = {}) {
77
77
  let closed = false;
78
78
  let subscribed = false;
79
79
  let recorder = null;
80
+ let startingRecorder = null;
80
81
  const locals = new Map();
81
82
  const tiles = new Map();
82
83
  const pending = [];
83
84
  let readyPromise = null;
84
85
  let settleReady = null;
85
86
 
87
+ function clientHints() {
88
+ if (typeof navigator === "undefined") return {};
89
+ const ua = String(navigator.userAgent || "");
90
+ const mobile = /Mobile|Android|iPhone|iPad|iPod|webOS|Opera Mini|IEMobile/i.test(ua)
91
+ || (typeof navigator.maxTouchPoints === "number" && navigator.maxTouchPoints > 1 && /Macintosh/i.test(ua));
92
+ const chrome = /Chrome\/\d/i.test(ua) && !/Edg\/|OPR\/|Opera/i.test(ua);
93
+ return { userAgent: ua, mobile, desktop: !mobile, chrome };
94
+ }
95
+
86
96
  function syncRecording() {
87
97
  recorder?.sync(tracksFromTiles([...tiles.values()]));
88
98
  }
@@ -207,6 +217,18 @@ export function createClient(options = {}) {
207
217
  .then(() => onRecording("stopped"))
208
218
  .catch((error) => onError(error));
209
219
  });
220
+ // Portal elected this peer to continue an in-progress recording after the host left.
221
+ socket.on("takeRecording", () => {
222
+ startRecording().catch((error) => onError(error));
223
+ });
224
+ socket.on("finalizeRecording", () => {
225
+ const current = recorder;
226
+ if (!current) return;
227
+ recorder = null;
228
+ current.finish()
229
+ .then(() => onRecording("stopped"))
230
+ .catch((error) => onError(error));
231
+ });
210
232
  socket.on("connect", async () => {
211
233
  try {
212
234
  if (closed) return;
@@ -215,6 +237,7 @@ export function createClient(options = {}) {
215
237
  channelId: sessionId,
216
238
  role: "publisher",
217
239
  displayName,
240
+ ...clientHints(),
218
241
  });
219
242
  iceServers = iceOverride || joined.iceServers || [];
220
243
  device = new Device();
@@ -258,7 +281,14 @@ export function createClient(options = {}) {
258
281
  if (joined.waiting) onStatus("Please wait, we will connect you soon");
259
282
  else onStatus("Ready");
260
283
  if (closed) return;
261
- if (recording && claims.role === "host") await startRecording();
284
+ // Recording must not block join — claim/start can fail before media is published.
285
+ if (recording && claims.role === "host") {
286
+ try {
287
+ await startRecording();
288
+ } catch (error) {
289
+ onError(error);
290
+ }
291
+ }
262
292
  if (closed) return;
263
293
  settleReady?.();
264
294
  } catch (error) {
@@ -377,25 +407,37 @@ export function createClient(options = {}) {
377
407
  if (closed) throw new Error("The session has ended");
378
408
  if (!sendTransport) await connect();
379
409
  if (closed || recorder) return;
380
- await emit(socket, "claimRecording", {});
381
- const next = new CanvasRecorder({
382
- webinarId: recordingWebinarId(sessionId),
383
- webinarName: sessionId,
384
- recordingId: await recordingIdFor(sessionId),
385
- endpoint,
386
- token,
387
- });
388
- recorder = next;
389
- next.sync(tracksFromTiles([...tiles.values()]));
410
+ if (startingRecorder) return startingRecorder;
411
+ startingRecorder = (async () => {
412
+ await emit(socket, "claimRecording", {});
413
+ if (closed || recorder) return;
414
+ const next = new CanvasRecorder({
415
+ webinarId: recordingWebinarId(sessionId),
416
+ webinarName: sessionId,
417
+ recordingId: await recordingIdFor(sessionId),
418
+ endpoint,
419
+ token,
420
+ // Chunks only flow while webcam / mic / screenshare is live.
421
+ onCaptureChange: (active) => onRecording(active ? "recording" : "stopped"),
422
+ });
423
+ recorder = next;
424
+ next.sync(tracksFromTiles([...tiles.values()]));
425
+ try {
426
+ await next.start();
427
+ } catch {
428
+ if (recorder === next) recorder = null;
429
+ onRecording("stopped");
430
+ return;
431
+ }
432
+ 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");
435
+ })();
390
436
  try {
391
- await next.start();
392
- } catch {
393
- if (recorder === next) recorder = null;
394
- onRecording("stopped");
395
- return;
437
+ await startingRecorder;
438
+ } finally {
439
+ startingRecorder = null;
396
440
  }
397
- if (recorder !== next) return;
398
- onRecording("recording");
399
441
  }
400
442
 
401
443
  async function end() {
@@ -405,7 +447,18 @@ export function createClient(options = {}) {
405
447
  const current = recorder;
406
448
  recorder = null;
407
449
  if (current) {
408
- await current.finish();
450
+ let handoff = false;
451
+ if (socket?.connected) {
452
+ try {
453
+ const result = await emit(socket, "leaveRecording", {});
454
+ handoff = Boolean(result?.handoff);
455
+ } catch {
456
+ handoff = false;
457
+ }
458
+ }
459
+ // Cohost continues the same recordingId; only finalize when nobody else can take over.
460
+ if (handoff) await current.handoff();
461
+ else await current.finish();
409
462
  onRecording("stopped");
410
463
  }
411
464
  for (const entry of locals.values()) entry.track.stop();
package/src/record.js CHANGED
@@ -66,17 +66,30 @@ 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. */
70
+ export function hasActiveMedia(tracks) {
71
+ return (tracks || []).some((item) => {
72
+ const track = item?.track;
73
+ 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";
78
+ });
79
+ }
80
+
69
81
  export class CanvasRecorder {
70
82
  static supported() {
71
83
  return typeof MediaRecorder !== "undefined" && MediaRecorder.isTypeSupported(mime);
72
84
  }
73
85
 
74
- constructor({ webinarId, webinarName, recordingId, endpoint, token }) {
86
+ constructor({ webinarId, webinarName, recordingId, endpoint, token, onCaptureChange }) {
75
87
  this.webinarId = webinarId;
76
88
  this.webinarName = webinarName || webinarId;
77
89
  this.recordingId = recordingId;
78
90
  this.endpoint = String(endpoint || "").replace(/\/+$/, "");
79
91
  this.token = token || "";
92
+ this.onCaptureChange = typeof onCaptureChange === "function" ? onCaptureChange : () => {};
80
93
  this.segment = 0;
81
94
  this.seq = 0;
82
95
  this.startedAt = 0;
@@ -89,6 +102,9 @@ export class CanvasRecorder {
89
102
  this.tries = new Map();
90
103
  this.chain = Promise.resolve();
91
104
  this.finishing = false;
105
+ this.prepared = false;
106
+ this.capturing = false;
107
+ this.captureGate = Promise.resolve();
92
108
  this.untilStop = new Promise((resolve) => {
93
109
  this.release = resolve;
94
110
  });
@@ -110,8 +126,10 @@ export class CanvasRecorder {
110
126
  });
111
127
  const run = async () => {
112
128
  try {
113
- await this.open(this.audio);
129
+ // Prepare canvas/audio only. Chunks start after the first live A/V/screen track.
130
+ await this.prepare(this.audio);
114
131
  this.ready();
132
+ await this.updateCapture();
115
133
  if (this.finishing) return;
116
134
  await this.untilStop;
117
135
  } catch (err) {
@@ -138,24 +156,46 @@ export class CanvasRecorder {
138
156
 
139
157
  sync(tracks) {
140
158
  this.tracks = tracks || [];
141
- if (this.dest) this.retile();
159
+ if (this.prepared) this.retile();
160
+ void this.updateCapture();
161
+ }
162
+
163
+ updateCapture() {
164
+ const run = this.captureGate.then(async () => {
165
+ if (this.finishing || !this.prepared) return;
166
+ const live = hasActiveMedia(this.tracks);
167
+ if (live && !this.capturing) await this.beginCapture();
168
+ else if (!live && this.capturing) await this.pauseCapture();
169
+ });
170
+ this.captureGate = run.catch(() => undefined);
171
+ return run;
142
172
  }
143
173
 
144
174
  async finish(options = {}) {
145
175
  if (this.finishing) return;
146
176
  this.finishing = true;
177
+ await this.captureGate.catch(() => undefined);
178
+ const didCapture = Boolean(this.startedAt);
179
+ if (this.capturing) {
180
+ this.capturing = false;
181
+ this.onCaptureChange(false);
182
+ }
147
183
  const rec = this.recorder;
184
+ this.recorder = null;
148
185
  if (rec && rec.state !== "inactive") {
149
186
  const last = new Promise((resolve) => {
150
187
  rec.addEventListener("dataavailable", () => resolve(), { once: true });
151
188
  rec.addEventListener("stop", () => resolve(), { once: true });
152
189
  });
153
- if (rec.state === "recording") rec.requestData();
154
- rec.stop();
190
+ if (rec.state === "recording" || rec.state === "paused") {
191
+ try { rec.requestData(); } catch { /* ignore */ }
192
+ try { rec.stop(); } catch { /* ignore */ }
193
+ }
155
194
  await Promise.race([last, sleep(3000)]);
156
195
  }
157
196
  await this.pump();
158
- if (options.finalize !== false) await this.finalize();
197
+ // Skip finalize when nothing was ever captured (no live media during the session).
198
+ if (options.finalize !== false && didCapture) await this.finalize();
159
199
  this.release?.();
160
200
  this.release = undefined;
161
201
  }
@@ -186,8 +226,8 @@ export class CanvasRecorder {
186
226
  return data;
187
227
  }
188
228
 
189
- async open(audio) {
190
- if (this.finishing) return;
229
+ async prepare(audio) {
230
+ if (this.finishing || this.prepared) return;
191
231
  this.audio = audio ?? new AudioContext();
192
232
  await this.audio.resume();
193
233
  if (this.audio.state !== "running") throw new Error("Click the page to continue this recording");
@@ -202,14 +242,6 @@ export class CanvasRecorder {
202
242
  document.body.appendChild(this.canvas);
203
243
  await this.flushStored();
204
244
  if (this.finishing) return;
205
- const opened = await this.api("POST", `/api/chunks/${this.recordingId}/segment`, {
206
- webinarId: this.webinarId,
207
- webinarName: this.webinarName,
208
- next: true,
209
- });
210
- this.segment = opened.segment;
211
- this.seq = 0;
212
- this.startedAt = Date.now();
213
245
  this.dest = this.audio.createMediaStreamDestination();
214
246
  const silence = this.audio.createGain();
215
247
  silence.gain.value = 0;
@@ -225,9 +257,30 @@ export class CanvasRecorder {
225
257
  this.stopDraw = () => worker.terminate();
226
258
  const video = this.canvas.captureStream(FPS).getVideoTracks()[0];
227
259
  this.capture = video;
228
- const stream = new MediaStream([video, this.dest.stream.getAudioTracks()[0]]);
229
- this.recorder = new MediaRecorder(stream, { mimeType: mime, videoBitsPerSecond: BITRATE, audioBitsPerSecond: 128_000 });
260
+ this.captureStream = new MediaStream([video, this.dest.stream.getAudioTracks()[0]]);
261
+ this.prepared = true;
262
+ window.addEventListener("beforeunload", this.onPageHide);
263
+ }
264
+
265
+ async beginCapture() {
266
+ if (this.finishing || this.capturing || !this.prepared || !this.captureStream) return;
267
+ const opened = await this.api("POST", `/api/chunks/${this.recordingId}/segment`, {
268
+ webinarId: this.webinarId,
269
+ webinarName: this.webinarName,
270
+ next: true,
271
+ });
272
+ if (this.finishing || !hasActiveMedia(this.tracks)) return;
273
+ this.segment = opened.segment;
274
+ this.seq = 0;
275
+ if (!this.startedAt) this.startedAt = Date.now();
276
+ this.recorder = new MediaRecorder(this.captureStream, {
277
+ mimeType: mime,
278
+ videoBitsPerSecond: BITRATE,
279
+ audioBitsPerSecond: 128_000,
280
+ });
230
281
  this.recorder.ondataavailable = (event) => {
282
+ // Drop slices while nothing live is on stage (pause races / trailing ticks).
283
+ if (!this.capturing || !hasActiveMedia(this.tracks)) return;
231
284
  if (event.data.size < 32 || !this.segment) return;
232
285
  const seq = ++this.seq;
233
286
  void this.store(seq, event.data).then(() => this.pump()).catch(() => undefined);
@@ -237,7 +290,8 @@ export class CanvasRecorder {
237
290
  };
238
291
  if (this.finishing) return;
239
292
  this.recorder.start(SLICE_MS);
240
- window.addEventListener("beforeunload", this.onPageHide);
293
+ this.capturing = true;
294
+ this.onCaptureChange(true);
241
295
  try {
242
296
  this.wake = await navigator.wakeLock?.request("screen");
243
297
  } catch {
@@ -252,25 +306,71 @@ export class CanvasRecorder {
252
306
  }, 30_000);
253
307
  }
254
308
 
309
+ async pauseCapture() {
310
+ if (!this.capturing) return;
311
+ this.capturing = false;
312
+ this.onCaptureChange(false);
313
+ const rec = this.recorder;
314
+ this.recorder = null;
315
+ if (rec && rec.state !== "inactive") {
316
+ const last = new Promise((resolve) => {
317
+ rec.addEventListener("dataavailable", () => resolve(), { once: true });
318
+ rec.addEventListener("stop", () => resolve(), { once: true });
319
+ });
320
+ if (rec.state === "recording" || rec.state === "paused") {
321
+ try { rec.requestData(); } catch { /* ignore */ }
322
+ try { rec.stop(); } catch { /* ignore */ }
323
+ }
324
+ await Promise.race([last, sleep(1500)]);
325
+ }
326
+ await this.pump().catch(() => undefined);
327
+ if (this.heartbeat) {
328
+ clearInterval(this.heartbeat);
329
+ this.heartbeat = undefined;
330
+ }
331
+ if (this.sweep) {
332
+ clearInterval(this.sweep);
333
+ this.sweep = undefined;
334
+ }
335
+ try {
336
+ await this.wake?.release();
337
+ } catch {
338
+ // ignore
339
+ }
340
+ this.wake = undefined;
341
+ this.segment = 0;
342
+ }
343
+
255
344
  retile() {
345
+ if (this._retiling) return;
346
+ this._retiling = true;
347
+ try {
348
+ this.retileUnsafe();
349
+ } finally {
350
+ this._retiling = false;
351
+ }
352
+ }
353
+
354
+ retileUnsafe() {
256
355
  const cameras = new Map();
257
356
  const screens = new Map();
258
357
  const mics = new Map();
259
358
  const screenAudio = new Map();
260
359
  for (const item of this.tracks) {
261
- const off = !item.track.enabled || item.track.muted;
360
+ // Remote WebRTC tracks often start muted until media arrives; do not drop them
361
+ // from the layout — paint() skips blank frames, and unmute re-triggers retile.
362
+ const disabled = !item.track.enabled;
262
363
  if (item.source === "mic") {
263
- if (!off) mics.set(item.isLocal ? "local-mic" : `${item.participantKey}|mic`, item.track);
364
+ if (!disabled) mics.set(item.isLocal ? "local-mic" : `${item.participantKey}|mic`, item.track);
264
365
  continue;
265
366
  }
266
367
  if (item.source === "screen-audio") {
267
- if (!off) screenAudio.set(item.participantKey, item.track);
368
+ if (!disabled) screenAudio.set(item.participantKey, item.track);
268
369
  continue;
269
370
  }
270
371
  if (item.kind !== "video") continue;
271
372
  if (item.source !== "webcam" && item.source !== "screen") continue;
272
- if (item.source === "screen" && off) continue;
273
- if (!item.isLocal && off) continue;
373
+ if (disabled) continue;
274
374
  const kind = item.source === "screen" ? "screen" : "camera";
275
375
  const key = `${item.participantKey}|${kind}`;
276
376
  const slot = {
@@ -279,34 +379,28 @@ export class CanvasRecorder {
279
379
  isLocal: item.isLocal,
280
380
  participantKey: item.participantKey,
281
381
  order: this.orderOf(key),
282
- video: off ? null : this.videoFor(key, item.track),
382
+ video: this.videoFor(key, item.track),
283
383
  };
284
384
  (kind === "screen" ? screens : cameras).set(key, slot);
285
385
  }
286
- if (![...cameras.values()].some((slot) => slot.isLocal)) {
287
- cameras.set("local|camera", {
288
- key: "local|camera",
289
- kind: "camera",
290
- isLocal: true,
291
- participantKey: "local",
292
- order: 0,
293
- video: null,
294
- });
295
- }
296
- const host = [...cameras.values()].find((slot) => slot.isLocal);
297
- const others = [...cameras.values()].filter((slot) => !slot.isLocal).sort((a, b) => a.order - b.order).slice(0, 3);
298
- const chosen = [host, ...others];
386
+ // Up to 4 camera tiles: prefer local host first, then earliest remotes.
387
+ const localCam = [...cameras.values()].find((slot) => slot.isLocal);
388
+ const remotes = [...cameras.values()]
389
+ .filter((slot) => !slot.isLocal)
390
+ .sort((a, b) => a.order - b.order);
391
+ const chosen = (localCam ? [localCam, ...remotes] : remotes).slice(0, 4);
299
392
  const screen = [...screens.values()].find((slot) => slot.isLocal)
300
393
  ?? [...screens.values()].sort((a, b) => a.order - b.order)[0];
301
394
  this.slots = screen ? [screen, ...chosen] : chosen;
395
+ // Mix every mic (and screen audio). Overflow cameras stay off-layout but audible.
302
396
  this.mixAudio(chosen, screen, mics, screenAudio);
397
+ const liveKeys = new Set(this.slots.filter((slot) => slot.video).map((slot) => slot.key));
303
398
  for (const key of [...this.videos.keys()]) {
304
- if (!this.slots.some((slot) => slot.key === key && slot.video)) {
305
- const el = this.videos.get(key);
306
- el?.pause();
307
- if (el) el.srcObject = null;
308
- this.videos.delete(key);
309
- }
399
+ if (liveKeys.has(key)) continue;
400
+ const el = this.videos.get(key);
401
+ el?.pause();
402
+ if (el) el.srcObject = null;
403
+ this.videos.delete(key);
310
404
  }
311
405
  }
312
406
 
@@ -330,21 +424,24 @@ export class CanvasRecorder {
330
424
  el.playsInline = true;
331
425
  el.srcObject = new MediaStream([track]);
332
426
  void el.play().catch(() => undefined);
427
+ const refresh = () => {
428
+ if (!this.dest || this.finishing) return;
429
+ queueMicrotask(() => {
430
+ if (this.dest && !this.finishing) this.retile();
431
+ });
432
+ };
433
+ track.addEventListener("unmute", refresh);
434
+ track.addEventListener("mute", refresh);
435
+ track.addEventListener("ended", refresh);
333
436
  this.videos.set(key, el);
334
437
  }
335
438
  return el;
336
439
  }
337
440
 
338
- mixAudio(cameras, screen, mics, screenAudio) {
441
+ mixAudio(_cameras, screen, mics, screenAudio) {
339
442
  if (!this.audio || !this.dest) return;
340
443
  const wanted = new Map();
341
- const localMic = mics.get("local-mic");
342
- if (localMic) wanted.set("local-mic", localMic);
343
- for (const cam of cameras) {
344
- if (cam.isLocal) continue;
345
- const mic = mics.get(`${cam.participantKey}|mic`);
346
- if (mic) wanted.set(cam.key, mic);
347
- }
444
+ for (const [key, track] of mics) wanted.set(key, track);
348
445
  if (screen) {
349
446
  const audio = screenAudio.get(screen.participantKey);
350
447
  if (audio) wanted.set(`${screen.key}|audio`, audio);