mediascale-sdk 1.0.6 → 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.
@@ -1,4 +1,4 @@
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
 
@@ -173,6 +173,7 @@ await client.end(); // combines every segment into one file
173
173
  | `stop()` | Turns off the camera and the microphone. The screen share stays on. |
174
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. |
175
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. |
176
177
  | `end()` | Leaves the session. If this person is the one recording, every segment is combined and saved. |
177
178
  | `listDevices()` | Returns `{ cameras, microphones }`. Each item is `{ id, label }`. |
178
179
 
@@ -269,6 +270,13 @@ const client = createClient({
269
270
 
270
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.
271
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
+
272
280
  ## Recording
273
281
 
274
282
  ### When it starts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mediascale-sdk",
3
- "version": "1.0.6",
3
+ "version": "1.0.7",
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
@@ -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 },
@@ -87,6 +87,8 @@ export function createClient(options = {}) {
87
87
  let selfPeerId = null;
88
88
  const locals = new Map();
89
89
  const tiles = new Map();
90
+ /** source id → normalized crop for recording compositor (e.g. whiteboard). */
91
+ const recordingCrops = new Map();
90
92
  const pending = [];
91
93
  let readyPromise = null;
92
94
  let settleReady = null;
@@ -100,8 +102,34 @@ export function createClient(options = {}) {
100
102
  return { userAgent: ua, mobile, desktop: !mobile, chrome };
101
103
  }
102
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
+
103
115
  function syncRecording() {
104
- recorder?.sync(tracksFromTiles([...tiles.values()]));
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
+ }
105
133
  }
106
134
 
107
135
  async function consume(params) {
@@ -568,7 +596,8 @@ export function createClient(options = {}) {
568
596
  recorder = next;
569
597
  next.wanted = true;
570
598
  notifyRecording(next);
571
- next.sync(tracksFromTiles([...tiles.values()]));
599
+ for (const [source, crop] of recordingCrops) next.setVideoCrop(source, crop);
600
+ next.sync(tracksForRecording());
572
601
  try {
573
602
  await next.start();
574
603
  } catch (error) {
@@ -666,6 +695,7 @@ export function createClient(options = {}) {
666
695
  subscribe: guard(subscribe),
667
696
  startRecording: guard(startRecording),
668
697
  stopRecording: guard(stopRecording),
698
+ setRecordingCrop,
669
699
  end: guard(end),
670
700
  listDevices: guard(listDevices),
671
701
  };
@@ -83,16 +83,16 @@ export async function createWorkerCompositor({ width, height, fps, onError = ()
83
83
  const keys = new Set(desired.map((source) => source.key));
84
84
  for (const [key, entry] of owned) if (!keys.has(key)) { release(entry); owned.delete(key); }
85
85
  const transfer = [];
86
- const updates = desired.map(({ key, track, rect }) => {
86
+ const updates = desired.map(({ key, track, rect, crop }) => {
87
87
  const previous = owned.get(key);
88
- if (previous?.original === track) return { key, rect };
88
+ if (previous?.original === track) return { key, rect, crop: crop || null };
89
89
  if (previous) release(previous);
90
90
  const clone = track.clone();
91
91
  owned.set(key, { clone, original: track });
92
- if (standard) { transfer.push(clone); return { key, rect, track: clone }; }
92
+ if (standard) { transfer.push(clone); return { key, rect, crop: crop || null, track: clone }; }
93
93
  const readable = new MediaStreamTrackProcessor({ track: clone, maxBufferSize: 1 }).readable;
94
94
  transfer.push(readable);
95
- return { key, rect, readable };
95
+ return { key, rect, crop: crop || null, readable };
96
96
  });
97
97
  worker.postMessage({ type: "sources", sources: updates }, transfer);
98
98
  };
@@ -53,14 +53,28 @@ export class FrameCompositor {
53
53
  if (!this.active || !this.dirty || this.writing || now - this.lastDraw < this.interval) return;
54
54
  this.ctx.fillStyle = "#000";
55
55
  this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
56
- for (const { key, rect } of this.sources) {
56
+ for (const { key, rect, crop } of this.sources) {
57
57
  const frame = this.frames.get(key);
58
58
  if (!frame) continue;
59
59
  const width = frame.displayWidth || frame.codedWidth || rect.w;
60
60
  const height = frame.displayHeight || frame.codedHeight || rect.h;
61
- const scale = Math.min(rect.w / width, rect.h / height);
62
- const w = width * scale, h = height * scale;
63
- this.ctx.drawImage(frame, rect.x + (rect.w - w) / 2, rect.y + (rect.h - h) / 2, w, h);
61
+ let sx = 0;
62
+ let sy = 0;
63
+ let sw = width;
64
+ let sh = height;
65
+ const c = crop && crop.w > 0 && crop.h > 0 ? crop : null;
66
+ if (c) {
67
+ sx = c.x * width;
68
+ sy = c.y * height;
69
+ sw = c.w * width;
70
+ sh = c.h * height;
71
+ if (sw <= 1 || sh <= 1) continue;
72
+ }
73
+ // Contain: preserve aspect ratio (letterbox/pillarbox inside the slot).
74
+ const scale = Math.min(rect.w / sw, rect.h / sh);
75
+ const w = sw * scale;
76
+ const h = sh * scale;
77
+ this.ctx.drawImage(frame, sx, sy, sw, sh, rect.x + (rect.w - w) / 2, rect.y + (rect.h - h) / 2, w, h);
64
78
  }
65
79
  this.timestamp = Math.max(this.timestamp + 1, Math.round((now - this.startedAt) * 1000));
66
80
  const frame = this.makeFrame(this.canvas, { timestamp: this.timestamp });
@@ -69,7 +69,7 @@ self.onmessage = async ({ data }) => {
69
69
  } else if (data.type === "sources") {
70
70
  const keys = new Set(data.sources.map((source) => source.key));
71
71
  for (const key of readers.keys()) if (!keys.has(key)) remove(key);
72
- compositor.setSources(data.sources.map(({ key, rect }) => ({ key, rect })));
72
+ compositor.setSources(data.sources.map(({ key, rect, crop }) => ({ key, rect, crop: crop || null })));
73
73
  for (const source of data.sources) {
74
74
  if (!source.readable && !source.track) continue;
75
75
  remove(source.key);
package/src/record.js CHANGED
@@ -8,7 +8,8 @@ const PAD = 8;
8
8
  const GAP = 8;
9
9
  const FPS = 15;
10
10
  const SLICE_MS = 5000;
11
- const BITRATE = 2_000_000;
11
+ /** Higher bitrate keeps sharp avatar/text edges; 2 Mbps made placeholders look blurry. */
12
+ const BITRATE = 4_500_000;
12
13
  const mime = "video/webm;codecs=vp8,opus";
13
14
 
14
15
  /** Channel ids become a single path segment. The original text stays the webinar name. */
@@ -48,12 +49,30 @@ export function layoutSlots(cameras, screen) {
48
49
  };
49
50
  }
50
51
 
52
+ /** Normalized viewport crop `{ x, y, w, h }` in 0..1 (same as sample presence / subscriber CSS crop). */
53
+ export function normalizeVideoCrop(raw) {
54
+ if (!raw || typeof raw !== "object") return null;
55
+ const x = Number(raw.x);
56
+ const y = Number(raw.y);
57
+ const w = Number(raw.w);
58
+ const h = Number(raw.h);
59
+ if (![x, y, w, h].every((n) => Number.isFinite(n))) return null;
60
+ if (w <= 0 || h <= 0) return null;
61
+ return {
62
+ x: Math.min(1, Math.max(0, x)),
63
+ y: Math.min(1, Math.max(0, y)),
64
+ w: Math.min(1, Math.max(0.01, w)),
65
+ h: Math.min(1, Math.max(0.01, h)),
66
+ };
67
+ }
68
+
51
69
  /** One entry per mediasoup track the stage is showing. */
52
70
  export function tracksFromTiles(tiles) {
53
71
  const out = [];
54
72
  for (const item of tiles) {
55
73
  if (!item?.stream) continue;
56
74
  const participantKey = item.local ? "local" : (item.publisherId || item.displayName || item.producerId);
75
+ const crop = normalizeVideoCrop(item.crop);
57
76
  for (const track of item.stream.getTracks()) {
58
77
  if (track.readyState === "ended") continue;
59
78
  const source = item.source === "screen" && track.kind === "audio" ? "screen-audio" : item.source;
@@ -63,6 +82,7 @@ export function tracksFromTiles(tiles) {
63
82
  kind: track.kind,
64
83
  isLocal: Boolean(item.local),
65
84
  track,
85
+ ...(crop && track.kind === "video" ? { crop } : {}),
66
86
  });
67
87
  }
68
88
  }
@@ -112,6 +132,8 @@ export class CanvasRecorder {
112
132
  this.videos = new Map();
113
133
  this.audioNodes = new Map();
114
134
  this.placeholderSources = new Map();
135
+ /** source id → normalized crop for featured video (e.g. whiteboard tab capture). */
136
+ this.videoCrops = new Map();
115
137
  this.tries = new Map();
116
138
  this.chain = Promise.resolve();
117
139
  this.pendingStores = new Set();
@@ -212,10 +234,28 @@ export class CanvasRecorder {
212
234
 
213
235
  sync(tracks) {
214
236
  this.tracks = tracks || [];
237
+ for (const item of this.tracks) {
238
+ if (item?.kind !== "video" || !item.source) continue;
239
+ const crop = normalizeVideoCrop(item.crop);
240
+ if (crop) this.videoCrops.set(item.source, crop);
241
+ }
215
242
  if (this.prepared) this.retile();
216
243
  void this.updateCapture();
217
244
  }
218
245
 
246
+ /**
247
+ * Crop a published video source when compositing (same normalized bounds as the sample
248
+ * subscriber whiteboard crop: `{ x, y, w, h }` relative to the full captured frame).
249
+ */
250
+ setVideoCrop(source, crop) {
251
+ const id = String(source || "").trim();
252
+ if (!id) return;
253
+ const next = normalizeVideoCrop(crop);
254
+ if (!next) this.videoCrops.delete(id);
255
+ else this.videoCrops.set(id, next);
256
+ if (this.prepared) this.retile();
257
+ }
258
+
219
259
  updateCapture() {
220
260
  const run = this.captureGate.then(async () => {
221
261
  if (this.finishing || !this.prepared) return;
@@ -470,14 +510,18 @@ export class CanvasRecorder {
470
510
  if (!featured && item.source !== "webcam") continue;
471
511
  const kind = featured ? "screen" : "camera";
472
512
  const key = `${item.participantKey}|${kind}`;
513
+ const crop = normalizeVideoCrop(item.crop) || this.videoCrops.get(item.source) || null;
514
+ if (crop) this.videoCrops.set(item.source, crop);
473
515
  const slot = {
474
516
  key,
475
517
  kind,
476
518
  isLocal: item.isLocal,
477
519
  participantKey: item.participantKey,
520
+ source: item.source,
478
521
  order: this.orderOf(key),
479
522
  video: this.compositor ? null : this.videoFor(key, item.track),
480
523
  track: item.track,
524
+ crop: featured ? crop : null,
481
525
  };
482
526
  (kind === "screen" ? screens : cameras).set(key, slot);
483
527
  }
@@ -512,8 +556,8 @@ export class CanvasRecorder {
512
556
  if (this.compositor) {
513
557
  const layout = layoutSlots(chosen.length, Boolean(screen));
514
558
  this.compositor.setSources([
515
- ...(screen ? [{ key: screen.key, track: screen.track, rect: layout.screen }] : []),
516
- ...chosen.map((slot, index) => ({ key: slot.key, track: slot.track, rect: layout.cameras[index] })),
559
+ ...(screen ? [{ key: screen.key, track: screen.track, rect: layout.screen, crop: screen.crop || null }] : []),
560
+ ...chosen.map((slot, index) => ({ key: slot.key, track: slot.track, rect: layout.cameras[index], crop: null })),
517
561
  ]);
518
562
  }
519
563
  // Mix every mic (and screen audio). Overflow cameras stay off-layout but audible.
@@ -528,7 +572,7 @@ export class CanvasRecorder {
528
572
  }
529
573
  }
530
574
 
531
- /** Synthetic webcam matching the live empty-stage avatar tile. */
575
+ /** Synthetic webcam matching the live empty-stage avatar tile (native 1280×720, no upscale). */
532
576
  ensurePlaceholderTrack(name, isLocal) {
533
577
  const key = `placeholder|${isLocal ? "local" : name}`;
534
578
  let entry = this.placeholderSources.get(key);
@@ -539,9 +583,10 @@ export class CanvasRecorder {
539
583
  return entry.track;
540
584
  }
541
585
  const canvas = document.createElement("canvas");
542
- canvas.width = 640;
543
- canvas.height = 360;
544
- const ctx = canvas.getContext("2d");
586
+ // Match recording output size so the compositor does not upscale (blur).
587
+ canvas.width = W;
588
+ canvas.height = H;
589
+ const ctx = canvas.getContext("2d", { alpha: false, desynchronized: true });
545
590
  const stream = canvas.captureStream(FPS);
546
591
  const track = stream.getVideoTracks()[0];
547
592
  entry = { track, canvas, name, isLocal, redraw: null, timer: null };
@@ -632,7 +677,7 @@ export class CanvasRecorder {
632
677
  const layout = layoutSlots(cameras.length, Boolean(screen));
633
678
  this.ctx.fillStyle = "#000";
634
679
  this.ctx.fillRect(0, 0, W, H);
635
- if (screen && layout.screen) paint(this.ctx, screen.video, layout.screen);
680
+ if (screen && layout.screen) paint(this.ctx, screen.video, layout.screen, screen.crop);
636
681
  cameras.forEach((slot, index) => {
637
682
  const rect = layout.cameras[index];
638
683
  if (!rect) return;
@@ -640,7 +685,7 @@ export class CanvasRecorder {
640
685
  drawStagePlaceholder(this.ctx, rect.x, rect.y, rect.w, rect.h, slot.displayName || this.selfName, true);
641
686
  return;
642
687
  }
643
- paint(this.ctx, slot.video, rect);
688
+ paint(this.ctx, slot.video, rect, null);
644
689
  });
645
690
  this.capture?.requestFrame();
646
691
  }
@@ -778,51 +823,70 @@ function placeholderLetter(name) {
778
823
  return text ? text[0].toUpperCase() : "?";
779
824
  }
780
825
 
781
- /** Same magenta empty-stage look as the live sample UI. */
782
- function drawStagePlaceholder(ctx, x, y, w, h, name, isLocal) {
783
- const cx = x + w / 2;
784
- const cy = y + h / 2;
785
- const gradient = ctx.createRadialGradient(cx, cy, 0, cx, cy, Math.max(w, h) * 0.75);
786
- gradient.addColorStop(0, "rgb(152, 62, 107)");
787
- gradient.addColorStop(0.75, "rgb(104, 39, 71)");
788
- gradient.addColorStop(1, "rgb(104, 39, 71)");
789
- ctx.fillStyle = gradient;
826
+ /**
827
+ * Empty-stage tile for the recording canvas:
828
+ * maroon radial field, solid #bd5a61 disk (no border), white initial, name top-left.
829
+ */
830
+ function drawStagePlaceholder(ctx, x, y, w, h, name, _isLocal) {
831
+ const cx = Math.round(x + w / 2);
832
+ const cy = Math.round(y + h / 2);
833
+ const span = Math.max(w, h) * 0.75;
834
+ const field = ctx.createRadialGradient(cx, cy, 0, cx, cy, span);
835
+ field.addColorStop(0, "rgb(152, 62, 107)");
836
+ field.addColorStop(0.75, "rgb(104, 39, 71)");
837
+ field.addColorStop(1, "rgb(104, 39, 71)");
838
+ ctx.fillStyle = field;
790
839
  ctx.fillRect(x, y, w, h);
791
840
 
792
- const radius = Math.min(w, h) * 0.16;
841
+ const diameter = Math.round(Math.min(128, Math.max(88, Math.min(w, h) * 0.18)));
842
+ const radius = diameter / 2;
793
843
  ctx.beginPath();
794
844
  ctx.arc(cx, cy, radius, 0, Math.PI * 2);
795
- ctx.fillStyle = "rgba(255, 255, 255, 0.1)";
845
+ ctx.fillStyle = "#bd5a61";
796
846
  ctx.fill();
797
- ctx.lineWidth = Math.max(2, radius * 0.06);
798
- ctx.strokeStyle = "rgba(255, 255, 255, 0.72)";
799
- ctx.stroke();
800
847
 
801
- ctx.fillStyle = "#fff";
802
- ctx.font = `700 ${Math.round(radius * 1.15)}px Mulish, "Segoe UI", sans-serif`;
848
+ const letterPx = Math.round(Math.min(Math.max(diameter * 0.42, 28), 45));
849
+ ctx.fillStyle = "#ffffff";
850
+ ctx.font = `600 ${letterPx}px "Segoe UI", Roboto, Helvetica, Arial, sans-serif`;
803
851
  ctx.textAlign = "center";
804
852
  ctx.textBaseline = "middle";
805
853
  ctx.fillText(placeholderLetter(name), cx, cy + 1);
806
854
 
807
- const label = `${String(name || "Host").slice(0, 40)}${isLocal ? " (You)" : ""}`;
808
- const pad = Math.max(12, Math.round(h * 0.04));
855
+ const label = String(name || "Host").slice(0, 40);
856
+ const padX = Math.max(14, Math.round(w * 0.016));
857
+ const padY = Math.max(14, Math.round(h * 0.024));
858
+ const namePx = Math.round(Math.min(Math.max(h * 0.028, 14), 18));
809
859
  ctx.textAlign = "left";
810
- ctx.textBaseline = "alphabetic";
811
- ctx.font = `800 ${Math.max(14, Math.round(h * 0.045))}px Mulish, "Segoe UI", sans-serif`;
812
- ctx.fillStyle = "rgba(0, 0, 0, 0.35)";
813
- ctx.fillText(label, x + pad + 1, y + h - pad + 1);
814
- ctx.fillStyle = "#fff";
815
- ctx.fillText(label, x + pad, y + h - pad);
860
+ ctx.textBaseline = "top";
861
+ ctx.font = `500 ${namePx}px "Segoe UI", Roboto, Helvetica, Arial, sans-serif`;
862
+ ctx.fillStyle = "#ffffff";
863
+ ctx.fillText(label, x + padX, y + padY);
816
864
  }
817
865
 
818
- function paint(ctx, video, rect) {
866
+ function paint(ctx, video, rect, crop) {
819
867
  ctx.fillStyle = "#000";
820
868
  ctx.fillRect(rect.x, rect.y, rect.w, rect.h);
821
869
  if (!video || video.readyState < 2 || !video.videoWidth) return;
822
- const scale = Math.min(rect.w / video.videoWidth, rect.h / video.videoHeight);
823
- const dw = video.videoWidth * scale;
824
- const dh = video.videoHeight * scale;
825
- ctx.drawImage(video, rect.x + (rect.w - dw) / 2, rect.y + (rect.h - dh) / 2, dw, dh);
870
+ let sx = 0;
871
+ let sy = 0;
872
+ let sw = video.videoWidth;
873
+ let sh = video.videoHeight;
874
+ const cropNorm = normalizeVideoCrop(crop);
875
+ if (cropNorm) {
876
+ sx = cropNorm.x * video.videoWidth;
877
+ sy = cropNorm.y * video.videoHeight;
878
+ sw = cropNorm.w * video.videoWidth;
879
+ sh = cropNorm.h * video.videoHeight;
880
+ if (sw <= 1 || sh <= 1) return;
881
+ }
882
+ // Contain (not stretch): keep source aspect ratio inside the destination slot.
883
+ const scale = Math.min(rect.w / sw, rect.h / sh);
884
+ const dw = sw * scale;
885
+ const dh = sh * scale;
886
+ const prev = ctx.imageSmoothingEnabled;
887
+ ctx.imageSmoothingEnabled = scale < 0.98;
888
+ ctx.drawImage(video, sx, sy, sw, sh, rect.x + (rect.w - dw) / 2, rect.y + (rect.h - dh) / 2, dw, dh);
889
+ ctx.imageSmoothingEnabled = prev;
826
890
  }
827
891
 
828
892
  function sleep(ms) {