@livekit/rtc-node 0.13.32 → 0.13.34

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 (141) 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-4M8XlO4-.d.cts → audio_stream-BNVaONuH.d.cts} +36 -10
  8. package/dist/audio_stream.d.cts +2 -2
  9. package/dist/audio_stream.d.ts +61 -18
  10. package/dist/data_streams/index.d.cts +1 -1
  11. package/dist/data_streams/index.d.ts +4 -3
  12. package/dist/data_streams/stream_reader.cjs +97 -58
  13. package/dist/data_streams/stream_reader.cjs.map +1 -1
  14. package/dist/data_streams/stream_reader.d.cts +1 -1
  15. package/dist/data_streams/stream_reader.d.ts +65 -2
  16. package/dist/data_streams/stream_reader.d.ts.map +1 -1
  17. package/dist/data_streams/stream_writer.d.cts +1 -1
  18. package/dist/data_streams/stream_writer.d.ts +5 -7
  19. package/dist/data_streams/types.cjs.map +1 -1
  20. package/dist/data_streams/types.d.cts +1 -1
  21. package/dist/data_streams/types.d.ts +47 -2
  22. package/dist/data_streams/types.d.ts.map +1 -1
  23. package/dist/e2ee.cjs +5 -1
  24. package/dist/e2ee.cjs.map +1 -1
  25. package/dist/e2ee.d.cts +3 -1
  26. package/dist/e2ee.d.ts +11 -11
  27. package/dist/e2ee.d.ts.map +1 -1
  28. package/dist/ffi_client.d.ts +8 -10
  29. package/dist/frame_processor.d.ts +8 -11
  30. package/dist/index.cjs.map +1 -1
  31. package/dist/index.d.cts +2 -2
  32. package/dist/index.d.ts +22 -17
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +1 -107
  35. package/dist/log.d.ts +5 -7
  36. package/dist/participant.cjs +179 -192
  37. package/dist/participant.cjs.map +1 -1
  38. package/dist/participant.d.cts +2 -2
  39. package/dist/participant.d.ts +169 -18
  40. package/dist/participant.d.ts.map +1 -1
  41. package/dist/room.cjs +166 -120
  42. package/dist/room.cjs.map +1 -1
  43. package/dist/room.d.cts +2 -2
  44. package/dist/room.d.ts +228 -18
  45. package/dist/room.d.ts.map +1 -1
  46. package/dist/rpc.d.ts +7 -9
  47. package/dist/tests/e2e_common.cjs +157 -0
  48. package/dist/tests/e2e_common.cjs.map +1 -0
  49. package/dist/tests/e2e_common.d.cts +56 -0
  50. package/dist/tests/e2e_common.d.ts +37 -0
  51. package/dist/tests/e2e_common.d.ts.map +1 -0
  52. package/dist/track.d.cts +2 -2
  53. package/dist/track.d.ts +67 -18
  54. package/dist/track_publication.d.cts +2 -2
  55. package/dist/track_publication.d.ts +45 -18
  56. package/dist/transcription.d.ts +3 -4
  57. package/dist/{types-_PdPVish.d.ts → types-f7wTlFjs.d.cts} +34 -11
  58. package/dist/types.d.ts +2 -3
  59. package/dist/utils.cjs +27 -2
  60. package/dist/utils.cjs.map +1 -1
  61. package/dist/utils.d.cts +8 -1
  62. package/dist/utils.d.ts +10 -5
  63. package/dist/utils.d.ts.map +1 -1
  64. package/dist/version.cjs +1 -1
  65. package/dist/version.cjs.map +1 -1
  66. package/dist/version.d.cts +1 -1
  67. package/dist/version.d.ts +2 -3
  68. package/dist/video_frame.d.ts +4 -5
  69. package/dist/video_source.d.ts +6 -8
  70. package/dist/video_stream.d.cts +2 -2
  71. package/dist/video_stream.d.ts +5 -22
  72. package/package.json +6 -7
  73. package/src/audio_stream_room_lifecycle.test.ts +4 -1
  74. package/src/data_streams/stream_reader.ts +132 -82
  75. package/src/data_streams/types.ts +6 -0
  76. package/src/e2ee.ts +7 -0
  77. package/src/index.ts +8 -1
  78. package/src/participant.ts +252 -223
  79. package/src/room.ts +233 -134
  80. package/src/tests/e2e.test.ts +50 -139
  81. package/src/tests/e2e_common.ts +163 -0
  82. package/src/tests/e2e_data_streams.test.ts +639 -0
  83. package/src/utils.ts +30 -0
  84. package/src/version.ts +1 -1
  85. package/dist/async_queue.js +0 -56
  86. package/dist/async_queue.js.map +0 -1
  87. package/dist/audio_filter.js +0 -24
  88. package/dist/audio_filter.js.map +0 -1
  89. package/dist/audio_frame.js +0 -78
  90. package/dist/audio_frame.js.map +0 -1
  91. package/dist/audio_mixer.js +0 -269
  92. package/dist/audio_mixer.js.map +0 -1
  93. package/dist/audio_resampler.js +0 -154
  94. package/dist/audio_resampler.js.map +0 -1
  95. package/dist/audio_source.js +0 -134
  96. package/dist/audio_source.js.map +0 -1
  97. package/dist/audio_stream-CTyN1Ldy.d.ts +0 -523
  98. package/dist/audio_stream.js +0 -122
  99. package/dist/audio_stream.js.map +0 -1
  100. package/dist/data_streams/index.js +0 -3
  101. package/dist/data_streams/index.js.map +0 -1
  102. package/dist/data_streams/stream_reader.js +0 -124
  103. package/dist/data_streams/stream_reader.js.map +0 -1
  104. package/dist/data_streams/stream_writer.js +0 -26
  105. package/dist/data_streams/stream_writer.js.map +0 -1
  106. package/dist/data_streams/types.js +0 -1
  107. package/dist/data_streams/types.js.map +0 -1
  108. package/dist/e2ee.js +0 -251
  109. package/dist/e2ee.js.map +0 -1
  110. package/dist/ffi_client.js +0 -89
  111. package/dist/ffi_client.js.map +0 -1
  112. package/dist/frame_processor.js +0 -29
  113. package/dist/frame_processor.js.map +0 -1
  114. package/dist/index.js.map +0 -1
  115. package/dist/log.js +0 -9
  116. package/dist/log.js.map +0 -1
  117. package/dist/participant.js +0 -715
  118. package/dist/participant.js.map +0 -1
  119. package/dist/room.js +0 -900
  120. package/dist/room.js.map +0 -1
  121. package/dist/rpc.js +0 -65
  122. package/dist/rpc.js.map +0 -1
  123. package/dist/track.js +0 -234
  124. package/dist/track.js.map +0 -1
  125. package/dist/track_publication.js +0 -100
  126. package/dist/track_publication.js.map +0 -1
  127. package/dist/transcription.js +0 -1
  128. package/dist/transcription.js.map +0 -1
  129. package/dist/types-_PdPVish.d.cts +0 -87
  130. package/dist/types.js +0 -1
  131. package/dist/types.js.map +0 -1
  132. package/dist/utils.js +0 -35
  133. package/dist/utils.js.map +0 -1
  134. package/dist/version.js +0 -5
  135. package/dist/version.js.map +0 -1
  136. package/dist/video_frame.js +0 -207
  137. package/dist/video_frame.js.map +0 -1
  138. package/dist/video_source.js +0 -53
  139. package/dist/video_source.js.map +0 -1
  140. package/dist/video_stream.js +0 -70
  141. package/dist/video_stream.js.map +0 -1
@@ -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 }\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Q,CAAC,YAAY,QAAQ,CAAC;AAC9D,SAAK,iBAAiB,MAAM;AAC5B,SAAK,iBAAiB,MAAM;AAAA,EAC9B;AAAA,EAEA,IAAI,SAAS;AACX,WAAO,KAAK,MAAM;AAAA,EACpB;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,IAA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AAI,QAAQ,KAAK;AAC/B,YAAM,MAAM,IAAI,CAAC,KAAK;AACtB,UAAI,MAAM,OAAO;AACf,cAAM,CAAC,IAAI;AAAA,MACb,WAAW,MAAM,QAAQ;AACvB,cAAM,CAAC,IAAI;AAAA,MACb,OAAO;AACL,cAAM,CAAC,IAAI;AAAA,MACb;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AAAA,EAEQ,MAAM,IAA2B;AACvC,WAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AAAA,EACzD;AAAA;AAAA;AAAA,EAIQ,YAAe,SAAqB,IAAoC;AAC9E,QAAI;AACJ,UAAM,iBAAiB,IAAI,QAAmB,CAAC,YAAY;AACzD,cAAQ,WAAW,MAAM,QAAQ,SAAS,GAAG,EAAE;AAAA,IACjD,CAAC;AACD,WAAO,QAAQ,KAAK,CAAC,QAAQ,QAAQ,MAAM,aAAa,KAAK,CAAC,GAAG,cAAc,CAAC;AAAA,EAClF;AACF;","names":["AsyncQueue"]}
@@ -1,154 +0,0 @@
1
- import {
2
- FlushSoxResamplerRequest,
3
- NewSoxResamplerRequest,
4
- PushSoxResamplerRequest,
5
- SoxQualityRecipe,
6
- SoxResamplerDataType
7
- } from "@livekit/rtc-ffi-bindings";
8
- import { AudioFrame } from "./audio_frame.js";
9
- import { FfiClient, FfiHandle } from "./ffi_client.js";
10
- var AudioResamplerQuality = ((AudioResamplerQuality2) => {
11
- AudioResamplerQuality2[AudioResamplerQuality2["QUICK"] = SoxQualityRecipe.SOXR_QUALITY_QUICK] = "QUICK";
12
- AudioResamplerQuality2[AudioResamplerQuality2["LOW"] = SoxQualityRecipe.SOXR_QUALITY_LOW] = "LOW";
13
- AudioResamplerQuality2[AudioResamplerQuality2["MEDIUM"] = SoxQualityRecipe.SOXR_QUALITY_MEDIUM] = "MEDIUM";
14
- AudioResamplerQuality2[AudioResamplerQuality2["HIGH"] = SoxQualityRecipe.SOXR_QUALITY_HIGH] = "HIGH";
15
- AudioResamplerQuality2[AudioResamplerQuality2["VERY_HIGH"] = SoxQualityRecipe.SOXR_QUALITY_VERYHIGH] = "VERY_HIGH";
16
- return AudioResamplerQuality2;
17
- })(AudioResamplerQuality || {});
18
- class AudioResampler {
19
- #inputRate;
20
- #outputRate;
21
- #channels;
22
- #ffiHandle;
23
- /**
24
- * Initializes a new AudioResampler.
25
- *
26
- * @param inputRate - The sample rate of the input audio data (in Hz).
27
- * @param outputRate - The desired sample rate of the output audio data (in Hz).
28
- * @param channels - The number of audio channels (e.g., 1 for mono, 2 for stereo). Defaults to 1.
29
- * @param quality - The quality setting for the resampler. Defaults to
30
- * `AudioResamplerQuality.MEDIUM`.
31
- */
32
- constructor(inputRate, outputRate, channels = 1, quality = AudioResamplerQuality.MEDIUM) {
33
- this.#inputRate = inputRate;
34
- this.#outputRate = outputRate;
35
- this.#channels = channels;
36
- const req = new NewSoxResamplerRequest({
37
- inputRate,
38
- outputRate,
39
- numChannels: channels,
40
- qualityRecipe: quality,
41
- inputDataType: SoxResamplerDataType.SOXR_DATATYPE_INT16I,
42
- outputDataType: SoxResamplerDataType.SOXR_DATATYPE_INT16I,
43
- flags: 0
44
- });
45
- const res = FfiClient.instance.request({
46
- message: {
47
- case: "newSoxResampler",
48
- value: req
49
- }
50
- });
51
- switch (res.message.case) {
52
- case "resampler":
53
- this.#ffiHandle = new FfiHandle(res.message.value.handle.id);
54
- break;
55
- case "error":
56
- default:
57
- throw new Error(res.message.value);
58
- }
59
- }
60
- get inputRate() {
61
- return this.#inputRate;
62
- }
63
- get outputRate() {
64
- return this.#outputRate;
65
- }
66
- get channels() {
67
- return this.#channels;
68
- }
69
- /**
70
- * Releases the underlying native resampler handle. Must be called when
71
- * the resampler is no longer needed to avoid leaking the FD.
72
- */
73
- close() {
74
- this.#ffiHandle.dispose();
75
- }
76
- /**
77
- * Push audio data into the resampler and retrieve any available resampled data.
78
- *
79
- * This method accepts audio data, resamples it according to the configured input and output rates,
80
- * and returns any resampled data that is available after processing the input.
81
- *
82
- * @param data - The audio frame to resample
83
- *
84
- * @returns A list of {@link AudioFrame} objects containing the resampled audio data. The list may
85
- * be empty if no output data is available yet.
86
- */
87
- push(data) {
88
- const req = new PushSoxResamplerRequest({
89
- resamplerHandle: this.#ffiHandle.handle,
90
- dataPtr: data.protoInfo().dataPtr,
91
- size: data.data.byteLength
92
- });
93
- const res = FfiClient.instance.request({
94
- message: {
95
- case: "pushSoxResampler",
96
- value: req
97
- }
98
- });
99
- if (res.error) {
100
- throw new Error(res.error);
101
- }
102
- if (!res.outputPtr) {
103
- return [];
104
- }
105
- const outputData = FfiClient.instance.copyBuffer(res.outputPtr, res.size);
106
- return [
107
- new AudioFrame(
108
- new Int16Array(outputData.buffer),
109
- this.#outputRate,
110
- this.#channels,
111
- Math.trunc(outputData.length / this.#channels / 2),
112
- data.userdata
113
- )
114
- ];
115
- }
116
- /**
117
- * Flush any remaining audio data through the resampler and retrieve the resampled data.
118
- *
119
- * @remarks
120
- * This method should be called when no more input data will be provided to ensure that all
121
- * internal buffers are processed and all resampled data is output.
122
- */
123
- flush() {
124
- const req = new FlushSoxResamplerRequest({
125
- resamplerHandle: this.#ffiHandle.handle
126
- });
127
- const res = FfiClient.instance.request({
128
- message: {
129
- case: "flushSoxResampler",
130
- value: req
131
- }
132
- });
133
- if (res.error) {
134
- throw new Error(res.error);
135
- }
136
- if (!res.outputPtr) {
137
- return [];
138
- }
139
- const outputData = FfiClient.instance.copyBuffer(res.outputPtr, res.size);
140
- return [
141
- new AudioFrame(
142
- new Int16Array(outputData.buffer),
143
- this.#outputRate,
144
- this.#channels,
145
- Math.trunc(outputData.length / this.#channels / 2)
146
- )
147
- ];
148
- }
149
- }
150
- export {
151
- AudioResampler,
152
- AudioResamplerQuality
153
- };
154
- //# sourceMappingURL=audio_resampler.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/audio_resampler.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type {\n FlushSoxResamplerResponse,\n NewSoxResamplerResponse,\n PushSoxResamplerResponse,\n} from '@livekit/rtc-ffi-bindings';\nimport {\n FlushSoxResamplerRequest,\n NewSoxResamplerRequest,\n PushSoxResamplerRequest,\n SoxQualityRecipe,\n SoxResamplerDataType,\n} from '@livekit/rtc-ffi-bindings';\nimport { AudioFrame } from './audio_frame.js';\nimport { FfiClient, FfiHandle } from './ffi_client.js';\n\n/**\n * Resampler quality. Higher quality settings result in better audio quality but require more\n * processing power.\n */\nexport enum AudioResamplerQuality {\n QUICK = SoxQualityRecipe.SOXR_QUALITY_QUICK,\n LOW = SoxQualityRecipe.SOXR_QUALITY_LOW,\n MEDIUM = SoxQualityRecipe.SOXR_QUALITY_MEDIUM,\n HIGH = SoxQualityRecipe.SOXR_QUALITY_HIGH,\n VERY_HIGH = SoxQualityRecipe.SOXR_QUALITY_VERYHIGH,\n}\n\n/**\n * AudioResampler provides functionality to resample audio data from an input sample rate to\n * an output sample rate using the Sox resampling library. It supports multiple channels and\n * configurable resampling quality.\n */\nexport class AudioResampler {\n #inputRate: number;\n #outputRate: number;\n #channels: number;\n #ffiHandle: FfiHandle;\n\n /**\n * Initializes a new AudioResampler.\n *\n * @param inputRate - The sample rate of the input audio data (in Hz).\n * @param outputRate - The desired sample rate of the output audio data (in Hz).\n * @param channels - The number of audio channels (e.g., 1 for mono, 2 for stereo). Defaults to 1.\n * @param quality - The quality setting for the resampler. Defaults to\n * `AudioResamplerQuality.MEDIUM`.\n */\n constructor(\n inputRate: number,\n outputRate: number,\n channels = 1,\n quality = AudioResamplerQuality.MEDIUM,\n ) {\n this.#inputRate = inputRate;\n this.#outputRate = outputRate;\n this.#channels = channels;\n\n const req = new NewSoxResamplerRequest({\n inputRate,\n outputRate,\n numChannels: channels,\n qualityRecipe: quality as number as SoxQualityRecipe,\n inputDataType: SoxResamplerDataType.SOXR_DATATYPE_INT16I,\n outputDataType: SoxResamplerDataType.SOXR_DATATYPE_INT16I,\n flags: 0,\n });\n\n const res = FfiClient.instance.request<NewSoxResamplerResponse>({\n message: {\n case: 'newSoxResampler',\n value: req,\n },\n });\n\n switch (res.message.case) {\n case 'resampler':\n this.#ffiHandle = new FfiHandle(res.message.value.handle!.id!);\n break;\n case 'error':\n default:\n throw new Error(res.message.value);\n }\n }\n\n get inputRate(): number {\n return this.#inputRate;\n }\n\n get outputRate(): number {\n return this.#outputRate;\n }\n\n get channels(): number {\n return this.#channels;\n }\n\n /**\n * Releases the underlying native resampler handle. Must be called when\n * the resampler is no longer needed to avoid leaking the FD.\n */\n close() {\n this.#ffiHandle.dispose();\n }\n\n /**\n * Push audio data into the resampler and retrieve any available resampled data.\n *\n * This method accepts audio data, resamples it according to the configured input and output rates,\n * and returns any resampled data that is available after processing the input.\n *\n * @param data - The audio frame to resample\n *\n * @returns A list of {@link AudioFrame} objects containing the resampled audio data. The list may\n * be empty if no output data is available yet.\n */\n push(data: AudioFrame): AudioFrame[] {\n const req = new PushSoxResamplerRequest({\n resamplerHandle: this.#ffiHandle.handle,\n dataPtr: data.protoInfo().dataPtr,\n size: data.data.byteLength,\n });\n\n const res = FfiClient.instance.request<PushSoxResamplerResponse>({\n message: {\n case: 'pushSoxResampler',\n value: req,\n },\n });\n\n if (res.error) {\n throw new Error(res.error);\n }\n\n if (!res.outputPtr) {\n return [];\n }\n\n const outputData = FfiClient.instance.copyBuffer(res.outputPtr, res.size!);\n\n return [\n new AudioFrame(\n new Int16Array(outputData.buffer),\n this.#outputRate,\n this.#channels,\n Math.trunc(outputData.length / this.#channels / 2),\n data.userdata,\n ),\n ];\n }\n\n /**\n * Flush any remaining audio data through the resampler and retrieve the resampled data.\n *\n * @remarks\n * This method should be called when no more input data will be provided to ensure that all\n * internal buffers are processed and all resampled data is output.\n */\n flush(): AudioFrame[] {\n const req = new FlushSoxResamplerRequest({\n resamplerHandle: this.#ffiHandle.handle,\n });\n\n const res = FfiClient.instance.request<FlushSoxResamplerResponse>({\n message: {\n case: 'flushSoxResampler',\n value: req,\n },\n });\n\n if (res.error) {\n throw new Error(res.error);\n }\n\n if (!res.outputPtr) {\n return [];\n }\n\n const outputData = FfiClient.instance.copyBuffer(res.outputPtr, res.size!);\n return [\n new AudioFrame(\n new Int16Array(outputData.buffer),\n this.#outputRate,\n this.#channels,\n Math.trunc(outputData.length / this.#channels / 2),\n ),\n ];\n }\n}\n"],"mappings":"AAQA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,kBAAkB;AAC3B,SAAS,WAAW,iBAAiB;AAM9B,IAAK,yBAAL,CAAKA,2BAAL;AACL,EAAAA,8CAAA,WAAQ,iBAAiB,sBAAzB;AACA,EAAAA,8CAAA,SAAM,iBAAiB,oBAAvB;AACA,EAAAA,8CAAA,YAAS,iBAAiB,uBAA1B;AACA,EAAAA,8CAAA,UAAO,iBAAiB,qBAAxB;AACA,EAAAA,8CAAA,eAAY,iBAAiB,yBAA7B;AALU,SAAAA;AAAA,GAAA;AAaL,MAAM,eAAe;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,YACE,WACA,YACA,WAAW,GACX,UAAU,sBAAsB,QAChC;AACA,SAAK,aAAa;AAClB,SAAK,cAAc;AACnB,SAAK,YAAY;AAEjB,UAAM,MAAM,IAAI,uBAAuB;AAAA,MACrC;AAAA,MACA;AAAA,MACA,aAAa;AAAA,MACb,eAAe;AAAA,MACf,eAAe,qBAAqB;AAAA,MACpC,gBAAgB,qBAAqB;AAAA,MACrC,OAAO;AAAA,IACT,CAAC;AAED,UAAM,MAAM,UAAU,SAAS,QAAiC;AAAA,MAC9D,SAAS;AAAA,QACP,MAAM;AAAA,QACN,OAAO;AAAA,MACT;AAAA,IACF,CAAC;AAED,YAAQ,IAAI,QAAQ,MAAM;AAAA,MACxB,KAAK;AACH,aAAK,aAAa,IAAI,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