-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathmedia-handler.js
More file actions
268 lines (240 loc) · 7.78 KB
/
Copy pathmedia-handler.js
File metadata and controls
268 lines (240 loc) · 7.78 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
/**
* MediaHandler: Manages Audio/Video capture and playback
*/
class MediaHandler {
constructor() {
this.audioContext = null;
this.mediaStream = null;
this.audioWorkletNode = null;
this.videoStream = null;
this.videoInterval = null;
this.nextStartTime = 0;
this.scheduledSources = [];
this.isRecording = false;
this.videoCanvas = document.createElement('canvas');
this.canvasCtx = this.videoCanvas.getContext('2d');
}
async initializeAudio() {
if (!this.audioContext) {
this.audioContext =
new (window.AudioContext || window.webkitAudioContext)();
await this.audioContext.audioWorklet.addModule(
'/static/pcm-processor.js');
}
if (this.audioContext.state === 'suspended') {
await this.audioContext.resume();
}
}
async startAudio(onAudioData) {
await this.initializeAudio();
try {
this.mediaStream = await navigator.mediaDevices.getUserMedia({
audio: true,
});
const source =
this.audioContext.createMediaStreamSource(this.mediaStream);
this.audioWorkletNode =
new AudioWorkletNode(this.audioContext, 'pcm-processor');
this.audioWorkletNode.port.onmessage = (event) => {
if (this.isRecording) {
const downsampled = this.downsampleBuffer(
event.data, this.audioContext.sampleRate, 16000);
const pcm16 = this.convertFloat32ToInt16(downsampled);
onAudioData(pcm16);
}
};
source.connect(this.audioWorkletNode);
// Mute local feedback
const muteGain = this.audioContext.createGain();
muteGain.gain.value = 0;
this.audioWorkletNode.connect(muteGain);
muteGain.connect(this.audioContext.destination);
this.isRecording = true;
} catch (e) {
console.error('Error starting audio:', e);
throw e;
}
}
stopAudio() {
this.isRecording = false;
if (this.mediaStream) {
this.mediaStream.getTracks().forEach((t) => t.stop());
this.mediaStream = null;
}
if (this.audioWorkletNode) {
this.audioWorkletNode.disconnect();
this.audioWorkletNode = null;
}
}
async startVideo(videoElement, onFrame) {
try {
this.videoStream = await navigator.mediaDevices.getUserMedia({
video: true,
});
videoElement.srcObject = this.videoStream;
this.videoInterval = setInterval(() => {
this.captureFrame(videoElement, onFrame);
}, 1000); // 1 FPS
} catch (e) {
console.error('Error starting video:', e);
throw e;
}
}
/**
* Start video and also upload frames to the robot backend at 5 FPS.
* This feeds the fake backend so the robot camera pipeline works.
*/
async startVideoWithRobotFeed(videoElement, onFrame) {
try {
this.videoStream = await navigator.mediaDevices.getUserMedia({
video: true,
});
videoElement.srcObject = this.videoStream;
// 1 FPS for Gemini direct image input
this.videoInterval = setInterval(() => {
this.captureFrame(videoElement, onFrame);
}, 1000);
// 5 FPS upload to fake backend via proxy
const uploadCanvas = document.createElement('canvas');
uploadCanvas.width = 384;
uploadCanvas.height = 384;
const uploadCtx = uploadCanvas.getContext('2d');
this._robotFeedInterval = setInterval(() => {
if (!this.videoStream) return;
uploadCtx.drawImage(videoElement, 0, 0, 384, 384);
uploadCanvas.toBlob(async (blob) => {
if (!blob) return;
try {
await fetch('/api/upload_frame', {
method: 'POST',
headers: {'Content-Type': 'image/jpeg'},
body: blob,
});
} catch (e) {
// silent — backend may not be ready yet
}
}, 'image/jpeg', 0.8);
}, 200); // 5 FPS
} catch (e) {
console.error('Error starting video:', e);
throw e;
}
}
async startScreen(videoElement, onFrame, onEnded) {
try {
this.videoStream = await navigator.mediaDevices.getDisplayMedia({
video: true,
});
videoElement.srcObject = this.videoStream;
// Handle stream ending (e.g. user clicks "Stop sharing" in browser UI)
this.videoStream.getVideoTracks()[0].onended = () => {
this.stopVideo(videoElement);
if (onEnded) onEnded();
};
this.videoInterval = setInterval(() => {
this.captureFrame(videoElement, onFrame);
}, 1000); // 1 FPS
} catch (e) {
console.error('Error starting screen share:', e);
throw e;
}
}
stopVideo(videoElement) {
if (this.videoStream) {
this.videoStream.getTracks().forEach((t) => t.stop());
this.videoStream = null;
}
if (this.videoInterval) {
clearInterval(this.videoInterval);
this.videoInterval = null;
}
if (this._robotFeedInterval) {
clearInterval(this._robotFeedInterval);
this._robotFeedInterval = null;
}
if (videoElement) {
videoElement.srcObject = null;
}
}
captureFrame(videoElement, onFrame) {
if (!this.videoStream) return;
this.videoCanvas.width = 640;
this.videoCanvas.height = 480;
this.canvasCtx.drawImage(videoElement, 0, 0, 640, 480);
const base64 = this.videoCanvas.toDataURL('image/jpeg', 0.7).split(',')[1];
onFrame(base64);
}
playAudio(arrayBuffer) {
if (!this.audioContext) return;
if (this.audioContext.state === 'suspended') {
this.audioContext.resume();
}
let bufferToUse = arrayBuffer;
if (arrayBuffer.byteLength % 2 !== 0) {
console.warn(`Audio buffer length is odd (${
arrayBuffer.byteLength}), slicing to even length.`);
bufferToUse = arrayBuffer.slice(0, arrayBuffer.byteLength - 1);
}
const pcmData = new Int16Array(bufferToUse);
const float32Data = new Float32Array(pcmData.length);
for (let i = 0; i < pcmData.length; i++) {
float32Data[i] = pcmData[i] / 32768.0;
}
const buffer = this.audioContext.createBuffer(1, float32Data.length, 24000);
buffer.getChannelData(0).set(float32Data);
const source = this.audioContext.createBufferSource();
source.buffer = buffer;
source.connect(this.audioContext.destination);
const now = this.audioContext.currentTime;
this.nextStartTime = Math.max(now, this.nextStartTime);
source.start(this.nextStartTime);
this.nextStartTime += buffer.duration;
this.scheduledSources.push(source);
source.onended = () => {
const idx = this.scheduledSources.indexOf(source);
if (idx > -1) this.scheduledSources.splice(idx, 1);
};
}
stopAudioPlayback() {
this.scheduledSources.forEach((s) => {
try {
s.stop();
} catch (e) {
}
});
this.scheduledSources = [];
if (this.audioContext) {
this.nextStartTime = this.audioContext.currentTime;
}
}
// Utils
downsampleBuffer(buffer, sampleRate, outSampleRate) {
if (outSampleRate === sampleRate) return buffer;
const ratio = sampleRate / outSampleRate;
const newLength = Math.round(buffer.length / ratio);
const result = new Float32Array(newLength);
let offsetResult = 0;
let offsetBuffer = 0;
while (offsetResult < result.length) {
const nextOffsetBuffer = Math.round((offsetResult + 1) * ratio);
let accum = 0, count = 0;
for (let i = offsetBuffer; i < nextOffsetBuffer && i < buffer.length;
i++) {
accum += buffer[i];
count++;
}
result[offsetResult] = accum / count;
offsetResult++;
offsetBuffer = nextOffsetBuffer;
}
return result;
}
convertFloat32ToInt16(buffer) {
let l = buffer.length;
const buf = new Int16Array(l);
while (l--) {
buf[l] = Math.min(1, Math.max(-1, buffer[l])) * 0x7fff;
}
return buf.buffer;
}
}