-
-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathwindow-audio-stream.js
More file actions
288 lines (246 loc) · 11.3 KB
/
Copy pathwindow-audio-stream.js
File metadata and controls
288 lines (246 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
// WindowAudioStream class to bridge VDO.Ninja with the native window audio capture module
console.log('WindowAudioStream: Loading WindowAudioStream class');
class WindowAudioStream {
constructor() {
this.audioContext = null;
this.captureActive = false;
this.audioStream = null;
this.scriptProcessor = null;
this.bufferSize = 4096;
this.sampleRate = 48000;
this.channels = 2;
this.cleanupCallback = null;
this.currentProcessId = null;
this.currentRequestTarget = null;
this.operations = Promise.resolve();
this.usingProcessLoopback = false;
}
_prepareTarget(targetId) {
if (typeof targetId === 'number' && Number.isFinite(targetId) && targetId > 0) {
return {
requestTarget: targetId,
clientId: String(targetId)
};
}
if (typeof targetId === 'bigint' && targetId > 0n) {
const numericValue = Number(targetId);
if (!Number.isFinite(numericValue) || numericValue <= 0) {
throw new Error(`WindowAudioStream: Invalid process identifier: ${targetId}`);
}
return {
requestTarget: numericValue,
clientId: targetId.toString()
};
}
if (typeof targetId === 'string') {
const trimmed = targetId.trim();
if (!trimmed.length) {
throw new Error('WindowAudioStream: Invalid process identifier: empty string');
}
if (/^\d+$/.test(trimmed)) {
const numericValue = Number(trimmed);
if (!Number.isFinite(numericValue) || numericValue <= 0) {
throw new Error(`WindowAudioStream: Invalid process identifier: ${targetId}`);
}
return {
requestTarget: numericValue,
clientId: String(numericValue)
};
}
return {
requestTarget: trimmed,
clientId: trimmed
};
}
throw new Error(`WindowAudioStream: Invalid process identifier: ${targetId}`);
}
_enqueue(operation) {
const result = this.operations.then(operation);
this.operations = result.catch(() => {});
return result;
}
start(targetId) {
return this._enqueue(() => this._start(targetId));
}
stop(expectedStream) {
return this._enqueue(() => {
if (expectedStream !== undefined && this.audioStream !== expectedStream) return;
return this._stop();
});
}
async _start(targetId) {
console.log(`WindowAudioStream: Starting capture for target ${targetId} (type: ${typeof targetId})`);
const targetInfo = this._prepareTarget(targetId);
const { requestTarget, clientId } = targetInfo;
console.log(`WindowAudioStream: Normalized target ${targetId} -> ${clientId}`);
if (this.captureActive) {
await this._stop();
}
this.currentProcessId = clientId;
this.currentRequestTarget = requestTarget;
this.usingProcessLoopback = false;
try {
const result = await window.electronApi.startStreamCapture(requestTarget);
if (!result || result.success !== true) {
throw new Error(result && result.error ? result.error : 'Failed to start window audio capture');
}
console.log(`WindowAudioStream: Native capture started - Sample rate: ${result.sampleRate}, Channels: ${result.channels}`);
this.sampleRate = result.sampleRate || 48000;
this.channels = result.channels || 2;
this.audioContext = new (window.AudioContext || window.webkitAudioContext)({
sampleRate: this.sampleRate,
latencyHint: 'interactive'
});
if (this.audioContext.state === 'suspended') {
await this.audioContext.resume();
}
const processLoopbackActive = !!(result.usingProcessSpecificLoopback ?? result.usingProcessLoopback);
this.usingProcessLoopback = processLoopbackActive;
console.log(`WindowAudioStream: Process-specific loopback ${processLoopbackActive ? 'active' : 'unavailable; using system loopback'}`);
const destination = this.audioContext.createMediaStreamDestination();
this.audioStream = destination.stream;
this.scriptProcessor = this.audioContext.createScriptProcessor(this.bufferSize, this.channels, this.channels);
let sampleBuffer = [];
let lastProcessTime = performance.now();
let listening = true;
const unsubscribe = window.electronApi.onAudioStreamData((payload) => {
if (!listening) return;
if (!payload || (payload.clientId && payload.clientId !== this.currentProcessId)) {
return;
}
const data = payload.data || payload;
if (!data || !data.samples) {
console.warn('WindowAudioStream: Received invalid audio data');
return;
}
const samples = data.samples;
const sampleRate = data.sampleRate || this.sampleRate;
const channels = data.channels || this.channels;
// Normalise channel count if backend sends unexpected layout
if (channels !== this.channels) {
this.channels = channels;
}
if (sampleRate && sampleRate !== this.sampleRate) {
this.sampleRate = sampleRate;
}
// Bound latency after a suspended or overloaded renderer, and
// avoid exceeding the JS argument limit with large IPC chunks.
const maxSamples = Math.max(this.bufferSize * 2, this.sampleRate) * this.channels;
// Treat buffered and incoming samples as one interleaved stream.
// Drop whole frames so a chunk split inside a stereo frame does
// not swap the left/right channels after an overflow.
const overflow = Math.max(0, sampleBuffer.length + samples.length - maxSamples);
const drop = Math.floor(overflow / this.channels) * this.channels;
const start = Math.max(0, drop - sampleBuffer.length);
if (drop > 0) sampleBuffer.splice(0, Math.min(drop, sampleBuffer.length));
for (let i = start; i < samples.length; i++) sampleBuffer.push(samples[i]);
const now = performance.now();
if (now - lastProcessTime > 5000) {
console.log(`WindowAudioStream: Buffer health - ${sampleBuffer.length} samples buffered`);
lastProcessTime = now;
}
});
this.cleanupCallback = () => {
listening = false;
if (typeof unsubscribe === 'function') unsubscribe();
};
this.scriptProcessor.onaudioprocess = (audioProcessingEvent) => {
const outputBuffer = audioProcessingEvent.outputBuffer;
const numChannels = outputBuffer.numberOfChannels;
const frameCount = outputBuffer.length;
const availableFrames = Math.min(frameCount, Math.floor(sampleBuffer.length / numChannels));
const frameSamples = sampleBuffer.splice(0, availableFrames * numChannels);
for (let channel = 0; channel < numChannels; channel++) {
const outputData = outputBuffer.getChannelData(channel);
outputData.fill(0);
for (let i = 0; i < availableFrames; i++) {
outputData[i] = frameSamples[i * numChannels + channel] || 0;
}
}
};
this.scriptProcessor.connect(destination);
this.captureActive = true;
console.log('WindowAudioStream: Audio stream created successfully');
return this.audioStream;
} catch (error) {
console.error('WindowAudioStream: Error starting capture:', error);
await this._stop();
throw error;
}
}
async _stop() {
if (!this.captureActive && !this.currentProcessId && !this.audioStream) {
return;
}
console.log('WindowAudioStream: Stopping capture');
try {
if (window.electronApi && typeof window.electronApi.stopStreamCapture === 'function' && (this.currentRequestTarget || this.currentProcessId)) {
const target = this.currentRequestTarget != null ? this.currentRequestTarget : this.currentProcessId;
await window.electronApi.stopStreamCapture(target);
}
} catch (error) {
console.warn('WindowAudioStream: stopStreamCapture threw', error);
}
try {
if (this.cleanupCallback) {
const cleanup = this.cleanupCallback;
this.cleanupCallback = null;
cleanup();
}
} catch (error) {
console.warn('WindowAudioStream: cleanup callback threw', error);
}
try {
if (this.scriptProcessor) {
const processor = this.scriptProcessor;
this.scriptProcessor = null;
processor.onaudioprocess = null;
processor.disconnect();
}
} catch (error) {
console.warn('WindowAudioStream: Error disconnecting scriptProcessor', error);
}
try {
if (this.audioStream) {
const stream = this.audioStream;
this.audioStream = null;
stream.getTracks().forEach((track) => {
try {
track.stop();
} catch (err) {
console.warn('WindowAudioStream: Failed to stop track', err);
}
});
}
} catch (error) {
console.warn('WindowAudioStream: Error stopping tracks', error);
}
try {
if (this.audioContext && this.audioContext.state !== 'closed') {
await this.audioContext.close();
}
} catch (error) {
console.warn('WindowAudioStream: Error closing AudioContext', error);
} finally {
this.audioContext = null;
}
this.captureActive = false;
this.currentProcessId = null;
this.currentRequestTarget = null;
this.usingProcessLoopback = false;
console.log('WindowAudioStream: Capture stopped successfully');
}
isCapturing() {
return this.captureActive;
}
getStream() {
return this.audioStream;
}
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = WindowAudioStream;
}
if (typeof window !== 'undefined') {
window.WindowAudioStream = WindowAudioStream;
console.log('WindowAudioStream: Class made available as window.WindowAudioStream');
}