Skip to main content
WorkflowsRecord a take on several cameras

Darkgrade Slate's VideoTake records one take on several cameras: it prepares and starts them together, stops them, and copies every clip off the cards. Its one state object is ready to show in a UI and save to disk.

For one camera, startRecording() and stopRecording() are all you need. Use VideoTake when a take has to succeed or fail as a whole.

import { VideoTake } from '@darkgrade/slate'

const take = new VideoTake('take-1', 'Interview, wide and close', cameras)

await take.start() // prepares, then starts every camera
// … the scene plays …
await take.stop() // stops every camera and finds its clip
await take.collect() // copies the clips off the cards

console.log(take.state.stage) // 'complete'

cameras is a Map from a name you choose to a TakeCamera: a small adapter you write over each camera.

Write the adapter

VideoTake never talks to a camera itself. It calls five methods on each TakeCamera, so a take can mix Slate cameras with anything else that records.

MethodMust do
prepare()Get the camera ready to record. Throw if it can't. Called once, before the start.
start()Start recording. Resolve to { recordingConfirmed, evidence }: whether the camera confirmed it, and how you know. Throw if it didn't start. Called once.
stop()Stop recording. Resolve to { stopped, media, warning? } with the clips it wrote, each a TakeMedia. stopped: false or a throw marks the camera uncertain. Called when the take or this camera stops.
collect(media, progress)Reopen the camera, copy the files and resolve to the same list with verified: true and a downloadUrl on each. Call progress(bytes, total) as you go. Called after every camera stopped and was closed.
close()Release the camera. Called whenever the camera is not recording: after it stops, and again after its clips are collected. Make a second call harmless.

This adapter wraps a Slate Camera and saves clips to a folder:

import { writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import {
    Camera,
    VideoTake,
    type TakeCamera,
    type TakeMedia,
} from '@darkgrade/slate'

function takeCamera(camera: Camera, folder: string): TakeCamera {
    let open = false
    const connect = async () => {
        if (open) return
        await camera.connect()
        open = true
    }
    return {
        prepare: connect,
        async start() {
            // Resolves once the camera reports recording.
            await camera.startRecording()
            return {
                recordingConfirmed: true,
                evidence: 'camera reported recording',
            }
        },
        async stop() {
            const clip = await camera.stopRecording()
            const file = {
                id: clip.mediaId,
                filename: clip.name,
                bytes: clip.sizeBytes ?? 0,
                verified: false,
            }
            return { stopped: true, media: [file] }
        },
        async collect(media, progress) {
            await connect() // the take closed this camera after it stopped
            const saved: TakeMedia[] = []
            for (const file of media) {
                const data = await camera.downloadMedia(file.id, {
                    onProgress: progress,
                })
                const path = join(folder, file.filename)
                await writeFile(path, data)
                const verified = data.byteLength === file.bytes
                saved.push({ ...file, downloadUrl: path, verified })
            }
            return saved
        },
        async close() {
            if (!open) return
            open = false
            await camera.disconnect()
        },
    }
}

const cameras = new Map([
    ['wide', takeCamera(new Camera(), './footage')],
    // Add one entry per camera.
])
const take = new VideoTake(crypto.randomUUID(), 'Interview', cameras)

collect() accepts a camera's files only if every one comes back with the same id, filename and bytes, a bytes above zero, verified: true and a downloadUrl. Anything else leaves that camera with an error: Transferred footage did not match the camera files. A clip over 4 GiB has no sizeBytes on Clip, so an adapter for long takes must read the size another way.

To open each of several cameras by serial number, see Choose a camera.

Constructor

new VideoTake(
    id: string,
    name: string,
    devices: Map<string, TakeCamera>,
    maximumMinutes?: number, // default 30
    publish?: (state: VideoTakeState) => void
)
ArgumentDescription
idYour identifier for the take. Must not be empty.
nameA label. Trimmed to 100 characters; 'Untitled take' when empty.
devices1 to 64 cameras, by the name each has in state.cameras.
maximumMinutesThe take's safety stop, 1 to 120. VideoTake records it in state.maximumMinutes; it runs no timer, so your code calls stop() when it elapses.
publishCalled with a copy of the state, a VideoTakeState, after every change. Use it to redraw a UI or save the take.

The constructor throws Choose 1–64 cameras and a safety stop of 1–120 minutes when an argument is out of range.

The life of a take

  1. 1

    Prepare

    prepare() readies every camera at once. When all are ready the take is armed. If one fails, the others are released and the take needs attention. start() calls it for you when you haven't.

  2. 2

    Start

    start() starts every camera at once. When every adapter's start() resolves, the take is recording, state.startedAt is the earliest start and state.startSkewMilliseconds is the gap between the first and last. If any start() throws, every camera is stopped and the take needs attention.

    A camera whose adapter resolved with recordingConfirmed: false still counts as recording: the take records what you reported and does not judge it.

  3. 3

    Stop

    stop() stops every camera that started. stopCamera(name) stops one and leaves the rest recording. When every camera has confirmed its stop, the take is in review.

  4. 4

    Collect

    collect() copies each camera's clips, one camera at a time, and closes each camera as it finishes. When every camera is collected, the take is complete.

VideoTake starts the cameras together, but it does not synchronise their frames. startSkewMilliseconds tells you how far apart the starts were confirmed; align the clips in your editor.

Take stages

state.stage is one of:

StageMeaning
preparingCreated; cameras are not all ready yet.
armedEvery camera is ready. Nothing is recording.
recordingAt least one camera is recording.
stoppingA stop is in progress.
reviewEvery camera has stopped. Ready to collect.
collectingClips are being copied.
completeEvery camera's clips are copied and verified.
attentionSomething needs a person: a camera failed to prepare or start, a stop was not confirmed, or a transfer failed. Read each camera's error.

Camera states

Each entry of state.cameras is a TakeCameraState with its own state:

StateMeaning
preparing, readyBefore the start.
recordingStarted. recordingConfirmed and evidence are what your adapter returned; startedAt is when.
stoppingA stop was requested (stopRequestedAt).
stoppedThe camera confirmed the stop; media lists its clips and stoppedAt is when they were found. Also a camera released before it started, with a warning saying so.
collectedIts clips are copied and verified.
errorIt failed to prepare.
uncertainA start or stop was sent and not confirmed. The camera may still be recording.

During a transfer, transferredBytes and totalBytes track progress, and transferRecovery holds a message while a retry is under way.

When something goes wrong

  • A stop is not confirmed. The camera becomes uncertain and the take needs attention. Call stop() again: it retries only the cameras still unstopped. hasUnstoppedCameras() says whether any remain. collect() refuses to run until none do.
  • A transfer fails. collect() retries a camera once, and only when the error your adapter threw has retryable: true. Any other failure is kept as that camera's error, the other cameras still collect, and the take ends in attention. Call collect() again to retry the cameras that are not yet collected.
  • A camera has no clips. It stays stopped, so the take ends in attention, not complete.
  • You need to cancel while it prepares or starts. requestStop() sets a flag that prepare() and start() honour: cameras that had not started are released, and any that had are stopped.
  • Two calls overlap. While another call is in progress, stop() and stopCamera() throw A take operation is still running, and collect() throws Confirm all cameras stopped before collecting footage.

Resume after a restart

Save the state your publish callback receives. After a restart, rebuild the take to finish collecting:

import { readFile, writeFile } from 'node:fs/promises'
import { VideoTake, type VideoTakeState } from '@darkgrade/slate'

const save = (state: VideoTakeState) =>
    writeFile('take.json', JSON.stringify(state))

const text = await readFile('take.json', 'utf8')
const saved: VideoTakeState = JSON.parse(text)
// Saved mid-transfer: nothing is copying now, so collect again.
if (saved.stage === 'collecting') saved.stage = 'review'
const take = VideoTake.resume(saved, cameras, save)
await take.collect()

VideoTake.resume only resumes collection, and has three limits:

  • It throws Confirm all recording stopped before resuming collection if any camera was saved as preparing, ready, recording, stopping or uncertain. A restart can't tell whether such a camera is still recording, so check it yourself with getRecordingState() first.
  • It throws A camera from this take is unavailable when a camera from the saved take is missing from devices.
  • It keeps the saved stage. A take saved while it was collecting stays collecting, and collect() refuses that stage; set it back to review first, as above. Cameras already collected are skipped.
⌘I