-
-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathaudioBridge.js
More file actions
357 lines (294 loc) · 9.21 KB
/
Copy pathaudioBridge.js
File metadata and controls
357 lines (294 loc) · 9.21 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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
const { app } = require("electron");
const { spawn } = require("child_process");
const fs = require("fs");
const path = require("path");
function createAudioBridge(sendLevel, onStatusChange = () => {}, sendColors = () => {}) {
let helperProcess = null;
let helperStatus = {
mode: "simulated",
reason: "Helper not started yet."
};
let lastStatusUpdate = 0;
let retryCount = 0;
const MAX_IMMEDIATE_RETRIES = 3;
const MAX_TOTAL_RETRIES = 10;
const INITIAL_RETRY_DELAY = 2000; // 2 seconds
const MAX_RETRY_DELAY = 30000; // 30 seconds
const RECOVERY_CHECK_INTERVAL = 60000; // 1 minute
const SUCCESS_RESET_THRESHOLD = 30000; // Reset retry count after 30s of success
let helperReady = false;
let stdoutBuffer = "";
const MAX_STDOUT_BUFFER_BYTES = 64 * 1024;
// How many consecutive overflows before we kill and restart the helper
const MAX_OVERFLOW_COUNT = 3;
let overflowCount = 0;
let isStopping = false;
let recoveryTimer = null;
let successStartTime = null;
function updateStatus(nextStatus) {
if (
helperStatus.mode === nextStatus.mode &&
helperStatus.reason === nextStatus.reason
) {
return false;
}
helperStatus = nextStatus;
onStatusChange(helperStatus);
return true;
}
function findHelperBinary() {
const appPath = app.getAppPath();
const candidates = [
// process.resourcesPath is only defined inside a packaged Electron app
...(process.resourcesPath
? [path.join(process.resourcesPath, "audio-helper", "Paraline.AudioBridge.exe")]
: []),
path.join(appPath, "build", "audio-helper", "Paraline.AudioBridge.exe"),
path.join(appPath, "audio-helper", "bin", "Release", "net8.0-windows", "win-x64", "publish", "Paraline.AudioBridge.exe"),
path.join(appPath, "audio-helper", "bin", "Debug", "net8.0-windows", "Paraline.AudioBridge.exe"),
path.join(appPath, "audio-helper", "bin", "Release", "net8.0-windows", "Paraline.AudioBridge.exe")
];
return candidates.find((p) => fs.existsSync(p)) || null;
}
function start() {
const helperBinary = findHelperBinary();
if (!helperBinary) {
updateStatus({
mode: "simulated",
reason:
"Audio capture helper not found.\n" +
"- Build C# helper first\n" +
"- Or run npm run build:helper"
});
return;
}
isStopping = false;
helperReady = false;
stdoutBuffer = "";
overflowCount = 0;
helperProcess = spawn(helperBinary, [], {
windowsHide: true,
stdio: ["ignore", "pipe", "pipe"]
});
helperProcess.stdout.on("data", (chunk) => {
stdoutBuffer += chunk.toString();
if (stdoutBuffer.length > MAX_STDOUT_BUFFER_BYTES) {
stdoutBuffer = "";
overflowCount++;
console.warn(
`[AudioBridge] stdout buffer overflow #${overflowCount} — buffer cleared (${MAX_STDOUT_BUFFER_BYTES} bytes exceeded).`
);
// Downgrade status immediately so tray/UI reflects the stall
helperReady = false;
successStartTime = null;
updateStatus({
mode: "simulated",
reason:
`Audio helper stdout overflowed (${overflowCount}/${MAX_OVERFLOW_COUNT}). ` +
"Audio levels stalled — attempting recovery."
});
if (overflowCount >= MAX_OVERFLOW_COUNT) {
// Too many consecutive overflows — kill the helper and let the
// existing exit handler schedule a reconnect.
console.error(
`[AudioBridge] ${MAX_OVERFLOW_COUNT} consecutive overflows — restarting helper.`
);
overflowCount = 0;
if (helperProcess) {
helperProcess.kill();
}
}
return;
}
// A valid chunk resets the consecutive overflow counter
overflowCount = 0;
const lines = stdoutBuffer.split(/\r?\n/);
stdoutBuffer = lines.pop() || "";
for (const line of lines) {
if (!line.trim()) continue;
try {
const message = JSON.parse(line);
if (!helperReady) {
helperReady = true;
retryCount = 0;
successStartTime = Date.now();
clearRecoveryTimer();
updateStatus({
mode: "helper",
reason: "C# helper process connected."
});
} else {
// Reset retry count if helper has been stable
resetRetryCountOnSuccess();
}
if (message.type === "level" && typeof message.value === "number") {
sendLevel(message.value);
} else if (message.type === "colors" && Array.isArray(message.value)) {
sendColors(message.value);
}
} catch {
console.warn("Invalid helper message received");
}
}
});
helperProcess.stderr.on("data", (chunk) => {
const errorMessage = chunk.toString().trim();
console.error(errorMessage);
const now = Date.now();
if (now - lastStatusUpdate < 1000) return;
lastStatusUpdate = now;
updateStatus({
mode: "helper-error",
reason:
"Audio helper error: " +
(errorMessage || "unknown error")
});
});
helperProcess.on("error", (err) => {
console.error("Failed to spawn audio helper process:", err);
updateStatus({
mode: "helper-error",
reason: `Failed to spawn audio helper: ${err.message}`
});
});
helperProcess.on("exit", (code) => {
helperProcess = null;
if (isStopping) {
clearRecoveryTimer();
return;
}
retryCount++;
// Calculate exponential backoff delay
const delay = calculateRetryDelay(retryCount);
if (retryCount <= MAX_IMMEDIATE_RETRIES) {
// Immediate retries with exponential backoff
updateStatus({
mode: "reconnecting",
reason: `Helper crashed. Restarting ${retryCount}/${MAX_IMMEDIATE_RETRIES} (retrying in ${Math.round(delay/1000)}s)`
});
setTimeout(() => {
if (!isStopping) {
start();
}
}, delay);
return;
}
if (retryCount <= MAX_TOTAL_RETRIES) {
// Extended recovery mode
updateStatus({
mode: "reconnecting",
reason: `Helper crashed. Extended recovery mode (${retryCount}/${MAX_TOTAL_RETRIES}). Next retry in ${Math.round(delay/1000)}s`
});
setTimeout(() => {
if (!isStopping) {
start();
}
}, delay);
return;
}
// Permanent failure - schedule periodic recovery attempts
updateStatus({
mode: "simulated",
reason:
`Audio helper stopped permanently (exit ${code}).\n` +
`Max retry limit reached (${MAX_TOTAL_RETRIES} attempts).\n` +
"Will attempt recovery every minute."
});
// Schedule periodic recovery attempts
scheduleRecovery();
});
}
function stop() {
isStopping = true;
clearRecoveryTimer();
if (helperProcess) {
helperProcess.kill();
helperProcess = null;
}
helperReady = false;
successStartTime = null;
updateStatus({
mode: "simulated",
reason: "Helper stopped."
});
}
function getStatus() {
return helperStatus;
}
function calculateRetryDelay(attemptNumber) {
return Math.min(
INITIAL_RETRY_DELAY * Math.pow(2, attemptNumber - 1),
MAX_RETRY_DELAY
);
}
function scheduleRecovery() {
clearRecoveryTimer();
recoveryTimer = setTimeout(() => {
if (isStopping) {
return;
}
retryCount = 0; // Reset retry count for recovery attempt
start();
}, RECOVERY_CHECK_INTERVAL);
}
function clearRecoveryTimer() {
if (recoveryTimer) {
clearTimeout(recoveryTimer);
recoveryTimer = null;
}
}
function resetRetryCountOnSuccess() {
if (retryCount > 0 && successStartTime && Date.now() - successStartTime > SUCCESS_RESET_THRESHOLD) {
retryCount = 0;
console.log("Helper stable for 30s, reset retry count");
}
}
return {
start,
stop,
getStatus
};
}
module.exports = {
createAudioBridge,
/**
* Exported for unit testing only.
* Creates a self-contained stdout-chunk handler that can be driven without
* spawning an Electron process. Returns { handleChunk, getOverflowCount }.
*/
_createStdoutHandler({
maxBytes = 64 * 1024,
maxOverflows = 3,
onOverflow = () => {},
onKill = () => {},
onLine = () => {}
} = {}) {
let buf = "";
let overflowCount = 0;
function handleChunk(chunk) {
buf += chunk.toString();
if (buf.length > maxBytes) {
buf = "";
overflowCount++;
onOverflow(overflowCount, maxOverflows);
if (overflowCount >= maxOverflows) {
overflowCount = 0;
onKill();
}
return;
}
// Valid chunk — reset counter
overflowCount = 0;
const lines = buf.split(/\r?\n/);
buf = lines.pop() || "";
for (const line of lines) {
if (line.trim()) onLine(line);
}
}
return {
handleChunk,
getOverflowCount: () => overflowCount,
reset: () => { buf = ""; overflowCount = 0; }
};
}
};