-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrenderer.js
781 lines (676 loc) · 23.1 KB
/
renderer.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
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
const { ipcRenderer } = require('electron');
let detector;
let video = null;
let lastHandNearHead = false;
let handNearHeadCount = 0;
const FRAMES_THRESHOLD = 30; // Reduced from 100 to 30 frames
let isReconnecting = false;
let selectedDeviceId = null;
let isWebGLInitialized = false;
const MAX_AUTO_RECONNECT_ATTEMPTS = 3;
let autoReconnectAttempts = 0;
let autoReconnectTimer = null;
const MAX_PLAYBACK_RETRY_ATTEMPTS = 3;
const PLAYBACK_RETRY_DELAY = 1000; // 1 second
let animationFrameId = null;
async function initializeWebGL() {
if (!isWebGLInitialized) {
await tf.ready();
console.log('TensorFlow.js version:', tf.version);
if (tf.getBackend() !== 'webgl') {
console.log('Setting backend to WebGL');
await tf.setBackend('webgl');
}
isWebGLInitialized = true;
console.log('Backend:', tf.getBackend());
}
}
// Function to populate camera select dropdown
async function populateCameraSelect() {
const select = document.getElementById('cameraSelect');
select.innerHTML = '<option value="">Select camera...</option>';
try {
const devices = await navigator.mediaDevices.enumerateDevices();
// Create a map to store unique devices by their label
const uniqueDevices = new Map();
// Filter video devices and handle duplicates
devices
.filter((device) => device.kind === 'videoinput')
.forEach((device) => {
const label = device.label || `Camera ${uniqueDevices.size + 1}`;
// Only add if we haven't seen this label before
if (
!Array.from(uniqueDevices.values()).some((d) => d.label === label)
) {
uniqueDevices.set(device.deviceId, {
deviceId: device.deviceId,
label: label,
});
}
});
console.log('Unique devices:', uniqueDevices);
console.log('Selected device ID:', selectedDeviceId);
// Add unique devices to select
uniqueDevices.forEach((device) => {
const option = document.createElement('option');
option.value = device.deviceId;
option.text = device.label;
select.appendChild(option);
});
// If we have a previously selected device, check if it's available
if (selectedDeviceId) {
const exists = uniqueDevices.has(selectedDeviceId);
if (exists) {
select.value = selectedDeviceId;
// Try to auto-reconnect if this is the exact device we were using before
if (autoReconnectAttempts < MAX_AUTO_RECONNECT_ATTEMPTS) {
console.log(
`Attempting auto-reconnect (${
autoReconnectAttempts + 1
}/${MAX_AUTO_RECONNECT_ATTEMPTS})...`,
);
// Clear any existing timer
if (autoReconnectTimer) {
clearTimeout(autoReconnectTimer);
}
// Increment attempt counter before trying
autoReconnectAttempts++;
// Attempt reconnection immediately
try {
await attemptReconnection();
} catch (error) {
console.error('Auto-reconnect attempt failed:', error);
if (autoReconnectAttempts < MAX_AUTO_RECONNECT_ATTEMPTS) {
// Schedule next attempt
autoReconnectTimer = setTimeout(
() => populateCameraSelect(),
2000,
);
} else {
console.log('Max auto-reconnect attempts reached');
autoReconnectAttempts = 0;
const statusDiv = document.getElementById('status');
statusDiv.textContent = 'Please select a camera to continue';
}
}
}
} else {
select.value = '';
// Stop any existing stream
if (video && video.srcObject) {
video.srcObject.getTracks().forEach((track) => track.stop());
video.srcObject = null;
}
}
}
} catch (error) {
console.error('Error enumerating devices:', error);
const statusDiv = document.getElementById('status');
statusDiv.textContent = 'Error: Could not list available cameras.';
}
}
// Setup device change monitoring
function setupDeviceMonitoring() {
// Update camera list when devices change
navigator.mediaDevices.addEventListener('devicechange', async () => {
console.log('Media devices changed, checking devices...');
try {
// Get current devices
const devices = await navigator.mediaDevices.enumerateDevices();
const videoDevices = devices.filter(
(device) => device.kind === 'videoinput',
);
// Check if our selected device is available
if (
selectedDeviceId &&
videoDevices.some((device) => device.deviceId === selectedDeviceId)
) {
console.log(
'Previously selected device is available, attempting reconnection...',
);
// Reset reconnection attempts since this is a new device change event
autoReconnectAttempts = 0;
await populateCameraSelect();
} else {
console.log('Selected device not available, updating device list...');
// Stop any existing stream first
if (video && video.srcObject) {
video.srcObject.getTracks().forEach((track) => track.stop());
video.srcObject = null;
}
await populateCameraSelect();
}
} catch (error) {
console.error('Error handling device change:', error);
await populateCameraSelect();
}
});
// Handle camera selection change
document
.getElementById('cameraSelect')
.addEventListener('change', async (event) => {
// Clear auto-reconnect state on manual selection
autoReconnectAttempts = 0;
if (autoReconnectTimer) {
clearTimeout(autoReconnectTimer);
autoReconnectTimer = null;
}
// Stop any existing stream first
if (video && video.srcObject) {
video.srcObject.getTracks().forEach((track) => track.stop());
video.srcObject = null;
}
selectedDeviceId = event.target.value;
if (selectedDeviceId) {
console.log(
'Camera selection changed, connecting to selected camera...',
);
try {
await attemptReconnection();
} catch (error) {
console.error('Error during connection:', error);
const statusDiv = document.getElementById('status');
statusDiv.textContent =
'Error connecting to camera. Please try again.';
}
} else {
const statusDiv = document.getElementById('status');
statusDiv.textContent = 'Please select a camera to begin';
}
});
}
async function setupCamera() {
cleanup();
// Initialize video element if it doesn't exist
if (!video) {
video = document.getElementById('webcam');
}
try {
// Ensure we have a selected camera
if (!selectedDeviceId) {
throw new Error('Please select a camera');
}
async function attemptDeviceConnection(retryCount = 0) {
try {
// Stop any existing streams
if (video.srcObject) {
video.srcObject.getTracks().forEach((track) => track.stop());
video.srcObject = null;
}
console.log(
`Attempting device connection (attempt ${
retryCount + 1
}/${MAX_PLAYBACK_RETRY_ATTEMPTS})...`,
);
const stream = await navigator.mediaDevices.getUserMedia({
video: {
deviceId: { exact: selectedDeviceId },
width: 640,
height: 480,
},
});
video.srcObject = stream;
// Wait for video to be ready
await new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
reject(new Error('Timeout waiting for video metadata'));
}, 5000);
video.onloadedmetadata = async () => {
clearTimeout(timeoutId);
try {
await video.play();
console.log('Video playback started successfully');
resolve();
} catch (error) {
reject(error);
}
};
});
console.log('Camera connection and playback successful');
return stream;
} catch (error) {
console.error(
`Device connection attempt ${retryCount + 1} failed:`,
error,
);
if (retryCount < MAX_PLAYBACK_RETRY_ATTEMPTS - 1) {
console.log(
`Retrying device connection in ${PLAYBACK_RETRY_DELAY}ms...`,
);
await new Promise((resolve) =>
setTimeout(resolve, PLAYBACK_RETRY_DELAY),
);
return attemptDeviceConnection(retryCount + 1);
}
throw new Error(
`Failed to connect to device after ${MAX_PLAYBACK_RETRY_ATTEMPTS} attempts`,
);
}
}
const stream = await attemptDeviceConnection();
// Reset reconnection state on successful connection
isReconnecting = false;
// Remove existing canvas if it exists
const existingCanvas = document.getElementById('overlay');
if (existingCanvas) {
existingCanvas.remove();
}
// Create canvas overlay for visualization
const canvas = document.createElement('canvas');
canvas.id = 'overlay';
canvas.width = 640;
canvas.height = 480;
canvas.style.position = 'absolute';
canvas.style.top = '0';
canvas.style.left = '0';
document.getElementById('videoContainer').appendChild(canvas);
// Add event listeners for track ended and error events
stream.getVideoTracks()[0].onended = handleCameraDisconnection;
video.onerror = handleCameraError;
return video;
} catch (error) {
console.error('Error accessing camera:', error);
handleCameraError(error);
throw error;
}
}
function handleCameraDisconnection() {
console.log('Camera disconnected');
cleanup();
const statusDiv = document.getElementById('status');
statusDiv.textContent =
'Camera disconnected. Waiting for device to become available...';
statusDiv.className = '';
// Keep the selected device ID for auto-reconnection
// But reset the auto-reconnect attempts
autoReconnectAttempts = 0;
// Update camera list
populateCameraSelect();
}
function handleCameraError(error) {
console.error('Camera error:', error);
cleanup();
const statusDiv = document.getElementById('status');
statusDiv.textContent =
error.message === 'Please select a camera'
? error.message
: 'Camera error. Please select a camera to continue.';
statusDiv.className = '';
// Clear the selected device
const select = document.getElementById('cameraSelect');
select.value = '';
// Update camera list
populateCameraSelect();
}
async function attemptReconnection() {
if (isReconnecting) return;
isReconnecting = true;
const statusDiv = document.getElementById('status');
statusDiv.textContent = 'Attempting to connect to selected camera...';
try {
// Initialize WebGL first
await initializeWebGL();
// Setup camera
await setupCamera();
// Initialize detector
await initializeDetector();
statusDiv.textContent = 'Camera connected successfully';
statusDiv.className = 'detection-active';
console.log('Camera connected successfully');
// Start pose detection after successful connection
detectPose();
} catch (error) {
console.error('Connection attempt failed:', error);
isReconnecting = false;
if (error.message === 'Please select a camera') {
statusDiv.textContent = error.message;
} else {
statusDiv.textContent =
'Failed to connect to camera. Please try another camera.';
}
}
}
async function initializeDetector() {
try {
// Initialize TensorFlow.js backend
await tf.ready();
console.log('TensorFlow.js version:', tf.version);
console.log('Backend:', tf.getBackend());
// Force WebGL backend initialization
if (tf.getBackend() !== 'webgl') {
console.log('Setting backend to WebGL');
await tf.setBackend('webgl');
}
// Wait for video to be ready
while (!video.videoWidth || !video.videoHeight) {
console.log('Waiting for video dimensions...');
await new Promise((resolve) => setTimeout(resolve, 100));
}
console.log('Video dimensions:', video.videoWidth, 'x', video.videoHeight);
// Initialize MoveNet
console.log('Initializing MoveNet...');
const modelConfig = {
modelType: poseDetection.movenet.modelType.SINGLEPOSE_LIGHTNING,
enableSmoothing: true,
};
console.log('Creating detector with config:', modelConfig);
detector = await poseDetection.createDetector(
poseDetection.SupportedModels.MoveNet,
modelConfig,
);
console.log('Pose detector initialized successfully');
} catch (error) {
console.error('Error initializing pose detector:', error);
console.error('Error stack:', error.stack);
throw error;
}
}
function drawKeypoints(keypoints) {
const canvas = document.getElementById('overlay');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Mirror coordinates for visualization
function mirrorX(x) {
return canvas.width - x;
}
// Draw all keypoints
keypoints.forEach((keypoint) => {
if (keypoint.score && keypoint.score > 0.2) {
const x = mirrorX(keypoint.x); // Mirror the x coordinate
ctx.beginPath();
ctx.arc(x, keypoint.y, 5, 0, 2 * Math.PI);
ctx.fillStyle = keypoint.name.includes('wrist')
? 'red'
: keypoint.name === 'nose'
? 'green'
: 'blue';
ctx.fill();
ctx.fillStyle = 'white';
ctx.fillText(keypoint.name, x + 5, keypoint.y - 5);
}
});
}
function isHandNearHead(keypoints) {
const canvas = document.getElementById('overlay');
function mirrorX(x) {
return canvas.width - x;
}
// Find relevant keypoints with lower confidence threshold
const nose = keypoints.find((kp) => kp.name === 'nose' && kp.score > 0.2);
const leftEye = keypoints.find(
(kp) => kp.name === 'left_eye' && kp.score > 0.2,
);
const rightEye = keypoints.find(
(kp) => kp.name === 'right_eye' && kp.score > 0.2,
);
const leftWrist = keypoints.find(
(kp) => kp.name === 'left_wrist' && kp.score > 0.2,
);
const rightWrist = keypoints.find(
(kp) => kp.name === 'right_wrist' && kp.score > 0.2,
);
// Only require nose and at least one eye for head position
if (!nose || (!leftEye && !rightEye) || (!leftWrist && !rightWrist)) {
return false;
}
// Calculate eye center and level using available eye(s) with mirrored coordinates
const eyeCenterX =
leftEye && rightEye
? (mirrorX(leftEye.x) + mirrorX(rightEye.x)) / 2
: leftEye
? mirrorX(leftEye.x)
: mirrorX(rightEye.x);
const eyeCenterY =
leftEye && rightEye
? (leftEye.y + rightEye.y) / 2
: leftEye
? leftEye.y
: rightEye.y;
const eyeDistance =
leftEye && rightEye ? Math.abs(leftEye.x - rightEye.x) : 100;
// Define larger detection area
const areaTop = eyeCenterY - eyeDistance * 3;
const areaBottom = eyeCenterY + eyeDistance;
const areaLeft = eyeCenterX - eyeDistance * 3;
const areaRight = eyeCenterX + eyeDistance * 3;
function isInTargetArea(wrist) {
if (!wrist) return false;
const mirroredX = mirrorX(wrist.x);
// Check if hand is in the target area
const isInArea =
mirroredX >= areaLeft &&
mirroredX <= areaRight &&
wrist.y >= areaTop &&
wrist.y <= areaBottom;
// Calculate distance to eye center
const distanceToEyes = calculateDistance(
{ x: eyeCenterX, y: eyeCenterY },
{ x: mirroredX, y: wrist.y },
);
// More lenient distance threshold
const isCloseEnough = distanceToEyes < eyeDistance * 4;
return isInArea && isCloseEnough;
}
const leftHandInArea = isInTargetArea(leftWrist);
const rightHandInArea = isInTargetArea(rightWrist);
// Draw visualization
const ctx = canvas.getContext('2d');
// Draw detection area
ctx.beginPath();
ctx.rect(areaLeft, areaTop, areaRight - areaLeft, areaBottom - areaTop);
ctx.strokeStyle =
(leftHandInArea || rightHandInArea) && !(leftHandInArea && rightHandInArea)
? 'rgba(255, 0, 0, 0.3)'
: 'rgba(255, 255, 255, 0.3)';
ctx.stroke();
// Draw eye center point
ctx.beginPath();
ctx.arc(eyeCenterX, eyeCenterY, 3, 0, 2 * Math.PI);
ctx.fillStyle = 'yellow';
ctx.fill();
// Draw distance circles
ctx.beginPath();
ctx.arc(eyeCenterX, eyeCenterY, eyeDistance * 4, 0, 2 * Math.PI);
ctx.strokeStyle = 'rgba(255, 255, 0, 0.2)';
ctx.stroke();
// Draw lines to hands with distances
if (leftWrist) {
const mirroredLeftX = mirrorX(leftWrist.x);
ctx.beginPath();
ctx.moveTo(eyeCenterX, eyeCenterY);
ctx.lineTo(mirroredLeftX, leftWrist.y);
ctx.strokeStyle = leftHandInArea && !rightHandInArea ? 'red' : 'green';
ctx.lineWidth = 2;
ctx.stroke();
const distance = calculateDistance(
{ x: eyeCenterX, y: eyeCenterY },
{ x: mirroredLeftX, y: leftWrist.y },
);
ctx.fillStyle = 'white';
ctx.fillText(
`${Math.round(distance)}px`,
(eyeCenterX + mirroredLeftX) / 2,
(eyeCenterY + leftWrist.y) / 2,
);
}
if (rightWrist) {
const mirroredRightX = mirrorX(rightWrist.x);
ctx.beginPath();
ctx.moveTo(eyeCenterX, eyeCenterY);
ctx.lineTo(mirroredRightX, rightWrist.y);
ctx.strokeStyle = rightHandInArea && !leftHandInArea ? 'red' : 'green';
ctx.lineWidth = 2;
ctx.stroke();
const distance = calculateDistance(
{ x: eyeCenterX, y: eyeCenterY },
{ x: mirroredRightX, y: rightWrist.y },
);
ctx.fillStyle = 'white';
ctx.fillText(
`${Math.round(distance)}px`,
(eyeCenterX + mirroredRightX) / 2,
(eyeCenterY + rightWrist.y) / 2,
);
}
// Only trigger if exactly one hand is in the area (not both)
return (
(leftHandInArea || rightHandInArea) && !(leftHandInArea && rightHandInArea)
);
}
function calculateDistance(point1, point2) {
return Math.sqrt(
Math.pow(point1.x - point2.x, 2) + Math.pow(point1.y - point2.y, 2),
);
}
function showNotification() {
try {
// Send through Electron IPC first
console.log('Sending notification through IPC...');
ipcRenderer.send('show-notification', {
title: 'Hair Pulling Alert',
body: 'You might be pulling your hair. Try to be mindful of this behavior.',
});
// Try browser notification as backup
if ('Notification' in window && Notification.permission === 'granted') {
new Notification('Hair Pulling Alert', {
body: 'You might be pulling your hair. Try to be mindful of this behavior.',
requireInteraction: true,
silent: false,
tag: 'hair-pulling', // Prevent duplicate notifications
});
}
} catch (error) {
console.error('Error showing notification:', error);
}
}
function updateDebugInfo(handNearHead, count, poses) {
const debugDiv = document.getElementById('debug');
if (!debugDiv) {
const div = document.createElement('div');
div.id = 'debug';
div.style.position = 'fixed';
div.style.bottom = '20px';
div.style.left = '20px';
div.style.backgroundColor = 'rgba(0,0,0,0.7)';
div.style.color = 'white';
div.style.padding = '10px';
div.style.borderRadius = '5px';
document.body.appendChild(div);
}
const pose = poses[0];
const nose = pose.keypoints.find((kp) => kp.name === 'nose');
const leftWrist = pose.keypoints.find((kp) => kp.name === 'left_wrist');
const rightWrist = pose.keypoints.find((kp) => kp.name === 'right_wrist');
document.getElementById('debug').innerHTML = `
Hand near head: ${handNearHead}<br>
Frame count: ${count}/${FRAMES_THRESHOLD}<br>
Pose score: ${pose.score?.toFixed(2)}<br>
Nose score: ${nose?.score?.toFixed(2)}<br>
Left wrist score: ${leftWrist?.score?.toFixed(2)}<br>
Right wrist score: ${rightWrist?.score?.toFixed(2)}
`;
}
async function detectPose() {
if (!detector || !video || video.paused || video.ended) {
animationFrameId = requestAnimationFrame(detectPose);
return;
}
try {
// Get video frame dimensions
const videoWidth = video.videoWidth;
const videoHeight = video.videoHeight;
if (!videoWidth || !videoHeight) {
console.log('Video dimensions not ready');
animationFrameId = requestAnimationFrame(detectPose);
return;
}
const poses = await detector.estimatePoses(video);
const statusDiv = document.getElementById('status');
if (poses.length > 0) {
statusDiv.textContent = 'Monitoring active';
statusDiv.className = 'detection-active';
// Draw all detected keypoints
drawKeypoints(poses[0].keypoints);
const handNearHead = isHandNearHead(poses[0].keypoints);
updateDebugInfo(handNearHead, handNearHeadCount, poses);
if (handNearHead) {
handNearHeadCount++;
console.log(
`Hand near head count: ${handNearHeadCount}/${FRAMES_THRESHOLD}`,
);
if (handNearHeadCount >= FRAMES_THRESHOLD && !lastHandNearHead) {
statusDiv.textContent = 'Warning: Hand near head detected!';
statusDiv.className = 'detection-warning';
showNotification();
lastHandNearHead = true;
}
} else {
handNearHeadCount = 0;
lastHandNearHead = false;
}
} else {
console.log('No poses detected');
statusDiv.textContent = 'No pose detected';
}
} catch (error) {
console.error('Error in pose detection:', error);
cleanup();
return;
}
animationFrameId = requestAnimationFrame(detectPose);
}
async function app() {
try {
console.log('Setting up device monitoring...');
await populateCameraSelect(); // Populate camera list initially
setupDeviceMonitoring();
// Don't automatically connect - wait for user to select a camera
const statusDiv = document.getElementById('status');
statusDiv.textContent = 'Please select a camera to begin';
// Request notification permission
if ('Notification' in window) {
const permission = await Notification.requestPermission();
console.log('Notification permission:', permission);
}
} catch (error) {
console.error('Error in app initialization:', error);
document.getElementById('status').textContent = 'Error: ' + error.message;
}
}
// Add IPC response listener
ipcRenderer.on('notification-sent', (event, success) => {
console.log(
'Notification status:',
success ? 'sent successfully' : 'failed to send',
);
});
// Listen for notification support response
ipcRenderer.on('notification-support', (event, isSupported) => {
console.log('System notifications supported:', isSupported);
});
function cleanup() {
// Cancel animation frame
if (animationFrameId) {
cancelAnimationFrame(animationFrameId);
animationFrameId = null;
}
// Stop video stream
if (video && video.srcObject) {
video.srcObject.getTracks().forEach((track) => track.stop());
video.srcObject = null;
}
// Clear canvas
const canvas = document.getElementById('overlay');
if (canvas) {
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
canvas.remove();
}
// Reset state variables
handNearHeadCount = 0;
lastHandNearHead = false;
isReconnecting = false;
}
app();
// Add window unload handler at the end of the file
window.addEventListener('unload', cleanup);