-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoffscreen.js
More file actions
244 lines (198 loc) · 6.79 KB
/
offscreen.js
File metadata and controls
244 lines (198 loc) · 6.79 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
const audioProcessors = new Map();
let audioContext = null;
function initAudioContext() {
if (!audioContext) {
audioContext = new AudioContext();
}
if (audioContext.state === 'suspended') {
audioContext.resume();
}
}
class TabAudioProcessor {
constructor(tabId, stream, initialGain = 100) {
this.tabId = Number.parseInt(tabId) || 0;
this.stream = stream;
// Validação de ganho inicial - usar Number.isNaN para aceitar 0 corretamente
const parsedGain = Number.parseInt(initialGain, 10);
const validGain = Math.max(0, Math.min(600, Number.isNaN(parsedGain) ? 100 : parsedGain));
this.gain = validGain / 100;
this.isMuted = false;
this.sourceNode = null;
this.gainNode = null;
this.compressorNode = null;
this.destinationNode = null;
this.setupAudioGraph();
}
setupAudioGraph() {
try {
this.sourceNode = audioContext.createMediaStreamSource(this.stream);
this.gainNode = audioContext.createGain();
this.gainNode.gain.value = this.isMuted ? 0 : this.gain;
this.compressorNode = audioContext.createDynamicsCompressor();
this.compressorNode.threshold.value = -24;
this.compressorNode.knee.value = 30;
this.compressorNode.ratio.value = 12;
this.compressorNode.attack.value = 0.003;
this.compressorNode.release.value = 0.25;
this.destinationNode = audioContext.destination;
this.sourceNode.connect(this.gainNode);
this.gainNode.connect(this.compressorNode);
this.compressorNode.connect(this.destinationNode);
} catch (error) {
console.error(`Erro ao configurar grafo de áudio para aba ${this.tabId}:`, error);
throw error;
}
}
setGain(gain) {
if (this.gainNode) {
// Validação de ganho - usar Number.isNaN para aceitar 0 corretamente
const parsed = Number.parseInt(gain, 10);
const validGain = Math.max(0, Math.min(600, Number.isNaN(parsed) ? 100 : parsed)) / 100;
this.gain = validGain;
this.gainNode.gain.value = this.isMuted ? 0 : this.gain;
}
}
setMute(muted) {
if (this.gainNode) {
this.isMuted = muted;
this.gainNode.gain.value = muted ? 0 : this.gain;
}
}
stop() {
try {
if (this.sourceNode) {
this.sourceNode.disconnect();
}
if (this.gainNode) {
this.gainNode.disconnect();
}
if (this.compressorNode) {
this.compressorNode.disconnect();
}
if (this.stream) {
this.stream.getTracks().forEach(track => track.stop());
}
console.log(`Processador de áudio parado para aba ${this.tabId}`);
} catch (error) {
console.error(`Erro ao parar processador de áudio para aba ${this.tabId}:`, error);
}
}
}
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
const { action } = message;
const handlers = {
'processAudio': () => handleProcessAudio(message.tabId, message.mediaStreamId, message.gain, sendResponse),
'restoreAudio': () => handleRestoreAudio(message.tabId, message.gain, sendResponse),
'stopProcessing': () => handleStopProcessing(message.tabId, sendResponse),
'setGain': () => handleSetGain(message.tabId, message.gain, sendResponse),
'setMute': () => handleSetMute(message.tabId, message.muted, sendResponse),
'checkProcessor': () => handleCheckProcessor(message.tabId, sendResponse)
};
if (handlers[action]) {
handlers[action]();
return true;
}
});
// Verificar se existe processador ativo para uma aba
function handleCheckProcessor(tabId, sendResponse) {
const validTabId = Number.parseInt(tabId) || 0;
const exists = audioProcessors.has(validTabId);
sendResponse({ exists });
}
async function handleProcessAudio(tabId, mediaStreamId, gain, sendResponse) {
try {
const validTabId = Number.parseInt(tabId) || 0;
if (audioProcessors.has(validTabId)) {
sendResponse({ success: false, error: 'Aba já está sendo processada' });
return;
}
initAudioContext();
const stream = await navigator.mediaDevices.getUserMedia({
audio: {
mandatory: {
chromeMediaSource: 'tab',
chromeMediaSourceId: mediaStreamId
}
},
video: false
});
const processor = new TabAudioProcessor(validTabId, stream, gain);
audioProcessors.set(validTabId, processor);
sendResponse({ success: true });
} catch (error) {
console.error('Erro ao processar áudio:', error);
sendResponse({ success: false, error: error.message });
}
}
async function handleRestoreAudio(tabId, gain, sendResponse) {
try {
if (audioProcessors.has(tabId)) {
const processor = audioProcessors.get(tabId);
processor.setGain(gain);
sendResponse({ success: true });
return;
}
const mediaStreamId = await chrome.tabCapture.getMediaStreamId({
targetTabId: tabId
});
if (!mediaStreamId) {
sendResponse({ success: false, error: 'Não foi possível obter stream de áudio' });
return;
}
await handleProcessAudio(tabId, mediaStreamId, gain, sendResponse);
} catch (error) {
console.error('Erro ao restaurar áudio:', error);
sendResponse({ success: false, error: error.message });
}
}
function handleStopProcessing(tabId, sendResponse) {
try {
const processor = audioProcessors.get(tabId);
if (!processor) {
sendResponse({ success: false, error: 'Nenhum processador encontrado para esta aba' });
return;
}
processor.stop();
audioProcessors.delete(tabId);
sendResponse({ success: true });
} catch (error) {
console.error('Erro ao parar processamento:', error);
sendResponse({ success: false, error: error.message });
}
}
function handleSetGain(tabId, gain, sendResponse) {
try {
const validTabId = Number.parseInt(tabId) || 0;
const processor = audioProcessors.get(validTabId);
if (!processor) {
sendResponse({ success: false, error: 'Nenhum processador encontrado para esta aba' });
return;
}
processor.setGain(gain);
sendResponse({ success: true });
} catch (error) {
console.error('Erro ao definir ganho:', error);
sendResponse({ success: false, error: error.message });
}
}
function handleSetMute(tabId, muted, sendResponse) {
try {
const validTabId = Number.parseInt(tabId) || 0;
const processor = audioProcessors.get(validTabId);
if (!processor) {
sendResponse({ success: false, error: 'Nenhum processador encontrado para esta aba' });
return;
}
processor.setMute(Boolean(muted));
sendResponse({ success: true });
} catch (error) {
console.error('Erro ao mutar/desmutar:', error);
sendResponse({ success: false, error: error.message });
}
}
window.addEventListener('beforeunload', () => {
for (const processor of audioProcessors.values()) {
processor.stop();
}
audioProcessors.clear();
});