Skip to content

The open source AI video agent: turns any coding agent into a video agent, with an editor to change anything it makes.

Exact frames: tell a video's frame by how long its frames last (#22)

riverisbuilding387d3922b8a2
diff --git a/.changeset/video-frame-length.md b/.changeset/video-frame-length.md
new file mode 100644
index 0000000..e49f594
--- /dev/null
+++ b/.changeset/video-frame-length.md
@@ -0,0 +1,5 @@
+---
+"openfilm": patch
+---
+
+Exact frames (render, look, Studio's exports): a video's frame on screen is told by how long its frames last, which the host reads with ffprobe. A video woken ahead while hidden, then shown, no longer leaves its old frame in the picture: shown again after the seek, it was taken for the sought one, and an export could hold a frame from the clip's start. Footage whose next frame is the same source frame (24 fps footage in a 30 fps export) no longer waits seconds for a frame that never comes: such a film exports several times as fast.
diff --git a/packages/openfilm/src/host.mjs b/packages/openfilm/src/host.mjs
index a31a9c3..4882220 100644
--- a/packages/openfilm/src/host.mjs
+++ b/packages/openfilm/src/host.mjs
@@ -1,4 +1,5 @@
// The reference host (SPEC §4): serves a film folder over HTTP, opens its page in Chromium and asks it for frames.
+import { execFile } from 'node:child_process';
import { createServer } from 'node:http';
import { createReadStream, readFileSync, realpathSync, statSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
@@ -72,6 +73,14 @@ export function folderFiles(root, { inject = `<script>${HOST_FLAG}</script>`, ti
res.writeHead(200, { ...extraHeaders, 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' }).end(FILM_DOC);
return true;
}
+ if (path.endsWith('/__film/frame-duration')) {
+ /* how long a video's frames last, for the timeline's exact frames (`?of=` the video's address) */
+ const file = fileInRoot(root, query?.get('of') ?? '');
+ const answer = (seconds) => res.writeHead(200, { ...extraHeaders, 'content-type': 'application/json', 'cache-control': 'no-store' }).end(JSON.stringify({ seconds }));
+ if (!file) answer(null);
+ else void frameDuration(file).then(answer);
+ return true;
+ }
let rel;
try { rel = decodeURIComponent(path); } catch { res.writeHead(400, extraHeaders).end('bad address'); return true; }
/* an address speaks in `/`: a `\` in it (escaped as %5C) would be a separator on Windows, past every check */
@@ -118,6 +127,42 @@ export function folderFiles(root, { inject = `<script>${HOST_FLAG}</script>`, ti
const within = (folder, path) => path === folder || path.startsWith(folder.endsWith(sep) ? folder : folder + sep);
+/** The file an address names inside `root` (not through a link out of it), or null. */
+function fileInRoot(root, address) {
+ let rel;
+ try { rel = decodeURIComponent(address); } catch { return null; }
+ if (!rel.startsWith('/') || rel.includes('\\') || rel.includes('\0')) return null;
+ const file = normalize(join(root, rel));
+ if (!file.startsWith(root + sep)) return null;
+ try { return within(realpathSync(root), realpathSync(file)) && statSync(file).isFile() ? file : null; } catch { return null; }
+}
+
+/** @type {Map<string, Promise<number | null>>} */
+const frameDurations = new Map();
+/**
+ * How long a video's frames last on average (ffprobe's frame rate), once per version of the file; null when ffprobe
+ * cannot tell (no ffprobe, no video stream).
+ * @param {string} file
+ */
+export function frameDuration(file) {
+ let key;
+ try { const stat = statSync(file); key = `${file}\0${stat.size}\0${stat.mtimeMs}`; } catch { return Promise.resolve(null); }
+ if (!frameDurations.has(key)) {
+ frameDurations.set(key, new Promise((done) => {
+ execFile('ffprobe', ['-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=avg_frame_rate,r_frame_rate', '-of', 'json', file],
+ { timeout: 20_000, windowsHide: true }, (error, stdout) => {
+ if (error) { frameDurations.delete(key); done(null); return; }
+ let stream;
+ try { stream = JSON.parse(String(stdout)).streams?.[0]; } catch { /* nothing to read */ }
+ const rate = [stream?.avg_frame_rate, stream?.r_frame_rate].map((r) => String(r ?? '').split('/').map(Number))
+ .map(([n, d]) => (n > 0 && d > 0 ? n / d : 0)).find((r) => r > 0 && r <= 1000);
+ done(rate ? 1 / rate : null);
+ });
+ }));
+ }
+ return /** @type {Promise<number | null>} */ (frameDurations.get(key));
+}
+
/**
* Serve `root`. HTML gets the host flag injected before any page script;
* ?film-host=0 serves the page untouched, as a visitor would see it.
diff --git a/packages/openfilm/src/timeline.mjs b/packages/openfilm/src/timeline.mjs
index 9e2004b..827ba0b 100644
--- a/packages/openfilm/src/timeline.mjs
+++ b/packages/openfilm/src/timeline.mjs
@@ -180,24 +180,27 @@ const SAME_TIME = 1e-4; // s: a video's currentTime is kept to the microsecond,
* Put a video on the frame at `t` and wait until that frame is the one on screen. `seeked` fires when the decoder
* has the frame, not when the compositor shows it: captured right after, the picture is still the previous one
* (often a stretch back, after a long seek), and the same t drew different pictures. The frame callback is the
- * moment the new frame is presented; one before the seek is done is still the old frame (shown again as its video turns
- * visible), and is not taken for it.
+ * moment the new frame is presented. Knowing how long the video's frames last (`frame`, from the host), the frame for t
+ * is told by its time: the old frame, shown again as its video turns visible, is not taken for it, even after the seek
+ * is done. Not knowing, a frame presented before the seek is done is taken for the old one when it is nearer where the
+ * video was.
*/
-async function showVideoAt(v, t) {
+async function showVideoAt(v, t, frame = null) {
/* a seek still under way (the start a video was woken at, see wake): its `seeked` and its frame would be taken for
this one's, and the picture captured was the earlier time's */
if (v.seeking) await new Promise((done) => { v.addEventListener('seeked', done, { once: true }); setTimeout(done, 10000); });
/* the same time again (to the microsecond the element keeps): no seek, nothing new to present (a seek there would
present nothing, and the wait would run out) */
if (!v.seeking && Math.abs(v.currentTime - t) < SAME_TIME && v.readyState >= 2) return;
- /* the old frame is the one nearer where the video was than where it is sought (a frame there would look the same) */
const before = v.currentTime;
let sought = false;
+ /* the frame a seek to t lands in starts at most a frame before t (and the seek goes a millisecond in, see host.mjs),
+ with a quarter frame to spare for footage whose frames are not all as long; without the frame's length, the old
+ frame is the one nearer where the video was than where it is sought (a frame there would look the same) */
+ const right = (m) => (frame ? m <= t + 0.002 && t + 0.001 - m < frame * 1.25 : sought || Math.abs(m - t) <= Math.abs(m - before));
const presented = typeof v.requestVideoFrameCallback === 'function'
? new Promise((done) => {
- const next = () => v.requestVideoFrameCallback((now, frame) => {
- if (sought || Math.abs(frame.mediaTime - t) <= Math.abs(frame.mediaTime - before)) done(); else next();
- });
+ const next = () => v.requestVideoFrameCallback((now, meta) => { if (right(meta.mediaTime)) done(); else next(); });
next();
setTimeout(done, 3000);
})
@@ -391,6 +394,23 @@ const cueing = new Set();
/** how long an edit waits for what it puts on screen; then it shows anyway, the rest drawn as it comes */
const CUE_MS = 5000;
+/** @type {Map<string, Promise<number | null>>} */
+const frameLengths = new Map();
+/**
+ * How long a video clip's frames last, as the host that serves the film says (host.mjs, from ffprobe); null from a
+ * server that cannot tell. Asked once a file.
+ */
+function frameOf(c) {
+ const src = url(c.row.src);
+ /* a video from another site: not the host's to say */
+ if (src.origin !== location.origin) return Promise.resolve(null);
+ if (!frameLengths.has(src.pathname)) {
+ frameLengths.set(src.pathname, fetch(new URL(`__film/frame-duration?of=${encodeURIComponent(src.pathname)}`, location.href))
+ .then((r) => (r.ok ? r.json() : null)).then((said) => (said?.seconds > 0 ? said.seconds : null)).catch(() => null));
+ }
+ return frameLengths.get(src.pathname);
+}
+
/** Wait for a video's file for an exact frame: too long is the film's error, said by the clip. */
function loaded(c) {
let timer;
@@ -559,7 +579,7 @@ async function draw(t, live) {
if (!c.el.paused) c.el.pause();
c.lastWant = want;
await loaded(c);
- await showVideoAt(c.el, want);
+ await showVideoAt(c.el, want, await frameOf(c));
return;
}
const local = sourceAt(c.span, t - c.at, c.row, c.native);
diff --git a/packages/openfilm/src/timeline.test.mjs b/packages/openfilm/src/timeline.test.mjs
index 442ee66..e47389f 100644
--- a/packages/openfilm/src/timeline.test.mjs
+++ b/packages/openfilm/src/timeline.test.mjs
@@ -272,6 +272,40 @@ test('an exact frame of a video sought there waits for its own frame on screen,
}
});
+test('a video woken ahead while hidden, then shown: its old frame presented again after the seek is not taken for the sought one', { skip: !hasFfmpeg && 'no ffmpeg', timeout: 60_000 }, async () => {
+ const dir = footage('of-stale-frame-');
+ writeFileSync(join(dir, 'film.html'), filmHtml({ stage: { w: 320, h: 180 }, tracks: [{ clips: [{ id: 'v', src: 'a.mp4', at: 2, time: [0, 4] }] }] }));
+ const s = await open(dir);
+ try {
+ const seen = await s.film.page.evaluate(async () => {
+ const v = document.querySelector('video');
+ /* before the clip: its video is woken at its first frame, hidden */
+ await window.film.frame(1.5);
+ const real = v.requestVideoFrameCallback.bind(v);
+ const presented = [];
+ const watch = () => real((now, meta) => { presented.push(meta.mediaTime); watch(); });
+ watch();
+ /* the clip comes on and the browser presents the frame the video holds once more, late: after the seek under
+ way is done, as a slow machine has it */
+ let late = true;
+ v.requestVideoFrameCallback = (callback) => {
+ if (!late) return real(callback);
+ late = false;
+ const old = v.currentTime;
+ const fire = () => callback(performance.now(), { mediaTime: old });
+ setTimeout(() => (v.seeking ? v.addEventListener('seeked', fire, { once: true }) : fire()), 0);
+ return 0;
+ };
+ await window.film.frame(2.75);
+ return presented;
+ });
+ /* 10 frames a second: the frame at 0.75 s of the video is the one from 0.7 s */
+ assert.ok(seen.some((m) => Math.abs(m - 0.7) < 0.01), `the frame at 0.75 s was on screen when the frame was done: ${seen}`);
+ } finally {
+ await s.close();
+ }
+});
+
test('an edit that splits, adds, removes or moves clips to a new track changes the film in place, without loading it again', { skip: !hasFfmpeg && 'no ffmpeg', timeout: 120_000 }, async () => {
const dir = footage('of-inplace-');
writeFileSync(join(dir, 'title.html'), page('title', 2));