-
-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathwindow-audio-stream.js
More file actions
257 lines (217 loc) · 9.89 KB
/
window-audio-stream.js
File metadata and controls
257 lines (217 loc) · 9.89 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
// 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.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: trimmed
};
}
return {
requestTarget: trimmed,
clientId: trimmed
};
}
throw new Error(`WindowAudioStream: Invalid process identifier: ${targetId}`);
}
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 {
if (!this.audioContext || this.audioContext.state === 'closed') {
this.audioContext = new (window.AudioContext || window.webkitAudioContext)({
sampleRate: this.sampleRate,
latencyHint: 'interactive'
});
}
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;
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.scriptProcessor = this.audioContext.createScriptProcessor(this.bufferSize, this.channels, this.channels);
let sampleBuffer = [];
let lastProcessTime = performance.now();
this.cleanupCallback = window.electronApi.onAudioStreamData((payload) => {
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;
}
sampleBuffer.push(...samples);
const now = performance.now();
if (now - lastProcessTime > 5000) {
console.log(`WindowAudioStream: Buffer health - ${sampleBuffer.length} samples buffered`);
lastProcessTime = now;
}
});
this.scriptProcessor.onaudioprocess = (audioProcessingEvent) => {
const outputBuffer = audioProcessingEvent.outputBuffer;
const numChannels = outputBuffer.numberOfChannels;
const frameCount = outputBuffer.length;
const samplesNeeded = frameCount * numChannels;
if (sampleBuffer.length >= samplesNeeded) {
const frameSamples = sampleBuffer.splice(0, samplesNeeded);
for (let channel = 0; channel < numChannels; channel++) {
const outputData = outputBuffer.getChannelData(channel);
for (let i = 0; i < frameCount; i++) {
outputData[i] = frameSamples[i * numChannels + channel] || 0;
}
}
} else {
for (let channel = 0; channel < numChannels; channel++) {
const outputData = outputBuffer.getChannelData(channel);
outputData.fill(0);
}
}
};
this.scriptProcessor.connect(destination);
this.audioStream = destination.stream;
this.captureActive = true;
console.log('WindowAudioStream: Audio stream created successfully');
return this.audioStream;
} catch (error) {
console.error('WindowAudioStream: Error starting capture:', error);
this.captureActive = false;
this.currentProcessId = null;
this.currentRequestTarget = null;
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) {
this.cleanupCallback();
this.cleanupCallback = null;
}
} catch (error) {
console.warn('WindowAudioStream: cleanup callback threw', error);
}
try {
if (this.scriptProcessor) {
this.scriptProcessor.disconnect();
this.scriptProcessor.onaudioprocess = null;
this.scriptProcessor = null;
}
} catch (error) {
console.warn('WindowAudioStream: Error disconnecting scriptProcessor', error);
}
try {
if (this.audioStream) {
this.audioStream.getTracks().forEach((track) => {
try {
track.stop();
} catch (err) {
console.warn('WindowAudioStream: Failed to stop track', err);
}
});
this.audioStream = null;
}
} 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);
}
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');
}