Skip to content

Video as code: canvas scenes rendered with WebCodecs in headless Chrome, a review viewer, and agent skills that build the video from your references.

Cut lists: one recording over several scenes by section, with captions (#14)

Stanyslaus Hary47d101443d7d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1aec8e3..dcc60dd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Changes are listed by release, newest first. The sections dated before 0.1.0 rec
- `motlab render` and the viewer's Export render several scenes and transitions at once, each in its own Chrome, after the first scene has picked the encoder. `--parallel N` sets how many; the default is 3, but never more than one per 4 CPU threads or per 1 GB of free memory. If a part fails while several run, the finished parts are kept and the rest are rendered one at a time, so a machine that cannot run three still finishes. Each part's log is printed in one piece when it ends. On the test laptop (Ryzen 7 5800H, 16 threads, RTX 3060 Laptop), a project of 12 two-second scenes with 11 transitions went from 78 s to 45 s at 1080p and from 93 s to 53 s at 4K; four at a time was no faster than three. The example project went from 12.7 to 13.1 s to 8.9 to 9.6 s at 1080p, with an identical MP4. `test/render.test.js` renders a four-scene project three at a time and checks the frame count and the colours of every scene and transition, then breaks one scene and checks that it is tried again alone and its error is the one reported. Not tried: a machine with fewer threads or less memory, and a GPU that runs out of encoder sessions.
- A scene transition can come from a `.glsl` file in the project, as `"type": "transitions/swipe.glsl"`. The file is a gl-transitions shader: `vec4 transition(vec2 uv)` with `getFromColor`, `getToColor`, `progress` and `ratio`. Its uniforms (float, int, bool, vec2 to vec4, ivec2 to ivec4) take their defaults from the comment after them, as gl-transitions writes them, and `params` sets them. The viewer and the render compile the file before the first frame and report a mistake with its line in the file. The file's contents are in the cache key, so `--only` renders an edited transition again. The skill's motion reference says how to write one, and how to match a transition from a reference video by laying frames from both on contact sheets. Checked: the 11 built-in shaders parse back to the uniforms and defaults listed with them; `test/render.test.js` renders a project with a shader file at its defaults and with `params`, and checks that a mistake on line 3 is reported on line 3; the wipe from the docs looked the same in the viewer and in a 1080p render, and the viewer showed a compile error with its line. Not tried: shaders copied from gl-transitions beyond the 11 built in, and matching a real reference video.
+- One recording can be split over several scenes by section, with captions from a transcript. `cuts.json` takes `"sections": [{ "name", "from" }]` in seconds of the recording (`cut_pauses.py --sections hook=0,demo=41.5` writes them and prints where each lands), and `cutList(cuts, clip, { section: 'demo' })` plays that section from time 0: it starts at the cut nearest its `from` and runs to the next section's cut, so the section scenes add up to the cut voice. `edit.captions(transcript)` takes Whisper's JSON with word times, or a list of `{ text, start, end }`, drops words that were cut out or lie outside the section, and returns caption lines in the scene's time, broken at pauses, sentence ends and a character limit. motlab does not transcribe. Checked: `test/cuts.test.js` (new) checks section starts and lengths with and without a dissolve and how captions are placed; `test/render.test.js` renders two section scenes of one grey-coded recording and checks all 24 frames; `cut_pauses.py --sections` on a made-up take matched `cutList`. Not tried: a real Whisper transcript and a real take split into sections.
- With no system Chrome, motlab uses the newest Chromium that Playwright downloaded, from Playwright's folder (`~/.cache/ms-playwright` on Linux, `~/Library/Caches/ms-playwright` on macOS, `%LOCALAPPDATA%\ms-playwright` on Windows, or `PLAYWRIGHT_BROWSERS_PATH`), so `motlab doctor` passes without `CHROME` on a machine set up for Playwright (issue #8). The folder names come from Playwright's own code, and a test checks the lookup on folders made for it. Not tried: a real Playwright download found this way. The render in issue #8 used that Chromium with `CHROME` set.
- `motlab render --only 3` (or `--only 3,5`) re-renders only the scenes you name, plus the transitions touching them, and takes the rest from the cache in `~/.cache/motlab/parts` (`%LOCALAPPDATA%\motlab\parts` on Windows, or `MOTLAB_CACHE_DIR`), which a full render leaves behind. A scene with no cached part is rendered, so `--only` on a project that was never rendered works like a full render. A finished render removes the cached parts it did not use, so the cache holds the last render only and `--only` needs the same `--scale` as that render. The cache key holds the motlab version, so parts made by an older version are rendered again after an update. The cache keys on the scene page itself: a file the scene loads changing (a shared script, a font, a picture) is not noticed, so render the whole project again then. Checked on the example project (3 scenes, 9 s, 1080p) on Ubuntu 24.04 with no GPU, SwiftShader, while other builds were running on the same machine: a full render took 44 to 49 s, `--only 3` took 17 to 24 s. The --only output differs from a full render by the same amount two full renders differ from each other (average PSNR 68.9 dB in both cases, from the encoder's run-to-run variation). `test/render.test.js` renders a project, changes one scene, re-renders with `--only` and checks the frame count, the cached log line, the colours of the cached, transition and re-rendered frames, and that the old parts are gone.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 0e273f4..79c9794 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -47,7 +47,7 @@ The code is plain JavaScript ESM with JSDoc, no TypeScript and no build step, be
npm test
```
-`test/codecs.test.js` checks the frame maths. `test/render.test.js` renders `test/fixtures/basic.html` through every path (default encoder, software, raw mux, three workers, audio, stills, events) and checks the frame count, duration, colour tags and decoded colour values. It also renders a WebM footage clip, projects with a transition, with a transition from a `.glsl` file and with scenes of different sizes, a project again with `--only`, and a project three parts at a time with one part failing. It needs Chrome and ffmpeg. The others need neither: `motion.test.js` checks the easings, springs, keyframes, transition names and how a `.glsl` transition's uniforms are read, `chrome.test.js` the `--no-sandbox` flag and the lookup of Playwright's Chromium, `server.test.js` that a file stream closes when its request is aborted, `install.test.js` what setup, `--update` and uninstall write and remove, `notes.test.js` how the viewer's notes merge into `selection.json`, `skills.test.js` the skills' frontmatter, and `editor-text.test.js` the viewer's `TEXT` table.
+`test/codecs.test.js` checks the frame maths. `test/render.test.js` renders `test/fixtures/basic.html` through every path (default encoder, software, raw mux, three workers, audio, stills, events) and checks the frame count, duration, colour tags and decoded colour values. It also renders a WebM footage clip, two scenes from sections of one recording, projects with a transition, with a transition from a `.glsl` file and with scenes of different sizes, a project again with `--only`, and a project three parts at a time with one part failing. It needs Chrome and ffmpeg. The others need neither: `motion.test.js` checks the easings, springs, keyframes, transition names and how a `.glsl` transition's uniforms are read, `chrome.test.js` the `--no-sandbox` flag and the lookup of Playwright's Chromium, `server.test.js` that a file stream closes when its request is aborted, `install.test.js` what setup, `--update` and uninstall write and remove, `cuts.test.js` how cut list sections and captions are placed, `notes.test.js` how the viewer's notes merge into `selection.json`, `skills.test.js` the skills' frontmatter, and `editor-text.test.js` the viewer's `TEXT` table.
If you touch the renderer, include the render time of the sample project before and after: `motlab render example --scale 1`.
diff --git a/ROADMAP.md b/ROADMAP.md
index 11269eb..599ba0e 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -7,7 +7,6 @@ What is not built, what has not been tested, and ideas that came up while using
- Alpha output (ProRes 4444).
- The viewer on a VPS with a domain. That needs security in front of it, or access only through Tailscale, which is also worth considering. From there, work could be run remotely on the personal laptop (when it is on) or on the VPS (when there is one).
- A transition as a layer over the cut (a swish of shapes) in `project.json`. It exists as the asset skill's `transition.js`, but each of the two scene pages has to draw its half by hand. Shader transitions from a `.glsl` file in the project are built.
-- A cut list that splits one recording over several scenes by section, with captions placed from a transcript. `cuts.js` has the time map (`toOut`), but each section page still picks its part of the list by hand.
- A dark mode for the viewer. Its colours are written into the CSS and the timeline's canvas code, so they need to become tokens with dark values checked for contrast first.
## Not tested yet
@@ -20,7 +19,7 @@ What is not built, what has not been tested, and ideas that came up while using
- A machine without a GPU beyond the tests. CI runs the end-to-end tests on Linux and Windows runners without a GPU, and the benchmark ran with Chrome drawing on SwiftShader on the test laptop (1080p and 4K, in `docs/rendering.md`). A real video has been rendered on such a machine now: a 42 s, 1080x1920 project on Ubuntu 24.04 with no GPU, in about 82 s (issue #8). No 3D (WebGL) scene has been rendered on one yet.
- Footage filmed on a phone (variable frame rate and HEVC were tested with files made by ffmpeg), and HEVC on a Chrome that cannot decode it.
- Scene transitions between scenes of different sizes in the viewer, and in a normal Chrome window. The render refuses scenes of different sizes.
-- The cut voice from `cut_pauses.py` on a real person's take. The whole-take test used Windows text to speech.
+- The cut voice from `cut_pauses.py` on a real person's take. The whole-take test used Windows text to speech. Sections and captions were tested on made-up recordings and a transcript shaped like Whisper's, not on a real take or real Whisper output.
- A `.glsl` transition copied from gl-transitions beyond the 11 built in, and one matched to a real reference video by the skill.
- Rive, Lottie text layers exported with glyphs, Theatre.js state exported from its studio, and the studio inside the viewer.
- p5.js `loadFont` and p5 add-on libraries.
diff --git a/docs/projects.md b/docs/projects.md
index ad4aed2..da9ce9b 100644
--- a/docs/projects.md
+++ b/docs/projects.md
@@ -170,4 +170,34 @@ window.renderAt = async t => { await window.ready; await edit.draw(ctx, t, 0, 0,
Tested on the first 40 s of a 1440x1440 talking-head recording: 10 parts, 38.64 s of take to 33.47 s, and the cut voice WAV was the same length as the cut list, with and without a 0.12 s dissolve. A 1080x1920 render of two 12 s scenes from it encoded at 55 to 72 fps on the test laptop (RTX 3060 Laptop). A whole 10-minute take (Windows text to speech with pauses of 0.4 to 2.5 s, over a pink noise room tone) went from 619.4 s to 384.4 s in 240 parts in 60 s. No part starts or ends inside a word: the clean voice is at least 38 dB below its speech level in the first and last 20 ms of every part. None of the 239 joins in the cut voice WAV clicks. Listened to with earshot: no clipping, the same loudness through the take (-20 LUFS), and 0.3 s gaps where sentences meet. A synthetic voice says little about how natural a real person sounds with these settings, so listen to the first real take.
+### One take over several scenes, with captions
+
+A long take can be split into scenes by section, so the viewer, notes and `--only` work per section. Name the sections and where each starts, in seconds of the recording:
+
+```bash
+python skills/motlab/scripts/cut_pauses.py footage/talk.mp4 cuts.json --audio-out audio/voice-cut.wav --sections hook=0,demo=41.5,outro=96
+```
+
+That adds `"sections": [{ "name": "hook", "from": 0 }, ...]` to `cuts.json` (it can also be written by hand) and prints where each section lands in the edit. Each scene then plays its own section, and its `TOTAL` is that section's length:
+
+```js
+const edit = cutList(cuts, clip, { section: 'demo', punch: [1, 1.12], glide: 0.25 });
+window.TOTAL = edit.duration; // set it before window.ready resolves
+```
+
+- A section starts at the cut nearest its `from` and runs to the cut where the next section starts, so a scene never starts in the middle of a part. Scene time 0 is that cut.
+- `edit.offset` is where the section starts in the whole edit. Put the scenes in `project.json` in section order with hard cuts, and the cut voice once at `start: 0`: the scenes' lengths add up to the cut list's, so the voice stays in step. With a dissolve, a section ends where the next one's first part starts, so the dissolve at that cut becomes a hard cut in the picture while the voice keeps its crossfade. A scene transition between sections would shorten the video and move the voice out of step.
+- `punch` alternates over the whole list, as it would in one scene.
+
+`edit.captions(transcript)` places a transcript of the recording on the scene's time and groups it into lines for burned-in captions. The transcript is Whisper's JSON with word times (`{ "segments": [{ "words": [{ "word", "start", "end" }] }] }`, from `whisper talk.mp4 --word_timestamps True --output_format json` with OpenAI's Whisper), or a plain list of `{ "text", "start", "end" }`, in seconds of the recording. motlab does not make the transcript.
+
+```js
+const lines = edit.captions(await (await fetch('../transcript.json')).json(), { maxChars: 32, maxGap: 0.6, hold: 0.3, shift: 0 });
+const line = lines.find(l => t >= l.start && t < l.end); // { text, start, end, words: [{ text, start, end }] }
+```
+
+Words that start inside a cut pause, or outside the section, are left out. A line ends at a pause longer than `maxGap` seconds, after a word ending in `.`, `?` or `!`, or before it would pass `maxChars` characters, and stays up `hold` seconds after its last word unless the next line starts sooner. `shift` moves every word by that many seconds before it is placed: Whisper's word times were about 0.23 s early in one take, so check by ear. Each word has its own time for a word-by-word highlight.
+
+Tested: `test/cuts.test.js` checks where sections start and that they add up to the whole edit, with and without a dissolve, and how captions are placed and broken into lines; `test/render.test.js` renders two section scenes from one recording whose frames each have their own grey and checks that all 24 output frames show the right source frame. `cut_pauses.py --sections` on a made-up 8 s take printed the same section starts and lengths as `cutList`. Not tried: a real transcript from Whisper (its JSON shape is from its documentation) and a real talking-head take split into sections.
+
The skill's [footage reference](../skills/motlab/references/footage.md) covers editing footage into a video.
diff --git a/skills/motlab/SKILL.md b/skills/motlab/SKILL.md
index dacd4c7..29404c6 100644
--- a/skills/motlab/SKILL.md
+++ b/skills/motlab/SKILL.md
@@ -280,9 +280,10 @@ and how to install it before you start.
- `get_font.py`: searches the Google Fonts catalog and downloads a family into the project. `templates/font-specimen.html`
shows the downloaded fonts side by side for `motlab stills`.
- In every scene page: `/__motlab/motion.js` (easings, `cubicBezier`, `spring`, `tween`, `stagger`, `motionBlur`),
- `/__motlab/footage.js` (video files) and `/__motlab/cuts.js` (a cut list over one recording).
-- `cut_pauses.py`: cuts the pauses out of a talking-head recording into `cuts.json`, and with `--audio-out` writes the
- voice with the same cuts.
+ `/__motlab/footage.js` (video files) and `/__motlab/cuts.js` (a cut list over one recording, by section, with
+ captions from a transcript).
+- `cut_pauses.py`: cuts the pauses out of a talking-head recording into `cuts.json`, with `--audio-out` writes the
+ voice with the same cuts, and with `--sections` splits the take into one scene per section.
- `mix.py`: puts library sounds on the page's events at a level set by their role, lowers them under a voiceover,
reports how close each landed and which moments to listen to. `synth_sfx.py`: builds a free sound kit. `get_sfx.py`: finds openly licensed sounds on
Openverse and downloads them with a `CREDITS.md`. If the user has earshot (`earshot --help` runs, or its MCP tools
diff --git a/skills/motlab/references/footage.md b/skills/motlab/references/footage.md
index 5d44c9a..47b6f7b 100644
--- a/skills/motlab/references/footage.md
+++ b/skills/motlab/references/footage.md
@@ -65,7 +65,7 @@ audio track. Pull a contact sheet to see what is in it: `ffmpeg -i demo.mp4 -vf
## Talking heads: cut the pauses
One scene per jump cut makes dozens of pages, each with its own decoder. Cut the pauses into a list instead and play
-it in one scene (or one scene per section, each with its part of the list):
+it in one scene, or in one scene per section (below):
```bash
python3 scripts/cut_pauses.py footage/talk.mp4 cuts.json --start 1.4 --audio-out audio/voice-cut.wav
@@ -90,6 +90,33 @@ window.renderAt = async t => { await window.ready; await edit.draw(ctx, t, 0, 0,
- Listen to the cut voice before building on it. Raise `--min-pause` if a deliberate pause was cut, and raise
`--keep-tail` or `--keep-lead` if a cut clips the end or start of a word.
+### One take, several scenes, captions
+
+For a take longer than about 30 s, make one scene per section (hook, each point, the close), so the user's notes and
+`--only` point at a section. Read the transcript, pick where each section starts, and pass the times in seconds of the
+recording; each moves to the nearest cut and the script prints where every section lands:
+
+```bash
+python3 scripts/cut_pauses.py footage/talk.mp4 cuts.json --audio-out audio/voice-cut.wav --sections hook=0,tip1=18.2,tip2=47.9,close=81
+```
+
+```js
+const cuts = await (await fetch('../cuts.json')).json();
+const edit = cutList(cuts, clip, { section: 'tip1', punch: [1, 1.12], glide: 0.25 });
+window.TOTAL = edit.duration; // inside window.ready, before it resolves
+const lines = edit.captions(await (await fetch('../transcript.json')).json(), { maxChars: 28 });
+```
+
+- List the section scenes in order with hard cuts and put `audio/voice-cut.wav` once at `start: 0`; the scenes add up
+ to the cut voice. No scene transitions between sections: they shorten the video and the voice drifts.
+- `edit.captions(transcript)` takes Whisper's JSON with word times (`whisper talk.mp4 --word_timestamps True
+ --output_format json`) or a list of `{ text, start, end }`, in seconds of the recording, and returns lines
+ `{ text, start, end, words }` in the scene's time. Draw the line where `start <= t < end` with the style's caption
+ rules, and use `words` for a word-by-word highlight. `maxChars` 24 to 32 suits a phone; `shift` moves every word
+ if the captions run early (0.23 s in one take).
+- motlab does not transcribe. If there is no transcript, ask the user for one or whether to install Whisper; do not
+ install it unasked. Without one, ask the user where each section starts.
+
## Footage sound
List the video file in `project.json` like any audio file, with `from` (seconds into the file) and `duration`:
diff --git a/skills/motlab/scripts/cut_pauses.py b/skills/motlab/scripts/cut_pauses.py
index 99ea7d8..1d00b20 100644
--- a/skills/motlab/scripts/cut_pauses.py
+++ b/skills/motlab/scripts/cut_pauses.py
@@ -8,6 +8,8 @@
# [--keep-tail 0.12] [--keep-lead 0.08] seconds kept after speech stops and before it starts again
# [--drop 61.2-63.0,90-91.5] more parts of the file to leave out (a fluffed line)
# [--dissolve 0.12] parts overlap and fade by this long instead of cutting hard
+# [--sections hook=0,demo=41.5,end=96] one scene per section: names and where each starts (seconds in the
+# file, moved to the nearest cut), for cutList(..., { section: 'demo' })
#
# Run it from the project folder; the paths in cuts.json are relative to it. Listen to the result: a pause that was a
# deliberate beat may need --min-pause raised, and a cut that clips a word needs more --keep-tail or --keep-lead.
@@ -48,9 +50,20 @@ def main():
segs = [{'from': round(a, 3), 'to': round(b, 3)} for a, b in keep]
length = sum(s['to'] - s['from'] for s in segs) - D * (len(segs) - 1)
data = {'source': src.replace('\\', '/'), 'dissolve': D, 'duration': round(length, 3), 'segments': segs}
+ sections = [(n.strip(), float(v)) for n, v in (x.split('=') for x in opt('--sections', '', str).split(',') if x)]
+ # The same rule as cutList in cuts.js: a section starts at the cut nearest its time and runs to the next section.
+ at = [sum(s['to'] - s['from'] - D for s in segs[:k]) for k in range(len(segs))]
+ first = [min(range(len(segs)), key=lambda k: abs(segs[k]['from'] - v)) for _, v in sections] + [len(segs)]
+ for i, (n, _) in enumerate(sections):
+ if first[i + 1] <= first[i]: sys.exit(f'section {n} starts at the same cut as the next one: move one of them')
+ if sections: data['sections'] = [{'name': n, 'from': v} for n, v in sections]
os.makedirs(os.path.dirname(os.path.abspath(out)), exist_ok=True)
with open(out, 'w', encoding='utf-8') as f: json.dump(data, f, indent=1)
print(f'{len(segs)} parts kept, {end - start:.2f} s of the take became {length:.2f} s -> {out}')
+ for i, (n, _) in enumerate(sections):
+ a, b = first[i], first[i + 1]
+ print(f' section {n}: from {segs[a]["from"]:.2f} s in the file, {at[a]:.2f} s into the edit, '
+ f'{(at[b] if b < len(segs) else length) - at[a]:.2f} s long ({b - a} part{"s" if b - a > 1 else ""})')
audio = opt('--audio-out', None, str)
if audio: # the same cuts on the sound: 5 ms fades at each cut so it does not click, or crossfades for a dissolve
diff --git a/src/page/cuts.js b/src/page/cuts.js
index 7521e04..300cb10 100644
--- a/src/page/cuts.js
+++ b/src/page/cuts.js
@@ -5,7 +5,7 @@ import { clamp, ease, lerp } from './motion.js';
// cuts (skills/motlab/scripts/cut_pauses.py writes the list from the pauses in the voice).
//
// const { cutList } = await import('/__motlab/cuts.js');
-// const cuts = await (await fetch('../cuts.json')).json(); // { segments: [{ from, to }, ...], dissolve }
+// const cuts = await (await fetch('../cuts.json')).json(); // { segments: [{ from, to }, ...], dissolve, sections }
// const edit = cutList(cuts, clip, { punch: [1, 1.12], glide: 0.2, drift: 0.01, x: 0.5, y: 0.4 });
// await edit.draw(ctx, t, 0, 0, W, H); // the frame at t seconds into the edit
//
@@ -15,18 +15,35 @@ import { clamp, ease, lerp } from './motion.js';
// (per second) so a part is never still. With `dissolve` (seconds, from the cut list or the options) parts overlap and
// fade into each other; that needs a second decoder of the same file as `clip2`, because both parts are drawn at once.
// edit.toOut(seconds in the file) gives the time in the edit, for words from a transcript of the recording.
-export function cutList(cuts, clip, { clip2 = null, punch = [1], glide = 0, drift = 0, x = 0.5, y = 0.5, dissolve, ease: easing = 'inOutCubic' } = {}) {
+//
+// `section` (a name or a 0-based index into cuts.sections) plays one section of the list, so a long take can be one
+// scene per section. A section is [{ name, from }, ...] in seconds of the recording, and starts at the cut nearest its
+// `from`; it runs to the cut where the next one starts. Its scene's time 0 is that cut, and `offset` is where it starts
+// in the whole edit, so scenes of consecutive sections joined by hard cuts stay in step with the cut voice.
+// edit.captions(transcript) places the transcript's words on the scene's time, grouped into caption lines.
+export function cutList(cuts, clip, { clip2 = null, punch = [1], glide = 0, drift = 0, x = 0.5, y = 0.5, dissolve, ease: easing = 'inOutCubic', section } = {}) {
const list = Array.isArray(cuts) ? cuts : cuts.segments, D = dissolve ?? cuts.dissolve ?? 0;
if (!list?.length) throw new Error('cutList: no segments');
if (D > 0 && !clip2) throw new Error('cutList: a dissolve needs clip2, a second openFootage() of the same file');
let at = 0;
- const parts = list.map((s, i) => {
+ const all = list.map((s, i) => {
const len = s.to - s.from;
if (!(len > D)) throw new Error(`cutList: segment ${i + 1} (${s.from} to ${s.to}) is not longer than the dissolve`);
const p = { from: s.from, to: s.to, len, at, zoom: s.zoom ?? punch[i % punch.length], x: s.x ?? x, y: s.y ?? y };
at += len - D; return p;
});
- const duration = at + D, E = ease[easing];
+ const whole = at + D, E = ease[easing];
+ let parts = all, offset = 0, duration = whole, name = null;
+ if (section !== undefined) {
+ const sections = cuts.sections;
+ if (!Array.isArray(sections) || !sections.length) throw new Error('cutList: the cut list has no "sections"');
+ const k = typeof section === 'number' ? section : sections.findIndex(s => s.name === section);
+ if (!sections[k]) throw new Error(`cutList: no section ${JSON.stringify(section)}; the sections are ${sections.map(s => s.name).join(', ')}`);
+ const first = sectionStart(all, sections[k].from), next = k + 1 < sections.length ? sectionStart(all, sections[k + 1].from) : all.length;
+ if (next <= first) throw new Error(`cutList: section ${JSON.stringify(sections[k].name)} starts at the same cut as the one after it, so it has no parts`);
+ offset = all[first].at; duration = (next < all.length ? all[next].at : whole) - offset; name = sections[k].name;
+ parts = all.slice(first, next).map(p => ({ ...p, at: p.at - offset }));
+ }
const index = t => { let k = 0; while (k + 1 < parts.length && parts[k + 1].at <= t + 1e-9) k++; return k; };
const zoomAt = (k, t) => { // the zoom of part k at edit time t
const p = parts[k], into = t - p.at, z = k && glide > 0 ? lerp(parts[k - 1].zoom, p.zoom, E(clamp(into / glide))) : p.zoom;
@@ -39,13 +56,37 @@ export function cutList(cuts, clip, { clip2 = null, punch = [1], glide = 0, drif
ctx.save(); ctx.beginPath(); ctx.rect(dx, dy, dw, dh); ctx.clip(); ctx.globalAlpha = alpha;
f.draw(ctx, ox, oy, w, h); ctx.restore();
}
+ // A word's time in this edit, or null when its start was cut out or lies outside this section.
+ const place = src => { const p = parts.find(p => src >= p.from && src < p.to); return p && p.at + (src - p.from) < duration ? p : null; };
return {
- duration, parts,
+ duration, parts, offset, section: name,
at(t) { const k = index(t), p = parts[k]; return { index: k, src: p.from + (t - p.at), zoom: zoomAt(k, t) }; },
toOut(src) {
for (const p of parts) { if (src < p.from) return p.at; if (src <= p.to) return p.at + (src - p.from); }
return duration;
},
+ // transcript: Whisper's JSON ({ segments: [{ words: [{ word, start, end }] }] }) or a list of { word or text, start,
+ // end }, in seconds of the recording. Words whose start was cut out are left out. A line ends at a pause longer
+ // than maxGap, after . ? or !, or before it would pass maxChars, and stays up for `hold` seconds after its last word
+ // unless the next line starts sooner. `shift` moves every word (Whisper's times were 0.23 s early in one take).
+ captions(transcript, { maxChars = 32, maxGap = 0.6, hold = 0.3, shift = 0 } = {}) {
+ const words = [];
+ for (const w of transcriptWords(transcript)) {
+ const start = w.start + shift, p = place(start);
+ if (!p) continue;
+ const end = Math.min(Math.max(w.end + shift, start), p.to);
+ words.push({ text: w.text, start: p.at + (start - p.from), end: Math.min(p.at + (end - p.from), duration) });
+ }
+ const lines = [];
+ for (const w of words) {
+ const line = lines.at(-1), last = line?.words.at(-1);
+ if (line && !(w.start - last.end > maxGap || /[.?!]["')\]]*$/.test(last.text) || line.text.length + 1 + w.text.length > maxChars)) {
+ line.words.push(w); line.text += ' ' + w.text; line.end = w.end;
+ } else lines.push({ text: w.text, start: w.start, end: w.end, words: [w] });
+ }
+ lines.forEach((l, i) => { l.end = Math.min(l.end + hold, lines[i + 1]?.start ?? duration, duration); });
+ return lines;
+ },
async draw(ctx, t, dx, dy, dw, dh) {
t = clamp(t, 0, duration - 1e-6);
const k = index(t), into = t - parts[k].at;
@@ -57,3 +98,16 @@ export function cutList(cuts, clip, { clip2 = null, punch = [1], glide = 0, drif
},
};
}
+
+// The part a section starts with: the one whose start (the cut before it) is nearest `from`.
+function sectionStart(parts, from) {
+ let best = 0;
+ parts.forEach((p, k) => { if (Math.abs(p.from - from) < Math.abs(parts[best].from - from)) best = k; });
+ return best;
+}
+
+function transcriptWords(t) {
+ const list = Array.isArray(t) ? t : t?.segments ? t.segments.flatMap(s => s.words ?? []) : t?.words ?? [];
+ return list.map(w => ({ text: String(w.word ?? w.text ?? '').trim(), start: Number(w.start), end: Number(w.end) }))
+ .filter(w => w.text && Number.isFinite(w.start) && Number.isFinite(w.end)).sort((a, b) => a.start - b.start);
+}
diff --git a/test/cuts.test.js b/test/cuts.test.js
new file mode 100644
index 0000000..96c270b
--- /dev/null
+++ b/test/cuts.test.js
@@ -0,0 +1,42 @@
+import assert from 'node:assert/strict';
+import { test } from 'node:test';
+import { cutList } from '../src/page/cuts.js';
+
+const ms = v => Math.round(v * 1000) / 1000; // times to the millisecond, past float noise
+const near = (a, b, d = 1e-9) => assert.ok(Math.abs(a - b) <= d, `${a} is not within ${d} of ${b}`);
+// four parts of 4 s with 1 s pauses cut out between them
+const segments = [{ from: 0, to: 4 }, { from: 5, to: 9 }, { from: 10, to: 14 }, { from: 15, to: 19 }];
+const sections = [{ name: 'hook', from: 0 }, { name: 'rest', from: 9.6 }]; // 9.6 is nearest the cut at 10
+const transcript = { segments: [{ words: [
+ { word: ' Hello', start: 1.0, end: 1.4 }, { word: ' world.', start: 1.5, end: 2.0 }, { word: ' this', start: 2.6, end: 2.9 },
+ { word: ' is', start: 3.0, end: 3.2 }, { word: ' um', start: 4.3, end: 4.6 }, { word: ' kept', start: 5.2, end: 5.5 },
+] }, { words: [{ word: ' Next', start: 10.2, end: 10.5 }, { word: ' part', start: 10.6, end: 11.0 }] }] };
+
+test('cut list sections: each starts at the cut nearest its time, and the sections add up to the whole edit', () => {
+ const whole = cutList({ segments }, null), hook = cutList({ segments, sections }, null, { section: 'hook' }), rest = cutList({ segments, sections }, null, { section: 1 });
+ assert.equal(whole.duration, 16);
+ assert.deepEqual([hook.duration, hook.offset, hook.parts.length, hook.section], [8, 0, 2, 'hook']);
+ assert.deepEqual([rest.duration, rest.offset, rest.parts.map(p => p.at)], [8, 8, [0, 4]]);
+ near(rest.toOut(12), 2); near(rest.at(5).src, 16);
+ // with a dissolve the parts overlap; a section ends where the next one's first part starts, so the sum still holds
+ const D = 0.5, wd = cutList({ segments, dissolve: D }, null, { clip2: {} });
+ const a = cutList({ segments, sections, dissolve: D }, null, { clip2: {}, section: 'hook' }), b = cutList({ segments, sections, dissolve: D }, null, { clip2: {}, section: 'rest' });
+ near(a.duration + b.duration, wd.duration); assert.deepEqual([a.duration, b.offset], [7, 7]);
+ // punch keeps alternating across the whole list, not per section
+ assert.deepEqual(cutList({ segments, sections }, null, { punch: [1, 1.2], section: 'rest' }).parts.map(p => p.zoom), [1, 1.2]);
+ assert.throws(() => cutList({ segments }, null, { section: 'hook' }), /no "sections"/);
+ assert.throws(() => cutList({ segments, sections }, null, { section: 'outro' }), /no section "outro"; the sections are hook, rest/);
+ assert.throws(() => cutList({ segments, sections: [{ name: 'a', from: 9.8 }, { name: 'b', from: 10.1 }] }, null, { section: 'a' }), /same cut as the one after it/);
+});
+
+test('captions: words land on the scene time, cut words are dropped, and lines break at pauses, sentences and length', () => {
+ const hook = cutList({ segments, sections }, null, { section: 'hook' }), rest = cutList({ segments, sections }, null, { section: 'rest' });
+ const lines = hook.captions(transcript);
+ assert.deepEqual(lines.map(l => l.text), ['Hello world.', 'this is', 'kept']); // "um" sat in a cut pause
+ assert.deepEqual(lines.map(l => [ms(l.start), ms(l.end)]), [[1, 2.3], [2.6, 3.5], [4.2, 4.8]]);
+ assert.deepEqual(rest.captions(transcript).map(l => [l.text, ms(l.start)]), [['Next part', 0.2]]);
+ assert.deepEqual(hook.captions(transcript, { maxChars: 8 }).map(l => l.text), ['Hello', 'world.', 'this is', 'kept']);
+ // shift moves every word before it is placed; a flat list of { text, start, end } works too
+ assert.deepEqual(rest.captions([{ text: 'late', start: 10.0, end: 10.2 }], { shift: 0.25 }).map(l => ms(l.start)), [0.25]);
+ assert.deepEqual(cutList({ segments }, null).captions([{ text: 'late', start: 10.0, end: 10.2 }]).map(l => l.start), [8]);
+});
diff --git a/test/render.test.js b/test/render.test.js
index b35f8fa..8e3ac47 100644
--- a/test/render.test.js
+++ b/test/render.test.js
@@ -97,6 +97,34 @@ test('footage: a WebM clip shows the right frame at every time, though Matroska
assert.deepEqual(wrong, [], `source greys ${src}`);
});
+test('cut list sections: two scenes play their own parts of one recording, back to back, with TOTAL set in ready', async () => {
+ const proj = join(dir, 'sections'), clip = join(proj, 'take.webm');
+ mkdirSync(proj);
+ // 3 s at 10 fps, each frame a grey 7 levels lighter than the one before
+ spawnSync('ffmpeg', ['-v', 'error', '-f', 'lavfi', '-i', 'nullsrc=s=64x64:r=10:d=3,geq=lum=16+N*7:cb=128:cr=128', '-c:v', 'libvpx-vp9', '-b:v', '2M', '-pix_fmt', 'yuv420p', clip]);
+ // three parts of 0.8 s; section "b" asks for 1.9 s, which moves it to the cut at 2.0 s
+ writeFileSync(join(proj, 'cuts.json'), JSON.stringify({ segments: [{ from: 0, to: 0.8 }, { from: 1, to: 1.8 }, { from: 2, to: 2.8 }], sections: [{ name: 'a', from: 0 }, { name: 'b', from: 1.9 }] }));
+ for (const name of ['a', 'b']) writeFileSync(join(proj, `${name}.html`), `<!doctype html><canvas id="c" width="64" height="64"></canvas><script>
+ const ctx = document.getElementById('c').getContext('2d'); let edit;
+ window.ready = (async () => {
+ const clip = await (await import('/__motlab/footage.js')).openFootage('take.webm'), { cutList } = await import('/__motlab/cuts.js');
+ edit = cutList(await (await fetch('cuts.json')).json(), clip, { section: '${name}' }); window.TOTAL = edit.duration; return true;
+ })();
+ window.renderAt = async t => { await window.ready; await edit.draw(ctx, t, 0, 0, 64, 64); };</script>`);
+ writeFileSync(join(proj, 'project.json'), JSON.stringify({ fps: 10, scenes: ['a.html', 'b.html'] }));
+ const out = join(dir, 'sections.mp4');
+ await renderProject({ dir: proj, out, scale: 1, ...quiet });
+ assert.equal((await probeVideo(out)).frames, 24); // section a: 16 frames, section b: 8
+ const grey = (file, f) => meanRgb(file, '32:32:16:16', f)[1];
+ const src = Array.from({ length: 30 }, (_, f) => grey(clip, f)), wrong = [];
+ const want = f => f < 8 ? f : f < 16 ? 10 + f - 8 : 20 + f - 16; // the source frame each output frame should show
+ for (let f = 0; f < 24; f++) {
+ const g = grey(out, f), shown = src.reduce((b, v, i) => Math.abs(v - g) < Math.abs(src[b] - g) ? i : b, 0);
+ if (shown !== want(f)) wrong.push(`frame ${f} showed source frame ${shown}, not ${want(f)}`);
+ }
+ assert.deepEqual(wrong, [], `source greys ${src}`);
+});
+
test('project: a transition overlaps two scenes and mixes them on the frame grid', async () => {
const proj = join(dir, 'proj'), flat = (name, colour) => writeFileSync(join(proj, name), `<!doctype html><canvas id="c" width="320" height="180"></canvas><script>
const c = document.getElementById('c').getContext('2d'); window.TOTAL = 1; window.ready = Promise.resolve(true);