Part 5 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, 4, rendering what Kdenlive can't.
In explainer videos and shorts, the thing that makes captions feel "pro" is timing: a word pops up on screen at the moment the narrator says it, a highlight box grows under "stand out" exactly on "stand out", the cursor clicks on "after". Doing that by hand means scrubbing audio and nudging keyframes for hours.
Movie Engine gets those times for free from the voice-over itself. This post shows the pipeline: Edge TTS with word boundaries, a small voice.json file, and generators that read it.
One mp3 per line, plus word timings
engine/voice/voice.mjs uses the msedge-tts package, which talks to the same speech service as Microsoft Edge's read-aloud feature. No API key is needed. The input is a list of lines:
[{ "id": "037", "text": "The key is to make your brand stand out." }] Every line becomes its own mp3. That is a deliberate choice for editing: on the timeline each line is a separate clip, so the agent (or you) can move a line, cut between lines, or re-voice one without touching the others.
The important flag is wordBoundaryEnabled. With it, the service sends metadata events alongside the audio:
await tts.setMetadata(VOICE, OUTPUT_FORMAT.AUDIO_24KHZ_96KBITRATE_MONO_MP3, { wordBoundaryEnabled: true }); The offsets come in 100-nanosecond ticks, so dividing by 10^7 gives seconds:
const words = JSON.parse(fs.readFileSync(meta, "utf8")).Metadata .filter((m) => m.Type === "WordBoundary") .map((m) => ({ text: m.Data.text.Text, start: +(m.Data.Offset / 1e7).toFixed(3), end: +((m.Data.Offset + m.Data.Duration) / 1e7).toFixed(3), })); The real duration of each mp3 is measured with the ffprobe.exe that ships with Kdenlive, and everything lands in one file:
[{ "id": "037", "text": "The key is to make your brand stand out.", "file": "037.mp3", "duration": 2.904, "words": [{ "text": "The", "start": 0.1, "end": 0.212 }, { "text": "key", "start": 0.225, "end": 0.45 }, ...] }] (Numbers here are illustrative; the shape is exactly what voice.mjs writes.)
Cache per line, keyed by voice, rate and text
Scripts change. When I fix three lines out of eighty, I don't want eighty requests and eighty slightly different takes. Each line is cached under a hash of everything that affects the sound:
const key = crypto.createHash("sha1").update(`${VOICE}|${RATE}|${text}`).digest("hex").slice(0, 16); const dir = path.join(OUT, ".cache", key); if (fs.existsSync(audio) && fs.existsSync(meta)) reused++; else ({ audioFilePath: audio, metadataFilePath: meta } = await synthesize(text, dir)); Changing the voice (ru-RU-DmitryNeural) or the rate (+10%) naturally invalidates everything; editing one line re-voices only that line. The run ends with a summary like 80 lines (77 from cache), 312.4 s of speech.
The bug: one ampersand killed the stream
A line like "Terri & Sandy" failed every time with Stream closed before the synthesis completed. Nothing about the error points at the text.
The cause: msedge-tts puts your text into SSML unescaped. SSML is XML, a bare & makes the document invalid, and the service just closes the connection. The fix is three replacements before the text goes in:
// msedge-tts sends the text inside SSML unescaped: a bare "&" (e.g. "Terri & Sandy") kills the stream const ssml = text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"); return await tts.toFile(dir, ssml, { rate: RATE }); The service also drops connections now and then for no visible reason, so synthesize retries up to four times with a growing pause (1.5 s, 3 s, 4.5 s) and creates a fresh client each attempt.
Using the timings: kinetic text
engine/tools/kinetic-text.ps1 renders per-letter animated captions (letters rise, scale up with a slight overshoot and fade in one after another) to transparent .mov clips. Its input names the first frame of each word:
[{ "n": 234, "L": 139, "lines": ["The key is to make", "your brand stand out"], "hl": "stand out", "starts": [2, 4, 13, ...] }] starts is just the word times from voice.json converted to frames relative to the card, roughly round((word.start - cardStart) * fps). Each letter of a word starts a frame after the previous one, and the highlight box starts two frames after its first word:
[void]$letters.Add([pscustomobject]@{ ch = $w[$k]; ...; start = $ws + $k }) ... $hlBoxes += [pscustomobject]@{ x = $wx - 0.2 * $size; ...; start = $ws + 2 } Because the captions are baked into video, the cards.json is kept with the project and the output goes to materials/aigenerated/<project>/. Change a word or the voice, re-run, and the clip on the timeline is replaced with a new version (files are never overwritten).
Using the timings: actions in a film
For long explainer films (engine/tools/film-render.mjs), the direction is one line per shot and any action can be pinned to a word with @word:
3 | click 116 108 @before | click 268 108 @after | chips Before~After @after The film kit flattens all words of all lines into one list and, for each @word, takes the first matching word that starts inside the shot (allowing 0.6 s of lead-in):
function wordTime (shot, word, report = true) { const key = norm(word) for (const w of words) { if (w.a < shot.t0 - 0.6) continue if (w.a > shot.t1) break if (w.w.startsWith(key)) return Math.max(shot.t0 + 0.05, w.a) } if (report) problems.push(`shot ${shot.n}: the voice does not say "${word}" during it`) return null } Matching is by prefix of a normalised word, so @brand also matches "brand's". When a word is missing, film-render.mjs --check reports it before any rendering starts, a typical error after a script edit: the line changed, the direction still refers to the old wording.
Why this matters for an AI editor
An agent can't "listen" to the cut. With word timings in a file, it doesn't need to: every timing decision is a lookup, every caption and click lands on the spoken word, and when the script changes the whole chain is re-generated in minutes. Speech recognition for footage you recorded yourself (Whisper or Vosk) is not included yet, because it needs a separate download.
Windows only, Kdenlive 26.08.3, MIT licensed: https://github.com/vladtarrow/movie-engine. To try it, clone the repo and run:
.\setup.cmd 