Repository navigation
Expand file tree
/
Copy pathoffscreen.js
More file actions
445 lines (417 loc) · 13.6 KB
/
Copy pathoffscreen.js
File metadata and controls
445 lines (417 loc) · 13.6 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
// Offscreen document: owns the AudioWorklet recorder, IndexedDB writes,
// stem-separation worker and WAV exports.
import { encodeWav, decodeWavBlob, splitChannels, floatToInterleaved, reverseWav, sliceWav, mixStems } from './lib/wav.js';
import { saveRecording, getRecording, newId } from './lib/db.js';
const SAMPLE_RATE = 44100;
const STEM_NAMES = ['drums', 'bass', 'other', 'vocals'];
let recorder = null;
let lastRecordingId = null;
let modelStatus = { status: 'unknown' };
const IDLE_CLOSE_MS = 60_000;
let idleTimer = null;
let busyCount = 0;
let activeStemJob = false;
let activeDownload = false;
const worker = new Worker(chrome.runtime.getURL('stems-worker.js'), { type: 'module' });
worker.onmessage = async ({ data }) => {
const message = data || {};
touch();
if (message.type === 'status' || message.type === 'download-progress' || message.type === 'downloaded') {
if (message.type === 'downloaded') activeDownload = false;
modelStatus = message.type === 'download-progress'
? { status: 'downloading', received: message.received, total: message.total }
: {
...message,
status: message.type === 'downloaded' ? 'cached' : message.status,
};
broadcast({ type: 'model-status', status: modelStatus });
return;
}
if (message.type === 'progress') {
broadcast({
type: 'stems-job',
job: {
jobId: message.jobId,
recordingId: message.recordingId,
kind: 'progress',
progress: message.progress,
},
});
return;
}
if (message.type === 'stems') {
activeStemJob = false;
try {
const recording = await getRecording(message.recordingId);
if (!recording) throw new Error('Enregistrement introuvable');
const stems = {};
for (const name of STEM_NAMES) {
const data = message.stems[name];
if (!data) continue;
stems[name] = encodeWav(floatToInterleaved([data.left, data.right]), 2, SAMPLE_RATE);
}
await saveRecording({ ...recording, stems, updatedAt: Date.now() });
broadcast({
type: 'stems-job',
job: {
jobId: message.jobId,
recordingId: message.recordingId,
kind: 'done',
stems: Object.keys(stems),
},
});
} catch (error) {
broadcast({
type: 'stems-job',
job: {
jobId: message.jobId,
recordingId: message.recordingId,
kind: 'error',
message: error.message,
},
});
}
return;
}
if (message.type === 'error') {
activeDownload = false;
activeStemJob = false;
broadcast({
type: 'stems-job',
job: {
jobId: message.jobId,
recordingId: message.recordingId,
kind: 'error',
message: message.message,
},
});
}
};
worker.onerror = (event) => {
activeDownload = false;
activeStemJob = false;
broadcast({
type: 'stems-job',
job: { kind: 'error', message: event.message || 'Erreur du worker de séparation' },
});
};
function broadcast(message) {
chrome.runtime.sendMessage(message).catch(() => {});
}
function isBusy() {
return busyCount > 0 || Boolean(recorder) || activeStemJob || activeDownload;
}
function touch() {
if (idleTimer) clearTimeout(idleTimer);
idleTimer = setTimeout(maybeCloseWhenIdle, IDLE_CLOSE_MS);
}
function maybeCloseWhenIdle() {
if (isBusy()) {
touch();
return;
}
idleTimer = null;
chrome.runtime.sendMessage({ type: 'idle-close' }).catch(() => {});
}
function concatInt16(chunks) {
let length = 0;
for (const chunk of chunks) length += chunk.length;
const out = new Int16Array(length);
let offset = 0;
for (const chunk of chunks) {
out.set(chunk, offset);
offset += chunk.length;
}
return out;
}
async function startRecording({ streamId, tabName }) {
if (recorder) throw new Error('Un enregistrement est déjà en cours');
const stream = await navigator.mediaDevices.getUserMedia({
audio: {
mandatory: {
chromeMediaSource: 'tab',
chromeMediaSourceId: streamId,
sampleRate: SAMPLE_RATE,
channelCount: 2,
},
},
});
const context = new AudioContext({ sampleRate: SAMPLE_RATE, latencyHint: 'interactive' });
try {
await context.audioWorklet.addModule(chrome.runtime.getURL('pcm-worklet.js'));
} catch (error) {
stream.getTracks().forEach((track) => track.stop());
await context.close();
throw error;
}
const source = context.createMediaStreamSource(stream);
// The original recorder keeps the graph active via destination while the
// zero-output worklet acts as a sink. Without this, the processor may never run.
source.connect(context.destination);
const node = new AudioWorkletNode(context, 'pcm-capture', {
numberOfInputs: 1,
numberOfOutputs: 0,
channelCount: 2,
});
const chunks = [];
const peakRef = { value: 0 };
node.port.onmessage = ({ data }) => {
if (data?.pcm) chunks.push(data.pcm);
if (typeof data?.peak === 'number') peakRef.value = Math.max(peakRef.value, data.peak);
};
source.connect(node);
await context.resume();
recorder = {
id: newId(),
tabName: tabName || 'Onglet',
startedAt: Date.now(),
context,
stream,
source,
node,
chunks,
peakRef,
channels: 2,
};
broadcast({
type: 'recording-state',
recording: true,
startedAt: recorder.startedAt,
tabName: recorder.tabName,
});
}
async function stopRecording() {
const current = recorder;
if (!current) return null;
recorder = null;
await new Promise((resolve) => {
const timeout = setTimeout(resolve, 1000);
current.node.port.onmessage = ({ data }) => {
if (data?.pcm) current.chunks.push(data.pcm);
if (typeof data?.peak === 'number') current.peakRef.value = Math.max(current.peakRef.value, data.peak);
if (data?.flushed) {
clearTimeout(timeout);
resolve();
}
};
current.node.port.postMessage({ type: 'stop' });
});
current.source.disconnect();
current.node.disconnect();
current.stream.getTracks().forEach((track) => track.stop());
await current.context.close().catch(() => {});
const interleaved = concatInt16(current.chunks);
if (!interleaved.length) throw new Error('Aucun audio capturé');
if (current.peakRef.value < 0.001) {
broadcast({ type: 'recording-state', recording: false });
broadcast({ type: 'recording-silent' });
return null;
}
const wav = encodeWav(interleaved, current.channels, SAMPLE_RATE);
const durationSeconds = interleaved.length / current.channels / SAMPLE_RATE;
const recording = {
id: current.id,
name: `${current.tabName} — ${new Date(current.startedAt).toLocaleTimeString('fr-FR')}`,
createdAt: current.startedAt,
updatedAt: Date.now(),
durationSeconds,
sampleRate: SAMPLE_RATE,
channels: current.channels,
wav,
reversed: reverseWav(await wav.arrayBuffer()),
stems: {},
};
await saveRecording(recording);
lastRecordingId = recording.id;
broadcast({ type: 'recording-state', recording: false });
broadcast({ type: 'recording-saved', recordingId: recording.id });
return recording;
}
async function runStems(job) {
if (!job?.recordingId) throw new Error('Enregistrement manquant');
const recording = await getRecording(job.recordingId);
if (!recording) throw new Error('Enregistrement introuvable');
const decoded = await decodeWavBlob(recording.wav);
const [left, right] = splitChannels(decoded.int16, decoded.channels);
worker.postMessage(
{
type: 'separate',
jobId: job.jobId || newId(),
recordingId: recording.id,
left,
right,
},
[left.buffer, right.buffer]
);
}
async function mixStemBlobs(blobs, gains, startSec, endSec) {
if (!blobs.length) throw new Error('Aucune tige sélectionnée');
const decoded = await Promise.all(blobs.map((blob) => decodeWavBlob(blob)));
const sampleRate = decoded[0].sampleRate;
const frames = Math.floor(decoded[0].int16.length / decoded[0].channels);
const from = Math.max(0, Math.min(frames, Math.round(startSec * sampleRate)));
const to = Math.max(from, Math.min(frames, Math.round(endSec * sampleRate)));
const length = to - from;
const left = new Float32Array(length);
const right = new Float32Array(length);
decoded.forEach((item, index) => {
const channels = splitChannels(item.int16, item.channels);
const gain = gains[index] ?? 1;
for (let i = 0; i < length; i++) {
left[i] += (channels[0][from + i] || 0) * gain;
right[i] += (channels[channels.length - 1][from + i] || 0) * gain;
}
});
return encodeWav(floatToInterleaved([left, right]), 2, sampleRate);
}
async function applyTrim({ recordingId, start, end }) {
const recording = await getRecording(recordingId);
if (!recording) throw new Error('Enregistrement introuvable');
const wav = sliceWav(await recording.wav.arrayBuffer(), start, end);
const stems = {};
for (const name of STEM_NAMES) {
const blob = recording.stems?.[name];
if (blob) stems[name] = sliceWav(await blob.arrayBuffer(), start, end);
}
const next = {
...recording,
wav,
reversed: reverseWav(await wav.arrayBuffer()),
stems,
durationSeconds: end - start,
trimmed: [start, end],
updatedAt: Date.now(),
};
await saveRecording(next);
broadcast({ type: 'recording-updated', recordingId });
return { ok: true, durationSeconds: next.durationSeconds };
}
async function exportAudio({ recordingId, kind, start = 0, end = 0, stems = [], fileName }) {
const recording = await getRecording(recordingId);
if (!recording) throw new Error('Enregistrement introuvable');
const to = end > start ? end : recording.durationSeconds;
let blob;
if (kind === 'original') {
blob = sliceWav(await recording.wav.arrayBuffer(), start, to);
} else if (kind === 'stems') {
const blobs = stems.map((stem) => recording.stems?.[stem.id || stem]).filter(Boolean);
blob = await mixStemBlobs(blobs, stems.map((stem) => stem.gain ?? 1), start, to);
} else if (kind === 'mix') {
const blobs = stems.map((stem) => recording.stems?.[stem.id || stem]).filter(Boolean);
const mixed = await mixStemBlobs(blobs, stems.map((stem) => stem.gain ?? 1), start, to);
const base = sliceWav(await recording.wav.arrayBuffer(), start, to);
blob = mixStems(
await base.arrayBuffer(),
[await mixed.arrayBuffer()],
[1],
0,
to - start
);
} else {
throw new Error(`Export inconnu: ${kind}`);
}
const safeName = (fileName || `${recording.name.replace(/[^\w\- ]/g, '_')}.wav`)
.replace(/[<>:"/\\|?*\x00-\x1f]/g, '_');
const url = URL.createObjectURL(blob);
setTimeout(() => URL.revokeObjectURL(url), 60000);
let downloadId = null;
let viaApi = false;
if (typeof chrome.downloads?.download === 'function') {
try {
downloadId = await chrome.downloads.download({
url,
filename: safeName,
conflictAction: 'uniquify',
saveAs: false,
});
viaApi = true;
} catch {
// Brave can hide the downloads API in offscreen contexts: fall back below.
}
}
if (!viaApi) {
const anchor = document.createElement('a');
anchor.href = url;
anchor.download = safeName;
anchor.style.display = 'none';
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
}
broadcast({ type: 'export-done', downloadId, fileName: safeName });
return { ok: true, downloadId, viaApi };
}
chrome.runtime.onMessage.addListener((message, sender, respond) => {
if (!message || message.target !== 'offscreen') return false;
// Content scripts must go through the service worker, never directly here.
if (sender?.id !== chrome.runtime.id || sender.tab) return false;
touch();
(async () => {
busyCount++;
try {
let result = { ok: true };
switch (message.type) {
case 'get-state':
result = {
ok: true,
recording: Boolean(recorder),
startedAt: recorder?.startedAt ?? null,
tabName: recorder?.tabName ?? '',
lastRecordingId,
modelStatus,
};
break;
case 'start-recording':
await startRecording(message);
break;
case 'stop-recording': {
const recording = await stopRecording();
result = { ok: true, recordingId: recording?.id ?? null };
break;
}
case 'model-status':
worker.postMessage({ type: 'status' });
break;
case 'model-download':
activeDownload = true;
worker.postMessage({ type: 'download' });
break;
case 'stems-run':
activeStemJob = true;
await runStems(message.job);
break;
case 'apply-trim':
result = await applyTrim(message);
break;
case 'export-audio':
result = await exportAudio(message);
break;
default:
throw new Error(`Message offscreen inconnu: ${message.type}`);
}
respond?.(result);
} catch (error) {
if (message.type === 'model-download') activeDownload = false;
if (message.type === 'stems-run') activeStemJob = false;
respond?.({ ok: false, error: error.message });
if (message.type === 'stems-run') {
broadcast({
type: 'stems-job',
job: {
jobId: message.job?.jobId,
recordingId: message.job?.recordingId,
kind: 'error',
message: error.message,
},
});
}
} finally {
busyCount--;
touch();
}
})();
return true;
});
worker.postMessage({ type: 'status' });
broadcast({ type: 'offscreen-ready' });
touch();