@cuekit-ai/react 1.6.7 → 1.6.9

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.
@@ -8836,23 +8836,6 @@ var SignalRequestError = class extends LivekitError {
8836
8836
  this.reasonName = typeof reason === "string" ? reason : RequestResponse_Reason[reason];
8837
8837
  }
8838
8838
  };
8839
- var DataStreamErrorReason;
8840
- (function(DataStreamErrorReason2) {
8841
- DataStreamErrorReason2[DataStreamErrorReason2["AlreadyOpened"] = 0] = "AlreadyOpened";
8842
- DataStreamErrorReason2[DataStreamErrorReason2["AbnormalEnd"] = 1] = "AbnormalEnd";
8843
- DataStreamErrorReason2[DataStreamErrorReason2["DecodeFailed"] = 2] = "DecodeFailed";
8844
- DataStreamErrorReason2[DataStreamErrorReason2["LengthExceeded"] = 3] = "LengthExceeded";
8845
- DataStreamErrorReason2[DataStreamErrorReason2["Incomplete"] = 4] = "Incomplete";
8846
- DataStreamErrorReason2[DataStreamErrorReason2["HandlerAlreadyRegistered"] = 7] = "HandlerAlreadyRegistered";
8847
- })(DataStreamErrorReason || (DataStreamErrorReason = {}));
8848
- var DataStreamError = class extends LivekitError {
8849
- constructor(message, reason) {
8850
- super(16, message);
8851
- this.name = "DataStreamError";
8852
- this.reason = reason;
8853
- this.reasonName = DataStreamErrorReason[reason];
8854
- }
8855
- };
8856
8839
  var MediaDeviceFailure;
8857
8840
  (function(MediaDeviceFailure2) {
8858
8841
  MediaDeviceFailure2["PermissionDenied"] = "PermissionDenied";
@@ -9109,7 +9092,7 @@ function getMatch(exp, ua) {
9109
9092
  function getOSVersion(ua) {
9110
9093
  return ua.includes("mac os") ? getMatch(/\(.+?(\d+_\d+(:?_\d+)?)/, ua, 1).replace(/_/g, ".") : void 0;
9111
9094
  }
9112
- var version$1 = "2.15.6";
9095
+ var version$1 = "2.15.4";
9113
9096
  var version = version$1;
9114
9097
  var protocolVersion = 16;
9115
9098
  var CriticalTimers = class {
@@ -9136,24 +9119,13 @@ var VideoQuality;
9136
9119
  VideoQuality2[VideoQuality2["HIGH"] = 2] = "HIGH";
9137
9120
  })(VideoQuality || (VideoQuality = {}));
9138
9121
  var Track = class _Track extends eventsExports.EventEmitter {
9139
- /**
9140
- * indicates current state of stream, it'll indicate `paused` if the track
9141
- * has been paused by congestion controller
9142
- */
9143
- get streamState() {
9144
- return this._streamState;
9145
- }
9146
- /** @internal */
9147
- setStreamState(value) {
9148
- this._streamState = value;
9149
- }
9150
9122
  constructor(mediaTrack, kind) {
9151
9123
  let loggerOptions = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
9152
9124
  var _a;
9153
9125
  super();
9154
9126
  this.attachedElements = [];
9155
9127
  this.isMuted = false;
9156
- this._streamState = _Track.StreamState.Active;
9128
+ this.streamState = _Track.StreamState.Active;
9157
9129
  this.isInBackground = false;
9158
9130
  this._currentBitrate = 0;
9159
9131
  this.log = livekitLogger;
@@ -9589,7 +9561,7 @@ function supportsAV1() {
9589
9561
  if (!("getCapabilities" in RTCRtpSender)) {
9590
9562
  return false;
9591
9563
  }
9592
- if (isSafari() || isFireFox()) {
9564
+ if (isSafari()) {
9593
9565
  return false;
9594
9566
  }
9595
9567
  const capabilities = RTCRtpSender.getCapabilities("video");
@@ -9686,9 +9658,9 @@ function isE2EESimulcastSupported() {
9686
9658
  if (browser) {
9687
9659
  if (browser.name !== "Safari" && browser.os !== "iOS") {
9688
9660
  return true;
9689
- } else if (browser.os === "iOS" && browser.osVersion && compareVersions(browser.osVersion, supportedSafariVersion) >= 0) {
9661
+ } else if (browser.os === "iOS" && browser.osVersion && compareVersions(supportedSafariVersion, browser.osVersion) >= 0) {
9690
9662
  return true;
9691
- } else if (browser.name === "Safari" && compareVersions(browser.version, supportedSafariVersion) >= 0) {
9663
+ } else if (browser.name === "Safari" && compareVersions(supportedSafariVersion, browser.version) >= 0) {
9692
9664
  return true;
9693
9665
  } else {
9694
9666
  return false;
@@ -9903,13 +9875,13 @@ function unwrapConstraint(constraint) {
9903
9875
  if (Array.isArray(constraint)) {
9904
9876
  return constraint[0];
9905
9877
  }
9906
- if (constraint.exact !== void 0) {
9878
+ if (constraint.exact) {
9907
9879
  if (Array.isArray(constraint.exact)) {
9908
9880
  return constraint.exact[0];
9909
9881
  }
9910
9882
  return constraint.exact;
9911
9883
  }
9912
- if (constraint.ideal !== void 0) {
9884
+ if (constraint.ideal) {
9913
9885
  if (Array.isArray(constraint.ideal)) {
9914
9886
  return constraint.ideal[0];
9915
9887
  }
@@ -10132,7 +10104,7 @@ function constraintsForOptions(options) {
10132
10104
  function detectSilence(track_1) {
10133
10105
  return __awaiter(this, arguments, void 0, function(track) {
10134
10106
  let timeOffset = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 200;
10135
- return (function* () {
10107
+ return function* () {
10136
10108
  const ctx = getNewAudioContext();
10137
10109
  if (ctx) {
10138
10110
  const analyser = ctx.createAnalyser();
@@ -10148,7 +10120,7 @@ function detectSilence(track_1) {
10148
10120
  return !someNoise;
10149
10121
  }
10150
10122
  return false;
10151
- })();
10123
+ }();
10152
10124
  });
10153
10125
  }
10154
10126
  function getNewAudioContext() {
@@ -10475,20 +10447,6 @@ var E2EEManager = class extends eventsExports.EventEmitter {
10475
10447
  room2.localParticipant.on(ParticipantEvent.LocalSenderCreated, (sender, track) => __awaiter(this, void 0, void 0, function* () {
10476
10448
  this.setupE2EESender(track, sender);
10477
10449
  }));
10478
- room2.localParticipant.on(ParticipantEvent.LocalTrackPublished, (publication) => {
10479
- if (!isVideoTrack(publication.track) || !isSafariBased()) {
10480
- return;
10481
- }
10482
- const msg = {
10483
- kind: "updateCodec",
10484
- data: {
10485
- trackId: publication.track.mediaStreamID,
10486
- codec: mimeTypeToVideoCodecString(publication.trackInfo.codecs[0].mimeType),
10487
- participantIdentity: this.room.localParticipant.identity
10488
- }
10489
- };
10490
- this.worker.postMessage(msg);
10491
- });
10492
10450
  keyProvider.on(KeyProviderEvent.SetKey, (keyInfo) => this.postKey(keyInfo)).on(KeyProviderEvent.RatchetRequest, (participantId, keyIndex) => this.postRatchetRequest(participantId, keyIndex));
10493
10451
  }
10494
10452
  postRatchetRequest(participantIdentity, keyIndex) {
@@ -10699,7 +10657,7 @@ var DeviceManager = class _DeviceManager {
10699
10657
  return __awaiter(this, arguments, void 0, function(kind) {
10700
10658
  var _this = this;
10701
10659
  let requestPermissions = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true;
10702
- return (function* () {
10660
+ return function* () {
10703
10661
  var _a;
10704
10662
  if (((_a = _DeviceManager.userMediaPromiseMap) === null || _a === void 0 ? void 0 : _a.size) > 0) {
10705
10663
  livekitLogger.debug("awaiting getUserMedia promise");
@@ -10742,7 +10700,7 @@ var DeviceManager = class _DeviceManager {
10742
10700
  devices = devices.filter((device) => device.kind === kind);
10743
10701
  }
10744
10702
  return devices;
10745
- })();
10703
+ }();
10746
10704
  });
10747
10705
  }
10748
10706
  normalizeDeviceId(kind, deviceId, groupId) {
@@ -11051,7 +11009,7 @@ var SignalClient = class {
11051
11009
  return __awaiter(this, arguments, void 0, function() {
11052
11010
  var _this = this;
11053
11011
  let updateState = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true;
11054
- return (function* () {
11012
+ return function* () {
11055
11013
  const unlock = yield _this.closingLock.lock();
11056
11014
  try {
11057
11015
  _this.clearPingInterval();
@@ -11083,7 +11041,7 @@ var SignalClient = class {
11083
11041
  }
11084
11042
  unlock();
11085
11043
  }
11086
- })();
11044
+ }();
11087
11045
  });
11088
11046
  }
11089
11047
  // initial offer after joining
@@ -11137,7 +11095,7 @@ var SignalClient = class {
11137
11095
  return __awaiter(this, arguments, void 0, function(metadata, name) {
11138
11096
  var _this2 = this;
11139
11097
  let attributes = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
11140
- return (function* () {
11098
+ return function* () {
11141
11099
  const requestId = _this2.getNextRequestId();
11142
11100
  yield _this2.sendRequest({
11143
11101
  case: "updateMetadata",
@@ -11149,7 +11107,7 @@ var SignalClient = class {
11149
11107
  })
11150
11108
  });
11151
11109
  return requestId;
11152
- })();
11110
+ }();
11153
11111
  });
11154
11112
  }
11155
11113
  sendUpdateTrackSettings(settings) {
@@ -11229,7 +11187,7 @@ var SignalClient = class {
11229
11187
  return __awaiter(this, arguments, void 0, function(message) {
11230
11188
  var _this3 = this;
11231
11189
  let fromQueue = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false;
11232
- return (function* () {
11190
+ return function* () {
11233
11191
  const canQueue = !fromQueue && !canPassThroughQueue(message);
11234
11192
  if (canQueue && _this3.state === SignalConnectionState.RECONNECTING) {
11235
11193
  _this3.queuedRequests.push(() => __awaiter(_this3, void 0, void 0, function* () {
@@ -11265,7 +11223,7 @@ var SignalClient = class {
11265
11223
  error: e2
11266
11224
  }));
11267
11225
  }
11268
- })();
11226
+ }();
11269
11227
  });
11270
11228
  }
11271
11229
  handleSignalResponse(res) {
@@ -13214,7 +13172,7 @@ var PCTransportManager = class {
13214
13172
  return __awaiter(this, arguments, void 0, function(pcTransport, abortController) {
13215
13173
  var _this = this;
13216
13174
  let timeout = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : this.peerConnectionTimeout;
13217
- return (function* () {
13175
+ return function* () {
13218
13176
  const connectionState = pcTransport.getConnectionState();
13219
13177
  if (connectionState === "connected") {
13220
13178
  return;
@@ -13244,7 +13202,7 @@ var PCTransportManager = class {
13244
13202
  abortController === null || abortController === void 0 ? void 0 : abortController.signal.removeEventListener("abort", abortHandler);
13245
13203
  resolve();
13246
13204
  }));
13247
- })();
13205
+ }();
13248
13206
  });
13249
13207
  }
13250
13208
  };
@@ -13467,14 +13425,9 @@ var LocalTrack = class extends Track {
13467
13425
  this.providedByUser = userProvidedTrack;
13468
13426
  this.muteLock = new _();
13469
13427
  this.pauseUpstreamLock = new _();
13470
- this.trackChangeLock = new _();
13471
- this.trackChangeLock.lock().then((unlock) => __awaiter(this, void 0, void 0, function* () {
13472
- try {
13473
- yield this.setMediaStreamTrack(mediaTrack, true);
13474
- } finally {
13475
- unlock();
13476
- }
13477
- }));
13428
+ this.processorLock = new _();
13429
+ this.restartLock = new _();
13430
+ this.setMediaStreamTrack(mediaTrack, true);
13478
13431
  this._constraints = mediaTrack.getConstraints();
13479
13432
  if (constraints) {
13480
13433
  this._constraints = constraints;
@@ -13543,20 +13496,25 @@ var LocalTrack = class extends Track {
13543
13496
  }
13544
13497
  let processedTrack;
13545
13498
  if (this.processor && newTrack) {
13546
- this.log.debug("restarting processor", this.logContext);
13547
- if (this.kind === "unknown") {
13548
- throw TypeError("cannot set processor on track of unknown kind");
13549
- }
13550
- if (this.processorElement) {
13551
- attachToElement(newTrack, this.processorElement);
13552
- this.processorElement.muted = true;
13499
+ const unlock = yield this.processorLock.lock();
13500
+ try {
13501
+ this.log.debug("restarting processor", this.logContext);
13502
+ if (this.kind === "unknown") {
13503
+ throw TypeError("cannot set processor on track of unknown kind");
13504
+ }
13505
+ if (this.processorElement) {
13506
+ attachToElement(newTrack, this.processorElement);
13507
+ this.processorElement.muted = true;
13508
+ }
13509
+ yield this.processor.restart({
13510
+ track: newTrack,
13511
+ kind: this.kind,
13512
+ element: this.processorElement
13513
+ });
13514
+ processedTrack = this.processor.processedTrack;
13515
+ } finally {
13516
+ unlock();
13553
13517
  }
13554
- yield this.processor.restart({
13555
- track: newTrack,
13556
- kind: this.kind,
13557
- element: this.processorElement
13558
- });
13559
- processedTrack = this.processor.processedTrack;
13560
13518
  }
13561
13519
  if (this.sender && ((_a = this.sender.transport) === null || _a === void 0 ? void 0 : _a.state) !== "closed") {
13562
13520
  yield this.sender.replaceTrack(processedTrack !== null && processedTrack !== void 0 ? processedTrack : newTrack);
@@ -13578,7 +13536,7 @@ var LocalTrack = class extends Track {
13578
13536
  return __awaiter(this, arguments, void 0, function() {
13579
13537
  var _this = this;
13580
13538
  let timeout = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : DEFAULT_DIMENSIONS_TIMEOUT;
13581
- return (function* () {
13539
+ return function* () {
13582
13540
  var _a;
13583
13541
  if (_this.kind === Track.Kind.Audio) {
13584
13542
  throw new Error("cannot get dimensions for audio tracks");
@@ -13595,7 +13553,7 @@ var LocalTrack = class extends Track {
13595
13553
  yield sleep(50);
13596
13554
  }
13597
13555
  throw new TrackInvalidError("unable to get track dimensions after timeout");
13598
- })();
13556
+ }();
13599
13557
  });
13600
13558
  }
13601
13559
  setDeviceId(deviceId) {
@@ -13618,7 +13576,7 @@ var LocalTrack = class extends Track {
13618
13576
  return __awaiter(this, arguments, void 0, function() {
13619
13577
  var _this2 = this;
13620
13578
  let normalize = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true;
13621
- return (function* () {
13579
+ return function* () {
13622
13580
  if (_this2.source === Track.Source.ScreenShare) {
13623
13581
  return;
13624
13582
  }
@@ -13628,7 +13586,7 @@ var LocalTrack = class extends Track {
13628
13586
  } = _this2._mediaStreamTrack.getSettings();
13629
13587
  const kind = _this2.kind === Track.Kind.Audio ? "audioinput" : "videoinput";
13630
13588
  return normalize ? DeviceManager.getInstance().normalizeDeviceId(kind, deviceId, groupId) : deviceId;
13631
- })();
13589
+ }();
13632
13590
  });
13633
13591
  }
13634
13592
  mute() {
@@ -13645,35 +13603,30 @@ var LocalTrack = class extends Track {
13645
13603
  }
13646
13604
  replaceTrack(track, userProvidedOrOptions) {
13647
13605
  return __awaiter(this, void 0, void 0, function* () {
13648
- const unlock = yield this.trackChangeLock.lock();
13649
- try {
13650
- if (!this.sender) {
13651
- throw new TrackInvalidError("unable to replace an unpublished track");
13652
- }
13653
- let userProvidedTrack;
13654
- let stopProcessor;
13655
- if (typeof userProvidedOrOptions === "boolean") {
13656
- userProvidedTrack = userProvidedOrOptions;
13657
- } else if (userProvidedOrOptions !== void 0) {
13658
- userProvidedTrack = userProvidedOrOptions.userProvidedTrack;
13659
- stopProcessor = userProvidedOrOptions.stopProcessor;
13660
- }
13661
- this.providedByUser = userProvidedTrack !== null && userProvidedTrack !== void 0 ? userProvidedTrack : true;
13662
- this.log.debug("replace MediaStreamTrack", this.logContext);
13663
- yield this.setMediaStreamTrack(track);
13664
- if (stopProcessor && this.processor) {
13665
- yield this.internalStopProcessor();
13666
- }
13667
- return this;
13668
- } finally {
13669
- unlock();
13606
+ if (!this.sender) {
13607
+ throw new TrackInvalidError("unable to replace an unpublished track");
13608
+ }
13609
+ let userProvidedTrack;
13610
+ let stopProcessor;
13611
+ if (typeof userProvidedOrOptions === "boolean") {
13612
+ userProvidedTrack = userProvidedOrOptions;
13613
+ } else if (userProvidedOrOptions !== void 0) {
13614
+ userProvidedTrack = userProvidedOrOptions.userProvidedTrack;
13615
+ stopProcessor = userProvidedOrOptions.stopProcessor;
13616
+ }
13617
+ this.providedByUser = userProvidedTrack !== null && userProvidedTrack !== void 0 ? userProvidedTrack : true;
13618
+ this.log.debug("replace MediaStreamTrack", this.logContext);
13619
+ yield this.setMediaStreamTrack(track);
13620
+ if (stopProcessor && this.processor) {
13621
+ yield this.stopProcessor();
13670
13622
  }
13623
+ return this;
13671
13624
  });
13672
13625
  }
13673
13626
  restart(constraints) {
13674
13627
  return __awaiter(this, void 0, void 0, function* () {
13675
13628
  this.manuallyStopped = false;
13676
- const unlock = yield this.trackChangeLock.lock();
13629
+ const unlock = yield this.restartLock.lock();
13677
13630
  try {
13678
13631
  if (!constraints) {
13679
13632
  constraints = this._constraints;
@@ -13695,9 +13648,9 @@ var LocalTrack = class extends Track {
13695
13648
  facingMode
13696
13649
  } : true;
13697
13650
  } else {
13698
- streamConstraints.audio = deviceId ? Object.assign({
13651
+ streamConstraints.audio = deviceId ? {
13699
13652
  deviceId
13700
- }, otherConstraints) : true;
13653
+ } : true;
13701
13654
  }
13702
13655
  this.attachedElements.forEach((el) => {
13703
13656
  detachTrack(this.mediaStreamTrack, el);
@@ -13706,9 +13659,7 @@ var LocalTrack = class extends Track {
13706
13659
  this._mediaStreamTrack.stop();
13707
13660
  const mediaStream = yield navigator.mediaDevices.getUserMedia(streamConstraints);
13708
13661
  const newTrack = mediaStream.getTracks()[0];
13709
- if (this.kind === Track.Kind.Video) {
13710
- yield newTrack.applyConstraints(otherConstraints);
13711
- }
13662
+ yield newTrack.applyConstraints(otherConstraints);
13712
13663
  newTrack.addEventListener("ended", this.handleEnded);
13713
13664
  this.log.debug("re-acquired MediaStreamTrack", this.logContext);
13714
13665
  yield this.setMediaStreamTrack(newTrack);
@@ -13847,9 +13798,9 @@ var LocalTrack = class extends Track {
13847
13798
  return __awaiter(this, arguments, void 0, function(processor) {
13848
13799
  var _this3 = this;
13849
13800
  let showProcessedStreamLocally = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true;
13850
- return (function* () {
13801
+ return function* () {
13851
13802
  var _a;
13852
- const unlock = yield _this3.trackChangeLock.lock();
13803
+ const unlock = yield _this3.processorLock.lock();
13853
13804
  try {
13854
13805
  _this3.log.debug("setting up processor", _this3.logContext);
13855
13806
  const processorElement = document.createElement(_this3.kind);
@@ -13862,7 +13813,7 @@ var LocalTrack = class extends Track {
13862
13813
  yield processor.init(processorOptions);
13863
13814
  _this3.log.debug("processor initialized", _this3.logContext);
13864
13815
  if (_this3.processor) {
13865
- yield _this3.internalStopProcessor();
13816
+ yield _this3.stopProcessor();
13866
13817
  }
13867
13818
  if (_this3.kind === "unknown") {
13868
13819
  throw TypeError("cannot set processor on track of unknown kind");
@@ -13902,7 +13853,7 @@ var LocalTrack = class extends Track {
13902
13853
  } finally {
13903
13854
  unlock();
13904
13855
  }
13905
- })();
13856
+ }();
13906
13857
  });
13907
13858
  }
13908
13859
  getProcessor() {
@@ -13919,40 +13870,21 @@ var LocalTrack = class extends Track {
13919
13870
  return __awaiter(this, arguments, void 0, function() {
13920
13871
  var _this4 = this;
13921
13872
  let keepElement = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true;
13922
- return (function* () {
13923
- const unlock = yield _this4.trackChangeLock.lock();
13924
- try {
13925
- yield _this4.internalStopProcessor(keepElement);
13926
- } finally {
13927
- unlock();
13928
- }
13929
- })();
13930
- });
13931
- }
13932
- /**
13933
- * @internal
13934
- * This method assumes the caller has acquired a trackChangeLock already.
13935
- * The public facing method for stopping the processor is `stopProcessor` and it wraps this method in the trackChangeLock.
13936
- */
13937
- internalStopProcessor() {
13938
- return __awaiter(this, arguments, void 0, function() {
13939
- var _this5 = this;
13940
- let keepElement = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true;
13941
- return (function* () {
13873
+ return function* () {
13942
13874
  var _a, _b;
13943
- if (!_this5.processor) return;
13944
- _this5.log.debug("stopping processor", _this5.logContext);
13945
- (_a = _this5.processor.processedTrack) === null || _a === void 0 ? void 0 : _a.stop();
13946
- yield _this5.processor.destroy();
13947
- _this5.processor = void 0;
13875
+ if (!_this4.processor) return;
13876
+ _this4.log.debug("stopping processor", _this4.logContext);
13877
+ (_a = _this4.processor.processedTrack) === null || _a === void 0 ? void 0 : _a.stop();
13878
+ yield _this4.processor.destroy();
13879
+ _this4.processor = void 0;
13948
13880
  if (!keepElement) {
13949
- (_b = _this5.processorElement) === null || _b === void 0 ? void 0 : _b.remove();
13950
- _this5.processorElement = void 0;
13881
+ (_b = _this4.processorElement) === null || _b === void 0 ? void 0 : _b.remove();
13882
+ _this4.processorElement = void 0;
13951
13883
  }
13952
- yield _this5._mediaStreamTrack.applyConstraints(_this5._constraints);
13953
- yield _this5.setMediaStreamTrack(_this5._mediaStreamTrack, true);
13954
- _this5.emit(TrackEvent.TrackProcessorUpdate);
13955
- })();
13884
+ yield _this4._mediaStreamTrack.applyConstraints(_this4._constraints);
13885
+ yield _this4.setMediaStreamTrack(_this4._mediaStreamTrack, true);
13886
+ _this4.emit(TrackEvent.TrackProcessorUpdate);
13887
+ }();
13956
13888
  });
13957
13889
  }
13958
13890
  /** @internal */
@@ -14140,13 +14072,13 @@ var LocalAudioTrack = class extends LocalTrack {
14140
14072
  setProcessor(processor) {
14141
14073
  return __awaiter(this, void 0, void 0, function* () {
14142
14074
  var _a;
14143
- const unlock = yield this.trackChangeLock.lock();
14075
+ const unlock = yield this.processorLock.lock();
14144
14076
  try {
14145
14077
  if (!isReactNative() && !this.audioContext) {
14146
14078
  throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");
14147
14079
  }
14148
14080
  if (this.processor) {
14149
- yield this.internalStopProcessor();
14081
+ yield this.stopProcessor();
14150
14082
  }
14151
14083
  const processorOptions = {
14152
14084
  kind: this.kind,
@@ -14801,7 +14733,7 @@ var LocalVideoTrack = class extends LocalTrack {
14801
14733
  return __awaiter(this, arguments, void 0, function(processor) {
14802
14734
  var _this = this;
14803
14735
  let showProcessedStreamLocally = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true;
14804
- return (function* () {
14736
+ return function* () {
14805
14737
  var _a, e_4, _b, _c;
14806
14738
  var _d, _e;
14807
14739
  yield _super.setProcessor.call(_this, processor, showProcessedStreamLocally);
@@ -14825,7 +14757,7 @@ var LocalVideoTrack = class extends LocalTrack {
14825
14757
  }
14826
14758
  }
14827
14759
  }
14828
- })();
14760
+ }();
14829
14761
  });
14830
14762
  }
14831
14763
  setDegradationPreference(preference) {
@@ -15176,7 +15108,7 @@ var RTCEngine = class extends eventsExports.EventEmitter {
15176
15108
  let {
15177
15109
  channel
15178
15110
  } = _ref;
15179
- return (function* () {
15111
+ return function* () {
15180
15112
  if (!channel) {
15181
15113
  return;
15182
15114
  }
@@ -15189,7 +15121,7 @@ var RTCEngine = class extends eventsExports.EventEmitter {
15189
15121
  }
15190
15122
  _this.log.debug("on data channel ".concat(channel.id, ", ").concat(channel.label), _this.logContext);
15191
15123
  channel.onmessage = _this.handleDataMessage;
15192
- })();
15124
+ }();
15193
15125
  });
15194
15126
  this.handleDataMessage = (message) => __awaiter(this, void 0, void 0, function* () {
15195
15127
  var _a2, _b;
@@ -16072,7 +16004,7 @@ var RTCEngine = class extends eventsExports.EventEmitter {
16072
16004
  return __awaiter(this, arguments, void 0, function(kind) {
16073
16005
  var _this2 = this;
16074
16006
  let subscriber = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : this.subscriberPrimary;
16075
- return (function* () {
16007
+ return function* () {
16076
16008
  var _a;
16077
16009
  if (!_this2.pcManager) {
16078
16010
  throw new UnexpectedConnectionState("PC manager is closed");
@@ -16105,7 +16037,7 @@ var RTCEngine = class extends eventsExports.EventEmitter {
16105
16037
  yield sleep(50);
16106
16038
  }
16107
16039
  throw new ConnectionError("could not establish ".concat(transportName, " connection, state: ").concat(transport.getICEConnectionState()), ConnectionErrorReason.InternalError);
16108
- })();
16040
+ }();
16109
16041
  });
16110
16042
  }
16111
16043
  ensurePublisherConnected(kind) {
@@ -16362,72 +16294,30 @@ var BaseStreamReader = class {
16362
16294
  get info() {
16363
16295
  return this._info;
16364
16296
  }
16365
- /** @internal */
16366
- validateBytesReceived() {
16367
- let doneReceiving = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : false;
16368
- if (typeof this.totalByteSize !== "number" || this.totalByteSize === 0) {
16369
- return;
16370
- }
16371
- if (doneReceiving && this.bytesReceived < this.totalByteSize) {
16372
- throw new DataStreamError("Not enough chunk(s) received - expected ".concat(this.totalByteSize, " bytes of data total, only received ").concat(this.bytesReceived, " bytes"), DataStreamErrorReason.Incomplete);
16373
- } else if (this.bytesReceived > this.totalByteSize) {
16374
- throw new DataStreamError("Extra chunk(s) received - expected ".concat(this.totalByteSize, " bytes of data total, received ").concat(this.bytesReceived, " bytes"), DataStreamErrorReason.LengthExceeded);
16375
- }
16376
- }
16377
- constructor(info, stream, totalByteSize, outOfBandFailureRejectingFuture) {
16297
+ constructor(info, stream, totalByteSize) {
16378
16298
  this.reader = stream;
16379
16299
  this.totalByteSize = totalByteSize;
16380
16300
  this._info = info;
16381
16301
  this.bytesReceived = 0;
16382
- this.outOfBandFailureRejectingFuture = outOfBandFailureRejectingFuture;
16383
16302
  }
16384
16303
  };
16385
16304
  var ByteStreamReader = class extends BaseStreamReader {
16386
16305
  handleChunkReceived(chunk) {
16387
16306
  var _a;
16388
16307
  this.bytesReceived += chunk.content.byteLength;
16389
- this.validateBytesReceived();
16390
16308
  const currentProgress = this.totalByteSize ? this.bytesReceived / this.totalByteSize : void 0;
16391
16309
  (_a = this.onProgress) === null || _a === void 0 ? void 0 : _a.call(this, currentProgress);
16392
16310
  }
16393
16311
  [Symbol.asyncIterator]() {
16394
16312
  const reader = this.reader.getReader();
16395
- let rejectingSignalFuture = new Future();
16396
- let activeSignal = null;
16397
- let onAbort = null;
16398
- if (this.signal) {
16399
- const signal = this.signal;
16400
- onAbort = () => {
16401
- var _a;
16402
- (_a = rejectingSignalFuture.reject) === null || _a === void 0 ? void 0 : _a.call(rejectingSignalFuture, signal.reason);
16403
- };
16404
- signal.addEventListener("abort", onAbort);
16405
- activeSignal = signal;
16406
- }
16407
- const cleanup = () => {
16408
- reader.releaseLock();
16409
- if (activeSignal && onAbort) {
16410
- activeSignal.removeEventListener("abort", onAbort);
16411
- }
16412
- this.signal = void 0;
16413
- };
16414
16313
  return {
16415
16314
  next: () => __awaiter(this, void 0, void 0, function* () {
16416
- var _a, _b;
16417
16315
  try {
16418
16316
  const {
16419
16317
  done,
16420
16318
  value
16421
- } = yield Promise.race([
16422
- reader.read(),
16423
- // Rejects if this.signal is aborted
16424
- rejectingSignalFuture.promise,
16425
- // Rejects if something external says it should, like a participant disconnecting, etc
16426
- (_b = (_a = this.outOfBandFailureRejectingFuture) === null || _a === void 0 ? void 0 : _a.promise) !== null && _b !== void 0 ? _b : new Promise(() => {
16427
- })
16428
- ]);
16319
+ } = yield reader.read();
16429
16320
  if (done) {
16430
- this.validateBytesReceived(true);
16431
16321
  return {
16432
16322
  done: true,
16433
16323
  value: void 0
@@ -16439,16 +16329,16 @@ var ByteStreamReader = class extends BaseStreamReader {
16439
16329
  value: value.content
16440
16330
  };
16441
16331
  }
16442
- } catch (err) {
16443
- cleanup();
16444
- throw err;
16332
+ } catch (error) {
16333
+ return {
16334
+ done: true,
16335
+ value: void 0
16336
+ };
16445
16337
  }
16446
16338
  }),
16447
- // note: `return` runs only for premature exits, see:
16448
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#errors_during_iteration
16449
16339
  return() {
16450
16340
  return __awaiter(this, void 0, void 0, function* () {
16451
- cleanup();
16341
+ reader.releaseLock();
16452
16342
  return {
16453
16343
  done: true,
16454
16344
  value: void 0
@@ -16457,45 +16347,29 @@ var ByteStreamReader = class extends BaseStreamReader {
16457
16347
  }
16458
16348
  };
16459
16349
  }
16460
- /**
16461
- * Injects an AbortSignal, which if aborted, will terminate the currently active
16462
- * stream iteration operation.
16463
- *
16464
- * Note that when using AbortSignal.timeout(...), the timeout applies across
16465
- * the whole iteration operation, not just one individual chunk read.
16466
- */
16467
- withAbortSignal(signal) {
16468
- this.signal = signal;
16469
- return this;
16470
- }
16471
16350
  readAll() {
16472
- return __awaiter(this, arguments, void 0, function() {
16473
- var _this = this;
16474
- let opts = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
16475
- return (function* () {
16476
- var _a, e_1, _b, _c;
16477
- let chunks = /* @__PURE__ */ new Set();
16478
- const iterator = opts.signal ? _this.withAbortSignal(opts.signal) : _this;
16351
+ return __awaiter(this, void 0, void 0, function* () {
16352
+ var _a, e_1, _b, _c;
16353
+ let chunks = /* @__PURE__ */ new Set();
16354
+ try {
16355
+ for (var _d = true, _e = __asyncValues(this), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) {
16356
+ _c = _f.value;
16357
+ _d = false;
16358
+ const chunk = _c;
16359
+ chunks.add(chunk);
16360
+ }
16361
+ } catch (e_1_1) {
16362
+ e_1 = {
16363
+ error: e_1_1
16364
+ };
16365
+ } finally {
16479
16366
  try {
16480
- for (var _d = true, iterator_1 = __asyncValues(iterator), iterator_1_1; iterator_1_1 = yield iterator_1.next(), _a = iterator_1_1.done, !_a; _d = true) {
16481
- _c = iterator_1_1.value;
16482
- _d = false;
16483
- const chunk = _c;
16484
- chunks.add(chunk);
16485
- }
16486
- } catch (e_1_1) {
16487
- e_1 = {
16488
- error: e_1_1
16489
- };
16367
+ if (!_d && !_a && (_b = _e.return)) yield _b.call(_e);
16490
16368
  } finally {
16491
- try {
16492
- if (!_d && !_a && (_b = iterator_1.return)) yield _b.call(iterator_1);
16493
- } finally {
16494
- if (e_1) throw e_1.error;
16495
- }
16369
+ if (e_1) throw e_1.error;
16496
16370
  }
16497
- return Array.from(chunks);
16498
- })();
16371
+ }
16372
+ return Array.from(chunks);
16499
16373
  });
16500
16374
  }
16501
16375
  };
@@ -16504,8 +16378,8 @@ var TextStreamReader = class extends BaseStreamReader {
16504
16378
  * A TextStreamReader instance can be used as an AsyncIterator that returns the entire string
16505
16379
  * that has been received up to the current point in time.
16506
16380
  */
16507
- constructor(info, stream, totalChunkCount, outOfBandFailureRejectingFuture) {
16508
- super(info, stream, totalChunkCount, outOfBandFailureRejectingFuture);
16381
+ constructor(info, stream, totalChunkCount) {
16382
+ super(info, stream, totalChunkCount);
16509
16383
  this.receivedChunks = /* @__PURE__ */ new Map();
16510
16384
  }
16511
16385
  handleChunkReceived(chunk) {
@@ -16517,7 +16391,6 @@ var TextStreamReader = class extends BaseStreamReader {
16517
16391
  }
16518
16392
  this.receivedChunks.set(index, chunk);
16519
16393
  this.bytesReceived += chunk.content.byteLength;
16520
- this.validateBytesReceived();
16521
16394
  const currentProgress = this.totalByteSize ? this.bytesReceived / this.totalByteSize : void 0;
16522
16395
  (_a = this.onProgress) === null || _a === void 0 ? void 0 : _a.call(this, currentProgress);
16523
16396
  }
@@ -16528,72 +16401,36 @@ var TextStreamReader = class extends BaseStreamReader {
16528
16401
  */
16529
16402
  [Symbol.asyncIterator]() {
16530
16403
  const reader = this.reader.getReader();
16531
- const decoder = new TextDecoder("utf-8", {
16532
- fatal: true
16533
- });
16534
- let rejectingSignalFuture = new Future();
16535
- let activeSignal = null;
16536
- let onAbort = null;
16537
- if (this.signal) {
16538
- const signal = this.signal;
16539
- onAbort = () => {
16540
- var _a;
16541
- (_a = rejectingSignalFuture.reject) === null || _a === void 0 ? void 0 : _a.call(rejectingSignalFuture, signal.reason);
16542
- };
16543
- signal.addEventListener("abort", onAbort);
16544
- activeSignal = signal;
16545
- }
16546
- const cleanup = () => {
16547
- reader.releaseLock();
16548
- if (activeSignal && onAbort) {
16549
- activeSignal.removeEventListener("abort", onAbort);
16550
- }
16551
- this.signal = void 0;
16552
- };
16404
+ const decoder = new TextDecoder();
16553
16405
  return {
16554
16406
  next: () => __awaiter(this, void 0, void 0, function* () {
16555
- var _a, _b;
16556
16407
  try {
16557
16408
  const {
16558
16409
  done,
16559
16410
  value
16560
- } = yield Promise.race([
16561
- reader.read(),
16562
- // Rejects if this.signal is aborted
16563
- rejectingSignalFuture.promise,
16564
- // Rejects if something external says it should, like a participant disconnecting, etc
16565
- (_b = (_a = this.outOfBandFailureRejectingFuture) === null || _a === void 0 ? void 0 : _a.promise) !== null && _b !== void 0 ? _b : new Promise(() => {
16566
- })
16567
- ]);
16411
+ } = yield reader.read();
16568
16412
  if (done) {
16569
- this.validateBytesReceived(true);
16570
16413
  return {
16571
16414
  done: true,
16572
16415
  value: void 0
16573
16416
  };
16574
16417
  } else {
16575
16418
  this.handleChunkReceived(value);
16576
- let decodedResult;
16577
- try {
16578
- decodedResult = decoder.decode(value.content);
16579
- } catch (err) {
16580
- throw new DataStreamError("Cannot decode datastream chunk ".concat(value.chunkIndex, " as text: ").concat(err), DataStreamErrorReason.DecodeFailed);
16581
- }
16582
16419
  return {
16583
16420
  done: false,
16584
- value: decodedResult
16421
+ value: decoder.decode(value.content)
16585
16422
  };
16586
16423
  }
16587
- } catch (err) {
16588
- cleanup();
16589
- throw err;
16424
+ } catch (error) {
16425
+ return {
16426
+ done: true,
16427
+ value: void 0
16428
+ };
16590
16429
  }
16591
16430
  }),
16592
- // note: `return` runs only for premature exits, see:
16593
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#errors_during_iteration
16594
16431
  return() {
16595
16432
  return __awaiter(this, void 0, void 0, function* () {
16596
- cleanup();
16433
+ reader.releaseLock();
16597
16434
  return {
16598
16435
  done: true,
16599
16436
  value: void 0
@@ -16602,597 +16439,142 @@ var TextStreamReader = class extends BaseStreamReader {
16602
16439
  }
16603
16440
  };
16604
16441
  }
16605
- /**
16606
- * Injects an AbortSignal, which if aborted, will terminate the currently active
16607
- * stream iteration operation.
16608
- *
16609
- * Note that when using AbortSignal.timeout(...), the timeout applies across
16610
- * the whole iteration operation, not just one individual chunk read.
16611
- */
16612
- withAbortSignal(signal) {
16613
- this.signal = signal;
16614
- return this;
16615
- }
16616
16442
  readAll() {
16617
- return __awaiter(this, arguments, void 0, function() {
16618
- var _this2 = this;
16619
- let opts = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
16620
- return (function* () {
16621
- var _a, e_2, _b, _c;
16622
- let finalString = "";
16623
- const iterator = opts.signal ? _this2.withAbortSignal(opts.signal) : _this2;
16443
+ return __awaiter(this, void 0, void 0, function* () {
16444
+ var _a, e_2, _b, _c;
16445
+ let finalString = "";
16446
+ try {
16447
+ for (var _d = true, _e = __asyncValues(this), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) {
16448
+ _c = _f.value;
16449
+ _d = false;
16450
+ const chunk = _c;
16451
+ finalString += chunk;
16452
+ }
16453
+ } catch (e_2_1) {
16454
+ e_2 = {
16455
+ error: e_2_1
16456
+ };
16457
+ } finally {
16624
16458
  try {
16625
- for (var _d = true, iterator_2 = __asyncValues(iterator), iterator_2_1; iterator_2_1 = yield iterator_2.next(), _a = iterator_2_1.done, !_a; _d = true) {
16626
- _c = iterator_2_1.value;
16627
- _d = false;
16628
- const chunk = _c;
16629
- finalString += chunk;
16630
- }
16631
- } catch (e_2_1) {
16632
- e_2 = {
16633
- error: e_2_1
16634
- };
16459
+ if (!_d && !_a && (_b = _e.return)) yield _b.call(_e);
16635
16460
  } finally {
16636
- try {
16637
- if (!_d && !_a && (_b = iterator_2.return)) yield _b.call(iterator_2);
16638
- } finally {
16639
- if (e_2) throw e_2.error;
16640
- }
16461
+ if (e_2) throw e_2.error;
16641
16462
  }
16642
- return finalString;
16643
- })();
16463
+ }
16464
+ return finalString;
16644
16465
  });
16645
16466
  }
16646
16467
  };
16647
- var IncomingDataStreamManager = class {
16648
- constructor() {
16649
- this.log = livekitLogger;
16650
- this.byteStreamControllers = /* @__PURE__ */ new Map();
16651
- this.textStreamControllers = /* @__PURE__ */ new Map();
16652
- this.byteStreamHandlers = /* @__PURE__ */ new Map();
16653
- this.textStreamHandlers = /* @__PURE__ */ new Map();
16468
+ var BaseStreamWriter = class {
16469
+ constructor(writableStream, info, onClose) {
16470
+ this.writableStream = writableStream;
16471
+ this.defaultWriter = writableStream.getWriter();
16472
+ this.onClose = onClose;
16473
+ this.info = info;
16654
16474
  }
16655
- registerTextStreamHandler(topic, callback) {
16656
- if (this.textStreamHandlers.has(topic)) {
16657
- throw new DataStreamError('A text stream handler for topic "'.concat(topic, '" has already been set.'), DataStreamErrorReason.HandlerAlreadyRegistered);
16658
- }
16659
- this.textStreamHandlers.set(topic, callback);
16475
+ write(chunk) {
16476
+ return this.defaultWriter.write(chunk);
16660
16477
  }
16661
- unregisterTextStreamHandler(topic) {
16662
- this.textStreamHandlers.delete(topic);
16478
+ close() {
16479
+ return __awaiter(this, void 0, void 0, function* () {
16480
+ var _a;
16481
+ yield this.defaultWriter.close();
16482
+ this.defaultWriter.releaseLock();
16483
+ (_a = this.onClose) === null || _a === void 0 ? void 0 : _a.call(this);
16484
+ });
16663
16485
  }
16664
- registerByteStreamHandler(topic, callback) {
16665
- if (this.byteStreamHandlers.has(topic)) {
16666
- throw new DataStreamError('A byte stream handler for topic "'.concat(topic, '" has already been set.'), DataStreamErrorReason.HandlerAlreadyRegistered);
16486
+ };
16487
+ var TextStreamWriter = class extends BaseStreamWriter {
16488
+ };
16489
+ var ByteStreamWriter = class extends BaseStreamWriter {
16490
+ };
16491
+ var RemoteTrack = class extends Track {
16492
+ constructor(mediaTrack, sid, kind, receiver, loggerOptions) {
16493
+ super(mediaTrack, kind, loggerOptions);
16494
+ this.sid = sid;
16495
+ this.receiver = receiver;
16496
+ }
16497
+ get isLocal() {
16498
+ return false;
16499
+ }
16500
+ /** @internal */
16501
+ setMuted(muted) {
16502
+ if (this.isMuted !== muted) {
16503
+ this.isMuted = muted;
16504
+ this._mediaStreamTrack.enabled = !muted;
16505
+ this.emit(muted ? TrackEvent.Muted : TrackEvent.Unmuted, this);
16667
16506
  }
16668
- this.byteStreamHandlers.set(topic, callback);
16669
16507
  }
16670
- unregisterByteStreamHandler(topic) {
16671
- this.byteStreamHandlers.delete(topic);
16508
+ /** @internal */
16509
+ setMediaStream(stream) {
16510
+ this.mediaStream = stream;
16511
+ const onRemoveTrack = (event) => {
16512
+ if (event.track === this._mediaStreamTrack) {
16513
+ stream.removeEventListener("removetrack", onRemoveTrack);
16514
+ if (this.receiver && "playoutDelayHint" in this.receiver) {
16515
+ this.receiver.playoutDelayHint = void 0;
16516
+ }
16517
+ this.receiver = void 0;
16518
+ this._currentBitrate = 0;
16519
+ this.emit(TrackEvent.Ended, this);
16520
+ }
16521
+ };
16522
+ stream.addEventListener("removetrack", onRemoveTrack);
16672
16523
  }
16673
- clearHandlersAndControllers() {
16674
- this.byteStreamControllers.clear();
16675
- this.textStreamControllers.clear();
16676
- this.byteStreamHandlers.clear();
16677
- this.textStreamHandlers.clear();
16524
+ start() {
16525
+ this.startMonitor();
16526
+ super.enable();
16678
16527
  }
16679
- validateParticipantHasNoActiveDataStreams(participantIdentity) {
16680
- var _a, _b, _c, _d;
16681
- const textStreamsBeingSentByDisconnectingParticipant = Array.from(this.textStreamControllers.entries()).filter((entry) => entry[1].sendingParticipantIdentity === participantIdentity);
16682
- const byteStreamsBeingSentByDisconnectingParticipant = Array.from(this.byteStreamControllers.entries()).filter((entry) => entry[1].sendingParticipantIdentity === participantIdentity);
16683
- if (textStreamsBeingSentByDisconnectingParticipant.length > 0 || byteStreamsBeingSentByDisconnectingParticipant.length > 0) {
16684
- const abnormalEndError = new DataStreamError("Participant ".concat(participantIdentity, " unexpectedly disconnected in the middle of sending data"), DataStreamErrorReason.AbnormalEnd);
16685
- for (const [id, controller] of byteStreamsBeingSentByDisconnectingParticipant) {
16686
- (_b = (_a = controller.outOfBandFailureRejectingFuture).reject) === null || _b === void 0 ? void 0 : _b.call(_a, abnormalEndError);
16687
- this.byteStreamControllers.delete(id);
16528
+ stop() {
16529
+ this.stopMonitor();
16530
+ super.disable();
16531
+ }
16532
+ /**
16533
+ * Gets the RTCStatsReport for the RemoteTrack's underlying RTCRtpReceiver
16534
+ * See https://developer.mozilla.org/en-US/docs/Web/API/RTCStatsReport
16535
+ *
16536
+ * @returns Promise<RTCStatsReport> | undefined
16537
+ */
16538
+ getRTCStatsReport() {
16539
+ return __awaiter(this, void 0, void 0, function* () {
16540
+ var _a;
16541
+ if (!((_a = this.receiver) === null || _a === void 0 ? void 0 : _a.getStats)) {
16542
+ return;
16688
16543
  }
16689
- for (const [id, controller] of textStreamsBeingSentByDisconnectingParticipant) {
16690
- (_d = (_c = controller.outOfBandFailureRejectingFuture).reject) === null || _d === void 0 ? void 0 : _d.call(_c, abnormalEndError);
16691
- this.textStreamControllers.delete(id);
16544
+ const statsReport = yield this.receiver.getStats();
16545
+ return statsReport;
16546
+ });
16547
+ }
16548
+ /**
16549
+ * Allows to set a playout delay (in seconds) for this track.
16550
+ * A higher value allows for more buffering of the track in the browser
16551
+ * and will result in a delay of media being played back of `delayInSeconds`
16552
+ */
16553
+ setPlayoutDelay(delayInSeconds) {
16554
+ if (this.receiver) {
16555
+ if ("playoutDelayHint" in this.receiver) {
16556
+ this.receiver.playoutDelayHint = delayInSeconds;
16557
+ } else {
16558
+ this.log.warn("Playout delay not supported in this browser");
16692
16559
  }
16560
+ } else {
16561
+ this.log.warn("Cannot set playout delay, track already ended");
16693
16562
  }
16694
16563
  }
16695
- handleDataStreamPacket(packet) {
16696
- return __awaiter(this, void 0, void 0, function* () {
16697
- switch (packet.value.case) {
16698
- case "streamHeader":
16699
- return this.handleStreamHeader(packet.value.value, packet.participantIdentity);
16700
- case "streamChunk":
16701
- return this.handleStreamChunk(packet.value.value);
16702
- case "streamTrailer":
16703
- return this.handleStreamTrailer(packet.value.value);
16704
- default:
16705
- throw new Error('DataPacket of value "'.concat(packet.value.case, '" is not data stream related!'));
16564
+ /**
16565
+ * Returns the current playout delay (in seconds) of this track.
16566
+ */
16567
+ getPlayoutDelay() {
16568
+ if (this.receiver) {
16569
+ if ("playoutDelayHint" in this.receiver) {
16570
+ return this.receiver.playoutDelayHint;
16571
+ } else {
16572
+ this.log.warn("Playout delay not supported in this browser");
16706
16573
  }
16707
- });
16708
- }
16709
- handleStreamHeader(streamHeader, participantIdentity) {
16710
- return __awaiter(this, void 0, void 0, function* () {
16711
- var _a;
16712
- if (streamHeader.contentHeader.case === "byteHeader") {
16713
- const streamHandlerCallback = this.byteStreamHandlers.get(streamHeader.topic);
16714
- if (!streamHandlerCallback) {
16715
- this.log.debug("ignoring incoming byte stream due to no handler for topic", streamHeader.topic);
16716
- return;
16717
- }
16718
- let streamController;
16719
- const outOfBandFailureRejectingFuture = new Future();
16720
- const info = {
16721
- id: streamHeader.streamId,
16722
- name: (_a = streamHeader.contentHeader.value.name) !== null && _a !== void 0 ? _a : "unknown",
16723
- mimeType: streamHeader.mimeType,
16724
- size: streamHeader.totalLength ? Number(streamHeader.totalLength) : void 0,
16725
- topic: streamHeader.topic,
16726
- timestamp: bigIntToNumber(streamHeader.timestamp),
16727
- attributes: streamHeader.attributes
16728
- };
16729
- const stream = new ReadableStream({
16730
- start: (controller) => {
16731
- streamController = controller;
16732
- if (this.textStreamControllers.has(streamHeader.streamId)) {
16733
- throw new DataStreamError("A data stream read is already in progress for a stream with id ".concat(streamHeader.streamId, "."), DataStreamErrorReason.AlreadyOpened);
16734
- }
16735
- this.byteStreamControllers.set(streamHeader.streamId, {
16736
- info,
16737
- controller: streamController,
16738
- startTime: Date.now(),
16739
- sendingParticipantIdentity: participantIdentity,
16740
- outOfBandFailureRejectingFuture
16741
- });
16742
- }
16743
- });
16744
- streamHandlerCallback(new ByteStreamReader(info, stream, bigIntToNumber(streamHeader.totalLength), outOfBandFailureRejectingFuture), {
16745
- identity: participantIdentity
16746
- });
16747
- } else if (streamHeader.contentHeader.case === "textHeader") {
16748
- const streamHandlerCallback = this.textStreamHandlers.get(streamHeader.topic);
16749
- if (!streamHandlerCallback) {
16750
- this.log.debug("ignoring incoming text stream due to no handler for topic", streamHeader.topic);
16751
- return;
16752
- }
16753
- let streamController;
16754
- const outOfBandFailureRejectingFuture = new Future();
16755
- const info = {
16756
- id: streamHeader.streamId,
16757
- mimeType: streamHeader.mimeType,
16758
- size: streamHeader.totalLength ? Number(streamHeader.totalLength) : void 0,
16759
- topic: streamHeader.topic,
16760
- timestamp: Number(streamHeader.timestamp),
16761
- attributes: streamHeader.attributes
16762
- };
16763
- const stream = new ReadableStream({
16764
- start: (controller) => {
16765
- streamController = controller;
16766
- if (this.textStreamControllers.has(streamHeader.streamId)) {
16767
- throw new DataStreamError("A data stream read is already in progress for a stream with id ".concat(streamHeader.streamId, "."), DataStreamErrorReason.AlreadyOpened);
16768
- }
16769
- this.textStreamControllers.set(streamHeader.streamId, {
16770
- info,
16771
- controller: streamController,
16772
- startTime: Date.now(),
16773
- sendingParticipantIdentity: participantIdentity,
16774
- outOfBandFailureRejectingFuture
16775
- });
16776
- }
16777
- });
16778
- streamHandlerCallback(new TextStreamReader(info, stream, bigIntToNumber(streamHeader.totalLength), outOfBandFailureRejectingFuture), {
16779
- identity: participantIdentity
16780
- });
16781
- }
16782
- });
16783
- }
16784
- handleStreamChunk(chunk) {
16785
- const fileBuffer = this.byteStreamControllers.get(chunk.streamId);
16786
- if (fileBuffer) {
16787
- if (chunk.content.length > 0) {
16788
- fileBuffer.controller.enqueue(chunk);
16789
- }
16790
- }
16791
- const textBuffer = this.textStreamControllers.get(chunk.streamId);
16792
- if (textBuffer) {
16793
- if (chunk.content.length > 0) {
16794
- textBuffer.controller.enqueue(chunk);
16795
- }
16796
- }
16797
- }
16798
- handleStreamTrailer(trailer) {
16799
- const textBuffer = this.textStreamControllers.get(trailer.streamId);
16800
- if (textBuffer) {
16801
- textBuffer.info.attributes = Object.assign(Object.assign({}, textBuffer.info.attributes), trailer.attributes);
16802
- textBuffer.controller.close();
16803
- this.textStreamControllers.delete(trailer.streamId);
16804
- }
16805
- const fileBuffer = this.byteStreamControllers.get(trailer.streamId);
16806
- if (fileBuffer) {
16807
- {
16808
- fileBuffer.info.attributes = Object.assign(Object.assign({}, fileBuffer.info.attributes), trailer.attributes);
16809
- fileBuffer.controller.close();
16810
- this.byteStreamControllers.delete(trailer.streamId);
16811
- }
16812
- }
16813
- }
16814
- };
16815
- var BaseStreamWriter = class {
16816
- constructor(writableStream, info, onClose) {
16817
- this.writableStream = writableStream;
16818
- this.defaultWriter = writableStream.getWriter();
16819
- this.onClose = onClose;
16820
- this.info = info;
16821
- }
16822
- write(chunk) {
16823
- return this.defaultWriter.write(chunk);
16824
- }
16825
- close() {
16826
- return __awaiter(this, void 0, void 0, function* () {
16827
- var _a;
16828
- yield this.defaultWriter.close();
16829
- this.defaultWriter.releaseLock();
16830
- (_a = this.onClose) === null || _a === void 0 ? void 0 : _a.call(this);
16831
- });
16832
- }
16833
- };
16834
- var TextStreamWriter = class extends BaseStreamWriter {
16835
- };
16836
- var ByteStreamWriter = class extends BaseStreamWriter {
16837
- };
16838
- var STREAM_CHUNK_SIZE = 15e3;
16839
- var OutgoingDataStreamManager = class {
16840
- constructor(engine, log2) {
16841
- this.engine = engine;
16842
- this.log = log2;
16843
- }
16844
- setupEngine(engine) {
16845
- this.engine = engine;
16846
- }
16847
- /** {@inheritDoc LocalParticipant.sendText} */
16848
- sendText(text, options) {
16849
- return __awaiter(this, void 0, void 0, function* () {
16850
- var _a;
16851
- const streamId = crypto.randomUUID();
16852
- const textInBytes = new TextEncoder().encode(text);
16853
- const totalTextLength = textInBytes.byteLength;
16854
- const fileIds = (_a = options === null || options === void 0 ? void 0 : options.attachments) === null || _a === void 0 ? void 0 : _a.map(() => crypto.randomUUID());
16855
- const progresses = new Array(fileIds ? fileIds.length + 1 : 1).fill(0);
16856
- const handleProgress = (progress, idx) => {
16857
- var _a2;
16858
- progresses[idx] = progress;
16859
- const totalProgress = progresses.reduce((acc, val) => acc + val, 0);
16860
- (_a2 = options === null || options === void 0 ? void 0 : options.onProgress) === null || _a2 === void 0 ? void 0 : _a2.call(options, totalProgress);
16861
- };
16862
- const writer2 = yield this.streamText({
16863
- streamId,
16864
- totalSize: totalTextLength,
16865
- destinationIdentities: options === null || options === void 0 ? void 0 : options.destinationIdentities,
16866
- topic: options === null || options === void 0 ? void 0 : options.topic,
16867
- attachedStreamIds: fileIds,
16868
- attributes: options === null || options === void 0 ? void 0 : options.attributes
16869
- });
16870
- yield writer2.write(text);
16871
- handleProgress(1, 0);
16872
- yield writer2.close();
16873
- if ((options === null || options === void 0 ? void 0 : options.attachments) && fileIds) {
16874
- yield Promise.all(options.attachments.map((file, idx) => __awaiter(this, void 0, void 0, function* () {
16875
- return this._sendFile(fileIds[idx], file, {
16876
- topic: options.topic,
16877
- mimeType: file.type,
16878
- onProgress: (progress) => {
16879
- handleProgress(progress, idx + 1);
16880
- }
16881
- });
16882
- })));
16883
- }
16884
- return writer2.info;
16885
- });
16886
- }
16887
- /**
16888
- * @internal
16889
- * @experimental CAUTION, might get removed in a minor release
16890
- */
16891
- streamText(options) {
16892
- return __awaiter(this, void 0, void 0, function* () {
16893
- var _a, _b;
16894
- const streamId = (_a = options === null || options === void 0 ? void 0 : options.streamId) !== null && _a !== void 0 ? _a : crypto.randomUUID();
16895
- const info = {
16896
- id: streamId,
16897
- mimeType: "text/plain",
16898
- timestamp: Date.now(),
16899
- topic: (_b = options === null || options === void 0 ? void 0 : options.topic) !== null && _b !== void 0 ? _b : "",
16900
- size: options === null || options === void 0 ? void 0 : options.totalSize,
16901
- attributes: options === null || options === void 0 ? void 0 : options.attributes
16902
- };
16903
- const header = new DataStream_Header({
16904
- streamId,
16905
- mimeType: info.mimeType,
16906
- topic: info.topic,
16907
- timestamp: numberToBigInt(info.timestamp),
16908
- totalLength: numberToBigInt(options === null || options === void 0 ? void 0 : options.totalSize),
16909
- attributes: info.attributes,
16910
- contentHeader: {
16911
- case: "textHeader",
16912
- value: new DataStream_TextHeader({
16913
- version: options === null || options === void 0 ? void 0 : options.version,
16914
- attachedStreamIds: options === null || options === void 0 ? void 0 : options.attachedStreamIds,
16915
- replyToStreamId: options === null || options === void 0 ? void 0 : options.replyToStreamId,
16916
- operationType: (options === null || options === void 0 ? void 0 : options.type) === "update" ? DataStream_OperationType.UPDATE : DataStream_OperationType.CREATE
16917
- })
16918
- }
16919
- });
16920
- const destinationIdentities = options === null || options === void 0 ? void 0 : options.destinationIdentities;
16921
- const packet = new DataPacket({
16922
- destinationIdentities,
16923
- value: {
16924
- case: "streamHeader",
16925
- value: header
16926
- }
16927
- });
16928
- yield this.engine.sendDataPacket(packet, DataPacket_Kind.RELIABLE);
16929
- let chunkId = 0;
16930
- const engine = this.engine;
16931
- const writableStream = new WritableStream({
16932
- // Implement the sink
16933
- write(text) {
16934
- return __awaiter(this, void 0, void 0, function* () {
16935
- for (const textByteChunk of splitUtf8(text, STREAM_CHUNK_SIZE)) {
16936
- yield engine.waitForBufferStatusLow(DataPacket_Kind.RELIABLE);
16937
- const chunk = new DataStream_Chunk({
16938
- content: textByteChunk,
16939
- streamId,
16940
- chunkIndex: numberToBigInt(chunkId)
16941
- });
16942
- const chunkPacket = new DataPacket({
16943
- destinationIdentities,
16944
- value: {
16945
- case: "streamChunk",
16946
- value: chunk
16947
- }
16948
- });
16949
- yield engine.sendDataPacket(chunkPacket, DataPacket_Kind.RELIABLE);
16950
- chunkId += 1;
16951
- }
16952
- });
16953
- },
16954
- close() {
16955
- return __awaiter(this, void 0, void 0, function* () {
16956
- const trailer = new DataStream_Trailer({
16957
- streamId
16958
- });
16959
- const trailerPacket = new DataPacket({
16960
- destinationIdentities,
16961
- value: {
16962
- case: "streamTrailer",
16963
- value: trailer
16964
- }
16965
- });
16966
- yield engine.sendDataPacket(trailerPacket, DataPacket_Kind.RELIABLE);
16967
- });
16968
- },
16969
- abort(err) {
16970
- console.log("Sink error:", err);
16971
- }
16972
- });
16973
- let onEngineClose = () => __awaiter(this, void 0, void 0, function* () {
16974
- yield writer2.close();
16975
- });
16976
- engine.once(EngineEvent.Closing, onEngineClose);
16977
- const writer2 = new TextStreamWriter(writableStream, info, () => this.engine.off(EngineEvent.Closing, onEngineClose));
16978
- return writer2;
16979
- });
16980
- }
16981
- sendFile(file, options) {
16982
- return __awaiter(this, void 0, void 0, function* () {
16983
- const streamId = crypto.randomUUID();
16984
- yield this._sendFile(streamId, file, options);
16985
- return {
16986
- id: streamId
16987
- };
16988
- });
16989
- }
16990
- _sendFile(streamId, file, options) {
16991
- return __awaiter(this, void 0, void 0, function* () {
16992
- var _a;
16993
- const writer2 = yield this.streamBytes({
16994
- streamId,
16995
- totalSize: file.size,
16996
- name: file.name,
16997
- mimeType: (_a = options === null || options === void 0 ? void 0 : options.mimeType) !== null && _a !== void 0 ? _a : file.type,
16998
- topic: options === null || options === void 0 ? void 0 : options.topic,
16999
- destinationIdentities: options === null || options === void 0 ? void 0 : options.destinationIdentities
17000
- });
17001
- const reader = file.stream().getReader();
17002
- while (true) {
17003
- const {
17004
- done,
17005
- value
17006
- } = yield reader.read();
17007
- if (done) {
17008
- break;
17009
- }
17010
- yield writer2.write(value);
17011
- }
17012
- yield writer2.close();
17013
- return writer2.info;
17014
- });
17015
- }
17016
- streamBytes(options) {
17017
- return __awaiter(this, void 0, void 0, function* () {
17018
- var _a, _b, _c, _d, _e;
17019
- const streamId = (_a = options === null || options === void 0 ? void 0 : options.streamId) !== null && _a !== void 0 ? _a : crypto.randomUUID();
17020
- const destinationIdentities = options === null || options === void 0 ? void 0 : options.destinationIdentities;
17021
- const info = {
17022
- id: streamId,
17023
- mimeType: (_b = options === null || options === void 0 ? void 0 : options.mimeType) !== null && _b !== void 0 ? _b : "application/octet-stream",
17024
- topic: (_c = options === null || options === void 0 ? void 0 : options.topic) !== null && _c !== void 0 ? _c : "",
17025
- timestamp: Date.now(),
17026
- attributes: options === null || options === void 0 ? void 0 : options.attributes,
17027
- size: options === null || options === void 0 ? void 0 : options.totalSize,
17028
- name: (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : "unknown"
17029
- };
17030
- const header = new DataStream_Header({
17031
- totalLength: numberToBigInt((_e = info.size) !== null && _e !== void 0 ? _e : 0),
17032
- mimeType: info.mimeType,
17033
- streamId,
17034
- topic: info.topic,
17035
- timestamp: numberToBigInt(Date.now()),
17036
- attributes: info.attributes,
17037
- contentHeader: {
17038
- case: "byteHeader",
17039
- value: new DataStream_ByteHeader({
17040
- name: info.name
17041
- })
17042
- }
17043
- });
17044
- const packet = new DataPacket({
17045
- destinationIdentities,
17046
- value: {
17047
- case: "streamHeader",
17048
- value: header
17049
- }
17050
- });
17051
- yield this.engine.sendDataPacket(packet, DataPacket_Kind.RELIABLE);
17052
- let chunkId = 0;
17053
- const writeMutex = new _();
17054
- const engine = this.engine;
17055
- const logLocal = this.log;
17056
- const writableStream = new WritableStream({
17057
- write(chunk) {
17058
- return __awaiter(this, void 0, void 0, function* () {
17059
- const unlock = yield writeMutex.lock();
17060
- let byteOffset = 0;
17061
- try {
17062
- while (byteOffset < chunk.byteLength) {
17063
- const subChunk = chunk.slice(byteOffset, byteOffset + STREAM_CHUNK_SIZE);
17064
- yield engine.waitForBufferStatusLow(DataPacket_Kind.RELIABLE);
17065
- const chunkPacket = new DataPacket({
17066
- destinationIdentities,
17067
- value: {
17068
- case: "streamChunk",
17069
- value: new DataStream_Chunk({
17070
- content: subChunk,
17071
- streamId,
17072
- chunkIndex: numberToBigInt(chunkId)
17073
- })
17074
- }
17075
- });
17076
- yield engine.sendDataPacket(chunkPacket, DataPacket_Kind.RELIABLE);
17077
- chunkId += 1;
17078
- byteOffset += subChunk.byteLength;
17079
- }
17080
- } finally {
17081
- unlock();
17082
- }
17083
- });
17084
- },
17085
- close() {
17086
- return __awaiter(this, void 0, void 0, function* () {
17087
- const trailer = new DataStream_Trailer({
17088
- streamId
17089
- });
17090
- const trailerPacket = new DataPacket({
17091
- destinationIdentities,
17092
- value: {
17093
- case: "streamTrailer",
17094
- value: trailer
17095
- }
17096
- });
17097
- yield engine.sendDataPacket(trailerPacket, DataPacket_Kind.RELIABLE);
17098
- });
17099
- },
17100
- abort(err) {
17101
- logLocal.error("Sink error:", err);
17102
- }
17103
- });
17104
- const byteWriter = new ByteStreamWriter(writableStream, info);
17105
- return byteWriter;
17106
- });
17107
- }
17108
- };
17109
- var RemoteTrack = class extends Track {
17110
- constructor(mediaTrack, sid, kind, receiver, loggerOptions) {
17111
- super(mediaTrack, kind, loggerOptions);
17112
- this.sid = sid;
17113
- this.receiver = receiver;
17114
- }
17115
- get isLocal() {
17116
- return false;
17117
- }
17118
- /** @internal */
17119
- setMuted(muted) {
17120
- if (this.isMuted !== muted) {
17121
- this.isMuted = muted;
17122
- this._mediaStreamTrack.enabled = !muted;
17123
- this.emit(muted ? TrackEvent.Muted : TrackEvent.Unmuted, this);
17124
- }
17125
- }
17126
- /** @internal */
17127
- setMediaStream(stream) {
17128
- this.mediaStream = stream;
17129
- const onRemoveTrack = (event) => {
17130
- if (event.track === this._mediaStreamTrack) {
17131
- stream.removeEventListener("removetrack", onRemoveTrack);
17132
- if (this.receiver && "playoutDelayHint" in this.receiver) {
17133
- this.receiver.playoutDelayHint = void 0;
17134
- }
17135
- this.receiver = void 0;
17136
- this._currentBitrate = 0;
17137
- this.emit(TrackEvent.Ended, this);
17138
- }
17139
- };
17140
- stream.addEventListener("removetrack", onRemoveTrack);
17141
- }
17142
- start() {
17143
- this.startMonitor();
17144
- super.enable();
17145
- }
17146
- stop() {
17147
- this.stopMonitor();
17148
- super.disable();
17149
- }
17150
- /**
17151
- * Gets the RTCStatsReport for the RemoteTrack's underlying RTCRtpReceiver
17152
- * See https://developer.mozilla.org/en-US/docs/Web/API/RTCStatsReport
17153
- *
17154
- * @returns Promise<RTCStatsReport> | undefined
17155
- */
17156
- getRTCStatsReport() {
17157
- return __awaiter(this, void 0, void 0, function* () {
17158
- var _a;
17159
- if (!((_a = this.receiver) === null || _a === void 0 ? void 0 : _a.getStats)) {
17160
- return;
17161
- }
17162
- const statsReport = yield this.receiver.getStats();
17163
- return statsReport;
17164
- });
17165
- }
17166
- /**
17167
- * Allows to set a playout delay (in seconds) for this track.
17168
- * A higher value allows for more buffering of the track in the browser
17169
- * and will result in a delay of media being played back of `delayInSeconds`
17170
- */
17171
- setPlayoutDelay(delayInSeconds) {
17172
- if (this.receiver) {
17173
- if ("playoutDelayHint" in this.receiver) {
17174
- this.receiver.playoutDelayHint = delayInSeconds;
17175
- } else {
17176
- this.log.warn("Playout delay not supported in this browser");
17177
- }
17178
- } else {
17179
- this.log.warn("Cannot set playout delay, track already ended");
17180
- }
17181
- }
17182
- /**
17183
- * Returns the current playout delay (in seconds) of this track.
17184
- */
17185
- getPlayoutDelay() {
17186
- if (this.receiver) {
17187
- if ("playoutDelayHint" in this.receiver) {
17188
- return this.receiver.playoutDelayHint;
17189
- } else {
17190
- this.log.warn("Playout delay not supported in this browser");
17191
- }
17192
- } else {
17193
- this.log.warn("Cannot get playout delay, track already ended");
17194
- }
17195
- return 0;
16574
+ } else {
16575
+ this.log.warn("Cannot get playout delay, track already ended");
16576
+ }
16577
+ return 0;
17196
16578
  }
17197
16579
  /* @internal */
17198
16580
  startMonitor() {
@@ -17441,13 +16823,6 @@ var RemoteVideoTrack = class extends RemoteTrack {
17441
16823
  get isAdaptiveStream() {
17442
16824
  return this.adaptiveStreamSettings !== void 0;
17443
16825
  }
17444
- setStreamState(value) {
17445
- super.setStreamState(value);
17446
- console.log("setStreamState", value);
17447
- if (value === Track.StreamState.Active) {
17448
- this.updateVisibility();
17449
- }
17450
- }
17451
16826
  /**
17452
16827
  * Note: When using adaptiveStream, you need to use remoteVideoTrack.attach() to add the track to a HTMLVideoElement, otherwise your video tracks might never start
17453
16828
  */
@@ -17591,13 +16966,13 @@ var RemoteVideoTrack = class extends RemoteTrack {
17591
16966
  this.updateVisibility();
17592
16967
  });
17593
16968
  }
17594
- updateVisibility(forceEmit) {
16969
+ updateVisibility() {
17595
16970
  var _a, _b;
17596
16971
  const lastVisibilityChange = this.elementInfos.reduce((prev, info) => Math.max(prev, info.visibilityChangedAt || 0), 0);
17597
16972
  const backgroundPause = ((_b = (_a = this.adaptiveStreamSettings) === null || _a === void 0 ? void 0 : _a.pauseVideoInBackground) !== null && _b !== void 0 ? _b : true) ? this.isInBackground : false;
17598
16973
  const isPiPMode = this.elementInfos.some((info) => info.pictureInPicture);
17599
16974
  const isVisible = this.elementInfos.some((info) => info.visible) && !backgroundPause || isPiPMode;
17600
- if (this.lastVisible === isVisible && !forceEmit) {
16975
+ if (this.lastVisible === isVisible) {
17601
16976
  return;
17602
16977
  }
17603
16978
  if (!isVisible && Date.now() - lastVisibilityChange < REACTION_DELAY) {
@@ -18345,9 +17720,10 @@ function trackPermissionToProto(perms) {
18345
17720
  trackSids: perms.allowedTrackSids || []
18346
17721
  });
18347
17722
  }
17723
+ var STREAM_CHUNK_SIZE = 15e3;
18348
17724
  var LocalParticipant = class extends Participant {
18349
17725
  /** @internal */
18350
- constructor(sid, identity, engine, options, roomRpcHandlers, roomOutgoingDataStreamManager) {
17726
+ constructor(sid, identity, engine, options, roomRpcHandlers) {
18351
17727
  super(sid, identity, void 0, void 0, void 0, {
18352
17728
  loggerName: options.loggerName,
18353
17729
  loggerContextCb: () => this.engine.logContext
@@ -18573,7 +17949,6 @@ var LocalParticipant = class extends Participant {
18573
17949
  this.activeDeviceMap = /* @__PURE__ */ new Map([["audioinput", "default"], ["videoinput", "default"], ["audiooutput", "default"]]);
18574
17950
  this.pendingSignalRequests = /* @__PURE__ */ new Map();
18575
17951
  this.rpcHandlers = roomRpcHandlers;
18576
- this.roomOutgoingDataStreamManager = roomOutgoingDataStreamManager;
18577
17952
  }
18578
17953
  get lastCameraError() {
18579
17954
  return this.cameraError;
@@ -18665,7 +18040,7 @@ var LocalParticipant = class extends Participant {
18665
18040
  name,
18666
18041
  attributes
18667
18042
  } = _ref;
18668
- return (function* () {
18043
+ return function* () {
18669
18044
  return new Promise((resolve, reject) => __awaiter(_this, void 0, void 0, function* () {
18670
18045
  var _a2, _b;
18671
18046
  try {
@@ -18700,7 +18075,7 @@ var LocalParticipant = class extends Participant {
18700
18075
  if (e2 instanceof Error) reject(e2);
18701
18076
  }
18702
18077
  }));
18703
- })();
18078
+ }();
18704
18079
  });
18705
18080
  }
18706
18081
  /**
@@ -18969,7 +18344,7 @@ var LocalParticipant = class extends Participant {
18969
18344
  return __awaiter(this, arguments, void 0, function(track, options) {
18970
18345
  var _this2 = this;
18971
18346
  let isRepublish = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
18972
- return (function* () {
18347
+ return function* () {
18973
18348
  var _a, _b, _c, _d;
18974
18349
  if (isLocalAudioTrack(track)) {
18975
18350
  track.setAudioContext(_this2.audioContext);
@@ -19094,7 +18469,7 @@ var LocalParticipant = class extends Participant {
19094
18469
  } finally {
19095
18470
  _this2.pendingPublishPromises.delete(track);
19096
18471
  }
19097
- })();
18472
+ }();
19098
18473
  });
19099
18474
  }
19100
18475
  waitUntilEngineConnected() {
@@ -19576,7 +18951,7 @@ var LocalParticipant = class extends Participant {
19576
18951
  return __awaiter(this, arguments, void 0, function(options) {
19577
18952
  var _this3 = this;
19578
18953
  let restartTracks = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true;
19579
- return (function* () {
18954
+ return function* () {
19580
18955
  if (_this3.republishPromise) {
19581
18956
  yield _this3.republishPromise;
19582
18957
  }
@@ -19610,7 +18985,7 @@ var LocalParticipant = class extends Participant {
19610
18985
  }
19611
18986
  }));
19612
18987
  yield _this3.republishPromise;
19613
- })();
18988
+ }();
19614
18989
  });
19615
18990
  }
19616
18991
  /**
@@ -19624,7 +18999,7 @@ var LocalParticipant = class extends Participant {
19624
18999
  return __awaiter(this, arguments, void 0, function(data) {
19625
19000
  var _this4 = this;
19626
19001
  let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
19627
- return (function* () {
19002
+ return function* () {
19628
19003
  const kind = options.reliable ? DataPacket_Kind.RELIABLE : DataPacket_Kind.LOSSY;
19629
19004
  const destinationIdentities = options.destinationIdentities;
19630
19005
  const topic = options.topic;
@@ -19641,7 +19016,7 @@ var LocalParticipant = class extends Participant {
19641
19016
  }
19642
19017
  });
19643
19018
  yield _this4.engine.sendDataPacket(packet, kind);
19644
- })();
19019
+ }();
19645
19020
  });
19646
19021
  }
19647
19022
  /**
@@ -19665,7 +19040,6 @@ var LocalParticipant = class extends Participant {
19665
19040
  yield this.engine.sendDataPacket(packet, DataPacket_Kind.RELIABLE);
19666
19041
  });
19667
19042
  }
19668
- /** @deprecated Consider migrating to {@link sendText} */
19669
19043
  sendChatMessage(text, options) {
19670
19044
  return __awaiter(this, void 0, void 0, function* () {
19671
19045
  const msg = {
@@ -19687,7 +19061,6 @@ var LocalParticipant = class extends Participant {
19687
19061
  return msg;
19688
19062
  });
19689
19063
  }
19690
- /** @deprecated Consider migrating to {@link sendText} */
19691
19064
  editChatMessage(editText, originalMessage) {
19692
19065
  return __awaiter(this, void 0, void 0, function* () {
19693
19066
  const msg = Object.assign(Object.assign({}, originalMessage), {
@@ -19704,55 +19077,268 @@ var LocalParticipant = class extends Participant {
19704
19077
  }
19705
19078
  });
19706
19079
  yield this.engine.sendDataPacket(packet, DataPacket_Kind.RELIABLE);
19707
- this.emit(ParticipantEvent.ChatMessage, msg);
19708
- return msg;
19709
- });
19710
- }
19711
- /**
19712
- * Sends the given string to participants in the room via the data channel.
19713
- * For longer messages, consider using {@link streamText} instead.
19714
- *
19715
- * @param text The text payload
19716
- * @param options.topic Topic identifier used to route the stream to appropriate handlers.
19717
- */
19718
- sendText(text, options) {
19719
- return __awaiter(this, void 0, void 0, function* () {
19720
- return this.roomOutgoingDataStreamManager.sendText(text, options);
19721
- });
19722
- }
19723
- /**
19724
- * Creates a new TextStreamWriter which can be used to stream text incrementally
19725
- * to participants in the room via the data channel.
19726
- *
19727
- * @param options.topic Topic identifier used to route the stream to appropriate handlers.
19728
- *
19729
- * @internal
19730
- * @experimental CAUTION, might get removed in a minor release
19731
- */
19732
- streamText(options) {
19733
- return __awaiter(this, void 0, void 0, function* () {
19734
- return this.roomOutgoingDataStreamManager.streamText(options);
19735
- });
19736
- }
19737
- /** Send a File to all participants in the room via the data channel.
19738
- * @param file The File object payload
19739
- * @param options.topic Topic identifier used to route the stream to appropriate handlers.
19740
- * @param options.onProgress A callback function used to monitor the upload progress percentage.
19741
- */
19742
- sendFile(file, options) {
19743
- return __awaiter(this, void 0, void 0, function* () {
19744
- return this.roomOutgoingDataStreamManager.sendFile(file, options);
19745
- });
19746
- }
19747
- /**
19748
- * Stream bytes incrementally to participants in the room via the data channel.
19749
- * For sending files, consider using {@link sendFile} instead.
19750
- *
19751
- * @param options.topic Topic identifier used to route the stream to appropriate handlers.
19752
- */
19753
- streamBytes(options) {
19754
- return __awaiter(this, void 0, void 0, function* () {
19755
- return this.roomOutgoingDataStreamManager.streamBytes(options);
19080
+ this.emit(ParticipantEvent.ChatMessage, msg);
19081
+ return msg;
19082
+ });
19083
+ }
19084
+ sendText(text, options) {
19085
+ return __awaiter(this, void 0, void 0, function* () {
19086
+ var _a;
19087
+ const streamId = crypto.randomUUID();
19088
+ const textInBytes = new TextEncoder().encode(text);
19089
+ const totalTextLength = textInBytes.byteLength;
19090
+ const fileIds = (_a = options === null || options === void 0 ? void 0 : options.attachments) === null || _a === void 0 ? void 0 : _a.map(() => crypto.randomUUID());
19091
+ const progresses = new Array(fileIds ? fileIds.length + 1 : 1).fill(0);
19092
+ const handleProgress = (progress, idx) => {
19093
+ var _a2;
19094
+ progresses[idx] = progress;
19095
+ const totalProgress = progresses.reduce((acc, val) => acc + val, 0);
19096
+ (_a2 = options === null || options === void 0 ? void 0 : options.onProgress) === null || _a2 === void 0 ? void 0 : _a2.call(options, totalProgress);
19097
+ };
19098
+ const writer2 = yield this.streamText({
19099
+ streamId,
19100
+ totalSize: totalTextLength,
19101
+ destinationIdentities: options === null || options === void 0 ? void 0 : options.destinationIdentities,
19102
+ topic: options === null || options === void 0 ? void 0 : options.topic,
19103
+ attachedStreamIds: fileIds,
19104
+ attributes: options === null || options === void 0 ? void 0 : options.attributes
19105
+ });
19106
+ yield writer2.write(text);
19107
+ handleProgress(1, 0);
19108
+ yield writer2.close();
19109
+ if ((options === null || options === void 0 ? void 0 : options.attachments) && fileIds) {
19110
+ yield Promise.all(options.attachments.map((file, idx) => __awaiter(this, void 0, void 0, function* () {
19111
+ return this._sendFile(fileIds[idx], file, {
19112
+ topic: options.topic,
19113
+ mimeType: file.type,
19114
+ onProgress: (progress) => {
19115
+ handleProgress(progress, idx + 1);
19116
+ }
19117
+ });
19118
+ })));
19119
+ }
19120
+ return writer2.info;
19121
+ });
19122
+ }
19123
+ /**
19124
+ * @internal
19125
+ * @experimental CAUTION, might get removed in a minor release
19126
+ */
19127
+ streamText(options) {
19128
+ return __awaiter(this, void 0, void 0, function* () {
19129
+ var _a, _b;
19130
+ const streamId = (_a = options === null || options === void 0 ? void 0 : options.streamId) !== null && _a !== void 0 ? _a : crypto.randomUUID();
19131
+ const info = {
19132
+ id: streamId,
19133
+ mimeType: "text/plain",
19134
+ timestamp: Date.now(),
19135
+ topic: (_b = options === null || options === void 0 ? void 0 : options.topic) !== null && _b !== void 0 ? _b : "",
19136
+ size: options === null || options === void 0 ? void 0 : options.totalSize,
19137
+ attributes: options === null || options === void 0 ? void 0 : options.attributes
19138
+ };
19139
+ const header = new DataStream_Header({
19140
+ streamId,
19141
+ mimeType: info.mimeType,
19142
+ topic: info.topic,
19143
+ timestamp: numberToBigInt(info.timestamp),
19144
+ totalLength: numberToBigInt(options === null || options === void 0 ? void 0 : options.totalSize),
19145
+ attributes: info.attributes,
19146
+ contentHeader: {
19147
+ case: "textHeader",
19148
+ value: new DataStream_TextHeader({
19149
+ version: options === null || options === void 0 ? void 0 : options.version,
19150
+ attachedStreamIds: options === null || options === void 0 ? void 0 : options.attachedStreamIds,
19151
+ replyToStreamId: options === null || options === void 0 ? void 0 : options.replyToStreamId,
19152
+ operationType: (options === null || options === void 0 ? void 0 : options.type) === "update" ? DataStream_OperationType.UPDATE : DataStream_OperationType.CREATE
19153
+ })
19154
+ }
19155
+ });
19156
+ const destinationIdentities = options === null || options === void 0 ? void 0 : options.destinationIdentities;
19157
+ const packet = new DataPacket({
19158
+ destinationIdentities,
19159
+ value: {
19160
+ case: "streamHeader",
19161
+ value: header
19162
+ }
19163
+ });
19164
+ yield this.engine.sendDataPacket(packet, DataPacket_Kind.RELIABLE);
19165
+ let chunkId = 0;
19166
+ const localP = this;
19167
+ const writableStream = new WritableStream({
19168
+ // Implement the sink
19169
+ write(text) {
19170
+ return __awaiter(this, void 0, void 0, function* () {
19171
+ for (const textByteChunk of splitUtf8(text, STREAM_CHUNK_SIZE)) {
19172
+ yield localP.engine.waitForBufferStatusLow(DataPacket_Kind.RELIABLE);
19173
+ const chunk = new DataStream_Chunk({
19174
+ content: textByteChunk,
19175
+ streamId,
19176
+ chunkIndex: numberToBigInt(chunkId)
19177
+ });
19178
+ const chunkPacket = new DataPacket({
19179
+ destinationIdentities,
19180
+ value: {
19181
+ case: "streamChunk",
19182
+ value: chunk
19183
+ }
19184
+ });
19185
+ yield localP.engine.sendDataPacket(chunkPacket, DataPacket_Kind.RELIABLE);
19186
+ chunkId += 1;
19187
+ }
19188
+ });
19189
+ },
19190
+ close() {
19191
+ return __awaiter(this, void 0, void 0, function* () {
19192
+ const trailer = new DataStream_Trailer({
19193
+ streamId
19194
+ });
19195
+ const trailerPacket = new DataPacket({
19196
+ destinationIdentities,
19197
+ value: {
19198
+ case: "streamTrailer",
19199
+ value: trailer
19200
+ }
19201
+ });
19202
+ yield localP.engine.sendDataPacket(trailerPacket, DataPacket_Kind.RELIABLE);
19203
+ });
19204
+ },
19205
+ abort(err) {
19206
+ console.log("Sink error:", err);
19207
+ }
19208
+ });
19209
+ let onEngineClose = () => __awaiter(this, void 0, void 0, function* () {
19210
+ yield writer2.close();
19211
+ });
19212
+ localP.engine.once(EngineEvent.Closing, onEngineClose);
19213
+ const writer2 = new TextStreamWriter(writableStream, info, () => this.engine.off(EngineEvent.Closing, onEngineClose));
19214
+ return writer2;
19215
+ });
19216
+ }
19217
+ sendFile(file, options) {
19218
+ return __awaiter(this, void 0, void 0, function* () {
19219
+ const streamId = crypto.randomUUID();
19220
+ yield this._sendFile(streamId, file, options);
19221
+ return {
19222
+ id: streamId
19223
+ };
19224
+ });
19225
+ }
19226
+ _sendFile(streamId, file, options) {
19227
+ return __awaiter(this, void 0, void 0, function* () {
19228
+ var _a;
19229
+ const writer2 = yield this.streamBytes({
19230
+ streamId,
19231
+ totalSize: file.size,
19232
+ name: file.name,
19233
+ mimeType: (_a = options === null || options === void 0 ? void 0 : options.mimeType) !== null && _a !== void 0 ? _a : file.type,
19234
+ topic: options === null || options === void 0 ? void 0 : options.topic,
19235
+ destinationIdentities: options === null || options === void 0 ? void 0 : options.destinationIdentities
19236
+ });
19237
+ const reader = file.stream().getReader();
19238
+ while (true) {
19239
+ const {
19240
+ done,
19241
+ value
19242
+ } = yield reader.read();
19243
+ if (done) {
19244
+ break;
19245
+ }
19246
+ yield writer2.write(value);
19247
+ }
19248
+ yield writer2.close();
19249
+ return writer2.info;
19250
+ });
19251
+ }
19252
+ streamBytes(options) {
19253
+ return __awaiter(this, void 0, void 0, function* () {
19254
+ var _a, _b, _c, _d, _e;
19255
+ const streamId = (_a = options === null || options === void 0 ? void 0 : options.streamId) !== null && _a !== void 0 ? _a : crypto.randomUUID();
19256
+ const destinationIdentities = options === null || options === void 0 ? void 0 : options.destinationIdentities;
19257
+ const info = {
19258
+ id: streamId,
19259
+ mimeType: (_b = options === null || options === void 0 ? void 0 : options.mimeType) !== null && _b !== void 0 ? _b : "application/octet-stream",
19260
+ topic: (_c = options === null || options === void 0 ? void 0 : options.topic) !== null && _c !== void 0 ? _c : "",
19261
+ timestamp: Date.now(),
19262
+ attributes: options === null || options === void 0 ? void 0 : options.attributes,
19263
+ size: options === null || options === void 0 ? void 0 : options.totalSize,
19264
+ name: (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : "unknown"
19265
+ };
19266
+ const header = new DataStream_Header({
19267
+ totalLength: numberToBigInt((_e = info.size) !== null && _e !== void 0 ? _e : 0),
19268
+ mimeType: info.mimeType,
19269
+ streamId,
19270
+ topic: info.topic,
19271
+ timestamp: numberToBigInt(Date.now()),
19272
+ attributes: info.attributes,
19273
+ contentHeader: {
19274
+ case: "byteHeader",
19275
+ value: new DataStream_ByteHeader({
19276
+ name: info.name
19277
+ })
19278
+ }
19279
+ });
19280
+ const packet = new DataPacket({
19281
+ destinationIdentities,
19282
+ value: {
19283
+ case: "streamHeader",
19284
+ value: header
19285
+ }
19286
+ });
19287
+ yield this.engine.sendDataPacket(packet, DataPacket_Kind.RELIABLE);
19288
+ let chunkId = 0;
19289
+ const writeMutex = new _();
19290
+ const engine = this.engine;
19291
+ const log2 = this.log;
19292
+ const writableStream = new WritableStream({
19293
+ write(chunk) {
19294
+ return __awaiter(this, void 0, void 0, function* () {
19295
+ const unlock = yield writeMutex.lock();
19296
+ let byteOffset = 0;
19297
+ try {
19298
+ while (byteOffset < chunk.byteLength) {
19299
+ const subChunk = chunk.slice(byteOffset, byteOffset + STREAM_CHUNK_SIZE);
19300
+ yield engine.waitForBufferStatusLow(DataPacket_Kind.RELIABLE);
19301
+ const chunkPacket = new DataPacket({
19302
+ destinationIdentities,
19303
+ value: {
19304
+ case: "streamChunk",
19305
+ value: new DataStream_Chunk({
19306
+ content: subChunk,
19307
+ streamId,
19308
+ chunkIndex: numberToBigInt(chunkId)
19309
+ })
19310
+ }
19311
+ });
19312
+ yield engine.sendDataPacket(chunkPacket, DataPacket_Kind.RELIABLE);
19313
+ chunkId += 1;
19314
+ byteOffset += subChunk.byteLength;
19315
+ }
19316
+ } finally {
19317
+ unlock();
19318
+ }
19319
+ });
19320
+ },
19321
+ close() {
19322
+ return __awaiter(this, void 0, void 0, function* () {
19323
+ const trailer = new DataStream_Trailer({
19324
+ streamId
19325
+ });
19326
+ const trailerPacket = new DataPacket({
19327
+ destinationIdentities,
19328
+ value: {
19329
+ case: "streamTrailer",
19330
+ value: trailer
19331
+ }
19332
+ });
19333
+ yield engine.sendDataPacket(trailerPacket, DataPacket_Kind.RELIABLE);
19334
+ });
19335
+ },
19336
+ abort(err) {
19337
+ log2.error("Sink error:", err);
19338
+ }
19339
+ });
19340
+ const byteWriter = new ByteStreamWriter(writableStream, info);
19341
+ return byteWriter;
19756
19342
  });
19757
19343
  }
19758
19344
  /**
@@ -19770,7 +19356,7 @@ var LocalParticipant = class extends Participant {
19770
19356
  payload,
19771
19357
  responseTimeout = 1e4
19772
19358
  } = _ref3;
19773
- return (function* () {
19359
+ return function* () {
19774
19360
  const maxRoundTripLatency = 2e3;
19775
19361
  return new Promise((resolve, reject) => __awaiter(_this5, void 0, void 0, function* () {
19776
19362
  var _a2, _b, _c, _d;
@@ -19817,7 +19403,7 @@ var LocalParticipant = class extends Participant {
19817
19403
  participantIdentity: destinationIdentity
19818
19404
  });
19819
19405
  }));
19820
- })();
19406
+ }();
19821
19407
  });
19822
19408
  }
19823
19409
  /**
@@ -20536,6 +20122,10 @@ var Room = class _Room extends eventsExports.EventEmitter {
20536
20122
  this.log = livekitLogger;
20537
20123
  this.bufferedEvents = [];
20538
20124
  this.isResuming = false;
20125
+ this.byteStreamControllers = /* @__PURE__ */ new Map();
20126
+ this.textStreamControllers = /* @__PURE__ */ new Map();
20127
+ this.byteStreamHandlers = /* @__PURE__ */ new Map();
20128
+ this.textStreamHandlers = /* @__PURE__ */ new Map();
20539
20129
  this.rpcHandlers = /* @__PURE__ */ new Map();
20540
20130
  this.connect = (url, token2, opts) => __awaiter(this, void 0, void 0, function* () {
20541
20131
  var _a2;
@@ -20750,7 +20340,7 @@ var Room = class _Room extends eventsExports.EventEmitter {
20750
20340
  return __awaiter(_this, [...args_1], void 0, function() {
20751
20341
  var _this2 = this;
20752
20342
  let stopTracks = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true;
20753
- return (function* () {
20343
+ return function* () {
20754
20344
  var _a2, _b2, _c2, _d;
20755
20345
  const unlock = yield _this2.disconnectLock.lock();
20756
20346
  try {
@@ -20776,7 +20366,7 @@ var Room = class _Room extends eventsExports.EventEmitter {
20776
20366
  } finally {
20777
20367
  unlock();
20778
20368
  }
20779
- })();
20369
+ }();
20780
20370
  });
20781
20371
  };
20782
20372
  this.onPageLeave = () => __awaiter(this, void 0, void 0, function* () {
@@ -20984,8 +20574,8 @@ var Room = class _Room extends eventsExports.EventEmitter {
20984
20574
  return;
20985
20575
  }
20986
20576
  const newStreamState = Track.streamStateFromProto(streamState.state);
20987
- pub.track.setStreamState(newStreamState);
20988
20577
  if (newStreamState !== pub.track.streamState) {
20578
+ pub.track.streamState = newStreamState;
20989
20579
  participant.emit(ParticipantEvent.TrackStreamStateChanged, pub, pub.track.streamState);
20990
20580
  this.emitWhenConnected(RoomEvent.TrackStreamStateChanged, pub, pub.track.streamState, participant);
20991
20581
  }
@@ -21025,8 +20615,12 @@ var Room = class _Room extends eventsExports.EventEmitter {
21025
20615
  this.handleChatMessage(participant, packet.value.value);
21026
20616
  } else if (packet.value.case === "metrics") {
21027
20617
  this.handleMetrics(packet.value.value, participant);
21028
- } else if (packet.value.case === "streamHeader" || packet.value.case === "streamChunk" || packet.value.case === "streamTrailer") {
21029
- this.handleDataStream(packet);
20618
+ } else if (packet.value.case === "streamHeader") {
20619
+ this.handleStreamHeader(packet.value.value, packet.participantIdentity);
20620
+ } else if (packet.value.case === "streamChunk") {
20621
+ this.handleStreamChunk(packet.value.value);
20622
+ } else if (packet.value.case === "streamTrailer") {
20623
+ this.handleStreamTrailer(packet.value.value);
21030
20624
  } else if (packet.value.case === "rpcRequest") {
21031
20625
  const rpc = packet.value.value;
21032
20626
  this.handleIncomingRpcRequest(packet.participantIdentity, rpc.id, rpc.method, rpc.payload, rpc.responseTimeoutMs, rpc.version);
@@ -21040,6 +20634,7 @@ var Room = class _Room extends eventsExports.EventEmitter {
21040
20634
  this.emit(RoomEvent.SipDTMFReceived, dtmf, participant);
21041
20635
  participant === null || participant === void 0 ? void 0 : participant.emit(ParticipantEvent.SipDTMFReceived, dtmf);
21042
20636
  };
20637
+ this.bufferedSegments = /* @__PURE__ */ new Map();
21043
20638
  this.handleTranscription = (_remoteParticipant, transcription) => {
21044
20639
  const participant = transcription.transcribedParticipantIdentity === this.localParticipant.identity ? this.localParticipant : this.getParticipantByIdentity(transcription.transcribedParticipantIdentity);
21045
20640
  const publication = participant === null || participant === void 0 ? void 0 : participant.trackPublications.get(transcription.trackId);
@@ -21055,10 +20650,6 @@ var Room = class _Room extends eventsExports.EventEmitter {
21055
20650
  this.handleMetrics = (metrics, participant) => {
21056
20651
  this.emit(RoomEvent.MetricsReceived, metrics, participant);
21057
20652
  };
21058
- this.handleDataStream = (packet) => {
21059
- this.incomingDataStreamManager.handleDataStreamPacket(packet);
21060
- };
21061
- this.bufferedSegments = /* @__PURE__ */ new Map();
21062
20653
  this.handleAudioPlaybackStarted = () => {
21063
20654
  if (this.canPlaybackAudio) {
21064
20655
  return;
@@ -21192,10 +20783,8 @@ var Room = class _Room extends eventsExports.EventEmitter {
21192
20783
  this.options.videoCaptureDefaults = Object.assign(Object.assign({}, videoDefaults), options === null || options === void 0 ? void 0 : options.videoCaptureDefaults);
21193
20784
  this.options.publishDefaults = Object.assign(Object.assign({}, publishDefaults), options === null || options === void 0 ? void 0 : options.publishDefaults);
21194
20785
  this.maybeCreateEngine();
21195
- this.incomingDataStreamManager = new IncomingDataStreamManager();
21196
- this.outgoingDataStreamManager = new OutgoingDataStreamManager(this.engine, this.log);
21197
20786
  this.disconnectLock = new _();
21198
- this.localParticipant = new LocalParticipant("", "", this.engine, this.options, this.rpcHandlers, this.outgoingDataStreamManager);
20787
+ this.localParticipant = new LocalParticipant("", "", this.engine, this.options, this.rpcHandlers);
21199
20788
  if (this.options.videoCaptureDefaults.deviceId) {
21200
20789
  this.localParticipant.activeDeviceMap.set("videoinput", unwrapConstraint(this.options.videoCaptureDefaults.deviceId));
21201
20790
  }
@@ -21221,16 +20810,22 @@ var Room = class _Room extends eventsExports.EventEmitter {
21221
20810
  }
21222
20811
  }
21223
20812
  registerTextStreamHandler(topic, callback) {
21224
- return this.incomingDataStreamManager.registerTextStreamHandler(topic, callback);
20813
+ if (this.textStreamHandlers.has(topic)) {
20814
+ throw new TypeError('A text stream handler for topic "'.concat(topic, '" has already been set.'));
20815
+ }
20816
+ this.textStreamHandlers.set(topic, callback);
21225
20817
  }
21226
20818
  unregisterTextStreamHandler(topic) {
21227
- return this.incomingDataStreamManager.unregisterTextStreamHandler(topic);
20819
+ this.textStreamHandlers.delete(topic);
21228
20820
  }
21229
20821
  registerByteStreamHandler(topic, callback) {
21230
- return this.incomingDataStreamManager.registerByteStreamHandler(topic, callback);
20822
+ if (this.byteStreamHandlers.has(topic)) {
20823
+ throw new TypeError('A byte stream handler for topic "'.concat(topic, '" has already been set.'));
20824
+ }
20825
+ this.byteStreamHandlers.set(topic, callback);
21231
20826
  }
21232
20827
  unregisterByteStreamHandler(topic) {
21233
- return this.incomingDataStreamManager.unregisterByteStreamHandler(topic);
20828
+ this.byteStreamHandlers.delete(topic);
21234
20829
  }
21235
20830
  /**
21236
20831
  * Establishes the participant as a receiver for calls of the specified RPC method.
@@ -21272,6 +20867,44 @@ var Room = class _Room extends eventsExports.EventEmitter {
21272
20867
  unregisterRpcMethod(method) {
21273
20868
  this.rpcHandlers.delete(method);
21274
20869
  }
20870
+ handleIncomingRpcRequest(callerIdentity, requestId, method, payload, responseTimeout, version2) {
20871
+ return __awaiter(this, void 0, void 0, function* () {
20872
+ yield this.engine.publishRpcAck(callerIdentity, requestId);
20873
+ if (version2 !== 1) {
20874
+ yield this.engine.publishRpcResponse(callerIdentity, requestId, null, RpcError.builtIn("UNSUPPORTED_VERSION"));
20875
+ return;
20876
+ }
20877
+ const handler = this.rpcHandlers.get(method);
20878
+ if (!handler) {
20879
+ yield this.engine.publishRpcResponse(callerIdentity, requestId, null, RpcError.builtIn("UNSUPPORTED_METHOD"));
20880
+ return;
20881
+ }
20882
+ let responseError = null;
20883
+ let responsePayload = null;
20884
+ try {
20885
+ const response = yield handler({
20886
+ requestId,
20887
+ callerIdentity,
20888
+ payload,
20889
+ responseTimeout
20890
+ });
20891
+ if (byteLength(response) > MAX_PAYLOAD_BYTES) {
20892
+ responseError = RpcError.builtIn("RESPONSE_PAYLOAD_TOO_LARGE");
20893
+ console.warn("RPC Response payload too large for ".concat(method));
20894
+ } else {
20895
+ responsePayload = response;
20896
+ }
20897
+ } catch (error) {
20898
+ if (error instanceof RpcError) {
20899
+ responseError = error;
20900
+ } else {
20901
+ console.warn("Uncaught error returned by RPC handler for ".concat(method, ". Returning APPLICATION_ERROR instead."), error);
20902
+ responseError = RpcError.builtIn("APPLICATION_ERROR");
20903
+ }
20904
+ }
20905
+ yield this.engine.publishRpcResponse(callerIdentity, requestId, responsePayload, responseError);
20906
+ });
20907
+ }
21275
20908
  /**
21276
20909
  * @experimental
21277
20910
  */
@@ -21436,9 +21069,6 @@ var Room = class _Room extends eventsExports.EventEmitter {
21436
21069
  if (this.e2eeManager) {
21437
21070
  this.e2eeManager.setupEngine(this.engine);
21438
21071
  }
21439
- if (this.outgoingDataStreamManager) {
21440
- this.outgoingDataStreamManager.setupEngine(this.engine);
21441
- }
21442
21072
  }
21443
21073
  /**
21444
21074
  * getLocalDevices abstracts navigator.mediaDevices.enumerateDevices.
@@ -21649,7 +21279,7 @@ var Room = class _Room extends eventsExports.EventEmitter {
21649
21279
  return __awaiter(this, arguments, void 0, function(kind, deviceId) {
21650
21280
  var _this3 = this;
21651
21281
  let exact = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : true;
21652
- return (function* () {
21282
+ return function* () {
21653
21283
  var _a, _b, _c, _d, _e, _f;
21654
21284
  var _g;
21655
21285
  let success = true;
@@ -21723,7 +21353,7 @@ var Room = class _Room extends eventsExports.EventEmitter {
21723
21353
  _this3.emit(RoomEvent.ActiveDeviceChanged, kind, deviceId);
21724
21354
  }
21725
21355
  return success;
21726
- })();
21356
+ }();
21727
21357
  });
21728
21358
  }
21729
21359
  setupLocalParticipantEvents() {
@@ -21785,10 +21415,7 @@ var Room = class _Room extends eventsExports.EventEmitter {
21785
21415
  adaptiveStreamSettings = {};
21786
21416
  }
21787
21417
  }
21788
- const publication = participant.addSubscribedMediaTrack(mediaTrack, trackId, stream, receiver, adaptiveStreamSettings);
21789
- if ((publication === null || publication === void 0 ? void 0 : publication.isEncrypted) && !this.e2eeManager) {
21790
- this.emit(RoomEvent.EncryptionError, new Error("Encrypted ".concat(publication.source, " track received from participant ").concat(participant.sid, ", but room does not have encryption enabled!")));
21791
- }
21418
+ participant.addSubscribedMediaTrack(mediaTrack, trackId, stream, receiver, adaptiveStreamSettings);
21792
21419
  }
21793
21420
  handleDisconnect() {
21794
21421
  let shouldStopTracks = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true;
@@ -21798,7 +21425,6 @@ var Room = class _Room extends eventsExports.EventEmitter {
21798
21425
  this.isResuming = false;
21799
21426
  this.bufferedEvents = [];
21800
21427
  this.transcriptionReceivedTimes.clear();
21801
- this.incomingDataStreamManager.clearHandlersAndControllers();
21802
21428
  if (this.state === ConnectionState.Disconnected) {
21803
21429
  return;
21804
21430
  }
@@ -21849,7 +21475,6 @@ var Room = class _Room extends eventsExports.EventEmitter {
21849
21475
  if (!participant) {
21850
21476
  return;
21851
21477
  }
21852
- this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(identity);
21853
21478
  participant.trackPublications.forEach((publication) => {
21854
21479
  participant.unpublishTrack(publication.trackSid, true);
21855
21480
  });
@@ -21857,44 +21482,99 @@ var Room = class _Room extends eventsExports.EventEmitter {
21857
21482
  participant.setDisconnected();
21858
21483
  (_a = this.localParticipant) === null || _a === void 0 ? void 0 : _a.handleParticipantDisconnected(participant.identity);
21859
21484
  }
21860
- handleIncomingRpcRequest(callerIdentity, requestId, method, payload, responseTimeout, version2) {
21485
+ handleStreamHeader(streamHeader, participantIdentity) {
21861
21486
  return __awaiter(this, void 0, void 0, function* () {
21862
- yield this.engine.publishRpcAck(callerIdentity, requestId);
21863
- if (version2 !== 1) {
21864
- yield this.engine.publishRpcResponse(callerIdentity, requestId, null, RpcError.builtIn("UNSUPPORTED_VERSION"));
21865
- return;
21866
- }
21867
- const handler = this.rpcHandlers.get(method);
21868
- if (!handler) {
21869
- yield this.engine.publishRpcResponse(callerIdentity, requestId, null, RpcError.builtIn("UNSUPPORTED_METHOD"));
21870
- return;
21871
- }
21872
- let responseError = null;
21873
- let responsePayload = null;
21874
- try {
21875
- const response = yield handler({
21876
- requestId,
21877
- callerIdentity,
21878
- payload,
21879
- responseTimeout
21880
- });
21881
- if (byteLength(response) > MAX_PAYLOAD_BYTES) {
21882
- responseError = RpcError.builtIn("RESPONSE_PAYLOAD_TOO_LARGE");
21883
- console.warn("RPC Response payload too large for ".concat(method));
21884
- } else {
21885
- responsePayload = response;
21487
+ var _a;
21488
+ if (streamHeader.contentHeader.case === "byteHeader") {
21489
+ const streamHandlerCallback = this.byteStreamHandlers.get(streamHeader.topic);
21490
+ if (!streamHandlerCallback) {
21491
+ this.log.debug("ignoring incoming byte stream due to no handler for topic", streamHeader.topic);
21492
+ return;
21886
21493
  }
21887
- } catch (error) {
21888
- if (error instanceof RpcError) {
21889
- responseError = error;
21890
- } else {
21891
- console.warn("Uncaught error returned by RPC handler for ".concat(method, ". Returning APPLICATION_ERROR instead."), error);
21892
- responseError = RpcError.builtIn("APPLICATION_ERROR");
21494
+ let streamController;
21495
+ const info = {
21496
+ id: streamHeader.streamId,
21497
+ name: (_a = streamHeader.contentHeader.value.name) !== null && _a !== void 0 ? _a : "unknown",
21498
+ mimeType: streamHeader.mimeType,
21499
+ size: streamHeader.totalLength ? Number(streamHeader.totalLength) : void 0,
21500
+ topic: streamHeader.topic,
21501
+ timestamp: bigIntToNumber(streamHeader.timestamp),
21502
+ attributes: streamHeader.attributes
21503
+ };
21504
+ const stream = new ReadableStream({
21505
+ start: (controller) => {
21506
+ streamController = controller;
21507
+ this.byteStreamControllers.set(streamHeader.streamId, {
21508
+ info,
21509
+ controller: streamController,
21510
+ startTime: Date.now()
21511
+ });
21512
+ }
21513
+ });
21514
+ streamHandlerCallback(new ByteStreamReader(info, stream, bigIntToNumber(streamHeader.totalLength)), {
21515
+ identity: participantIdentity
21516
+ });
21517
+ } else if (streamHeader.contentHeader.case === "textHeader") {
21518
+ const streamHandlerCallback = this.textStreamHandlers.get(streamHeader.topic);
21519
+ if (!streamHandlerCallback) {
21520
+ this.log.debug("ignoring incoming text stream due to no handler for topic", streamHeader.topic);
21521
+ return;
21893
21522
  }
21523
+ let streamController;
21524
+ const info = {
21525
+ id: streamHeader.streamId,
21526
+ mimeType: streamHeader.mimeType,
21527
+ size: streamHeader.totalLength ? Number(streamHeader.totalLength) : void 0,
21528
+ topic: streamHeader.topic,
21529
+ timestamp: Number(streamHeader.timestamp),
21530
+ attributes: streamHeader.attributes
21531
+ };
21532
+ const stream = new ReadableStream({
21533
+ start: (controller) => {
21534
+ streamController = controller;
21535
+ this.textStreamControllers.set(streamHeader.streamId, {
21536
+ info,
21537
+ controller: streamController,
21538
+ startTime: Date.now()
21539
+ });
21540
+ }
21541
+ });
21542
+ streamHandlerCallback(new TextStreamReader(info, stream, bigIntToNumber(streamHeader.totalLength)), {
21543
+ identity: participantIdentity
21544
+ });
21894
21545
  }
21895
- yield this.engine.publishRpcResponse(callerIdentity, requestId, responsePayload, responseError);
21896
21546
  });
21897
21547
  }
21548
+ handleStreamChunk(chunk) {
21549
+ const fileBuffer = this.byteStreamControllers.get(chunk.streamId);
21550
+ if (fileBuffer) {
21551
+ if (chunk.content.length > 0) {
21552
+ fileBuffer.controller.enqueue(chunk);
21553
+ }
21554
+ }
21555
+ const textBuffer = this.textStreamControllers.get(chunk.streamId);
21556
+ if (textBuffer) {
21557
+ if (chunk.content.length > 0) {
21558
+ textBuffer.controller.enqueue(chunk);
21559
+ }
21560
+ }
21561
+ }
21562
+ handleStreamTrailer(trailer) {
21563
+ const textBuffer = this.textStreamControllers.get(trailer.streamId);
21564
+ if (textBuffer) {
21565
+ textBuffer.info.attributes = Object.assign(Object.assign({}, textBuffer.info.attributes), trailer.attributes);
21566
+ textBuffer.controller.close();
21567
+ this.textStreamControllers.delete(trailer.streamId);
21568
+ }
21569
+ const fileBuffer = this.byteStreamControllers.get(trailer.streamId);
21570
+ if (fileBuffer) {
21571
+ {
21572
+ fileBuffer.info.attributes = Object.assign(Object.assign({}, fileBuffer.info.attributes), trailer.attributes);
21573
+ fileBuffer.controller.close();
21574
+ this.byteStreamControllers.delete(trailer.streamId);
21575
+ }
21576
+ }
21577
+ }
21898
21578
  /**
21899
21579
  * attempt to select the default devices if the previously selected devices are no longer available after a device change event
21900
21580
  */