-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcamera.html
More file actions
285 lines (243 loc) · 12.9 KB
/
Copy pathcamera.html
File metadata and controls
285 lines (243 loc) · 12.9 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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
<!DOCTYPE html>
<html>
<head>
<title>TIMERTHING - Camera</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/coco-ssd"></script>
<style>
video, canvas { position: absolute; top: 0; left: 0; width: 100vw; height: 100vh; object-fit: cover; }
</style>
</head>
<body class="bg-black text-white m-0 overflow-hidden font-sans">
<video id="video" autoplay playsinline muted></video>
<canvas id="canvas"></canvas>
<div id="uiOverlay" class="relative z-10 p-4 flex flex-col h-screen pointer-events-none">
<div id="controls" class="bg-black/80 backdrop-blur-md p-6 rounded-2xl border border-white/10 w-full max-w-sm pointer-events-auto shadow-2xl">
<div id="joinArea">
<h1 class="text-2xl font-black mb-4 tracking-tight">TIMER<span class="text-red-600">THING</span></h1>
<div class="flex gap-2">
<input type="text" id="roomInput" placeholder="CODE" class="w-full bg-zinc-800 border border-zinc-700 rounded-xl px-4 py-2 text-center font-mono text-lg uppercase focus:outline-none focus:border-red-600">
<button id="joinBtn" class="bg-red-600 hover:bg-red-700 text-white font-bold px-6 rounded-xl transition-all">JOIN</button>
</div>
</div>
<div id="activeControls" style="display:none;" class="space-y-4">
<div class="flex justify-between items-center">
<h2 class="font-bold text-sm uppercase tracking-widest text-zinc-400">Alignment</h2>
<div class="flex gap-1">
<button id="zoomOut" class="bg-zinc-800 hover:bg-zinc-700 text-white font-bold px-2 py-1 rounded-lg transition-all text-[10px] uppercase border border-zinc-700">-</button>
<button id="zoomIn" class="bg-zinc-800 hover:bg-zinc-700 text-white font-bold px-2 py-1 rounded-lg transition-all text-[10px] uppercase border border-zinc-700">+</button>
<button id="flipBtn" class="bg-zinc-800 hover:bg-zinc-700 text-white font-bold px-3 py-1 rounded-lg transition-all text-[10px] uppercase border border-zinc-700">Flip</button>
</div>
<span id="status" class="text-xs font-black px-2 py-1 rounded bg-green-500/20 text-green-500 border border-green-500/50">READY</span>
</div>
<input type="range" id="linePos" min="0" max="100" value="50" class="w-full h-2 bg-zinc-800 rounded-lg appearance-none cursor-pointer accent-red-600">
<p id="loadingMsg" class="text-[10px] text-red-500 uppercase font-bold text-center animate-pulse">Loading AI Model...</p>
<p class="text-[10px] text-zinc-500 uppercase font-bold text-center">Only detects humans crossing the line</p>
</div>
</div>
</div>
<script>
const socket = io();
const video = document.getElementById('video');
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d', { willReadFrequently: true });
const lineInput = document.getElementById('linePos');
const flipBtn = document.getElementById('flipBtn');
let videoTrack = null;
let detector = null;
let useFrontCamera = false;
let currentRoom = null;
let minSplitTime = 5000;
let cooldown = false;
let isDetecting = false;
let raceStarted = false;
let actualRaceStartTime = 0;
let audioCtx = null;
// Auto-fill room from URL
const urlParams = new URLSearchParams(window.location.search);
const roomFromUrl = urlParams.get('room');
const storedRoom = localStorage.getItem('cameraRoomId');
if (roomFromUrl) {
document.getElementById('roomInput').value = roomFromUrl;
} else if (storedRoom) {
document.getElementById('roomInput').value = storedRoom;
}
// Auto-join if room is present on load
if (document.getElementById('roomInput').value) {
setTimeout(() => document.getElementById('joinBtn').click(), 500);
}
document.getElementById('joinBtn').onclick = () => {
currentRoom = document.getElementById('roomInput').value.toUpperCase();
localStorage.setItem('cameraRoomId', currentRoom);
if (!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
// Pre-load audio to unlock browser policy
const unlockAudio = new Audio('start.mp3');
unlockAudio.volume = 0;
unlockAudio.play().catch(() => {});
socket.emit('join-camera', currentRoom);
};
socket.on('race-started', (startTime) => {
raceStarted = true;
actualRaceStartTime = startTime;
const statusEl = document.getElementById('status');
statusEl.innerText = "RACE ACTIVE";
statusEl.className = "text-xs font-black px-2 py-1 rounded bg-red-600 text-white border border-red-500 shadow-[0_0_15px_rgba(220,38,38,0.5)]";
document.getElementById('loadingMsg').style.display = 'none';
});
socket.on('race-stopped', () => {
raceStarted = false;
const statusEl = document.getElementById('status');
statusEl.innerText = "RACE STOPPED";
statusEl.className = "text-xs font-black px-2 py-1 rounded bg-zinc-700 text-zinc-400 border border-zinc-600";
});
socket.on('play-audio', (command) => {
if (command === 'marks') {
const msg = new SpeechSynthesisUtterance("runners on your marks");
window.speechSynthesis.speak(msg);
} else if (command === 'set') {
const msg = new SpeechSynthesisUtterance("set");
window.speechSynthesis.speak(msg);
} else if (command === 'start' || command === 'false-start') {
new Audio('start.mp3').play().catch(e => console.log("Audio play blocked"));
}
});
socket.on('min-split-time-update', (seconds) => {
minSplitTime = seconds * 1000;
});
socket.on('race-false-start', () => {
raceStarted = false;
const statusEl = document.getElementById('status');
statusEl.innerText = "FALSE START";
statusEl.className = "text-xs font-black px-2 py-1 rounded bg-amber-600 text-white border border-amber-500 shadow-[0_0_15px_rgba(217,119,6,0.5)]";
});
socket.on('race-reset', () => {
raceStarted = false;
const statusEl = document.getElementById('status');
statusEl.innerText = "READY";
statusEl.className = "text-xs font-black px-2 py-1 rounded bg-green-500/20 text-green-500 border border-green-500/50";
});
flipBtn.onclick = () => {
useFrontCamera = !useFrontCamera;
startCamera();
};
document.getElementById('zoomIn').onclick = () => updateZoom(0.2);
document.getElementById('zoomOut').onclick = () => updateZoom(-0.2);
async function updateZoom(delta) {
if (!videoTrack) return;
try {
const caps = videoTrack.getCapabilities();
if (!caps.zoom) return;
const settings = videoTrack.getSettings();
const currentZoom = settings.zoom || 1;
const newZoom = Math.min(caps.zoom.max, Math.max(caps.zoom.min, currentZoom + delta));
await videoTrack.applyConstraints({ advanced: [{ zoom: newZoom }] });
} catch (e) { console.error("Zoom not supported", e); }
}
socket.on('camera-joined', async () => {
document.getElementById('joinArea').style.display = 'none';
document.getElementById('activeControls').style.display = 'block';
// Start camera and UI loop immediately
startCamera();
requestAnimationFrame(processFrame);
// Load AI in background
detector = await cocoSsd.load();
document.getElementById('loadingMsg').style.display = 'none';
});
async function startCamera() {
try {
if (window.stream) {
window.stream.getTracks().forEach(track => track.stop());
}
const stream = await navigator.mediaDevices.getUserMedia({
video: {
facingMode: useFrontCamera ? "user" : "environment",
width: { ideal: 1280 },
height: { ideal: 720 }
}
});
window.stream = stream;
video.srcObject = stream;
videoTrack = stream.getVideoTracks()[0];
} catch (err) {
alert("Camera access denied or unavailable.");
}
}
function processFrame() {
requestAnimationFrame(processFrame);
if (video.paused || video.ended || video.videoWidth === 0) return;
if (canvas.width !== video.videoWidth || canvas.height !== video.videoHeight) {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
}
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
const x = Math.floor((lineInput.value / 100) * canvas.width);
// Draw the Digital Finish Line
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, canvas.height);
ctx.lineWidth = 4;
ctx.strokeStyle = cooldown ? '#ffffff' : '#dc2626';
ctx.stroke();
// Run AI Detection asynchronously to keep UI smooth
if (detector && !isDetecting && !cooldown) {
detectHumans(x);
}
}
async function detectHumans(lineX) {
isDetecting = true;
// detect() is heavy, it returns an array of objects found
const predictions = await detector.detect(video);
for (let prediction of predictions) {
if (prediction.class === 'person' && prediction.score > 0.6) {
const [bx, by, bw, bh] = prediction.bbox;
// Scale the bbox to canvas size
const scaleX = canvas.width / video.videoWidth;
const personLeft = bx * scaleX;
const personRight = (bx + bw) * scaleX;
// Optional: Draw box for debugging
ctx.strokeStyle = 'rgba(0, 255, 0, 0.5)';
ctx.lineWidth = 2;
ctx.strokeRect(bx * scaleX, by * (canvas.height/video.videoHeight), bw * scaleX, bh * (canvas.height/video.videoHeight));
// Check if person's body intersects the line
if (lineX >= personLeft && lineX <= personRight) {
triggerDetection();
break;
}
}
}
isDetecting = false;
}
function triggerDetection() {
if (!raceStarted) return;
// Ignore splits for the first 5 seconds to account for people crossing start line
if (Date.now() - actualRaceStartTime < minSplitTime) return;
cooldown = true;
// Small little beep
try {
const oscillator = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
oscillator.type = 'square';
oscillator.frequency.setValueAtTime(440, audioCtx.currentTime);
oscillator.connect(gainNode);
gainNode.connect(audioCtx.destination);
gainNode.gain.setValueAtTime(0.1, audioCtx.currentTime);
oscillator.start();
oscillator.stop(audioCtx.currentTime + 0.1);
} catch(e) {}
const statusEl = document.getElementById('status');
statusEl.innerText = "DETECTED!";
statusEl.className = "text-xs font-black px-2 py-1 rounded bg-white text-black border border-white";
// Capture a snapshot of the current frame
const imageData = canvas.toDataURL('image/jpeg', 0.5);
socket.emit('detection', { roomId: currentRoom, timestamp: Date.now(), image: imageData });
setTimeout(() => {
cooldown = false;
statusEl.innerText = "READY";
statusEl.className = "text-xs font-black px-2 py-1 rounded bg-green-500/20 text-green-500 border border-green-500/50";
}, 1500);
}
</script>
</body>
</html>