-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
268 lines (230 loc) · 8.49 KB
/
index.js
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
import { AudioProcessor } from './src/audio/AudioProcessor.js'
import { makeVisualizer } from './src/Visualizer.js'
import './index.css'
// Add service worker registration
window.addEventListener('load', async () => {
console.log('Registering service worker...')
if(!navigator.serviceWorker) {
console.log('Service worker not supported')
return
}
// Add cache version to URL to force update when version changes
const registration = await navigator.serviceWorker.register(`/service-worker.js?version=${CACHE_NAME}`)
registration.addEventListener('statechange', (e) =>
console.log('ServiceWorker state changed:', e.target.state))
registration.addEventListener('message', processServiceWorkerMessage)
})
/**
* Process messages from the service worker
* @param {MessageEvent} event
*/
const processServiceWorkerMessage = (event) => {
if (event.data === 'reload') {
console.log('Received reload message from service worker')
window.stop()
return window.location.reload()
}
console.log('Received strange message from service worker', event.data)
}
const events = ['touchstart', 'touchmove', 'touchstop', 'keydown', 'mousedown', 'resize']
let ranMain = false
let startTime = 0
const params = new URLSearchParams(window.location.search)
const getVisualizerDOMElement = () => {
if (!window.visualizer) {
window.visualizer = document.getElementById('visualizer')
}
return window.visualizer
}
// Add this new function to handle touch/mouse coordinates
const getNormalizedCoordinates = (event, element) => {
let x, y
if (event.touches) {
x = event.touches[0].clientX
y = event.touches[0].clientY
} else {
x = event.clientX
y = event.clientY
}
const rect = element.getBoundingClientRect()
return {
x: (x - rect.left) / rect.width,
y: 1.0 - (y - rect.top) / rect.height // Flip Y coordinate for WebGL
}
}
const audioConfig = {
echoCancellation: params.get('echoCancellation') === 'true',
noiseSuppression: params.get('noiseSuppression') === 'true',
autoGainControl: params.get('autoGainControl') !== 'false', // true by default
voiceIsolation: params.get('voiceIsolation') === 'true',
latency: params.get('latency') ? parseFloat(params.get('latency')) : 0,
sampleRate: params.get('sampleRate') ? parseInt(params.get('sampleRate')) : 44100,
sampleSize: params.get('sampleSize') ? parseInt(params.get('sampleSize')) : 16,
channelCount: params.get('channelCount') ? parseInt(params.get('channelCount')) : 2,
}
// Factor out common audio setup logic
const getAudioStream = async (config) => {
const devices = await navigator.mediaDevices.enumerateDevices();
const audioInputs = devices.filter(device => device.kind === 'audioinput');
const constraints = {
audio: {
...config,
// Only specify deviceId if we have multiple audio inputs
...(audioInputs.length > 1 ? { deviceId: { exact: audioInputs[0].deviceId } } : {})
}
};
return navigator.mediaDevices.getUserMedia(constraints);
};
// Factor out coordinate handling
const coordsHandler = {
coords: { x: 0.5, y: 0.5 },
touched: false,
updateCoords(event, element) {
this.coords = getNormalizedCoordinates(event, element);
this.touched = true;
},
reset() {
this.touched = false;
}
};
// Factor out canvas event handling
const setupCanvasEvents = (canvas) => {
const updateCoords = (e) => coordsHandler.updateCoords(e, canvas);
const resetTouch = () => coordsHandler.reset();
canvas.addEventListener('touchmove', updateCoords);
canvas.addEventListener('touchstart', updateCoords);
canvas.addEventListener('mousemove', updateCoords);
canvas.addEventListener('touchend', resetTouch);
canvas.addEventListener('mouseup', resetTouch);
canvas.addEventListener('mouseleave', resetTouch);
};
// Check microphone access and initialize
const initializeAudio = async () => {
try {
await getAudioStream(audioConfig);
main();
} catch (err) {
document.querySelector('body').classList.remove('ready');
console.error('Audio initialization failed:', err);
}
};
const setupAudio = async () => {
const audioContext = new AudioContext();
await audioContext.resume();
const stream = await getAudioStream(audioConfig);
const sourceNode = audioContext.createMediaStreamSource(stream);
const historySize = parseInt(params.get('history_size') ?? '500');
const audioProcessor = new AudioProcessor(audioContext, sourceNode, historySize);
audioProcessor.start();
return audioProcessor;
};
const main = async () => {
try {
if (ranMain) return;
ranMain = true;
window.c = cranes;
startTime = performance.now();
const fragmentShader = await getFragmentShader();
const audio = await setupAudio();
window.shader = fragmentShader;
const canvas = getVisualizerDOMElement();
setupCanvasEvents(canvas);
const visualizerConfig = {
canvas,
initialImageUrl: params.get('image') ?? 'images/placeholder-image.png',
fullscreen: (params.get('fullscreen') ?? false) === 'true'
};
const render = await makeVisualizer(visualizerConfig);
requestAnimationFrame(() => animate({ render, audio, fragmentShader }));
} catch (e) {
console.error('Main initialization error:', e);
}
};
const animate = ({ render, audio, fragmentShader }) => {
requestAnimationFrame(() => animate({ render, audio, fragmentShader }));
const features = {
...audio.getFeatures(),
...Object.fromEntries(params),
...window.cranes.manualFeatures,
touch: [coordsHandler.coords.x, coordsHandler.coords.y],
touched: coordsHandler.touched
};
window.cranes.measuredAudioFeatures = features;
try {
render({
time: (performance.now() - startTime) / 1000,
features,
fragmentShader: window.cranes?.shader ?? fragmentShader,
});
} catch (e) {
console.error('Render error:', e);
}
};
// Combine initialization into a single function
const initializeApp = async () => {
if (ranMain) return;
// get the default audio input
const devices = await navigator.mediaDevices.enumerateDevices();
const audioInputs = devices.filter(device => device.kind === 'audioinput');
const defaultAudioInput = audioInputs[0].deviceId
try {
// Get microphone access first
await navigator.mediaDevices.getUserMedia({
audio: {
...audioConfig,
...(audioInputs.length > 1 ? { deviceId: { exact: defaultAudioInput } } : {})
}
});
// If successful, run main
await main();
// Add click handlers for fullscreen
if (!window.location.href.includes('edit')) {
const visualizer = getVisualizerDOMElement();
for (const event of events) {
visualizer.addEventListener(event, async () => {
try {
await document.documentElement.requestFullscreen();
} catch (e) {
console.error(`requesting fullscreen from event ${event} failed`, e);
}
}, { once: true });
}
}
} catch (err) {
console.error('Failed to initialize:', err);
const body = document.querySelector('body');
body.classList.remove('ready');
}
};
// Start initialization immediately
initializeApp();
window.cranes = {
manualFeatures: {}
}
const getRelativeOrAbsolute = async (url) => {
//if the url is not a full url, then it's a relative url
if (!url.includes('http')) {
url = `/shaders/${url}`
}
const res = await fetch(url)
const shader = await res.text()
return shader
}
const getFragmentShader = async () => {
const shaderUrl = params.get('shader')
let fragmentShader
if (shaderUrl) {
fragmentShader = await getRelativeOrAbsolute(`${shaderUrl}.frag`)
}
if (!fragmentShader) {
fragmentShader = localStorage.getItem('cranes-manual-code')
}
if (!fragmentShader) {
fragmentShader = await getRelativeOrAbsolute('default.frag')
}
return fragmentShader
}
if(process.env.LIVE_RELOAD) {
new EventSource('/esbuild').addEventListener('change', () => location.reload());
}
console.log(`paper cranes version ${CACHE_NAME}`);