Webcam motion detection in JavaScript, plus sound levels
SafeOS’s Motion and sound page compares camera frames 5 times a second and reads the microphone’s level 10 times a second, in plain JavaScript with no model. This post goes through that code: pixels read from a canvas, frame differencing on a grid of samples, the box drawn round what moved, a second check against an older frame, a level from the Web Audio API, and the rules that turn a reading into an alert.
The same loops in brief, beside the rest of SafeOS, are in the motion and sound section of how SafeOS watches a room in your browser. The earlier post on how SafeOS Guardian checks for motion before it runs a model follows a frame from this check to the detection model, and object detection in the browser takes that model apart. Nothing in this post loads one. The same checks run when you use an old phone as a pet camera while you are out or an old phone as a nap monitor.
Reading frames: the camera, a canvas and getImageData every 200 ms
The page asks the browser for a camera of 1280 by 720, as an ideal, and for the back camera when the person has chosen none (camera-constraints.ts). Once the video plays, one timer in the camera feed does the rest:
const interval = setInterval(() => {
if (!videoRef.current || videoPausedRef.current) return;
// Draw current frame
canvas.width = videoRef.current.videoWidth || 640;
canvas.height = videoRef.current.videoHeight || 480;
ctx.drawImage(videoRef.current, 0, 0);
// Get current frame data
const currentFrame = ctx.getImageData(0, 0, canvas.width, canvas.height);CameraFeed.tsx, lines 456–465 at commit 017b33bThe canvas takes the video’s own size, so at the size the page asks for one frame is 921,600 pixels. getImageData returns them as one flat array, four bytes a pixel in the order red, green, blue and alpha (MDN), 3,686,400 bytes a frame. The context is made with willReadFrequently: true (CameraFeed.tsx), which MDN says forces a software 2D canvas and “can save memory when calling getImageData() frequently” (MDN, Mozilla Contributors, CC BY-SA 2.5).
At the end of each tick the frame is kept for the next one (CameraFeed.tsx), so every comparison below is between two frames 200 ms apart. A paused video skips the tick. People and Wildlife shrink their frames to 320 by 240 before they compare anything; this page keeps every pixel the camera gives.
Frame differencing: one sample in 16, 30 levels, a share against the line
The motion check is one function of a few lines:
// Iterate over pixels with downsampling
for (let y = 0; y < height; y += DOWNSAMPLE) {
for (let x = 0; x < width; x += DOWNSAMPLE) {
const i = (y * width + x) * 4;
// Calculate grayscale for comparison
const prevGray = (prev[i] + prev[i + 1] + prev[i + 2]) / 3;
const currGray = (curr[i] + curr[i + 1] + curr[i + 2]) / 3;
// Check if pixel changed significantly
if (Math.abs(prevGray - currGray) > PIXEL_THRESHOLD) {
changedPixels++;
}
totalPixels++;
}
}
return totalPixels > 0 ? changedPixels / totalPixels : 0;motion-detection.ts, lines 99–116 at commit 017b33bIt steps 4 pixels along each row and 4 rows down, so it reads one pixel in 16. Each sample’s grey is the plain mean of its red, green and blue, and a sample counts as changed when the two greys differ by more than 30 of 255 levels (motion-detection.ts). The result is the share of samples that changed, from 0 to 1, which the camera feed rounds to a whole number from 0 to 100 (CameraFeed.tsx). A share does not grow with the camera’s resolution, so one line serves every camera.
The line is 100 minus the motion sensitivity the person sets (page.tsx). The default setting, Maximum Alert, has a motion sensitivity of 80, so its line is 20 per cent of the samples (settings-store.ts; settings-store.ts). A higher sensitivity lowers the line and gives more alerts.
By default the check reads one zone, Full Screen (settings-store.ts). Where the person draws zones, each zone gets its own share, a zone can carry its own sensitivity, and the zone that stands highest over its own line is the one an alert reads (CameraFeed.tsx; page.tsx).
- Grey is (R + G + B) / 3, read at one pixel in 4 each way.
- A sample counts when the two greys differ by more than 30.
- The share of samples that changed is compared with the line: 20 per cent by default.
- Over the line, a box is drawn round the cells that changed.
Where it moved: the 16 by 12 grid and the box
The share says how much of the picture changed, not where. That is worked out once, when an alert is raised, not on every check: the page compares the check’s two frames again, cell by cell over a 16 by 12 grid, with the same grey and the same step (motion-detection.ts). A cell is kept when its own share of changed samples reaches the line that raised the alert, with a ceiling the code sets:
// A cell counts at the line that raised the alert, up to the detector's own 10 per cent, so a
// change spread thin over the picture keeps its box.
frames?.previous
? boxFromCells(detectRegionalMotion(frames.previous, frame, Math.max(0.001, Math.min(0.1, best.threshold / 100))), frame.width, frame.height, zone)
: null,page.tsx, lines 1253–1257 at commit 017b33bThe box goes round the cells kept, inside the zone that set the alert off where zones are drawn, and it is drawn on the picture the alert keeps (page.tsx).
Picture change: luminance, the frame two back, severity from the ratio
Picture change is a second check on the same canvas in the same tick, run when the setting turns it on; Maximum Alert does (settings-store.ts; CameraFeed.tsx). It reads every pixel, or every second one under a sleep setting (page.tsx), and weighs the three colours:
// Calculate weighted difference
const rDiff = Math.abs(current.data[i] - previous.data[i]);
const gDiff = Math.abs(current.data[i + 1] - previous.data[i + 1]);
const bDiff = Math.abs(current.data[i + 2] - previous.data[i + 2]);
const weightedDiff = (
rDiff * colorWeight.r +
gDiff * colorWeight.g +
bDiff * colorWeight.b
);
if (weightedDiff > pixelThreshold) {pixel-detection.ts, lines 415–426 at commit 017b33bThe weights are the ones the code calls luminance weights, 0.299 for red, 0.587 for green and 0.114 for blue (pixel-detection.ts), applied to each colour’s own change. A pixel counts when that weighted change is over (100 minus the sensitivity) times 2.55 levels (pixel-detection.ts). The page passes 100 minus the setting’s picture line as the sensitivity (page.tsx), so under Maximum Alert a pixel counts at more than 51 of 255. The check says yes when 1 per cent of the pixels it read have changed, and an 8 by 8 grid marks the cells where the change is (pixel-detection.ts).
The order of two lines decides which frame it compares with:
analyzeImageData(currentFrame: ImageData): PixelDetectionResult {
if (!this.isEnabled) {
return this.createEmptyResult();
}
const previousFrame = this.frameBuffer.getPrevious();
this.frameBuffer.push(this.cloneImageData(currentFrame));
if (!previousFrame) {
return this.createEmptyResult();
}pixel-detection.ts, lines 272–282 at commit 017b33bThe buffer holds the last three frames, and getPrevious() returns the one before the newest stored (pixel-detection.ts). It is read before the new frame goes in, so the new frame is compared with the frame from two ticks back, 400 ms earlier, where the motion check compares with the frame 200 ms earlier. A slow change has twice as long to pass this check’s line.
A picture-change alert’s severity is how many times over its line the reading is: the share of changed pixels over the 1 per cent line, the same ratio the page’s meter shows (watch-meters.ts). So 2, 5 and 10 times the line give medium, high and critical:
const severity: AlertSeverity | null = !triggered
? null
: ratioNow >= 10 ? 'critical' : ratioNow >= 5 ? 'high' : ratioNow >= 2 ? 'medium' : 'low';
const outcome = readDetector(pixelEventRef.current, now, severity, {
severitySeconds: severity ? getCooldownForSeverity(severity) : undefined,
cooldownPeriodSeconds: timingSettings.cooldownPeriod,
// Require sustained pixel change (especially for very low thresholds)
sustainedMs: Math.max(150, timingSettings.minimumMotionDuration / 2),
});page.tsx, lines 1390–1398 at commit 017b33bSound: AnalyserNode, 128 bins, and why the number is not decibels
When sound is on and the camera came with a live microphone track, the camera feed opens an AudioContext, makes a source from the camera’s stream and connects it to an AnalyserNode whose fftSize is 256 (CameraFeed.tsx). The Web Audio specification defines the analyser’s frequencyBinCount as “Half the FFT size” (Web Audio API, W3C), so each reading has 128 bins. Every 100 ms the page reads them (CameraFeed.tsx) and turns them into one level:
export function getAudioLevel(analyser: AnalyserNode, range: PitchRange | null = null): number {
const bufferLength = analyser.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
analyser.getByteFrequencyData(dataArray);
if (!range) {
// Root mean square of every bin: the level saved sensitivities were set against.
let sum = 0;
for (let i = 0; i < bufferLength; i++) {
sum += dataArray[i] * dataArray[i];
}
return Math.sqrt(sum / bufferLength) / 255;
}audio-levels.ts, lines 172–184 at commit 017b33bThe level is the root mean square of the bins’ byte values, over 255. The camera feed rounds it to a whole number from 0 to 100, and the sound line is 100 minus the sound sensitivity: 20 under Maximum Alert (page.tsx).
What those bytes hold explains why the result is not a decibel reading. The specification converts each bin’s smoothed magnitude to decibels, and for getByteFrequencyData() the value “is clipped to lie between minDecibels and maxDecibels and then scaled to fit in an unsigned byte such that minDecibels is represented by the value 0 and maxDecibels is represented by the value 255” (Web Audio API, W3C). The defaults are −100 dB and −30 dB, where 0 dB is the loudest possible sound (MDN, MDN), and the bins are averaged over time with a smoothing constant of 0.8 (MDN). SafeOS sets none of the three, so it reads the browser’s defaults. The level is a place on that scale. It is not a measure of sound pressure, and a different microphone, or the same one at another input level, reads the same room differently.
A pitch range the person chooses on the Detection settings changes two things: the analyser grows to 2048 points, and only the bins inside the range count (audio-levels.ts). One bin is the sample rate over the analyser’s size wide, so at 48,000 Hz a bin is about 23 Hz at 2048 points and 188 Hz at 256.
The page keeps no recording of the microphone: it reads a level. A server the person connects receives that level as a number beside a frame (page.tsx). Before the first watch on a device, the notice about alert pictures says: “Ask before you watch or listen to another adult or the people you live with. Laws on recording sound differ by place” (PicturesNotice.tsx, words.ts).
From readings to an alert: windows, cooldowns, severity, five levels
Each kind of reading goes to one function with a severity, or with none when it is under the line. These are the lines that decide whether it raises an alert:
// Require sustained readings to avoid single-frame spikes and lighting flicker; with no
// sustained window asked for (a sighting's check), the first reading over the line starts it.
if (!event.active && timing.sustainedMs > 0) {
if (event.aboveSince === null) {
event.aboveSince = now;
return { kind: 'quiet' };
}
if (now - event.aboveSince < timing.sustainedMs) return { kind: 'quiet' };
}
const severitySeconds = seconds(timing.severitySeconds, FALLBACK_SEVERITY_SECONDS);
const period = seconds(timing.cooldownPeriodSeconds, 0) || FALLBACK_COOLDOWN_PERIOD_SECONDS;
// A rise above the event's last alert is timed as a new event, so a rise
// to critical (no cooldown by default) alerts at once.
const rose = event.active && event.lastSeverity !== null && RANK[severity] > RANK[event.lastSeverity];
const waitSeconds = event.active && !rose ? Math.max(severitySeconds, period) : severitySeconds;
if (waitSeconds > 0 && now - event.lastAlertAt < waitSeconds * 1000) return { kind: 'held' };alert-event.ts, lines 177–193 at commit 017b33b- The first alert needs the reading to stay over the line for the sustained window. One frame over the line is not enough.
- While the event lasts, a repeat waits for the longer of the severity’s own cooldown and the Cooldown Period. A rise to a higher severity waits only for that severity’s cooldown.
- The event ends when readings stay under the line for the window (
alert-event.ts).
Motion’s window is the minimum motion duration. Sound uses the same window with a floor of its own, and picture change half of it with a floor (page.tsx; page.tsx; page.tsx). The defaults:
timingSettings: {
cooldownPeriod: 30,
minimumMotionDuration: 500,
emergencyEscalationDelay: 300, // 5 minutes
},
severityCooldowns: {
info: 5,
low: 10,
medium: 30,
high: 60,
critical: 0, // No cooldown for critical alerts
},settings-store.ts, lines 692–703 at commit 017b33bFor motion and sound, severity is how many points over the line the reading is: under 10 is low, and 10, 25 and 40 points give medium, high and critical (page.tsx). The first alert of an event adds a History entry, and its repeats count on that entry while nobody has acknowledged it (page.tsx). Each alert keeps the picture of the moment, plays its sound and asks for a notification if the browser allows one (page.tsx).
An alert nobody acknowledges climbs 5 levels, Gentle Reminder, Attention, Urgent, Critical and Emergency. Each waits for its own delay after the one before, 30, 60, 120 and 180 seconds, so the levels start at 0, 30, 90, 210 and 390 seconds, and each plays its own sound, louder than the last until it reaches full volume, which under Maximum Alert the first level already plays at (settings-store.ts; AlertPanel.tsx). The top level loops until someone acknowledges it. A Lost and Found sighting takes no part in the climb (AlertPanel.tsx).
- Readings go over the line.
- They stay over it for the sustained window. If they drop under it first, nothing starts.
- The first alert.
- Repeats, each after the longer of the severity’s cooldown and the Cooldown Period; a rise in severity waits only for its own cooldown.
- Unacknowledged, it climbs to levels 2 to 5 at 30 s, 90 s, 210 s and 390 s.
- Readings stay under the line for the window, and the event ends.
Stillness works the other way round. It is off until the person turns it on, they set its minutes from 1 to 60, and every 15 s the page checks how long it has been since a motion or picture-change reading last stayed over its line for its window (settings-store.ts; stillness-bounds.ts; page.tsx; page.tsx). The page on an old phone as a camera for an elderly parent shows where it fits.
Limits
- Both picture checks compare brightness and colour, with no idea of what moved. A light switched on, a camera adjusting its exposure, a curtain or a screen in view count as change.
- The sound level is a place on the browser’s scale, not decibels, and microphones differ.
- The checks run on timers. The time between calls can be longer than asked (MDN), and browsers slow the timers of an inactive tab, each by its own rules: Firefox for Android, for one, may unload such a tab entirely (MDN). A hidden tab can check far less often, or not at all.
- SafeOS does not ask for a screen wake lock, the API that keeps a screen from dimming or locking (MDN), so nothing in it stops the device’s own screen timeout.
- Reading and comparing a full frame happens on the page’s main thread, beside everything else the page does.
SafeOS adds an alert. It does not replace a person nearby. A phone or a browser can sleep, lose power or drop the camera, so stay within reach.
Next: image similarity by colour histogram, k-means and edges, how Lost and Found compares the camera’s picture with a pet’s photos, again with no model.
MDN quotations by Mozilla Contributors, CC BY-SA 2.5. The Web Audio API quotation is from the W3C specification. Other product names belong to their owners; SafeOS is not affiliated with them.
— The Frame.dev Team