DEV Community

Vladyslav Tarasenko
Vladyslav Tarasenko

Posted on Fully Autonomous

Motion graphics an editor can't do: render them with headless Edge, place them as clips

Part 4 of a series on Movie Engine, where an AI agent edits Kdenlive video projects while the editor stays open. Earlier parts: 1, overview, 2, UI Automation without stealing focus, 3, menu names from translation files.

Kdenlive is a good editor, but its engine (MLT) has no per-letter text animation, no expressions, little 3D, and heavy effects slow playback down. When an AI agent is building the cut, the temptation is to quietly use a weaker effect. Movie Engine has a rule against that: whatever Kdenlive can't do is generated by code outside, then placed on the timeline as an ordinary clip. The user still sees and trims it in Kdenlive like any other clip.

This post walks through the three generator styles in the repo and the plumbing they share.

The contract: a scene is a pure function of time

engine/tools/html-render.mjs renders any HTML/CSS/canvas page to video. The page defines three things:

window.SCENE = { fps: 30, frames: 90, width: 1920, height: 1080 }
window.ready = /* a promise: fonts and images loaded */
window.render = t => { /* draw the moment t (seconds) */ }
Enter fullscreen mode Exit fullscreen mode

Because render(t) depends on nothing but t, any frame can be drawn on its own, out of order, in a separate browser. That is what makes parallel rendering and motion blur trivial. The demo in examples/demo/scene/scene.html is a title card with a 3D flip, a cursor and a click ripple:

window.render = t => {
  const flip = out(span(t, 0.1, 0.9))
  const press = span(t, CLICK, 0.12) - span(t, CLICK + 0.12, 0.3)
  $('card').style.transform =
    `rotateX(${lerp(-80, 0, flip)}deg) scale(${lerp(0.8, 1, back(span(t, 0.1, 0.9))) - 0.04 * press})`
  $('card').style.opacity = flip
  // ...cursor path and ripple
}
Enter fullscreen mode Exit fullscreen mode

Headless Edge, no network, no window

Every Windows 10/11 machine has Microsoft Edge, so the renderer drives it over the DevTools protocol instead of shipping Chromium. It starts Edge headless with a throw-away profile and a resolver rule that maps every host to nothing, so a scene can only load local files:

spawn(findBrowser(), [
  '--headless=new', '--remote-debugging-port=0', `--user-data-dir=${profile}`,
  '--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1',
  '--allow-file-access-from-files',
  '--force-color-profile=srgb', '--force-device-scale-factor=1', '--hide-scrollbars',
  'about:blank'
], { stdio: 'ignore', windowsHide: true })
Enter fullscreen mode Exit fullscreen mode

--remote-debugging-port=0 picks a free port, which Edge writes to DevToolsActivePort in the profile; the script reads it and connects with a plain WebSocket. The browser runs at below-normal priority, because the user is working on the same PC.

Motion blur by sub-frame sampling

Each output frame is the average of 16 renders spread over half a frame interval (a 180° shutter, centred on the frame):

for (let s = 0; s < sub; s++) {
  const offset = sub > 1 ? ((s + 0.5) / sub - 0.5) / 2 : 0
  ffmpeg.stdin.write(await shoot(Math.max(0, f + offset) / scene.fps))
}
Enter fullscreen mode Exit fullscreen mode

The PNG screenshots are piped into the bundled ffmpeg at fps × 16, and ffmpeg does the averaging and the decimation:

filters.push(`tmix=frames=${sub}`, `select='eq(mod(n\\,${sub})\\,${sub - 1})'`, `setpts=N/(${scene.fps}*TB)`)
Enter fullscreen mode Exit fullscreen mode

Output is H.264 at CRF 12 with a 15-frame GOP, so the editor can seek quickly. The default --sub 16 is not arbitrary: with 4 samples a fast move shows visible steps. With --workers 5 the frame range is split between several Edge processes and the parts are joined with ffmpeg's concat demuxer without re-encoding. --frames 0,45 renders only check stills, which is what the agent looks at before spending minutes on a full render.

Long films: compose on the GPU, encode in the page

Screenshots are fine for a 3-second card, and slow for a 3-minute explainer. engine/tools/film-render.mjs with engine/tools/film/film-kit.js keeps everything inside the page: frames are drawn on an OffscreenCanvas, the motion-blur samples are accumulated into a canvas with 16-bit float colour, and WebCodecs encodes H.264 right there. Only finished video leaves the browser.

const sum = new OffscreenCanvas(W, H)
const sg = sum.getContext('2d', { colorType: 'float16' })
// for sample k of count: draw the foreground at time t + offset, then
sg.globalAlpha = 1 / (k + 1)     // running average
sg.drawImage(layer, 0, 0)
Enter fullscreen mode Exit fullscreen mode

The number of samples is adaptive. A "dry pass" draws the frame at t ± a quarter frame without painting, collects the positions of everything that moves, and picks enough samples that neighbouring samples are at most 2.5 px apart (1 to 56). A still shot costs one sample; a whip pan gets many. The docs give about 45 frames/s on a mid-range GPU, roughly 20 times faster than the screenshot path.

Films are written as data plus one line of direction per shot, with actions timed to the voice-over (@word fires when the voice says that word; that is the topic of the next post):

1 | hover 192 108 @brand | tag 300 60 Your brand @deserves | confetti 192 90 @film
3 | click 116 108 @before | click 268 108 @after | chips Before~After @after
Enter fullscreen mode Exit fullscreen mode

--check lists direction errors (an unknown action, a word the voice never says during that shot) and --shots all renders a still of every shot to review before the real render.

Overlays need alpha

A full-frame scene can be an mp4. Text and annotations that sit over footage need transparency. engine/tools/kinetic-text.ps1 (per-letter kinetic captions) and annotate.ps1 (hand-drawn circles, arrows, underlines that draw on) draw frames with System.Drawing into 32-bit ARGB bitmaps and encode a PNG-codec QuickTime file, which keeps the alpha channel:

& $ff -hide_banner -loglevel error -y -framerate $Fps -i (Join-Path $tmp 'f%04d.png') -c:v png -pix_fmt rgba $out
Enter fullscreen mode Exit fullscreen mode

The font is loaded from engine/fonts/Poppins-Bold.ttf with a PrivateFontCollection, so nothing is installed into Windows and the folder stays portable. One PowerShell trap worth knowing for animation code: [math]::Min(1, $v) picks the integer overload and rounds $v, so a 0..1 progress value jumps from 0 to 1. Type both arguments: [math]::Min([double]1, $v).

Putting the clip on the timeline

Generated files go to materials/aigenerated/<project>/, never overwriting, with the generator script kept next to the project, so a changed word or font means re-running the script, not redrawing by hand. Then two commands of the project CLI:

engine\kdp.ps1 bin-add -Project projects\demo\demo.kdenlive -File materials\aigenerated\demo\text-12.mov
engine\kdp.ps1 add -Project projects\demo\demo.kdenlive -Bin 5 -Track V2 -At 14.2   # 5 = the id bin-add printed
Enter fullscreen mode Exit fullscreen mode

Overlays go on their own track above the picture. If the picture clip has a push-in or whip, the same motion filters are copied onto the overlay so both move together. The open Kdenlive reloads and the user sees the clip appear (how that works safely is part 6).

Takeaways

  • Make every scene a pure function of time; parallelism and motion blur come for free.
  • Headless Edge plus DevTools is a renderer every Windows PC already has.
  • For long pieces, keep compositing and encoding inside the page (float16 canvas + WebCodecs).
  • Ship alpha overlays as PNG-in-MOV, and keep the generator so the clip can be regenerated.

Windows only, Kdenlive 26.08.3, MIT licensed: https://github.com/vladtarrow/movie-engine. To try it, clone the repo and run:

.\setup.cmd
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
hamza_h_02a9b1947e8355f3d profile image
Hamza •

Really clever setup! Making scenes a pure function of time with window.render(t) and exporting alpha overlays as PNG-in-MOV solves so many headaches when mixing web motion graphics with NLE timelines.

For anyone reading this who loves the HTML/CSS/Canvas-to-video workflow but doesn't want to maintain a local headless browser + FFmpeg pipeline, cloud renderers like VectoRender also handle direct HTML/SVG exports to MP4 and transparent MOV/WebM out of the box. Awesome write-up!