Files
web-dslr/README.md
Jon baaa0b5472
Some checks failed
CI / build-and-deploy (push) Has been cancelled
Add fullscreen preview, PWA support, and connect without a button
Fullscreen: a button on the preview pane fullscreens the live view, carrying
the countdown over as an overlay - fullscreen hides the entire control column,
so without it you're left staring at a picture with no idea when the next
frame lands.

Wake lock: held from app start until you switch it off, rather than only for
the duration of a sequence. You're usually mid-setup when the display would
otherwise sleep.

PWA: manifest, icons and a service worker, so it installs to a standalone
window and runs with no network. That matters more here than for most web
apps - the camera is on a USB cable, so this is fully functional in a field
with no signal.

The worker precaches the pinned unpkg dependencies at install rather than
leaving them to the runtime cache. On a first visit the worker isn't
controlling the page yet, so the app's own imports go straight to the network
and never reach the fetch handler; without the precache it looked cached but
died offline on its imports. Our own files are network-first so a redeploy
always wins, and the version-pinned CDN files are cache-first.

Connecting: no connect button. The app reaches for the camera on load, retries
every 1.5s, and listens for USB connect events, so switching the camera on
mid-wait attaches it with no click or reload. The exception is a browser that
has never been granted access to the device: Chrome will not open its WebUSB
chooser outside a user gesture, so that case still shows a one-off prompt.
After that the permission is remembered and getDevices() finds the camera with
no interaction.

tsconfig excludes sw.js, which runs in ServiceWorkerGlobalScope and reports
every worker global as undefined when checked against the DOM lib.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QK7PKpRVoy69Fpa32R8abb
2026-08-02 09:53:24 +01:00

200 lines
10 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Web-gPhoto2
A gPhoto2 implementation using WebAssembly to control DSLR cameras from the browser.
Powered by a [custom fork](https://github.com/RReverser/libgphoto2) of [libgphoto2](https://github.com/gphoto/libgphoto2), the [WebUSB](https://github.com/WICG/webusb) backend of [libusb](https://github.com/libusb/libusb), and WebAssembly via [Emscripten](https://emscripten.org/).
## Installation
```bash
npm install web-gphoto2
```
## Usage
A short example on how to use this package:
```js
import { Camera } from "web-gphoto2";
let camera = new Camera();
// Triggers the browser's native USB picker listing all connected cameras.
await Camera.showPicker();
// Connects to the camera exposed in the previous step.
// In the future we might allow to connect to multiple cameras by passing a specific instance.
await camera.connect();
console.log("Operations supported by the camera:", await camera.getSupportedOps());
console.log("Current configuration tree:", await camera.getConfig());
// Update camera configuration by the setting's name.
await camera.setConfigValue("iso", "800");
// Capture a lower-quality preview frame, useful for high-FPS live view stream.
// Returns a Blob with image mime type and contents.
const blob = await camera.capturePreviewAsBlob();
// Use `URL.createObjectURL` to create an image URL from the blob or `createImageBitmap` to decode it directly.
const img = new Image();
img.src = URL.createObjectURL(blob);
// Capture a full-resolution image in format currently selected on the camera (JPEG or RAW).
// This can be used in the same way as Blob above, but also has extra information such as filename useful for download.
const file = await camera.captureImageAsFile();
const a = document.createElement("a");
a.href = URL.createObjectURL(file);
a.download = file.name;
```
## Intervalometer app
`examples/preact` is an intervalometer for shooting timelapses, built around a Canon EOS 450D but not specific to it — anything the PTP driver supports will work.
```bash
cd examples/preact
npm install
npx serve . # serve.json sets the COOP/COEP headers the WASM module needs
```
Open the printed URL in Chrome and plug the camera in. It connects on its own — there's no connect button. The one exception is the very first visit, which shows a "Choose camera" prompt: Chrome will not open its WebUSB device chooser without a click. After that the permission is remembered, and `navigator.usb.getDevices()` finds the camera with no interaction, so later visits go straight in. If the camera is off or asleep the page sits on "Looking for your camera…" and keeps retrying, connecting the moment it wakes up.
It's also an installable PWA: install it from Chrome's address bar to get a standalone window, and it works with no network at all — the app shell and the pinned unpkg dependencies (including the ~2 MB WASM) are precached by a service worker. That matters here because the camera is on a USB cable, so the app is perfectly useful in a field with no signal.
**Home screen** — only the things you change between runs:
- **Interval**, **frames** (or ∞ for open-ended) and **start delay**
- Start/stop, plus a single-shot button for framing
- Live countdown to the next frame, progress, estimated finish time, and a log of the last few events
- A 🔊 toggle that speaks the countdown into each frame ("five, four, three, two, one") along with start and finish, for when you're in front of the camera rather than at the laptop
- A ⛶ button on the preview for a fullscreen live view, with the countdown carried over as an overlay so you don't lose it
- A read-only strip showing shutter / aperture / ISO / format / battery / shots remaining, so you can sanity-check exposure against the interval without opening anything
- Pre-flight warnings when the interval is too tight for the current exposure and transfer time, when you're shooting RAW on a short interval, or when no output folder is set
**Settings drawer** (⚙, top right) — everything else, including the full gPhoto2 config tree, so the home screen stays uncluttered:
- Where frames go: a folder on disk via the File System Access API, one-at-a-time downloads, or nothing at all if you're keeping them on the card. Frames are named after the moment they were taken — `20260801-172713_00007.JPG` in a sequence, `20260801-172713.JPG` for a single shot — so sorting by name is sorting by capture time. The camera's own `IMG_1234` is dropped: it wraps at 9999 and resets on a card format, so it can't order a long run.
- Live view on/off, and whether it stays up between frames during a sequence (on by default — the feed drops only while each shot fires, since the camera needs live view down to take it, then recovers on its own)
- Screen wake lock, so a backgrounded tab doesn't get its timers throttled mid-run
- Voice countdown detail: how many seconds out to start counting (capped at one second under the interval so it never talks over the previous frame), which system voice to use, and whether to announce frame numbers
- Bulb exposures, if the camera exposes `bulb` or `eosremoterelease`
- The camera's own settings: shutter, aperture, ISO, image format, capture target, drive mode, and so on
### Deploying
Deployed as an assets-only Cloudflare Worker:
```bash
cd examples/preact
./build-dist.sh # copies just the browser files into dist/
npx wrangler deploy
```
Live at <https://dslr-intervalometer.bournemouthtech.workers.dev>.
`build-dist.sh` is an explicit allowlist rather than an ignore file, because everything in the assets directory becomes publicly readable and `.assetsignore` was not excluding `node_modules`.
The one thing a static host has to get right here: the WASM module is built with pthreads and allocates a **shared** `WebAssembly.Memory`, so the page must be [cross-origin isolated](https://web.dev/coop-coep/) or it fails to start outright. `_headers` sets the same COOP/COEP pair `serve.json` uses locally. If you host this anywhere else, set those two headers or nothing will work. Verify with `crossOriginIsolated === true` in the console.
Notes on the timing and its limits:
- Frames are scheduled on an absolute grid (`start + n × interval`), so transfer time doesn't accumulate as drift over a long run. If a capture overruns its slot the next frame fires as soon as the camera is free and the overrun is logged, rather than a frame being dropped.
- Three failed captures in a row abort the sequence.
- Config polling only runs while the settings drawer is open; during a sequence the USB link is left to the captures.
- Keep the tab in the foreground. Chrome throttles timers hard in hidden tabs, which will stretch your intervals.
- **Bulb is experimental.** Bulb frames are written to the camera's card and are *not* downloaded — the WASM API only returns files produced by an explicit `captureImageAsFile`, and there's no hook for images arriving any other way. Set the capture target to the memory card and pull the card afterwards. For exposures of 30s or less, just set the shutter speed normally and leave bulb off.
## Original demo
`examples/preact` started out as the upstream gPhoto2-on-the-Web demo — a live view next to the raw camera config tree — and the intervalometer above replaced it. The original is still hosted and documented upstream:
![A picture of DSLR camera connected via a USB cable to a laptop. The laptop is running the Web demo mentioned in the article, which mirrors a live video feed from the camera as well as allows to tweak its settings via form controls.](https://web-dev.imgix.net/image/9oK23mr86lhFOwKaoYZ4EySNFp02/MR4YGRvl0Z9AWT6vv3sQ.jpg?auto=format&w=1600)
For the detailed technical write-up, see [the official blog post](https://web.dev/porting-libusb-to-webusb/). To see the demo in action, visit the hosted version [here](https://web-gphoto2.rreverser.com/) (but make sure to read the [cross-platform compatibility notes](https://web.dev/porting-libusb-to-webusb/#important-cross-platform-compatibility-notes) first).
If you don't have a DSLR, you can check out a recording of the demo below:
<https://user-images.githubusercontent.com/557590/152155035-a1664656-a7d9-411f-8cb3-5f04320f1391.mp4>
## Building
To build the WebAssembly part of the repo, you'll need Docker on Linux (WSL works too) or macOS machine. Then:
```bash
npm run build:wasm # runs build in Docker
```
If you are just updating the JS library (`src/camera.ts`), then it's enough to do
```bash
npm run build:ts
```
on any system as Wasm parts are committed to this repo.
To serve the demo, run:
```bash
npx serve examples/preact # starts a local server with COOP/COEP
```
Then, navigate to <http://localhost:3000/> in Chrome.
## Common Issues
<details>
<summary>
SharedArrayBuffer can not be found
</summary>
SharedArrayBuffer has been disabled across all browsers due to the Spectre vulnerability. This package uses SharedArrayBuffer to communicate with the WebAssembly module. To work around this issue, you need to set two response headers for your document:
```http
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
```
Information from [Stackoverflow](https://stackoverflow.com/questions/64650119/react-error-sharedarraybuffer-is-not-defined-in-firefox)
</details>
<details>
<summary>
Error: Not found: /node_modules/.vite/deps/libapi.wasm
</summary>
Vite tries to optimize the dependencies by default. This causes the WebAssembly module to be moved to a different location. To prevent this, you need to exclude the web-gphoto2 package from the optimization.
In vite, both of the above mentioned issues are solved by adding the following to your vite.config.js:
```js
import { sveltekit } from "@sveltejs/kit/vite";
import { defineConfig } from "vite";
/** @type {import('vite').Plugin} */
const viteServerConfig = {
name: "add headers",
configureServer: (server) => {
server.middlewares.use((req, res, next) => {
res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
next();
});
},
};
export default defineConfig({
plugins: [sveltekit(), viteServerConfig],
optimizeDeps: {
exclude: ["web-gphoto2"],
},
});
```
</details>
## See also
[RReverser/eos-remote-web](https://github.com/RReverser/eos-remote-web) - my other project for controlling Canon cameras over Web Bluetooth.
## License
Like the dependencies, this demo is licensed under [LGPL v2.1](https://github.com/GoogleChromeLabs/web-gphoto2/blob/main/LICENSE).