mediascale-sdk 1.0.15 → 1.0.17

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.
@@ -47,6 +47,8 @@ export async function POST(request) {
47
47
  const recording = body.recording === true || body.recording === "1" || body.recording === 1;
48
48
  // Host-only: when true and destinations exist for this sessionId, SDK auto Go Live on connect().
49
49
  const rtmp = body.rtmp === true || body.rtmp === "1" || body.rtmp === 1;
50
+ // Host-only, optional: "rtmp" = live stream first (WebRTC video starts when someone joins).
51
+ const startMode = rtmp && body.startMode === "rtmp" ? "rtmp" : undefined;
50
52
  if (!sessionId) return Response.json({ error: "sessionId is required" }, { status: 400 });
51
53
 
52
54
  const payload = {
@@ -54,7 +56,7 @@ export async function POST(request) {
54
56
  role,
55
57
  name,
56
58
  // Host-only: when true, createClient starts recording on connect() even if you omit recording: true.
57
- ...(role === "host" ? { recording, rtmp } : { recording: false }),
59
+ ...(role === "host" ? { recording, rtmp, ...(startMode ? { startMode } : {}) } : { recording: false }),
58
60
  exp: Date.now() + 2 * 60 * 60 * 1000,
59
61
  };
60
62
  const encoded = Buffer.from(JSON.stringify(payload)).toString("base64url");
@@ -74,6 +76,7 @@ Token claims the SDK reads:
74
76
  | `name` | Display name |
75
77
  | `recording` | When `true` on a **host** token, auto-start recording on `connect()` unless `createClient({ recording: false })` |
76
78
  | `rtmp` | When `true` on a **host** token **and** the meeting already has enabled destinations, the SDK calls `startRtmp()` automatically after `connect()`. Stream keys are **never** put in the token. Hosts can still open Live and stream without this claim by adding destinations in-meeting. |
79
+ | `startMode` | Optional, **host** token with `rtmp: true`. `webrtc` (default) or `rtmp` (live stream first). With `rtmp`, the host sends only the H264 stage and one Opus mic to the live platforms. Camera, screen and custom tracks stay in the browser and still appear on the stage. They are published to WebRTC (VP8 by default) as soon as anyone else joins the room. See [Start modes](#start-modes). |
77
80
  | `exp` | Expiry as a Unix timestamp in **milliseconds** |
78
81
 
79
82
  ### Sample stage roles (meet UI)
@@ -116,6 +119,56 @@ Rules:
116
119
 
117
120
  Without `setRecordingStage`, recording falls back to live tracks only (plus a single host placeholder when nobody is publishing) — so off-stage speakers without video will be **missing** from the file.
118
121
 
122
+ ### Active speaker in the recording
123
+
124
+ Keep server-side active-speaker detection enabled the same way you do for the live UI. The SDK already receives portal `activeSpeaker` events and paints a **cyan speak ring** on the matching camera or camera-off avatar tile in the recorded file. You do **not** call a separate “setSpeaking” API.
125
+
126
+ | Required? | Action |
127
+ | --- | --- |
128
+ | No (if already done for live UI) | Keep active-speaker detection enabled server-side |
129
+ | No new callback | Do not call a speak API — the recording host browser applies speak state automatically |
130
+ | Keep as today | Continue `setRecordingStage([{ id, name, local?, ... }])` so stage ids match peer ids used by `activeSpeaker` |
131
+ | Only if not 1080p | Pass once: `createClient({ recordingResolution: 2048 })` → `3640×2048` WebM (see [Recording resolution](#recording-resolution-custom-height)) |
132
+ | Verify | The recording host is the browser that receives portal `activeSpeaker` (same as live highlight) |
133
+
134
+ ### Recording resolution (custom height)
135
+
136
+ The recorded WebM defaults to **1080p** (`1920×1080`). To raise (or lower) quality, set a custom **vertical** resolution — same meaning as “720p” / “1080p” / “2048p”: the number is the **height**, and width is derived at **16:9** (even dimensions for the encoder).
137
+
138
+ | `recordingResolution` | Output canvas | Notes |
139
+ | --- | --- | --- |
140
+ | unset / `1080` / `"1080p"` | `1920×1080` | Default |
141
+ | `720` / `"720p"` | `1280×720` | |
142
+ | `2048` / `"2048p"` | `3640×2048` | Custom “2048p” |
143
+ | any number `N` (360–4096) | width ≈ `N × 16/9` × height `N` | Height is clamped to 360–4096 |
144
+
145
+ Pass it once when creating the client (recommended for webinar apps), or when starting / updating recording:
146
+
147
+ ```js
148
+ // Preferred: set once at create time
149
+ const client = createClient({
150
+ endpoint,
151
+ sessionId,
152
+ token,
153
+ recording: true,
154
+ recordingResolution: 2048, // → 3640×2048 WebM
155
+ // recordingBitrate: 16_000_000, // optional override (bps); otherwise scales with pixels
156
+ });
157
+
158
+ // Or change before the next segment
159
+ client.setRecordingResolution(2048);
160
+ client.getRecordingResolution(); // { resolution: 2048, width: 3640, height: 2048 }
161
+
162
+ await client.startRecording({ resolution: 2048 });
163
+ ```
164
+
165
+ **Details for integrators**
166
+
167
+ - Size and bitrate apply on the **next** recorder open / segment start (same pattern as `recordingFps`). A running segment keeps its size.
168
+ - VP8 bitrate scales with pixel count (~4.5 Mbps at 1080p; ~16 Mbps at 2048p) unless you set `recordingBitrate`.
169
+ - This only affects the **recording** canvas, not live RTMP (`rtmpResolution` is separate and still capped at 1080p).
170
+ - The JWT / Stream Control meet link does not carry resolution; set it in your app via `createClient` (the sample also accepts `?recordingResolution=2048` on the meet URL for QA).
171
+
119
172
  ## 2. Copy the room page
120
173
 
121
174
  Copy `sdk/react-sdk/sample/app/room.js` into your app. The comments in that file are the steps.
@@ -222,7 +275,7 @@ await client.end(); // combines every segment into one file
222
275
 
223
276
  | Function | What it does |
224
277
  | --- | --- |
225
- | `createClient({ endpoint, sessionId, token, recording, canvasBackground, avatarBackground, recordingFps, recordingBitrate, rtmpResolution, rtmpFps, rtmpBitrate, rtmpKeyframeInterval, iceServers, publishLimits, ...callbacks })` | Prepares the client. `sessionId` and `token` are required. `endpoint` defaults to `http://localhost:8080`. `recording` defaults to **false**. Optional `canvasBackground` (CSS color or gradient, default `#0A0036`; `recordingCanvasBackground` is the older name) and `avatarBackground` (camera-off tile gradient or list) style both recording and RTMP — see [Stage look](#stage-look-background--avatars). Optional `publishLimits: { cameraBps, screenBps }` overrides portal join caps. Frame rates are independent: `recordingFps` (default **15**) and `rtmpFps` (default **30**), each 1–60. `recordingBitrate` (default 4.5 Mbps) and `rtmpBitrate` (default and max 2.5 Mbps) are in bps. RTMP output quality: `rtmpResolution` (preset `480p`/`540p`/`720p`/`1080p` or any custom `"WxH"` / `{ width, height }`, default **1080p**), `rtmpKeyframeInterval` (seconds, default **2**) — or group them as `rtmpQuality: { resolution, fps, bitrate, keyframeInterval }`. See [Live stream quality](#live-stream-quality). |
278
+ | `createClient({ endpoint, sessionId, token, recording, canvasBackground, avatarBackground, recordingFps, recordingResolution, recordingBitrate, rtmpResolution, rtmpFps, rtmpBitrate, rtmpKeyframeInterval, iceServers, publishLimits, ...callbacks })` | Prepares the client. `sessionId` and `token` are required. `endpoint` defaults to `http://localhost:8080`. `recording` defaults to **false**. Optional `canvasBackground` (CSS color or gradient, default `#0A0036`; `recordingCanvasBackground` is the older name) and `avatarBackground` (camera-off tile gradient or list) style both recording and RTMP — see [Stage look](#stage-look-background--avatars). Optional `publishLimits: { cameraBps, screenBps }` overrides portal join caps. Frame rates are independent: `recordingFps` (default **15**) and `rtmpFps` (default **30**), each 1–60. `recordingResolution` defaults to **1080p** (`1920×1080`); a number `N` (e.g. `2048`) sets the **height** at 16:9 (like 1080p) — see [Recording resolution](#recording-resolution). `recordingBitrate` (default ~4.5 Mbps at 1080p, scales with pixels) and `rtmpBitrate` (default and max 2.5 Mbps) are in bps. RTMP output quality: `rtmpResolution` (preset `480p`/`540p`/`720p`/`1080p` or any custom `"WxH"` / `{ width, height }`, default **1080p**), `rtmpKeyframeInterval` (seconds, default **2**) — or group them as `rtmpQuality: { resolution, fps, bitrate, keyframeInterval }`. See [Live stream quality](#live-stream-quality). Optional `videoCodec` (string or ordered list) sets the WebRTC camera / screen codec preference. The default is **`vp8`**, then `h264`, `vp9`, `av1`; the first one the browser and server both support is used. The live (RTMP) stage is always H264. |
226
279
  | `connect()` | Checks the token and joins the session. If recording is enabled for a **host**, recording starts in the background. If the host token has `rtmp: true` and the meeting already has enabled destinations, `startRtmp()` also runs in the background. Join does not wait for either to finish preparing. |
227
280
  | `subscribe()` | Starts playing the other people. Call this once after `connect()`. |
228
281
  | `startCamera({ cameraId, resolution, track })` | Publishes the camera. Pass `track` to use your own live video track (SDK clones it). |
@@ -237,11 +290,12 @@ await client.end(); // combines every segment into one file
237
290
  | `stopCustomStream(identifier)` | Stops that custom stream. |
238
291
  | `publish({ cameraId, micId, resolution })` | Turns on the camera and the microphone together. |
239
292
  | `stop()` | Turns off the camera and the microphone. The screen share stays on. |
240
- | `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. |
293
+ | `startRecording({ resolution? })` | Starts recording for this person (or resumes after `stopRecording()`). Optional `resolution` overrides `recordingResolution` for the next segment (same semantics as [Recording resolution](#recording-resolution)). 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. |
241
294
  | `stopRecording()` | Pauses recording without saving. Call `startRecording()` again to continue; `end()` still combines all segments into one file. |
242
295
  | `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. |
243
296
  | `setRecordingStage(people)` | **Required for stage-accurate recording.** Who appears on the recording stage: `[{ id, name, local?, avatarBackground? }]` (max six on canvas). `avatarBackground` overrides that person's camera-off gradient. Avatars + name pills until that peer’s webcam arrives. See [Recording must match the live stage](#recording-must-match-the-live-stage). |
244
297
  | `setRecordingFps(fps)` / `getRecordingFps()` | Recording frame rate (1–60). Applies to the next `startRecording()`; a running segment keeps its rate. |
298
+ | `setRecordingResolution(resolution)` / `getRecordingResolution()` | Custom recording output size for the next segment. `1080` → `1920×1080`; `2048` / `"2048p"` → height 2048 at 16:9 (`3640×2048`). See [Recording resolution](#recording-resolution-custom-height). `getRecordingResolution()` returns `{ resolution, width, height }`. |
245
299
  | `startRtmp({ destinations? })` | **Go Live** (host / co-host). Streams the stage to every enabled destination. Optional `destinations` are added first. Also runs automatically after `connect()` when the host token has `rtmp: true` and destinations already exist. Throws if the browser cannot encode H264. |
246
300
  | `stopRtmp()` | Ends the live stream on every platform. Destinations stay saved so the host can Go Live again. |
247
301
  | `addRtmpDestinations(list)` | Adds `[{ platform, streamKey, serverUrl?, label? }]`. `platform` is `youtube`, `twitch`, `facebook`, or `custom` (custom needs `serverUrl`). Works before or during a live stream. |
@@ -252,6 +306,8 @@ await client.end(); // combines every segment into one file
252
306
  | `setAppearance({ canvasBackground, avatarBackground })` / `getAppearance()` | Change the stage backdrop / camera-off gradients live (recording and RTMP, no restart). `getAppearance().canvasBackgroundCss` is a ready CSS `background` for your own stage. |
253
307
  | `setRtmpQuality({ resolution, fps, bitrate, keyframeInterval })` / `getRtmpQuality()` | Change any subset of the RTMP output quality. While live: `bitrate` applies instantly, `fps` / `resolution` restart the compositor in place, `keyframeInterval` applies on the next Go Live. Returns `{ resolution, width, height, fps, bitrate, keyframeInterval }`. |
254
308
  | `canLiveStream()` | `true` when this browser can compose and encode H264. Hide or disable Go Live when this is `false`. |
309
+ | `getMediaDemand()` | `{ webrtc }`. `false` while a live-stream-first room has nobody else in it: camera / screen tracks are kept local, and the stage and your preview still show them. |
310
+ | `getVideoCodecs()` | The ordered WebRTC video codec preference in use (`["vp8", "h264", "vp9", "av1"]` by default). |
255
311
  | `isRtmpEnabled()` | `true` after a host has joined (or a co-host has opened Live). Safe to show the Live control when this is true for managers. |
256
312
  | `getPeerId()` | Socket peer id for this browser after `connect()`. |
257
313
  | `getPublishLimits()` | Current `{ cameraBps, screenBps }` used for outgoing video encode caps. |
@@ -274,6 +330,7 @@ Pass these to `createClient`.
274
330
  | `onRecording(state)` | `armed` briefly while capture is preparing. `recording` while chunks are uploading. `stopped` after `stopRecording()`, handoff, or `end()`. |
275
331
  | `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. |
276
332
  | `onRtmpStatus(status)` | Live stream state changed. `status` is `{ enabled, state, live, startedAt, composing }`; hosts and co-hosts also get `destinations: [{ id, platform, label, host, keyHint, enabled, state, kbps, error }]`, `fps`, and `error`. `state` is `idle`, `starting`, `connecting`, `waiting-media`, `live`, `reconnecting`, `failed`, or `error`. |
333
+ | `onMediaDemand({ webrtc })` | Optional. Fires after join and whenever the portal changes WebRTC demand (live-stream-first rooms only). Nothing needs to change in your UI: `startCamera` / `startScreenShare` work the same and return a stream for the preview either way. |
277
334
  | `onStageChanged(people)` | Optional. Fires when the recording stage list changes after `setRecordingStage` (or sample roster updates). |
278
335
  | `onUserList` / `onUserJoined` / `onUserLeft` / `onUserUpdated` / `onUserBlocked` | Optional portal roster events for the sample meet UI. Not required if your webinar app manages join/leave/stage itself — use `setRecordingStage` instead. |
279
336
 
@@ -403,6 +460,7 @@ Canvas is **1280×720**. Video tiles and audio follow these rules:
403
460
  - Label comes from `setRecordingStage` `name`, else the track `displayName`, else the local host JWT name (`Guest` / `Host` as fallback). Presenter gets `(Presenter)` on the pill.
404
461
  - The pill is drawn even while the first video frame is still loading (dark tile + name).
405
462
  - The large screen / whiteboard pane does **not** get a name pill.
463
+ - **Active speaker:** a cyan ring (same as live `.tile.speaking`) is burned onto the speaking camera or avatar tile. Presenter name-pill chrome stays separate from the speak ring.
406
464
 
407
465
  Use `setRecordingStage([{ id, name, local? }, ...])` so avatar tiles and name pills match the live stage. Without it, only live tracks appear (plus a single host placeholder when nobody is publishing).
408
466
 
@@ -486,6 +544,26 @@ A host streams the meeting to several platforms at once (YouTube, Twitch, Facebo
486
544
 
487
545
  Audience tokens never get `rtmp`. Stream keys never go in the JWT — only in destination storage / `addRtmpDestinations`.
488
546
 
547
+ ### Start modes
548
+
549
+ How the host's media is sent depends on how the webinar starts (`startMode` on the host token). Both modes end up in the same state once Live and WebRTC participants are both present.
550
+
551
+ | | `webrtc` (default) | `rtmp` — live stream first |
552
+ |---|---|---|
553
+ | At start | Camera / screen / mic → origin → edge → viewers (VP8 by default) | H264 stage + one Opus mic → origin → RTMP service → platforms. Camera / screen are only drawn into the stage |
554
+ | A WebRTC participant joins | Already published | Portal sends `mediaDemand { webrtc: true }`; the SDK publishes camera / screen / custom tracks (VP8 by default). The viewer also gets the existing mic |
555
+ | Host goes Live | An extra H264 stage goes to RTMP | Already live |
556
+ | Last participant leaves | Unchanged | After 30 s the SDK stops the WebRTC video producers; the local tracks keep running |
557
+
558
+ **Audio is one Opus stream whenever possible.** When nothing needs mixing, RTMP uses the host's `mic` producer directly. Nothing needs mixing when:
559
+ - no other microphone is on the stage,
560
+ - there is no screen or tab audio, and
561
+ - the host's mic is on.
562
+
563
+ When a mix becomes necessary, the SDK switches that same producer to the stage mix. Platforms never reconnect. The SDK then publishes a fresh `mic` for WebRTC viewers, so there are two Opus streams only while mixing. Once the mix has been unnecessary for 10 s, it goes back to one. All of this happens inside the SDK; apps call the same functions as before.
564
+
565
+ Stream Control → Webinar → Live streaming → **Start with: Live stream only** creates a `startMode: "rtmp"` host link. With your own token route, add `startMode: "rtmp"` next to `rtmp: true`; at least one destination must exist.
566
+
489
567
  ### Path A — Stream Control webinar create
490
568
 
491
569
  Stream Control → Webinar → **Enable live streaming (RTMP)** saves destinations (keys encrypted) and puts `rtmp: true` on the host link.
@@ -511,6 +589,7 @@ await fetch("/api/token", {
511
589
  name: hostDisplayName,
512
590
  recording: true, // optional
513
591
  rtmp: true, // auto Go Live when destinations already exist
592
+ startMode: "rtmp", // optional: live stream first, WebRTC video only once someone joins
514
593
  }),
515
594
  });
516
595
  ```
@@ -534,6 +613,7 @@ const client = createClient({
534
613
  rtmpBitrate: 2_500_000, // bps, max 2 500 000 (2500 kbps)
535
614
  rtmpKeyframeInterval: 2, // seconds (default 2)
536
615
  recordingFps: 15, // independent of rtmpFps
616
+ recordingResolution: 2048, // optional custom height (3640×2048); default 1080p
537
617
  onRtmpStatus: (status) => {
538
618
  // status.enabled — show Live for managers once the room allows it
539
619
  // status.live — true when platforms are receiving
@@ -664,6 +744,7 @@ RTMP server (one VM runs many meetings)
664
744
  | Option | Default | Used for |
665
745
  | --- | --- | --- |
666
746
  | `recordingFps` | `15` | MediaRecorder recording canvas |
747
+ | `recordingResolution` | `1080` (`1920×1080`) | Custom MediaRecorder size; number `N` / `"Np"` = **height** at 16:9 (`2048` → `3640×2048`). See [Recording resolution](#recording-resolution-custom-height). |
667
748
  | `rtmpFps` | `30` | Live stream canvas and H264 encode |
668
749
 
669
750
  Separate canvases — each rate is independent. Live compositor window events: `mediascale:live-mode` / `mediascale:live-error`.
@@ -709,4 +790,4 @@ Open http://localhost:3200. The page asks your Next.js server for a token, then
709
790
 
710
791
  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`.
711
792
 
712
- 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` and `rtmp` from those toggles. When RTMP destinations were saved at create, the host page **starts streaming on join**; the **LIVE** button stays available to end, restart, or edit destinations (`sample/app/live-panel.js`). `?recordingFps=15&rtmpFps=30` on the meet URL overrides frame rates for testing.
793
+ 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` and `rtmp` from those toggles. When RTMP destinations were saved at create, the host page **starts streaming on join**; the **LIVE** button stays available to end, restart, or edit destinations (`sample/app/live-panel.js`). `?recordingFps=15&rtmpFps=30&recordingResolution=2048` on the meet URL overrides recording/live quality for testing. Active-speaker glow in the downloaded WebM needs no extra sample code — portal `activeSpeaker` is forwarded into the recorder automatically.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mediascale-sdk",
3
- "version": "1.0.15",
3
+ "version": "1.0.17",
4
4
  "description": "Mediascale React/browser SDK for live sessions, WebRTC publish/subscribe, recording, and RTMP live streaming",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/client.js CHANGED
@@ -4,6 +4,7 @@ import {
4
4
  CanvasRecorder,
5
5
  DEFAULT_RECORDING_FPS,
6
6
  clampFps,
7
+ normalizeRecordingResolution,
7
8
  normalizeVideoCrop,
8
9
  recordingWebinarId,
9
10
  resolveRecorderAffinity,
@@ -27,6 +28,28 @@ const SIZES = {
27
28
  /** Built-in sources that have dedicated start/stop helpers. */
28
29
  const RESERVED_SOURCES = new Set(["webcam", "mic", "screen", "screen-audio"]);
29
30
 
31
+ /**
32
+ * WebRTC video codec preference. VP8 is the default; the next codec in the list is used
33
+ * only when the browser cannot send the previous one (or the server does not offer it).
34
+ * Override with createClient({ videoCodec: "h264" }) or an ordered list. The live (RTMP)
35
+ * stage is always H264 and is not affected by this setting.
36
+ */
37
+ export const DEFAULT_VIDEO_CODECS = ["vp8", "h264", "vp9", "av1"];
38
+
39
+ export function normalizeVideoCodecs(raw) {
40
+ const wanted = (Array.isArray(raw) ? raw : raw == null ? [] : [raw])
41
+ .map((item) => String(item || "").trim().toLowerCase().replace(/^video\//, ""))
42
+ .filter(Boolean);
43
+ const out = [];
44
+ for (const name of [...wanted, ...DEFAULT_VIDEO_CODECS]) {
45
+ if (!out.includes(name)) out.push(name);
46
+ }
47
+ return out;
48
+ }
49
+
50
+ /** How long the live mix must be unnecessary before the host goes back to one Opus stream. */
51
+ const LIVE_MIX_RELEASE_MS = 10_000;
52
+
30
53
  /** Default SDK publish caps (bps). Portal join / createClient can override. */
31
54
  const DEFAULT_CAMERA_MAX_BITRATE_BPS = 1_000_000;
32
55
  const DEFAULT_SCREEN_MAX_BITRATE_BPS = 1_500_000;
@@ -163,6 +186,9 @@ export function createClient(options = {}) {
163
186
  const onUserBlocked = options.onUserBlocked || (() => {});
164
187
  const onStageChanged = options.onStageChanged || (() => {});
165
188
  const onRtmpStatus = options.onRtmpStatus || (() => {});
189
+ const onMediaDemand = options.onMediaDemand || (() => {});
190
+ /** Ordered WebRTC video codec preference (VP8 first unless overridden). */
191
+ const videoCodecs = normalizeVideoCodecs(options.videoCodec ?? options.videoCodecs);
166
192
 
167
193
  if (!sessionId) throw new Error("sessionId is required");
168
194
  if (!token) throw new Error("token is required");
@@ -177,6 +203,8 @@ export function createClient(options = {}) {
177
203
  let avatarBackground = normalizeAvatarBackground(options.avatarBackground);
178
204
  // Frame rates are independent: recording (MediaRecorder) vs RTMP live output.
179
205
  let recordingFps = clampFps(options.recordingFps, DEFAULT_RECORDING_FPS);
206
+ /** Long-edge / 1080p preset for the next recording segment (default 1080p → 1920×1080). */
207
+ let recordingResolution = options.recordingResolution != null ? options.recordingResolution : 1080;
180
208
  const recordingBitrate = Number(options.recordingBitrate) > 0 ? Math.round(Number(options.recordingBitrate)) : undefined;
181
209
  // RTMP output quality. Flat options or `rtmpQuality: { resolution, fps, bitrate, keyframeInterval }`.
182
210
  const rtmpQualityOption = options.rtmpQuality && typeof options.rtmpQuality === "object" ? options.rtmpQuality : {};
@@ -230,10 +258,30 @@ export function createClient(options = {}) {
230
258
  let settleReady = null;
231
259
  /** Session-scoped portal peer (query param). Avoids browser-wide cookie collisions. */
232
260
  let portalPeer = readStoredPortalPeer(sessionId);
233
- /** RTMP: stage compositor + hidden H264/Opus producers on the origin. */
261
+ /** RTMP: stage compositor + hidden H264 producer (+ live audio) on the origin. */
234
262
  let live = null;
235
- let liveProducers = [];
263
+ /** Hidden `rtmp-video` (H264 stage). */
264
+ let liveVideo = null;
265
+ /**
266
+ * RTMP audio. `shared: true` → it is my `mic` producer (one Opus stream for WebRTC + RTMP).
267
+ * `shared: false` → a hidden producer carrying the stage mix (co-host mics, screen audio…).
268
+ * The same producer moves between the two (portal re-labels it), so RTMP is never re-wired.
269
+ */
270
+ let liveAudio = null;
271
+ /** Serializes everything that touches the mic producer or the live audio. */
272
+ let audioQueue = Promise.resolve();
273
+ let liveAudioCheckTimer = null;
274
+ let liveMixIdleSince = 0;
236
275
  let startingLive = null;
276
+ /**
277
+ * WebRTC demand from the portal. Live-stream-first rooms start with `false`: camera /
278
+ * screen / custom tracks stay local (the RTMP stage still shows them) until somebody
279
+ * joins to watch over WebRTC. Every other room is always `true` (publish immediately).
280
+ */
281
+ let webrtcDemand = true;
282
+ let demandQueue = Promise.resolve();
283
+ /** Portal capabilities from the join ack (older portals send none). */
284
+ let portalFeatures = {};
237
285
  let rtmpState = { enabled: rtmpEnabled, state: "idle", live: false, destinations: [] };
238
286
 
239
287
  function userOnStage(user) {
@@ -350,6 +398,7 @@ export function createClient(options = {}) {
350
398
  const people = stagePeopleForRecording();
351
399
  recorder?.sync(tracks, people);
352
400
  live?.sync(tracks, people);
401
+ scheduleLiveAudioCheck();
353
402
  }
354
403
 
355
404
  /**
@@ -459,17 +508,42 @@ export function createClient(options = {}) {
459
508
  if (entry.original !== track) entry.original.addEventListener("ended", entry.onEnded);
460
509
  }
461
510
 
511
+ /**
512
+ * Local entries are keyed by a stable id: the producer id when published right away
513
+ * (unchanged behavior), or a `local-…` id while the track is kept local (no WebRTC demand).
514
+ * `entry.producer` may be null or change (mic shared with RTMP) — never key by it.
515
+ */
462
516
  async function unpublish(producerId) {
463
517
  const entry = locals.get(producerId);
464
518
  if (!entry) return;
519
+ if (entry.source === "mic") return withAudioLock(() => unpublishNow(producerId));
520
+ return unpublishNow(producerId);
521
+ }
522
+
523
+ async function unpublishNow(producerId) {
524
+ const entry = locals.get(producerId);
525
+ if (!entry) return;
526
+ // My mic is also the RTMP audio: hand that producer to the live mix instead of closing
527
+ // it, so the platforms keep their audio input.
528
+ if (liveAudio?.shared && entry.producer && entry.producer === liveAudio.producer) {
529
+ try {
530
+ await splitLiveAudio({ keepMic: false });
531
+ } catch (error) {
532
+ onError(error);
533
+ liveAudio = null;
534
+ }
535
+ }
465
536
  locals.delete(producerId);
466
537
  tiles.delete(producerId);
467
538
  detachEnded(entry);
468
539
  entry.track.stop();
469
- entry.producer.close();
540
+ const producer = entry.producer;
541
+ entry.producer = null;
542
+ producer?.close();
470
543
  syncRecording();
471
544
  onTrackEnded({ producerId, local: true, source: entry.source });
472
- if (socket?.connected) await emit(socket, "closeProducer", { producerId }).catch(() => {});
545
+ if (producer && socket?.connected) await emit(socket, "closeProducer", { producerId: producer.id }).catch(() => {});
546
+ if (entry.source === "mic" && live && !liveAudio) await repairLiveAudio();
473
547
  }
474
548
 
475
549
  function maxBitrateFor(source, kind) {
@@ -571,27 +645,67 @@ export function createClient(options = {}) {
571
645
  return /out of credits|transport not found|ORIGIN_FULL|Origin is full/i.test(msg);
572
646
  }
573
647
 
648
+ /** First codec in the preference list that both this browser and the server can use. */
649
+ function pickVideoCodec() {
650
+ const offered = device?.rtpCapabilities?.codecs || [];
651
+ const sendable = typeof RTCRtpSender !== "undefined" && RTCRtpSender.getCapabilities
652
+ ? RTCRtpSender.getCapabilities("video")?.codecs || null
653
+ : null;
654
+ for (const name of videoCodecs) {
655
+ const mime = `video/${name}`;
656
+ if (sendable && !sendable.some((codec) => String(codec.mimeType).toLowerCase() === mime)) continue;
657
+ const codec = offered.find((item) => item.kind === "video" && String(item.mimeType).toLowerCase() === mime);
658
+ if (codec) return codec;
659
+ }
660
+ return undefined; // let mediasoup pick, as before
661
+ }
662
+
663
+ /** Send one local track to the origin (WebRTC). */
664
+ async function sendProduce(source, track) {
665
+ const options = { track, stopTracks: false, appData: { source } };
666
+ const maxBitrate = maxBitrateFor(source, track.kind);
667
+ if (maxBitrate > 0) {
668
+ options.encodings = [{ maxBitrate }];
669
+ // Chrome start bitrate is kbps; keep a modest ramp under the cap.
670
+ options.codecOptions = {
671
+ videoGoogleStartBitrate: Math.max(100, Math.min(1000, Math.round(maxBitrate / 2000))),
672
+ };
673
+ }
674
+ if (track.kind === "video") {
675
+ const codec = pickVideoCodec();
676
+ if (codec) options.codec = codec;
677
+ }
678
+ if (!sendTransport) throw new Error("The session is not ready");
679
+ try {
680
+ return await sendTransport.produce(options);
681
+ } catch (error) {
682
+ if (!shouldRecreateSendTransport(error)) throw error;
683
+ await recreateSendTransport();
684
+ return sendTransport.produce(options);
685
+ }
686
+ }
687
+
688
+ /** The mic is always published (it is also the RTMP audio); everything else follows demand. */
689
+ function followsDemand(source) {
690
+ return source !== "mic";
691
+ }
692
+
693
+ function localKey() {
694
+ const random = typeof crypto !== "undefined" && crypto.randomUUID
695
+ ? crypto.randomUUID()
696
+ : Math.random().toString(36).slice(2);
697
+ return `local-${random}`;
698
+ }
699
+
574
700
  // Camera inputs use an SDK-owned clone. Custom inputs keep upstream direct ownership.
575
701
  async function produce(source, track, original = track) {
576
- let producer;
702
+ let producer = null;
703
+ const deferred = followsDemand(source) && !webrtcDemand;
577
704
  try {
578
- const options = { track, stopTracks: false, appData: { source } };
579
- const maxBitrate = maxBitrateFor(source, track.kind);
580
- if (maxBitrate > 0) {
581
- options.encodings = [{ maxBitrate }];
582
- // Chrome start bitrate is kbps; keep a modest ramp under the cap.
583
- options.codecOptions = {
584
- videoGoogleStartBitrate: Math.max(100, Math.min(1000, Math.round(maxBitrate / 2000))),
585
- };
586
- }
587
705
  if (!sendTransport) throw new Error("The session is not ready");
588
- try {
589
- producer = await sendTransport.produce(options);
590
- } catch (error) {
591
- if (!shouldRecreateSendTransport(error)) throw error;
592
- await recreateSendTransport();
593
- producer = await sendTransport.produce(options);
594
- }
706
+ // No WebRTC viewer yet (live-stream-first room): keep the track local. The preview
707
+ // and the RTMP stage use it; it is published the moment demand turns on.
708
+ if (!deferred) producer = await sendProduce(source, track);
595
709
  if (closed) throw new Error("The session has ended");
596
710
  if (track.readyState === "ended" || original.readyState === "ended") throw new Error("The source track ended");
597
711
  } catch (error) {
@@ -599,11 +713,12 @@ export function createClient(options = {}) {
599
713
  track.stop();
600
714
  throw error;
601
715
  }
716
+ const key = producer ? producer.id : localKey();
602
717
  const stream = new MediaStream([track]);
603
718
  const entry = { producer, track, original, source };
604
- locals.set(producer.id, entry);
605
- tiles.set(producer.id, {
606
- producerId: producer.id,
719
+ locals.set(key, entry);
720
+ tiles.set(key, {
721
+ producerId: key,
607
722
  publisherId: "local",
608
723
  source,
609
724
  kind: track.kind,
@@ -611,9 +726,11 @@ export function createClient(options = {}) {
611
726
  stream,
612
727
  local: true,
613
728
  });
614
- attachEnded(producer.id, entry);
729
+ attachEnded(key, entry);
615
730
  syncRecording();
616
- return { producerId: producer.id, stream, source };
731
+ // Demand may have turned on while this track was being prepared.
732
+ if (deferred && webrtcDemand) queueDemandReconcile();
733
+ return { producerId: key, stream, source };
617
734
  }
618
735
 
619
736
  async function ensurePortalAffinity({ force = false } = {}) {
@@ -688,15 +805,22 @@ export function createClient(options = {}) {
688
805
  socket.on("rtmpStopped", () => {
689
806
  stopLiveOutput().catch(() => {});
690
807
  });
808
+ // Live-stream-first rooms: publish camera / screen only while someone watches over WebRTC.
809
+ socket.on("mediaDemand", (payload = {}) => {
810
+ if (!closed) setWebrtcDemand(payload.webrtc !== false);
811
+ });
691
812
  socket.on("activeSpeaker", (payload = {}) => {
692
813
  if (closed) return;
693
814
  const peerId = payload.peerId || null;
815
+ const local = Boolean(peerId && selfPeerId && peerId === selfPeerId);
694
816
  onActiveSpeaker({
695
817
  peerId,
696
818
  displayName: payload.displayName || null,
697
819
  producerId: payload.producerId || null,
698
- local: Boolean(peerId && selfPeerId && peerId === selfPeerId),
820
+ local,
699
821
  });
822
+ // Burn the same active-speaker highlight into the recording (no app API).
823
+ recorder?.setActiveSpeaker?.({ peerId, local });
700
824
  });
701
825
  socket.on("userJoined", (user) => {
702
826
  if (closed) return;
@@ -795,6 +919,10 @@ export function createClient(options = {}) {
795
919
  ...clientHints(),
796
920
  });
797
921
  selfPeerId = joined.peerId || null;
922
+ portalFeatures = joined.features && typeof joined.features === "object" ? joined.features : {};
923
+ // Older portals send no mediaDemand: always publish, exactly as before.
924
+ webrtcDemand = joined.mediaDemand?.webrtc !== false;
925
+ onMediaDemand({ webrtc: webrtcDemand });
798
926
  if (joined.rtmp) setRtmpState(joined.rtmp);
799
927
  iceServers = iceOverride || joined.iceServers || [];
800
928
  applyPublishLimitsFromJoin(joined.publishLimits);
@@ -965,13 +1093,19 @@ export function createClient(options = {}) {
965
1093
 
966
1094
  async function replaceLocalTrack(source, track, kind) {
967
1095
  requireLiveTrack(track, kind);
1096
+ if (source === "mic") return withAudioLock(() => replaceLocalTrackNow(source, track, kind));
1097
+ return replaceLocalTrackNow(source, track, kind);
1098
+ }
1099
+
1100
+ async function replaceLocalTrackNow(source, track, kind) {
968
1101
  if (closed) throw new Error("The session has ended");
969
1102
  const current = [...locals].find(([, entry]) => entry.source === source);
970
1103
  if (!current) throw new Error(source === "webcam" ? "The camera is not started" : "The microphone is not started");
971
1104
  const [producerId, entry] = current;
972
1105
  const replacement = track.clone();
973
1106
  try {
974
- await entry.producer.replaceTrack({ track: replacement });
1107
+ // A track kept local (no WebRTC demand) has no producer yet — just swap it.
1108
+ if (entry.producer) await entry.producer.replaceTrack({ track: replacement });
975
1109
  if (closed || locals.get(producerId) !== entry) {
976
1110
  throw new Error(source === "webcam" ? "The camera is not started" : "The microphone is not started");
977
1111
  }
@@ -1165,6 +1299,7 @@ export function createClient(options = {}) {
1165
1299
  recorderPeer: peer,
1166
1300
  fps: recordingFps,
1167
1301
  bitrate: recordingBitrate,
1302
+ resolution: recordingResolution,
1168
1303
  // Chunks start immediately; empty stage uses the same host placeholder as live UI.
1169
1304
  onCaptureChange: () => notifyRecording(next),
1170
1305
  onFailure: (error) => {
@@ -1202,8 +1337,11 @@ export function createClient(options = {}) {
1202
1337
  throw lastError instanceof Error ? lastError : new Error(String(lastError || "Could not start recording"));
1203
1338
  }
1204
1339
 
1205
- async function startRecording() {
1340
+ async function startRecording(opts = {}) {
1206
1341
  if (closed) throw new Error("The session has ended");
1342
+ if (opts && typeof opts === "object" && opts.resolution != null) {
1343
+ recordingResolution = opts.resolution;
1344
+ }
1207
1345
  if (!sendTransport) await connect();
1208
1346
  if (closed) return;
1209
1347
  if (recorder) {
@@ -1261,6 +1399,235 @@ export function createClient(options = {}) {
1261
1399
  return LiveCompositor.supported() && Boolean(h264Codec());
1262
1400
  }
1263
1401
 
1402
+ // ---- WebRTC demand (live-stream-first rooms) --------------------------------
1403
+
1404
+ function setWebrtcDemand(next) {
1405
+ const value = Boolean(next);
1406
+ if (value === webrtcDemand) return;
1407
+ webrtcDemand = value;
1408
+ onMediaDemand({ webrtc: value });
1409
+ queueDemandReconcile();
1410
+ }
1411
+
1412
+ function queueDemandReconcile() {
1413
+ const run = demandQueue.then(reconcileDemand, reconcileDemand);
1414
+ demandQueue = run.catch((error) => onError(error));
1415
+ return run;
1416
+ }
1417
+
1418
+ /** Publish (or stop publishing) every local non-mic track to match `webrtcDemand`. */
1419
+ async function reconcileDemand() {
1420
+ for (const [key, entry] of [...locals]) {
1421
+ if (closed || !sendTransport) return;
1422
+ if (!followsDemand(entry.source)) continue;
1423
+ if (webrtcDemand && !entry.producer) {
1424
+ const track = entry.track;
1425
+ let producer = null;
1426
+ try {
1427
+ producer = await sendProduce(entry.source, track);
1428
+ } catch (error) {
1429
+ onError(error);
1430
+ continue;
1431
+ }
1432
+ if (closed || locals.get(key) !== entry || !webrtcDemand || entry.producer) {
1433
+ producer.close();
1434
+ if (socket?.connected) await emit(socket, "closeProducer", { producerId: producer.id }).catch(() => {});
1435
+ continue;
1436
+ }
1437
+ entry.producer = producer;
1438
+ // The track was swapped (device change) while publishing.
1439
+ if (entry.track !== track) await producer.replaceTrack({ track: entry.track }).catch((error) => onError(error));
1440
+ } else if (!webrtcDemand && entry.producer) {
1441
+ const producer = entry.producer;
1442
+ entry.producer = null;
1443
+ producer.close();
1444
+ if (socket?.connected) await emit(socket, "closeProducer", { producerId: producer.id }).catch(() => {});
1445
+ }
1446
+ }
1447
+ }
1448
+
1449
+ // ---- Live (RTMP) audio: one Opus stream unless a mix is needed -----------------
1450
+
1451
+ function withAudioLock(job) {
1452
+ const run = audioQueue.then(job, job);
1453
+ audioQueue = run.then(() => {}, () => {});
1454
+ return run;
1455
+ }
1456
+
1457
+ function micEntry() {
1458
+ for (const entry of locals.values()) {
1459
+ if (entry.source === "mic" && entry.track.kind === "audio") return entry;
1460
+ }
1461
+ return null;
1462
+ }
1463
+
1464
+ /**
1465
+ * The RTMP audio needs the compositor mix when anything besides my own mic is audible
1466
+ * on the stage (co-host / guest mics, screen or tab audio) or when my mic is off.
1467
+ * Mute state does not matter, so muting never flips the audio path.
1468
+ */
1469
+ function needsLiveMix() {
1470
+ const mic = micEntry();
1471
+ if (!mic?.producer) return true;
1472
+ for (const tile of tiles.values()) {
1473
+ if (tile.kind !== "audio") continue;
1474
+ if (tile.local && tile.source === "mic") continue;
1475
+ return true;
1476
+ }
1477
+ return false;
1478
+ }
1479
+
1480
+ function canShareMic() {
1481
+ return portalFeatures.rtmpSharedAudio === true;
1482
+ }
1483
+
1484
+ /** On Go Live: use my mic producer directly when nothing needs mixing, else a hidden mix. */
1485
+ async function setupLiveAudio(compositor) {
1486
+ const mic = micEntry();
1487
+ if (canShareMic() && mic?.producer && !needsLiveMix()) {
1488
+ try {
1489
+ await emit(socket, "rtmpAudio", { action: "shared", producerId: mic.producer.id });
1490
+ liveAudio = { producer: mic.producer, shared: true };
1491
+ liveMixIdleSince = 0;
1492
+ return;
1493
+ } catch (error) {
1494
+ console.warn("[mediascale] live audio: mic sharing refused, using the mix", error?.message || error);
1495
+ }
1496
+ }
1497
+ const producer = await produceHidden("rtmp-audio", compositor.audioTrack);
1498
+ liveAudio = { producer, shared: false };
1499
+ liveMixIdleSince = 0;
1500
+ }
1501
+
1502
+ async function teardownLiveAudio() {
1503
+ const current = liveAudio;
1504
+ liveAudio = null;
1505
+ liveMixIdleSince = 0;
1506
+ if (liveAudioCheckTimer) {
1507
+ clearTimeout(liveAudioCheckTimer);
1508
+ liveAudioCheckTimer = null;
1509
+ }
1510
+ // Shared: it is my mic — it keeps serving WebRTC; the portal already dropped it from RTMP.
1511
+ if (!current || current.shared) return;
1512
+ try { current.producer.close(); } catch { /* ignore */ }
1513
+ if (socket?.connected) await emit(socket, "closeProducer", { producerId: current.producer.id }).catch(() => {});
1514
+ }
1515
+
1516
+ /** RTMP lost its audio producer (e.g. mic sharing failed): publish a hidden mix. */
1517
+ async function repairLiveAudio() {
1518
+ if (!live || liveAudio || closed) return;
1519
+ try {
1520
+ const producer = await produceHidden("rtmp-audio", live.audioTrack);
1521
+ liveAudio = { producer, shared: false };
1522
+ } catch (error) {
1523
+ onError(error);
1524
+ }
1525
+ }
1526
+
1527
+ /**
1528
+ * shared → mix: the producer RTMP uses switches to the stage mix (portal hides it from
1529
+ * WebRTC), and my plain mic goes out as a new producer for WebRTC viewers.
1530
+ */
1531
+ async function splitLiveAudio({ keepMic = true } = {}) {
1532
+ const current = liveAudio;
1533
+ const compositor = live;
1534
+ if (!current?.shared || !compositor) return;
1535
+ const producer = current.producer;
1536
+ await emit(socket, "rtmpAudio", { action: "split", producerId: producer.id });
1537
+ try {
1538
+ await producer.replaceTrack({ track: compositor.audioTrack });
1539
+ } catch (error) {
1540
+ onError(error);
1541
+ }
1542
+ liveAudio = { producer, shared: false };
1543
+ liveMixIdleSince = 0;
1544
+ const mic = micEntry();
1545
+ if (mic && mic.producer === producer) {
1546
+ mic.producer = null;
1547
+ if (keepMic) {
1548
+ try {
1549
+ mic.producer = await sendProduce("mic", mic.track);
1550
+ } catch (error) {
1551
+ onError(error);
1552
+ }
1553
+ }
1554
+ }
1555
+ }
1556
+
1557
+ /**
1558
+ * mix → shared: the RTMP producer carries my plain mic again and becomes my visible mic;
1559
+ * the separate WebRTC mic closes first (a short gap beats viewers hearing me twice).
1560
+ */
1561
+ async function mergeLiveAudio() {
1562
+ const current = liveAudio;
1563
+ const mic = micEntry();
1564
+ if (!current || current.shared || !mic?.producer || mic.producer === current.producer) return;
1565
+ const producer = current.producer;
1566
+ const webrtcMic = mic.producer;
1567
+ await producer.replaceTrack({ track: mic.track });
1568
+ mic.producer = null;
1569
+ webrtcMic.close();
1570
+ if (socket?.connected) await emit(socket, "closeProducer", { producerId: webrtcMic.id }).catch(() => {});
1571
+ try {
1572
+ await emit(socket, "rtmpAudio", { action: "merge", producerId: producer.id });
1573
+ } catch (error) {
1574
+ // Stay on the mix and bring the WebRTC mic back.
1575
+ if (live) await producer.replaceTrack({ track: live.audioTrack }).catch(() => {});
1576
+ try {
1577
+ if (micEntry() === mic && !mic.producer) mic.producer = await sendProduce("mic", mic.track);
1578
+ } catch (produceError) {
1579
+ onError(produceError);
1580
+ }
1581
+ throw error;
1582
+ }
1583
+ mic.producer = producer;
1584
+ liveAudio = { producer, shared: true };
1585
+ liveMixIdleSince = 0;
1586
+ }
1587
+
1588
+ async function reconcileLiveAudio() {
1589
+ if (closed || !live || !liveAudio || !canShareMic() || !socket?.connected) return;
1590
+ const mic = micEntry();
1591
+ // A WebRTC mic that failed to publish during a split: try again.
1592
+ if (mic && !mic.producer && sendTransport) {
1593
+ try {
1594
+ mic.producer = await sendProduce("mic", mic.track);
1595
+ } catch (error) {
1596
+ onError(error);
1597
+ }
1598
+ }
1599
+ const need = needsLiveMix();
1600
+ if (liveAudio.shared) {
1601
+ liveMixIdleSince = 0;
1602
+ if (need) await splitLiveAudio();
1603
+ return;
1604
+ }
1605
+ if (need) {
1606
+ liveMixIdleSince = 0;
1607
+ return;
1608
+ }
1609
+ // Go back to one Opus stream only after the mix has been unnecessary for a while,
1610
+ // so a guest briefly joining / leaving the stage does not flip the audio back and forth.
1611
+ const now = Date.now();
1612
+ if (!liveMixIdleSince) liveMixIdleSince = now;
1613
+ const left = LIVE_MIX_RELEASE_MS - (now - liveMixIdleSince);
1614
+ if (left > 0) {
1615
+ scheduleLiveAudioCheck(left + 50);
1616
+ return;
1617
+ }
1618
+ liveMixIdleSince = 0;
1619
+ await mergeLiveAudio();
1620
+ }
1621
+
1622
+ function scheduleLiveAudioCheck(delayMs = 300) {
1623
+ if (closed || !live || !liveAudio || !canShareMic()) return;
1624
+ if (liveAudioCheckTimer) clearTimeout(liveAudioCheckTimer);
1625
+ liveAudioCheckTimer = setTimeout(() => {
1626
+ liveAudioCheckTimer = null;
1627
+ withAudioLock(reconcileLiveAudio).catch((error) => onError(error));
1628
+ }, delayMs);
1629
+ }
1630
+
1264
1631
  async function produceHidden(source, track, extra = {}) {
1265
1632
  const options = { track, stopTracks: false, appData: { source }, ...extra };
1266
1633
  try {
@@ -1297,12 +1664,13 @@ export function createClient(options = {}) {
1297
1664
  }
1298
1665
 
1299
1666
  async function closeLiveProducers() {
1300
- const producers = liveProducers;
1301
- liveProducers = [];
1302
- for (const producer of producers) {
1303
- try { producer.close(); } catch { /* ignore */ }
1304
- if (socket?.connected) await emit(socket, "closeProducer", { producerId: producer.id }).catch(() => {});
1667
+ const video = liveVideo;
1668
+ liveVideo = null;
1669
+ if (video) {
1670
+ try { video.close(); } catch { /* ignore */ }
1671
+ if (socket?.connected) await emit(socket, "closeProducer", { producerId: video.id }).catch(() => {});
1305
1672
  }
1673
+ await withAudioLock(teardownLiveAudio);
1306
1674
  }
1307
1675
 
1308
1676
  async function createLiveCompositor() {
@@ -1328,7 +1696,10 @@ export function createClient(options = {}) {
1328
1696
  return next;
1329
1697
  }
1330
1698
 
1331
- /** Compose the stage and publish hidden rtmp-video (H264) + rtmp-audio on the origin. */
1699
+ /**
1700
+ * Compose the stage and publish hidden rtmp-video (H264) on the origin. Audio is my mic
1701
+ * producer while nothing needs mixing (one Opus stream), else a hidden rtmp-audio mix.
1702
+ */
1332
1703
  async function startLiveOutput() {
1333
1704
  if (closed) throw new Error("The session has ended");
1334
1705
  if (live) return;
@@ -1348,10 +1719,9 @@ export function createClient(options = {}) {
1348
1719
  // Start near the target so the first seconds on the platform are not blurry.
1349
1720
  codecOptions: { videoGoogleStartBitrate: Math.round(rtmpBitrate / 1000 * 0.8) },
1350
1721
  });
1351
- liveProducers.push(video);
1722
+ liveVideo = video;
1352
1723
  await applyLiveSenderParams(video);
1353
- const audio = await produceHidden("rtmp-audio", next.audioTrack);
1354
- liveProducers.push(audio);
1724
+ await withAudioLock(() => setupLiveAudio(next));
1355
1725
  } catch (error) {
1356
1726
  await closeLiveProducers();
1357
1727
  if (live === next) live = null;
@@ -1359,6 +1729,8 @@ export function createClient(options = {}) {
1359
1729
  throw error;
1360
1730
  }
1361
1731
  setRtmpState({});
1732
+ // The stage may have changed while going live (a co-host joined, screen audio…).
1733
+ scheduleLiveAudioCheck();
1362
1734
  })();
1363
1735
  try {
1364
1736
  await startingLive;
@@ -1430,16 +1802,36 @@ export function createClient(options = {}) {
1430
1802
  return recordingFps;
1431
1803
  }
1432
1804
 
1805
+ /**
1806
+ * Recording output size for the next segment start.
1807
+ * `1080` / `"1080p"` → 1920×1080; number N (e.g. 2048) → height N at 16:9 (≈3644×2048).
1808
+ */
1809
+ function setRecordingResolution(resolution) {
1810
+ recordingResolution = resolution != null ? resolution : 1080;
1811
+ return getRecordingResolution();
1812
+ }
1813
+
1814
+ function getRecordingResolution() {
1815
+ const out = normalizeRecordingResolution(recordingResolution);
1816
+ return {
1817
+ resolution: recordingResolution,
1818
+ width: out.width,
1819
+ height: out.height,
1820
+ };
1821
+ }
1822
+
1433
1823
  /** Rebuild the live compositor (new fps / resolution) and swap tracks without leaving the platforms. */
1434
1824
  async function restartLiveCompositor() {
1435
- if (!live || liveProducers.length < 2) return;
1825
+ if (!live || !liveVideo || !liveAudio) return;
1436
1826
  const previous = live;
1437
1827
  const replacement = await createLiveCompositor();
1438
- const [video, audio] = liveProducers;
1439
- await video.replaceTrack({ track: replacement.videoTrack });
1440
- await audio.replaceTrack({ track: replacement.audioTrack });
1441
- await applyLiveSenderParams(video);
1442
- live = replacement;
1828
+ await liveVideo.replaceTrack({ track: replacement.videoTrack });
1829
+ await applyLiveSenderParams(liveVideo);
1830
+ await withAudioLock(async () => {
1831
+ live = replacement;
1832
+ // Shared mic audio is not from the compositor; only a mix producer follows it.
1833
+ if (liveAudio && !liveAudio.shared) await liveAudio.producer.replaceTrack({ track: replacement.audioTrack });
1834
+ });
1443
1835
  await previous.finish().catch(() => {});
1444
1836
  }
1445
1837
 
@@ -1474,9 +1866,9 @@ export function createClient(options = {}) {
1474
1866
  rtmpFps = fps;
1475
1867
  rtmpResolution = resolution;
1476
1868
  rtmpBitrate = bitrate;
1477
- if (live && liveProducers.length >= 2) {
1869
+ if (live && liveVideo) {
1478
1870
  if (restart) await restartLiveCompositor();
1479
- else if (rebitrate) await applyLiveSenderParams(liveProducers[0]);
1871
+ else if (rebitrate) await applyLiveSenderParams(liveVideo);
1480
1872
  }
1481
1873
  return getRtmpQuality();
1482
1874
  }
@@ -1528,6 +1920,10 @@ export function createClient(options = {}) {
1528
1920
  clearInterval(stageDebugTimer);
1529
1921
  stageDebugTimer = null;
1530
1922
  }
1923
+ if (liveAudioCheckTimer) {
1924
+ clearTimeout(liveAudioCheckTimer);
1925
+ liveAudioCheckTimer = null;
1926
+ }
1531
1927
  settleReady?.(new Error("Ended"));
1532
1928
  // Finalize only on explicit stop-session / finalize. Browser close uses disconnect handoff.
1533
1929
  const forceFinalize = options.finalize === true || options.endSession === true;
@@ -1572,7 +1968,8 @@ export function createClient(options = {}) {
1572
1968
  for (const entry of locals.values()) {
1573
1969
  detachEnded(entry);
1574
1970
  entry.track.stop();
1575
- entry.producer.close();
1971
+ entry.producer?.close();
1972
+ entry.producer = null;
1576
1973
  }
1577
1974
  locals.clear();
1578
1975
  try { sendTransport?.close(); } catch { /* ignore */ }
@@ -1625,6 +2022,8 @@ export function createClient(options = {}) {
1625
2022
  stopRecording: guard(stopRecording),
1626
2023
  setRecordingFps,
1627
2024
  getRecordingFps: () => recordingFps,
2025
+ setRecordingResolution,
2026
+ getRecordingResolution,
1628
2027
  startRtmp: guard(startRtmp),
1629
2028
  stopRtmp: guard(stopRtmp),
1630
2029
  getRtmpStatus: guard(getRtmpStatus),
@@ -1639,6 +2038,10 @@ export function createClient(options = {}) {
1639
2038
  getAppearance,
1640
2039
  canLiveStream,
1641
2040
  isRtmpEnabled: () => Boolean(rtmpState.enabled),
2041
+ /** `{ webrtc }` — false while a live-stream-first room has no WebRTC viewer (tracks stay local). */
2042
+ getMediaDemand: () => ({ webrtc: webrtcDemand }),
2043
+ /** Ordered WebRTC video codec preference in use (VP8 first by default). */
2044
+ getVideoCodecs: () => [...videoCodecs],
1642
2045
  setRecordingCrop,
1643
2046
  setRecordingStage,
1644
2047
  getUserList: guard(getUserList),
package/src/index.js CHANGED
@@ -1,6 +1,11 @@
1
- export { createClient } from "./client.js";
1
+ export { createClient, DEFAULT_VIDEO_CODECS, normalizeVideoCodecs } from "./client.js";
2
2
  export { FrameCompositor } from "./record-frame-compositor.js";
3
- export { DEFAULT_RECORDING_FPS } from "./record.js";
3
+ export {
4
+ DEFAULT_RECORDING_FPS,
5
+ normalizeRecordingResolution,
6
+ recordingBitrateForSize,
7
+ stageOutputSize,
8
+ } from "./record.js";
4
9
  export {
5
10
  avatarBackgroundFor,
6
11
  gradientToCss,
@@ -84,7 +84,7 @@ export async function createWorkerCompositor({ width, height, scale = 1, fps, ba
84
84
  for (const [key, entry] of owned) if (!keys.has(key)) { release(entry); owned.delete(key); }
85
85
  const transfer = [];
86
86
  const updates = desired.map((source) => {
87
- const { key, track, rect, crop, label, accent, radius, muted, fit, fillStyle, placeholder, avatarBackground: avatar } = source;
87
+ const { key, track, rect, crop, label, accent, radius, muted, fit, fillStyle, placeholder, avatarBackground: avatar, speaking } = source;
88
88
  const chrome = {
89
89
  key,
90
90
  rect,
@@ -97,6 +97,7 @@ export async function createWorkerCompositor({ width, height, scale = 1, fps, ba
97
97
  ...(fillStyle ? { fillStyle } : {}),
98
98
  placeholder: Boolean(placeholder),
99
99
  avatarBackground: avatar || null,
100
+ speaking: Boolean(speaking),
100
101
  };
101
102
  const previous = owned.get(key);
102
103
  if (previous?.original === track) return chrome;
@@ -219,6 +219,8 @@ export function roundedRectPath(ctx, x, y, w, h, radius) {
219
219
 
220
220
  /** Neon magenta presenter ring — matches the live stage / webinar UI. */
221
221
  export const PRESENTER_ACCENT = "#e879f9";
222
+ /** Cyan active-speaker ring — matches live `.tile.speaking` (`rgba(56, 189, 248, …)`). */
223
+ export const SPEAKING_ACCENT = "#38bdf8";
222
224
 
223
225
  /**
224
226
  * Bottom-left name label (design): plain white text + soft scrim. No mic / signal icons.
@@ -267,6 +269,27 @@ export function strokeTileBorder(ctx, x, y, w, h, radius, { accent = false, acce
267
269
  ctx.restore();
268
270
  }
269
271
 
272
+ /**
273
+ * Active-speaker highlight burned into the recording. Drawn for flush tiles too
274
+ * (TILE_RADIUS = 0) so camera-off avatars match the live cyan ring.
275
+ */
276
+ export function strokeSpeakingRing(ctx, x, y, w, h, radius = 0, color = SPEAKING_ACCENT) {
277
+ const base = parseCssColor(color) || { r: 56, g: 189, b: 248 };
278
+ ctx.save();
279
+ if (radius > 0) {
280
+ roundedRectPath(ctx, x + 0.5, y + 0.5, w - 1, h - 1, radius);
281
+ } else {
282
+ ctx.beginPath();
283
+ ctx.rect(x + 0.5, y + 0.5, w - 1, h - 1);
284
+ }
285
+ ctx.strokeStyle = cssRgb(base, 0.85);
286
+ ctx.lineWidth = 3;
287
+ ctx.shadowColor = cssRgb(base, 0.55);
288
+ ctx.shadowBlur = 12;
289
+ ctx.stroke();
290
+ ctx.restore();
291
+ }
292
+
270
293
  /**
271
294
  * Draw a video/image source into a rounded tile + bottom-left name (no mic icons).
272
295
  * `fit: "cover"` fills the rect (cameras). `fit: "contain"` letterboxes screenshare.
@@ -288,6 +311,7 @@ export function paintRoundedTile(ctx, {
288
311
  fit = "cover",
289
312
  placeholder = false,
290
313
  avatarBackground = null,
314
+ speaking = false,
291
315
  }) {
292
316
  const { x, y, w, h } = rect;
293
317
  ctx.save();
@@ -330,6 +354,7 @@ export function paintRoundedTile(ctx, {
330
354
  }
331
355
  ctx.restore();
332
356
  if (label) drawNamePill(ctx, x, y, w, h, label, { presenter: accent, muted });
357
+ if (speaking) strokeSpeakingRing(ctx, x, y, w, h, radius);
333
358
  }
334
359
 
335
360
  /** Owns at most one input frame per source and one output write. */
@@ -408,7 +433,7 @@ export class FrameCompositor {
408
433
  if (!this.active || (!this.dirty && !this.steady && !idleTiles) || this.writing || now - this.lastDraw < this.interval) return;
409
434
  this.backdrop.paint(this.ctx, this.width, this.height);
410
435
  for (const source of this.sources) {
411
- const { key, rect, crop, label, accent, radius, muted, fit, fillStyle, placeholder, avatarBackground } = source;
436
+ const { key, rect, crop, label, accent, radius, muted, fit, fillStyle, placeholder, avatarBackground, speaking } = source;
412
437
  const frame = this.frames.get(key);
413
438
  if (!rect) continue;
414
439
  const tileRadius = radius == null ? 0 : radius;
@@ -422,6 +447,7 @@ export class FrameCompositor {
422
447
  fit: fit === "contain" ? "contain" : "cover",
423
448
  placeholder: Boolean(placeholder),
424
449
  avatarBackground: avatarBackground || this.avatarBackground,
450
+ speaking: Boolean(speaking),
425
451
  };
426
452
  if (!frame) {
427
453
  // Screenshare before its first frame: keep the uniform backdrop.
@@ -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, crop, label, accent, radius, muted, fit, fillStyle, placeholder, avatarBackground }) => ({
72
+ compositor.setSources(data.sources.map(({ key, rect, crop, label, accent, radius, muted, fit, fillStyle, placeholder, avatarBackground, speaking }) => ({
73
73
  key,
74
74
  rect,
75
75
  crop: crop || null,
@@ -81,6 +81,7 @@ self.onmessage = async ({ data }) => {
81
81
  ...(fillStyle ? { fillStyle } : {}),
82
82
  placeholder: Boolean(placeholder),
83
83
  avatarBackground: avatarBackground || null,
84
+ speaking: Boolean(speaking),
84
85
  })));
85
86
  for (const source of data.sources) {
86
87
  if (!source.readable && !source.track) continue;
package/src/record.js CHANGED
@@ -7,6 +7,7 @@ import {
7
7
  roundedRectPath,
8
8
  fillNameTone,
9
9
  drawInitialAvatar,
10
+ strokeSpeakingRing,
10
11
  STAGE_BACKGROUND,
11
12
  PRESENTER_ACCENT,
12
13
  } from "./record-frame-compositor.js";
@@ -14,6 +15,7 @@ export {
14
15
  FrameCompositor,
15
16
  fillRadialBackground,
16
17
  PRESENTER_ACCENT,
18
+ SPEAKING_ACCENT,
17
19
  STAGE_BACKGROUND,
18
20
  } from "./record-frame-compositor.js";
19
21
 
@@ -23,16 +25,24 @@ export {
23
25
  */
24
26
  const W = 1280;
25
27
  const H = 720;
26
- /** Output limits: keep the client light — never more pixels than 1080p, long edge ≤ 1920. */
28
+ /** Default output limits (RTMP + legacy recording): never more pixels than 1080p, long edge ≤ 1920. */
27
29
  const MAX_OUTPUT_EDGE = 1920;
28
30
  const MAX_OUTPUT_PIXELS = 1920 * 1080;
29
31
  const MIN_OUTPUT_EDGE = 160;
32
+ /** Recording resolution long-edge clamp (createClient / startRecording). */
33
+ const MIN_RECORDING_EDGE = 360;
34
+ const MAX_RECORDING_EDGE = 4096;
35
+ /** Reference pixel count for bitrate scaling (1080p). */
36
+ const BASE_OUTPUT_PIXELS = 1920 * 1080;
30
37
 
31
38
  /**
32
39
  * Output size for the stage. Accepts `{ width, height }`, or a height (16:9 width derived).
33
40
  * Keeps the aspect ratio while clamping to the limits; dimensions are even (H264 needs it).
41
+ * Optional `limits: { maxEdge, maxPixels }` — recording may raise these for 2048 long-edge.
34
42
  */
35
- export function stageOutputSize(size = H) {
43
+ export function stageOutputSize(size = H, limits = {}) {
44
+ const maxEdge = Number(limits.maxEdge) > 0 ? Number(limits.maxEdge) : MAX_OUTPUT_EDGE;
45
+ const maxPixels = Number(limits.maxPixels) > 0 ? Number(limits.maxPixels) : MAX_OUTPUT_PIXELS;
36
46
  let width;
37
47
  let height;
38
48
  if (size && typeof size === "object") {
@@ -43,14 +53,48 @@ export function stageOutputSize(size = H) {
43
53
  }
44
54
  if (!Number.isFinite(height) || height <= 0) height = H;
45
55
  if (!Number.isFinite(width) || width <= 0) width = (height * W) / H;
46
- let fit = Math.min(1, MAX_OUTPUT_EDGE / Math.max(width, height), Math.sqrt(MAX_OUTPUT_PIXELS / (width * height)));
56
+ let fit = Math.min(1, maxEdge / Math.max(width, height), Math.sqrt(maxPixels / (width * height)));
47
57
  fit = Math.max(fit, MIN_OUTPUT_EDGE / Math.min(width, height));
48
58
  const even = (v) => Math.max(2, Math.round(v / 2) * 2);
49
- const outW = even(Math.min(MAX_OUTPUT_EDGE, width * fit));
50
- const outH = even(Math.min(MAX_OUTPUT_EDGE, height * fit));
59
+ const outW = even(Math.min(maxEdge, width * fit));
60
+ const outH = even(Math.min(maxEdge, height * fit));
51
61
  const scale = outW / W;
52
62
  return { width: outW, height: outH, scale, layoutWidth: W, layoutHeight: outH / scale };
53
63
  }
64
+
65
+ /**
66
+ * Resolve recording output size from `recordingResolution` / `startRecording({ resolution })`.
67
+ * Same “Np” meaning as 720p / 1080p: N is the **height**, width is 16:9.
68
+ * - unset / `1080` / `"1080p"` → 1920×1080
69
+ * - number N (e.g. 2048) → height N at 16:9 (3640×2048), even dims, height clamped 360–4096
70
+ */
71
+ export function normalizeRecordingResolution(value, fallback = 1080) {
72
+ const as1080p = () => stageOutputSize({ width: 1920, height: 1080 }, {
73
+ maxEdge: 1920,
74
+ maxPixels: 1920 * 1080,
75
+ });
76
+ if (value == null || value === "") {
77
+ return fallback === 1080 || fallback === "1080" || fallback === "1080p"
78
+ ? as1080p()
79
+ : normalizeRecordingResolution(fallback, 1080);
80
+ }
81
+ const text = String(value).trim().toLowerCase();
82
+ if (text === "1080" || text === "1080p") return as1080p();
83
+ // "2048p" / "720p" → use the numeric height.
84
+ const pLabel = text.match(/^(\d{3,4})p$/);
85
+ const n = pLabel ? Number(pLabel[1]) : Number(value);
86
+ if (!Number.isFinite(n) || n <= 0) return as1080p();
87
+ if (n === 1080) return as1080p();
88
+ const even = (v) => Math.max(2, Math.round(v / 2) * 2);
89
+ const height = even(Math.max(MIN_RECORDING_EDGE, Math.min(MAX_RECORDING_EDGE, Math.round(n))));
90
+ const width = even((height * 16) / 9);
91
+ const longEdge = Math.max(width, height);
92
+ return stageOutputSize({ width, height }, {
93
+ maxEdge: Math.max(longEdge, MAX_OUTPUT_EDGE),
94
+ maxPixels: Math.max(width * height, BASE_OUTPUT_PIXELS),
95
+ });
96
+ }
97
+
54
98
  /** Outer margin around the whole layout. */
55
99
  const PAD = 28;
56
100
  /**
@@ -74,6 +118,14 @@ const MAX_STAGE_CAMERAS = 6;
74
118
  const BITRATE = 4_500_000;
75
119
  const mime = "video/webm;codecs=vp8,opus";
76
120
 
121
+ /** VP8 bitrate scaled with output pixels (4.5 Mbps at 1080p). */
122
+ export function recordingBitrateForSize(width, height, override) {
123
+ if (Number(override) > 0) return Math.round(Number(override));
124
+ const pixels = Math.max(1, Number(width) * Number(height));
125
+ const scaled = BITRATE * (pixels / BASE_OUTPUT_PIXELS);
126
+ return Math.max(1_500_000, Math.min(20_000_000, Math.round(scaled)));
127
+ }
128
+
77
129
  /** Clamp a configured frame rate to 1–60 (fallback when missing or invalid). */
78
130
  export function clampFps(value, fallback = DEFAULT_RECORDING_FPS) {
79
131
  const n = Math.round(Number(value));
@@ -322,9 +374,24 @@ export class CanvasRecorder {
322
374
  bitrate,
323
375
  outputHeight,
324
376
  outputSize,
377
+ resolution,
325
378
  }) {
326
379
  /** Canvas pixel size; layout math stays in design units (1280 wide). */
327
- const output = stageOutputSize(outputSize || outputHeight);
380
+ let output;
381
+ if (outputSize && typeof outputSize === "object" && Number(outputSize.width) > 0 && Number(outputSize.height) > 0) {
382
+ // Live / explicit size (already normalized). Allow the requested dims through.
383
+ const reqW = Number(outputSize.width);
384
+ const reqH = Number(outputSize.height);
385
+ output = stageOutputSize({ width: reqW, height: reqH }, {
386
+ maxEdge: Math.max(reqW, reqH, MAX_OUTPUT_EDGE),
387
+ maxPixels: Math.max(reqW * reqH, MAX_OUTPUT_PIXELS),
388
+ });
389
+ } else if (resolution != null || outputHeight != null) {
390
+ output = normalizeRecordingResolution(resolution ?? outputHeight);
391
+ } else {
392
+ // Recording default: 1080p (1920×1080).
393
+ output = normalizeRecordingResolution(1080);
394
+ }
328
395
  this.outputWidth = output.width;
329
396
  this.outputHeight = output.height;
330
397
  this.outputScale = output.scale;
@@ -332,7 +399,7 @@ export class CanvasRecorder {
332
399
  this.layoutHeight = output.layoutHeight;
333
400
  /** Compositor + capture frame rate (recording and live output can differ). */
334
401
  this.fps = clampFps(fps);
335
- this.bitrate = Number(bitrate) > 0 ? Math.round(Number(bitrate)) : BITRATE;
402
+ this.bitrate = recordingBitrateForSize(this.outputWidth, this.outputHeight, bitrate);
336
403
  /** Window event prefix: "recording" here, "live" for the RTMP compositor. */
337
404
  this.eventPrefix = "recording";
338
405
  /** Worker compositor emits frames only on change unless steady (live output sets this). */
@@ -346,6 +413,9 @@ export class CanvasRecorder {
346
413
  if (this.recorderPeer) writeStoredRecorderPeer(this.webinarId, this.recorderPeer);
347
414
  /** @type {{ id: string, name: string, local?: boolean }[] | null} */
348
415
  this.stagePeople = null;
416
+ /** Active speaker from portal → cyan ring on matching camera / avatar tile. */
417
+ this.speakingPeerId = null;
418
+ this.speakingLocal = false;
349
419
  this.token = token || "";
350
420
  this.selfName = String(selfName || "Host").slice(0, 40);
351
421
  /** Color or gradient spec (string / object) for the stage backdrop. */
@@ -529,6 +599,28 @@ export class CanvasRecorder {
529
599
  if (this.prepared) this.retile();
530
600
  }
531
601
 
602
+ /**
603
+ * Portal activeSpeaker → cyan speak ring on the matching camera / avatar tile.
604
+ * Pass `{ peerId: null }` (or omit peerId) to clear.
605
+ */
606
+ setActiveSpeaker({ peerId = null, local = false } = {}) {
607
+ const nextPeer = peerId ? String(peerId) : null;
608
+ const nextLocal = Boolean(local);
609
+ if (this.speakingPeerId === nextPeer && this.speakingLocal === nextLocal) return;
610
+ this.speakingPeerId = nextPeer;
611
+ this.speakingLocal = nextLocal;
612
+ if (this.prepared) this.retile();
613
+ }
614
+
615
+ /** True when this camera / avatar slot matches the current active speaker. */
616
+ isSpeakingSlot(slot) {
617
+ if (!slot || slot.kind === "screen") return false;
618
+ if (!this.speakingPeerId && !this.speakingLocal) return false;
619
+ if (slot.isLocal) return this.speakingLocal;
620
+ if (!this.speakingPeerId) return false;
621
+ return String(slot.participantKey || "") === this.speakingPeerId;
622
+ }
623
+
532
624
  updateCapture() {
533
625
  const run = this.captureGate.then(async () => {
534
626
  if (this.finishing || !this.prepared) return;
@@ -927,7 +1019,7 @@ export class CanvasRecorder {
927
1019
  });
928
1020
  }
929
1021
  }
930
- // Attach mic / presenter chrome onto camera slots for both compositor paths.
1022
+ // Attach mic / presenter / speaking chrome onto camera slots for both compositor paths.
931
1023
  chosen = chosen.map((slot) => {
932
1024
  const label = resolveTileLabel(slot, this.selfName);
933
1025
  return {
@@ -935,6 +1027,7 @@ export class CanvasRecorder {
935
1027
  displayName: label,
936
1028
  micMuted: !hasLiveMic(slot, mics),
937
1029
  presenter: isPresenterSlot(slot, label),
1030
+ speaking: this.isSpeakingSlot(slot),
938
1031
  // Resolved per tile so the worker gets a single spec (also used before the first frame).
939
1032
  avatarBackground: slot.avatarBackground || avatarBackgroundFor(label, this.avatarBackground),
940
1033
  };
@@ -955,6 +1048,7 @@ export class CanvasRecorder {
955
1048
  fit: "contain",
956
1049
  radius: layout.screen?.radius ?? SCREEN_RADIUS,
957
1050
  placeholder: false,
1051
+ speaking: false,
958
1052
  }] : []),
959
1053
  ...chosen.map((slot, index) => {
960
1054
  const rect = layout.cameras[index];
@@ -970,6 +1064,7 @@ export class CanvasRecorder {
970
1064
  fit: "cover",
971
1065
  placeholder: Boolean(slot.placeholder),
972
1066
  avatarBackground: slot.avatarBackground,
1067
+ speaking: Boolean(slot.speaking),
973
1068
  };
974
1069
  }),
975
1070
  ]);
@@ -1082,12 +1177,14 @@ export class CanvasRecorder {
1082
1177
  if (!rect) return;
1083
1178
  const label = resolveTileLabel(slot, this.selfName);
1084
1179
  const radius = rect.radius ?? TILE_RADIUS;
1180
+ const speaking = Boolean(slot.speaking);
1085
1181
  if (slot.placeholder) {
1086
1182
  drawStagePlaceholder(this.ctx, rect.x, rect.y, rect.w, rect.h, label, false, STAGE_BACKGROUND, {
1087
1183
  chrome: true,
1088
1184
  radius,
1089
1185
  muted: false,
1090
1186
  avatarBackground: slot.avatarBackground,
1187
+ speaking,
1091
1188
  });
1092
1189
  return;
1093
1190
  }
@@ -1098,6 +1195,7 @@ export class CanvasRecorder {
1098
1195
  radius,
1099
1196
  muted: false,
1100
1197
  avatarBackground: slot.avatarBackground,
1198
+ speaking,
1101
1199
  });
1102
1200
  });
1103
1201
  this.capture?.requestFrame();
@@ -1285,6 +1383,7 @@ function drawStagePlaceholder(ctx, x, y, w, h, name, _accent = false, _accentCol
1285
1383
  ctx.restore();
1286
1384
  if (!chrome) return;
1287
1385
  drawNamePill(ctx, x, y, w, h, name, {});
1386
+ if (options.speaking) strokeSpeakingRing(ctx, x, y, w, h, corner);
1288
1387
  }
1289
1388
 
1290
1389
  function paint(ctx, video, rect, crop, options = {}) {
@@ -1293,6 +1392,7 @@ function paint(ctx, video, rect, crop, options = {}) {
1293
1392
  const accentColor = options.accentColor || PRESENTER_ACCENT;
1294
1393
  const radius = options.radius ?? TILE_RADIUS;
1295
1394
  const muted = Boolean(options.muted);
1395
+ const speaking = Boolean(options.speaking);
1296
1396
  const fit = options.fit === "contain" ? "contain" : "cover";
1297
1397
  const fillStyle = options.fillStyle || STAGE_BACKGROUND;
1298
1398
  if (!video || video.readyState < 2 || !video.videoWidth) {
@@ -1312,6 +1412,7 @@ function paint(ctx, video, rect, crop, options = {}) {
1312
1412
  fillStyle,
1313
1413
  placeholder: true,
1314
1414
  avatarBackground: options.avatarBackground || null,
1415
+ speaking,
1315
1416
  });
1316
1417
  return;
1317
1418
  }
@@ -1342,6 +1443,7 @@ function paint(ctx, video, rect, crop, options = {}) {
1342
1443
  muted,
1343
1444
  fit,
1344
1445
  fillStyle,
1446
+ speaking,
1345
1447
  });
1346
1448
  }
1347
1449