Skip to main content
WorkflowsAnalyse and set up a shot

Darkgrade Slate's analyseShot looks at a picture from the camera and tells you whether it is too dark, too bright, soft or colour-cast. optimiseShot then fixes the exposure: it picks a shutter speed and ISO the camera offers, focuses, and checks its work on a new frame.

import { Camera, analyseShot } from '@darkgrade/slate'

const camera = new Camera()
await camera.connect()

const { jpeg } = await camera.getLiveViewFrame()
const analysis = await analyseShot(jpeg)
console.log(analysis.exposure, analysis.focus, analysis.colour)
// 'balanced' 'detail-visible' 'neutral'

analyseShot and optimiseShot run in Node.js and decode the image with FFmpeg. Slate runs ffmpeg from your PATH; set FFMPEG_BIN to use another binary.

Analyse a frame

analyseShot(
    image: Uint8Array,
    vision?: boolean, // default true
    reviewer?: (image: Uint8Array) => Promise<ShotAnalysis['scene']>
): Promise<ShotAnalysis>

image is any still FFmpeg can read: a live-view frame, a photo's data, or a preview. Slate scales it to 160×90 and measures the middle 70% of the frame, so borders and on-screen overlays at the edges don't count. Decoding has a three-second budget; past it, analyseShot throws Visual analysis exceeded its three-second budget.

It resolves to a ShotAnalysis:

FieldMeaning
exposure'bright' when more than 2.5% of pixels are clipped or the median is above 0.72. 'dark' when the median and highlights are both low. Otherwise 'balanced'.
focus'detail-visible' or 'soft': whether the frame has fine edge detail. This describes the image; it can't prove your subject is the sharp part.
colour'neutral' or 'cast': whether near-grey pixels are balanced between red and blue. 'unknown' when under 3% of the frame is near grey.
metricsA ShotMetrics: the numbers behind the three verdicts (below).
effectiveIsoThe ISO in the image's EXIF data, when it has one.
sceneA vision model's review of the subject, when one ran (below).
methodA sentence saying which of the two methods produced the result.
durationMillisecondsHow long the analysis took.

ShotMetrics

All on a 0–1 scale unless noted, over the middle 70% of the frame.

FieldMeaning
medianMedian brightness.
p95Brightness of the 95th percentile: the highlights.
clippedShare of pixels above 0.97, or sitting on a video-white plateau.
darkShare of pixels below 0.08.
detailEdge energy. Above 0.00035 reads as detail-visible.
neutralPixelsShare of pixels that are near grey.
redBlueRatioRed over blue among near-grey pixels. 0.85 to 1.18 reads as neutral.

Subject review by a vision model

Edge detail can't tell a sharp background from a sharp face. With vision on, analyseShot also asks a vision model whether the main subject is sharp and the colour plausible, and returns its answer as scene: { subject, focus, colour, confidence }.

  • By default Slate asks an Ollama server at http://127.0.0.1:11434, and only when a model whose name matches qwen3.5, llava, gemma3 or gemma4 is already loaded there. It never loads one. With no such model, scene is absent and the measurements stand alone.
  • Set DARKGRADE_SHOT_VISION=0 to skip the default review.
  • Pass reviewer to use your own model. It receives the frame as a JPEG 512 pixels wide.
  • Pass false for vision to measure only.

subjectFocusVerified(analysis, cameraAcquired) combines the evidence into one answer. It is true when the camera reported focus (pass true when autofocus() resolved to 'acquired') or a review with confidence of at least 0.8 says the subject is sharp. A confident review that says the subject is soft makes it false either way.

Measure your own pixels

Without FFmpeg, measure raw pixels yourself. Both functions are synchronous and have no dependencies:

import { describeShot, measureShot } from '@darkgrade/slate'

declare const rgb: Uint8Array // width × height × 3 bytes, RGB
const metrics = measureShot(rgb, 160, 90)
const { exposure, focus, colour } = describeShot(metrics)

measureShot throws Invalid visual reference unless the image is at least 8×8 and the buffer is exactly width × height × 3 bytes.

Set up a shot automatically

optimiseShot is built for video: it fixes the shutter speed and ISO so brightness does not drift during a take, then verifies the picture.

It holds no camera. You give it a frame, the camera's settings and a few callbacks, so it works with a Camera, a remote camera or a test double:

import { Camera, optimiseShot } from '@darkgrade/slate'

const camera = new Camera()
await camera.connect()

const controls = async () => (await camera.getCapabilities()).controls
const frame = async () => (await camera.getLiveViewFrame()).jpeg
const settings = {
    'set-shutter-speed': 'shutterSpeed',
    'set-iso': 'iso',
    'set-aperture': 'aperture',
    'set-white-balance': 'whiteBalance',
    'set-focus-mode': 'focusMode',
} as const

const report = await optimiseShot({
    image: await frame(),
    controls: await controls(),
    frameRate: 25,
    focusRequested: true,
    apply: async (action, value) => {
        const id = settings[action as keyof typeof settings]
        await camera.setControl(id, value)
        return controls()
    },
    recapture: frame,
    focus: async () => {
        const result = await camera.autofocus()
        return { focusAcquired: result === 'acquired' }
    },
    publish: stage => console.log(stage), // 'Locking iso: ISO 400', …
})

console.log(report.status, report.summary, report.changes)

What it does, in order

  1. 1

    Shutter speed

    Picks the offered value closest to a 180° shutter. If the camera lists angles, it picks the one nearest 180°. Otherwise it picks the duration nearest 1 / (2 × frameRate), within one stop. Without frameRate and without angles, it leaves the shutter alone.

  2. 2

    ISO

    Picks a fixed ISO between 100 and 25600 from the camera's list: lower when the frame is bright, higher when dark. A balanced frame on Auto ISO gets the fixed value nearest the ISO in the frame's EXIF data, or ISO 400 without one.

  3. 3

    Aperture, as a last resort

    Only when the first frame was dark and the ISO is now 12800 or above: opens the aperture by up to one stop.

  4. 4

    White balance, only if you ask

    Only with tuneWhiteBalance: true and a whiteBalanceTarget. If the new frame shows a colour cast, or has lost most of its near-grey pixels, it puts the old value back and marks the change reverted.

  5. 5

    Focus

    Calls your focus when you set focusRequested, or when the first frame looked soft. A camera in manual focus is left alone, unless you set both focusRequested and repairFocusMode: then it is first switched to a single or continuous autofocus mode the camera offers.

  6. 6

    Verify

    If anything changed, calls recapture and analyses the new frame. If exposure is still off, it corrects the ISO up to three more times, each one checked on a fresh frame.

It only ever writes values from a setting's allowedValues. If a setting it needs to change has writable: false or enabled: false, it stops there and reports attention with the reason in error.

Options

The first five are required.

OptionDescription
imageThe starting frame.
controlsThe camera's settings by id: shutterSpeed, iso, aperture, whiteBalance, focusMode. getCapabilities().controls has the right shape.
apply(action, value)Writes one setting and resolves to the fresh settings. action is 'set-shutter-speed', 'set-iso', 'set-aperture', 'set-white-balance' or 'set-focus-mode'.
recapture()Resolves to a new frame taken after the changes.
publish(stage)Called with a short progress sentence before each step.
focus()Runs autofocus and resolves to { focusAcquired }. Without it, nothing is focused.
frameRateFrames per second, for the 180° shutter rule.
focusRequestedFocus even when the frame looks sharp, and require verified focus for a verified result.
repairFocusModeWith focusRequested, allow switching a manual-focus camera to autofocus.
focusEvidence{ focusAcquired: true } when the camera already reported focus for image.
tuneWhiteBalance, whiteBalanceTargetSet white balance to this value. Both are needed.
budgetMillisecondsTime allowed, default 20000. Kept between 10000 and 60000.
analyseA replacement for analyseShot.

The report

optimiseShot resolves to a ShotSetupReport:

FieldMeaning
status'verified': exposure is balanced on a frame taken after the last change, every change read back, shutter and ISO are fixed values, and focus is verified if you asked for it. 'attention': anything less. The type also allows 'unavailable', which optimiseShot never returns.
summaryOne sentence a person can act on, such as Scene remains too dark at the automatic gain limit; add light or reframe.
changesEach write: setting, before, after, verified (the camera read it back), and reverted with attempted for a white balance that was put back.
analysis, beforeThe final and the first ShotAnalysis.
exposureVerified, focusVerified, imageVerifiedWhich parts were confirmed on a frame taken after the last change.
budgetExceededThe time budget ran out before verification finished.
durationMillisecondsHow long the setup took.
errorWhy it could not finish, when it could not.

optimiseShot changes settings on the camera and does not put them back. Read the settings first if you need to restore them: changes[].before has the old value of each one it wrote.

The choosers on their own

The functions optimiseShot uses to pick values are exported, for your own setup logic. Each returns undefined when the current value is already the best choice or nothing suitable is offered.

FunctionReturns
chooseShutterSpeed(allowed, frameRate, current?)The offered shutter closest to 180°, as above.
chooseIso(allowed, current, analysis)The offered ISO (100–25600) that best corrects analysis.exposure.
exifIso(data)The ISO in a JPEG's EXIF data, or undefined.
import { chooseShutterSpeed } from '@darkgrade/slate'

chooseShutterSpeed(['1/25', '1/50', '1/100'], 25, '1/100') // '1/50'
chooseShutterSpeed(['90°', '172.8°', '180°'], undefined) // '180°'
⌘I