mediascale-sdk 1.0.12 → 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.
@@ -1,10 +1,12 @@
1
- # Use the SDK in Next.js ( v1.0.6 )
1
+ # Use the SDK in Next.js ( v1.1.0 )
2
2
 
3
3
  One address talks to Mediascale. The default is `http://localhost:8080`.
4
4
 
5
5
  A person joins a session, turns on camera and microphone, hears the others, and leaves. Recording is **off by default**. Pass `recording: true` to `createClient`, or put `recording: true` on a **host** token (for example from Stream Control → Webinar → Enable recording). Recording then starts on `connect()` — no mic or camera required. You can also call `startRecording()` / `stopRecording()` any time. Each start/stop opens a new segment; `end()` combines every segment into one file.
6
6
 
7
- The secret that signs tokens stays on your server. The browser only receives a short-lived token.
7
+ Live streaming to YouTube, Twitch, Facebook, or any RTMP server is built in. Put destinations on the meeting (Stream Control or `addRtmpDestinations`), put `rtmp: true` on the **host** token when you want streaming to start on join, or call `startRtmp()` from your Live UI. See [Live streaming (RTMP)](#live-streaming-rtmp).
8
+
9
+ The secret that signs tokens stays on your server. The browser only receives a short-lived token. **Never put stream keys in the JWT.**
8
10
 
9
11
  ## Install
10
12
 
@@ -43,6 +45,8 @@ export async function POST(request) {
43
45
  const role = body.role === "host" ? "host" : "audience";
44
46
  const name = String(body.name || "Guest").slice(0, 40);
45
47
  const recording = body.recording === true || body.recording === "1" || body.recording === 1;
48
+ // Host-only: when true and destinations exist for this sessionId, SDK auto Go Live on connect().
49
+ const rtmp = body.rtmp === true || body.rtmp === "1" || body.rtmp === 1;
46
50
  if (!sessionId) return Response.json({ error: "sessionId is required" }, { status: 400 });
47
51
 
48
52
  const payload = {
@@ -50,7 +54,7 @@ export async function POST(request) {
50
54
  role,
51
55
  name,
52
56
  // Host-only: when true, createClient starts recording on connect() even if you omit recording: true.
53
- ...(role === "host" ? { recording } : { recording: false }),
57
+ ...(role === "host" ? { recording, rtmp } : { recording: false }),
54
58
  exp: Date.now() + 2 * 60 * 60 * 1000,
55
59
  };
56
60
  const encoded = Buffer.from(JSON.stringify(payload)).toString("base64url");
@@ -69,6 +73,7 @@ Token claims the SDK reads:
69
73
  | `role` | `host` or `audience` (required) |
70
74
  | `name` | Display name |
71
75
  | `recording` | When `true` on a **host** token, auto-start recording on `connect()` unless `createClient({ recording: false })` |
76
+ | `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. |
72
77
  | `exp` | Expiry as a Unix timestamp in **milliseconds** |
73
78
 
74
79
  ### Sample stage roles (meet UI)
@@ -121,7 +126,8 @@ Copy `sdk/react-sdk/sample/app/room.js` into your app. The comments in that file
121
126
  4. **Screen** calls `startScreenShare()` or `stopScreenShare()`.
122
127
  5. **Custom stream** (optional) — see [Custom streams](#custom-streams) (`startCustomStream` / `stopCustomStream`), for example a whiteboard tab capture.
123
128
  6. **Record** (host) starts automatically when enabled on the token / `createClient`, or from the toolbar via `startRecording()` / `stopRecording()`. You can toggle any time; the final file includes every segment and mirrors the live stage layout.
124
- 7. **End** leaves the session and saves the recording if this person was recording.
129
+ 7. **Live (RTMP)** (host / co-host) — wire a Live control to `onRtmpStatus`, `startRtmp()`, and `stopRtmp()`. If the host token has `rtmp: true` and destinations were saved for this `sessionId`, streaming starts on connect (same as pressing Go Live). See [Live streaming (RTMP)](#live-streaming-rtmp).
130
+ 8. **End** leaves the session and saves the recording if this person was recording.
125
131
 
126
132
  `recording` defaults to **false**. Set `createClient({ recording: true })` **or** put `recording: true` on the host JWT when the host should already be recording when they join (Stream Control “Enable recording” does this). Chunks start **immediately** on connect / `startRecording()` — mic and camera are not required. Until video is live, the recording canvas shows the host placeholder (magenta field, circular letter avatar, bottom-left **name pill**).
127
133
 
@@ -216,8 +222,8 @@ await client.end(); // combines every segment into one file
216
222
 
217
223
  | Function | What it does |
218
224
  | --- | --- |
219
- | `createClient({ endpoint, sessionId, token, recording, recordingCanvasBackground, 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. |
220
- | `connect()` | Checks the token and joins the session. If recording is enabled for a **host**, recording starts immediately in the background (same as `startRecording()`). Join does not wait for capture to finish preparing. |
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
+ | `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. |
221
227
  | `subscribe()` | Starts playing the other people. Call this once after `connect()`. |
222
228
  | `startCamera({ cameraId, resolution, track })` | Publishes the camera. Pass `track` to use your own live video track (SDK clones it). |
223
229
  | `replaceCameraTrack(track)` | Hot-swaps the live camera producer with a new live video track (SDK clones it). No unpublish. Camera must already be started. |
@@ -234,7 +240,19 @@ await client.end(); // combines every segment into one file
234
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. |
235
241
  | `stopRecording()` | Pauses recording without saving. Call `startRecording()` again to continue; `end()` still combines all segments into one file. |
236
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. |
237
- | `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
+ | `setRecordingFps(fps)` / `getRecordingFps()` | Recording frame rate (1–60). Applies to the next `startRecording()`; a running segment keeps its rate. |
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
+ | `stopRtmp()` | Ends the live stream on every platform. Destinations stay saved so the host can Go Live again. |
247
+ | `addRtmpDestinations(list)` | Adds `[{ platform, streamKey, serverUrl?, label? }]`. `platform` is `youtube`, `twitch`, `facebook`, or `custom` (custom needs `serverUrl`). Works before or during a live stream. |
248
+ | `setRtmpDestination(id, enabled)` | Turns one destination on or off. While live, only that platform connects or disconnects. |
249
+ | `removeRtmpDestination(id)` | Deletes a destination. |
250
+ | `getRtmpStatus()` | Returns the current live state (see `onRtmpStatus`). |
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 }`. |
254
+ | `canLiveStream()` | `true` when this browser can compose and encode H264. Hide or disable Go Live when this is `false`. |
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. |
238
256
  | `getPeerId()` | Socket peer id for this browser after `connect()`. |
239
257
  | `getPublishLimits()` | Current `{ cameraBps, screenBps }` used for outgoing video encode caps. |
240
258
  | `getUserList()` / `updateSelf(...)` / `stageAction(...)` | Optional portal roster helpers used by the sample meet UI. Skip these if your app already manages users and stage on its own. |
@@ -255,6 +273,7 @@ Pass these to `createClient`.
255
273
  | `onError(error)` | A call failed. `error.message` is the reason. The same call also throws, so `await` can use `try/catch`. |
256
274
  | `onRecording(state)` | `armed` briefly while capture is preparing. `recording` while chunks are uploading. `stopped` after `stopRecording()`, handoff, or `end()`. |
257
275
  | `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
+ | `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`. |
258
277
  | `onStageChanged(people)` | Optional. Fires when the recording stage list changes after `setRecordingStage` (or sample roster updates). |
259
278
  | `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. |
260
279
 
@@ -391,23 +410,48 @@ Use `setRecordingStage([{ id, name, local? }, ...])` so avatar tiles and name pi
391
410
 
392
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:
393
412
 
413
+ ### Stage look (background + avatars)
414
+
394
415
  ```js
416
+ import { createClient, avatarBackgroundFor, gradientToCss } from "mediascale-sdk";
417
+
395
418
  const client = createClient({
396
419
  endpoint,
397
420
  sessionId,
398
421
  token,
399
- recording: true,
400
- // Base color for the radial + wave canvas background.
401
- // Default: "#2563eb"
402
- 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
+ ],
403
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));
404
437
  ```
405
438
 
406
- | Option | Default | Meaning |
407
- | --- | --- | --- |
408
- | `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`):
409
440
 
410
- 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.
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 |
447
+
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).
411
455
 
412
456
  ### Background-safe compositing
413
457
 
@@ -426,6 +470,233 @@ window.addEventListener("mediascale:recording-error", (event) => {
426
470
  });
427
471
  ```
428
472
 
473
+ ## Live streaming (RTMP)
474
+
475
+ A host streams the meeting to several platforms at once (YouTube, Twitch, Facebook, or any RTMP/RTMPS ingest). The live picture uses the **same stage layout** as recording (screen + up to six cameras, name pills, brand background, every mic mixed). Keep calling `setRecordingStage([...])` whenever your stage changes — that list drives both recording and the live compositor.
476
+
477
+ ### What webinar apps must do
478
+
479
+ | Step | Who | What |
480
+ | --- | --- | --- |
481
+ | 1. Store destinations | Your backend **or** Stream Control | Platform + server URL + stream key per destination, keyed by the same `sessionId` the host will join |
482
+ | 2. Mint host token | Your `/api/token` | Include `rtmp: true` when destinations were prepared ahead of time (auto Go Live). Omit it when the host will configure Live only inside the room |
483
+ | 3. Create the client | Browser | `createClient({ …, onRtmpStatus })` then `connect()` / `subscribe()` |
484
+ | 4. Drive stage layout | Browser | `setRecordingStage` so avatars / names match the live UI |
485
+ | 5. Live UI | Host / co-host | Show a Live control; call `startRtmp` / `stopRtmp`; render destinations from `onRtmpStatus` |
486
+
487
+ Audience tokens never get `rtmp`. Stream keys never go in the JWT — only in destination storage / `addRtmpDestinations`.
488
+
489
+ ### Path A — Stream Control webinar create
490
+
491
+ Stream Control → Webinar → **Enable live streaming (RTMP)** saves destinations (keys encrypted) and puts `rtmp: true` on the host link.
492
+
493
+ 1. Host opens the meet URL.
494
+ 2. After `connect()`, the SDK **auto Go Live** when enabled destinations exist for that `sessionId`.
495
+ 3. The Live panel lists those destinations (`platform`, `serverUrl` / `host`, `keyHint`). Keys are not re-entered.
496
+ 4. Host can **End live stream**, change destinations, or Go Live again from the same panel.
497
+
498
+ ### Path B — Your own webinar product (SDK only)
499
+
500
+ Use the same `sessionId` everywhere (token, destinations, `createClient`).
501
+
502
+ **1. Token** — see the route above. Example body from your create-webinar API:
503
+
504
+ ```js
505
+ await fetch("/api/token", {
506
+ method: "POST",
507
+ headers: { "Content-Type": "application/json" },
508
+ body: JSON.stringify({
509
+ sessionId, // same id you stored destinations under
510
+ role: "host",
511
+ name: hostDisplayName,
512
+ recording: true, // optional
513
+ rtmp: true, // auto Go Live when destinations already exist
514
+ }),
515
+ });
516
+ ```
517
+
518
+ **2. Destinations before join** (optional)
519
+
520
+ - Stream Control meet session API stores them when you use that product, **or**
521
+ - Host adds them in-meeting with `addRtmpDestinations` / `startRtmp({ destinations })` (Path C).
522
+
523
+ If you store destinations yourself via the control plane, use the same `sessionId` and never return full stream keys to the browser (UI only shows `keyHint`).
524
+
525
+ **3. Client + Live UI**
526
+
527
+ ```js
528
+ const client = createClient({
529
+ endpoint, // e.g. https://stream.example.com or http://localhost:8080
530
+ sessionId,
531
+ token, // host JWT
532
+ rtmpResolution: "1080p", // 480p | 540p | 720p | 1080p (default 1080p)
533
+ rtmpFps: 30, // live canvas / H264 (default 30)
534
+ rtmpBitrate: 2_500_000, // bps, max 2 500 000 (2500 kbps)
535
+ rtmpKeyframeInterval: 2, // seconds (default 2)
536
+ recordingFps: 15, // independent of rtmpFps
537
+ onRtmpStatus: (status) => {
538
+ // status.enabled — show Live for managers once the room allows it
539
+ // status.live — true when platforms are receiving
540
+ // status.state — idle | starting | connecting | waiting-media | live | reconnecting | failed | error
541
+ // status.destinations — host/co-host only: id, platform, label, host, serverUrl, keyHint, enabled, state, kbps, error
542
+ setLive(status);
543
+ },
544
+ onError: (error) => showToast(error.message),
545
+ });
546
+
547
+ await client.connect();
548
+ await client.subscribe();
549
+
550
+ // Keep live + recording tiles aligned with your stage UI
551
+ client.setRecordingStage([
552
+ { id: hostPeerId, name: "Alex", local: true },
553
+ { id: speakerPeerId, name: "Rakesh", local: false },
554
+ ]);
555
+ ```
556
+
557
+ Wire your Live button like the sample (`sample/app/live-panel.js`):
558
+
559
+ ```js
560
+ if (!client.canLiveStream()) {
561
+ // Hide Go Live — need Chrome, Edge, or Safari (H264)
562
+ }
563
+
564
+ // Go Live (no-op destinations if already saved for this session)
565
+ await client.startRtmp();
566
+
567
+ // Or add / replace destinations in one call
568
+ await client.startRtmp({
569
+ destinations: [
570
+ { platform: "youtube", streamKey: "xxxx-xxxx-xxxx-xxxx" },
571
+ { platform: "twitch", streamKey: "live_123_abc" },
572
+ { platform: "custom", serverUrl: "rtmp://ingest.example/live", streamKey: "my-key", label: "CDN" },
573
+ ],
574
+ });
575
+
576
+ await client.addRtmpDestinations([
577
+ { platform: "facebook", streamKey: "FB-123?s_bl=1&a=b" },
578
+ ]);
579
+
580
+ await client.setRtmpDestination(destinationId, false); // one platform off; others keep going
581
+ await client.removeRtmpDestination(destinationId);
582
+
583
+ await client.stopRtmp(); // end broadcast; destinations remain for a later Go Live
584
+ ```
585
+
586
+ ### Path C — No RTMP at create time
587
+
588
+ Omit `rtmp` on the token (or set `false`). The host still gets a Live control after join:
589
+
590
+ 1. Open Live → add destinations (`addRtmpDestinations`) → **Go Live** (`startRtmp()`).
591
+ 2. Or call `startRtmp({ destinations: [...] })` once.
592
+
593
+ ### Destination object
594
+
595
+ | Field | Required | Notes |
596
+ | --- | --- | --- |
597
+ | `platform` | yes | `youtube`, `twitch`, `facebook`, or `custom` |
598
+ | `streamKey` | yes when adding | Never store this in the JWT or client logs |
599
+ | `serverUrl` | custom yes; others optional | Presets: YouTube `rtmp://a.rtmp.youtube.com/live2`, Twitch `rtmp://live.twitch.tv/app`, Facebook `rtmps://live-api-s.facebook.com:443/rtmp/` |
600
+ | `label` | no | Defaults to the platform name |
601
+
602
+ Presets fill `serverUrl` when omitted. Max destinations per meeting defaults to **5** (`RTMP_MAX_DESTINATIONS`).
603
+
604
+ ### Auto-start rules
605
+
606
+ | Host token | Destinations for `sessionId` | On `connect()` |
607
+ | --- | --- | --- |
608
+ | `rtmp: true` | ≥1 enabled | SDK calls `startRtmp()` automatically |
609
+ | `rtmp: true` | none | Idle — host adds destinations then Go Live |
610
+ | `rtmp` omitted / false | any | Idle — host uses Live UI manually |
611
+
612
+ Auto-start does **not** block join. Failures go to `onError` / `onRtmpStatus` (`state: "error"`).
613
+
614
+ ### `onRtmpStatus` shape
615
+
616
+ ```js
617
+ {
618
+ enabled: true,
619
+ state: "live", // see table in Callbacks
620
+ live: true,
621
+ startedAt: "2026-…",
622
+ composing: true, // this browser is publishing hidden rtmp-* tracks
623
+ fps: 30, // host / co-host
624
+ error: null,
625
+ destinations: [ // host / co-host only
626
+ {
627
+ id: "…",
628
+ platform: "youtube",
629
+ label: "YouTube",
630
+ host: "a.rtmp.youtube.com",
631
+ serverUrl: "rtmp://a.rtmp.youtube.com/live2",
632
+ keyHint: "••••xxxx",
633
+ enabled: true,
634
+ state: "live", // idle | pending | connecting | live | failed | off | …
635
+ kbps: 2400,
636
+ error: null,
637
+ },
638
+ ],
639
+ }
640
+ ```
641
+
642
+ Suggested UI: Live toolbar button `on` when `state` is not `idle` / `error`; panel lists `destinations` (prefilled from create — no need to retype keys); primary action is Go Live / End live stream.
643
+
644
+ ### How the media flows
645
+
646
+ ```
647
+ Host browser
648
+ stage canvas @ rtmpFps ─► H264 (hidden track "rtmp-video") ─┐
649
+ mix of every mic ─► Opus (hidden track "rtmp-audio") ─┴─► origin ─RTP─► RTMP server
650
+ RTMP server (one VM runs many meetings)
651
+ H264 ─► passed through (no decode / encode)
652
+ Opus ─► AAC (once per meeting) ─► FLV ─► YouTube / Twitch / Facebook / custom …
653
+ ```
654
+
655
+ - Hidden tracks are charged on the **origin** only and are never sent to edges or shown to participants.
656
+ - Browser must encode **H264** (Chrome, Edge, Safari). Check `canLiveStream()` before enabling Go Live.
657
+ - Host uploads about `rtmpBitrate` (default and max 2.5 Mbps) more while live.
658
+ - If the presenter leaves, another publisher takes over composing (same idea as recording). If nobody can, the stream stops.
659
+ - Each destination reconnects with its own backoff; one bad key does not stop the others.
660
+ - Platform side (e.g. YouTube) must already be **Go Live** / accepting the key, or the destination stays connecting / failed while Mediascale is pushing.
661
+
662
+ ### Frame rates
663
+
664
+ | Option | Default | Used for |
665
+ | --- | --- | --- |
666
+ | `recordingFps` | `15` | MediaRecorder recording canvas |
667
+ | `rtmpFps` | `30` | Live stream canvas and H264 encode |
668
+
669
+ Separate canvases — each rate is independent. Live compositor window events: `mediascale:live-mode` / `mediascale:live-error`.
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
+
429
700
  ## Run the sample
430
701
 
431
702
  ```bash
@@ -438,4 +709,4 @@ Open http://localhost:3200. The page asks your Next.js server for a token, then
438
709
 
439
710
  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`.
440
711
 
441
- 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` set from the Enable recording toggle.
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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mediascale-sdk",
3
- "version": "1.0.12",
4
- "description": "Mediascale React/browser SDK for live sessions, WebRTC publish/subscribe, and recording",
3
+ "version": "1.0.15",
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",
7
7
  "exports": {