-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcamera.js
More file actions
296 lines (273 loc) · 11.1 KB
/
Copy pathcamera.js
File metadata and controls
296 lines (273 loc) · 11.1 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
286
287
288
289
290
291
292
293
294
295
296
/**
* @module camera
* @description
* Webcam lifecycle and the per-frame effect loop driver. Three areas of
* responsibility, kept in one module because they share the `els.video`
* element and the same lifecycle assumption ("the camera is started once
* and stays running"):
*
* 1. Webcam acquisition: requesting `getUserMedia`, attaching the stream,
* applying the mirror transform based on facing mode, and resizing the
* overlay canvas to match the video's native dimensions.
* 2. Effect render loop: throttled `requestAnimationFrame` driver that
* calls `runEffectPass()` from `engine.js` at the rate selected by the
* FPS dropdown.
* 3. One-second recording: a small MediaRecorder wrapper used by the
* workshop's "capture and share" button.
*
* No module-level mutable state lives here except `effectLoopHandle` (the
* rAF id used to cancel the loop on stop). All other state goes through
* `state.js`.
*/
import { state } from './state.js';
import { setStatus, els, clearOverlay } from './dom.js';
import { setLog } from './utils.js';
import { runEffectPass } from './engine.js';
import { RECORDING_CONFIG } from './config.js';
import { t } from './i18n.js';
/**
* Acquire the webcam stream, attach it to the `<video>` element, configure
* mirroring based on the current facing mode, and start the per-frame
* effect loop. Resolves once the video has loaded its metadata and is
* actually playing — callers can treat resolution as "the live feed is
* visible on screen".
*
* Failure modes:
* - `navigator.mediaDevices` missing (insecure context, e.g. HTTP on a LAN
* IP instead of localhost or HTTPS): logs an actionable message and
* throws.
* - `getUserMedia` rejection: propagates the underlying error.
*
* @returns {Promise<void>}
* @throws {Error} If the page is in an insecure context, or the user denies
* camera permission.
* @see scripts/main.js – called once at the end of `init()` after every
* model has been loaded.
* @see startEffectLoop – kicked off here.
*/
export async function startCamera() {
if (!navigator.mediaDevices || typeof navigator.mediaDevices.getUserMedia !== 'function') {
const httpsHint = !window.isSecureContext ? t('webcam_https_hint') : '';
setLog(t('webcam_unavailable_log', { hint: httpsHint }));
throw new Error(t('media_devices_unavailable_error'));
}
const stream = await navigator.mediaDevices.getUserMedia({
video: {
width: { ideal: 1920 },
height: { ideal: 1080 },
facingMode: state.currentFacingMode
},
audio: false
});
els.video.srcObject = stream;
// Auto-mirror when using the front camera: by convention a selfie view
// is mirrored, a rear-camera (environment) view is not.
state.isMirrored = state.currentFacingMode === 'user';
els.video.style.transform = state.isMirrored ? 'scaleX(-1)' : 'scaleX(1)';
els.overlay.style.transform = state.isMirrored ? 'scaleX(-1)' : 'scaleX(1)';
if (els.mirrorToggle) {
els.mirrorToggle.classList.toggle('mirrored', state.isMirrored);
els.mirrorToggle.textContent = state.isMirrored ? t('mirror_webcam_on_status') : t('mirror_webcam_button');
}
await new Promise(resolve => {
els.video.onloadedmetadata = () => resolve();
});
await els.video.play();
els.placeholder.style.display = 'none';
setStatus('live', t('webcam_live_status'));
setLog(t('webcam_active_log'));
resizeCanvas();
startEffectLoop();
}
/**
* Align the overlay canvas's intrinsic dimensions to the video's native
* resolution. CSS `object-fit: cover` then handles the visual crop to the
* container, which means coordinates returned by face-api / MediaPipe (in
* video-pixel space) project 1:1 onto the canvas without stretching, even
* on screen aspect ratios different from the camera's. Falls back to the
* container's bounding box before the video has known dimensions (during
* boot, before camera permissions are granted).
*
* @see startCamera – called once after the stream starts.
* @see scripts/engine.js – `drawGhostyleOverlay()` calls this before
* drawing, in case the window has been resized since the last frame.
*/
export function resizeCanvas() {
const rect = els.viewer.getBoundingClientRect();
const w = els.video.videoWidth || Math.max(1, Math.floor(rect.width));
const h = els.video.videoHeight || Math.max(1, Math.floor(rect.height));
els.overlay.width = w;
els.overlay.height = h;
}
/**
* Handle returned by the most recent `requestAnimationFrame` for the effect
* render loop. Exported so tests can inspect the start / stop transitions.
* `null` when the loop is not running.
*/
export let effectLoopHandle = null;
/**
* One iteration of the effect render loop. Runs `runEffectPass()` from
* `engine.js` if at least `currentDelay` milliseconds have passed since the
* last execution (so the FPS dropdown actually throttles the inference,
* even though `requestAnimationFrame` itself fires every 16–17 ms).
* Schedules the next iteration unconditionally — to stop the loop, call
* `stopEffectLoop()`.
*
* @param {number} [ts=0] Timestamp from rAF; defaults to 0 for the very
* first frame so the first `runEffectPass` runs immediately.
* @returns {Promise<void>}
* @see runEffectPass – the actual face-api inference call.
* @see startEffectLoop – schedules the first iteration.
*/
export async function effectLoop(ts = 0) {
const currentDelay = parseInt(els.fpsSelect.value, 10) || 120;
if (ts - state.lastEffectRun > currentDelay) {
state.lastEffectRun = ts;
let result = await runEffectPass();
if (result) {
clearOverlay();
}
}
effectLoopHandle = requestAnimationFrame(effectLoop);
}
/**
* Start (or restart) the effect render loop. Cancels any previously
* scheduled rAF first so successive calls don't stack up parallel loops —
* useful when the camera is restarted after a facingMode switch.
*
* @see effectLoop – the function actually scheduled.
* @see startCamera – calls this once the stream is live.
*/
export function startEffectLoop() {
if (effectLoopHandle) cancelAnimationFrame(effectLoopHandle);
effectLoopHandle = requestAnimationFrame(effectLoop);
}
/**
* Stop the effect render loop and reset the inference-in-flight guard.
* Currently called only from unit tests; no production code path teardown
* the loop because the page lifecycle does it implicitly. Kept for
* completeness and as a test-only handle.
*
* @see startEffectLoop – the symmetric counterpart.
* @see tests/unit/camera.test.js – asserts the cancel + null-out behaviour.
*/
export function stopEffectLoop() {
if (effectLoopHandle) cancelAnimationFrame(effectLoopHandle);
effectLoopHandle = null;
state.effectInferenceInFlight = false;
}
/**
* Capture a short video clip from the live webcam stream and either trigger
* a browser download or POST it to the configured upload endpoint
* (`RECORDING_CONFIG.mode`). Honours `state.isRecording` and
* `state.isSystemBusy` to refuse overlapping captures, and updates the
* record button visual state for the duration of the recording.
*
* MIME-type selection is best-effort: prefers H.264 MP4 (broadest player
* support), falls back to MP4 generic, then VP9 WebM, then VP8 WebM. If
* none of these are supported, `MediaRecorder` will throw and the error is
* surfaced into the log.
*
* @returns {Promise<void>}
* @see RECORDING_CONFIG – controls mode, endpoint, and duration.
* @see scripts/main.js – wires the `recordBtn` click handler to this.
*/
export async function recordOneSecond() {
if (state.isRecording || state.isSystemBusy) return;
const stream = els.video.srcObject;
if (!stream) {
setLog(t('webcam_stream_inactive_log'));
return;
}
// 1. Mark recording state
state.isRecording = true;
if (els.recordBtn) {
els.recordBtn.classList.add('recording');
els.recordBtn.disabled = true;
}
setLog(t('recording_started_log'));
// 2. Select format
let mimeType = 'video/webm';
let extension = 'webm';
if (MediaRecorder.isTypeSupported('video/mp4;codecs=h264')) {
mimeType = 'video/mp4;codecs=h264';
extension = 'mp4';
} else if (MediaRecorder.isTypeSupported('video/mp4')) {
mimeType = 'video/mp4';
extension = 'mp4';
} else if (MediaRecorder.isTypeSupported('video/webm;codecs=vp9')) {
mimeType = 'video/webm;codecs=vp9';
extension = 'webm';
} else if (MediaRecorder.isTypeSupported('video/webm;codecs=vp8')) {
mimeType = 'video/webm;codecs=vp8';
extension = 'webm';
}
try {
const recorder = new MediaRecorder(stream, { mimeType });
const chunks = [];
recorder.ondataavailable = (e) => {
if (e.data && e.data.size > 0) {
chunks.push(e.data);
}
};
recorder.onstop = async () => {
const blob = new Blob(chunks, { type: mimeType });
const isUploadMode = RECORDING_CONFIG.mode === 'upload';
if (isUploadMode) {
setLog(t('video_uploading_log'));
try {
const formData = new FormData();
const filename = `ghostati-recording-${Date.now()}.${extension}`;
formData.append('video', blob, filename);
const response = await fetch(RECORDING_CONFIG.uploadEndpoint, {
method: 'POST',
body: formData
});
if (response.ok) {
setLog(t('video_upload_done_log', { status: response.status, filename }));
} else {
setLog(t('video_upload_http_error_log', { status: response.status, statusText: response.statusText }));
}
} catch (err) {
setLog(t('video_upload_network_error_log', { message: err.message }));
}
} else {
// Direct download mode
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = `ghostati-recording-${Date.now()}.${extension}`;
document.body.appendChild(a);
a.click();
setTimeout(() => {
document.body.removeChild(a);
URL.revokeObjectURL(url);
}, 100);
setLog(t('recording_downloaded_log', { filename: a.download }));
}
// Reset visual styles and state
state.isRecording = false;
if (els.recordBtn) {
els.recordBtn.classList.remove('recording');
// Re-enable if system not busy
els.recordBtn.disabled = state.isSystemBusy;
}
};
// Start recording
recorder.start();
// Stop recording after RECORDING_CONFIG.durationMs
setTimeout(() => {
if (recorder.state !== 'inactive') {
recorder.stop();
}
}, RECORDING_CONFIG.durationMs);
} catch (err) {
setLog(t('media_recorder_error_log', { message: err.message }));
state.isRecording = false;
if (els.recordBtn) {
els.recordBtn.classList.remove('recording');
els.recordBtn.disabled = state.isSystemBusy;
}
}
}