-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoffscreen.js
More file actions
747 lines (655 loc) · 22.5 KB
/
Copy pathoffscreen.js
File metadata and controls
747 lines (655 loc) · 22.5 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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
// offscreen.js
// Log to confirm the script is loaded
console.log("Offscreen document script loaded.");
// --- Global variables for audio processing ---
let tabStream = null;
let audioContext = null;
let audioSource = null;
let audioWorkletNode = null; // Using AudioWorkletNode for modern implementation
let socket = null;
let analyser = null; // For audio level monitoring
let audioLevelDataArray = null;
let levelMonitorInterval = null;
// Buffer for 10-second chunks
let audioBuffer = [];
let bufferStartTime = null;
// Define your backend WebSocket URL
const BACKEND_WEBSOCKET_URL = "ws://localhost:8000/ws/diarize"; // Make sure this matches!
// Add state for the offscreen document
let isRecordingActive = false; // Reflects if this document is actively recording
let isWebSocketConnected = false;
// --- Constants for audio processing ---
const TARGET_SAMPLE_RATE = 16000; // Hz - Backend expects this
const BUFFER_SIZE = 4096; // ScriptProcessorNode buffer size
const CHUNK_DURATION_MS = 10000; // 10 seconds per chunk
const SAMPLES_PER_CHUNK = TARGET_SAMPLE_RATE * (CHUNK_DURATION_MS / 1000); // Number of samples in a 10-second chunk at 16kHz
// --- Message Listener from Background Script ---
chrome.runtime.onMessage.addListener(async (request) => {
console.log("Offscreen received message:", request);
console.log("Offscreen received message type:", request.type);
console.log(
"Offscreen received message data:",
JSON.stringify(request.data || {}, null, 2)
);
switch (request.type) {
case "START_RECORDING_OFFSCREEN":
if (request.data && request.data.tabStreamId) {
startRecordingOffscreen(request.data.tabStreamId);
} else {
console.error(
"Offscreen: Received START_RECORDING_OFFSCREEN message without stream ID."
);
}
break;
case "STOP_RECORDING_OFFSCREEN":
stopRecordingOffscreen();
break;
}
});
// --- Functions for recording using Web Audio API ---
async function startRecordingOffscreen(tabStreamId) {
console.log("Offscreen: Starting recording process with Web Audio API...");
if (isRecordingActive) {
console.log("Offscreen: Recording is already active.");
return;
}
isRecordingActive = true;
sendStatusUpdateOffscreen();
try {
// 1. Get Tab Audio Stream using the ID from background
console.log("Offscreen: Attempting to get tab audio stream from ID...");
const tabMedia = await navigator.mediaDevices
.getUserMedia({
audio: {
mandatory: {
chromeMediaSource: "tab",
chromeMediaSourceId: tabStreamId,
},
},
video: false,
})
.catch((error) => {
const errorMsg = `Offscreen: Failed to get tab audio stream: ${error.name} - ${error.message}`;
console.error(errorMsg, error);
stopRecordingOffscreen(errorMsg);
throw new Error(errorMsg);
});
tabStream = tabMedia;
console.log("Offscreen: Tab audio stream obtained:", tabStream);
// 2. Setup Web Audio API for processing
console.log("Offscreen: Setting up Web Audio API...");
audioContext = new (window.AudioContext || window.webkitAudioContext)();
const sourceSampleRate = audioContext.sampleRate;
console.log(
`Offscreen: AudioContext created. Source sample rate: ${sourceSampleRate} Hz`
);
const audioTracks = tabStream.getAudioTracks();
if (audioTracks.length === 0) {
const errorMsg = "Offscreen: No audio tracks found in tab stream.";
console.error(errorMsg);
stopRecordingOffscreen(errorMsg);
return;
}
audioSource = audioContext.createMediaStreamSource(tabStream);
// Register the AudioWorklet processor
console.log("Offscreen: Loading AudioWorklet processor...");
try {
// Use the bundled audio processor file
await audioContext.audioWorklet.addModule("audioProcessor.js");
console.log("Offscreen: AudioWorklet module loaded successfully");
// Create the AudioWorkletNode
audioWorkletNode = new AudioWorkletNode(
audioContext,
"audio-buffer-processor",
{
numberOfInputs: 1,
numberOfOutputs: 1,
processorOptions: {
targetSampleRate: TARGET_SAMPLE_RATE,
},
}
);
// Listen for messages from the processor
audioWorkletNode.port.onmessage = (event) => {
if (
!isRecordingActive ||
!socket ||
socket.readyState !== WebSocket.OPEN
) {
return;
}
if (event.data.type === "audio-chunk") {
// We've received a 10-second audio chunk from the processor
const audioData = event.data.audioData;
// Send the audio data to the WebSocket server
console.log(
`Offscreen: Sending audio chunk from AudioWorklet (${audioData.byteLength} bytes)`
);
socket.send(audioData);
}
};
// Connect the audio graph: source -> audioWorkletNode -> destination
audioSource.connect(audioWorkletNode);
audioWorkletNode.connect(audioContext.destination);
// Continue to play the captured audio to the user.
const output = new AudioContext();
const source = output.createMediaStreamSource(tabMedia);
source.connect(output.destination);
console.log("Offscreen: AudioWorklet setup complete");
} catch (error) {
const errorMsg = `Offscreen: Failed to initialize AudioWorklet: ${error.message}`;
console.error(errorMsg, error);
// Fall back to ScriptProcessor if AudioWorklet fails
console.log("Offscreen: Falling back to ScriptProcessor implementation");
// Create ScriptProcessorNode for processing audio chunks
// Deprecated, but used as fallback
scriptProcessor = audioContext.createScriptProcessor(BUFFER_SIZE, 1, 1);
scriptProcessor.onaudioprocess = (event) => {
if (
!isRecordingActive ||
!socket ||
socket.readyState !== WebSocket.OPEN
) {
return;
}
// Get the audio data from the input buffer (Float32Array)
const inputBuffer = event.inputBuffer.getChannelData(0); // Assuming mono
// Resample the audio to the target sample rate (16000 Hz)
const resampledBuffer = resampleAudio(
inputBuffer,
sourceSampleRate,
TARGET_SAMPLE_RATE
);
// Convert Float32Array to Int16Array (16-bit PCM)
const int16Array = float32ToInt16(resampledBuffer);
if (int16Array.length > 0) {
// Add the current chunk to our buffer
audioBuffer.push(int16Array);
// Initialize start time if this is the first chunk
if (bufferStartTime === null) {
bufferStartTime = Date.now();
}
// Calculate total samples in buffer
let totalSamples = 0;
audioBuffer.forEach((chunk) => {
totalSamples += chunk.length;
});
// Check if we've reached 10 seconds of audio
if (totalSamples >= SAMPLES_PER_CHUNK) {
// Merge all chunks in buffer
const mergedBuffer = mergeAudioChunks(audioBuffer, totalSamples);
// Send the merged 10-second chunk
console.log(
`Offscreen: Sending 10-second audio chunk (${mergedBuffer.byteLength} bytes)`
);
socket.send(mergedBuffer);
// Clear buffer and reset start time
audioBuffer = [];
bufferStartTime = Date.now();
}
// Also check if we've been buffering for more than 10 seconds (in case we don't get enough samples)
const currentTime = Date.now();
if (
bufferStartTime &&
currentTime - bufferStartTime >= CHUNK_DURATION_MS
) {
if (audioBuffer.length > 0) {
// Calculate total samples
let bufferSamples = 0;
audioBuffer.forEach((chunk) => {
bufferSamples += chunk.length;
});
// Merge and send whatever we have if it's not empty
if (bufferSamples > 0) {
const mergedBuffer = mergeAudioChunks(
audioBuffer,
bufferSamples
);
console.log(
`Offscreen: Sending time-based audio chunk (${mergedBuffer.byteLength} bytes)`
);
socket.send(mergedBuffer);
}
// Reset buffer
audioBuffer = [];
bufferStartTime = Date.now();
}
}
} else {
console.log("Offscreen: onaudioprocess generated empty chunk.");
}
};
// Connect the audio graph: source -> scriptProcessor -> destination
audioSource.connect(scriptProcessor);
scriptProcessor.connect(audioContext.destination);
}
// Setup Analyser for level monitoring
analyser = audioContext.createAnalyser();
audioLevelDataArray = new Uint8Array(analyser.frequencyBinCount);
audioSource.connect(analyser); // Connect source to analyser
// --- Start Level Monitoring ---
startLevelMonitoringOffscreen();
// --- Setup WebSocket Connection ---
console.log("Offscreen: Connecting to WebSocket backend...");
socket = new WebSocket(BACKEND_WEBSOCKET_URL);
socket.onopen = () => {
console.log("Offscreen: WebSocket connection opened.");
isWebSocketConnected = true;
sendStatusUpdateOffscreen();
// Send explicit WebSocket connection status to UI
chrome.runtime
.sendMessage({
type: "WEBSOCKET_STATUS",
target: "background",
isConnected: true,
message: "WebSocket connection established",
})
.catch((error) => {
if (
error.message !==
"Could not establish connection. Receiving end does not exist."
) {
console.warn(
"Offscreen: Could not send WebSocket status update to background:",
error.message
);
}
});
// Start processing via scriptProcessor.onaudioprocess when data is available
};
socket.onerror = (error) => {
console.error("Offscreen: WebSocket error:", error);
stopRecordingOffscreen("WebSocket connection failed.");
};
socket.onclose = (event) => {
console.log(
"Offscreen: WebSocket connection closed:",
event.code,
event.reason
);
isWebSocketConnected = false;
sendStatusUpdateOffscreen();
// Send explicit WebSocket disconnection status to UI
chrome.runtime
.sendMessage({
type: "WEBSOCKET_STATUS",
target: "background",
isConnected: false,
message: `WebSocket disconnected (Code: ${event.code})`,
})
.catch((error) => {
if (
error.message !==
"Could not establish connection. Receiving end does not exist."
) {
console.warn(
"Offscreen: Could not send WebSocket status update to background:",
error.message
);
}
});
if (isRecordingActive) {
stopRecordingOffscreen(
`WebSocket connection closed unexpectedly (Code: ${event.code}).`
);
}
};
socket.onmessage = (event) => {
console.log(
"Offscreen WebSocket received message:",
typeof event.data,
event.data.length || 0
);
try {
const result = JSON.parse(event.data);
console.log(
"Offscreen WebSocket parsed message:",
JSON.stringify(result, null, 2)
);
// Don't spread the result directly, as it would overwrite the message type
// Instead, pass the entire parsed message as a data field
chrome.runtime
.sendMessage({
type: "UPDATE_TRANSCRIPTION",
target: "background",
data: result, // Send the entire result as data field
})
.catch((error) => {
if (
error.message !==
"Could not establish connection. Receiving end does not exist."
) {
console.warn(
"Offscreen: Could not send transcription update message to background:",
error.message
);
}
});
} catch (e) {
console.error("Offscreen: Failed to parse backend message:", e);
}
};
console.log(
"Offscreen: Web Audio API setup complete. Processing will start when audio data is available."
);
} catch (error) {
console.error("Offscreen: Error during recording setup:", error);
stopRecordingOffscreen(`Error during recording setup: ${error.message}`);
}
}
// Flags for controlled shutdown
let shutdownInProgress = false;
let finalTranscriptReceived = false;
let shutdownTimeoutId = null;
// Function to stop recording and clean up
function stopRecordingOffscreen(errorMessage = null) {
console.log("Offscreen: Stopping recording process initiated.");
// Only proceed with a full shutdown if we're not already shutting down
if (shutdownInProgress) {
console.log(
"Offscreen: Shutdown already in progress, ignoring duplicate call."
);
return;
}
// Mark that we're in shutdown process
shutdownInProgress = true;
// Update UI immediately to show recording is stopping
isRecordingActive = false;
// Send status update but keep WebSocket connection status as is
// This lets the UI know recording stopped but connection still active for final transcript
sendStatusUpdateOffscreen();
// Send explicit status message to UI
chrome.runtime
.sendMessage({
type: "STATUS_UPDATE",
target: "background",
message: "Waiting for final transcription before closing...",
})
.catch((error) => {
if (
error.message !==
"Could not establish connection. Receiving end does not exist."
) {
console.warn(
"Offscreen: Could not send shutdown status update to background:",
error.message
);
}
});
// Send any remaining buffered audio before shutting down
if (
audioBuffer.length > 0 &&
socket &&
socket.readyState === WebSocket.OPEN
) {
let bufferSamples = 0;
audioBuffer.forEach((chunk) => {
bufferSamples += chunk.length;
});
if (bufferSamples > 0) {
const mergedBuffer = mergeAudioChunks(audioBuffer, bufferSamples);
console.log(
`Offscreen: Sending final audio chunk (${mergedBuffer.byteLength} bytes)`
);
socket.send(mergedBuffer);
}
audioBuffer = [];
bufferStartTime = null;
}
// Set a maximum timeout for waiting for the server to send final transcript
const MAX_WAIT_FOR_FINAL = 5000; // 5 seconds
shutdownTimeoutId = setTimeout(
completeShutdown,
MAX_WAIT_FOR_FINAL,
errorMessage
);
stopLevelMonitoringOffscreen();
}
// Helper function to complete the shutdown process
function completeShutdown(errorMessage = null) {
console.log(
"Offscreen: Completing shutdown process - cleaning up resources."
);
// Clear the timeout if it's still active
if (shutdownTimeoutId) {
clearTimeout(shutdownTimeoutId);
shutdownTimeoutId = null;
}
// Update state to indicate fully disconnected
isWebSocketConnected = false;
sendStatusUpdateOffscreen();
if (audioWorkletNode) {
console.log("Offscreen: Disconnecting AudioWorkletNode...");
try {
audioWorkletNode.disconnect();
} catch (e) {
console.error("Offscreen: Error disconnecting AudioWorkletNode:", e);
}
audioWorkletNode = null;
}
if (scriptProcessor) {
console.log("Offscreen: Disconnecting scriptProcessor...");
try {
scriptProcessor.disconnect();
} catch (e) {
console.error("Offscreen: Error disconnecting scriptProcessor:", e);
}
scriptProcessor = null;
}
if (audioSource) {
console.log("Offscreen: Disconnecting audioSource...");
try {
audioSource.disconnect();
} catch (e) {
console.error("Offscreen: Error disconnecting audioSource:", e);
}
audioSource = null;
}
if (tabStream) {
console.log("Offscreen: Stopping tab stream tracks...");
tabStream.getTracks().forEach((track) => {
try {
track.stop();
} catch (e) {
console.error("Offscreen: Error stopping tab track:", e);
}
});
tabStream = null;
}
if (audioContext) {
console.log("Offscreen: Closing audio context...");
try {
audioContext.close();
} catch (e) {
console.error("Offscreen: Error closing audio context:", e);
}
audioContext = null;
}
if (socket && socket.readyState === WebSocket.OPEN) {
console.log("Offscreen: Closing WebSocket...");
try {
socket.close();
} catch (e) {
console.error("Offscreen: Error closing socket:", e);
}
} else if (socket) {
console.log("Offscreen: WebSocket already closed or closing.");
}
socket = null;
analyser = null;
audioLevelDataArray = null;
console.log("Offscreen: Cleanup complete.");
if (errorMessage) {
chrome.runtime
.sendMessage({
type: "RECORDING_ERROR",
target: "background",
error: errorMessage,
})
.catch((error) => {
if (
error.message !==
"Could not establish connection. Receiving end does not exist."
) {
console.warn(
"Offscreen: Could not send error message to background:",
error.message
);
}
});
}
// Send a message that transcription is complete
chrome.runtime
.sendMessage({
type: "STATUS_UPDATE",
target: "background",
message: "Recording stopped.",
})
.catch((error) => {
if (
error.message !==
"Could not establish connection. Receiving end does not exist."
) {
console.warn(
"Offscreen: Could not send final status message to background:",
error.message
);
}
});
}
// Function to send status updates to the background script
function sendStatusUpdateOffscreen() {
console.log("Offscreen: Sending status update to background:", {
isRecording: isRecordingActive,
isConnected: isWebSocketConnected,
});
chrome.runtime
.sendMessage({
type: "RECORDING_STATE_UPDATE",
target: "background",
isRecording: isRecordingActive,
isConnected: isWebSocketConnected,
})
.catch((error) => {
if (
error.message !==
"Could not establish connection. Receiving end does not exist."
) {
console.warn(
"Offscreen: Could not send status update message to background:",
error.message
);
}
});
}
// Implement Audio Level Monitoring
function startLevelMonitoringOffscreen() {
if (!audioContext || !analyser || audioLevelDataArray === null) {
console.error(
"Offscreen: Cannot start level monitoring, Web Audio not initialized."
);
return;
}
console.log("Offscreen: Starting level monitoring.");
stopLevelMonitoringOffscreen();
const intervalTime = 100; // milliseconds
levelMonitorInterval = setInterval(() => {
if (!isRecordingActive || !analyser || audioLevelDataArray === null) {
stopLevelMonitoringOffscreen();
return;
}
analyser.getByteFrequencyData(audioLevelDataArray);
let sum = 0;
for (let i = 0; i < audioLevelDataArray.length; i++) {
sum += audioLevelDataArray[i];
}
const averageLevel = sum / audioLevelDataArray.length;
const normalizedLevel = averageLevel / 255;
chrome.runtime
.sendMessage({
type: "AUDIO_LEVEL_UPDATE",
target: "background",
level: normalizedLevel,
})
.catch((error) => {
if (
error.message !==
"Could not establish connection. Receiving end does not exist."
) {
console.warn(
"Offscreen: Could not send level update message to background:",
error.message
);
}
});
}, intervalTime);
}
function stopLevelMonitoringOffscreen() {
console.log("Offscreen: Stopping level monitoring.");
if (levelMonitorInterval !== null) {
clearInterval(levelMonitorInterval);
levelMonitorInterval = null;
}
chrome.runtime
.sendMessage({ type: "AUDIO_LEVEL_UPDATE", target: "background", level: 0 })
.catch((error) => {
if (
error.message !==
"Could not establish connection. Receiving end does not exist."
) {
console.warn(
"Offscreen: Could not send final level update message to background:",
error.message
);
}
});
}
// --- Helper functions for audio processing ---
// Function to merge multiple Int16Array chunks into a single ArrayBuffer
function mergeAudioChunks(chunks, totalSamples) {
// Create a new Int16Array to hold all samples
const mergedArray = new Int16Array(totalSamples);
let offset = 0;
chunks.forEach((chunk) => {
mergedArray.set(chunk, offset);
offset += chunk.length;
});
return mergedArray.buffer;
}
// Basic resampling function (linear interpolation)
// Note: More sophisticated resampling (e.g., using a library or AudioWorklet with a proper resampler)
// would provide better quality. This is a simple implementation for demonstration.
function resampleAudio(inputBuffer, sourceSampleRate, targetSampleRate) {
if (sourceSampleRate === targetSampleRate) {
return inputBuffer; // No resampling needed
}
const ratio = targetSampleRate / sourceSampleRate;
const newLength = Math.round(inputBuffer.length * ratio);
const resampledBuffer = new Float32Array(newLength);
const oldSampleRate = 1 / sourceSampleRate;
const newSampleRate = 1 / targetSampleRate;
for (let i = 0; i < newLength; i++) {
const oldIndex = i / ratio;
const indexFloor = Math.floor(oldIndex);
const indexCeil = Math.ceil(oldIndex);
const frac = oldIndex - indexFloor;
if (indexCeil >= inputBuffer.length) {
resampledBuffer[i] = inputBuffer[indexFloor];
} else {
// Linear interpolation
resampledBuffer[i] =
inputBuffer[indexFloor] * (1 - frac) + inputBuffer[indexCeil] * frac;
}
}
return resampledBuffer;
}
// Convert Float32Array to Int16Array (16-bit PCM)
function float32ToInt16(floatBuffer) {
const int16Buffer = new Int16Array(floatBuffer.length);
for (let i = 0; i < floatBuffer.length; i++) {
// Clamp the value to the range [-1, 1] and scale to Int16 range
const s = Math.max(-1, Math.min(1, floatBuffer[i]));
int16Buffer[i] = s < 0 ? s * 32768 : s * 32767;
}
return int16Buffer;
}