@livekit/rtc-node 0.13.31 → 0.13.33

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 (120) hide show
  1. package/dist/async_queue.d.ts +2 -3
  2. package/dist/audio_filter.d.ts +2 -3
  3. package/dist/audio_frame.d.ts +5 -6
  4. package/dist/audio_mixer.d.ts +3 -6
  5. package/dist/audio_resampler.d.ts +3 -6
  6. package/dist/audio_source.d.ts +5 -6
  7. package/dist/{audio_stream-B4hGVcKz.d.cts → audio_stream-CnODFAmo.d.cts} +26 -0
  8. package/dist/audio_stream.cjs +31 -18
  9. package/dist/audio_stream.cjs.map +1 -1
  10. package/dist/audio_stream.d.cts +1 -1
  11. package/dist/audio_stream.d.ts +61 -18
  12. package/dist/audio_stream.d.ts.map +1 -1
  13. package/dist/data_streams/index.d.ts +4 -3
  14. package/dist/data_streams/stream_reader.d.ts +48 -2
  15. package/dist/data_streams/stream_writer.d.ts +5 -7
  16. package/dist/data_streams/types.d.ts +41 -2
  17. package/dist/e2ee.d.ts +8 -10
  18. package/dist/ffi_client.d.ts +8 -10
  19. package/dist/frame_processor.d.ts +8 -11
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.cts +2 -2
  22. package/dist/index.d.ts +22 -17
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +1 -107
  25. package/dist/log.d.ts +5 -7
  26. package/dist/participant.cjs +7 -2
  27. package/dist/participant.cjs.map +1 -1
  28. package/dist/participant.d.cts +1 -1
  29. package/dist/participant.d.ts +152 -18
  30. package/dist/participant.d.ts.map +1 -1
  31. package/dist/room.cjs +7 -0
  32. package/dist/room.cjs.map +1 -1
  33. package/dist/room.d.cts +2 -2
  34. package/dist/room.d.ts +220 -18
  35. package/dist/room.d.ts.map +1 -1
  36. package/dist/rpc.d.ts +7 -9
  37. package/dist/track.cjs +16 -0
  38. package/dist/track.cjs.map +1 -1
  39. package/dist/track.d.cts +1 -1
  40. package/dist/track.d.ts +67 -18
  41. package/dist/track.d.ts.map +1 -1
  42. package/dist/track_publication.d.cts +1 -1
  43. package/dist/track_publication.d.ts +45 -18
  44. package/dist/transcription.d.ts +3 -4
  45. package/dist/types.d.ts +2 -3
  46. package/dist/utils.d.ts +4 -5
  47. package/dist/version.cjs +1 -1
  48. package/dist/version.cjs.map +1 -1
  49. package/dist/version.d.cts +1 -1
  50. package/dist/version.d.ts +2 -3
  51. package/dist/video_frame.d.ts +4 -5
  52. package/dist/video_source.d.ts +6 -8
  53. package/dist/video_stream.d.cts +1 -1
  54. package/dist/video_stream.d.ts +5 -22
  55. package/package.json +5 -6
  56. package/src/audio_stream.ts +37 -24
  57. package/src/audio_stream_room_lifecycle.test.ts +50 -3
  58. package/src/index.ts +8 -1
  59. package/src/participant.ts +7 -1
  60. package/src/room.ts +14 -0
  61. package/src/tests/e2e.test.ts +137 -16
  62. package/src/track.ts +17 -0
  63. package/src/version.ts +1 -1
  64. package/dist/async_queue.js +0 -56
  65. package/dist/async_queue.js.map +0 -1
  66. package/dist/audio_filter.js +0 -24
  67. package/dist/audio_filter.js.map +0 -1
  68. package/dist/audio_frame.js +0 -78
  69. package/dist/audio_frame.js.map +0 -1
  70. package/dist/audio_mixer.js +0 -269
  71. package/dist/audio_mixer.js.map +0 -1
  72. package/dist/audio_resampler.js +0 -154
  73. package/dist/audio_resampler.js.map +0 -1
  74. package/dist/audio_source.js +0 -134
  75. package/dist/audio_source.js.map +0 -1
  76. package/dist/audio_stream-DEG1JKge.d.ts +0 -498
  77. package/dist/audio_stream.js +0 -109
  78. package/dist/audio_stream.js.map +0 -1
  79. package/dist/data_streams/index.js +0 -3
  80. package/dist/data_streams/index.js.map +0 -1
  81. package/dist/data_streams/stream_reader.js +0 -124
  82. package/dist/data_streams/stream_reader.js.map +0 -1
  83. package/dist/data_streams/stream_writer.js +0 -26
  84. package/dist/data_streams/stream_writer.js.map +0 -1
  85. package/dist/data_streams/types.js +0 -1
  86. package/dist/data_streams/types.js.map +0 -1
  87. package/dist/e2ee.js +0 -251
  88. package/dist/e2ee.js.map +0 -1
  89. package/dist/ffi_client.js +0 -89
  90. package/dist/ffi_client.js.map +0 -1
  91. package/dist/frame_processor.js +0 -29
  92. package/dist/frame_processor.js.map +0 -1
  93. package/dist/index.js.map +0 -1
  94. package/dist/log.js +0 -9
  95. package/dist/log.js.map +0 -1
  96. package/dist/participant.js +0 -715
  97. package/dist/participant.js.map +0 -1
  98. package/dist/room.js +0 -899
  99. package/dist/room.js.map +0 -1
  100. package/dist/rpc.js +0 -65
  101. package/dist/rpc.js.map +0 -1
  102. package/dist/track.js +0 -218
  103. package/dist/track.js.map +0 -1
  104. package/dist/track_publication.js +0 -100
  105. package/dist/track_publication.js.map +0 -1
  106. package/dist/transcription.js +0 -1
  107. package/dist/transcription.js.map +0 -1
  108. package/dist/types-_PdPVish.d.ts +0 -87
  109. package/dist/types.js +0 -1
  110. package/dist/types.js.map +0 -1
  111. package/dist/utils.js +0 -35
  112. package/dist/utils.js.map +0 -1
  113. package/dist/version.js +0 -5
  114. package/dist/version.js.map +0 -1
  115. package/dist/video_frame.js +0 -207
  116. package/dist/video_frame.js.map +0 -1
  117. package/dist/video_source.js +0 -53
  118. package/dist/video_source.js.map +0 -1
  119. package/dist/video_stream.js +0 -70
  120. package/dist/video_stream.js.map +0 -1
package/src/track.ts CHANGED
@@ -99,6 +99,23 @@ export abstract class Track {
99
99
  }
100
100
  }
101
101
 
102
+ /**
103
+ * End every {@link AudioStream} attached to this track.
104
+ *
105
+ * @remarks
106
+ * The FFI keeps feeding an audio stream until the stream's own handle is
107
+ * dropped, so streams on a track that is no longer subscribed would otherwise
108
+ * go on delivering audio for the lifetime of the process.
109
+ *
110
+ * @internal
111
+ */
112
+ closeAudioStreams(): void {
113
+ for (const stream of [...this.iterateStreams()]) {
114
+ stream.teardown();
115
+ }
116
+ this.audioStreams.clear();
117
+ }
118
+
102
119
  private *iterateStreams(): Generator<AudioStreamSource> {
103
120
  const dead: Array<WeakRef<AudioStreamSource>> = [];
104
121
  for (const ref of this.audioStreams) {
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export const SDK_VERSION = "0.13.31";
1
+ export const SDK_VERSION = "0.13.33";
@@ -1,56 +0,0 @@
1
- import { Deque } from "@datastructures-js/deque";
2
- class AsyncQueue {
3
- constructor(capacity = Infinity) {
4
- this.capacity = capacity;
5
- this.items = [];
6
- this.waitingProducers = new Deque();
7
- this.waitingConsumers = new Deque();
8
- this.closed = false;
9
- }
10
- async put(item) {
11
- if (this.closed) throw new Error("Queue closed");
12
- while (this.items.length >= this.capacity) {
13
- await new Promise(
14
- (resolve, reject) => this.waitingProducers.pushBack({ resolve, reject })
15
- );
16
- if (this.closed) throw new Error("Queue closed");
17
- }
18
- this.items.push(item);
19
- if (this.waitingConsumers.size() > 0) {
20
- const resolve = this.waitingConsumers.popFront();
21
- resolve();
22
- }
23
- }
24
- get() {
25
- const item = this.items.shift();
26
- if (this.waitingProducers.size() > 0) {
27
- const producer = this.waitingProducers.popFront();
28
- producer.resolve();
29
- }
30
- return item;
31
- }
32
- /**
33
- * Wait until an item is available or the queue is closed.
34
- * Returns immediately if items are already available.
35
- */
36
- async waitForItem() {
37
- if (this.items.length > 0 || this.closed) {
38
- return;
39
- }
40
- await new Promise((resolve) => this.waitingConsumers.pushBack(resolve));
41
- }
42
- close() {
43
- this.closed = true;
44
- this.waitingProducers.toArray().forEach((producer) => producer.reject(new Error("Queue closed")));
45
- this.waitingConsumers.toArray().forEach((resolve) => resolve());
46
- this.waitingProducers.clear();
47
- this.waitingConsumers.clear();
48
- }
49
- get length() {
50
- return this.items.length;
51
- }
52
- }
53
- export {
54
- AsyncQueue
55
- };
56
- //# sourceMappingURL=async_queue.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/async_queue.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { Deque } from '@datastructures-js/deque';\n\n/**\n * AsyncQueue is a bounded queue with async support for both producers and consumers.\n *\n * This queue simplifies the AudioMixer implementation by handling backpressure and\n * synchronization automatically:\n * - Producers can await put() until the queue has space (when queue is full)\n * - Consumers can await waitForItem() until data is available (when queue is empty)\n *\n * This eliminates the need for manual coordination logic, polling loops, and\n * complex state management throughout the rest of the codebase.\n */\nexport class AsyncQueue<T> {\n private items: T[] = [];\n private waitingProducers = new Deque<{ resolve: () => void; reject: (err: Error) => void }>();\n private waitingConsumers = new Deque<() => void>();\n closed = false;\n\n constructor(private capacity: number = Infinity) {}\n\n async put(item: T) {\n if (this.closed) throw new Error('Queue closed');\n\n while (this.items.length >= this.capacity) {\n await new Promise<void>((resolve, reject) =>\n this.waitingProducers.pushBack({ resolve, reject }),\n );\n // Re-check if closed after waking up\n if (this.closed) throw new Error('Queue closed');\n }\n\n this.items.push(item);\n\n // Wake up one waiting consumer\n if (this.waitingConsumers.size() > 0) {\n const resolve = this.waitingConsumers.popFront()!;\n resolve();\n }\n }\n\n get(): T | undefined {\n const item = this.items.shift();\n if (this.waitingProducers.size() > 0) {\n const producer = this.waitingProducers.popFront()!;\n producer.resolve(); // wakes up one waiting producer\n }\n return item;\n }\n\n /**\n * Wait until an item is available or the queue is closed.\n * Returns immediately if items are already available.\n */\n async waitForItem(): Promise<void> {\n if (this.items.length > 0 || this.closed) {\n return;\n }\n await new Promise<void>((resolve) => this.waitingConsumers.pushBack(resolve));\n }\n\n close() {\n this.closed = true;\n // Reject all waiting producers with an error\n this.waitingProducers\n .toArray()\n .forEach((producer) => producer.reject(new Error('Queue closed')));\n // Resolve all waiting consumers so they can see the queue is closed\n this.waitingConsumers.toArray().forEach((resolve) => resolve());\n this.waitingProducers.clear();\n this.waitingConsumers.clear();\n }\n\n get length() {\n return this.items.length;\n }\n}\n"],"mappings":"AAGA,SAAS,aAAa;AAaf,MAAM,WAAc;AAAA,EAMzB,YAAoB,WAAmB,UAAU;AAA7B;AALpB,SAAQ,QAAa,CAAC;AACtB,SAAQ,mB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AACF;","names":[]}
@@ -1,24 +0,0 @@
1
- import { LoadAudioFilterPluginRequest } from "@livekit/rtc-ffi-bindings";
2
- import { FfiClient } from "./ffi_client.js";
3
- class AudioFilter {
4
- constructor(moduleId, path, dependencies = []) {
5
- const req = new LoadAudioFilterPluginRequest({
6
- moduleId,
7
- pluginPath: path,
8
- dependencies
9
- });
10
- const res = FfiClient.instance.request({
11
- message: {
12
- case: "loadAudioFilterPlugin",
13
- value: req
14
- }
15
- });
16
- if (res.error) {
17
- throw new Error(`Failed to initialize audio filter: ${res.error}`);
18
- }
19
- }
20
- }
21
- export {
22
- AudioFilter
23
- };
24
- //# sourceMappingURL=audio_filter.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/audio_filter.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { LoadAudioFilterPluginResponse } from '@livekit/rtc-ffi-bindings';\nimport { LoadAudioFilterPluginRequest } from '@livekit/rtc-ffi-bindings';\nimport { FfiClient } from './ffi_client.js';\n\nexport class AudioFilter {\n constructor(moduleId: string, path: string, dependencies: string[] = []) {\n const req = new LoadAudioFilterPluginRequest({\n moduleId,\n pluginPath: path,\n dependencies,\n });\n\n const res = FfiClient.instance.request<LoadAudioFilterPluginResponse>({\n message: {\n case: 'loadAudioFilterPlugin',\n value: req,\n },\n });\n\n if (res.error) {\n throw new Error(`Failed to initialize audio filter: ${res.error}`);\n }\n }\n}\n"],"mappings":"AAIA,SAAS,oCAAoC;AAC7C,SAAS,iBAAiB;AAEnB,MAAM,YAAY;AAAA,EACvB,YAAY,UAAkB,MAAc,eAAyB,CAAC,GAAG;AACvE,UAAM,MAAM,IAAI,6BAA6B;AAAA,MAC3C;AAAA,MACA,YAAY;AAAA,MACZ;AAAA,IACF,CAAC;AAED,UAAM,MAAM,UAAU,SAAS,QAAuC;AAAA,MACpE,SAAS;AAAA,QACP,MAAM;AAAA,QACN,OAAO;AAAA,MACT;AAAA,IACF,CAAC;AAED,QAAI,IAAI,OAAO;AACb,YAAM,IAAI,MAAM,sCAAsC,IAAI,KAAK,EAAE;AAAA,IACnE;AAAA,EACF;AACF;","names":[]}
@@ -1,78 +0,0 @@
1
- import { AudioFrameBufferInfo } from "@livekit/rtc-ffi-bindings";
2
- import { FfiClient, FfiHandle } from "./ffi_client.js";
3
- class AudioFrame {
4
- // note: if converting from Uint8Array to Int16Array, *do not* use buffer.slice!
5
- // it is marked unstable by Node and can cause undefined behaviour, such as massive chunks of
6
- // noise being added to the end.
7
- // it is recommended to use buffer.subarray instead.
8
- // XXX(nbsp): add this when writing proper docs
9
- constructor(data, sampleRate, channels, samplesPerChannel, userdata = {}) {
10
- this.data = data;
11
- this.sampleRate = sampleRate;
12
- this.channels = channels;
13
- this.samplesPerChannel = samplesPerChannel;
14
- this._userdata = userdata;
15
- }
16
- static create(sampleRate, channels, samplesPerChannel, userdata) {
17
- const data = new Int16Array(channels * samplesPerChannel);
18
- return new AudioFrame(data, sampleRate, channels, samplesPerChannel, userdata);
19
- }
20
- /** @internal */
21
- static fromOwnedInfo(owned) {
22
- const info = owned.info;
23
- const len = info.numChannels * info.samplesPerChannel * 2;
24
- const data = FfiClient.instance.copyBuffer(info.dataPtr, len);
25
- new FfiHandle(owned.handle.id).dispose();
26
- return new AudioFrame(
27
- new Int16Array(data.buffer),
28
- info.sampleRate,
29
- info.numChannels,
30
- info.samplesPerChannel
31
- );
32
- }
33
- /** @internal */
34
- protoInfo() {
35
- return new AudioFrameBufferInfo({
36
- dataPtr: FfiClient.instance.retrievePtr(new Uint8Array(this.data.buffer)),
37
- sampleRate: this.sampleRate,
38
- numChannels: this.channels,
39
- samplesPerChannel: this.samplesPerChannel
40
- });
41
- }
42
- /** Returns the user data associated with the audio frame. */
43
- get userdata() {
44
- return this._userdata;
45
- }
46
- }
47
- const combineAudioFrames = (buffer) => {
48
- if (!Array.isArray(buffer)) {
49
- return buffer;
50
- }
51
- buffer = buffer;
52
- if (buffer.length === 0) {
53
- throw new Error("buffer is empty");
54
- }
55
- const sampleRate = buffer[0].sampleRate;
56
- const channels = buffer[0].channels;
57
- let totalSamplesPerChannel = 0;
58
- for (const frame of buffer) {
59
- if (frame.sampleRate != sampleRate) {
60
- throw new Error(`sample rate mismatch: expected ${sampleRate}, got ${frame.sampleRate}`);
61
- }
62
- if (frame.channels != channels) {
63
- throw new Error(`channel mismatch: expected ${channels}, got ${frame.channels}`);
64
- }
65
- totalSamplesPerChannel += frame.samplesPerChannel;
66
- }
67
- const data = new Int16Array(buffer.map((x) => [...x.data]).flat());
68
- const mergedUserdata = {};
69
- for (const frame of buffer) {
70
- Object.assign(mergedUserdata, frame.userdata);
71
- }
72
- return new AudioFrame(data, sampleRate, channels, totalSamplesPerChannel, mergedUserdata);
73
- };
74
- export {
75
- AudioFrame,
76
- combineAudioFrames
77
- };
78
- //# sourceMappingURL=audio_frame.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/audio_frame.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { OwnedAudioFrameBuffer } from '@livekit/rtc-ffi-bindings';\nimport { AudioFrameBufferInfo } from '@livekit/rtc-ffi-bindings';\nimport { FfiClient, FfiHandle } from './ffi_client.js';\n\nexport class AudioFrame {\n data: Int16Array;\n sampleRate: number;\n channels: number;\n samplesPerChannel: number;\n\n private _userdata: Record<string, unknown>;\n\n // note: if converting from Uint8Array to Int16Array, *do not* use buffer.slice!\n // it is marked unstable by Node and can cause undefined behaviour, such as massive chunks of\n // noise being added to the end.\n // it is recommended to use buffer.subarray instead.\n // XXX(nbsp): add this when writing proper docs\n constructor(\n data: Int16Array,\n sampleRate: number,\n channels: number,\n samplesPerChannel: number,\n userdata: Record<string, unknown> = {},\n ) {\n this.data = data;\n this.sampleRate = sampleRate;\n this.channels = channels;\n this.samplesPerChannel = samplesPerChannel;\n this._userdata = userdata;\n }\n\n static create(\n sampleRate: number,\n channels: number,\n samplesPerChannel: number,\n userdata?: Record<string, unknown>,\n ): AudioFrame {\n const data = new Int16Array(channels * samplesPerChannel);\n return new AudioFrame(data, sampleRate, channels, samplesPerChannel, userdata);\n }\n\n /** @internal */\n static fromOwnedInfo(owned: OwnedAudioFrameBuffer): AudioFrame {\n const info = owned.info!;\n const len = info.numChannels! * info.samplesPerChannel! * 2; // c_int16\n const data = FfiClient.instance.copyBuffer(info.dataPtr!, len);\n new FfiHandle(owned.handle!.id!).dispose();\n return new AudioFrame(\n new Int16Array(data.buffer),\n info.sampleRate!,\n info.numChannels!,\n info.samplesPerChannel!,\n );\n }\n\n /** @internal */\n protoInfo(): AudioFrameBufferInfo {\n return new AudioFrameBufferInfo({\n dataPtr: FfiClient.instance.retrievePtr(new Uint8Array(this.data.buffer)),\n sampleRate: this.sampleRate,\n numChannels: this.channels,\n samplesPerChannel: this.samplesPerChannel,\n });\n }\n\n /** Returns the user data associated with the audio frame. */\n get userdata() {\n return this._userdata;\n }\n}\n\n/**\n * Combines one or more `rtc.AudioFrame` objects into a single `rtc.AudioFrame`.\n *\n * This function concatenates the audio data from multiple frames, ensuring that all frames have\n * the same sample rate and number of channels. It efficiently merges the data by preallocating the\n * necessary memory and copying the frame data without unnecessary reallocations.\n *\n * @param buffer - a single AudioFrame or list thereof\n */\nexport const combineAudioFrames = (buffer: AudioFrame | AudioFrame[]): AudioFrame => {\n if (!Array.isArray(buffer)) {\n return buffer;\n }\n buffer = buffer as AudioFrame[];\n\n if (buffer.length === 0) {\n throw new Error('buffer is empty');\n }\n\n const sampleRate = buffer[0]!.sampleRate;\n const channels = buffer[0]!.channels;\n\n let totalSamplesPerChannel = 0;\n for (const frame of buffer) {\n if (frame.sampleRate != sampleRate) {\n throw new Error(`sample rate mismatch: expected ${sampleRate}, got ${frame.sampleRate}`);\n }\n\n if (frame.channels != channels) {\n throw new Error(`channel mismatch: expected ${channels}, got ${frame.channels}`);\n }\n\n totalSamplesPerChannel += frame.samplesPerChannel;\n }\n\n const data = new Int16Array(buffer.map((x) => [...x.data]).flat());\n\n // Merge userdata from all frames\n const mergedUserdata: Record<string, unknown> = {};\n for (const frame of buffer) {\n Object.assign(mergedUserdata, frame.userdata);\n }\n\n return new AudioFrame(data, sampleRate, channels, totalSamplesPerChannel, mergedUserdata);\n};\n"],"mappings":"AAIA,SAAS,4BAA4B;AACrC,SAAS,WAAW,iBAAiB;AAE9B,MAAM,WAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAatB,YACE,MACA,YACA,UACA,mBACA,WAAoC,CAAC,GACrC;AACA,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,WAAW;AAChB,SAAK,oBAAoB;AACzB,SAAK,YAAY;AAAA,EACnB;AAAA,EAEA,OAAO,OACL,YACA,UACA,mBACA,UACY;AACZ,UAAM,OAAO,IAAI,WAAW,WAAW,iBAAiB;AACxD,WAAO,IAAI,WAAW,MAAM,YAAY,UAAU,mBAAmB,QAAQ;AAAA,EAC/E;AAAA;AAAA,EAGA,OAAO,cAAc,OAA0C;AAC7D,UAAM,OAAO,MAAM;AACnB,UAAM,MAAM,KAAK,cAAe,KAAK,oBAAqB;AAC1D,UAAM,OAAO,UAAU,SAAS,WAAW,KAAK,SAAU,GAAG;AAC7D,QAAI,UAAU,MAAM,OAAQ,EAAG,EAAE,QAAQ;AACzC,WAAO,IAAI;AAAA,MACT,IAAI,WAAW,KAAK,MAAM;AAAA,MAC1B,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,IACP;AAAA,EACF;AAAA;AAAA,EAGA,YAAkC;AAChC,WAAO,IAAI,qBAAqB;AAAA,MAC9B,SAAS,UAAU,SAAS,YAAY,IAAI,WAAW,KAAK,KAAK,MAAM,CAAC;AAAA,MACxE,YAAY,KAAK;AAAA,MACjB,aAAa,KAAK;AAAA,MAClB,mBAAmB,KAAK;AAAA,IAC1B,CAAC;AAAA,EACH;AAAA;AAAA,EAGA,IAAI,WAAW;AACb,WAAO,KAAK;AAAA,EACd;AACF;AAWO,MAAM,qBAAqB,CAAC,WAAkD;AACnF,MAAI,CAAC,MAAM,QAAQ,MAAM,GAAG;AAC1B,WAAO;AAAA,EACT;AACA,WAAS;AAET,MAAI,OAAO,WAAW,GAAG;AACvB,UAAM,IAAI,MAAM,iBAAiB;AAAA,EACnC;AAEA,QAAM,aAAa,OAAO,CAAC,EAAG;AAC9B,QAAM,WAAW,OAAO,CAAC,EAAG;AAE5B,MAAI,yBAAyB;AAC7B,aAAW,SAAS,QAAQ;AAC1B,QAAI,MAAM,cAAc,YAAY;AAClC,YAAM,IAAI,MAAM,kCAAkC,UAAU,SAAS,MAAM,UAAU,EAAE;AAAA,IACzF;AAEA,QAAI,MAAM,YAAY,UAAU;AAC9B,YAAM,IAAI,MAAM,8BAA8B,QAAQ,SAAS,MAAM,QAAQ,EAAE;AAAA,IACjF;AAEA,8BAA0B,MAAM;AAAA,EAClC;AAEA,QAAM,OAAO,IAAI,WAAW,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,IAAI,CAAC,EAAE,KAAK,CAAC;AAGjE,QAAM,iBAA0C,CAAC;AACjD,aAAW,SAAS,QAAQ;AAC1B,WAAO,OAAO,gBAAgB,MAAM,QAAQ;AAAA,EAC9C;AAEA,SAAO,IAAI,WAAW,MAAM,YAAY,UAAU,wBAAwB,cAAc;AAC1F;","names":[]}
@@ -1,269 +0,0 @@
1
- import { AsyncQueue } from "./async_queue.js";
2
- import { AudioFrame } from "./audio_frame.js";
3
- import { log } from "./log.js";
4
- import { AsyncQueue as AsyncQueue2 } from "./async_queue.js";
5
- class AudioMixer {
6
- /**
7
- * Initialize the AudioMixer.
8
- *
9
- * @param sampleRate - The audio sample rate in Hz.
10
- * @param numChannels - The number of audio channels.
11
- * @param options - Optional configuration for the mixer.
12
- */
13
- constructor(sampleRate, numChannels, options = {}) {
14
- this.streams = /* @__PURE__ */ new Set();
15
- this.buffers = /* @__PURE__ */ new Map();
16
- this.streamIterators = /* @__PURE__ */ new Map();
17
- this.sampleRate = sampleRate;
18
- this.numChannels = numChannels;
19
- this.chunkSize = options.blocksize && options.blocksize > 0 ? options.blocksize : Math.floor(sampleRate / 10);
20
- this.streamTimeoutMs = options.streamTimeoutMs ?? 100;
21
- this.queue = new AsyncQueue(options.capacity ?? 100);
22
- this.streamSignal = new AsyncQueue(1);
23
- this.ending = false;
24
- this.closed = false;
25
- this.mixerTask = this.mixer();
26
- }
27
- /**
28
- * Add an audio stream to the mixer.
29
- *
30
- * The stream is added to the internal set of streams and an empty buffer is initialized for it,
31
- * if not already present.
32
- *
33
- * @param stream - An async iterable that produces AudioFrame objects.
34
- * @throws Error if the mixer has been closed.
35
- */
36
- addStream(stream) {
37
- if (this.ending) {
38
- throw new Error("Cannot add stream after mixer has been closed");
39
- }
40
- this.streams.add(stream);
41
- if (!this.buffers.has(stream)) {
42
- this.buffers.set(stream, new Int16Array(0));
43
- }
44
- this.streamSignal.put(void 0).catch(() => {
45
- });
46
- }
47
- /**
48
- * Remove an audio stream from the mixer.
49
- *
50
- * This method removes the specified stream and its associated buffer from the mixer.
51
- *
52
- * @param stream - The audio stream to remove.
53
- */
54
- removeStream(stream) {
55
- this.streams.delete(stream);
56
- this.buffers.delete(stream);
57
- this.streamIterators.delete(stream);
58
- }
59
- /**
60
- * Returns an async iterator for the mixed audio frames.
61
- */
62
- [Symbol.asyncIterator]() {
63
- return {
64
- next: async () => {
65
- const frame = await this.getNextFrame();
66
- if (frame === null) {
67
- return { done: true, value: void 0 };
68
- }
69
- return { done: false, value: frame };
70
- }
71
- };
72
- }
73
- /**
74
- * Immediately stop mixing and close the mixer.
75
- *
76
- * This stops the mixing task, and any unconsumed output in the queue may be dropped.
77
- */
78
- async aclose() {
79
- if (this.closed) {
80
- return;
81
- }
82
- this.closed = true;
83
- this.ending = true;
84
- this.streamSignal.close();
85
- this.queue.close();
86
- await this.mixerTask;
87
- }
88
- /**
89
- * Signal that no more streams will be added.
90
- *
91
- * This method marks the mixer as closed so that it flushes any remaining buffered output before ending.
92
- * Note that existing streams will still be processed until exhausted.
93
- */
94
- endInput() {
95
- this.ending = true;
96
- }
97
- async getNextFrame() {
98
- while (true) {
99
- const frame = this.queue.get();
100
- if (frame !== void 0) {
101
- return frame;
102
- }
103
- if (this.queue.closed || this.ending && this.streams.size === 0) {
104
- return null;
105
- }
106
- await this.queue.waitForItem();
107
- }
108
- }
109
- async mixer() {
110
- while (true) {
111
- if (this.ending && this.streams.size === 0) {
112
- break;
113
- }
114
- if (this.streams.size === 0) {
115
- await this.streamSignal.waitForItem();
116
- this.streamSignal.get();
117
- continue;
118
- }
119
- const streamArray = Array.from(this.streams);
120
- const promises = streamArray.map((stream) => this.getContribution(stream));
121
- const results = await Promise.all(
122
- promises.map(
123
- (p) => p.then((value) => ({ status: "fulfilled", value })).catch((reason) => ({ status: "rejected", reason }))
124
- )
125
- );
126
- const contributions = [];
127
- let anyData = false;
128
- const removals = [];
129
- for (const result of results) {
130
- if (result.status !== "fulfilled") {
131
- log.warn({ reason: result.reason }, "AudioMixer: Stream contribution failed");
132
- continue;
133
- }
134
- const contrib = result.value;
135
- contributions.push(contrib.data);
136
- this.buffers.set(contrib.stream, contrib.buffer);
137
- if (contrib.hadData) {
138
- anyData = true;
139
- }
140
- if (contrib.exhausted && contrib.buffer.length === 0) {
141
- removals.push(contrib.stream);
142
- }
143
- }
144
- for (const stream of removals) {
145
- this.removeStream(stream);
146
- }
147
- if (!this.ending && removals.length > 0 && this.streams.size === 0) {
148
- this.ending = true;
149
- }
150
- if (!anyData) {
151
- await this.sleep(1);
152
- continue;
153
- }
154
- const mixed = this.mixAudio(contributions);
155
- const frame = new AudioFrame(mixed, this.sampleRate, this.numChannels, this.chunkSize);
156
- if (this.closed) {
157
- break;
158
- }
159
- try {
160
- await this.queue.put(frame);
161
- } catch {
162
- break;
163
- }
164
- }
165
- this.queue.close();
166
- }
167
- async getContribution(stream) {
168
- let buf = this.buffers.get(stream) ?? new Int16Array(0);
169
- const initialBufferLength = buf.length;
170
- let exhausted = false;
171
- let receivedDataInThisCall = false;
172
- let iterator = this.streamIterators.get(stream);
173
- if (!iterator) {
174
- iterator = stream[Symbol.asyncIterator]();
175
- this.streamIterators.set(stream, iterator);
176
- }
177
- while (buf.length < this.chunkSize * this.numChannels && !exhausted && !this.closed) {
178
- try {
179
- const result = await this.timeoutRace(iterator.next(), this.streamTimeoutMs);
180
- if (result === "timeout") {
181
- console.warn(`AudioMixer: stream timeout after ${this.streamTimeoutMs}ms`);
182
- break;
183
- }
184
- if (result.done) {
185
- exhausted = true;
186
- break;
187
- }
188
- const frame = result.value;
189
- const newData = frame.data;
190
- receivedDataInThisCall = true;
191
- if (buf.length === 0) {
192
- buf = newData;
193
- } else {
194
- const combined = new Int16Array(buf.length + newData.length);
195
- combined.set(buf);
196
- combined.set(newData, buf.length);
197
- buf = combined;
198
- }
199
- } catch (error) {
200
- console.error(`AudioMixer: Error reading from stream:`, error);
201
- exhausted = true;
202
- break;
203
- }
204
- }
205
- let contrib;
206
- const samplesNeeded = this.chunkSize * this.numChannels;
207
- if (buf.length >= samplesNeeded) {
208
- contrib = buf.subarray(0, samplesNeeded);
209
- buf = buf.subarray(samplesNeeded);
210
- } else {
211
- const padded = new Int16Array(samplesNeeded);
212
- padded.set(buf);
213
- contrib = padded;
214
- buf = new Int16Array(0);
215
- }
216
- const hadData = initialBufferLength > 0 || receivedDataInThisCall || buf.length > 0;
217
- return {
218
- stream,
219
- data: contrib,
220
- buffer: buf,
221
- hadData,
222
- exhausted
223
- };
224
- }
225
- mixAudio(contributions) {
226
- if (contributions.length === 0) {
227
- return new Int16Array(this.chunkSize * this.numChannels);
228
- }
229
- const length = this.chunkSize * this.numChannels;
230
- const acc = new Int32Array(length);
231
- for (const contrib of contributions) {
232
- for (let i = 0; i < length; i++) {
233
- const val = contrib[i];
234
- if (val !== void 0) {
235
- acc[i] = (acc[i] ?? 0) + val;
236
- }
237
- }
238
- }
239
- const mixed = new Int16Array(length);
240
- for (let i = 0; i < length; i++) {
241
- const val = acc[i] ?? 0;
242
- if (val > 32767) {
243
- mixed[i] = 32767;
244
- } else if (val < -32768) {
245
- mixed[i] = -32768;
246
- } else {
247
- mixed[i] = val;
248
- }
249
- }
250
- return mixed;
251
- }
252
- sleep(ms) {
253
- return new Promise((resolve) => setTimeout(resolve, ms));
254
- }
255
- /** Race a promise against a timeout. The losing setTimeout is automatically
256
- * cleared via `.finally()` so callers don't need to manage cleanup. */
257
- timeoutRace(promise, ms) {
258
- let timer;
259
- const timeoutPromise = new Promise((resolve) => {
260
- timer = setTimeout(() => resolve("timeout"), ms);
261
- });
262
- return Promise.race([promise.finally(() => clearTimeout(timer)), timeoutPromise]);
263
- }
264
- }
265
- export {
266
- AsyncQueue2 as AsyncQueue,
267
- AudioMixer
268
- };
269
- //# sourceMappingURL=audio_mixer.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/audio_mixer.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { AsyncQueue } from './async_queue.js';\nimport { AudioFrame } from './audio_frame.js';\nimport { log } from './log.js';\n\n// Re-export AsyncQueue for backward compatibility\nexport { AsyncQueue } from './async_queue.js';\n\n// Define types for async iteration (since lib: es2015 doesn't include them)\ntype AudioStream = {\n [Symbol.asyncIterator](): {\n next(): Promise<IteratorResult<AudioFrame>>;\n };\n};\n\ninterface Contribution {\n stream: AudioStream;\n data: Int16Array;\n buffer: Int16Array;\n hadData: boolean;\n exhausted: boolean;\n}\n\nexport interface AudioMixerOptions {\n /**\n * The size of the audio block (in samples) for mixing.\n * If not provided, defaults to sampleRate / 10 (100ms).\n */\n blocksize?: number;\n\n /**\n * The maximum wait time in milliseconds for each stream to provide\n * audio data before timing out. Defaults to 100 ms.\n */\n streamTimeoutMs?: number;\n\n /**\n * The maximum number of mixed frames to store in the output queue.\n * Defaults to 100.\n */\n capacity?: number;\n}\n\n/**\n * AudioMixer combines multiple async audio streams into a single output stream.\n *\n * The mixer accepts multiple async audio streams and mixes them into a single output stream.\n * Each output frame is generated with a fixed chunk size determined by the blocksize (in samples).\n * If blocksize is not provided (or 0), it defaults to 100ms.\n *\n * Each input stream is processed in parallel, accumulating audio data until at least one chunk\n * of samples is available. If an input stream does not provide data within the specified timeout,\n * a warning is logged. The mixer can be closed immediately\n * (dropping unconsumed frames) or allowed to flush remaining data using endInput().\n *\n * @example\n * ```typescript\n * const mixer = new AudioMixer(48000, 2);\n * mixer.addStream(stream1);\n * mixer.addStream(stream2);\n *\n * for await (const frame of mixer) {\n * // Process mixed audio frame\n * }\n * ```\n */\nexport class AudioMixer {\n private streams: Set<AudioStream>;\n private buffers: Map<AudioStream, Int16Array>;\n private streamIterators: Map<AudioStream, { next(): Promise<IteratorResult<AudioFrame>> }>;\n private sampleRate: number;\n private numChannels: number;\n private chunkSize: number;\n private streamTimeoutMs: number;\n private queue: AsyncQueue<AudioFrame>;\n private streamSignal: AsyncQueue<void>; // Signals when streams are added\n private ending: boolean;\n private mixerTask?: Promise<void>;\n private closed: boolean;\n\n /**\n * Initialize the AudioMixer.\n *\n * @param sampleRate - The audio sample rate in Hz.\n * @param numChannels - The number of audio channels.\n * @param options - Optional configuration for the mixer.\n */\n constructor(sampleRate: number, numChannels: number, options: AudioMixerOptions = {}) {\n this.streams = new Set();\n this.buffers = new Map();\n this.streamIterators = new Map();\n this.sampleRate = sampleRate;\n this.numChannels = numChannels;\n this.chunkSize =\n options.blocksize && options.blocksize > 0 ? options.blocksize : Math.floor(sampleRate / 10);\n this.streamTimeoutMs = options.streamTimeoutMs ?? 100;\n this.queue = new AsyncQueue<AudioFrame>(options.capacity ?? 100);\n this.streamSignal = new AsyncQueue<void>(1); // there should only be one mixer\n this.ending = false;\n this.closed = false;\n\n // Start the mixer task\n this.mixerTask = this.mixer();\n }\n\n /**\n * Add an audio stream to the mixer.\n *\n * The stream is added to the internal set of streams and an empty buffer is initialized for it,\n * if not already present.\n *\n * @param stream - An async iterable that produces AudioFrame objects.\n * @throws Error if the mixer has been closed.\n */\n addStream(stream: AudioStream): void {\n if (this.ending) {\n throw new Error('Cannot add stream after mixer has been closed');\n }\n\n this.streams.add(stream);\n if (!this.buffers.has(stream)) {\n this.buffers.set(stream, new Int16Array(0));\n }\n\n // Signal that a stream was added (non-blocking)\n this.streamSignal.put(undefined).catch(() => {\n // Ignore errors if signal queue is closed\n });\n }\n\n /**\n * Remove an audio stream from the mixer.\n *\n * This method removes the specified stream and its associated buffer from the mixer.\n *\n * @param stream - The audio stream to remove.\n */\n removeStream(stream: AudioStream): void {\n this.streams.delete(stream);\n this.buffers.delete(stream);\n this.streamIterators.delete(stream);\n }\n\n /**\n * Returns an async iterator for the mixed audio frames.\n */\n [Symbol.asyncIterator]() {\n return {\n next: async (): Promise<IteratorResult<AudioFrame>> => {\n const frame = await this.getNextFrame();\n if (frame === null) {\n return { done: true, value: undefined };\n }\n return { done: false, value: frame };\n },\n };\n }\n\n /**\n * Immediately stop mixing and close the mixer.\n *\n * This stops the mixing task, and any unconsumed output in the queue may be dropped.\n */\n async aclose(): Promise<void> {\n if (this.closed) {\n return;\n }\n this.closed = true;\n this.ending = true;\n\n // Close both queues to wake up any waiting operations\n this.streamSignal.close();\n this.queue.close();\n\n await this.mixerTask;\n }\n\n /**\n * Signal that no more streams will be added.\n *\n * This method marks the mixer as closed so that it flushes any remaining buffered output before ending.\n * Note that existing streams will still be processed until exhausted.\n */\n endInput(): void {\n this.ending = true;\n }\n\n private async getNextFrame(): Promise<AudioFrame | null> {\n while (true) {\n // Try to get an item from the queue (non-blocking)\n const frame = this.queue.get();\n\n if (frame !== undefined) {\n return frame;\n }\n\n // Check if mixer is closed or ending\n if (this.queue.closed || (this.ending && this.streams.size === 0)) {\n return null;\n }\n\n // Queue is empty but mixer is still running - wait for an item to be added\n await this.queue.waitForItem();\n }\n }\n\n private async mixer(): Promise<void> {\n // Main mixing loop that continuously processes streams and produces output frames\n while (true) {\n // If we're in ending mode and there are no more streams, exit\n if (this.ending && this.streams.size === 0) {\n break;\n }\n\n if (this.streams.size === 0) {\n // Wait for a stream to be added (signal queue will have an item)\n await this.streamSignal.waitForItem();\n // Consume the signal\n this.streamSignal.get();\n continue;\n }\n\n // Process all streams in parallel\n const streamArray = Array.from(this.streams);\n const promises = streamArray.map((stream) => this.getContribution(stream));\n const results = await Promise.all(\n promises.map((p) =>\n p\n .then((value) => ({ status: 'fulfilled' as const, value }))\n .catch((reason) => ({ status: 'rejected' as const, reason })),\n ),\n );\n\n const contributions: Int16Array[] = [];\n let anyData = false;\n const removals: AudioStream[] = [];\n\n for (const result of results) {\n if (result.status !== 'fulfilled') {\n log.warn({ reason: result.reason }, 'AudioMixer: Stream contribution failed');\n continue;\n }\n\n const contrib = result.value;\n contributions.push(contrib.data);\n this.buffers.set(contrib.stream, contrib.buffer);\n\n if (contrib.hadData) {\n anyData = true;\n }\n\n // Mark exhausted streams with no remaining buffer for removal\n if (contrib.exhausted && contrib.buffer.length === 0) {\n removals.push(contrib.stream);\n }\n }\n\n // Remove exhausted streams\n for (const stream of removals) {\n this.removeStream(stream);\n }\n\n // If all streams are exhausted, end the mixer automatically.\n // This keeps `for await...of` consumers from hanging indefinitely when inputs complete.\n if (!this.ending && removals.length > 0 && this.streams.size === 0) {\n this.ending = true;\n }\n\n if (!anyData) {\n // No data available from any stream, wait briefly before trying again\n await this.sleep(1);\n continue;\n }\n\n // Mix the audio data\n const mixed = this.mixAudio(contributions);\n const frame = new AudioFrame(mixed, this.sampleRate, this.numChannels, this.chunkSize);\n\n if (this.closed) {\n break;\n }\n\n try {\n // Add mixed frame to output queue\n await this.queue.put(frame);\n } catch {\n // Queue closed while trying to add frame\n break;\n }\n }\n\n // Close the queue to signal end of stream\n this.queue.close();\n }\n\n private async getContribution(stream: AudioStream): Promise<Contribution> {\n let buf = this.buffers.get(stream) ?? new Int16Array(0);\n const initialBufferLength = buf.length;\n let exhausted = false;\n let receivedDataInThisCall = false;\n\n // Get or create iterator for this stream\n let iterator = this.streamIterators.get(stream);\n if (!iterator) {\n iterator = stream[Symbol.asyncIterator]();\n this.streamIterators.set(stream, iterator);\n }\n\n // Accumulate data until we have at least chunkSize samples\n while (buf.length < this.chunkSize * this.numChannels && !exhausted && !this.closed) {\n try {\n const result = await this.timeoutRace(iterator.next(), this.streamTimeoutMs);\n\n if (result === 'timeout') {\n console.warn(`AudioMixer: stream timeout after ${this.streamTimeoutMs}ms`);\n break;\n }\n\n if (result.done) {\n exhausted = true;\n break;\n }\n\n const frame = result.value;\n const newData = frame.data;\n\n // Mark that we received data in this call\n receivedDataInThisCall = true;\n\n // Concatenate buffers\n if (buf.length === 0) {\n buf = newData;\n } else {\n const combined = new Int16Array(buf.length + newData.length);\n combined.set(buf);\n combined.set(newData, buf.length);\n buf = combined;\n }\n } catch (error) {\n console.error(`AudioMixer: Error reading from stream:`, error);\n exhausted = true;\n break;\n }\n }\n\n // Extract contribution and update buffer\n let contrib: Int16Array;\n const samplesNeeded = this.chunkSize * this.numChannels;\n\n if (buf.length >= samplesNeeded) {\n // Extract the needed samples and keep the remainder in the buffer\n contrib = buf.subarray(0, samplesNeeded);\n buf = buf.subarray(samplesNeeded);\n } else {\n // Pad with zeros if we don't have enough data\n const padded = new Int16Array(samplesNeeded);\n padded.set(buf);\n contrib = padded;\n buf = new Int16Array(0);\n }\n\n // hadData means: we had data at start OR we received data during this call OR we have data remaining\n const hadData = initialBufferLength > 0 || receivedDataInThisCall || buf.length > 0;\n\n return {\n stream,\n data: contrib,\n buffer: buf,\n hadData,\n exhausted,\n };\n }\n\n private mixAudio(contributions: Int16Array[]): Int16Array {\n if (contributions.length === 0) {\n return new Int16Array(this.chunkSize * this.numChannels);\n }\n\n const length = this.chunkSize * this.numChannels;\n // Use a wider accumulator to avoid int16 overflow while summing.\n const acc = new Int32Array(length);\n\n // Sum all contributions\n for (const contrib of contributions) {\n for (let i = 0; i < length; i++) {\n const val = contrib[i];\n if (val !== undefined) {\n acc[i] = (acc[i] ?? 0) + val;\n }\n }\n }\n\n // Clip to Int16 range\n const mixed = new Int16Array(length);\n for (let i = 0; i < length; i++) {\n const val = acc[i] ?? 0;\n if (val > 32767) {\n mixed[i] = 32767;\n } else if (val < -32768) {\n mixed[i] = -32768;\n } else {\n mixed[i] = val;\n }\n }\n\n return mixed;\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n /** Race a promise against a timeout. The losing setTimeout is automatically\n * cleared via `.finally()` so callers don't need to manage cleanup. */\n private timeoutRace<T>(promise: Promise<T>, ms: number): Promise<T | 'timeout'> {\n let timer: ReturnType<typeof setTimeout>;\n const timeoutPromise = new Promise<'timeout'>((resolve) => {\n timer = setTimeout(() => resolve('timeout'), ms);\n });\n return Promise.race([promise.finally(() => clearTimeout(timer)), timeoutPromise]);\n }\n}\n"],"mappings":"AAGA,SAAS,kBAAkB;AAC3B,SAAS,kBAAkB;AAC3B,SAAS,WAAW;AAGpB,SAAS,cAAAA,mBAAkB;AA4DpB,MAAM,WAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAqBtB,YAAY,YAAoB,aAAqB,UAA6B,CAAC,GAAG;AACpF,SAAK,UAAU,oBAAI,IAAI;AACvB,SAAK,UAAU,oBAAI,IAAI;AACvB,SAAK,kBAAkB,oBAAI,IAAI;AAC/B,SAAK,aAAa;AAClB,SAAK,cAAc;AACnB,SAAK,YACH,QAAQ,aAAa,QAAQ,YAAY,IAAI,QAAQ,YAAY,KAAK,MAAM,aAAa,EAAE;AAC7F,SAAK,kBAAkB,QAAQ,mBAAmB;AAClD,SAAK,QAAQ,IAAI,WAAuB,QAAQ,YAAY,GAAG;AAC/D,SAAK,eAAe,IAAI,WAAiB,CAAC;AAC1C,SAAK,SAAS;AACd,SAAK,SAAS;AAGd,SAAK,YAAY,KAAK,MAAM;AAAA,EAC9B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,E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