Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

utils.ts

439 lines12.3 KB

1import type { GeminiLiveClient } from './client'
2​
3/**
4 * Audio Worklet Processor for capturing and processing audio
5 */
6const captureWorkletCode = `
7class AudioCaptureProcessor extends AudioWorkletProcessor {
8 constructor() {
9 super();
10 this.bufferSize = 512; // 32ms at 16kHz — per Gemini best practices (20-40ms chunks)
11 this.buffer = new Float32Array(this.bufferSize);
12 this.bufferIndex = 0;
13 }
14​
15 process(inputs, outputs, parameters) {
16 const input = inputs[0];
17​
18 if (input && input.length > 0) {
19 const inputChannel = input[0];
20​
21 // Buffer the incoming audio
22 for (let i = 0; i < inputChannel.length; i++) {
23 this.buffer[this.bufferIndex++] = inputChannel[i];
24​
25 // When buffer is full, send it to main thread
26 if (this.bufferIndex >= this.bufferSize) {
27 // Send the buffered audio to the main thread
28 this.port.postMessage({
29 type: "audio",
30 data: this.buffer.slice(),
31 });
32​
33 // Reset buffer
34 this.bufferIndex = 0;
35 }
36 }
37 }
38​
39 // Return true to keep the processor alive
40 return true;
41 }
43​
44// Register the processor
45registerProcessor("audio-capture-processor", AudioCaptureProcessor);`
46​
47/**
48 * Audio Playback Worklet Processor for playing PCM audio.
49 * Uses an offset tracker instead of slice() to avoid allocations
50 * on the real-time audio thread.
51 */
52const playbackWorkletCode = `
53class PCMProcessor extends AudioWorkletProcessor {
54 constructor() {
55 super();
56 this.audioQueue = [];
57 this.currentOffset = 0; // Track position in current buffer (avoids slice())
58​
59 this.port.onmessage = (event) => {
60 if (event.data === "interrupt") {
61 // Clear the queue on interrupt
62 this.audioQueue = [];
63 this.currentOffset = 0;
64 } else if (event.data instanceof Float32Array) {
65 // Add audio data to the queue
66 this.audioQueue.push(event.data);
67 }
68 };
69 }
70​
71 process(inputs, outputs, parameters) {
72 const output = outputs[0];
73 if (output.length === 0) return true;
74​
75 const channel = output[0];
76 let outputIndex = 0;
77​
78 // Fill the output buffer from the queue
79 while (outputIndex < channel.length && this.audioQueue.length > 0) {
80 const currentBuffer = this.audioQueue[0];
81​
82 if (!currentBuffer || currentBuffer.length === 0) {
83 this.audioQueue.shift();
84 this.currentOffset = 0;
85 continue;
86 }
87​
88 const remainingOutput = channel.length - outputIndex;
89 const remainingBuffer = currentBuffer.length - this.currentOffset;
90 const copyLength = Math.min(remainingOutput, remainingBuffer);
91​
92 // Copy audio data to output using offset (no slice allocation)
93 for (let i = 0; i < copyLength; i++) {
94 channel[outputIndex++] = currentBuffer[this.currentOffset++];
95 }
96​
97 // If we've consumed the entire buffer, move to the next one
98 if (this.currentOffset >= currentBuffer.length) {
99 this.audioQueue.shift();
100 this.currentOffset = 0;
101 }
102 }
103​
104 // Fill remaining output with silence
105 while (outputIndex < channel.length) {
106 channel[outputIndex++] = 0;
107 }
108​
109 return true;
110 }
112​
113registerProcessor("pcm-processor", PCMProcessor);`
114​
115function calculateLevel(analyser: AnalyserNode): number {
116 const data = new Uint8Array(analyser.fftSize)
117 analyser.getByteTimeDomainData(data)
118​
119 // Find peak deviation from center (128 is silence)
120 // This is more responsive than RMS for voice level meters
121 let maxDeviation = 0
122 for (const sample of data) {
123 const deviation = Math.abs(sample - 128)
124 if (deviation > maxDeviation) {
125 maxDeviation = deviation
126 }
127 }
128​
129 // Normalize to 0-1 range (max deviation is 128)
130 // Scale by 1.5x so that ~66% amplitude reads as full scale
131 // This provides good visual feedback without pegging too early
132 const normalized = maxDeviation / 128
133 return Math.min(1, normalized * 1.5)
135​
136export function base64ToArrayBuffer(base64: string): ArrayBuffer {
137 const binary = atob(base64)
138 const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0))
139 return bytes.buffer
141​
142// Empty arrays for when visualization isn't available
143// frequencyBinCount = fftSize / 2 = 1024
144const emptyFrequencyData = new Uint8Array(1024)
145const emptyTimeDomainData = new Uint8Array(2048).fill(128) // 128 is silence
146​
147export class AudioStreamer {
148 private audioContext: AudioContext | null = null
149 private audioWorklet: AudioWorkletNode | null = null
150 private mediaStream: MediaStream | null = null
151 private analyser: AnalyserNode | null = null
152 private isStreaming = false
153 private readonly sampleRate = 16000
154 private readonly client: GeminiLiveClient | null = null
155​
156 constructor(client: GeminiLiveClient) {
157 this.client = client
158 }
159​
160 get inputLevel() {
161 if (!this.analyser) return 0
162 return calculateLevel(this.analyser)
163 }
164​
165 get inputFrequencyData() {
166 if (!this.analyser) return emptyFrequencyData
167 const data = new Uint8Array(this.analyser.frequencyBinCount)
168 this.analyser.getByteFrequencyData(data)
169 return data
170 }
171​
172 get inputTimeDomainData() {
173 if (!this.analyser) return emptyTimeDomainData
174 const data = new Uint8Array(this.analyser.fftSize)
175 this.analyser.getByteTimeDomainData(data)
176 return data
177 }
178​
179 get inputSampleRate() {
180 return this.sampleRate
181 }
182​
183 async start() {
184 try {
185 const audioConstraints: MediaTrackConstraints = {
186 sampleRate: this.sampleRate,
187 echoCancellation: true,
188 noiseSuppression: true,
189 autoGainControl: true,
190 }
191​
192 // Get microphone access
193 this.mediaStream = await navigator.mediaDevices.getUserMedia({
194 audio: audioConstraints,
195 })
196​
197 // Check if native AGC is active
198 const track = this.mediaStream.getAudioTracks()[0]
199 const settings = track?.getSettings()
200​
201 if (settings?.autoGainControl) {
202 console.warn('Native AGC not supported.')
203 }
204​
205 // Create audio context
206 this.audioContext = new AudioContext({
207 sampleRate: this.sampleRate,
208 })
209​
210 if (this.audioContext.state === 'suspended') {
211 await this.audioContext.resume()
212 }
213​
214 const workletBlob = new Blob([captureWorkletCode], {
215 type: 'application/javascript',
216 })
217 const workletUrl = URL.createObjectURL(workletBlob)
218​
219 // Load the audio worklet module, then release the blob URL.
220 await this.audioContext.audioWorklet.addModule(workletUrl)
221 URL.revokeObjectURL(workletUrl)
222​
223 // Create the audio worklet node
224 this.audioWorklet = new AudioWorkletNode(
225 this.audioContext,
226 'audio-capture-processor',
227 )
228​
229 // Set up message handling from the worklet
230 this.audioWorklet.port.onmessage = (event) => {
231 if (!this.isStreaming) return
232​
233 if (event.data.type === 'audio') {
234 const inputData = event.data.data
235 const pcmData = this.convertToPCM16(inputData)
236 const base64Audio = this.arrayBufferToBase64(pcmData)
237​
238 // Send to Gemini only if after setup complete
239 if (this.client?.isSetupComplete) {
240 this.client.sendAudioMessage(base64Audio)
241 }
242 }
243 }
244​
245 // Create analyser for volume detection
246 this.analyser = this.audioContext.createAnalyser()
247 this.analyser.fftSize = 2048 // Larger size for more accurate level detection
248 this.analyser.smoothingTimeConstant = 0.3
249​
250 // Connect the audio graph
251 const source = this.audioContext.createMediaStreamSource(this.mediaStream)
252 source.connect(this.analyser)
253 this.analyser.connect(this.audioWorklet)
254​
255 // Start streaming
256 this.isStreaming = true
257 } catch (error) {
258 // Clean up the mic + audio context if setup failed partway through.
259 this.stop()
260 throw error
261 }
262 }
263​
264 stop() {
265 this.isStreaming = false
266​
267 if (this.audioWorklet) {
268 this.audioWorklet.disconnect()
269 this.audioWorklet.port.close()
270 this.audioWorklet = null
271 }
272​
273 if (this.audioContext) {
274 void this.audioContext.close()
275 this.audioContext = null
276 }
277​
278 if (this.mediaStream) {
279 this.mediaStream.getTracks().forEach((track) => track.stop())
280 this.mediaStream = null
281 }
282 }
283​
284 startAudioCapture() {
285 if (this.mediaStream) {
286 for (const track of this.mediaStream.getAudioTracks()) {
287 track.enabled = true
288 }
289 }
290 this.isStreaming = true
291 }
292​
293 stopAudioCapture() {
294 if (this.mediaStream) {
295 // Disable tracks rather than stopping them to allow re-enabling
296 for (const track of this.mediaStream.getAudioTracks()) {
297 track.enabled = false
298 }
299 }
300 this.isStreaming = false
301 }
302​
303 private convertToPCM16(float32Array: Float32Array): ArrayBuffer {
304 const int16Array = new Int16Array(float32Array.length)
305 for (let i = 0; i < float32Array.length; i++) {
306 const sample = Math.max(-1, Math.min(1, float32Array[i] ?? 0))
307 int16Array[i] = sample * 0x7fff
308 }
309 return int16Array.buffer
310 }
311​
312 private arrayBufferToBase64(buffer: ArrayBuffer): string {
313 const bytes = new Uint8Array(buffer)
314 const binary = String.fromCharCode(...bytes)
315 return btoa(binary)
316 }
318​
319export class AudioPlayer {
320 private audioContext: AudioContext | null = null
321 private workletNode: AudioWorkletNode | null = null
322 private gainNode: GainNode | null = null
323 private analyser: AnalyserNode | null = null
324 private isInitialized = false
325 private volume = 1.0
326 private readonly sampleRate = 24000
327​
328 get outputLevel() {
329 if (!this.analyser) return 0
330 return calculateLevel(this.analyser)
331 }
332​
333 get outputFrequencyData() {
334 if (!this.analyser) return emptyFrequencyData
335 const data = new Uint8Array(this.analyser.frequencyBinCount)
336 this.analyser.getByteFrequencyData(data)
337 return data
338 }
339​
340 get outputTimeDomainData() {
341 if (!this.analyser) return emptyTimeDomainData
342 const data = new Uint8Array(this.analyser.fftSize)
343 this.analyser.getByteTimeDomainData(data)
344 return data
345 }
346​
347 get outputSampleRate() {
348 return this.sampleRate
349 }
350​
351 async init() {
352 if (this.isInitialized) return
353​
354 try {
355 // Create audio context at 24kHz to match Gemini
356 this.audioContext = new AudioContext({
357 sampleRate: this.sampleRate,
358 })
359​
360 const workletBlob = new Blob([playbackWorkletCode], {
361 type: 'application/javascript',
362 })
363 const workletUrl = URL.createObjectURL(workletBlob)
364​
365 // Load the audio worklet module, then release the blob URL.
366 await this.audioContext.audioWorklet.addModule(workletUrl)
367 URL.revokeObjectURL(workletUrl)
368​
369 // Create worklet node
370 this.workletNode = new AudioWorkletNode(
371 this.audioContext,
372 'pcm-processor',
373 )
374​
375 // Create gain node for volume control
376 this.gainNode = this.audioContext.createGain()
377 this.gainNode.gain.value = this.volume
378​
379 // Create analyser for volume detection
380 this.analyser = this.audioContext.createAnalyser()
381 this.analyser.fftSize = 2048 // Larger size for more accurate level detection
382 this.analyser.smoothingTimeConstant = 0.3
383​
384 // Connect nodes
385 this.workletNode.connect(this.gainNode)
386 this.gainNode.connect(this.analyser)
387 this.analyser.connect(this.audioContext.destination)
388​
389 this.isInitialized = true
390 } catch (error) {
391 // Release the audio context if initialization failed partway through.
392 this.destroy()
393 throw error
394 }
395 }
396​
397 async play(pcmData: ArrayBuffer) {
398 if (!this.isInitialized) {
399 await this.init()
400 }
401​
402 // Resume audio context if suspended
403 if (this.audioContext?.state === 'suspended') {
404 await this.audioContext.resume()
405 }
406​
407 // Convert PCM16 LE to Float32
408 const inputArray = new Int16Array(pcmData)
409 const float32Data = new Float32Array(inputArray.length)
410 for (let i = 0; i < inputArray.length; i++) {
411 float32Data[i] = (inputArray[i] ?? 0) / 32768
412 }
413​
414 // Send to worklet for playback
415 this.workletNode?.port.postMessage(float32Data)
416 }
417​
418 /* Interrupt playback */
419 interrupt() {
420 if (this.workletNode) {
421 this.workletNode.port.postMessage('interrupt')
422 }
423 }
424​
425 setVolume(volume: number) {
426 this.volume = Math.max(0, Math.min(1, volume))
427 if (this.gainNode) {
428 this.gainNode.gain.value = this.volume
429 }
430 }
431​
432 destroy() {
433 if (this.audioContext) {
434 void this.audioContext.close()
435 this.audioContext = null
436 }
437 this.isInitialized = false
438 }