mediascale-sdk 1.0.13 → 1.0.16

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)
@@ -222,7 +225,7 @@ await client.end(); // combines every segment into one file
222
225
 
223
226
  | Function | What it does |
224
227
  | --- | --- |
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. |
228
+ | `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). 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
229
  | `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
230
  | `subscribe()` | Starts playing the other people. Call this once after `connect()`. |
228
231
  | `startCamera({ cameraId, resolution, track })` | Publishes the camera. Pass `track` to use your own live video track (SDK clones it). |
@@ -240,7 +243,7 @@ await client.end(); // combines every segment into one file
240
243
  | `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
244
  | `stopRecording()` | Pauses recording without saving. Call `startRecording()` again to continue; `end()` still combines all segments into one file. |
242
245
  | `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). |
246
+ | `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
247
  | `setRecordingFps(fps)` / `getRecordingFps()` | Recording frame rate (1–60). Applies to the next `startRecording()`; a running segment keeps its rate. |
245
248
  | `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
249
  | `stopRtmp()` | Ends the live stream on every platform. Destinations stay saved so the host can Go Live again. |
@@ -249,7 +252,11 @@ await client.end(); // combines every segment into one file
249
252
  | `removeRtmpDestination(id)` | Deletes a destination. |
250
253
  | `getRtmpStatus()` | Returns the current live state (see `onRtmpStatus`). |
251
254
  | `setRtmpFps(fps)` / `getRtmpFps()` | RTMP frame rate (1–60). While live, the compositor restarts and swaps tracks in place (platforms stay connected). |
255
+ | `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. |
256
+ | `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
257
  | `canLiveStream()` | `true` when this browser can compose and encode H264. Hide or disable Go Live when this is `false`. |
258
+ | `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. |
259
+ | `getVideoCodecs()` | The ordered WebRTC video codec preference in use (`["vp8", "h264", "vp9", "av1"]` by default). |
253
260
  | `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
261
  | `getPeerId()` | Socket peer id for this browser after `connect()`. |
255
262
  | `getPublishLimits()` | Current `{ cameraBps, screenBps }` used for outgoing video encode caps. |
@@ -272,6 +279,7 @@ Pass these to `createClient`.
272
279
  | `onRecording(state)` | `armed` briefly while capture is preparing. `recording` while chunks are uploading. `stopped` after `stopRecording()`, handoff, or `end()`. |
273
280
  | `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. |
274
281
  | `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`. |
282
+ | `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. |
275
283
  | `onStageChanged(people)` | Optional. Fires when the recording stage list changes after `setRecordingStage` (or sample roster updates). |
276
284
  | `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. |
277
285
 
@@ -408,23 +416,48 @@ Use `setRecordingStage([{ id, name, local? }, ...])` so avatar tiles and name pi
408
416
 
409
417
  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
418
 
419
+ ### Stage look (background + avatars)
420
+
411
421
  ```js
422
+ import { createClient, avatarBackgroundFor, gradientToCss } from "mediascale-sdk";
423
+
412
424
  const client = createClient({
413
425
  endpoint,
414
426
  sessionId,
415
427
  token,
416
- recording: true,
417
- // Base color for the radial + wave canvas background.
418
- // Default: "#2563eb"
419
- recordingCanvasBackground: "#6d28d9",
428
+ // Stage backdrop for recording AND RTMP. CSS gradient string, object, or plain color.
429
+ canvasBackground: "linear-gradient(135deg, #0f2027 0%, #203a43 50%, #2c5364 100%)",
430
+ // Camera-off tiles: one gradient for everyone, or a list picked by a stable name hash.
431
+ avatarBackground: [
432
+ "linear-gradient(135deg, #f6d365, #fda085)",
433
+ "radial-gradient(circle at 50% 35%, #6d28d9, #2e1065)",
434
+ ],
420
435
  });
436
+
437
+ // Change live — no restart, platforms / recording keep running.
438
+ client.setAppearance({ canvasBackground: "radial-gradient(ellipse at 50% 40%, #2a1a6e, #05021a)" });
439
+
440
+ // Keep your own UI identical to the recording:
441
+ stageEl.style.background = client.getAppearance().canvasBackgroundCss;
442
+ tileEl.style.background = gradientToCss(avatarBackgroundFor(user.name, client.getAppearance().avatarBackground));
421
443
  ```
422
444
 
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). |
445
+ Accepted gradient values (`canvasBackground`, `avatarBackground`, per-person `avatarBackground`):
426
446
 
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.
447
+ | Form | Example |
448
+ | --- | --- |
449
+ | CSS linear | `"linear-gradient(135deg, #1e1b4b 0%, #0f172a 100%)"`, `"linear-gradient(to top right, red, blue)"` |
450
+ | CSS radial | `"radial-gradient(circle at 30% 20%, #6d28d9, #0b0620 70%)"`, `"radial-gradient(ellipse farthest-side at center, …)"` |
451
+ | Object | `{ type: "linear", angle: 135, stops: ["#1e1b4b", { color: "#0f172a", offset: 1 }] }`, `{ type: "radial", shape: "circle", at: [50, 50], stops: [...] }`, `{ type: "solid", color: "#111" }` |
452
+ | Plain color | `"#0A0036"` — the backdrop keeps the legacy soft-glow look derived from that color |
453
+
454
+ - The canvas draws gradients with CSS geometry (angles, `to <corner>`, radial sizes/positions), so the same string looks the same in your DOM.
455
+ - 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).
456
+ - Screen share is letterboxed onto the **same** backdrop (no separate box color), so the background is uniform.
457
+ - Without `avatarBackground`, the built-in per-name tones are used (`DEFAULT_AVATAR_BACKGROUNDS`); `avatarBackgroundFor(name)` returns that same pick for your UI.
458
+ - Per person: `setRecordingStage([{ id, name, avatarBackground: "linear-gradient(...)" }])` wins over the shared list.
459
+
460
+ 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
461
 
429
462
  ### Background-safe compositing
430
463
 
@@ -459,6 +492,26 @@ A host streams the meeting to several platforms at once (YouTube, Twitch, Facebo
459
492
 
460
493
  Audience tokens never get `rtmp`. Stream keys never go in the JWT — only in destination storage / `addRtmpDestinations`.
461
494
 
495
+ ### Start modes
496
+
497
+ 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.
498
+
499
+ | | `webrtc` (default) | `rtmp` — live stream first |
500
+ |---|---|---|
501
+ | 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 |
502
+ | 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 |
503
+ | Host goes Live | An extra H264 stage goes to RTMP | Already live |
504
+ | Last participant leaves | Unchanged | After 30 s the SDK stops the WebRTC video producers; the local tracks keep running |
505
+
506
+ **Audio is one Opus stream whenever possible.** When nothing needs mixing, RTMP uses the host's `mic` producer directly. Nothing needs mixing when:
507
+ - no other microphone is on the stage,
508
+ - there is no screen or tab audio, and
509
+ - the host's mic is on.
510
+
511
+ 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.
512
+
513
+ 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.
514
+
462
515
  ### Path A — Stream Control webinar create
463
516
 
464
517
  Stream Control → Webinar → **Enable live streaming (RTMP)** saves destinations (keys encrypted) and puts `rtmp: true` on the host link.
@@ -484,6 +537,7 @@ await fetch("/api/token", {
484
537
  name: hostDisplayName,
485
538
  recording: true, // optional
486
539
  rtmp: true, // auto Go Live when destinations already exist
540
+ startMode: "rtmp", // optional: live stream first, WebRTC video only once someone joins
487
541
  }),
488
542
  });
489
543
  ```
@@ -502,8 +556,10 @@ const client = createClient({
502
556
  endpoint, // e.g. https://stream.example.com or http://localhost:8080
503
557
  sessionId,
504
558
  token, // host JWT
559
+ rtmpResolution: "1080p", // 480p | 540p | 720p | 1080p (default 1080p)
505
560
  rtmpFps: 30, // live canvas / H264 (default 30)
506
- rtmpBitrate: 2_500_000,
561
+ rtmpBitrate: 2_500_000, // bps, max 2 500 000 (2500 kbps)
562
+ rtmpKeyframeInterval: 2, // seconds (default 2)
507
563
  recordingFps: 15, // independent of rtmpFps
508
564
  onRtmpStatus: (status) => {
509
565
  // status.enabled — show Live for managers once the room allows it
@@ -625,7 +681,7 @@ RTMP server (one VM runs many meetings)
625
681
 
626
682
  - Hidden tracks are charged on the **origin** only and are never sent to edges or shown to participants.
627
683
  - 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.
684
+ - Host uploads about `rtmpBitrate` (default and max 2.5 Mbps) more while live.
629
685
  - If the presenter leaves, another publisher takes over composing (same idea as recording). If nobody can, the stream stops.
630
686
  - Each destination reconnects with its own backoff; one bad key does not stop the others.
631
687
  - 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 +695,35 @@ RTMP server (one VM runs many meetings)
639
695
 
640
696
  Separate canvases — each rate is independent. Live compositor window events: `mediascale:live-mode` / `mediascale:live-error`.
641
697
 
698
+ ### Live stream quality
699
+
700
+ | Option | Default | Range | Notes |
701
+ | --- | --- | --- | --- |
702
+ | `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. |
703
+ | `rtmpFps` | `30` | 1–60 | Frame rate of the canvas and the encoder. |
704
+ | `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). |
705
+ | `rtmpKeyframeInterval` | `2` | 1–10 s | The origin requests a keyframe at this interval. YouTube / Facebook want 2 s (4 s at most). |
706
+
707
+ Suggested presets at the 2.5 Mbps cap:
708
+
709
+ | Content | Resolution | FPS |
710
+ | --- | --- | --- |
711
+ | Slides / screen share (default) | `1080p` | 30 |
712
+ | Mostly cameras, lots of motion | `720p` | 30 |
713
+ | Weak host uplink / CPU | `720p` (and a lower `rtmpBitrate`) | 24–30 |
714
+
715
+ How the quality is kept up:
716
+
717
+ - The encoder keeps the frame size fixed (`maintain-resolution`). Under pressure it drops frames instead of resolution.
718
+ - Screen-share tracks are tagged `contentHint = "detail"`, so the sharer's encoder keeps text sharp.
719
+ - 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.
720
+ - The stream can only be as sharp as its sources. A remote participant's camera arrives at that participant's publish quality (`publishLimits.cameraBps`).
721
+
722
+ ```js
723
+ await client.setRtmpQuality({ resolution: "720p", fps: 30, bitrate: 2_000_000 });
724
+ client.getRtmpQuality(); // { resolution: "720p", width: 1280, height: 720, fps: 30, bitrate: 2000000, keyframeInterval: 2 }
725
+ ```
726
+
642
727
  ## Run the sample
643
728
 
644
729
  ```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.16",
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",