livekit-client 2.15.3 → 2.15.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +2 -2
  2. package/dist/livekit-client.e2ee.worker.js +1 -1
  3. package/dist/livekit-client.e2ee.worker.js.map +1 -1
  4. package/dist/livekit-client.e2ee.worker.mjs +329 -124
  5. package/dist/livekit-client.e2ee.worker.mjs.map +1 -1
  6. package/dist/livekit-client.esm.mjs +868 -548
  7. package/dist/livekit-client.esm.mjs.map +1 -1
  8. package/dist/livekit-client.umd.js +1 -1
  9. package/dist/livekit-client.umd.js.map +1 -1
  10. package/dist/src/api/SignalClient.d.ts.map +1 -1
  11. package/dist/src/e2ee/worker/FrameCryptor.d.ts +0 -46
  12. package/dist/src/e2ee/worker/FrameCryptor.d.ts.map +1 -1
  13. package/dist/src/e2ee/worker/naluUtils.d.ts +27 -0
  14. package/dist/src/e2ee/worker/naluUtils.d.ts.map +1 -0
  15. package/dist/src/index.d.ts +2 -2
  16. package/dist/src/index.d.ts.map +1 -1
  17. package/dist/src/room/Room.d.ts +6 -10
  18. package/dist/src/room/Room.d.ts.map +1 -1
  19. package/dist/src/room/data-stream/incoming/IncomingDataStreamManager.d.ts +20 -0
  20. package/dist/src/room/data-stream/incoming/IncomingDataStreamManager.d.ts.map +1 -0
  21. package/dist/src/room/{StreamReader.d.ts → data-stream/incoming/StreamReader.d.ts} +32 -6
  22. package/dist/src/room/data-stream/incoming/StreamReader.d.ts.map +1 -0
  23. package/dist/src/room/data-stream/outgoing/OutgoingDataStreamManager.d.ts +27 -0
  24. package/dist/src/room/data-stream/outgoing/OutgoingDataStreamManager.d.ts.map +1 -0
  25. package/dist/src/room/{StreamWriter.d.ts → data-stream/outgoing/StreamWriter.d.ts} +1 -1
  26. package/dist/src/room/data-stream/outgoing/StreamWriter.d.ts.map +1 -0
  27. package/dist/src/room/errors.d.ts +13 -0
  28. package/dist/src/room/errors.d.ts.map +1 -1
  29. package/dist/src/room/participant/LocalParticipant.d.ts +33 -20
  30. package/dist/src/room/participant/LocalParticipant.d.ts.map +1 -1
  31. package/dist/src/room/track/LocalTrack.d.ts +8 -2
  32. package/dist/src/room/track/LocalTrack.d.ts.map +1 -1
  33. package/dist/src/room/track/record.d.ts.map +1 -1
  34. package/dist/src/room/types.d.ts +17 -1
  35. package/dist/src/room/types.d.ts.map +1 -1
  36. package/dist/ts4.2/src/e2ee/worker/FrameCryptor.d.ts +0 -46
  37. package/dist/ts4.2/src/e2ee/worker/naluUtils.d.ts +27 -0
  38. package/dist/ts4.2/src/index.d.ts +2 -2
  39. package/dist/ts4.2/src/room/Room.d.ts +6 -10
  40. package/dist/ts4.2/src/room/data-stream/incoming/IncomingDataStreamManager.d.ts +20 -0
  41. package/dist/ts4.2/src/room/{StreamReader.d.ts → data-stream/incoming/StreamReader.d.ts} +32 -6
  42. package/dist/ts4.2/src/room/data-stream/outgoing/OutgoingDataStreamManager.d.ts +27 -0
  43. package/dist/ts4.2/src/room/{StreamWriter.d.ts → data-stream/outgoing/StreamWriter.d.ts} +1 -1
  44. package/dist/ts4.2/src/room/errors.d.ts +13 -0
  45. package/dist/ts4.2/src/room/participant/LocalParticipant.d.ts +33 -20
  46. package/dist/ts4.2/src/room/track/LocalTrack.d.ts +8 -2
  47. package/dist/ts4.2/src/room/types.d.ts +17 -1
  48. package/package.json +1 -1
  49. package/src/api/SignalClient.ts +6 -0
  50. package/src/e2ee/worker/FrameCryptor.ts +48 -139
  51. package/src/e2ee/worker/naluUtils.ts +328 -0
  52. package/src/index.ts +2 -2
  53. package/src/room/Room.ts +94 -207
  54. package/src/room/data-stream/incoming/IncomingDataStreamManager.ts +247 -0
  55. package/src/room/data-stream/incoming/StreamReader.ts +317 -0
  56. package/src/room/data-stream/outgoing/OutgoingDataStreamManager.ts +316 -0
  57. package/src/room/{StreamWriter.ts → data-stream/outgoing/StreamWriter.ts} +1 -1
  58. package/src/room/errors.ts +34 -0
  59. package/src/room/participant/LocalParticipant.ts +48 -299
  60. package/src/room/track/LocalAudioTrack.ts +2 -2
  61. package/src/room/track/LocalTrack.ts +75 -49
  62. package/src/room/track/record.ts +15 -2
  63. package/src/room/types.ts +22 -1
  64. package/src/room/utils.ts +3 -3
  65. package/dist/src/room/StreamReader.d.ts.map +0 -1
  66. package/dist/src/room/StreamWriter.d.ts.map +0 -1
  67. package/src/room/StreamReader.ts +0 -170
@@ -1,4 +1,3 @@
1
- import { Mutex } from '@livekit/mutex';
2
1
  import {
3
2
  AddTrackRequest,
4
3
  AudioTrackFeature,
@@ -7,12 +6,6 @@ import {
7
6
  Codec,
8
7
  DataPacket,
9
8
  DataPacket_Kind,
10
- DataStream_ByteHeader,
11
- DataStream_Chunk,
12
- DataStream_Header,
13
- DataStream_OperationType,
14
- DataStream_TextHeader,
15
- DataStream_Trailer,
16
9
  Encryption_Type,
17
10
  JoinResponse,
18
11
  ParticipantInfo,
@@ -34,7 +27,8 @@ import { SignalConnectionState } from '../../api/SignalClient';
34
27
  import type { InternalRoomOptions } from '../../options';
35
28
  import { PCTransportState } from '../PCTransportManager';
36
29
  import type RTCEngine from '../RTCEngine';
37
- import { ByteStreamWriter, TextStreamWriter } from '../StreamWriter';
30
+ import type OutgoingDataStreamManager from '../data-stream/outgoing/OutgoingDataStreamManager';
31
+ import type { TextStreamWriter } from '../data-stream/outgoing/StreamWriter';
38
32
  import { defaultVideoCodec } from '../defaults';
39
33
  import {
40
34
  DeviceUnsupportedError,
@@ -76,10 +70,11 @@ import {
76
70
  sourceToKind,
77
71
  } from '../track/utils';
78
72
  import {
79
- type ByteStreamInfo,
80
73
  type ChatMessage,
81
74
  type DataPublishOptions,
75
+ type SendFileOptions,
82
76
  type SendTextOptions,
77
+ type StreamBytesOptions,
83
78
  type StreamTextOptions,
84
79
  type TextStreamInfo,
85
80
  } from '../types';
@@ -96,9 +91,7 @@ import {
96
91
  isSafari17Based,
97
92
  isVideoTrack,
98
93
  isWeb,
99
- numberToBigInt,
100
94
  sleep,
101
- splitUtf8,
102
95
  supportsAV1,
103
96
  supportsVP9,
104
97
  } from '../utils';
@@ -112,8 +105,6 @@ import {
112
105
  getDefaultDegradationPreference,
113
106
  } from './publishUtils';
114
107
 
115
- const STREAM_CHUNK_SIZE = 15_000;
116
-
117
108
  export default class LocalParticipant extends Participant {
118
109
  audioTrackPublications: Map<string, LocalTrackPublication>;
119
110
 
@@ -157,6 +148,8 @@ export default class LocalParticipant extends Participant {
157
148
 
158
149
  private rpcHandlers: Map<string, (data: RpcInvocationData) => Promise<string>>;
159
150
 
151
+ private roomOutgoingDataStreamManager: OutgoingDataStreamManager;
152
+
160
153
  private pendingSignalRequests: Map<
161
154
  number,
162
155
  {
@@ -185,6 +178,7 @@ export default class LocalParticipant extends Participant {
185
178
  engine: RTCEngine,
186
179
  options: InternalRoomOptions,
187
180
  roomRpcHandlers: Map<string, (data: RpcInvocationData) => Promise<string>>,
181
+ roomOutgoingDataStreamManager: OutgoingDataStreamManager,
188
182
  ) {
189
183
  super(sid, identity, undefined, undefined, undefined, {
190
184
  loggerName: options.loggerName,
@@ -203,6 +197,7 @@ export default class LocalParticipant extends Participant {
203
197
  ]);
204
198
  this.pendingSignalRequests = new Map();
205
199
  this.rpcHandlers = roomRpcHandlers;
200
+ this.roomOutgoingDataStreamManager = roomOutgoingDataStreamManager;
206
201
  }
207
202
 
208
203
  get lastCameraError(): Error | undefined {
@@ -261,7 +256,7 @@ export default class LocalParticipant extends Participant {
261
256
  .on(EngineEvent.Resuming, this.handleReconnecting)
262
257
  .on(EngineEvent.LocalTrackUnpublished, this.handleLocalTrackUnpublished)
263
258
  .on(EngineEvent.SubscribedQualityUpdate, this.handleSubscribedQualityUpdate)
264
- .on(EngineEvent.Disconnected, this.handleDisconnected)
259
+ .on(EngineEvent.Closing, this.handleClosing)
265
260
  .on(EngineEvent.SignalRequestResponse, this.handleSignalRequestResponse)
266
261
  .on(EngineEvent.DataPacketReceived, this.handleDataPacket);
267
262
  }
@@ -278,7 +273,7 @@ export default class LocalParticipant extends Participant {
278
273
  this.updateTrackSubscriptionPermissions();
279
274
  };
280
275
 
281
- private handleDisconnected = () => {
276
+ private handleClosing = () => {
282
277
  if (this.reconnectFuture) {
283
278
  this.reconnectFuture.promise.catch((e) => this.log.warn(e.message, this.logContext));
284
279
  this.reconnectFuture?.reject?.('Got disconnected during reconnection attempt');
@@ -558,10 +553,14 @@ export default class LocalParticipant extends Participant {
558
553
  }
559
554
 
560
555
  for (const localTrack of localTracks) {
556
+ const opts: TrackPublishOptions = {
557
+ ...this.roomOptions.publishDefaults,
558
+ ...options,
559
+ };
561
560
  if (
562
561
  source === Track.Source.Microphone &&
563
562
  isAudioTrack(localTrack) &&
564
- publishOptions?.preConnectBuffer
563
+ opts.preConnectBuffer
565
564
  ) {
566
565
  this.log.info('starting preconnect buffer for microphone', {
567
566
  ...this.logContext,
@@ -1302,6 +1301,7 @@ export default class LocalParticipant extends Participant {
1302
1301
  ti.audioFeatures.includes(AudioTrackFeature.TF_PRECONNECT_BUFFER)
1303
1302
  ) {
1304
1303
  const stream = track.getPreConnectBuffer();
1304
+ const mimeType = track.getPreConnectBufferMimeType();
1305
1305
  // TODO: we're registering the listener after negotiation, so there might be a race
1306
1306
  this.on(ParticipantEvent.LocalTrackSubscribed, (pub) => {
1307
1307
  if (pub.trackSid === ti.sid) {
@@ -1335,7 +1335,7 @@ export default class LocalParticipant extends Participant {
1335
1335
  });
1336
1336
  const writer = await this.streamBytes({
1337
1337
  name: 'preconnect-buffer',
1338
- mimeType: 'audio/opus',
1338
+ mimeType,
1339
1339
  topic: 'lk.agent.pre-connect-audio-buffer',
1340
1340
  destinationIdentities: [agent.identity],
1341
1341
  attributes: {
@@ -1685,6 +1685,7 @@ export default class LocalParticipant extends Participant {
1685
1685
  await this.engine.sendDataPacket(packet, DataPacket_Kind.RELIABLE);
1686
1686
  }
1687
1687
 
1688
+ /** @deprecated Consider migrating to {@link sendText} */
1688
1689
  async sendChatMessage(text: string, options?: SendTextOptions): Promise<ChatMessage> {
1689
1690
  const msg = {
1690
1691
  id: crypto.randomUUID(),
@@ -1707,6 +1708,7 @@ export default class LocalParticipant extends Participant {
1707
1708
  return msg;
1708
1709
  }
1709
1710
 
1711
+ /** @deprecated Consider migrating to {@link sendText} */
1710
1712
  async editChatMessage(editText: string, originalMessage: ChatMessage) {
1711
1713
  const msg = {
1712
1714
  ...originalMessage,
@@ -1728,300 +1730,47 @@ export default class LocalParticipant extends Participant {
1728
1730
  return msg;
1729
1731
  }
1730
1732
 
1733
+ /**
1734
+ * Sends the given string to participants in the room via the data channel.
1735
+ * For longer messages, consider using {@link streamText} instead.
1736
+ *
1737
+ * @param text The text payload
1738
+ * @param options.topic Topic identifier used to route the stream to appropriate handlers.
1739
+ */
1731
1740
  async sendText(text: string, options?: SendTextOptions): Promise<TextStreamInfo> {
1732
- const streamId = crypto.randomUUID();
1733
- const textInBytes = new TextEncoder().encode(text);
1734
- const totalTextLength = textInBytes.byteLength;
1735
-
1736
- const fileIds = options?.attachments?.map(() => crypto.randomUUID());
1737
-
1738
- const progresses = new Array<number>(fileIds ? fileIds.length + 1 : 1).fill(0);
1739
-
1740
- const handleProgress = (progress: number, idx: number) => {
1741
- progresses[idx] = progress;
1742
- const totalProgress = progresses.reduce((acc, val) => acc + val, 0);
1743
- options?.onProgress?.(totalProgress);
1744
- };
1745
-
1746
- const writer = await this.streamText({
1747
- streamId,
1748
- totalSize: totalTextLength,
1749
- destinationIdentities: options?.destinationIdentities,
1750
- topic: options?.topic,
1751
- attachedStreamIds: fileIds,
1752
- attributes: options?.attributes,
1753
- });
1754
-
1755
- await writer.write(text);
1756
- // set text part of progress to 1
1757
- handleProgress(1, 0);
1758
-
1759
- await writer.close();
1760
-
1761
- if (options?.attachments && fileIds) {
1762
- await Promise.all(
1763
- options.attachments.map(async (file, idx) =>
1764
- this._sendFile(fileIds[idx], file, {
1765
- topic: options.topic,
1766
- mimeType: file.type,
1767
- onProgress: (progress) => {
1768
- handleProgress(progress, idx + 1);
1769
- },
1770
- }),
1771
- ),
1772
- );
1773
- }
1774
- return writer.info;
1741
+ return this.roomOutgoingDataStreamManager.sendText(text, options);
1775
1742
  }
1776
1743
 
1777
1744
  /**
1745
+ * Creates a new TextStreamWriter which can be used to stream text incrementally
1746
+ * to participants in the room via the data channel.
1747
+ *
1748
+ * @param options.topic Topic identifier used to route the stream to appropriate handlers.
1749
+ *
1778
1750
  * @internal
1779
1751
  * @experimental CAUTION, might get removed in a minor release
1780
1752
  */
1781
1753
  async streamText(options?: StreamTextOptions): Promise<TextStreamWriter> {
1782
- const streamId = options?.streamId ?? crypto.randomUUID();
1783
-
1784
- const info: TextStreamInfo = {
1785
- id: streamId,
1786
- mimeType: 'text/plain',
1787
- timestamp: Date.now(),
1788
- topic: options?.topic ?? '',
1789
- size: options?.totalSize,
1790
- attributes: options?.attributes,
1791
- };
1792
- const header = new DataStream_Header({
1793
- streamId,
1794
- mimeType: info.mimeType,
1795
- topic: info.topic,
1796
- timestamp: numberToBigInt(info.timestamp),
1797
- totalLength: numberToBigInt(options?.totalSize),
1798
- attributes: info.attributes,
1799
- contentHeader: {
1800
- case: 'textHeader',
1801
- value: new DataStream_TextHeader({
1802
- version: options?.version,
1803
- attachedStreamIds: options?.attachedStreamIds,
1804
- replyToStreamId: options?.replyToStreamId,
1805
- operationType:
1806
- options?.type === 'update'
1807
- ? DataStream_OperationType.UPDATE
1808
- : DataStream_OperationType.CREATE,
1809
- }),
1810
- },
1811
- });
1812
- const destinationIdentities = options?.destinationIdentities;
1813
- const packet = new DataPacket({
1814
- destinationIdentities,
1815
- value: {
1816
- case: 'streamHeader',
1817
- value: header,
1818
- },
1819
- });
1820
- await this.engine.sendDataPacket(packet, DataPacket_Kind.RELIABLE);
1821
-
1822
- let chunkId = 0;
1823
- const localP = this;
1824
-
1825
- const writableStream = new WritableStream<string>({
1826
- // Implement the sink
1827
- async write(text) {
1828
- for (const textByteChunk of splitUtf8(text, STREAM_CHUNK_SIZE)) {
1829
- await localP.engine.waitForBufferStatusLow(DataPacket_Kind.RELIABLE);
1830
- const chunk = new DataStream_Chunk({
1831
- content: textByteChunk,
1832
- streamId,
1833
- chunkIndex: numberToBigInt(chunkId),
1834
- });
1835
- const chunkPacket = new DataPacket({
1836
- destinationIdentities,
1837
- value: {
1838
- case: 'streamChunk',
1839
- value: chunk,
1840
- },
1841
- });
1842
- await localP.engine.sendDataPacket(chunkPacket, DataPacket_Kind.RELIABLE);
1843
-
1844
- chunkId += 1;
1845
- }
1846
- },
1847
- async close() {
1848
- const trailer = new DataStream_Trailer({
1849
- streamId,
1850
- });
1851
- const trailerPacket = new DataPacket({
1852
- destinationIdentities,
1853
- value: {
1854
- case: 'streamTrailer',
1855
- value: trailer,
1856
- },
1857
- });
1858
- await localP.engine.sendDataPacket(trailerPacket, DataPacket_Kind.RELIABLE);
1859
- },
1860
- abort(err) {
1861
- console.log('Sink error:', err);
1862
- // TODO handle aborts to signal something to receiver side
1863
- },
1864
- });
1865
-
1866
- let onEngineClose = async () => {
1867
- await writer.close();
1868
- };
1869
-
1870
- localP.engine.once(EngineEvent.Closing, onEngineClose);
1871
-
1872
- const writer = new TextStreamWriter(writableStream, info, () =>
1873
- this.engine.off(EngineEvent.Closing, onEngineClose),
1874
- );
1875
-
1876
- return writer;
1754
+ return this.roomOutgoingDataStreamManager.streamText(options);
1877
1755
  }
1878
1756
 
1879
- async sendFile(
1880
- file: File,
1881
- options?: {
1882
- mimeType?: string;
1883
- topic?: string;
1884
- destinationIdentities?: Array<string>;
1885
- onProgress?: (progress: number) => void;
1886
- },
1887
- ): Promise<{ id: string }> {
1888
- const streamId = crypto.randomUUID();
1889
- await this._sendFile(streamId, file, options);
1890
- return { id: streamId };
1891
- }
1892
-
1893
- private async _sendFile(
1894
- streamId: string,
1895
- file: File,
1896
- options?: {
1897
- mimeType?: string;
1898
- topic?: string;
1899
- encryptionType?: Encryption_Type.NONE;
1900
- destinationIdentities?: Array<string>;
1901
- onProgress?: (progress: number) => void;
1902
- },
1903
- ) {
1904
- const writer = await this.streamBytes({
1905
- streamId,
1906
- totalSize: file.size,
1907
- name: file.name,
1908
- mimeType: options?.mimeType ?? file.type,
1909
- topic: options?.topic,
1910
- destinationIdentities: options?.destinationIdentities,
1911
- });
1912
- const reader = file.stream().getReader();
1913
- while (true) {
1914
- const { done, value } = await reader.read();
1915
- if (done) {
1916
- break;
1917
- }
1918
- await writer.write(value);
1919
- }
1920
- await writer.close();
1921
- return writer.info;
1757
+ /** Send a File to all participants in the room via the data channel.
1758
+ * @param file The File object payload
1759
+ * @param options.topic Topic identifier used to route the stream to appropriate handlers.
1760
+ * @param options.onProgress A callback function used to monitor the upload progress percentage.
1761
+ */
1762
+ async sendFile(file: File, options?: SendFileOptions): Promise<{ id: string }> {
1763
+ return this.roomOutgoingDataStreamManager.sendFile(file, options);
1922
1764
  }
1923
1765
 
1924
- async streamBytes(options?: {
1925
- name?: string;
1926
- topic?: string;
1927
- attributes?: Record<string, string>;
1928
- destinationIdentities?: Array<string>;
1929
- streamId?: string;
1930
- mimeType?: string;
1931
- totalSize?: number;
1932
- }) {
1933
- const streamId = options?.streamId ?? crypto.randomUUID();
1934
- const destinationIdentities = options?.destinationIdentities;
1935
-
1936
- const info: ByteStreamInfo = {
1937
- id: streamId,
1938
- mimeType: options?.mimeType ?? 'application/octet-stream',
1939
- topic: options?.topic ?? '',
1940
- timestamp: Date.now(),
1941
- attributes: options?.attributes,
1942
- size: options?.totalSize,
1943
- name: options?.name ?? 'unknown',
1944
- };
1945
-
1946
- const header = new DataStream_Header({
1947
- totalLength: numberToBigInt(info.size ?? 0),
1948
- mimeType: info.mimeType,
1949
- streamId,
1950
- topic: info.topic,
1951
- timestamp: numberToBigInt(Date.now()),
1952
- attributes: info.attributes,
1953
- contentHeader: {
1954
- case: 'byteHeader',
1955
- value: new DataStream_ByteHeader({
1956
- name: info.name,
1957
- }),
1958
- },
1959
- });
1960
-
1961
- const packet = new DataPacket({
1962
- destinationIdentities,
1963
- value: {
1964
- case: 'streamHeader',
1965
- value: header,
1966
- },
1967
- });
1968
-
1969
- await this.engine.sendDataPacket(packet, DataPacket_Kind.RELIABLE);
1970
-
1971
- let chunkId = 0;
1972
- const writeMutex = new Mutex();
1973
- const engine = this.engine;
1974
- const log = this.log;
1975
-
1976
- const writableStream = new WritableStream<Uint8Array>({
1977
- async write(chunk) {
1978
- const unlock = await writeMutex.lock();
1979
-
1980
- let byteOffset = 0;
1981
- try {
1982
- while (byteOffset < chunk.byteLength) {
1983
- const subChunk = chunk.slice(byteOffset, byteOffset + STREAM_CHUNK_SIZE);
1984
- await engine.waitForBufferStatusLow(DataPacket_Kind.RELIABLE);
1985
- const chunkPacket = new DataPacket({
1986
- destinationIdentities,
1987
- value: {
1988
- case: 'streamChunk',
1989
- value: new DataStream_Chunk({
1990
- content: subChunk,
1991
- streamId,
1992
- chunkIndex: numberToBigInt(chunkId),
1993
- }),
1994
- },
1995
- });
1996
- await engine.sendDataPacket(chunkPacket, DataPacket_Kind.RELIABLE);
1997
- chunkId += 1;
1998
- byteOffset += subChunk.byteLength;
1999
- }
2000
- } finally {
2001
- unlock();
2002
- }
2003
- },
2004
- async close() {
2005
- const trailer = new DataStream_Trailer({
2006
- streamId,
2007
- });
2008
- const trailerPacket = new DataPacket({
2009
- destinationIdentities,
2010
- value: {
2011
- case: 'streamTrailer',
2012
- value: trailer,
2013
- },
2014
- });
2015
- await engine.sendDataPacket(trailerPacket, DataPacket_Kind.RELIABLE);
2016
- },
2017
- abort(err) {
2018
- log.error('Sink error:', err);
2019
- },
2020
- });
2021
-
2022
- const byteWriter = new ByteStreamWriter(writableStream, info);
2023
-
2024
- return byteWriter;
1766
+ /**
1767
+ * Stream bytes incrementally to participants in the room via the data channel.
1768
+ * For sending files, consider using {@link sendFile} instead.
1769
+ *
1770
+ * @param options.topic Topic identifier used to route the stream to appropriate handlers.
1771
+ */
1772
+ async streamBytes(options?: StreamBytesOptions) {
1773
+ return this.roomOutgoingDataStreamManager.streamBytes(options);
2025
1774
  }
2026
1775
 
2027
1776
  /**
@@ -169,7 +169,7 @@ export default class LocalAudioTrack extends LocalTrack<Track.Kind.Audio> {
169
169
  };
170
170
 
171
171
  async setProcessor(processor: TrackProcessor<Track.Kind.Audio, AudioProcessorOptions>) {
172
- const unlock = await this.processorLock.lock();
172
+ const unlock = await this.trackChangeLock.lock();
173
173
  try {
174
174
  if (!isReactNative() && !this.audioContext) {
175
175
  throw Error(
@@ -177,7 +177,7 @@ export default class LocalAudioTrack extends LocalTrack<Track.Kind.Audio> {
177
177
  );
178
178
  }
179
179
  if (this.processor) {
180
- await this.stopProcessor();
180
+ await this.internalStopProcessor();
181
181
  }
182
182
 
183
183
  const processorOptions = {
@@ -57,15 +57,13 @@ export default abstract class LocalTrack<
57
57
 
58
58
  protected processor?: TrackProcessor<TrackKind, any>;
59
59
 
60
- protected processorLock: Mutex;
61
-
62
60
  protected audioContext?: AudioContext;
63
61
 
64
62
  protected manuallyStopped: boolean = false;
65
63
 
66
64
  protected localTrackRecorder: LocalTrackRecorder<typeof this> | undefined;
67
65
 
68
- private restartLock: Mutex;
66
+ protected trackChangeLock: Mutex;
69
67
 
70
68
  /**
71
69
  *
@@ -86,9 +84,14 @@ export default abstract class LocalTrack<
86
84
  this.providedByUser = userProvidedTrack;
87
85
  this.muteLock = new Mutex();
88
86
  this.pauseUpstreamLock = new Mutex();
89
- this.processorLock = new Mutex();
90
- this.restartLock = new Mutex();
91
- this.setMediaStreamTrack(mediaTrack, true);
87
+ this.trackChangeLock = new Mutex();
88
+ this.trackChangeLock.lock().then(async (unlock) => {
89
+ try {
90
+ await this.setMediaStreamTrack(mediaTrack, true);
91
+ } finally {
92
+ unlock();
93
+ }
94
+ });
92
95
 
93
96
  // added to satisfy TS compiler, constraints are synced with MediaStreamTrack
94
97
  this._constraints = mediaTrack.getConstraints();
@@ -171,27 +174,22 @@ export default abstract class LocalTrack<
171
174
  }
172
175
  let processedTrack: MediaStreamTrack | undefined;
173
176
  if (this.processor && newTrack) {
174
- const unlock = await this.processorLock.lock();
175
- try {
176
- this.log.debug('restarting processor', this.logContext);
177
- if (this.kind === 'unknown') {
178
- throw TypeError('cannot set processor on track of unknown kind');
179
- }
177
+ this.log.debug('restarting processor', this.logContext);
178
+ if (this.kind === 'unknown') {
179
+ throw TypeError('cannot set processor on track of unknown kind');
180
+ }
180
181
 
181
- if (this.processorElement) {
182
- attachToElement(newTrack, this.processorElement);
183
- // ensure the processorElement itself stays muted
184
- this.processorElement.muted = true;
185
- }
186
- await this.processor.restart({
187
- track: newTrack,
188
- kind: this.kind,
189
- element: this.processorElement,
190
- });
191
- processedTrack = this.processor.processedTrack;
192
- } finally {
193
- unlock();
182
+ if (this.processorElement) {
183
+ attachToElement(newTrack, this.processorElement);
184
+ // ensure the processorElement itself stays muted
185
+ this.processorElement.muted = true;
194
186
  }
187
+ await this.processor.restart({
188
+ track: newTrack,
189
+ kind: this.kind,
190
+ element: this.processorElement,
191
+ });
192
+ processedTrack = this.processor.processedTrack;
195
193
  }
196
194
  if (this.sender && this.sender.transport?.state !== 'closed') {
197
195
  await this.sender.replaceTrack(processedTrack ?? newTrack);
@@ -290,36 +288,42 @@ export default abstract class LocalTrack<
290
288
  track: MediaStreamTrack,
291
289
  userProvidedOrOptions: boolean | ReplaceTrackOptions | undefined,
292
290
  ) {
293
- if (!this.sender) {
294
- throw new TrackInvalidError('unable to replace an unpublished track');
295
- }
291
+ const unlock = await this.trackChangeLock.lock();
292
+ try {
293
+ if (!this.sender) {
294
+ throw new TrackInvalidError('unable to replace an unpublished track');
295
+ }
296
296
 
297
- let userProvidedTrack: boolean | undefined;
298
- let stopProcessor: boolean | undefined;
297
+ let userProvidedTrack: boolean | undefined;
298
+ let stopProcessor: boolean | undefined;
299
299
 
300
- if (typeof userProvidedOrOptions === 'boolean') {
301
- userProvidedTrack = userProvidedOrOptions;
302
- } else if (userProvidedOrOptions !== undefined) {
303
- userProvidedTrack = userProvidedOrOptions.userProvidedTrack;
304
- stopProcessor = userProvidedOrOptions.stopProcessor;
305
- }
300
+ if (typeof userProvidedOrOptions === 'boolean') {
301
+ userProvidedTrack = userProvidedOrOptions;
302
+ } else if (userProvidedOrOptions !== undefined) {
303
+ userProvidedTrack = userProvidedOrOptions.userProvidedTrack;
304
+ stopProcessor = userProvidedOrOptions.stopProcessor;
305
+ }
306
306
 
307
- this.providedByUser = userProvidedTrack ?? true;
307
+ this.providedByUser = userProvidedTrack ?? true;
308
308
 
309
- this.log.debug('replace MediaStreamTrack', this.logContext);
310
- await this.setMediaStreamTrack(track);
311
- // this must be synced *after* setting mediaStreamTrack above, since it relies
312
- // on the previous state in order to cleanup
309
+ this.log.debug('replace MediaStreamTrack', this.logContext);
310
+ await this.setMediaStreamTrack(track);
311
+ // this must be synced *after* setting mediaStreamTrack above, since it relies
312
+ // on the previous state in order to cleanup
313
313
 
314
- if (stopProcessor && this.processor) {
315
- await this.stopProcessor();
314
+ if (stopProcessor && this.processor) {
315
+ await this.internalStopProcessor();
316
+ }
317
+ return this;
318
+ } finally {
319
+ unlock();
316
320
  }
317
- return this;
318
321
  }
319
322
 
320
323
  protected async restart(constraints?: MediaTrackConstraints) {
321
324
  this.manuallyStopped = false;
322
- const unlock = await this.restartLock.lock();
325
+ const unlock = await this.trackChangeLock.lock();
326
+
323
327
  try {
324
328
  if (!constraints) {
325
329
  constraints = this._constraints;
@@ -518,7 +522,7 @@ export default abstract class LocalTrack<
518
522
  * @returns
519
523
  */
520
524
  async setProcessor(processor: TrackProcessor<TrackKind>, showProcessedStreamLocally = true) {
521
- const unlock = await this.processorLock.lock();
525
+ const unlock = await this.trackChangeLock.lock();
522
526
  try {
523
527
  this.log.debug('setting up processor', this.logContext);
524
528
 
@@ -534,7 +538,7 @@ export default abstract class LocalTrack<
534
538
  this.log.debug('processor initialized', this.logContext);
535
539
 
536
540
  if (this.processor) {
537
- await this.stopProcessor();
541
+ await this.internalStopProcessor();
538
542
  }
539
543
  if (this.kind === 'unknown') {
540
544
  throw TypeError('cannot set processor on track of unknown kind');
@@ -589,8 +593,21 @@ export default abstract class LocalTrack<
589
593
  * @returns
590
594
  */
591
595
  async stopProcessor(keepElement = true) {
592
- if (!this.processor) return;
596
+ const unlock = await this.trackChangeLock.lock();
597
+ try {
598
+ await this.internalStopProcessor(keepElement);
599
+ } finally {
600
+ unlock();
601
+ }
602
+ }
593
603
 
604
+ /**
605
+ * @internal
606
+ * This method assumes the caller has acquired a trackChangeLock already.
607
+ * The public facing method for stopping the processor is `stopProcessor` and it wraps this method in the trackChangeLock.
608
+ */
609
+ protected async internalStopProcessor(keepElement = true) {
610
+ if (!this.processor) return;
594
611
  this.log.debug('stopping processor', this.logContext);
595
612
  this.processor.processedTrack?.stop();
596
613
  await this.processor.destroy();
@@ -617,8 +634,13 @@ export default abstract class LocalTrack<
617
634
  }
618
635
 
619
636
  if (!this.localTrackRecorder) {
637
+ let mimeType = 'audio/webm;codecs=opus';
638
+ if (!MediaRecorder.isTypeSupported(mimeType)) {
639
+ // iOS currently only supports video/mp4 as a mime type - even for audio.
640
+ mimeType = 'video/mp4';
641
+ }
620
642
  this.localTrackRecorder = new LocalTrackRecorder(this, {
621
- mimeType: 'audio/webm;codecs=opus',
643
+ mimeType,
622
644
  });
623
645
  } else {
624
646
  this.log.warn('preconnect buffer already started');
@@ -649,5 +671,9 @@ export default abstract class LocalTrack<
649
671
  return this.localTrackRecorder?.byteStream;
650
672
  }
651
673
 
674
+ getPreConnectBufferMimeType() {
675
+ return this.localTrackRecorder?.mimeType;
676
+ }
677
+
652
678
  protected abstract monitorSender(): void;
653
679
  }