@livekit/rtc-node 0.13.21 → 0.13.22

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 (50) hide show
  1. package/dist/async_queue.cjs +80 -0
  2. package/dist/async_queue.cjs.map +1 -0
  3. package/dist/async_queue.d.cts +30 -0
  4. package/dist/async_queue.d.ts +30 -0
  5. package/dist/async_queue.d.ts.map +1 -0
  6. package/dist/async_queue.js +56 -0
  7. package/dist/async_queue.js.map +1 -0
  8. package/dist/audio_mixer.cjs +281 -0
  9. package/dist/audio_mixer.cjs.map +1 -0
  10. package/dist/audio_mixer.d.cts +121 -0
  11. package/dist/audio_mixer.d.ts +121 -0
  12. package/dist/audio_mixer.d.ts.map +1 -0
  13. package/dist/audio_mixer.js +256 -0
  14. package/dist/audio_mixer.js.map +1 -0
  15. package/dist/index.cjs +3 -0
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.d.cts +2 -0
  18. package/dist/index.d.ts +2 -0
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +2 -0
  21. package/dist/index.js.map +1 -1
  22. package/dist/participant.cjs +4 -4
  23. package/dist/participant.cjs.map +1 -1
  24. package/dist/participant.d.cts +2 -2
  25. package/dist/participant.d.ts +2 -2
  26. package/dist/participant.d.ts.map +1 -1
  27. package/dist/participant.js +4 -4
  28. package/dist/participant.js.map +1 -1
  29. package/dist/room.cjs +276 -278
  30. package/dist/room.cjs.map +1 -1
  31. package/dist/room.d.cts +1 -1
  32. package/dist/room.d.ts +1 -1
  33. package/dist/room.d.ts.map +1 -1
  34. package/dist/room.js +276 -278
  35. package/dist/room.js.map +1 -1
  36. package/dist/version.cjs +1 -1
  37. package/dist/version.cjs.map +1 -1
  38. package/dist/version.d.cts +1 -1
  39. package/dist/version.d.ts +1 -1
  40. package/dist/version.js +1 -1
  41. package/dist/version.js.map +1 -1
  42. package/package.json +9 -8
  43. package/src/async_queue.test.ts +250 -0
  44. package/src/async_queue.ts +80 -0
  45. package/src/audio_mixer.test.ts +167 -0
  46. package/src/audio_mixer.ts +407 -0
  47. package/src/index.ts +1 -0
  48. package/src/participant.ts +5 -5
  49. package/src/room.ts +286 -289
  50. package/src/version.ts +1 -1
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var async_queue_exports = {};
20
+ __export(async_queue_exports, {
21
+ AsyncQueue: () => AsyncQueue
22
+ });
23
+ module.exports = __toCommonJS(async_queue_exports);
24
+ var import_deque = require("@datastructures-js/deque");
25
+ class AsyncQueue {
26
+ constructor(capacity = Infinity) {
27
+ this.capacity = capacity;
28
+ this.items = [];
29
+ this.waitingProducers = new import_deque.Deque();
30
+ this.waitingConsumers = new import_deque.Deque();
31
+ this.closed = false;
32
+ }
33
+ async put(item) {
34
+ if (this.closed) throw new Error("Queue closed");
35
+ while (this.items.length >= this.capacity) {
36
+ await new Promise(
37
+ (resolve, reject) => this.waitingProducers.pushBack({ resolve, reject })
38
+ );
39
+ if (this.closed) throw new Error("Queue closed");
40
+ }
41
+ this.items.push(item);
42
+ if (this.waitingConsumers.size() > 0) {
43
+ const resolve = this.waitingConsumers.popFront();
44
+ resolve();
45
+ }
46
+ }
47
+ get() {
48
+ const item = this.items.shift();
49
+ if (this.waitingProducers.size() > 0) {
50
+ const producer = this.waitingProducers.popFront();
51
+ producer.resolve();
52
+ }
53
+ return item;
54
+ }
55
+ /**
56
+ * Wait until an item is available or the queue is closed.
57
+ * Returns immediately if items are already available.
58
+ */
59
+ async waitForItem() {
60
+ if (this.items.length > 0 || this.closed) {
61
+ return;
62
+ }
63
+ await new Promise((resolve) => this.waitingConsumers.pushBack(resolve));
64
+ }
65
+ close() {
66
+ this.closed = true;
67
+ this.waitingProducers.toArray().forEach((producer) => producer.reject(new Error("Queue closed")));
68
+ this.waitingConsumers.toArray().forEach((resolve) => resolve());
69
+ this.waitingProducers.clear();
70
+ this.waitingConsumers.clear();
71
+ }
72
+ get length() {
73
+ return this.items.length;
74
+ }
75
+ }
76
+ // Annotate the CommonJS export names for ESM import in node:
77
+ 0 && (module.exports = {
78
+ AsyncQueue
79
+ });
80
+ //# sourceMappingURL=async_queue.cjs.map
@@ -0,0 +1 @@
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":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,mBAAsB;AAaf,MAAM,WAAc;AAAA,EAMzB,YAAoB,WAAmB,UAAU;AAA7B;AALpB,SAAQ,QAAa,CAAC;AACtB,SAAQ,mBAAmB,IAAI,mBAA6D;AAC5F,SAAQ,mBAAmB,IAAI,mBAAkB;AACjD,kBAAS;AAAA,EAEyC;AAAA,EAElD,MAAM,IAAI,MAAS;AACjB,QAAI,KAAK,OAAQ,OAAM,IAAI,MAAM,cAAc;AAE/C,WAAO,KAAK,MAAM,UAAU,KAAK,UAAU;AACzC,YAAM,IAAI;AAAA,QAAc,CAAC,SAAS,WAChC,KAAK,iBAAiB,SAAS,EAAE,SAAS,OAAO,CAAC;AAAA,MACpD;AAEA,UAAI,KAAK,OAAQ,OAAM,IAAI,MAAM,cAAc;AAAA,IACjD;AAEA,SAAK,MAAM,KAAK,IAAI;AAGpB,QAAI,KAAK,iBAAiB,KAAK,IAAI,GAAG;AACpC,YAAM,UAAU,KAAK,iBAAiB,SAAS;AAC/C,cAAQ;AAAA,IACV;AAAA,EACF;AAAA,EAEA,MAAqB;AACnB,UAAM,OAAO,KAAK,MAAM,MAAM;AAC9B,QAAI,KAAK,iBAAiB,KAAK,IAAI,GAAG;AACpC,YAAM,WAAW,KAAK,iBAAiB,SAAS;AAChD,eAAS,QAAQ;AAAA,IACnB;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,cAA6B;AACjC,QAAI,KAAK,MAAM,SAAS,KAAK,KAAK,QAAQ;AACxC;AAAA,IACF;AACA,UAAM,IAAI,QAAc,CAAC,YAAY,KAAK,iBAAiB,SAAS,OAAO,CAAC;AAAA,EAC9E;AAAA,EAEA,QAAQ;AACN,SAAK,SAAS;AAEd,SAAK,iBACF,QAAQ,EACR,QAAQ,CAAC,aAAa,SAAS,OAAO,IAAI,MAAM,cAAc,CAAC,CAAC;AAEnE,SAAK,iBAAiB,QAAQ,EAAE,QAAQ,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":[]}
@@ -0,0 +1,30 @@
1
+ /**
2
+ * AsyncQueue is a bounded queue with async support for both producers and consumers.
3
+ *
4
+ * This queue simplifies the AudioMixer implementation by handling backpressure and
5
+ * synchronization automatically:
6
+ * - Producers can await put() until the queue has space (when queue is full)
7
+ * - Consumers can await waitForItem() until data is available (when queue is empty)
8
+ *
9
+ * This eliminates the need for manual coordination logic, polling loops, and
10
+ * complex state management throughout the rest of the codebase.
11
+ */
12
+ declare class AsyncQueue<T> {
13
+ private capacity;
14
+ private items;
15
+ private waitingProducers;
16
+ private waitingConsumers;
17
+ closed: boolean;
18
+ constructor(capacity?: number);
19
+ put(item: T): Promise<void>;
20
+ get(): T | undefined;
21
+ /**
22
+ * Wait until an item is available or the queue is closed.
23
+ * Returns immediately if items are already available.
24
+ */
25
+ waitForItem(): Promise<void>;
26
+ close(): void;
27
+ get length(): number;
28
+ }
29
+
30
+ export { AsyncQueue };
@@ -0,0 +1,30 @@
1
+ /**
2
+ * AsyncQueue is a bounded queue with async support for both producers and consumers.
3
+ *
4
+ * This queue simplifies the AudioMixer implementation by handling backpressure and
5
+ * synchronization automatically:
6
+ * - Producers can await put() until the queue has space (when queue is full)
7
+ * - Consumers can await waitForItem() until data is available (when queue is empty)
8
+ *
9
+ * This eliminates the need for manual coordination logic, polling loops, and
10
+ * complex state management throughout the rest of the codebase.
11
+ */
12
+ declare class AsyncQueue<T> {
13
+ private capacity;
14
+ private items;
15
+ private waitingProducers;
16
+ private waitingConsumers;
17
+ closed: boolean;
18
+ constructor(capacity?: number);
19
+ put(item: T): Promise<void>;
20
+ get(): T | undefined;
21
+ /**
22
+ * Wait until an item is available or the queue is closed.
23
+ * Returns immediately if items are already available.
24
+ */
25
+ waitForItem(): Promise<void>;
26
+ close(): void;
27
+ get length(): number;
28
+ }
29
+
30
+ export { AsyncQueue };
@@ -0,0 +1 @@
1
+ {"version":3,"file":"async_queue.d.ts","sourceRoot":"","sources":["../src/async_queue.ts"],"names":[],"mappings":"AAKA;;;;;;;;;;GAUG;AACH,qBAAa,UAAU,CAAC,CAAC;IAMX,OAAO,CAAC,QAAQ;IAL5B,OAAO,CAAC,KAAK,CAAW;IACxB,OAAO,CAAC,gBAAgB,CAAsE;IAC9F,OAAO,CAAC,gBAAgB,CAA2B;IACnD,MAAM,UAAS;gBAEK,QAAQ,GAAE,MAAiB;IAEzC,GAAG,CAAC,IAAI,EAAE,CAAC;IAoBjB,GAAG,IAAI,CAAC,GAAG,SAAS;IASpB;;;OAGG;IACG,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC;IAOlC,KAAK;IAYL,IAAI,MAAM,WAET;CACF"}
@@ -0,0 +1,56 @@
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
@@ -0,0 +1 @@
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,mBAAmB,IAAI,MAA6D;AAC5F,SAAQ,mBAAmB,IAAI,MAAkB;AACjD,kBAAS;AAAA,EAEyC;AAAA,EAElD,MAAM,IAAI,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or;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var audio_mixer_exports = {};
20
+ __export(audio_mixer_exports, {
21
+ AsyncQueue: () => import_async_queue2.AsyncQueue,
22
+ AudioMixer: () => AudioMixer
23
+ });
24
+ module.exports = __toCommonJS(audio_mixer_exports);
25
+ var import_async_queue = require("./async_queue.cjs");
26
+ var import_audio_frame = require("./audio_frame.cjs");
27
+ var import_async_queue2 = require("./async_queue.cjs");
28
+ class AudioMixer {
29
+ /**
30
+ * Initialize the AudioMixer.
31
+ *
32
+ * @param sampleRate - The audio sample rate in Hz.
33
+ * @param numChannels - The number of audio channels.
34
+ * @param options - Optional configuration for the mixer.
35
+ */
36
+ constructor(sampleRate, numChannels, options = {}) {
37
+ this.streams = /* @__PURE__ */ new Set();
38
+ this.buffers = /* @__PURE__ */ new Map();
39
+ this.streamIterators = /* @__PURE__ */ new Map();
40
+ this.sampleRate = sampleRate;
41
+ this.numChannels = numChannels;
42
+ this.chunkSize = options.blocksize && options.blocksize > 0 ? options.blocksize : Math.floor(sampleRate / 10);
43
+ this.streamTimeoutMs = options.streamTimeoutMs ?? 100;
44
+ this.queue = new import_async_queue.AsyncQueue(options.capacity ?? 100);
45
+ this.streamSignal = new import_async_queue.AsyncQueue(1);
46
+ this.ending = false;
47
+ this.closed = false;
48
+ this.mixerTask = this.mixer();
49
+ }
50
+ /**
51
+ * Add an audio stream to the mixer.
52
+ *
53
+ * The stream is added to the internal set of streams and an empty buffer is initialized for it,
54
+ * if not already present.
55
+ *
56
+ * @param stream - An async iterable that produces AudioFrame objects.
57
+ * @throws Error if the mixer has been closed.
58
+ */
59
+ addStream(stream) {
60
+ if (this.ending) {
61
+ throw new Error("Cannot add stream after mixer has been closed");
62
+ }
63
+ this.streams.add(stream);
64
+ if (!this.buffers.has(stream)) {
65
+ this.buffers.set(stream, new Int16Array(0));
66
+ }
67
+ this.streamSignal.put(void 0).catch(() => {
68
+ });
69
+ }
70
+ /**
71
+ * Remove an audio stream from the mixer.
72
+ *
73
+ * This method removes the specified stream and its associated buffer from the mixer.
74
+ *
75
+ * @param stream - The audio stream to remove.
76
+ */
77
+ removeStream(stream) {
78
+ this.streams.delete(stream);
79
+ this.buffers.delete(stream);
80
+ this.streamIterators.delete(stream);
81
+ }
82
+ /**
83
+ * Returns an async iterator for the mixed audio frames.
84
+ */
85
+ [Symbol.asyncIterator]() {
86
+ return {
87
+ next: async () => {
88
+ const frame = await this.getNextFrame();
89
+ if (frame === null) {
90
+ return { done: true, value: void 0 };
91
+ }
92
+ return { done: false, value: frame };
93
+ }
94
+ };
95
+ }
96
+ /**
97
+ * Immediately stop mixing and close the mixer.
98
+ *
99
+ * This stops the mixing task, and any unconsumed output in the queue may be dropped.
100
+ */
101
+ async aclose() {
102
+ if (this.closed) {
103
+ return;
104
+ }
105
+ this.closed = true;
106
+ this.ending = true;
107
+ this.streamSignal.close();
108
+ this.queue.close();
109
+ await this.mixerTask;
110
+ }
111
+ /**
112
+ * Signal that no more streams will be added.
113
+ *
114
+ * This method marks the mixer as closed so that it flushes any remaining buffered output before ending.
115
+ * Note that existing streams will still be processed until exhausted.
116
+ */
117
+ endInput() {
118
+ this.ending = true;
119
+ }
120
+ async getNextFrame() {
121
+ while (true) {
122
+ const frame = this.queue.get();
123
+ if (frame !== void 0) {
124
+ return frame;
125
+ }
126
+ if (this.queue.closed || this.ending && this.streams.size === 0) {
127
+ return null;
128
+ }
129
+ await this.queue.waitForItem();
130
+ }
131
+ }
132
+ async mixer() {
133
+ while (true) {
134
+ if (this.ending && this.streams.size === 0) {
135
+ break;
136
+ }
137
+ if (this.streams.size === 0) {
138
+ await this.streamSignal.waitForItem();
139
+ this.streamSignal.get();
140
+ continue;
141
+ }
142
+ const streamArray = Array.from(this.streams);
143
+ const promises = streamArray.map((stream) => this.getContribution(stream));
144
+ const results = await Promise.all(
145
+ promises.map(
146
+ (p) => p.then((value) => ({ status: "fulfilled", value })).catch((reason) => ({ status: "rejected", reason }))
147
+ )
148
+ );
149
+ const contributions = [];
150
+ let anyData = false;
151
+ const removals = [];
152
+ for (const result of results) {
153
+ if (result.status !== "fulfilled") {
154
+ console.warn("AudioMixer: Stream contribution failed:", result.reason);
155
+ continue;
156
+ }
157
+ const contrib = result.value;
158
+ contributions.push(contrib.data);
159
+ this.buffers.set(contrib.stream, contrib.buffer);
160
+ if (contrib.hadData) {
161
+ anyData = true;
162
+ }
163
+ if (contrib.exhausted && contrib.buffer.length === 0) {
164
+ removals.push(contrib.stream);
165
+ }
166
+ }
167
+ for (const stream of removals) {
168
+ this.removeStream(stream);
169
+ }
170
+ if (!anyData) {
171
+ await this.sleep(1);
172
+ continue;
173
+ }
174
+ const mixed = this.mixAudio(contributions);
175
+ const frame = new import_audio_frame.AudioFrame(mixed, this.sampleRate, this.numChannels, this.chunkSize);
176
+ if (this.closed) {
177
+ break;
178
+ }
179
+ try {
180
+ await this.queue.put(frame);
181
+ } catch {
182
+ break;
183
+ }
184
+ }
185
+ this.queue.close();
186
+ }
187
+ async getContribution(stream) {
188
+ let buf = this.buffers.get(stream) ?? new Int16Array(0);
189
+ const initialBufferLength = buf.length;
190
+ let exhausted = false;
191
+ let receivedDataInThisCall = false;
192
+ let iterator = this.streamIterators.get(stream);
193
+ if (!iterator) {
194
+ iterator = stream[Symbol.asyncIterator]();
195
+ this.streamIterators.set(stream, iterator);
196
+ }
197
+ while (buf.length < this.chunkSize * this.numChannels && !exhausted && !this.closed) {
198
+ try {
199
+ const result = await Promise.race([iterator.next(), this.timeout(this.streamTimeoutMs)]);
200
+ if (result === "timeout") {
201
+ console.warn(`AudioMixer: stream timeout after ${this.streamTimeoutMs}ms`);
202
+ break;
203
+ }
204
+ if (result.done) {
205
+ exhausted = true;
206
+ break;
207
+ }
208
+ const frame = result.value;
209
+ const newData = frame.data;
210
+ receivedDataInThisCall = true;
211
+ if (buf.length === 0) {
212
+ buf = newData;
213
+ } else {
214
+ const combined = new Int16Array(buf.length + newData.length);
215
+ combined.set(buf);
216
+ combined.set(newData, buf.length);
217
+ buf = combined;
218
+ }
219
+ } catch (error) {
220
+ console.error(`AudioMixer: Error reading from stream:`, error);
221
+ exhausted = true;
222
+ break;
223
+ }
224
+ }
225
+ let contrib;
226
+ const samplesNeeded = this.chunkSize * this.numChannels;
227
+ if (buf.length >= samplesNeeded) {
228
+ contrib = buf.subarray(0, samplesNeeded);
229
+ buf = buf.subarray(samplesNeeded);
230
+ } else {
231
+ const padded = new Int16Array(samplesNeeded);
232
+ padded.set(buf);
233
+ contrib = padded;
234
+ buf = new Int16Array(0);
235
+ }
236
+ const hadData = initialBufferLength > 0 || receivedDataInThisCall || buf.length > 0;
237
+ return {
238
+ stream,
239
+ data: contrib,
240
+ buffer: buf,
241
+ hadData,
242
+ exhausted
243
+ };
244
+ }
245
+ mixAudio(contributions) {
246
+ if (contributions.length === 0) {
247
+ return new Int16Array(this.chunkSize * this.numChannels);
248
+ }
249
+ const length = this.chunkSize * this.numChannels;
250
+ const mixed = new Int16Array(length);
251
+ for (const contrib of contributions) {
252
+ for (let i = 0; i < length; i++) {
253
+ const val = contrib[i];
254
+ if (val !== void 0) {
255
+ mixed[i] = (mixed[i] ?? 0) + val;
256
+ }
257
+ }
258
+ }
259
+ for (let i = 0; i < length; i++) {
260
+ const val = mixed[i] ?? 0;
261
+ if (val > 32767) {
262
+ mixed[i] = 32767;
263
+ } else if (val < -32768) {
264
+ mixed[i] = -32768;
265
+ }
266
+ }
267
+ return mixed;
268
+ }
269
+ sleep(ms) {
270
+ return new Promise((resolve) => setTimeout(resolve, ms));
271
+ }
272
+ timeout(ms) {
273
+ return new Promise((resolve) => setTimeout(() => resolve("timeout"), ms));
274
+ }
275
+ }
276
+ // Annotate the CommonJS export names for ESM import in node:
277
+ 0 && (module.exports = {
278
+ AsyncQueue,
279
+ AudioMixer
280
+ });
281
+ //# sourceMappingURL=audio_mixer.cjs.map
@@ -0,0 +1 @@
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';\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 console.warn('AudioMixer: Stream contribution failed:', result.reason);\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 (!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 Promise.race([iterator.next(), this.timeout(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 const mixed = new Int16Array(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 mixed[i] = (mixed[i] ?? 0) + val;\n }\n }\n }\n\n // Clip to Int16 range\n for (let i = 0; i < length; i++) {\n const val = mixed[i] ?? 0;\n if (val > 32767) {\n mixed[i] = 32767;\n } else if (val < -32768) {\n mixed[i] = -32768;\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 private timeout(ms: number): Promise<'timeout'> {\n return new Promise((resolve) => setTimeout(() => resolve('timeout'), ms));\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,yBAA2B;AAC3B,yBA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AAI,WAAW,KAAK,YAAY,KAAK,WAAW;AAAA,IACzD;AAEA,UAAM,SAAS,KAAK,YAAY,KAAK;AACrC,UAAM,QAAQ,IAAI,WAAW,MAAM;AAGnC,eAAW,WAAW,eAAe;AACnC,eAAS,IAAI,GAAG,IAAI,QAAQ,KAAK;AAC/B,cAAM,MAAM,QAAQ,CAAC;AACrB,YAAI,QAAQ,QAAW;AACrB,gBAAM,CAAC,KAAK,MAAM,CAAC,KAAK,KAAK;AAAA,QAC/B;AAAA,MACF;AAAA,IACF;AAGA,aAAS,IAAI,GAAG,IAAI,QAAQ,KAAK;AAC/B,YAAM,MAAM,MAAM,CAAC,KAAK;AACxB,UAAI,MAAM,OAAO;AACf,cAAM,CAAC,IAAI;AAAA,MACb,WAAW,MAAM,QAAQ;AACvB,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,EAEQ,QAAQ,IAAgC;AAC9C,WAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,MAAM,QAAQ,SAAS,GAAG,EAAE,CAAC;AAAA,EAC1E;AACF;","names":["import_async_queue"]}
@@ -0,0 +1,121 @@
1
+ import { AudioFrame } from './audio_frame.cjs';
2
+ export { AsyncQueue } from './async_queue.cjs';
3
+ import './proto/audio_frame_pb.cjs';
4
+ import '@bufbuild/protobuf';
5
+ import './proto/track_pb.cjs';
6
+ import './proto/stats_pb.cjs';
7
+ import './proto/e2ee_pb.cjs';
8
+ import './proto/handle_pb.cjs';
9
+
10
+ type AudioStream = {
11
+ [Symbol.asyncIterator](): {
12
+ next(): Promise<IteratorResult<AudioFrame>>;
13
+ };
14
+ };
15
+ interface AudioMixerOptions {
16
+ /**
17
+ * The size of the audio block (in samples) for mixing.
18
+ * If not provided, defaults to sampleRate / 10 (100ms).
19
+ */
20
+ blocksize?: number;
21
+ /**
22
+ * The maximum wait time in milliseconds for each stream to provide
23
+ * audio data before timing out. Defaults to 100 ms.
24
+ */
25
+ streamTimeoutMs?: number;
26
+ /**
27
+ * The maximum number of mixed frames to store in the output queue.
28
+ * Defaults to 100.
29
+ */
30
+ capacity?: number;
31
+ }
32
+ /**
33
+ * AudioMixer combines multiple async audio streams into a single output stream.
34
+ *
35
+ * The mixer accepts multiple async audio streams and mixes them into a single output stream.
36
+ * Each output frame is generated with a fixed chunk size determined by the blocksize (in samples).
37
+ * If blocksize is not provided (or 0), it defaults to 100ms.
38
+ *
39
+ * Each input stream is processed in parallel, accumulating audio data until at least one chunk
40
+ * of samples is available. If an input stream does not provide data within the specified timeout,
41
+ * a warning is logged. The mixer can be closed immediately
42
+ * (dropping unconsumed frames) or allowed to flush remaining data using endInput().
43
+ *
44
+ * @example
45
+ * ```typescript
46
+ * const mixer = new AudioMixer(48000, 2);
47
+ * mixer.addStream(stream1);
48
+ * mixer.addStream(stream2);
49
+ *
50
+ * for await (const frame of mixer) {
51
+ * // Process mixed audio frame
52
+ * }
53
+ * ```
54
+ */
55
+ declare class AudioMixer {
56
+ private streams;
57
+ private buffers;
58
+ private streamIterators;
59
+ private sampleRate;
60
+ private numChannels;
61
+ private chunkSize;
62
+ private streamTimeoutMs;
63
+ private queue;
64
+ private streamSignal;
65
+ private ending;
66
+ private mixerTask?;
67
+ private closed;
68
+ /**
69
+ * Initialize the AudioMixer.
70
+ *
71
+ * @param sampleRate - The audio sample rate in Hz.
72
+ * @param numChannels - The number of audio channels.
73
+ * @param options - Optional configuration for the mixer.
74
+ */
75
+ constructor(sampleRate: number, numChannels: number, options?: AudioMixerOptions);
76
+ /**
77
+ * Add an audio stream to the mixer.
78
+ *
79
+ * The stream is added to the internal set of streams and an empty buffer is initialized for it,
80
+ * if not already present.
81
+ *
82
+ * @param stream - An async iterable that produces AudioFrame objects.
83
+ * @throws Error if the mixer has been closed.
84
+ */
85
+ addStream(stream: AudioStream): void;
86
+ /**
87
+ * Remove an audio stream from the mixer.
88
+ *
89
+ * This method removes the specified stream and its associated buffer from the mixer.
90
+ *
91
+ * @param stream - The audio stream to remove.
92
+ */
93
+ removeStream(stream: AudioStream): void;
94
+ /**
95
+ * Returns an async iterator for the mixed audio frames.
96
+ */
97
+ [Symbol.asyncIterator](): {
98
+ next: () => Promise<IteratorResult<AudioFrame>>;
99
+ };
100
+ /**
101
+ * Immediately stop mixing and close the mixer.
102
+ *
103
+ * This stops the mixing task, and any unconsumed output in the queue may be dropped.
104
+ */
105
+ aclose(): Promise<void>;
106
+ /**
107
+ * Signal that no more streams will be added.
108
+ *
109
+ * This method marks the mixer as closed so that it flushes any remaining buffered output before ending.
110
+ * Note that existing streams will still be processed until exhausted.
111
+ */
112
+ endInput(): void;
113
+ private getNextFrame;
114
+ private mixer;
115
+ private getContribution;
116
+ private mixAudio;
117
+ private sleep;
118
+ private timeout;
119
+ }
120
+
121
+ export { AudioMixer, type AudioMixerOptions };