@voltkit-rtc/client 0.3.0 → 0.4.0

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.
Files changed (48) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/README.md +125 -14
  3. package/dist/cjs/chat.d.ts +2 -0
  4. package/dist/cjs/chat.d.ts.map +1 -1
  5. package/dist/cjs/chat.js +23 -4
  6. package/dist/cjs/chat.js.map +1 -1
  7. package/dist/cjs/device.d.ts +85 -0
  8. package/dist/cjs/device.d.ts.map +1 -0
  9. package/dist/cjs/device.js +134 -0
  10. package/dist/cjs/device.js.map +1 -0
  11. package/dist/cjs/index.d.ts +153 -2
  12. package/dist/cjs/index.d.ts.map +1 -1
  13. package/dist/cjs/index.js +506 -36
  14. package/dist/cjs/index.js.map +1 -1
  15. package/dist/cjs/quality.d.ts +35 -6
  16. package/dist/cjs/quality.d.ts.map +1 -1
  17. package/dist/cjs/quality.js +51 -19
  18. package/dist/cjs/quality.js.map +1 -1
  19. package/dist/cjs/stats.d.ts +151 -0
  20. package/dist/cjs/stats.d.ts.map +1 -0
  21. package/dist/cjs/stats.js +243 -0
  22. package/dist/cjs/stats.js.map +1 -0
  23. package/dist/esm/chat.d.ts +2 -0
  24. package/dist/esm/chat.d.ts.map +1 -1
  25. package/dist/esm/chat.js +23 -4
  26. package/dist/esm/chat.js.map +1 -1
  27. package/dist/esm/device.d.ts +85 -0
  28. package/dist/esm/device.d.ts.map +1 -0
  29. package/dist/esm/device.js +122 -0
  30. package/dist/esm/device.js.map +1 -0
  31. package/dist/esm/index.d.ts +153 -2
  32. package/dist/esm/index.d.ts.map +1 -1
  33. package/dist/esm/index.js +507 -37
  34. package/dist/esm/index.js.map +1 -1
  35. package/dist/esm/quality.d.ts +35 -6
  36. package/dist/esm/quality.d.ts.map +1 -1
  37. package/dist/esm/quality.js +49 -19
  38. package/dist/esm/quality.js.map +1 -1
  39. package/dist/esm/stats.d.ts +151 -0
  40. package/dist/esm/stats.d.ts.map +1 -0
  41. package/dist/esm/stats.js +232 -0
  42. package/dist/esm/stats.js.map +1 -0
  43. package/package.json +1 -1
  44. package/src/chat.ts +21 -4
  45. package/src/device.ts +168 -0
  46. package/src/index.ts +582 -42
  47. package/src/quality.ts +54 -19
  48. package/src/stats.ts +328 -0
package/dist/esm/index.js CHANGED
@@ -6,8 +6,10 @@
6
6
  * setup, consumer resume ordering and reconnection, each slightly wrong.
7
7
  */
8
8
  import { Device } from 'mediasoup-client';
9
+ import { chooseCodec, currentEnv, defaultLayerCount, findCodec, h264HardwareEncode, isAppleMobile, isPhoneOrTablet, normalizeCodec, } from './device.js';
9
10
  import { MusicSource } from './music.js';
10
- import { allowedQuality, DEFAULT_VIDEO_POLICY, videoEncodings } from './quality.js';
11
+ import { allowedQuality, DEFAULT_VIDEO_POLICY, sameLayout, topLayerSize, videoEncodings, } from './quality.js';
12
+ import { parseReceiveStats, parseSendStats, pruneBaseline, VideoLimitWatch, } from './stats.js';
11
13
  export { BroadcastPublisher, WhipError, whipEnd, whipOffer } from './broadcast.js';
12
14
  export { AudioMixer, MusicSource } from './music.js';
13
15
  export { ChatClient, ChatRpcError } from './chat.js';
@@ -48,6 +50,14 @@ const CLOSE_REPLACED = 4001;
48
50
  /** The server ended the session on purpose and said why first: do not reconnect. */
49
51
  const CLOSE_ENDED = 4003;
50
52
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
53
+ const isLayer = (value) => Number.isInteger(value) && value >= 0;
54
+ /**
55
+ * Where a new camera stream's bandwidth estimate starts, in kbps. Chrome
56
+ * otherwise starts low and takes many seconds to climb to the top layer.
57
+ */
58
+ const VIDEO_START_BITRATE_KBPS = 1500;
59
+ /** Why a publish gave up: unpublish() ran while it was under way, and unpublish wins. */
60
+ const unpublishedWhile = (what) => `the ${what} was unpublished while it was being published`;
51
61
  export class StreamClient {
52
62
  wsUrl;
53
63
  ws = null;
@@ -80,9 +90,31 @@ export class StreamClient {
80
90
  musicProducerId = null;
81
91
  /** What each remote producer carries, so a pause can say "music" rather than just "audio". */
82
92
  remoteSources = new Map();
93
+ /**
94
+ * The layers asked for each remote video, by producerId. A reconnect
95
+ * consumes everything again, and the new consumer would otherwise start at
96
+ * the full picture.
97
+ */
98
+ preferredLayers = new Map();
83
99
  closedByUs = false;
84
100
  reconnecting = false;
85
101
  reconnectAttempt = 0;
102
+ /** Set once a connect() has joined and set up. Only such a session is reconnected. */
103
+ joinedOnce = false;
104
+ /** The camera producer's layers, to tell whether a new track fits them. */
105
+ cameraEncodings = null;
106
+ // Changes to the camera producer run one at a time. Two overlapping swaps
107
+ // (an effect toggled on and off quickly) would otherwise both close the
108
+ // same producer and both produce a new one.
109
+ cameraQueue = Promise.resolve();
110
+ // Bumped by unpublish(). A producer still being made when it runs (camera,
111
+ // microphone or music) belongs to the publish it ended: it is closed, not
112
+ // kept.
113
+ publishGeneration = 0;
114
+ codecFallbackLogged = false;
115
+ sendStatsBaseline = new Map();
116
+ recvStatsBaseline = new Map();
117
+ limitWatch = new VideoLimitWatch((baseline) => this.collectVideoStats(baseline), (event) => this.emit('videoLimited', event));
86
118
  constructor(wsUrl, token) {
87
119
  this.wsUrl = wsUrl;
88
120
  this.token = token;
@@ -94,7 +126,17 @@ export class StreamClient {
94
126
  this.listeners.set(event, set);
95
127
  }
96
128
  set.add(fn);
97
- return () => set.delete(fn);
129
+ // videoLimited costs a getStats every 2 s, so it runs only while heard.
130
+ if (event === 'videoLimited')
131
+ this.syncLimitWatch();
132
+ return () => {
133
+ set.delete(fn);
134
+ if (event === 'videoLimited')
135
+ this.syncLimitWatch();
136
+ };
137
+ }
138
+ listenerCount(event) {
139
+ return this.listeners.get(event)?.size ?? 0;
98
140
  }
99
141
  emit(event, ...args) {
100
142
  for (const fn of this.listeners.get(event) ?? []) {
@@ -108,12 +150,36 @@ export class StreamClient {
108
150
  }
109
151
  // ------------------------------------------------------------- connection
110
152
  async connect() {
111
- await this.openSocket();
112
- const result = (await this.rpc('join', { token: this.token }));
113
- this.joinResult = result;
114
- this.device = new Device();
115
- await this.device.load({ routerRtpCapabilities: result.routerRtpCapabilities });
153
+ let result;
154
+ try {
155
+ await this.openSocket();
156
+ result = (await this.rpc('join', { token: this.token }));
157
+ this.joinResult = result;
158
+ this.device = this.createDevice();
159
+ await this.device.load({ routerRtpCapabilities: result.routerRtpCapabilities });
160
+ }
161
+ catch (err) {
162
+ // A session that never got going: the app has the error. Left open,
163
+ // the socket would be closed by the server's join deadline instead, and
164
+ // that close would start reconnecting a session that never began.
165
+ if (!this.joinedOnce)
166
+ this.detachSocket();
167
+ throw err;
168
+ }
169
+ // Joined and set up: the next drop gets every reconnect attempt again.
170
+ // Not when the socket opens -- a join refused with a code worth retrying
171
+ // (no-capacity) never used them up, and every client of a full cluster
172
+ // retried about twice a second, forever.
173
+ this.reconnectAttempt = 0;
174
+ this.joinedOnce = true;
116
175
  this.emit('joined', result);
176
+ // A video that ended while this client was away sends it no
177
+ // producerClosed: forget the layers asked for it.
178
+ const present = new Set(result.producers.map((p) => p.producerId));
179
+ for (const producerId of this.preferredLayers.keys()) {
180
+ if (!present.has(producerId))
181
+ this.preferredLayers.delete(producerId);
182
+ }
117
183
  // Subscribe to everything already publishing before we announce readiness.
118
184
  for (const p of result.producers) {
119
185
  await this.consume(p).catch((err) => this.emit('error', err));
@@ -126,6 +192,10 @@ export class StreamClient {
126
192
  }
127
193
  return result;
128
194
  }
195
+ /** A new mediasoup Device for each join. Its own method so tests, which have no WebRTC, can stand one in. */
196
+ createDevice() {
197
+ return new Device();
198
+ }
129
199
  openSocket() {
130
200
  // Abandon any previous socket first. Its close handler checks identity
131
201
  // against `this.ws`, so once it is detached it can no longer trigger a
@@ -137,7 +207,6 @@ export class StreamClient {
137
207
  const ws = new WebSocket(url.toString());
138
208
  this.ws = ws;
139
209
  const onOpen = () => {
140
- this.reconnectAttempt = 0;
141
210
  this.emit('connected');
142
211
  resolve();
143
212
  };
@@ -163,6 +232,9 @@ export class StreamClient {
163
232
  // displace it, and it would displace us right back, forever.
164
233
  this.emit('error', new Error('this identity connected from somewhere else'));
165
234
  this.closedByUs = true;
235
+ // The producers outlive this close until the app calls close(); the
236
+ // videoLimited sampling must not, or it reports after `closed`.
237
+ this.limitWatch.reset();
166
238
  this.emit('closed', 'replaced');
167
239
  return;
168
240
  }
@@ -170,9 +242,14 @@ export class StreamClient {
170
242
  // Normally roomClosed has already ended the session; this covers a
171
243
  // close that arrived without it.
172
244
  this.closedByUs = true;
245
+ this.limitWatch.reset();
173
246
  this.emit('closed', 'room-closed');
174
247
  return;
175
248
  }
249
+ // Before a first successful join the app is still waiting on
250
+ // connect(), which reports the failure; there is nothing to restore.
251
+ if (!this.joinedOnce)
252
+ return;
176
253
  void this.scheduleReconnect();
177
254
  });
178
255
  });
@@ -216,8 +293,13 @@ export class StreamClient {
216
293
  return;
217
294
  try {
218
295
  this.teardownMedia();
219
- await this.connect();
220
- return; // connect() resets the attempt counter once the socket opens
296
+ await this.connect(); // which resets the attempt counter once joined
297
+ // The socket can drop again while the session is being restored,
298
+ // and its close handler then finds this loop still running and
299
+ // leaves it to us. Returning would leave the client disconnected
300
+ // for good, with no `closed`.
301
+ if (this.ws)
302
+ return;
221
303
  }
222
304
  catch (err) {
223
305
  this.emit('error', err);
@@ -243,6 +325,9 @@ export class StreamClient {
243
325
  this.closedByUs = true;
244
326
  this.wasPublishing = false;
245
327
  this.teardownMedia();
328
+ this.preferredLayers.clear();
329
+ // Nothing is emitted after closing, so not even a clearing videoLimited.
330
+ this.limitWatch.reset();
246
331
  // Producers no longer stop their tracks, so releasing the camera and
247
332
  // microphone is ours to do -- otherwise the device light stays on.
248
333
  this.localStream?.getTracks().forEach((t) => t.stop());
@@ -261,6 +346,10 @@ export class StreamClient {
261
346
  p.close();
262
347
  this.producers.clear();
263
348
  this.musicProducerId = null;
349
+ this.cameraEncodings = null;
350
+ // Paused, not reset: a reconnect's republish starts it again, and a
351
+ // limitation already reported is not reported twice.
352
+ this.syncLimitWatch();
264
353
  this.sendTransport?.close();
265
354
  this.recvTransport?.close();
266
355
  this.sendTransport = null;
@@ -329,6 +418,7 @@ export class StreamClient {
329
418
  break;
330
419
  case 'producerClosed': {
331
420
  const { producerId, identity } = data;
421
+ this.preferredLayers.delete(producerId);
332
422
  const consumer = this.consumers.get(producerId);
333
423
  if (!consumer)
334
424
  break; // never consumed it, or already cleaned up
@@ -508,9 +598,17 @@ export class StreamClient {
508
598
  *
509
599
  * `options.quality` picks 1080p, 720p or 480p (see `videoPolicy` for what
510
600
  * the project allows). Capture at least that size for the full picture.
601
+ * `options.layers`, `codec` and `degradationPreference` tune how the video
602
+ * is encoded; the defaults suit both phones and computers. The options are
603
+ * kept for a reconnect's republish.
511
604
  */
512
605
  async publish(stream, constraints, options) {
606
+ const generation = this.publishGeneration;
513
607
  const transport = await this.ensureSendTransport();
608
+ // unpublish() ran first: this publish is over before it began, and must
609
+ // leave nothing behind that a reconnect would publish again.
610
+ if (generation !== this.publishGeneration)
611
+ throw new Error(unpublishedWhile('stream'));
514
612
  this.localStream = stream;
515
613
  this.wasPublishing = true;
516
614
  if (constraints)
@@ -527,11 +625,16 @@ export class StreamClient {
527
625
  codecOptions: { opusStereo: true, opusDtx: true, opusFec: true },
528
626
  appData: { source: 'mic' },
529
627
  });
530
- this.producers.set(producer.id, producer);
628
+ await this.keepProducer(producer, generation, 'microphone');
629
+ // A microphone handed over switched off, or muted before a reconnect.
630
+ await this.pauseOnServer(producer);
531
631
  }
532
632
  const video = stream.getVideoTracks()[0];
533
- if (video)
534
- await this.produceCamera(transport, video);
633
+ if (video) {
634
+ // The track is read when the camera's turn comes: one handed to
635
+ // replaceVideoTrack while this publish was under way is the one to send.
636
+ await this.cameraTask(() => this.produceCamera(transport, this.localStream?.getVideoTracks()[0] ?? video, generation));
637
+ }
535
638
  }
536
639
  /** What this project may publish. Known once joined; 720p before that. */
537
640
  get videoPolicy() {
@@ -549,36 +652,354 @@ export class StreamClient {
549
652
  */
550
653
  async setVideoQuality(quality) {
551
654
  this.publishOptions = { ...this.publishOptions, quality };
552
- const current = [...this.producers.values()].find((p) => p.kind === 'video' && p.appData.source === 'camera');
553
- const track = current?.track;
554
- if (!current || !track || track.readyState !== 'live')
555
- return this.videoQuality;
655
+ await this.cameraTask(async () => {
656
+ const current = this.cameraProducer();
657
+ const track = current?.track;
658
+ if (!current || !track || track.readyState !== 'live')
659
+ return;
660
+ await this.reproduceCamera(current, track);
661
+ });
662
+ return this.videoQuality;
663
+ }
664
+ /**
665
+ * Send a different video track from now on: a canvas with effects drawn on
666
+ * it, the raw camera again, another camera. When the new track needs the
667
+ * same layers as the current one (the same size, or another size the
668
+ * project's quality scales alike), viewers see no pause, and the layers
669
+ * take the new picture's bitrates. Otherwise the camera producer is
670
+ * replaced, as `setVideoQuality` does. Either way a paused camera stays
671
+ * paused.
672
+ *
673
+ * Your own stream is left as it is: the client keeps a stream of its own
674
+ * (`local`, announced by `localStreamChanged`) with the new track and your
675
+ * microphone, and a reconnect republishes that. The track you replaced is
676
+ * not stopped; it is yours again, switched back on if pausing the camera
677
+ * had switched it off. Rejects when no camera is being published.
678
+ */
679
+ async replaceVideoTrack(track) {
680
+ if (!track || track.kind !== 'video')
681
+ throw new TypeError('replaceVideoTrack needs a video track');
682
+ if (track.readyState === 'ended')
683
+ throw new Error('replaceVideoTrack: that track has ended');
684
+ await this.cameraTask(async () => {
685
+ const current = this.cameraProducer();
686
+ // Between a dropped connection and the republish there is no producer,
687
+ // but the camera is still being published: the republish sends this.
688
+ const reconnecting = !current && this.wasPublishing && (this.localStream?.getVideoTracks().length ?? 0) > 0;
689
+ if (!current && !reconnecting)
690
+ throw new Error('replaceVideoTrack: no camera is being published');
691
+ if (!current) {
692
+ // The republish reads the camera's state off the track it sends, and
693
+ // the track being replaced is switched off exactly when the camera is
694
+ // paused. Hand that state on, or a camera that was off comes back on;
695
+ // and the old track back switched on, as below.
696
+ const replaced = this.localStream?.getVideoTracks()[0];
697
+ if (replaced && replaced !== track) {
698
+ track.enabled = replaced.enabled;
699
+ replaced.enabled = true;
700
+ }
701
+ }
702
+ this.adoptVideoTrack(track);
703
+ if (!current || current.track === track)
704
+ return;
705
+ const previous = current.track;
706
+ const paused = current.paused;
707
+ try {
708
+ const { width = 0, height = 0 } = track.getSettings();
709
+ const next = videoEncodings(width, height, this.videoQuality, this.layerCount());
710
+ if (this.cameraEncodings && sameLayout(this.cameraEncodings, next)) {
711
+ await current.replaceTrack({ track });
712
+ await this.applyLayerBitrates(current, next);
713
+ return;
714
+ }
715
+ await this.reproduceCamera(current, track);
716
+ }
717
+ finally {
718
+ // Pausing switched the old track off (mediasoup-client pauses that
719
+ // way), and nothing switches it back on once it is replaced. It is the
720
+ // app's again, often the camera its canvas draws from: handed back
721
+ // off, that canvas stays black after the camera is resumed.
722
+ if (paused && previous && previous !== this.cameraProducer()?.track)
723
+ previous.enabled = true;
724
+ }
725
+ });
726
+ }
727
+ /**
728
+ * Give a camera producer whose track was swapped in place the bitrates of
729
+ * its new picture. The layout matched, but a bigger picture at the same
730
+ * scales (a 1280×720 canvas for a 960×540 camera) would otherwise stay
731
+ * capped at the smaller one's. Best effort: a browser that refuses keeps
732
+ * the old caps.
733
+ */
734
+ async applyLayerBitrates(producer, encodings) {
735
+ const before = this.cameraEncodings;
736
+ if (before && before.every((encoding, i) => encoding.maxBitrate === encodings[i]?.maxBitrate)) {
737
+ this.cameraEncodings = encodings;
738
+ return;
739
+ }
740
+ const sender = producer.rtpSender;
741
+ if (!sender)
742
+ return;
743
+ try {
744
+ const parameters = sender.getParameters();
745
+ // One entry per layer, smallest first, as they were produced. A browser
746
+ // that reports them some other way is left with its own.
747
+ if (parameters.encodings.length !== encodings.length)
748
+ return;
749
+ parameters.encodings.forEach((encoding, i) => {
750
+ encoding.maxBitrate = encodings[i].maxBitrate;
751
+ });
752
+ await sender.setParameters(parameters);
753
+ this.cameraEncodings = encodings;
754
+ }
755
+ catch {
756
+ // Unsupported here; the layers keep the caps they were produced with.
757
+ }
758
+ }
759
+ /**
760
+ * What your camera video is sending now, layer by layer, or null when no
761
+ * camera is being published. The top-level fields describe the biggest
762
+ * layer going out. `qualityLimitation` says why it is less than asked:
763
+ * `cpu` is this device, `bandwidth` the upload, `none` neither (then check
764
+ * the camera and the light). Bitrates are averaged since the previous call,
765
+ * so call it every second or two; the first call reports 0.
766
+ */
767
+ async getVideoStats() {
768
+ return this.collectVideoStats(this.sendStatsBaseline);
769
+ }
770
+ /**
771
+ * What this client receives of a remote video (by its `producerId`, from
772
+ * the `track` event), or null when it is not receiving that video. Bitrates
773
+ * are averaged since the previous call for it; the first call reports 0.
774
+ */
775
+ async getReceiveStats(producerId) {
776
+ const consumer = this.consumers.get(producerId);
777
+ if (!consumer || consumer.kind !== 'video')
778
+ return null;
779
+ let report;
780
+ try {
781
+ report = await consumer.getStats();
782
+ }
783
+ catch (err) {
784
+ if (consumer.closed)
785
+ return null;
786
+ throw err;
787
+ }
788
+ const live = new Set([...this.consumers.values()].map((c) => c.id));
789
+ pruneBaseline(this.recvStatsBaseline, (key) => live.has(key));
790
+ return parseReceiveStats(report.values(), { producerId, baseline: this.recvStatsBaseline, key: consumer.id });
791
+ }
792
+ /**
793
+ * Receive a smaller copy of someone's video (by its `producerId`, from the
794
+ * `track` event), for a tile that does not need the full picture. Spatial
795
+ * layer 0 is the smallest copy the publisher sends: a computer sends three
796
+ * (at 720p 320×180, 640×360 and 1280×720), a phone two (640×360 and
797
+ * 1280×720), and a layer above the biggest means the biggest. Leave
798
+ * `temporalLayer` out to keep the full frame rate. It is the most this
799
+ * client is sent: a connection that cannot carry it still gets less. The
800
+ * choice is kept across reconnects and forgotten when the track ends.
801
+ * Rejects for a producer whose video this client is not receiving.
802
+ */
803
+ async setPreferredLayers(producerId, spatialLayer, temporalLayer) {
804
+ if (!isLayer(spatialLayer) || (temporalLayer !== undefined && !isLayer(temporalLayer))) {
805
+ throw new RangeError('setPreferredLayers: layers are whole numbers from 0');
806
+ }
807
+ const consumer = this.consumers.get(producerId);
808
+ if (!consumer || consumer.kind !== 'video') {
809
+ throw new Error(`setPreferredLayers: this client is not receiving a video with producerId ${producerId}`);
810
+ }
811
+ const layers = temporalLayer === undefined ? { spatialLayer } : { spatialLayer, temporalLayer };
812
+ // Kept first: a reconnect that interrupts the request still applies it.
813
+ this.preferredLayers.set(producerId, layers);
814
+ await this.rpc('setPreferredLayers', { consumerId: consumer.id, ...layers });
815
+ }
816
+ async collectVideoStats(baseline) {
817
+ const producer = this.cameraProducer();
818
+ if (!producer)
819
+ return null;
820
+ let report;
821
+ try {
822
+ report = await producer.getStats();
823
+ }
824
+ catch (err) {
825
+ if (producer.closed)
826
+ return null;
827
+ throw err;
828
+ }
829
+ const prefix = `${producer.id}:`;
830
+ pruneBaseline(baseline, (key) => key.startsWith(prefix));
831
+ return parseSendStats(report.values(), { quality: this.videoQuality, baseline, keyPrefix: prefix });
832
+ }
833
+ cameraProducer() {
834
+ for (const p of this.producers.values()) {
835
+ if (p.kind === 'video' && p.appData.source === 'camera')
836
+ return p;
837
+ }
838
+ return undefined;
839
+ }
840
+ cameraTask(task) {
841
+ const run = this.cameraQueue.then(task, task);
842
+ this.cameraQueue = run.catch(() => undefined);
843
+ return run;
844
+ }
845
+ /** Swap the video in the client's own stream, never the app's. */
846
+ adoptVideoTrack(track) {
847
+ const previous = this.localStream;
848
+ if (previous && previous.getVideoTracks()[0] === track)
849
+ return;
850
+ const others = previous ? previous.getTracks().filter((t) => t.kind !== 'video') : [];
851
+ this.localStream = new MediaStream([...others, track]);
852
+ this.emit('localStreamChanged', this.localStream);
853
+ }
854
+ /** Close the camera producer and produce `track` in its place, paused on both ends if it was. */
855
+ async reproduceCamera(current, track) {
856
+ const generation = this.publishGeneration;
556
857
  const paused = current.paused;
557
858
  current.close();
558
859
  this.producers.delete(current.id);
860
+ this.cameraEncodings = null;
861
+ this.syncLimitWatch();
559
862
  await this.rpc('closeProducer', { producerId: current.id }).catch(() => undefined);
560
- const producer = await this.produceCamera(await this.ensureSendTransport(), track);
561
- if (paused) {
562
- producer.pause();
563
- await this.rpc('pauseProducer', { producerId: producer.id, paused: true });
564
- }
565
- return this.videoQuality;
863
+ return this.produceCamera(await this.ensureSendTransport(), track, generation, paused);
864
+ }
865
+ /** `options.layers` when valid, else 2 on phones and tablets and 3 elsewhere. */
866
+ layerCount() {
867
+ const asked = this.publishOptions.layers;
868
+ return asked === 1 || asked === 2 || asked === 3 ? asked : defaultLayerCount();
566
869
  }
567
- async produceCamera(transport, track) {
870
+ /**
871
+ * Produce the camera from `track`, paused on both ends when `paused`. By
872
+ * default the track says: one handed over switched off is a camera that is
873
+ * off, and so is one a pause switched off before a reconnect.
874
+ */
875
+ async produceCamera(transport, track, generation, paused = !track.enabled) {
876
+ if (generation !== this.publishGeneration)
877
+ throw new Error(unpublishedWhile('camera'));
878
+ // mediasoup-client starts a producer paused exactly when its track is
879
+ // off. Setting the track to the camera's state first makes the producer
880
+ // start in it, and a camera that is off never sends a frame of the new
881
+ // track; the server is told below.
882
+ track.enabled = !paused;
568
883
  // Simulcast from day one: it is what lets one node serve far more viewers.
569
- // The layers follow the picture's real size and the project's quality, so
570
- // the browser sends every layer asked for (see videoEncodings).
884
+ // The layers follow the picture's real size, the project's quality and
885
+ // the device, so the browser sends every layer asked for (see
886
+ // videoEncodings).
571
887
  const { width = 0, height = 0 } = track.getSettings();
572
- const producer = await transport.produce({
888
+ const quality = this.videoQuality;
889
+ const encodings = videoEncodings(width, height, quality, this.layerCount());
890
+ let codecs;
891
+ try {
892
+ codecs = this.device?.sendRtpCapabilities.codecs;
893
+ }
894
+ catch {
895
+ codecs = undefined;
896
+ }
897
+ const chosen = await this.cameraCodec(codecs, encodings, width, height, quality);
898
+ const produce = (codec) => transport.produce({
573
899
  track,
574
900
  stopTracks: false,
575
- encodings: videoEncodings(width, height, this.videoQuality),
576
- codecOptions: { videoGoogleStartBitrate: 1000 },
901
+ encodings,
902
+ codecOptions: { videoGoogleStartBitrate: VIDEO_START_BITRATE_KBPS },
903
+ ...(codec ? { codec } : {}),
577
904
  appData: { source: 'camera' },
578
905
  });
579
- this.producers.set(producer.id, producer);
906
+ let producer;
907
+ try {
908
+ producer = await produce(chosen.capability);
909
+ }
910
+ catch (err) {
911
+ // Never fail a publish over the codec: H.264 refused is VP8 instead.
912
+ // A closed transport (a reconnect under way) fails either way.
913
+ if (chosen.codec !== 'h264' || transport.closed)
914
+ throw err;
915
+ this.reportCodecFallback(`H.264 was refused (${err.message}): publishing VP8 instead`);
916
+ producer = await produce(findCodec(codecs, 'vp8'));
917
+ }
918
+ // unpublish() may have run while this was being made (a publish, a
919
+ // quality change or a track swap under way).
920
+ await this.keepProducer(producer, generation, 'camera');
921
+ this.cameraEncodings = encodings;
922
+ await this.pauseOnServer(producer);
923
+ await this.applyDegradationPreference(producer);
924
+ this.syncLimitWatch();
580
925
  return producer;
581
926
  }
927
+ /**
928
+ * Keep a producer just made -- unless unpublish() ran while it was being
929
+ * made. Kept, it would publish again what was just unpublished, so it is
930
+ * closed instead, on both ends.
931
+ */
932
+ async keepProducer(producer, generation, what) {
933
+ if (generation !== this.publishGeneration) {
934
+ producer.close();
935
+ await this.rpc('closeProducer', { producerId: producer.id }).catch(() => undefined);
936
+ throw new Error(unpublishedWhile(what));
937
+ }
938
+ this.producers.set(producer.id, producer);
939
+ }
940
+ /**
941
+ * mediasoup-client makes a producer paused when its track is off, and the
942
+ * server makes every producer live. Unless the server is told, viewers get
943
+ * black video or silence from a camera or microphone they are told is on.
944
+ */
945
+ async pauseOnServer(producer) {
946
+ if (producer.paused)
947
+ await this.rpc('pauseProducer', { producerId: producer.id, paused: true });
948
+ }
949
+ /**
950
+ * H.264 or VP8 for the camera (see chooseCodec), with the device's own
951
+ * capability entry for it: produce() must only ever get one of those.
952
+ */
953
+ async cameraCodec(codecs, encodings, width, height, quality) {
954
+ const requested = normalizeCodec(this.publishOptions.codec);
955
+ const env = currentEnv();
956
+ const phoneOrTablet = isPhoneOrTablet(env);
957
+ const h264 = findCodec(codecs, 'h264');
958
+ let h264Hardware = null;
959
+ if (requested === 'auto' && phoneOrTablet && h264) {
960
+ const top = topLayerSize(width, height, quality);
961
+ h264Hardware = await h264HardwareEncode({ width: top.width, height: top.height, bitrate: encodings[encodings.length - 1].maxBitrate });
962
+ }
963
+ const choice = chooseCodec({ requested, phoneOrTablet, appleMobile: isAppleMobile(env), h264Available: Boolean(h264), h264Hardware });
964
+ if (choice.warning)
965
+ this.reportCodecFallback(choice.warning);
966
+ else if (requested === 'auto' && phoneOrTablet && !h264)
967
+ this.reportCodecFallback('this browser cannot send H.264 to this server: publishing VP8');
968
+ if (choice.codec === 'h264' && h264)
969
+ return { codec: 'h264', capability: h264 };
970
+ return { codec: 'vp8', capability: findCodec(codecs, 'vp8') };
971
+ }
972
+ /** A forced H.264 that could not be used is the app's to hear about; 'auto' just notes it, once. */
973
+ reportCodecFallback(message) {
974
+ if (normalizeCodec(this.publishOptions.codec) === 'h264') {
975
+ this.emit('error', new Error(message));
976
+ }
977
+ else if (!this.codecFallbackLogged) {
978
+ this.codecFallbackLogged = true;
979
+ console.warn(`[voltkit-rtc] ${message}`);
980
+ }
981
+ }
982
+ /** Best effort: a browser that ignores or refuses it keeps its own default. */
983
+ async applyDegradationPreference(producer) {
984
+ const preference = this.publishOptions.degradationPreference;
985
+ const sender = producer.rtpSender;
986
+ if (!sender)
987
+ return;
988
+ if (preference !== 'maintain-resolution' && preference !== 'maintain-framerate' && preference !== 'balanced')
989
+ return;
990
+ try {
991
+ const parameters = sender.getParameters();
992
+ parameters.degradationPreference = preference;
993
+ await sender.setParameters(parameters);
994
+ }
995
+ catch {
996
+ // Unsupported here; the encoder keeps the browser's own trade-off.
997
+ }
998
+ }
999
+ /** videoLimited sampling runs while a camera is published and someone listens. */
1000
+ syncLimitWatch() {
1001
+ this.limitWatch.set(!this.closedByUs && this.cameraProducer() !== undefined && this.listenerCount('videoLimited') > 0);
1002
+ }
582
1003
  /**
583
1004
  * Re-establish this client's broadcast after a reconnect.
584
1005
  *
@@ -587,10 +1008,15 @@ export class StreamClient {
587
1008
  * when the tracks have genuinely ended.
588
1009
  */
589
1010
  async republish() {
1011
+ // unpublish() can run while this is under way, and wins: nothing it
1012
+ // stopped is published again.
1013
+ const generation = this.publishGeneration;
590
1014
  // Music is not a device and cannot be "gone": publish it again whatever
591
1015
  // happens to the camera and microphone below.
592
1016
  if (this.music)
593
- await this.produceMusic(this.music).catch((err) => this.emit('error', err));
1017
+ await this.produceMusic(this.music, generation).catch((err) => this.emit('error', err));
1018
+ if (generation !== this.publishGeneration)
1019
+ return;
594
1020
  let stream = this.localStream;
595
1021
  if (!stream && !this.publishConstraints)
596
1022
  return; // music was all that was being published
@@ -600,7 +1026,20 @@ export class StreamClient {
600
1026
  this.emit('error', new Error('cannot restore the broadcast: the devices are gone'));
601
1027
  return;
602
1028
  }
1029
+ const ended = stream;
603
1030
  stream = await navigator.mediaDevices.getUserMedia(this.publishConstraints);
1031
+ if (generation !== this.publishGeneration) {
1032
+ for (const track of stream.getTracks())
1033
+ track.stop();
1034
+ return;
1035
+ }
1036
+ // New devices come back switched on. A camera or microphone the user
1037
+ // had switched off stays off: a dropped connection is no reason to
1038
+ // switch it back on.
1039
+ for (const track of stream.getTracks()) {
1040
+ if (ended?.getTracks().some((t) => t.kind === track.kind && !t.enabled))
1041
+ track.enabled = false;
1042
+ }
604
1043
  this.localStream = stream;
605
1044
  this.emit('localStreamChanged', stream);
606
1045
  }
@@ -620,11 +1059,17 @@ export class StreamClient {
620
1059
  * the user has not interacted with.
621
1060
  */
622
1061
  async publishMusic(input, options) {
1062
+ const generation = this.publishGeneration;
623
1063
  if (this.music)
624
1064
  await this.stopMusic();
625
1065
  const music = new MusicSource(input, options);
626
1066
  try {
627
- await this.produceMusic(music);
1067
+ await this.produceMusic(music, generation);
1068
+ // Checked again here: an unpublish() after the producer was kept has
1069
+ // already closed it, and the music must not be remembered for a
1070
+ // reconnect to publish again.
1071
+ if (generation !== this.publishGeneration)
1072
+ throw new Error(unpublishedWhile('music'));
628
1073
  }
629
1074
  catch (err) {
630
1075
  music.close();
@@ -634,8 +1079,10 @@ export class StreamClient {
634
1079
  this.wasPublishing = true;
635
1080
  this.emitLocalMedia();
636
1081
  }
637
- async produceMusic(music) {
1082
+ async produceMusic(music, generation) {
638
1083
  const transport = await this.ensureSendTransport();
1084
+ if (generation !== this.publishGeneration)
1085
+ throw new Error(unpublishedWhile('music'));
639
1086
  const producer = await transport.produce({
640
1087
  track: music.track,
641
1088
  stopTracks: false,
@@ -644,8 +1091,10 @@ export class StreamClient {
644
1091
  codecOptions: { opusStereo: true, opusDtx: false, opusFec: true, opusMaxAverageBitrate: 128_000 },
645
1092
  appData: { source: 'music' },
646
1093
  });
647
- this.producers.set(producer.id, producer);
1094
+ await this.keepProducer(producer, generation, 'music');
648
1095
  this.musicProducerId = producer.id;
1096
+ // Music switched off before a reconnect comes back paused here.
1097
+ await this.pauseOnServer(producer);
649
1098
  }
650
1099
  /** True while music is published, whether or not it is switched on. */
651
1100
  get musicPublishing() {
@@ -708,6 +1157,13 @@ export class StreamClient {
708
1157
  }));
709
1158
  const consumer = await transport.consume(params);
710
1159
  this.consumers.set(remote.producerId, consumer);
1160
+ // Layers asked for before a reconnect: the new consumer gets them before
1161
+ // its first frame instead of starting at the full picture. Not getting
1162
+ // them costs data, not the track, so a refusal is only reported.
1163
+ const layers = this.preferredLayers.get(remote.producerId);
1164
+ if (layers) {
1165
+ await this.rpc('setPreferredLayers', { consumerId: consumer.id, ...layers }).catch((err) => this.emit('error', err));
1166
+ }
711
1167
  // The server created it paused. Resume only now that our end exists,
712
1168
  // otherwise the first frames arrive before there is anything to decode them.
713
1169
  await this.rpc('resumeConsumer', { consumerId: consumer.id });
@@ -767,21 +1223,35 @@ export class StreamClient {
767
1223
  }
768
1224
  /** Stop publishing entirely and release the local devices. */
769
1225
  async unpublish() {
1226
+ // All of it takes effect now; only telling the server is waited for. So
1227
+ // publish() and unpublish() act in the order they are called: a publish
1228
+ // called while this still waits is not undone by it, and one already
1229
+ // under way stops at its next step (keepProducer).
1230
+ this.publishGeneration += 1;
770
1231
  const ids = [...this.producers.keys()];
771
1232
  for (const producer of this.producers.values())
772
1233
  producer.close();
773
1234
  this.producers.clear();
774
- for (const id of ids) {
775
- await this.rpc('closeProducer', { producerId: id }).catch(() => undefined);
776
- }
1235
+ this.cameraEncodings = null;
1236
+ // Start over for the next publish, and clear a limitation still showing:
1237
+ // nothing is being held back once nothing is being sent.
1238
+ const cleared = this.limitWatch.reset();
1239
+ if (cleared)
1240
+ this.emit('videoLimited', cleared);
777
1241
  this.localStream?.getTracks().forEach((t) => t.stop());
778
1242
  this.localStream = null;
1243
+ // Forgotten with the stream: kept, a reconnect would ask for the camera
1244
+ // and microphone again and publish them, after the app unpublished them.
1245
+ this.publishConstraints = null;
779
1246
  this.music?.close();
780
1247
  this.music = null;
781
1248
  this.musicProducerId = null;
782
1249
  this.wasPublishing = false;
783
1250
  this.emit('localStreamChanged', null);
784
1251
  this.emit('localMediaChanged', { micEnabled: false, camEnabled: false, musicEnabled: false });
1252
+ for (const id of ids) {
1253
+ await this.rpc('closeProducer', { producerId: id }).catch(() => undefined);
1254
+ }
785
1255
  }
786
1256
  get local() {
787
1257
  return this.localStream;