Frame.dev
playwrighttestinggetusermediagithub-actions

Playwright fake camera: testing a webcam app in CI

Frame.dev Team10 min read

SafeOS’s web app reads a camera and a microphone, so its tests need both on GitHub’s runners, which have neither. On every pull request, Chromium plays a committed clip as its camera and microphone, the pages run their own camera code against it, and the walks check what a person would see. This post shows the flags, the stand-ins and the measurements, and ends with what no test covers.

The short version, beside the rest of SafeOS, is the last section of how SafeOS watches a room in your browser. The path from a pull request to the live site:

From pull request to safeos.shA pull request runs the checks, the walks and the pictures; master is measured, checked offline and deployed. The list under the drawing says each step in words.A pull request starts CI,Pictures and the Deployworkflow’s build.CI runs the server and webchecks and the browserwalks. Pictures takesscreenshots in both looksand reads contrast from thepixels.The merge to master.On master, Measure runs onslowed processors. Deploybuilds the export and theoffline file list, and theoffline start check runs.GitHub Pages serves thebuild, and the live home iscompared with it.safeos.sh.
From pull request to safeos.sh
  1. A pull request starts CI, Pictures and the Deploy workflow’s build.
  2. CI runs the server and web checks and the browser walks. Pictures takes screenshots in both looks and reads contrast from the pixels.
  3. The merge to master.
  4. On master, Measure runs on slowed processors. Deploy builds the export and the offline file list, and the offline start check runs.
  5. GitHub Pages serves the build, and the live home is compared with it.
  6. safeos.sh.

A CC0 clip as the camera and the microphone

The repository holds one sample clip, 28.2 seconds of a kitten grooming itself at 640 by 480 and 15 frames a second, with a separate recording of a dog out of view mixed in from 6 to 9 seconds. Both sources are under CC0 1.0, and the clip’s record lists every change made to them (sample-clip.json; CC0 1.0). Chromium’s fake camera reads a .y4m file and its fake microphone a .wav file, so CI makes both from the clip and never commits them:

- name: Make the fake camera's files from the sample clip
  id: clip
  if: always() && steps.ffmpeg.outcome == 'success'
  run: |
    ffmpeg -nostdin -v error -y -i public/home/sample-clip.mp4 -an -pix_fmt yuv420p "$RUNNER_TEMP/sample-clip.y4m"
    ffmpeg -nostdin -v error -y -i public/home/sample-clip.mp4 -vn -ac 1 -ar 48000 -c:a pcm_s16le "$RUNNER_TEMP/sample-clip.wav"
    ls -l "$RUNNER_TEMP"/sample-clip.*
    echo "SAMPLE_CLIP_Y4M=$RUNNER_TEMP/sample-clip.y4m" >> "$GITHUB_ENV"
    echo "SAMPLE_CLIP_WAV=$RUNNER_TEMP/sample-clip.wav" >> "$GITHUB_ENV"
ci.yml, lines 240–248 at commit 19a286c

The walks launch Chromium with these arguments:

export function sampleClipLaunch(): string[] {
  const video = process.env.SAMPLE_CLIP_Y4M;
  const audio = process.env.SAMPLE_CLIP_WAV;
  return [
    '--use-fake-ui-for-media-stream',
    '--use-fake-device-for-media-stream',
    // Without the clip's files the fake devices play Chromium's own pattern;
    // the walks that need the clip fail in requireSampleClip.
    ...(video ? [`--use-file-for-fake-video-capture=${video}`] : []),
    ...(audio ? [`--use-file-for-fake-audio-capture=${audio}`] : []),
    '--autoplay-policy=no-user-gesture-required',
  ];
}
alert-pictures.ts, lines 476–488 at commit 19a286c

Chromium’s source says what each flag does. --use-fake-device-for-media-stream uses a fake device “to replace actual camera and microphone”; --use-file-for-fake-video-capture plays “an .y4m file … as the webcam”; --use-file-for-fake-audio-capture plays “a .wav file as the microphone”, looping unless the path ends in %noloop, and must be used with the fake device flag or the flag that turns audio input off (media_switches.cc). --use-fake-ui-for-media-stream bypasses the permission prompt by selecting the default device (content_switches.cc). The test file also grants the camera and the microphone through Playwright (alert-pictures.spec.ts). With those in place, the Motion and sound page calls getUserMedia as it would on a phone, and its frame differencing, its sound meter and its alerts run on the clip.

A canvas in place of the camera

A recorded clip plays what it plays. For a walk that needs a picture to change in a known way, a third of the frame redrawn in four greys for instance, the test replaces getUserMedia before the page loads (alert-pictures.ts). The stand-in paints a canvas every 40 ms and hands the page the canvas’s stream:

draw();
const timer = setInterval(draw, 40);
stream = canvas.captureStream(25);
window.__streams = [...(window.__streams ?? []), stream];
if (constraints && constraints.audio) {
  audio = new AudioContext();
  const microphone = audio.createMediaStreamDestination();
  if (live.tone) {
    const tone = audio.createOscillator();
    tone.type = 'sawtooth';
    tone.frequency.value = 440;
    const gain = audio.createGain();
    gain.gain.value = 1;
    tone.connect(gain).connect(microphone);
    tone.start();
  }
  void audio.resume();
  for (const track of microphone.stream.getAudioTracks()) stream.addTrack(track);
}
return stream;
alert-pictures.ts, lines 428–447 at commit 19a286c

captureStream() returns a MediaStream with “a real-time video capture of the canvas’s contents” (MDN, Mozilla Contributors, CC BY-SA 2.5), and a Web Audio destination node adds a microphone track, silent or a sawtooth tone at 440 Hz. The page reads that stream the way it reads a real camera. The fake device flags stay on even then, because the page lists the browser’s cameras before it asks for one, and the fake device gives it one to list (alerts-repeat.spec.ts). The camera’s own change is described in the helper, so a walk can say what the page should report: LEFT_THIRD redraws the left third of a 320 by 240 picture at grey levels 0, 85, 170 and 255 on a grey of 128 (alert-pictures.ts).

Both camera walks run in desktop Chromium only, and skip under every other project in the config (alerts-repeat.spec.ts, alert-pictures.spec.ts). Playwright warns that supported permissions “differ between browsers, and even between different versions of the same browser” (BrowserContext.grantPermissions), and in Playwright 1.57, the version the web app locks (package-lock.json), Firefox grants only geolocation, persistent storage, push and notifications and throws “Unknown permission: camera” for the camera (ffBrowser.ts). CI’s Firefox step runs one check of Firefox’s own, which needs no camera: Settings, Notifications says that Firefox shows a notification’s words without its picture (ci.yml, notification-picture-firefox.spec.ts). The config lists WebKit and two phone projects too (playwright.config.ts); no workflow runs them.

The Lost and Found walks and the probe

Lost and Found needs a camera that shows the pet it was given. Its walks write their own .y4m: grey stripes, 640 by 480, drifting sideways one period and looping, and a still of the same stripes to enrol, so the walks need no clip in the repository and no ffmpeg (striped-subject.ts). One job builds the site once and runs fourteen spec files against it in Chromium: the enrolment, the watch, the sounds, the settings that change what the watch does, and a possible sighting’s entry with the camera’s picture beside the pet’s photo (ci.yml).

The Pictures workflow then probes Lost and Found on the sample clip at the app’s default settings. It enrols a pet named Toffee through the Lost and Found page twice, each time on a new browser: once from the three example photos (set A) and once from photo 1 alone (set B). Each time it watches the clip for 85 seconds, three plays, reading what the watch kept every two seconds, and the step fails when either set raises nothing (lost-found-probe.mjs, pictures.yml). The record of its tries holds a run in which each set raised a possible sighting, 0.3 and 0.4 seconds after the watch went live (photos.json). Photos 2 and 3 are stills from the recording the clip comes from, so the probe shows how the comparison works, not how well it works on another pet in another room.

Slowing the processor 1, 2, 4 and 6 times

A runner is not a phone. The Measure workflow, which runs on each push to master and records without judging (measure.yml), plays the same clip through the fake camera into two device classes: a phone class at 390 by 844 CSS pixels, three device pixels to each, touch and the mobile flag, slowed 4 and 6 times; and a laptop class at 1280 by 800, slowed 1 and 2 times (measure-devices.mjs). The slowing is one call of the Chrome DevTools Protocol on each page:

async function slowedPage(context, rate) {
  const page = await context.newPage();
  const cdp = await context.newCDPSession(page);
  await cdp.send('Emulation.setCPUThrottlingRate', { rate });
  return { page, cdp };
}
measure-devices.mjs, lines 246–251 at commit 19a286c

The protocol defines the rate as “a slowdown factor (1 is no throttle, 2 is 2x slowdown, etc)” (Emulation.setCPUThrottlingRate), and Playwright supports CDP sessions in Chromium-based browsers only (BrowserContext.newCDPSession). The script’s own summary says what that is worth: “the slow-down is an approximation of a slower device, not a named phone” (measure-devices.mjs). For each class and factor it times the watch’s timers from inside the page for 60 seconds, runs the detection model once and then up to 40 more times, within 2 minutes, on a 320 by 240 copy of the camera’s frame, and times Lost and Found’s comparisons for 30 seconds (measure-devices.mjs, measure-devices.mjs, measure-devices.mjs).

The figures here come from Measure’s run on commit 017b33b, on its runner: A GitHub-hosted ubuntu-24.04 runner with no graphics card: Intel Xeon 6975P-C, 4 logical CPUs, Chromium 143. The model ran on the cpu backend, and one check took a median of 1.7 s in the laptop class at a factor of 1 and 10.8 s in the phone class at a factor of 6. On one server computer with no graphics card, its processor slowed to stand in for a phone. No real phone was measured.

One part of Measure does fail the run. Its Wildlife probe opens the real Wildlife page with the model already in the browser’s cache, presses Start Monitoring and watches the clip twice, counting the page’s canvas reads and finished model checks without changing them (measure-devices.mjs, wildlife-probe.mjs, wildlife-probe.mjs). Unless Wildlife got through its motion gate, finished a model check and saved a cat on both plays, the run fails (wildlife-shortfall.mjs, measure-devices.mjs).

A test that holds the pages’ words to the code

One unit test reads the source of every public page and of the components they render, the README’s product sections, the security policy, the quick start and the changelog’s Unreleased section, with code comments left out (public-pages-say-what-is-true.test.ts, public-pages-say-what-is-true.test.ts). It collapses the whitespace, so a phrase split over JSX lines still matches, and runs each file against two lists of phrases:

function findPhrases(phrases: Phrase[], files: string[] = [...SCANNED, README, CHANGELOG, SECURITY, QUICKSTART]): Hit[] {
  const hits: Hit[] = [];
  for (const file of files) {
    const { text, lineOf } = collapse(readable(file));
    for (const { pattern, why } of phrases) {
      const global = new RegExp(pattern.source, pattern.flags.includes('g') ? pattern.flags : pattern.flags + 'g');
      for (const match of Array.from(text.matchAll(global))) {
        const at = match.index ?? 0;
        hits.push(`${rel(file)}:${lineOf[at]} "${match[0]}" (${why})`);
      }
    }
  }
  return hits;
}
public-pages-say-what-is-true.test.ts, lines 470–483 at commit 19a286c

Every entry carries its reason: the file and the behaviour that make the phrase untrue (public-pages-say-what-is-true.test.ts). A page that names a model the server does not select, a buffer the browser does not keep, or a privacy promise the code does not keep fails with that reason beside the line. The test runs with the others in CI’s Web app tests job (ci.yml). This post sits in a folder the test reads.

Contrast read from pixels

The Pictures workflow captures the site’s pages at four widths in the light and the dark look, for the pull request and for its base commit (pictures.yml). For the home page it then measures readability from the screenshots themselves (pictures.yml). The sampler crops each box the page reported, takes the most common colour as the ground, keeps the pixels that stand out from it as ink, and compares them with these floors:

FLOORS = {"body": (12, 18), "label": (7, 16), "poster": (7, 14), "glyph": (4.5, 0), "edge": (4.5, 0)}
DISCLOSURES = ("motion", "sound", "people-animals", "lost-found", "offline", "storage")


def linear(channel):
    value = channel / 255
    return value / 12.92 if value <= 0.04045 else ((value + 0.055) / 1.055) ** 2.4


LUMINANCE = [linear(channel) for channel in range(256)]


def luminance(rgb):
    return sum(LUMINANCE[channel] * weight for channel, weight in zip(rgb, (0.2126, 0.7152, 0.0722)))


def contrast(first, second):
    return (max(first, second) + 0.05) / (min(first, second) + 0.05)
contrast-sample.py, lines 13–31 at commit 19a286c

The luminance and the ratio are WCAG 2.2’s: “(L1 + 0.05) / (L2 + 0.05), where L1 is the relative luminance of the lighter of the colors” (WCAG 2.2). The body floor of 12:1 is well above the 4.5:1 that WCAG’s Contrast (Minimum) asks of text. Each box also states its CSS size, so a word under 18 px in body text fails (contrast-sample.py).

Before and after each deploy

Before the deploy uploads the export, a check in Chromium visits only the home page, goes offline and opens the Wildlife page it never visited (deploy-pages.yml); the post on how the app works offline takes it apart. After the deploy, a last job reads the live home page up to six times. It compares the SHA-256 of the served HTML with the build’s, compares the recorded runs’ list and files with the commit’s, and plays each recorded run (deploy-pages.yml, deploy-pages.yml, check-published-home.mjs).

What no test covers

  • People’s watch with the real model. The pull request’s pictures run People and Wildlife with a canvas that flashes between two dark colours, a stand-in graph in place of the model that returns fixed boxes and scores, and the motion line set to zero or nearly, so they show the alert screens without testing the gate or the model (watch-page-captures.mjs, watch-page-captures.mjs). The unit tests replace the model with fixed answers (person-detection.test.ts, animal-detection.test.ts). Only Measure’s probe runs the real model behind the real gate, on Wildlife.
  • The server. The walk that connects one answers the page’s WebSocket itself through Playwright’s routeWebSocket (Page.routeWebSocket), greets the page’s session and records what it sends (alert-pictures.ts). It checks that frames are sent and that they carry no kept picture (alert-pictures.spec.ts), not that the real server accepts them. At this commit the real server refuses them, as the post on the self-hosted server shows.
  • Safari, WebKit and Firefox’s camera path, and any real phone.
  • How often People, Wildlife or Lost and Found is right or wrong. Nothing measures it.

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: object detection in the browser with COCO-SSD on TensorFlow.js, the model these walks never run on People.

Playwright, Chromium, Chrome, Firefox, Safari, WebKit and GitHub are named to describe what SafeOS is tested with. Product names belong to their owners; SafeOS is not affiliated with them.

— The Frame.dev Team

Frame.dev Team

Frame makes SafeOS and AgentOS. frame.dev