mediascale-sdk 1.0.13 → 1.0.15

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.
@@ -222,7 +222,7 @@ await client.end(); // combines every segment into one file
222
222
 
223
223
  | Function | What it does |
224
224
  | --- | --- |
225
- | `createClient({ endpoint, sessionId, token, recording, recordingCanvasBackground, recordingFps, recordingBitrate, rtmpFps, rtmpBitrate, iceServers, publishLimits, ...callbacks })` | Prepares the client. `sessionId` and `token` are required. `endpoint` defaults to `http://localhost:8080`. `recording` defaults to **false**. Optional `recordingCanvasBackground` (CSS color, default `#2563eb`) is the base for the radial + wave canvas backdrop and the local/presenter accent border. 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 2.5 Mbps) are in bps. |
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). |
226
226
  | `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
227
  | `subscribe()` | Starts playing the other people. Call this once after `connect()`. |
228
228
  | `startCamera({ cameraId, resolution, track })` | Publishes the camera. Pass `track` to use your own live video track (SDK clones it). |
@@ -240,7 +240,7 @@ await client.end(); // combines every segment into one file
240
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. |
241
241
  | `stopRecording()` | Pauses recording without saving. Call `startRecording()` again to continue; `end()` still combines all segments into one file. |
242
242
  | `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
- | `setRecordingStage(people)` | **Required for stage-accurate recording.** Who appears on the recording stage: `[{ id, name, local? }]` (max six on canvas). Avatars + name pills until that peer’s webcam arrives. See [Recording must match the live stage](#recording-must-match-the-live-stage). |
243
+ | `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
244
  | `setRecordingFps(fps)` / `getRecordingFps()` | Recording frame rate (1–60). Applies to the next `startRecording()`; a running segment keeps its rate. |
245
245
  | `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
246
  | `stopRtmp()` | Ends the live stream on every platform. Destinations stay saved so the host can Go Live again. |
@@ -249,6 +249,8 @@ await client.end(); // combines every segment into one file
249
249
  | `removeRtmpDestination(id)` | Deletes a destination. |
250
250
  | `getRtmpStatus()` | Returns the current live state (see `onRtmpStatus`). |
251
251
  | `setRtmpFps(fps)` / `getRtmpFps()` | RTMP frame rate (1–60). While live, the compositor restarts and swaps tracks in place (platforms stay connected). |
252
+ | `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
+ | `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 }`. |
252
254
  | `canLiveStream()` | `true` when this browser can compose and encode H264. Hide or disable Go Live when this is `false`. |
253
255
  | `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. |
254
256
  | `getPeerId()` | Socket peer id for this browser after `connect()`. |
@@ -408,23 +410,48 @@ Use `setRecordingStage([{ id, name, local? }, ...])` so avatar tiles and name pi
408
410
 
409
411
  The canvas behind multi-tile / screen layouts defaults to `#2563eb`. Pass any CSS color on `createClient`; the SDK paints a **radial gradient with soft wave glows** from that color:
410
412
 
413
+ ### Stage look (background + avatars)
414
+
411
415
  ```js
416
+ import { createClient, avatarBackgroundFor, gradientToCss } from "mediascale-sdk";
417
+
412
418
  const client = createClient({
413
419
  endpoint,
414
420
  sessionId,
415
421
  token,
416
- recording: true,
417
- // Base color for the radial + wave canvas background.
418
- // Default: "#2563eb"
419
- recordingCanvasBackground: "#6d28d9",
422
+ // Stage backdrop for recording AND RTMP. CSS gradient string, object, or plain color.
423
+ canvasBackground: "linear-gradient(135deg, #0f2027 0%, #203a43 50%, #2c5364 100%)",
424
+ // Camera-off tiles: one gradient for everyone, or a list picked by a stable name hash.
425
+ avatarBackground: [
426
+ "linear-gradient(135deg, #f6d365, #fda085)",
427
+ "radial-gradient(circle at 50% 35%, #6d28d9, #2e1065)",
428
+ ],
420
429
  });
430
+
431
+ // Change live — no restart, platforms / recording keep running.
432
+ client.setAppearance({ canvasBackground: "radial-gradient(ellipse at 50% 40%, #2a1a6e, #05021a)" });
433
+
434
+ // Keep your own UI identical to the recording:
435
+ stageEl.style.background = client.getAppearance().canvasBackgroundCss;
436
+ tileEl.style.background = gradientToCss(avatarBackgroundFor(user.name, client.getAppearance().avatarBackground));
421
437
  ```
422
438
 
423
- | Option | Default | Meaning |
424
- | --- | --- | --- |
425
- | `recordingCanvasBackground` | `#2563eb` | Base CSS color for the recording canvas gradient / wave backdrop and the local/presenter accent border (multi-tile layouts). |
439
+ Accepted gradient values (`canvasBackground`, `avatarBackground`, per-person `avatarBackground`):
440
+
441
+ | Form | Example |
442
+ | --- | --- |
443
+ | CSS linear | `"linear-gradient(135deg, #1e1b4b 0%, #0f172a 100%)"`, `"linear-gradient(to top right, red, blue)"` |
444
+ | CSS radial | `"radial-gradient(circle at 30% 20%, #6d28d9, #0b0620 70%)"`, `"radial-gradient(ellipse farthest-side at center, …)"` |
445
+ | Object | `{ type: "linear", angle: 135, stops: ["#1e1b4b", { color: "#0f172a", offset: 1 }] }`, `{ type: "radial", shape: "circle", at: [50, 50], stops: [...] }`, `{ type: "solid", color: "#111" }` |
446
+ | Plain color | `"#0A0036"` — the backdrop keeps the legacy soft-glow look derived from that color |
426
447
 
427
- Set this once at `createClient`. It applies to both the worker compositor and the foreground canvas fallback. On a **single full-bleed** camera/avatar tile the background is covered by the tile itself.
448
+ - The canvas draws gradients with CSS geometry (angles, `to <corner>`, radial sizes/positions), so the same string looks the same in your DOM.
449
+ - Stops accept any CSS color and `%` positions (missing positions are spread like CSS). `repeating-*` and `conic-gradient` are not supported → default is used (a warning is logged).
450
+ - Screen share is letterboxed onto the **same** backdrop (no separate box color), so the background is uniform.
451
+ - Without `avatarBackground`, the built-in per-name tones are used (`DEFAULT_AVATAR_BACKGROUNDS`); `avatarBackgroundFor(name)` returns that same pick for your UI.
452
+ - Per person: `setRecordingStage([{ id, name, avatarBackground: "linear-gradient(...)" }])` wins over the shared list.
453
+
454
+ Performance: the backdrop is rendered once per output size and blitted each frame; camera-off tiles are painted directly by the compositor (no hidden canvas track per avatar).
428
455
 
429
456
  ### Background-safe compositing
430
457
 
@@ -502,8 +529,10 @@ const client = createClient({
502
529
  endpoint, // e.g. https://stream.example.com or http://localhost:8080
503
530
  sessionId,
504
531
  token, // host JWT
532
+ rtmpResolution: "1080p", // 480p | 540p | 720p | 1080p (default 1080p)
505
533
  rtmpFps: 30, // live canvas / H264 (default 30)
506
- rtmpBitrate: 2_500_000,
534
+ rtmpBitrate: 2_500_000, // bps, max 2 500 000 (2500 kbps)
535
+ rtmpKeyframeInterval: 2, // seconds (default 2)
507
536
  recordingFps: 15, // independent of rtmpFps
508
537
  onRtmpStatus: (status) => {
509
538
  // status.enabled — show Live for managers once the room allows it
@@ -625,7 +654,7 @@ RTMP server (one VM runs many meetings)
625
654
 
626
655
  - Hidden tracks are charged on the **origin** only and are never sent to edges or shown to participants.
627
656
  - Browser must encode **H264** (Chrome, Edge, Safari). Check `canLiveStream()` before enabling Go Live.
628
- - Host uploads about `rtmpBitrate` (default 2.5 Mbps) more while live.
657
+ - Host uploads about `rtmpBitrate` (default and max 2.5 Mbps) more while live.
629
658
  - If the presenter leaves, another publisher takes over composing (same idea as recording). If nobody can, the stream stops.
630
659
  - Each destination reconnects with its own backoff; one bad key does not stop the others.
631
660
  - Platform side (e.g. YouTube) must already be **Go Live** / accepting the key, or the destination stays connecting / failed while Mediascale is pushing.
@@ -639,6 +668,35 @@ RTMP server (one VM runs many meetings)
639
668
 
640
669
  Separate canvases — each rate is independent. Live compositor window events: `mediascale:live-mode` / `mediascale:live-error`.
641
670
 
671
+ ### Live stream quality
672
+
673
+ | Option | Default | Range | Notes |
674
+ | --- | --- | --- | --- |
675
+ | `rtmpResolution` | `1080p` | Preset `480p` / `540p` / `720p` / `1080p`, custom `"1600x900"` / `"1080x1920"` / `{ width, height }`, or a height (`720` → 16:9) | Size of the stage canvas and the H264 output. Aspect ratio is kept; the size is clamped to ≤ 1920 px on the long edge and ≤ 1920×1080 pixels (e.g. `3840x2160` → `1920x1080`) so the browser stays light. Dimensions are rounded to even numbers. Layout is the same at every 16:9 size; other aspects (portrait, 4:3, square) re-flow the tiles. |
676
+ | `rtmpFps` | `30` | 1–60 | Frame rate of the canvas and the encoder. |
677
+ | `rtmpBitrate` | `2_500_000` | 300 000 – 2 500 000 bps | **Hard cap 2500 kbps.** Larger values are clamped. Values under 10 000 are read as kbps (`2500` = 2.5 Mbps). |
678
+ | `rtmpKeyframeInterval` | `2` | 1–10 s | The origin requests a keyframe at this interval. YouTube / Facebook want 2 s (4 s at most). |
679
+
680
+ Suggested presets at the 2.5 Mbps cap:
681
+
682
+ | Content | Resolution | FPS |
683
+ | --- | --- | --- |
684
+ | Slides / screen share (default) | `1080p` | 30 |
685
+ | Mostly cameras, lots of motion | `720p` | 30 |
686
+ | Weak host uplink / CPU | `720p` (and a lower `rtmpBitrate`) | 24–30 |
687
+
688
+ How the quality is kept up:
689
+
690
+ - The encoder keeps the frame size fixed (`maintain-resolution`). Under pressure it drops frames instead of resolution.
691
+ - Screen-share tracks are tagged `contentHint = "detail"`, so the sharer's encoder keeps text sharp.
692
+ - While the stage track is live, the origin gives the host's send transport `RTMP_PUBLISH_HEADROOM_BPS` (default 2.6 Mbps) on top of `MAX_PUBLISH_BITRATE_BPS`. The live track therefore doesn't compete with the host's own camera and screen.
693
+ - The stream can only be as sharp as its sources. A remote participant's camera arrives at that participant's publish quality (`publishLimits.cameraBps`).
694
+
695
+ ```js
696
+ await client.setRtmpQuality({ resolution: "720p", fps: 30, bitrate: 2_000_000 });
697
+ client.getRtmpQuality(); // { resolution: "720p", width: 1280, height: 720, fps: 30, bitrate: 2000000, keyframeInterval: 2 }
698
+ ```
699
+
642
700
  ## Run the sample
643
701
 
644
702
  ```bash
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mediascale-sdk",
3
- "version": "1.0.13",
3
+ "version": "1.0.15",
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
@@ -9,7 +9,14 @@ import {
9
9
  resolveRecorderAffinity,
10
10
  tracksFromTiles,
11
11
  } from "./record.js";
12
- import { DEFAULT_RTMP_BITRATE, DEFAULT_RTMP_FPS, LiveCompositor } from "./live.js";
12
+ import {
13
+ DEFAULT_RTMP_FPS,
14
+ LiveCompositor,
15
+ clampRtmpBitrate,
16
+ clampRtmpKeyframeInterval,
17
+ normalizeRtmpResolution,
18
+ } from "./live.js";
19
+ import { gradientToCss, normalizeGradient } from "./gradient.js";
13
20
 
14
21
  const SIZES = {
15
22
  "480p": { width: 854, height: 480 },
@@ -38,10 +45,29 @@ function normalizePublishLimits(raw = {}) {
38
45
  };
39
46
  }
40
47
 
41
- /** CSS color for the recording canvas gradient. Empty → design navy default. */
48
+ const DEFAULT_CANVAS_BACKGROUND = "#0A0036";
49
+
50
+ /**
51
+ * Stage backdrop for recording + RTMP: a CSS color (legacy glow look) or any gradient
52
+ * (`linear-gradient(...)`, `radial-gradient(...)`, `{ type, angle, stops }`). Invalid → default.
53
+ */
42
54
  function normalizeCanvasBackground(raw) {
43
- const color = String(raw ?? "").trim();
44
- return color || "#0A0036";
55
+ if (raw == null || raw === "") return DEFAULT_CANVAS_BACKGROUND;
56
+ if (!normalizeGradient(raw)) {
57
+ console.warn("[mediascale] canvasBackground not understood, using the default", raw);
58
+ return DEFAULT_CANVAS_BACKGROUND;
59
+ }
60
+ return typeof raw === "string" ? raw.trim() : raw;
61
+ }
62
+
63
+ /** Camera-off tile gradient: one spec or a list (picked by participant name). null → built-in tones. */
64
+ function normalizeAvatarBackground(raw) {
65
+ if (raw == null || raw === "") return null;
66
+ if (Array.isArray(raw)) {
67
+ const list = raw.filter((item) => normalizeGradient(item));
68
+ return list.length ? list : null;
69
+ }
70
+ return normalizeGradient(raw) ? raw : null;
45
71
  }
46
72
 
47
73
  function readToken(token) {
@@ -146,12 +172,21 @@ export function createClient(options = {}) {
146
172
  const recording = options.recording === true
147
173
  || (options.recording !== false && claims.recording === true && claims.role === "host");
148
174
  // Main recording canvas fill (letterbox / empty areas). Defaults to design navy.
149
- const recordingCanvasBackground = normalizeCanvasBackground(options.recordingCanvasBackground);
175
+ // `canvasBackground` (gradient or color) wins; `recordingCanvasBackground` is the older name.
176
+ let canvasBackground = normalizeCanvasBackground(options.canvasBackground ?? options.recordingCanvasBackground);
177
+ let avatarBackground = normalizeAvatarBackground(options.avatarBackground);
150
178
  // Frame rates are independent: recording (MediaRecorder) vs RTMP live output.
151
179
  let recordingFps = clampFps(options.recordingFps, DEFAULT_RECORDING_FPS);
152
180
  const recordingBitrate = Number(options.recordingBitrate) > 0 ? Math.round(Number(options.recordingBitrate)) : undefined;
153
- let rtmpFps = clampFps(options.rtmpFps, DEFAULT_RTMP_FPS);
154
- const rtmpBitrate = Number(options.rtmpBitrate) > 0 ? Math.round(Number(options.rtmpBitrate)) : DEFAULT_RTMP_BITRATE;
181
+ // RTMP output quality. Flat options or `rtmpQuality: { resolution, fps, bitrate, keyframeInterval }`.
182
+ const rtmpQualityOption = options.rtmpQuality && typeof options.rtmpQuality === "object" ? options.rtmpQuality : {};
183
+ let rtmpFps = clampFps(options.rtmpFps ?? rtmpQualityOption.fps, DEFAULT_RTMP_FPS);
184
+ /** bps, capped at 2500 kbps. */
185
+ let rtmpBitrate = clampRtmpBitrate(options.rtmpBitrate ?? rtmpQualityOption.bitrate);
186
+ /** "480p" | "540p" | "720p" | "1080p". */
187
+ let rtmpResolution = normalizeRtmpResolution(options.rtmpResolution ?? rtmpQualityOption.resolution);
188
+ /** Seconds between keyframes (GOP). Sent to the portal on Go Live. */
189
+ let rtmpKeyframeInterval = clampRtmpKeyframeInterval(options.rtmpKeyframeInterval ?? rtmpQualityOption.keyframeInterval);
155
190
  /**
156
191
  * Hosts can always open Live. `claims.rtmp` means destinations were prepared at
157
192
  * webinar create — auto Go Live after join when those destinations are present.
@@ -215,10 +250,14 @@ export function createClient(options = {}) {
215
250
  const id = String(person.id || "").trim();
216
251
  const name = String(person.name || "Guest").trim().slice(0, 40) || "Guest";
217
252
  if (!id && !name) return null;
253
+ const avatar = person.avatarBackground != null && normalizeGradient(person.avatarBackground)
254
+ ? person.avatarBackground
255
+ : null;
218
256
  return {
219
257
  id,
220
258
  name,
221
259
  local: Boolean(person.local) || Boolean(id && selfPeerId && id === selfPeerId),
260
+ ...(avatar ? { avatarBackground: avatar } : {}),
222
261
  };
223
262
  }
224
263
 
@@ -1021,6 +1060,8 @@ export function createClient(options = {}) {
1021
1060
  stream.getTracks().forEach((track) => track.stop());
1022
1061
  throw new Error("No screen was selected");
1023
1062
  }
1063
+ // Text / slides: the encoder keeps full resolution and drops frames instead of blurring.
1064
+ try { videoTrack.contentHint = "detail"; } catch { /* optional */ }
1024
1065
  try {
1025
1066
  const screen = await produce("screen", videoTrack);
1026
1067
  // Screen audio is optional — never tear down a live video share if mic capture fails.
@@ -1119,7 +1160,8 @@ export function createClient(options = {}) {
1119
1160
  endpoint,
1120
1161
  token,
1121
1162
  selfName: displayName,
1122
- canvasBackground: recordingCanvasBackground,
1163
+ canvasBackground,
1164
+ avatarBackground,
1123
1165
  recorderPeer: peer,
1124
1166
  fps: recordingFps,
1125
1167
  bitrate: recordingBitrate,
@@ -1230,6 +1272,30 @@ export function createClient(options = {}) {
1230
1272
  }
1231
1273
  }
1232
1274
 
1275
+ function liveEncoding() {
1276
+ return {
1277
+ maxBitrate: rtmpBitrate,
1278
+ maxFramerate: rtmpFps,
1279
+ scaleResolutionDownBy: 1,
1280
+ priority: "high",
1281
+ networkPriority: "high",
1282
+ };
1283
+ }
1284
+
1285
+ /** Bitrate / fps cap + keep the frame size fixed (platforms dislike resolution changes). */
1286
+ async function applyLiveSenderParams(video) {
1287
+ const sender = video?.rtpSender;
1288
+ if (!sender?.getParameters) return;
1289
+ try {
1290
+ const params = sender.getParameters();
1291
+ params.degradationPreference = "maintain-resolution";
1292
+ if (params.encodings?.[0]) Object.assign(params.encodings[0], liveEncoding());
1293
+ await sender.setParameters(params);
1294
+ } catch {
1295
+ /* optional: older browsers ignore some fields */
1296
+ }
1297
+ }
1298
+
1233
1299
  async function closeLiveProducers() {
1234
1300
  const producers = liveProducers;
1235
1301
  liveProducers = [];
@@ -1242,8 +1308,10 @@ export function createClient(options = {}) {
1242
1308
  async function createLiveCompositor() {
1243
1309
  const next = new LiveCompositor({
1244
1310
  fps: rtmpFps,
1311
+ resolution: rtmpResolution,
1245
1312
  selfName: displayName,
1246
- canvasBackground: recordingCanvasBackground,
1313
+ canvasBackground,
1314
+ avatarBackground,
1247
1315
  onFailure: (error) => {
1248
1316
  if (live !== next) return;
1249
1317
  onError(error);
@@ -1276,20 +1344,12 @@ export function createClient(options = {}) {
1276
1344
  try {
1277
1345
  const video = await produceHidden("rtmp-video", next.videoTrack, {
1278
1346
  codec,
1279
- encodings: [{ maxBitrate: rtmpBitrate, maxFramerate: rtmpFps }],
1280
- codecOptions: { videoGoogleStartBitrate: Math.max(300, Math.min(2500, Math.round(rtmpBitrate / 2000))) },
1347
+ encodings: [liveEncoding()],
1348
+ // Start near the target so the first seconds on the platform are not blurry.
1349
+ codecOptions: { videoGoogleStartBitrate: Math.round(rtmpBitrate / 1000 * 0.8) },
1281
1350
  });
1282
1351
  liveProducers.push(video);
1283
- // Platforms expect a steady frame size; let WebRTC drop frames rather than resolution.
1284
- try {
1285
- const params = video.rtpSender?.getParameters();
1286
- if (params) {
1287
- params.degradationPreference = "maintain-resolution";
1288
- await video.rtpSender.setParameters(params);
1289
- }
1290
- } catch {
1291
- /* optional */
1292
- }
1352
+ await applyLiveSenderParams(video);
1293
1353
  const audio = await produceHidden("rtmp-audio", next.audioTrack);
1294
1354
  liveProducers.push(audio);
1295
1355
  } catch (error) {
@@ -1326,7 +1386,10 @@ export function createClient(options = {}) {
1326
1386
  if (!canLiveStream()) {
1327
1387
  throw new Error("This browser cannot encode H264, which live streaming needs. Use Chrome, Edge, or Safari.");
1328
1388
  }
1329
- const result = await emit(socket, "startRtmp", { destinations }, 15000);
1389
+ const result = await emit(socket, "startRtmp", {
1390
+ destinations,
1391
+ quality: { keyframeInterval: rtmpKeyframeInterval },
1392
+ }, 15000);
1330
1393
  setRtmpState(result.rtmp);
1331
1394
  try {
1332
1395
  await startLiveOutput();
@@ -1367,28 +1430,89 @@ export function createClient(options = {}) {
1367
1430
  return recordingFps;
1368
1431
  }
1369
1432
 
1370
- /** RTMP frame rate (1–60). Applied live: the compositor restarts and swaps tracks in place. */
1371
- async function setRtmpFps(fps) {
1372
- const next = clampFps(fps, rtmpFps);
1373
- if (next === rtmpFps) return rtmpFps;
1374
- rtmpFps = next;
1375
- if (!live || liveProducers.length < 2) return rtmpFps;
1433
+ /** Rebuild the live compositor (new fps / resolution) and swap tracks without leaving the platforms. */
1434
+ async function restartLiveCompositor() {
1435
+ if (!live || liveProducers.length < 2) return;
1376
1436
  const previous = live;
1377
1437
  const replacement = await createLiveCompositor();
1378
1438
  const [video, audio] = liveProducers;
1379
1439
  await video.replaceTrack({ track: replacement.videoTrack });
1380
1440
  await audio.replaceTrack({ track: replacement.audioTrack });
1381
- try {
1382
- const params = video.rtpSender?.getParameters();
1383
- if (params?.encodings?.[0]) {
1384
- params.encodings[0].maxFramerate = rtmpFps;
1385
- await video.rtpSender.setParameters(params);
1386
- }
1387
- } catch {
1388
- /* optional */
1389
- }
1441
+ await applyLiveSenderParams(video);
1390
1442
  live = replacement;
1391
1443
  await previous.finish().catch(() => {});
1444
+ }
1445
+
1446
+ function getRtmpQuality() {
1447
+ return {
1448
+ resolution: rtmpResolution.label,
1449
+ width: rtmpResolution.width,
1450
+ height: rtmpResolution.height,
1451
+ fps: rtmpFps,
1452
+ bitrate: rtmpBitrate,
1453
+ keyframeInterval: rtmpKeyframeInterval,
1454
+ };
1455
+ }
1456
+
1457
+ /**
1458
+ * Update RTMP output quality. Any subset of
1459
+ * `{ resolution: "480p"|"540p"|"720p"|"1080p", fps: 1–60, bitrate: bps (≤ 2 500 000), keyframeInterval: s (1–10) }`.
1460
+ * While live: bitrate applies instantly; fps / resolution restart the compositor in place;
1461
+ * keyframeInterval applies on the next Go Live.
1462
+ */
1463
+ async function setRtmpQuality(next = {}) {
1464
+ const fps = next.fps != null ? clampFps(next.fps, rtmpFps) : rtmpFps;
1465
+ const resolution = next.resolution != null ? normalizeRtmpResolution(next.resolution, rtmpResolution) : rtmpResolution;
1466
+ const bitrate = next.bitrate != null ? clampRtmpBitrate(next.bitrate, rtmpBitrate) : rtmpBitrate;
1467
+ if (next.keyframeInterval != null) {
1468
+ rtmpKeyframeInterval = clampRtmpKeyframeInterval(next.keyframeInterval, rtmpKeyframeInterval);
1469
+ }
1470
+ const restart = fps !== rtmpFps
1471
+ || resolution.width !== rtmpResolution.width
1472
+ || resolution.height !== rtmpResolution.height;
1473
+ const rebitrate = bitrate !== rtmpBitrate;
1474
+ rtmpFps = fps;
1475
+ rtmpResolution = resolution;
1476
+ rtmpBitrate = bitrate;
1477
+ if (live && liveProducers.length >= 2) {
1478
+ if (restart) await restartLiveCompositor();
1479
+ else if (rebitrate) await applyLiveSenderParams(liveProducers[0]);
1480
+ }
1481
+ return getRtmpQuality();
1482
+ }
1483
+
1484
+ /**
1485
+ * Stage look for recording + RTMP (applied live, no restart):
1486
+ * `{ canvasBackground, avatarBackground }` — colors / gradients (see createClient options).
1487
+ * Pass `null` to reset one to the default.
1488
+ */
1489
+ function setAppearance(next = {}) {
1490
+ const update = {};
1491
+ if (next.canvasBackground !== undefined) {
1492
+ canvasBackground = normalizeCanvasBackground(next.canvasBackground);
1493
+ update.canvasBackground = canvasBackground;
1494
+ }
1495
+ if (next.avatarBackground !== undefined) {
1496
+ avatarBackground = normalizeAvatarBackground(next.avatarBackground);
1497
+ update.avatarBackground = avatarBackground;
1498
+ }
1499
+ recorder?.setAppearance?.(update);
1500
+ live?.setAppearance?.(update);
1501
+ return getAppearance();
1502
+ }
1503
+
1504
+ function getAppearance() {
1505
+ return {
1506
+ canvasBackground,
1507
+ avatarBackground,
1508
+ /** Ready-to-use CSS `background` for your own stage element. */
1509
+ canvasBackgroundCss: gradientToCss(canvasBackground),
1510
+ };
1511
+ }
1512
+
1513
+ /** RTMP frame rate (1–60). Applied live: the compositor restarts and swaps tracks in place. */
1514
+ async function setRtmpFps(fps) {
1515
+ await setRtmpQuality({ fps });
1392
1516
  return rtmpFps;
1393
1517
  }
1394
1518
 
@@ -1509,6 +1633,10 @@ export function createClient(options = {}) {
1509
1633
  removeRtmpDestination: guard(removeRtmpDestination),
1510
1634
  setRtmpFps: guard(setRtmpFps),
1511
1635
  getRtmpFps: () => rtmpFps,
1636
+ setRtmpQuality: guard(setRtmpQuality),
1637
+ getRtmpQuality,
1638
+ setAppearance,
1639
+ getAppearance,
1512
1640
  canLiveStream,
1513
1641
  isRtmpEnabled: () => Boolean(rtmpState.enabled),
1514
1642
  setRecordingCrop,