mediascale-sdk 1.0.15 → 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, 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). |
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). |
@@ -252,6 +255,8 @@ await client.end(); // combines every segment into one file
252
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. |
253
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 }`. |
254
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). |
255
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. |
256
261
  | `getPeerId()` | Socket peer id for this browser after `connect()`. |
257
262
  | `getPublishLimits()` | Current `{ cameraBps, screenBps }` used for outgoing video encode caps. |
@@ -274,6 +279,7 @@ Pass these to `createClient`.
274
279
  | `onRecording(state)` | `armed` briefly while capture is preparing. `recording` while chunks are uploading. `stopped` after `stopRecording()`, handoff, or `end()`. |
275
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. |
276
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. |
277
283
  | `onStageChanged(people)` | Optional. Fires when the recording stage list changes after `setRecordingStage` (or sample roster updates). |
278
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. |
279
285
 
@@ -486,6 +492,26 @@ A host streams the meeting to several platforms at once (YouTube, Twitch, Facebo
486
492
 
487
493
  Audience tokens never get `rtmp`. Stream keys never go in the JWT — only in destination storage / `addRtmpDestinations`.
488
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
+
489
515
  ### Path A — Stream Control webinar create
490
516
 
491
517
  Stream Control → Webinar → **Enable live streaming (RTMP)** saves destinations (keys encrypted) and puts `rtmp: true` on the host link.
@@ -511,6 +537,7 @@ await fetch("/api/token", {
511
537
  name: hostDisplayName,
512
538
  recording: true, // optional
513
539
  rtmp: true, // auto Go Live when destinations already exist
540
+ startMode: "rtmp", // optional: live stream first, WebRTC video only once someone joins
514
541
  }),
515
542
  });
516
543
  ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mediascale-sdk",
3
- "version": "1.0.15",
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",
package/src/client.js CHANGED
@@ -27,6 +27,28 @@ const SIZES = {
27
27
  /** Built-in sources that have dedicated start/stop helpers. */
28
28
  const RESERVED_SOURCES = new Set(["webcam", "mic", "screen", "screen-audio"]);
29
29
 
30
+ /**
31
+ * WebRTC video codec preference. VP8 is the default; the next codec in the list is used
32
+ * only when the browser cannot send the previous one (or the server does not offer it).
33
+ * Override with createClient({ videoCodec: "h264" }) or an ordered list. The live (RTMP)
34
+ * stage is always H264 and is not affected by this setting.
35
+ */
36
+ export const DEFAULT_VIDEO_CODECS = ["vp8", "h264", "vp9", "av1"];
37
+
38
+ export function normalizeVideoCodecs(raw) {
39
+ const wanted = (Array.isArray(raw) ? raw : raw == null ? [] : [raw])
40
+ .map((item) => String(item || "").trim().toLowerCase().replace(/^video\//, ""))
41
+ .filter(Boolean);
42
+ const out = [];
43
+ for (const name of [...wanted, ...DEFAULT_VIDEO_CODECS]) {
44
+ if (!out.includes(name)) out.push(name);
45
+ }
46
+ return out;
47
+ }
48
+
49
+ /** How long the live mix must be unnecessary before the host goes back to one Opus stream. */
50
+ const LIVE_MIX_RELEASE_MS = 10_000;
51
+
30
52
  /** Default SDK publish caps (bps). Portal join / createClient can override. */
31
53
  const DEFAULT_CAMERA_MAX_BITRATE_BPS = 1_000_000;
32
54
  const DEFAULT_SCREEN_MAX_BITRATE_BPS = 1_500_000;
@@ -163,6 +185,9 @@ export function createClient(options = {}) {
163
185
  const onUserBlocked = options.onUserBlocked || (() => {});
164
186
  const onStageChanged = options.onStageChanged || (() => {});
165
187
  const onRtmpStatus = options.onRtmpStatus || (() => {});
188
+ const onMediaDemand = options.onMediaDemand || (() => {});
189
+ /** Ordered WebRTC video codec preference (VP8 first unless overridden). */
190
+ const videoCodecs = normalizeVideoCodecs(options.videoCodec ?? options.videoCodecs);
166
191
 
167
192
  if (!sessionId) throw new Error("sessionId is required");
168
193
  if (!token) throw new Error("token is required");
@@ -230,10 +255,30 @@ export function createClient(options = {}) {
230
255
  let settleReady = null;
231
256
  /** Session-scoped portal peer (query param). Avoids browser-wide cookie collisions. */
232
257
  let portalPeer = readStoredPortalPeer(sessionId);
233
- /** RTMP: stage compositor + hidden H264/Opus producers on the origin. */
258
+ /** RTMP: stage compositor + hidden H264 producer (+ live audio) on the origin. */
234
259
  let live = null;
235
- let liveProducers = [];
260
+ /** Hidden `rtmp-video` (H264 stage). */
261
+ let liveVideo = null;
262
+ /**
263
+ * RTMP audio. `shared: true` → it is my `mic` producer (one Opus stream for WebRTC + RTMP).
264
+ * `shared: false` → a hidden producer carrying the stage mix (co-host mics, screen audio…).
265
+ * The same producer moves between the two (portal re-labels it), so RTMP is never re-wired.
266
+ */
267
+ let liveAudio = null;
268
+ /** Serializes everything that touches the mic producer or the live audio. */
269
+ let audioQueue = Promise.resolve();
270
+ let liveAudioCheckTimer = null;
271
+ let liveMixIdleSince = 0;
236
272
  let startingLive = null;
273
+ /**
274
+ * WebRTC demand from the portal. Live-stream-first rooms start with `false`: camera /
275
+ * screen / custom tracks stay local (the RTMP stage still shows them) until somebody
276
+ * joins to watch over WebRTC. Every other room is always `true` (publish immediately).
277
+ */
278
+ let webrtcDemand = true;
279
+ let demandQueue = Promise.resolve();
280
+ /** Portal capabilities from the join ack (older portals send none). */
281
+ let portalFeatures = {};
237
282
  let rtmpState = { enabled: rtmpEnabled, state: "idle", live: false, destinations: [] };
238
283
 
239
284
  function userOnStage(user) {
@@ -350,6 +395,7 @@ export function createClient(options = {}) {
350
395
  const people = stagePeopleForRecording();
351
396
  recorder?.sync(tracks, people);
352
397
  live?.sync(tracks, people);
398
+ scheduleLiveAudioCheck();
353
399
  }
354
400
 
355
401
  /**
@@ -459,17 +505,42 @@ export function createClient(options = {}) {
459
505
  if (entry.original !== track) entry.original.addEventListener("ended", entry.onEnded);
460
506
  }
461
507
 
508
+ /**
509
+ * Local entries are keyed by a stable id: the producer id when published right away
510
+ * (unchanged behavior), or a `local-…` id while the track is kept local (no WebRTC demand).
511
+ * `entry.producer` may be null or change (mic shared with RTMP) — never key by it.
512
+ */
462
513
  async function unpublish(producerId) {
463
514
  const entry = locals.get(producerId);
464
515
  if (!entry) return;
516
+ if (entry.source === "mic") return withAudioLock(() => unpublishNow(producerId));
517
+ return unpublishNow(producerId);
518
+ }
519
+
520
+ async function unpublishNow(producerId) {
521
+ const entry = locals.get(producerId);
522
+ if (!entry) return;
523
+ // My mic is also the RTMP audio: hand that producer to the live mix instead of closing
524
+ // it, so the platforms keep their audio input.
525
+ if (liveAudio?.shared && entry.producer && entry.producer === liveAudio.producer) {
526
+ try {
527
+ await splitLiveAudio({ keepMic: false });
528
+ } catch (error) {
529
+ onError(error);
530
+ liveAudio = null;
531
+ }
532
+ }
465
533
  locals.delete(producerId);
466
534
  tiles.delete(producerId);
467
535
  detachEnded(entry);
468
536
  entry.track.stop();
469
- entry.producer.close();
537
+ const producer = entry.producer;
538
+ entry.producer = null;
539
+ producer?.close();
470
540
  syncRecording();
471
541
  onTrackEnded({ producerId, local: true, source: entry.source });
472
- if (socket?.connected) await emit(socket, "closeProducer", { producerId }).catch(() => {});
542
+ if (producer && socket?.connected) await emit(socket, "closeProducer", { producerId: producer.id }).catch(() => {});
543
+ if (entry.source === "mic" && live && !liveAudio) await repairLiveAudio();
473
544
  }
474
545
 
475
546
  function maxBitrateFor(source, kind) {
@@ -571,27 +642,67 @@ export function createClient(options = {}) {
571
642
  return /out of credits|transport not found|ORIGIN_FULL|Origin is full/i.test(msg);
572
643
  }
573
644
 
645
+ /** First codec in the preference list that both this browser and the server can use. */
646
+ function pickVideoCodec() {
647
+ const offered = device?.rtpCapabilities?.codecs || [];
648
+ const sendable = typeof RTCRtpSender !== "undefined" && RTCRtpSender.getCapabilities
649
+ ? RTCRtpSender.getCapabilities("video")?.codecs || null
650
+ : null;
651
+ for (const name of videoCodecs) {
652
+ const mime = `video/${name}`;
653
+ if (sendable && !sendable.some((codec) => String(codec.mimeType).toLowerCase() === mime)) continue;
654
+ const codec = offered.find((item) => item.kind === "video" && String(item.mimeType).toLowerCase() === mime);
655
+ if (codec) return codec;
656
+ }
657
+ return undefined; // let mediasoup pick, as before
658
+ }
659
+
660
+ /** Send one local track to the origin (WebRTC). */
661
+ async function sendProduce(source, track) {
662
+ const options = { track, stopTracks: false, appData: { source } };
663
+ const maxBitrate = maxBitrateFor(source, track.kind);
664
+ if (maxBitrate > 0) {
665
+ options.encodings = [{ maxBitrate }];
666
+ // Chrome start bitrate is kbps; keep a modest ramp under the cap.
667
+ options.codecOptions = {
668
+ videoGoogleStartBitrate: Math.max(100, Math.min(1000, Math.round(maxBitrate / 2000))),
669
+ };
670
+ }
671
+ if (track.kind === "video") {
672
+ const codec = pickVideoCodec();
673
+ if (codec) options.codec = codec;
674
+ }
675
+ if (!sendTransport) throw new Error("The session is not ready");
676
+ try {
677
+ return await sendTransport.produce(options);
678
+ } catch (error) {
679
+ if (!shouldRecreateSendTransport(error)) throw error;
680
+ await recreateSendTransport();
681
+ return sendTransport.produce(options);
682
+ }
683
+ }
684
+
685
+ /** The mic is always published (it is also the RTMP audio); everything else follows demand. */
686
+ function followsDemand(source) {
687
+ return source !== "mic";
688
+ }
689
+
690
+ function localKey() {
691
+ const random = typeof crypto !== "undefined" && crypto.randomUUID
692
+ ? crypto.randomUUID()
693
+ : Math.random().toString(36).slice(2);
694
+ return `local-${random}`;
695
+ }
696
+
574
697
  // Camera inputs use an SDK-owned clone. Custom inputs keep upstream direct ownership.
575
698
  async function produce(source, track, original = track) {
576
- let producer;
699
+ let producer = null;
700
+ const deferred = followsDemand(source) && !webrtcDemand;
577
701
  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
702
  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
- }
703
+ // No WebRTC viewer yet (live-stream-first room): keep the track local. The preview
704
+ // and the RTMP stage use it; it is published the moment demand turns on.
705
+ if (!deferred) producer = await sendProduce(source, track);
595
706
  if (closed) throw new Error("The session has ended");
596
707
  if (track.readyState === "ended" || original.readyState === "ended") throw new Error("The source track ended");
597
708
  } catch (error) {
@@ -599,11 +710,12 @@ export function createClient(options = {}) {
599
710
  track.stop();
600
711
  throw error;
601
712
  }
713
+ const key = producer ? producer.id : localKey();
602
714
  const stream = new MediaStream([track]);
603
715
  const entry = { producer, track, original, source };
604
- locals.set(producer.id, entry);
605
- tiles.set(producer.id, {
606
- producerId: producer.id,
716
+ locals.set(key, entry);
717
+ tiles.set(key, {
718
+ producerId: key,
607
719
  publisherId: "local",
608
720
  source,
609
721
  kind: track.kind,
@@ -611,9 +723,11 @@ export function createClient(options = {}) {
611
723
  stream,
612
724
  local: true,
613
725
  });
614
- attachEnded(producer.id, entry);
726
+ attachEnded(key, entry);
615
727
  syncRecording();
616
- return { producerId: producer.id, stream, source };
728
+ // Demand may have turned on while this track was being prepared.
729
+ if (deferred && webrtcDemand) queueDemandReconcile();
730
+ return { producerId: key, stream, source };
617
731
  }
618
732
 
619
733
  async function ensurePortalAffinity({ force = false } = {}) {
@@ -688,6 +802,10 @@ export function createClient(options = {}) {
688
802
  socket.on("rtmpStopped", () => {
689
803
  stopLiveOutput().catch(() => {});
690
804
  });
805
+ // Live-stream-first rooms: publish camera / screen only while someone watches over WebRTC.
806
+ socket.on("mediaDemand", (payload = {}) => {
807
+ if (!closed) setWebrtcDemand(payload.webrtc !== false);
808
+ });
691
809
  socket.on("activeSpeaker", (payload = {}) => {
692
810
  if (closed) return;
693
811
  const peerId = payload.peerId || null;
@@ -795,6 +913,10 @@ export function createClient(options = {}) {
795
913
  ...clientHints(),
796
914
  });
797
915
  selfPeerId = joined.peerId || null;
916
+ portalFeatures = joined.features && typeof joined.features === "object" ? joined.features : {};
917
+ // Older portals send no mediaDemand: always publish, exactly as before.
918
+ webrtcDemand = joined.mediaDemand?.webrtc !== false;
919
+ onMediaDemand({ webrtc: webrtcDemand });
798
920
  if (joined.rtmp) setRtmpState(joined.rtmp);
799
921
  iceServers = iceOverride || joined.iceServers || [];
800
922
  applyPublishLimitsFromJoin(joined.publishLimits);
@@ -965,13 +1087,19 @@ export function createClient(options = {}) {
965
1087
 
966
1088
  async function replaceLocalTrack(source, track, kind) {
967
1089
  requireLiveTrack(track, kind);
1090
+ if (source === "mic") return withAudioLock(() => replaceLocalTrackNow(source, track, kind));
1091
+ return replaceLocalTrackNow(source, track, kind);
1092
+ }
1093
+
1094
+ async function replaceLocalTrackNow(source, track, kind) {
968
1095
  if (closed) throw new Error("The session has ended");
969
1096
  const current = [...locals].find(([, entry]) => entry.source === source);
970
1097
  if (!current) throw new Error(source === "webcam" ? "The camera is not started" : "The microphone is not started");
971
1098
  const [producerId, entry] = current;
972
1099
  const replacement = track.clone();
973
1100
  try {
974
- await entry.producer.replaceTrack({ track: replacement });
1101
+ // A track kept local (no WebRTC demand) has no producer yet — just swap it.
1102
+ if (entry.producer) await entry.producer.replaceTrack({ track: replacement });
975
1103
  if (closed || locals.get(producerId) !== entry) {
976
1104
  throw new Error(source === "webcam" ? "The camera is not started" : "The microphone is not started");
977
1105
  }
@@ -1261,6 +1389,235 @@ export function createClient(options = {}) {
1261
1389
  return LiveCompositor.supported() && Boolean(h264Codec());
1262
1390
  }
1263
1391
 
1392
+ // ---- WebRTC demand (live-stream-first rooms) --------------------------------
1393
+
1394
+ function setWebrtcDemand(next) {
1395
+ const value = Boolean(next);
1396
+ if (value === webrtcDemand) return;
1397
+ webrtcDemand = value;
1398
+ onMediaDemand({ webrtc: value });
1399
+ queueDemandReconcile();
1400
+ }
1401
+
1402
+ function queueDemandReconcile() {
1403
+ const run = demandQueue.then(reconcileDemand, reconcileDemand);
1404
+ demandQueue = run.catch((error) => onError(error));
1405
+ return run;
1406
+ }
1407
+
1408
+ /** Publish (or stop publishing) every local non-mic track to match `webrtcDemand`. */
1409
+ async function reconcileDemand() {
1410
+ for (const [key, entry] of [...locals]) {
1411
+ if (closed || !sendTransport) return;
1412
+ if (!followsDemand(entry.source)) continue;
1413
+ if (webrtcDemand && !entry.producer) {
1414
+ const track = entry.track;
1415
+ let producer = null;
1416
+ try {
1417
+ producer = await sendProduce(entry.source, track);
1418
+ } catch (error) {
1419
+ onError(error);
1420
+ continue;
1421
+ }
1422
+ if (closed || locals.get(key) !== entry || !webrtcDemand || entry.producer) {
1423
+ producer.close();
1424
+ if (socket?.connected) await emit(socket, "closeProducer", { producerId: producer.id }).catch(() => {});
1425
+ continue;
1426
+ }
1427
+ entry.producer = producer;
1428
+ // The track was swapped (device change) while publishing.
1429
+ if (entry.track !== track) await producer.replaceTrack({ track: entry.track }).catch((error) => onError(error));
1430
+ } else if (!webrtcDemand && entry.producer) {
1431
+ const producer = entry.producer;
1432
+ entry.producer = null;
1433
+ producer.close();
1434
+ if (socket?.connected) await emit(socket, "closeProducer", { producerId: producer.id }).catch(() => {});
1435
+ }
1436
+ }
1437
+ }
1438
+
1439
+ // ---- Live (RTMP) audio: one Opus stream unless a mix is needed -----------------
1440
+
1441
+ function withAudioLock(job) {
1442
+ const run = audioQueue.then(job, job);
1443
+ audioQueue = run.then(() => {}, () => {});
1444
+ return run;
1445
+ }
1446
+
1447
+ function micEntry() {
1448
+ for (const entry of locals.values()) {
1449
+ if (entry.source === "mic" && entry.track.kind === "audio") return entry;
1450
+ }
1451
+ return null;
1452
+ }
1453
+
1454
+ /**
1455
+ * The RTMP audio needs the compositor mix when anything besides my own mic is audible
1456
+ * on the stage (co-host / guest mics, screen or tab audio) or when my mic is off.
1457
+ * Mute state does not matter, so muting never flips the audio path.
1458
+ */
1459
+ function needsLiveMix() {
1460
+ const mic = micEntry();
1461
+ if (!mic?.producer) return true;
1462
+ for (const tile of tiles.values()) {
1463
+ if (tile.kind !== "audio") continue;
1464
+ if (tile.local && tile.source === "mic") continue;
1465
+ return true;
1466
+ }
1467
+ return false;
1468
+ }
1469
+
1470
+ function canShareMic() {
1471
+ return portalFeatures.rtmpSharedAudio === true;
1472
+ }
1473
+
1474
+ /** On Go Live: use my mic producer directly when nothing needs mixing, else a hidden mix. */
1475
+ async function setupLiveAudio(compositor) {
1476
+ const mic = micEntry();
1477
+ if (canShareMic() && mic?.producer && !needsLiveMix()) {
1478
+ try {
1479
+ await emit(socket, "rtmpAudio", { action: "shared", producerId: mic.producer.id });
1480
+ liveAudio = { producer: mic.producer, shared: true };
1481
+ liveMixIdleSince = 0;
1482
+ return;
1483
+ } catch (error) {
1484
+ console.warn("[mediascale] live audio: mic sharing refused, using the mix", error?.message || error);
1485
+ }
1486
+ }
1487
+ const producer = await produceHidden("rtmp-audio", compositor.audioTrack);
1488
+ liveAudio = { producer, shared: false };
1489
+ liveMixIdleSince = 0;
1490
+ }
1491
+
1492
+ async function teardownLiveAudio() {
1493
+ const current = liveAudio;
1494
+ liveAudio = null;
1495
+ liveMixIdleSince = 0;
1496
+ if (liveAudioCheckTimer) {
1497
+ clearTimeout(liveAudioCheckTimer);
1498
+ liveAudioCheckTimer = null;
1499
+ }
1500
+ // Shared: it is my mic — it keeps serving WebRTC; the portal already dropped it from RTMP.
1501
+ if (!current || current.shared) return;
1502
+ try { current.producer.close(); } catch { /* ignore */ }
1503
+ if (socket?.connected) await emit(socket, "closeProducer", { producerId: current.producer.id }).catch(() => {});
1504
+ }
1505
+
1506
+ /** RTMP lost its audio producer (e.g. mic sharing failed): publish a hidden mix. */
1507
+ async function repairLiveAudio() {
1508
+ if (!live || liveAudio || closed) return;
1509
+ try {
1510
+ const producer = await produceHidden("rtmp-audio", live.audioTrack);
1511
+ liveAudio = { producer, shared: false };
1512
+ } catch (error) {
1513
+ onError(error);
1514
+ }
1515
+ }
1516
+
1517
+ /**
1518
+ * shared → mix: the producer RTMP uses switches to the stage mix (portal hides it from
1519
+ * WebRTC), and my plain mic goes out as a new producer for WebRTC viewers.
1520
+ */
1521
+ async function splitLiveAudio({ keepMic = true } = {}) {
1522
+ const current = liveAudio;
1523
+ const compositor = live;
1524
+ if (!current?.shared || !compositor) return;
1525
+ const producer = current.producer;
1526
+ await emit(socket, "rtmpAudio", { action: "split", producerId: producer.id });
1527
+ try {
1528
+ await producer.replaceTrack({ track: compositor.audioTrack });
1529
+ } catch (error) {
1530
+ onError(error);
1531
+ }
1532
+ liveAudio = { producer, shared: false };
1533
+ liveMixIdleSince = 0;
1534
+ const mic = micEntry();
1535
+ if (mic && mic.producer === producer) {
1536
+ mic.producer = null;
1537
+ if (keepMic) {
1538
+ try {
1539
+ mic.producer = await sendProduce("mic", mic.track);
1540
+ } catch (error) {
1541
+ onError(error);
1542
+ }
1543
+ }
1544
+ }
1545
+ }
1546
+
1547
+ /**
1548
+ * mix → shared: the RTMP producer carries my plain mic again and becomes my visible mic;
1549
+ * the separate WebRTC mic closes first (a short gap beats viewers hearing me twice).
1550
+ */
1551
+ async function mergeLiveAudio() {
1552
+ const current = liveAudio;
1553
+ const mic = micEntry();
1554
+ if (!current || current.shared || !mic?.producer || mic.producer === current.producer) return;
1555
+ const producer = current.producer;
1556
+ const webrtcMic = mic.producer;
1557
+ await producer.replaceTrack({ track: mic.track });
1558
+ mic.producer = null;
1559
+ webrtcMic.close();
1560
+ if (socket?.connected) await emit(socket, "closeProducer", { producerId: webrtcMic.id }).catch(() => {});
1561
+ try {
1562
+ await emit(socket, "rtmpAudio", { action: "merge", producerId: producer.id });
1563
+ } catch (error) {
1564
+ // Stay on the mix and bring the WebRTC mic back.
1565
+ if (live) await producer.replaceTrack({ track: live.audioTrack }).catch(() => {});
1566
+ try {
1567
+ if (micEntry() === mic && !mic.producer) mic.producer = await sendProduce("mic", mic.track);
1568
+ } catch (produceError) {
1569
+ onError(produceError);
1570
+ }
1571
+ throw error;
1572
+ }
1573
+ mic.producer = producer;
1574
+ liveAudio = { producer, shared: true };
1575
+ liveMixIdleSince = 0;
1576
+ }
1577
+
1578
+ async function reconcileLiveAudio() {
1579
+ if (closed || !live || !liveAudio || !canShareMic() || !socket?.connected) return;
1580
+ const mic = micEntry();
1581
+ // A WebRTC mic that failed to publish during a split: try again.
1582
+ if (mic && !mic.producer && sendTransport) {
1583
+ try {
1584
+ mic.producer = await sendProduce("mic", mic.track);
1585
+ } catch (error) {
1586
+ onError(error);
1587
+ }
1588
+ }
1589
+ const need = needsLiveMix();
1590
+ if (liveAudio.shared) {
1591
+ liveMixIdleSince = 0;
1592
+ if (need) await splitLiveAudio();
1593
+ return;
1594
+ }
1595
+ if (need) {
1596
+ liveMixIdleSince = 0;
1597
+ return;
1598
+ }
1599
+ // Go back to one Opus stream only after the mix has been unnecessary for a while,
1600
+ // so a guest briefly joining / leaving the stage does not flip the audio back and forth.
1601
+ const now = Date.now();
1602
+ if (!liveMixIdleSince) liveMixIdleSince = now;
1603
+ const left = LIVE_MIX_RELEASE_MS - (now - liveMixIdleSince);
1604
+ if (left > 0) {
1605
+ scheduleLiveAudioCheck(left + 50);
1606
+ return;
1607
+ }
1608
+ liveMixIdleSince = 0;
1609
+ await mergeLiveAudio();
1610
+ }
1611
+
1612
+ function scheduleLiveAudioCheck(delayMs = 300) {
1613
+ if (closed || !live || !liveAudio || !canShareMic()) return;
1614
+ if (liveAudioCheckTimer) clearTimeout(liveAudioCheckTimer);
1615
+ liveAudioCheckTimer = setTimeout(() => {
1616
+ liveAudioCheckTimer = null;
1617
+ withAudioLock(reconcileLiveAudio).catch((error) => onError(error));
1618
+ }, delayMs);
1619
+ }
1620
+
1264
1621
  async function produceHidden(source, track, extra = {}) {
1265
1622
  const options = { track, stopTracks: false, appData: { source }, ...extra };
1266
1623
  try {
@@ -1297,12 +1654,13 @@ export function createClient(options = {}) {
1297
1654
  }
1298
1655
 
1299
1656
  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(() => {});
1657
+ const video = liveVideo;
1658
+ liveVideo = null;
1659
+ if (video) {
1660
+ try { video.close(); } catch { /* ignore */ }
1661
+ if (socket?.connected) await emit(socket, "closeProducer", { producerId: video.id }).catch(() => {});
1305
1662
  }
1663
+ await withAudioLock(teardownLiveAudio);
1306
1664
  }
1307
1665
 
1308
1666
  async function createLiveCompositor() {
@@ -1328,7 +1686,10 @@ export function createClient(options = {}) {
1328
1686
  return next;
1329
1687
  }
1330
1688
 
1331
- /** Compose the stage and publish hidden rtmp-video (H264) + rtmp-audio on the origin. */
1689
+ /**
1690
+ * Compose the stage and publish hidden rtmp-video (H264) on the origin. Audio is my mic
1691
+ * producer while nothing needs mixing (one Opus stream), else a hidden rtmp-audio mix.
1692
+ */
1332
1693
  async function startLiveOutput() {
1333
1694
  if (closed) throw new Error("The session has ended");
1334
1695
  if (live) return;
@@ -1348,10 +1709,9 @@ export function createClient(options = {}) {
1348
1709
  // Start near the target so the first seconds on the platform are not blurry.
1349
1710
  codecOptions: { videoGoogleStartBitrate: Math.round(rtmpBitrate / 1000 * 0.8) },
1350
1711
  });
1351
- liveProducers.push(video);
1712
+ liveVideo = video;
1352
1713
  await applyLiveSenderParams(video);
1353
- const audio = await produceHidden("rtmp-audio", next.audioTrack);
1354
- liveProducers.push(audio);
1714
+ await withAudioLock(() => setupLiveAudio(next));
1355
1715
  } catch (error) {
1356
1716
  await closeLiveProducers();
1357
1717
  if (live === next) live = null;
@@ -1359,6 +1719,8 @@ export function createClient(options = {}) {
1359
1719
  throw error;
1360
1720
  }
1361
1721
  setRtmpState({});
1722
+ // The stage may have changed while going live (a co-host joined, screen audio…).
1723
+ scheduleLiveAudioCheck();
1362
1724
  })();
1363
1725
  try {
1364
1726
  await startingLive;
@@ -1432,14 +1794,16 @@ export function createClient(options = {}) {
1432
1794
 
1433
1795
  /** Rebuild the live compositor (new fps / resolution) and swap tracks without leaving the platforms. */
1434
1796
  async function restartLiveCompositor() {
1435
- if (!live || liveProducers.length < 2) return;
1797
+ if (!live || !liveVideo || !liveAudio) return;
1436
1798
  const previous = live;
1437
1799
  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;
1800
+ await liveVideo.replaceTrack({ track: replacement.videoTrack });
1801
+ await applyLiveSenderParams(liveVideo);
1802
+ await withAudioLock(async () => {
1803
+ live = replacement;
1804
+ // Shared mic audio is not from the compositor; only a mix producer follows it.
1805
+ if (liveAudio && !liveAudio.shared) await liveAudio.producer.replaceTrack({ track: replacement.audioTrack });
1806
+ });
1443
1807
  await previous.finish().catch(() => {});
1444
1808
  }
1445
1809
 
@@ -1474,9 +1838,9 @@ export function createClient(options = {}) {
1474
1838
  rtmpFps = fps;
1475
1839
  rtmpResolution = resolution;
1476
1840
  rtmpBitrate = bitrate;
1477
- if (live && liveProducers.length >= 2) {
1841
+ if (live && liveVideo) {
1478
1842
  if (restart) await restartLiveCompositor();
1479
- else if (rebitrate) await applyLiveSenderParams(liveProducers[0]);
1843
+ else if (rebitrate) await applyLiveSenderParams(liveVideo);
1480
1844
  }
1481
1845
  return getRtmpQuality();
1482
1846
  }
@@ -1528,6 +1892,10 @@ export function createClient(options = {}) {
1528
1892
  clearInterval(stageDebugTimer);
1529
1893
  stageDebugTimer = null;
1530
1894
  }
1895
+ if (liveAudioCheckTimer) {
1896
+ clearTimeout(liveAudioCheckTimer);
1897
+ liveAudioCheckTimer = null;
1898
+ }
1531
1899
  settleReady?.(new Error("Ended"));
1532
1900
  // Finalize only on explicit stop-session / finalize. Browser close uses disconnect handoff.
1533
1901
  const forceFinalize = options.finalize === true || options.endSession === true;
@@ -1572,7 +1940,8 @@ export function createClient(options = {}) {
1572
1940
  for (const entry of locals.values()) {
1573
1941
  detachEnded(entry);
1574
1942
  entry.track.stop();
1575
- entry.producer.close();
1943
+ entry.producer?.close();
1944
+ entry.producer = null;
1576
1945
  }
1577
1946
  locals.clear();
1578
1947
  try { sendTransport?.close(); } catch { /* ignore */ }
@@ -1639,6 +2008,10 @@ export function createClient(options = {}) {
1639
2008
  getAppearance,
1640
2009
  canLiveStream,
1641
2010
  isRtmpEnabled: () => Boolean(rtmpState.enabled),
2011
+ /** `{ webrtc }` — false while a live-stream-first room has no WebRTC viewer (tracks stay local). */
2012
+ getMediaDemand: () => ({ webrtc: webrtcDemand }),
2013
+ /** Ordered WebRTC video codec preference in use (VP8 first by default). */
2014
+ getVideoCodecs: () => [...videoCodecs],
1642
2015
  setRecordingCrop,
1643
2016
  setRecordingStage,
1644
2017
  getUserList: guard(getUserList),
package/src/index.js CHANGED
@@ -1,4 +1,4 @@
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
3
  export { DEFAULT_RECORDING_FPS } from "./record.js";
4
4
  export {