Skip to content

A Claude Code skill for editing talking-head, tutorial, explainer and Short videos: word-accurate cuts, GSAP scenes, synthesized sound effects, honest loudness.

Python

Add video-edit skill: word-accurate cuts, scene template, synthesized sound effects

Yıldız Dikme28b583c87372
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..e458dd6
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,6 @@
+__pycache__/
+*.pyc
+.DS_Store
+template/sfx/*.wav
+work/
+out/
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..c6e9e85
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 [YOUR NAME]
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..439f287
--- /dev/null
+++ b/README.md
@@ -0,0 +1,121 @@
+# video-edit: a Claude Code skill for editing videos
+
+A Claude Code skill for editing talking-head, tutorial, explainer and Short videos together with Claude:
+
+- cuts raw takes on real word edges, without clipping words
+- removes retakes and pauses
+- builds motion graphics as HTML + GSAP pages, locked to the spoken words
+- synthesizes sound effects in Python
+- keeps the voice clean and at the right loudness
+- renders frame-exact
+
+[Türkçe açıklama aşağıda](#türkçe).
+
+## Read this first
+
+Claude cannot hear. Everything this skill knows about sound is measured: word timestamps from Whisper, a 10 ms energy envelope, loudness meters. So the workflow is built around that:
+
+- **Cuts follow the measured energy, not guesses.** Each cut snaps to the real start and end of a word in the waveform.
+- **Picture and sound share one clock.** Graphics and sound effects are triggered from the same timeline, so effects land on the picture without anyone listening for sync.
+- **The voice is never processed by default.** No noise reduction, EQ or compression: one linear gain only. Those filters are the usual cause of muffled voices.
+- **A human reviews every stage.** Claude will not produce a perfect edit in one go. You work stage by stage: rough cut, review, chapters, graphics range by range, sound, final render. Expect corrections, and that is how good edits get made.
+
+## What is inside
+
+```
+SKILL.md the workflow Claude follows
+reference/audio.md cutting rules, loudness, sound effects, captions (the most important file)
+reference/style.md glass cards, neutral palette, typography, motion per video type, things to avoid
+reference/edl.md the edit-list format
+scripts/ transcribe, cuts, build, verify, loudness, sfx, mix (Python) · render, audit (Node)
+template/ a scene page: engine, glass-card styles, chapter veils, demo beats
+```
+
+## Install
+
+1. Requirements: Python 3.10+ with numpy, ffmpeg and ffprobe, Node 20+, and Google Chrome or Chromium. You also need one Whisper backend: `pip install faster-whisper` on any OS, or `brew install whisperkit-cli` on Apple Silicon.
+2. Put this folder where Claude Code finds skills, for example:
+
+```bash
+git clone <this repo> ~/.claude/skills/video-edit
+```
+
+3. Try the template without any footage:
+
+```bash
+cd ~/.claude/skills/video-edit
+python3 scripts/sfx.py lib --out template/sfx
+python3 scripts/serve.py --project . --port 5600
+```
+
+Open http://127.0.0.1:5600/template/?demo and press Space.
+
+## How to use it
+
+In your project folder, put the raw clips in `src/` and ask Claude, for example:
+
+> Edit these clips into a 10-minute educational video. Follow script.md. Cut retakes and pauses, natural pace. Propose chapters. Graphics calm, no sound effects. Neutral palette with our accent #2E7D6B.
+
+> This is a Short. Tight cuts, captions on, more energetic graphics, quiet effects on the highlights.
+
+Claude asks a few questions, transcribes, makes a rough cut, and hands you a preview with a list of what it decided. You give timestamps and corrections. Then it adds chapters, builds the graphics one range at a time, and renders when you approve.
+
+## Video types
+
+| Type | Graphics | Effects | Cuts |
+|---|---|---|---|
+| Educational / explainer | calm, clear diagrams, slow camera, three.js only when it explains | none or very quiet | natural |
+| Talk | few long-lasting cards, never over the face | quiet transitions | natural or tight |
+| Tutorial | zoom into the screen, highlight boxes, steps | optional soft clicks | natural |
+| Short | bigger, faster, hook in 2 s, captions | allowed, under the voice | tight |
+
+## Limits
+
+- Claude can't judge taste, emotion, or whether a mix "sounds good". Listen to every flagged join and every effect level.
+- Whisper makes mistakes with names and technical words. Check the transcript.
+- Rendering through a browser is slow, about 10 fps per worker at 1080p. Use several workers for long videos.
+
+## License
+
+MIT. See `LICENSE`.
+
+---
+
+## Türkçe
+
+Bu repo, Claude Code ile video editlemek için hazırlanmış bir skill. Konuşma, eğitim, ekran kaydı ve Short videolarında şunları yapar:
+
+- ham çekimleri kelime sınırlarından keser, kelimeleri kırpmaz
+- tekrar çekimleri ve duraksamaları çıkarır
+- konuşmaya kilitli animasyonları HTML + GSAP sayfaları olarak kurar
+- ses efektlerini Python ile matematikten üretir
+- sesi temiz ve doğru seviyede tutar
+- kare kare render alır
+
+### En önemli kısım
+
+Claude duymaz. Bu skill sesle ilgili her şeyi ölçerek yapar: Whisper kelime zamanları, 10 ms'lik enerji zarfı ve ses yüksekliği ölçümleri. Bu yüzden:
+
+- **Kesimler ölçülen enerjiye göre yapılır.** Kelime başları ve sonları dalga formundaki gerçek yerinden kesilir.
+- **Görüntü ve ses aynı saatten tetiklenir.** Animasyon da efekt de aynı zaman çizelgesinden çalıştığı için efekt görüntüye oturur.
+- **Ses varsayılan olarak işlenmez.** Gürültü azaltma, EQ ya da kompresör yok, sadece doğrusal kazanç var. Boğuk sesin en sık sebebi bu filtreler.
+- **Her aşamayı bir insan kontrol eder.** Claude ilk seferde mükemmel edit çıkarmaz. Aşama aşama çalışılır: kaba kurgu, kontrol, bölümler, animasyonlar aralık aralık, ses, final render.
+
+### Kurulum ve deneme
+
+Gereksinimler: Python 3.10+, numpy, ffmpeg, Node 20+, Chrome ve bir Whisper (`pip install faster-whisper` ya da Apple Silicon'da `brew install whisperkit-cli`).
+
+```bash
+git clone <bu repo> ~/.claude/skills/video-edit
+```
+
+Görüntü olmadan şablonu denemek için `python3 scripts/serve.py --project . --port 5600` çalıştırıp http://127.0.0.1:5600/template/?demo adresini açın, Space'e basın.
+
+### Kullanım
+
+Proje klasörünüzde ham klipleri `src/` içine koyun ve Claude'a ne istediğinizi söyleyin. Örneğin: "Bu klipleri 10 dakikalık bir eğitim videosuna çevir, tekrarları ve duraksamaları kes, bölüm öner, animasyonlar sakin olsun, efekt koyma."
+
+Video türüne göre tempo değişir:
+
+- Eğitim videosunda animasyonlar sakin ve açıklayıcı olur, gerekirse three.js kullanılır.
+- Short'ta animasyonlar daha hareketli olur, kesimler sıkıdır ve altyazı açıktır.
diff --git a/SKILL.md b/SKILL.md
new file mode 100644
index 0000000..273cf2b
--- /dev/null
+++ b/SKILL.md
@@ -0,0 +1,156 @@
+---
+name: video-edit
+description: Edit talking-head, tutorial, explainer and Short videos with Claude Code. Word-accurate cuts from raw takes, motion graphics built as HTML + GSAP (optionally three.js) pages locked to the spoken words, sound effects synthesized in Python, honest loudness handling and frame-exact rendering. Use when the user wants to cut raw footage, remove retakes and pauses, add animated cards or chapters, add or design sound effects, fix loudness, or render a final edit.
+---
+
+# Video edit
+
+This skill turns raw footage into a finished edit together with a human editor. Read this whole file before touching a project. Then read `reference/audio.md` before any cut or level change, and `reference/style.md` before any graphics.
+
+## Read first: what you can and cannot do
+
+- **You cannot hear.** You never listen to audio. Everything you know about sound comes from numbers: Whisper word timestamps, a 10 ms energy envelope, loudness meters, spectrograms. Say this to the user plainly and never claim that something "sounds good".
+- **The human ear is the final check.** Whether a cut clips a word, whether an effect is too loud, whether a voice sounds muffled: the user decides. Your job is to make every problem measurable and every fix fast.
+- **The first pass is never the final edit.** Work stage by stage, hand over a preview after each stage, and expect corrections. Most good results come from short review loops, not from one long autonomous run.
+- **Sync by construction, not by ear.** Animations and sound effects are triggered from the same timeline clock, and that clock is derived from the measured word times. That is how effects land on the picture without you hearing them.
+
+## Paths
+
+Commands run from the user's project folder. `$SKILL` is the folder this file is in (for example `~/.claude/skills/video-edit`); set it once in the shell: `SKILL=~/.claude/skills/video-edit`.
+
+## Before you start: ask
+
+Ask these once, keep the answers in `work/NOTES.md`:
+
+1. **Video type:** educational / explainer, talk (talking head), tutorial with screen recording, or Short (vertical, under 60 s). This sets the motion level (see the table below).
+2. **Raw material:** which clips, in which order, is there a script or outline to follow?
+3. **On-screen language(s):** one language, or two (for example native + English)?
+4. **Brand:** one accent colour, a font if they have one. If they have none, use the neutral palette in `reference/style.md`.
+5. **Sound effects:** yes, no, or "only on chapter transitions". Default is very quiet transitions only.
+6. **Deliverables:** resolution (1080p / 1440p / 4K), captions, YouTube chapter list, deadline.
+
+## Video types
+
+| Type | Motion | Sound effects | Cuts |
+|---|---|---|---|
+| Educational / explainer | Calm and serious. Clean diagrams, readable panels, slow camera moves. three.js only when it explains something (a 3D model of the thing being taught). | None, or very quiet transitions | Natural pace |
+| Talk (talking head) | Few cards that stay on screen long, placed in empty areas, never over the face. | Quiet chapter transitions only | Natural or tight |
+| Tutorial / screen recording | Zoom into the part of the screen being discussed, highlight boxes, step cards. | Optional soft clicks on highlights | Natural |
+| Short | More energetic: faster reveals, bigger type, a hook in the first 2 s, captions on. Still eased, never jittery. | Allowed, still under the voice | Tight |
+
+If the user does not say, infer the type from the transcript and confirm it. Do not over-animate an educational video, and do not make a Short feel slow.
+
+## The workflow
+
+Work in this order. After each numbered stage, stop and hand over a preview URL or file plus a short list of what you decided and why.
+
+### 0. Project layout
+
+```
+project/
+ src/ raw clips (or symlinks to them)
+ work/ everything generated: wav, transcripts, program.json, proxy.mp4, sfx/, NOTES.md, backups
+ scene/ the motion-graphics page (copied from this skill's template/)
+ out/ renders and final files
+```
+
+Keep the project outside cloud-synced folders (iCloud Desktop, Dropbox) if possible. Synced files can be evicted from disk mid-render and reads then hang.
+
+### 1. Transcribe
+
+```bash
+python3 $SKILL/scripts/transcribe.py --project . src/*.mov --lang en
+```
+
+This splits each clip at pauses, transcribes each short chunk separately (padded with silence), and writes `work/transcripts/<clip>.json` + `.txt` with numbered utterances and word times. Transcribing whole files hides retakes: Whisper merges repeated sentences and drops repeated words. See `reference/audio.md`.
+
+Then **read the .txt files yourself**. Mark retakes, false starts, half sentences and filler. Speakers often repeat a sentence two or three times; keep the last fluent take unless the user says otherwise.
+
+### 2. Rough cut
+
+Write `work/edl.json` (format in `reference/edl.md`): the utterances to keep, in the script's order, with chapter markers. Then:
+
+```bash
+python3 $SKILL/scripts/cuts.py --project . # edl.json -> work/program.json (cut points snapped to real word edges)
+python3 $SKILL/scripts/build.py --project . audio video # -> work/prog.wav + work/proxy.mp4 (1080p preview)
+python3 $SKILL/scripts/verify.py --project . # re-transcribes every join, flags clipped words and leftover repeats
+```
+
+Fix what `verify.py` flags, rebuild, and only then hand over. Tell the user the new length and how many cuts were made.
+
+### 3. Review loop
+
+- The user gives timestamps. **Map them by content, not by clock.** Their tab may show an older build. Quote the sentence you think they mean and confirm when unsure. If a time does not match, search the transcripts for the quoted words.
+- Before every new version, copy `work/edl.json` and `work/program.json` to `work/backup/vN/`. If the user says "undo everything", restore exactly, do not reinterpret.
+- Never replace `work/proxy.mp4` while the user is watching it; write the new one and say when it is ready.
+- Change one thing at a time when the user is unhappy. A broken preview makes people distrust the whole revision.
+
+### 4. Chapters
+
+Propose chapters from the transcript (topic changes, the script's sections). Suggest short titles. After approval, add `{"chapter": "..."}` items to the EDL. `cuts.py` prints a YouTube chapter list (`0:00 Intro …`) and writes `work/chapters.txt`. The first chapter must start at 0:00, and YouTube needs at least three chapters, each at least 10 s long.
+
+A chapter transition on screen is a full-frame veil (see `reference/style.md`): the chapter number, the title, and a progress row. Sub-topics inside a chapter do not get their own veil, only a small chip change.
+
+### 5. Graphics, range by range
+
+Copy the template into the project (`cp -R $SKILL/template scene`), serve the project and open the scene. `?demo` shows the template's own demo; without it the scene loads `work/program.json` and plays `work/proxy.mp4`:
+
+```bash
+python3 $SKILL/scripts/serve.py --project . --port 5600 # http://127.0.0.1:5600/scene/
+```
+
+Work on one chapter or time range at a time, never the whole video at once. For each range:
+
+1. List the beats: the few things worth showing (numbers, steps, a comparison, a key idea, a source). **Do not put the narration on screen.** Cards are not subtitles; they carry what the voice cannot (structure, data, a picture).
+2. Lock every beat to a spoken word with `at('phrase')`. An element rises when its word is said (about 0.1 s before) and leaves only after its sentence ends.
+3. Check `?t=SECONDS` freezes at the beats, then hand over the URL.
+
+Rules that apply to every frame are in `reference/style.md`. Run the layout audit before each handover:
+
+```bash
+node $SKILL/scripts/audit.mjs http://127.0.0.1:5600/scene/ --every 0.5
+```
+
+### 6. Sound effects (only if wanted)
+
+Generate the library, then cue effects from the scene's timeline with `cue(t, 'whoosh')`:
+
+```bash
+python3 $SKILL/scripts/sfx.py lib --out scene/sfx # --gain -3 makes every effect 3 dB quieter
+```
+
+Levels and rules are in `reference/audio.md`. The user's first reaction to the level decides: if they say "can't hear it" or "too much", change the level in small steps and remember the answer for the rest of the video.
+
+### 7. Final render and mix
+
+```bash
+python3 $SKILL/scripts/build.py --project . video --final # source-resolution program video (the render background)
+node $SKILL/scripts/render.mjs "http://127.0.0.1:5600/scene/?src=../work/prog-final.mp4" --out out/frames --workers 4 --dpr 2
+python3 $SKILL/scripts/mix.py --project . --video out/frames --out out/FINAL.mp4
+python3 $SKILL/scripts/loudness.py out/FINAL.mp4
+```
+
+Only start a long final render after the user approves the preview. Ask before deleting anything to free disk space.
+
+Deliver the file plus a short report: length, resolution, loudness (integrated LUFS, true peak), the YouTube chapter list, and what was not checked.
+
+## Scripts
+
+| Script | What it does |
+|---|---|
+| `transcribe.py` | Chunked transcription with word times (faster-whisper or whisperkit-cli) |
+| `cuts.py` | EDL to program: cut points snapped to measured word edges, pause removal, chapters, words in program time |
+| `build.py` | Sample-exact program audio (gain only, no filters by default) and frame-exact video |
+| `verify.py` | Re-transcribes the program around every join to catch clipped words and repeats |
+| `loudness.py` | Integrated LUFS, true peak, loudness range, with a plain verdict |
+| `sfx.py` | Sound effects synthesized from math: whoosh, tick, click, key, typing, pop, chime |
+| `serve.py` | Static server with HTTP range support (needed for video seeking) |
+| `render.mjs` | Frame-exact render of the scene in headless Chrome, piped into ffmpeg, parallel workers |
+| `audit.mjs` | Finds overlapping cards, text under the face, and elements touching the frame edge |
+| `mix.py` | Joins the rendered parts with the voice and the effects track, final encode |
+
+Requirements: Python 3.10+, numpy, ffmpeg + ffprobe, Node 20+, Google Chrome or Chromium, and one Whisper backend (`pip install faster-whisper`, or `whisperkit-cli` on Apple Silicon).
+
+## Working notes
+
+Keep `work/NOTES.md` up to date: the answers from the intake, every rule the user gives ("no sound effects in this video", "effects one step quieter"), and the current version. Rules the user gives in one video usually apply to the next one; ask before assuming so.
diff --git a/reference/audio.md b/reference/audio.md
new file mode 100644
index 0000000..1955e78
--- /dev/null
+++ b/reference/audio.md
@@ -0,0 +1,96 @@
+# Audio: cuts, levels and sound effects
+
+Read this before any cut, gain change or sound effect. Audio mistakes are the ones viewers notice first and forgive last, and they are exactly the ones you cannot hear. Every rule here exists because a measurement looked fine and a human ear said otherwise.
+
+## 1. The voice is sacred
+
+- **Never make the voice muffled.** Do not add noise reduction, EQ, compression, gates, de-essers or "enhancers" by default. Adaptive noise reduction and low-pass filters are the usual cause of a voice that sounds boxed, underwater or lisping in some places and fine in others. You cannot hear that happening.
+- **Default processing is one linear gain.** The recording stays as it was, only louder or quieter. `build.py` does exactly this.
+- Processing is allowed only when the user asks for it, and then only the minimum, with an A/B file for them to compare:
+ - **A steady tonal whine** (a thin constant line in the spectrogram, often 7–20 kHz, visible in truly silent windows): narrow notch filters at those frequencies only.
+ - **Hiss:** a static, profile-based reduction above about 2.5 kHz, a few dB at most, voice change ≤ 1–2 dB. Never an adaptive denoiser on the whole band.
+ - **Rumble / hum below the voice:** a high-pass at 60–80 Hz.
+ - **Too quiet even at full gain:** a gentle true-peak limiter (a few dB of gain reduction), see section 3.
+- If the user says "it sounds muffled", "it hisses" or "you made it too loud", undo the processing first, then ask. Do not stack another filter on top.
+
+## 2. Cutting: never clip a word
+
+Whisper's word start and end times are approximate (often 0.1–0.4 s off around pauses) and SRT times are worse. **Cut points come from the energy envelope, not from Whisper.** `cuts.py` does this:
+
+1. A 10 ms RMS envelope of each clip (dB). Speech regions = above a threshold set from the clip's own noise floor.
+2. Inside a kept utterance, pauses longer than the pace's max gap are removed.
+3. **Word ends:** the end is extended while the level stays above the soft floor (about −61 dB), up to 0.10 s, so a decaying last syllable is not chopped.
+4. **Release bursts:** words ending in t, k, p, ç have a short silent closure followed by a burst (about 10–120 ms). If a short burst follows a short closure and silence follows it, it is kept. Without this rule, "basic" becomes "basi".
+5. **Word starts:** the start is pulled back up to 0.06 s while the level is above the soft floor, so a soft onset is kept.
+6. Margins: a small head before the first word and a tail after the last word, never reaching into the neighbouring speech.
+7. Frame rounding goes outward: the cut never rounds into a word.
+8. Every join gets a short fade: 4 ms in, 15 ms out. No clicks, no audible fade.
+
+Pace presets (`edl.json` → `"pace"`):
+
+| Pace | Head | Tail | Max kept pause | Feel |
+|---|---|---|---|---|
+| `natural` (default) | 0.10 s | 0.16 s | 0.35 s | Breathing room; educational and calm talks |
+| `tight` | 0.04 s | 0.06 s | 0.15 s | Jump-cut YouTube pace; Shorts |
+
+Rules learned the hard way:
+
+- **Do not cut between two words that run together** (gap under ~0.2 s). Keep the sentence to its natural end instead; a cut there sounds like a chopped word.
+- **A hand-set cut point must be checked against the envelope**, not against Whisper's word end. Whisper may end a word at its first syllable.
+- **Snapping to the quietest 10 ms** near a hand-set point can land inside the previous or next word. Use `"exact": true` for points you measured yourself.
+- **Re-transcribe after every build.** `verify.py` transcribes a window around every join. Read the joins: a half word, a doubled word ("and, and"), or a sentence that ends too early all show up there.
+- **Hidden retakes** live inside a single Whisper utterance. A disfluency-heavy speaker can say "because I, because I actively" in one breath. When `verify.py` shows doubled phrases, split that utterance with `start`/`end` times.
+- **Blank stares** are silent but visible: the speaker finishes, freezes, then restarts. Audio silence alone does not find them; check with a frame-difference measure or by asking the user. Cut them the same way as pauses.
+- **Retakes that start the same way:** keep the take that is fluent to the end, not the first one.
+
+## 3. Loudness
+
+Targets for online video:
+
+| Target | Value |
+|---|---|
+| Integrated loudness | about −14 LUFS (YouTube, most platforms). Acceptable range −16 to −13. |
+| True peak | at most −1 dBTP |
+| Loudness range (LRA) | a talking voice is usually 3–8 LU; much higher means a level problem |
+
+- YouTube turns loud videos down to about −14 LUFS but generally does **not** turn quiet videos up. A video at −24 LUFS stays quiet and viewers keep changing the volume.
+- `build.py` computes one gain: the smaller of (target − measured loudness) and (−1 dBTP − measured true peak). If the true peak stops the gain short of the target, it reports how many dB are missing. Then offer the user `--limiter`: a gentle true-peak limiter that allows the missing gain. Do not apply it silently.
+- Measure correctly: `ebur128` on the actual stereo file. Downmixing with `-ac 1` sums the channels and reports a false peak about 3 dB too high. If you need mono, use `pan=mono|c0=c0`.
+- Do not loudness-normalize twice. The final mix only checks the level; the gain was already set on the voice.
+
+## 4. Mixing other sources
+
+- **Inserted clips** (an old video, a screen recording with sound, a demo output): level each insert separately so its short-term loudness matches the surrounding voice. Recordings differ by 5–10 dB.
+- **Synthetic or cloned voices** read louder than they measure: dry, even, bright. Sit them about 3 dB under the real voice and never brighten them with EQ.
+- **Background music:** at least 18–22 dB under the voice while someone speaks. Dip it under speech; let it rise only in pauses and transitions.
+- **Room tone, not digital silence.** When you need a short gap between two pieces, use a fraction of a second of the clip's own room tone. Pure digital zeros sound like a stop.
+
+## 5. Sound effects
+
+Effects are synthesized in Python from math (`scripts/sfx.py`): filtered noise with a moving filter for whooshes, short decaying sine bursts with a bit of noise for ticks and key presses, modal (inharmonic) partials for chimes. No downloads, no licences, fully reproducible.
+
+Levels (peak, effect on its own):
+
+| Use | Start at |
+|---|---|
+| Chapter transition whoosh | −32 dBFS |
+| UI tick / click / pop | −30 dBFS |
+| Typing | −32 dBFS |
+| Short (more energetic) | up to −26 dBFS |
+
+- Effects must sit **under** the voice and never mask a word. Avoid placing a hit on top of a stressed syllable.
+- Start quiet and let the user pull it up. Real corrections from practice: −32 dBFS was "can't hear it at all", −26 was "a bit less", −28 stuck. The same −28 whoosh was "a bit much" in a calmer video, and −34 stuck. The right level depends on the video; the user's ear decides.
+- Normalize every effect type to a similar loudness so quiet types (a soft tick) are heard as well as loud ones (a whoosh).
+- Many videos are better with no effects at all (serious educational parts, emotional parts). Ask.
+- **Sync:** effects are cued from the scene timeline (`cue(t, name)`). The render exports the cue list, and `sfx.py track` renders the full-length effects track from it. Picture and sound come from the same clock, so they cannot drift.
+- **Typing sounds** must follow the typing animation: one key sound per revealed character group, at the reveal time, with small random variation in pitch, level and timing so it does not sound like a machine gun. Never lay a generic typing loop under a typing animation; that is the classic "the keys don't match the text" mistake.
+
+## 6. Captions and subtitles
+
+- Captions follow the final audio exactly as spoken. Fix only misheard words (names, product names, technical terms); never rewrite sentences.
+- Build captions from the **final** program audio, transcribed in chunks split at silences and padded with silence, not with neighbouring audio (neighbouring audio makes Whisper invent half words).
+- Do not break inside fixed phrases (a number and its unit, a name).
+
+## 7. What to report
+
+After every build, report: program length, number of cuts, integrated LUFS, true peak, LRA, and the gain applied. If anything was limited, say by how much. Say what you could not verify by measurement and ask the user to listen to those spots (list timestamps).
diff --git a/reference/edl.md b/reference/edl.md
new file mode 100644
index 0000000..e836e94
--- /dev/null
+++ b/reference/edl.md
@@ -0,0 +1,44 @@
+# The edit list (`work/edl.json`)
+
+The EDL says which spoken pieces to keep and in what order. You (Claude) write it after reading the transcripts; `cuts.py` turns it into frame-exact pieces with cut points snapped to real word edges.
+
+```json
+{
+ "fps": 30,
+ "pace": "natural",
+ "clips": {
+ "a": "src/take-01.mov",
+ "b": "src/take-02.mov"
+ },
+ "items": [
+ { "chapter": "Intro" },
+ { "clip": "a", "utt": 0 },
+ { "clip": "a", "utt": [2, 4] },
+ { "clip": "a", "utt": 5, "start": 61.20 },
+ { "clip": "a", "utt": 6, "end": 70.10, "exact": true },
+ { "chapter": "How it works" },
+ { "clip": "b", "range": [12.00, 18.50] },
+ { "note": "utt 7-9 of clip a are retakes of utt 6, dropped" }
+ ]
+}
+```
+
+| Field | Meaning |
+|---|---|
+| `fps` | Frame rate of the sources and the program. All clips must share it. |
+| `pace` | `natural` (default) or `tight`. See `audio.md` section 2. |
+| `clips` | Short id → source file (relative to the project). The id is also the transcript name. |
+| `chapter` | Starts a chapter at this point of the program. Used for veils and the YouTube chapter list. |
+| `clip` + `utt` | Keep utterance N (or N to M) from that clip's transcript. Pauses inside are shortened to the pace. |
+| `start` / `end` | Source seconds that trim the utterance(s). Snapped to the quietest 10 ms within ±0.15 s unless `exact` is true. |
+| `exact` | Use `start` / `end` exactly as given. For points you measured on the envelope yourself. |
+| `range` | A raw source range kept as is: no pause removal. For reactions, a demo with sound, a laugh. |
+| `keep_pauses` | On a `utt` item: keep its internal pauses (dramatic pause, a beat before a punch line). |
+| `note` | Ignored. Write down why something was dropped; it helps the next review. |
+
+Tips:
+
+- Utterance numbers come from `work/transcripts/<clip>.txt`, which shows `#index [start-end] text`.
+- To drop the first half-sentence of a utterance ("So the... So the main point is"), set `start` just before the second "So"; check the envelope around it with `python3 $SKILL/scripts/cuts.py --project . --peek a 60.5 62.0`.
+- Keep the items in the order of the script, not the order of recording.
+- After every change: `cuts.py`, `build.py audio video`, `verify.py`.
diff --git a/reference/style.md b/reference/style.md
new file mode 100644
index 0000000..7948838
--- /dev/null
+++ b/reference/style.md
@@ -0,0 +1,132 @@
+# Style: graphics that support the voice
+
+The graphics in this skill are web pages: HTML + CSS + GSAP, with three.js when a 3D object helps explain something. A page is frozen at any time with `?t=SECONDS` and rendered frame by frame. Everything below is measured at a 1920×1080 stage (rendered at 2× for 4K). For a Short, the stage is 1080×1920.
+
+## 1. What goes on screen
+
+- **Never transcribe the narration onto the screen.** A card that repeats the sentence being spoken is a subtitle, not a graphic. Show what the voice cannot carry:
+ - structure (steps, a list of options, a before/after)
+ - numbers and data (counters, small charts)
+ - the one key idea of a section, in a few words
+ - a source shown the way it looks (an article window with its title and a highlighted line), with the link in the description, not on screen
+ - a picture of the thing being discussed
+- **Rephrase, do not quote.** "I stopped writing prompts" → "Writing prompts? / Stopped."
+- **Fewer, longer-lasting cards.** In a talking-head video, one card that stays and grows as the speaker continues beats five cards flashing past. After the opening, reduce the density.
+- **Never cover the face, the hands making a point, or the UI the speaker is pointing at.** Keep a visible cursor visible.
+
+## 2. Palette (neutral default)
+
+Use the channel's brand colour as the single accent if they have one. Otherwise use this neutral set. Keep one accent per video: two strong accents compete.
+
+Dark (default for talking heads and screen recordings):
+
+| Token | Value | Use |
+|---|---|---|
+| `--bg` | `#0B0C0E` | full-screen pages, veils |
+| `--glass` | `rgba(18, 20, 24, 0.62)` | card fill over video |
+| `--glass-solid` | `#16181C` | card fill over flat backgrounds |
+| `--line` | `rgba(255, 255, 255, 0.10)` | 1 px card border, dividers |
+| `--ink` | `#F4F4F1` | main text |
+| `--ink-2` | `#BFC3CA` | secondary text |
+| `--label` | `#9198A3` | kicker labels (never for content) |
+| `--accent` | `#3D8BFF` | the one accent: bars, underlines, the active item |
+| `--accent-ink` | `#A8C8FF` | accent-coloured text (second language line, emphasis) |
+| `--good` / `--bad` / `--warn` | `#35C27D` / `#F0524D` / `#F2B53C` | meaning only (correct / wrong / caution) |
+
+Light (paper look, for bright recordings or diagrams):
+
+| Token | Value |
+|---|---|
+| `--bg` | `#F3F2EE` |
+| `--glass` | `rgba(255, 255, 255, 0.78)` |
+| `--line` | `rgba(0, 0, 0, 0.09)` |
+| `--ink` | `#141518` |
+| `--ink-2` | `#4A4F57` |
+| `--accent` | `#1F6FEB` |
+| `--accent-ink` | `#1557C0` |
+
+With a brand colour: set `--accent` to it, derive `--accent-ink` by lightening it (dark theme) or darkening it (light theme) until text contrast on the card is at least 4.5:1. Check it; do not guess.
+
+## 3. Glass cards
+
+The basic unit. Dark frosted glass over the video, readable at phone size:
+
+```css
+.card {
+ background: var(--glass);
+ border: 1px solid var(--line);
+ border-radius: 14px;
+ padding: 22px 26px;
+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.28); /* small and tight, never a big soft glow */
+}
+.card .kick { font: 600 20px/1 var(--mono); letter-spacing: .08em; text-transform: uppercase; color: var(--label); }
+.card .kick::before { content: ""; display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: var(--accent); margin-right: 10px; }
+.card h3 { font: 700 44px/1.1 var(--sans); color: var(--ink); }
+.card .l2 { font: 700 44px/1.1 var(--sans); color: var(--accent-ink); } /* second language: same size */
+```
+
+- **Blur:** a real `backdrop-filter: blur()` looks best but is expensive. Use it on a few small cards at most. Never put a full-screen live `backdrop-filter` or CSS `filter` on the stage: it stutters during playback. For a blurred full-frame background, draw a downscaled frame into a small canvas with `ctx.filter = 'blur()'` and scale it up.
+- **Over a flat or already-blurred background** use `--glass-solid` without blur.
+- Radius 10–16 px for cards, 6–8 px for chips. Keep one radius scale per video.
+
+## 4. Typography
+
+- One sans family for everything, plus one monospace for small labels and code. Variable fonts with Latin-extended glyphs (for Turkish, German, etc.) must be loaded and decoded before the first frame (`document.fonts.ready`).
+- **Minimum sizes at 1080p:** content text 32 px, card titles 44 px and up, kicker labels 20 px, nothing under 18 px. Small mono labels are the first thing to become unreadable on a phone.
+- Bold-ish weights (600–800) for anything the viewer must read. No thin weights, no italics, no low-opacity content text.
+- Key phrases get a drawn underline in the accent colour, not a highlight box over the text.
+
+## 5. Two languages on screen (optional)
+
+When the channel has an international audience:
+
+- Both languages at the **same size**, in two colours that both read clearly: main language in `--ink` on top, second language in `--accent-ink` below. No "EN / TR" labels on statements.
+- Long source texts (a prompt, a quote): two columns side by side, rows aligned paragraph by paragraph, with column headers.
+- Keep second-language text short; it doubles the reading load.
+
+## 6. Layout
+
+- Safe margins: 64 px from every frame edge (Short: also keep clear of the platform's UI at the bottom ~300 px and right ~120 px).
+- **Nothing overlaps.** No stamp laid across a card, no card over another card, no tag over a screenshot. Put things beside each other.
+- **Nothing sits cut off at the frame edge.** Every camera hold shows its group whole with about 44 px of margin.
+- Mark the face (or any keep-out area) with `data-keepout` and every card with `data-box`; `scripts/audit.mjs` checks overlaps and margins at sampled times. Run it before every handover.
+
+## 7. Motion
+
+- Eased, not linear: `power3.out` / `expo.out` for entrances, `power2.inOut` for camera moves. No bounce or elastic eases unless it is a playful Short.
+- **Word-locked:** an element appears when its word is said (about 0.1 s before the word's onset) and leaves after its sentence ends. Revealing a whole title at the start of a sentence feels like the graphics are running ahead.
+- **Do not compress the timeline to shorten a scene.** Cut beats instead. A sped-up animation feels broken.
+- Camera moves (zoom into a screenshot, pan across a board): slow, at most about 1 % scale change per frame. Never a hard jump in scale. Cut-synced punch-ins at 30 fps without motion blur read as jolts; use them rarely (about one per minute at most), or not at all.
+- Typing animations type at a human pace with eased line reveals; a machine-gun typewriter is not motion design.
+- Play once on load, then hold. No looping idle animation behind text the viewer is reading.
+
+| Video type | Entrance length | Holds | Extras |
+|---|---|---|---|
+| Educational | 0.6–0.9 s | long | diagrams, step boards, calm camera pans across a large board |
+| Talk | 0.5–0.8 s | long | keyword card that swaps on its word, counters, a lower third once |
+| Tutorial | 0.4–0.7 s | medium | zoom on the UI, highlight boxes, numbered steps |
+| Short | 0.25–0.45 s | short | bigger type, hook card in the first 2 s, captions with the spoken word underlined |
+
+## 8. three.js
+
+Use 3D when it explains: a part being assembled, an object that is the topic, a spatial idea. Not as decoration.
+
+- The scene's time must come from the timeline (`TL.time()`), not from `requestAnimationFrame` deltas, so every frame renders the same in preview and in the final render.
+- Prewarm shaders and load every model and texture before the first frame (the template's `ASSETS` list); the renderer waits for them.
+- Keep the camera calm; let the object move.
+
+## 9. Chapter transitions and recurring elements
+
+- **Chapter veil:** a full-frame glass panel wipes across (about 2–2.6 s in total), shows "CHAPTER 02 / 05", the title (and second language), and a progress row of all chapters, then wipes off. A soft whoosh is optional. Only main chapters get a veil.
+- **Chapter chip:** a small chip in a top corner shows the current chapter number and title for the rest of the chapter.
+- **Lower third:** name and one-line role, once, early. It slides out from the edge or from behind the face cut-out and retracts the same way.
+- **Like / subscribe:** if used, one short animation in the first minute and one at the end, never in the middle of an explanation.
+
+## 10. Avoid
+
+- Radial gradients, round glows, vignettes and big soft shadows behind elements: they band into visible rings after video compression.
+- Full-frame colour washes over the speaker (a sepia "old days" tint, a red alarm flash).
+- Cream or white cards over a dark video: they pull all the attention. Keep cards darker than the subject.
+- Physics distortions (rubbery UI, warps) and speed ramps unless the user asks.
+- Other people's URLs on screen.
+- Emoji as icons in cards.
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000..da1272f
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,4 @@
+numpy>=1.24
+# one Whisper backend:
+# faster-whisper>=1.0 (any OS)
+# or: brew install whisperkit-cli (Apple Silicon)
diff --git a/scripts/_cdp.mjs b/scripts/_cdp.mjs
new file mode 100644
index 0000000..ca30d73
--- /dev/null
+++ b/scripts/_cdp.mjs
@@ -0,0 +1,81 @@
+// Minimal headless Chrome driver over the DevTools protocol. No npm dependencies.
+// Needs a global WebSocket (Node 22+, or Node 20/21 with --experimental-websocket: the scripts re-launch themselves).
+import { spawn } from 'node:child_process';
+import { existsSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+export function ensureWebSocket() {
+ if (typeof globalThis.WebSocket !== 'undefined') return true;
+ const r = spawn(process.execPath, ['--experimental-websocket', ...process.argv.slice(1)], { stdio: 'inherit' });
+ r.on('close', (c) => process.exit(c ?? 1));
+ return false;
+}
+
+export function findChrome() {
+ const c = [
+ process.env.CHROME,
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
+ '/Applications/Chromium.app/Contents/MacOS/Chromium',
+ '/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', '/usr/bin/chromium', '/usr/bin/chromium-browser',
+ 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
+ ].filter(Boolean);
+ const hit = c.find((p) => existsSync(p));
+ if (!hit) throw new Error('Chrome not found. Set CHROME=/path/to/chrome');
+ return hit;
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+export async function openPage({ width, height, dpr = 1 }) {
+ const port = 9300 + Math.floor(Math.random() * 600);
+ const prof = mkdtempSync(join(tmpdir(), 've-chrome-'));
+ const chrome = spawn(findChrome(), [
+ '--headless=new', `--remote-debugging-port=${port}`, `--user-data-dir=${prof}`,
+ `--window-size=${width},${height}`, '--hide-scrollbars', '--mute-audio', '--no-first-run', '--no-default-browser-check',
+ '--autoplay-policy=no-user-gesture-required', '--disable-background-timer-throttling', '--disable-renderer-backgrounding',
+ 'about:blank',
+ ], { stdio: 'ignore' });
+ const close = () => { try { chrome.kill('SIGKILL'); } catch (e) {} try { rmSync(prof, { recursive: true, force: true }); } catch (e) {} };
+ process.on('exit', close);
+
+ let list = null;
+ for (let i = 0; i < 120 && !list; i++) {
+ await sleep(150);
+ try { list = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json(); } catch (e) {}
+ }
+ if (!list) throw new Error('Chrome did not start');
+ const ws = new WebSocket(list.find((t) => t.type === 'page').webSocketDebuggerUrl);
+ await new Promise((r) => ws.addEventListener('open', r, { once: true }));
+ let seq = 0;
+ const waiting = new Map(), listeners = [];
+ ws.addEventListener('message', (ev) => {
+ const m = JSON.parse(ev.data);
+ if (m.id && waiting.has(m.id)) { const { res, rej } = waiting.get(m.id); waiting.delete(m.id); m.error ? rej(new Error(m.error.message)) : res(m.result); }
+ else if (m.method) listeners.forEach((f) => f(m));
+ });
+ const send = (method, params = {}) => new Promise((res, rej) => { const id = ++seq; waiting.set(id, { res, rej }); ws.send(JSON.stringify({ id, method, params })); });
+ const evaluate = async (expression) => {
+ const r = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });
+ if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description || r.exceptionDetails.text);
+ return r.result.value;
+ };
+ await send('Page.enable');
+ await send('Runtime.enable');
+ await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: dpr, mobile: false });
+
+ const goto = async (url) => {
+ const loaded = new Promise((r) => listeners.push((m) => { if (m.method === 'Page.loadEventFired') r(); }));
+ await send('Page.navigate', { url });
+ await loaded;
+ for (let i = 0; i < 300; i++) { if (await evaluate('!!(window.__scene && window.__sceneReady)')) break; await sleep(100); }
+ if (!(await evaluate('!!window.__scene'))) throw new Error('the page has no window.__scene (is it a scene from the template?)');
+ await evaluate('window.__sceneReady()');
+ };
+ const shot = async (quality = 95) => Buffer.from((await send('Page.captureScreenshot', { format: 'jpeg', quality, fromSurface: true })).data, 'base64');
+ return { send, evaluate, goto, shot, close: () => { try { ws.close(); } catch (e) {} close(); } };
+}
+
+export function withParam(url, p) {
+ return url + (url.includes('?') ? '&' : '?') + p;
+}
diff --git a/scripts/_common.py b/scripts/_common.py
new file mode 100644
index 0000000..d69e18d
--- /dev/null
+++ b/scripts/_common.py
@@ -0,0 +1,125 @@
+"""Shared helpers: project paths, audio decoding, the 10 ms energy envelope, loudness measurement."""
+import json
+import os
+import re
+import subprocess
+import sys
+
+import numpy as np
+
+ENV_HOP = 0.01 # envelope resolution: 10 ms
+
+
+def project_paths(project):
+ root = os.path.abspath(project)
+ work = os.path.join(root, 'work')
+ os.makedirs(work, exist_ok=True)
+ return root, work
+
+
+def need(tool):
+ from shutil import which
+ if not which(tool):
+ sys.exit(f'{tool} not found on PATH')
+
+
+def ffmpeg(*args, check=True, capture=False, inp=None):
+ need('ffmpeg')
+ r = subprocess.run(['ffmpeg', '-v', 'error', '-y', *args], input=inp,
+ capture_output=capture)
+ if check and r.returncode != 0:
+ err = r.stderr.decode(errors='replace') if capture and r.stderr else ''
+ sys.exit(f'ffmpeg failed ({r.returncode}): {" ".join(args[:6])} ... {err}')
+ return r
+
+
+def decode(path, sr=48000, channels=2):
+ """Decode any audio/video file to float32 samples, shape (n, channels)."""
+ need('ffmpeg')
+ raw = subprocess.run(['ffmpeg', '-v', 'error', '-i', path, '-vn', '-f', 'f32le', '-ac', str(channels),
+ '-ar', str(sr), '-'], capture_output=True).stdout
+ return np.frombuffer(raw, np.float32).reshape(-1, channels)
+
+
+def envelope(path_or_samples, sr=16000):
+ """10 ms RMS envelope in dB of the mono signal, high-passed at 80 Hz so rumble does not count as speech."""
+ if isinstance(path_or_samples, str):
+ raw = subprocess.run(['ffmpeg', '-v', 'error', '-i', path_or_samples, '-vn', '-af', 'highpass=f=80',
+ '-f', 'f32le', '-ac', '1', '-ar', str(sr), '-'], capture_output=True).stdout
+ x = np.frombuffer(raw, np.float32)
+ else:
+ x = path_or_samples
+ hop = int(sr * ENV_HOP)
+ n = len(x) // hop
+ rms = np.sqrt(np.mean(x[:n * hop].reshape(n, hop) ** 2, axis=1) + 1e-12)
+ return 20 * np.log10(rms)
+
+
+def speech_threshold(env, override=None):
+ """Speech/silence threshold from the clip's own noise floor (10th percentile) unless given."""
+ if override is not None:
+ return float(override)
+ floor = float(np.percentile(env, 10))
+ return float(np.clip(floor + 18, -60, -40))
+
+
+def speech_regions(env, thr, bridge=0.25, min_len=0.08):
+ """Regions above thr; gaps shorter than bridge are closed, blips shorter than min_len dropped. Seconds."""
+ on = env > thr
+ segs, i, n = [], 0, len(env)
+ while i < n:
+ if on[i]:
+ j = i
+ while j < n and on[j]:
+ j += 1
+ segs.append([i, j])
+ i = j
+ else:
+ i += 1
+ merged = []
+ for a, b in segs:
+ if merged and (a - merged[-1][1]) * ENV_HOP < bridge:
+ merged[-1][1] = b
+ else:
+ merged.append([a, b])
+ return [[round(a * ENV_HOP, 2), round(b * ENV_HOP, 2)] for a, b in merged if (b - a) * ENV_HOP >= min_len]
+
+
+def loudness(path):
+ """Integrated loudness (LUFS), true peak (dBTP), loudness range (LU) via ffmpeg ebur128 on the real channels."""
+ need('ffmpeg')
+ err = subprocess.run(['ffmpeg', '-nostats', '-hide_banner', '-i', path, '-vn', '-af', 'ebur128=peak=true',
+ '-f', 'null', '-'], capture_output=True, text=True).stderr
+ s = err[err.rindex('Summary:'):]
+ i = float(re.search(r'I:\s+(-?[\d.]+|-inf) LUFS', s).group(1))
+ tp = float(re.search(r'Peak:\s+(-?[\d.]+|-inf) dBFS', s).group(1))
+ lra = float(re.search(r'LRA:\s+(-?[\d.]+) LU', s).group(1))
+ return i, tp, lra
+
+
+def write_wav(path, x, sr=48000, bits=24):
+ """Write float samples (n, ch) to WAV through ffmpeg (24-bit by default)."""
+ x = np.ascontiguousarray(x, dtype=np.float32)
+ ch = 1 if x.ndim == 1 else x.shape[1]
+ ffmpeg('-f', 'f32le', '-ar', str(sr), '-ac', str(ch), '-i', '-', '-c:a', f'pcm_s{bits}le', path, inp=x.tobytes())
+
+
+def load_json(path):
+ with open(path, encoding='utf-8') as f:
+ return json.load(f)
+
+
+def save_json(path, data):
+ with open(path, 'w', encoding='utf-8') as f:
+ json.dump(data, f, ensure_ascii=False, indent=1)
+
+
+def fmt_time(t):
+ t = max(0.0, t)
+ return f'{int(t // 60)}:{t % 60:05.2f}'
+
+
+def yt_time(t):
+ t = int(t)
+ h, m, s = t // 3600, t % 3600 // 60, t % 60
+ return f'{h}:{m:02d}:{s:02d}' if h else f'{m}:{s:02d}'
diff --git a/scripts/audit.mjs b/scripts/audit.mjs
new file mode 100644
index 0000000..d653d2c
--- /dev/null
+++ b/scripts/audit.mjs
@@ -0,0 +1,46 @@
+// Layout audit: at sampled times, finds visible cards ([data-box]) that overlap each other, cover a keep-out
+// area ([data-keepout], e.g. the speaker's face) or sit closer than --margin px to the frame edge.
+//
+// usage: node scripts/audit.mjs URL [--every 0.5] [--at 3,7.5] [--margin 40]
+import { ensureWebSocket, openPage, withParam } from './_cdp.mjs';
+
+if (!ensureWebSocket()) await new Promise(() => {});
+
+const args = process.argv.slice(2);
+const opt = (k, d) => { const i = args.indexOf(`--${k}`); return i >= 0 ? args[i + 1] : d; };
+const URL0 = args[0];
+if (!URL0 || URL0.startsWith('--')) { console.error('usage: node scripts/audit.mjs URL [--every 0.5] [--margin 40]'); process.exit(1); }
+const MARGIN = +opt('margin', 40);
+
+const page = await openPage({ width: 1920, height: 1080 });
+await page.goto(withParam(URL0, 'still'));
+const info = await page.evaluate('({ d: window.__scene.duration, missing: window.__scene.missing })');
+const times = opt('at', null) ? opt('at').split(',').map(Number)
+ : [...Array(Math.floor(info.d / +opt('every', 0.5)) + 1).keys()].map((i) => +(i * +opt('every', 0.5)).toFixed(3));
+
+const problems = new Map();
+for (const t of times) {
+ await page.evaluate(`window.__scene.render(${t})`);
+ const r = await page.evaluate(`(() => {
+ const stage = document.querySelector('#stage'), st = stage.getBoundingClientRect(), W = +document.body.dataset.w || 1920, H = +document.body.dataset.h || 1080, s = st.width / W;
+ const R = (e) => { const b = e.getBoundingClientRect(); return { x: (b.left - st.left) / s, y: (b.top - st.top) / s, w: b.width / s, h: b.height / s }; };
+ const vis = (e) => { for (let n = e; n && n !== stage; n = n.parentElement) { const c = getComputedStyle(n); if (c.display === 'none' || c.visibility === 'hidden' || +c.opacity < 0.05) return false; } return true; };
+ const name = (e) => e.id || e.className || e.tagName;
+ const boxes = [...document.querySelectorAll('[data-box]')].filter(vis).map((e) => [name(e), R(e)]).filter(([, b]) => b.w > 2 && b.h > 2);
+ const keep = [...document.querySelectorAll('[data-keepout]')].map(R);
+ const hit = (a, b) => a.x < b.x + b.w - 4 && a.x + a.w > b.x + 4 && a.y < b.y + b.h - 4 && a.y + a.h > b.y + 4;
+ const out = [];
+ for (const [n, b] of boxes) {
+ if (b.x < ${MARGIN} || b.y < ${MARGIN} || b.x + b.w > W - ${MARGIN} || b.y + b.h > H - ${MARGIN}) out.push('edge: ' + n);
+ if (keep.some((k) => hit(b, k))) out.push('covers keep-out: ' + n);
+ }
+ for (let i = 0; i < boxes.length; i++) for (let j = i + 1; j < boxes.length; j++) if (hit(boxes[i][1], boxes[j][1])) out.push('overlap: ' + boxes[i][0] + ' / ' + boxes[j][0]);
+ return out;
+ })()`);
+ for (const p of r) { if (!problems.has(p)) problems.set(p, []); problems.get(p).push(t); }
+}
+page.close();
+if (info.missing.length) console.log(`phrases not found: ${JSON.stringify(info.missing)}`);
+for (const [p, ts] of problems) console.log(`${p} at ${ts.length > 6 ? ts.slice(0, 3).join(', ') + ' … ' + ts.slice(-2).join(', ') : ts.join(', ')} s`);
+console.log(`audit: ${times.length} moments, ${problems.size} problem(s)${info.missing.length ? ', missing phrases' : ''}`);
+process.exit(problems.size || info.missing.length ? 1 : 0);
diff --git a/scripts/build.py b/scripts/build.py
new file mode 100644
index 0000000..4171da4
--- /dev/null
+++ b/scripts/build.py
@@ -0,0 +1,155 @@
+#!/usr/bin/env python3
+"""Program -> audio and video.
+
+audio: every piece is taken sample-exact from its source at 48 kHz, with a 4 ms fade-in and a 15 ms fade-out at
+ each join (no clicks). Then ONE linear gain: as close to the loudness target as the true-peak ceiling
+ allows. No noise reduction, EQ, compression or gate: they make voices muffled (see reference/audio.md).
+video: every piece is encoded frame-exact from its source, then joined without re-encoding.
+
+usage:
+ python3 scripts/build.py --project . audio video # work/prog.wav + work/proxy.mp4 (1080p preview)
+ python3 scripts/build.py --project . video --final # work/prog-final.mp4 at source resolution (render background)
+options:
+ --target -14 loudness target (LUFS)
+ --ceiling -1 true-peak ceiling (dBTP)
+ --limiter allow a gentle peak limiter when the ceiling stops the gain short of the target (ask the user first)
+ --highpass 70 high-pass filter in Hz, only for rumble / hum the user asked to remove
+ --hw hardware encoder on macOS (h264_videotoolbox) for the preview
+ --workers 4 parallel encodes
+"""
+import argparse
+import os
+import subprocess
+import sys
+from concurrent.futures import ThreadPoolExecutor
+
+import numpy as np
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from _common import decode, ffmpeg, fmt_time, load_json, loudness, project_paths, write_wav # noqa: E402
+
+SR = 48000
+FADE_IN, FADE_OUT = 0.004, 0.015
+
+
+def sample(frame, fps):
+ return int(round(frame * SR / fps))
+
+
+def build_audio(root, work, prog, a):
+ fps, cache, parts = prog['fps'], {}, []
+ for p in prog['pieces']:
+ cid = p['clip']
+ if cid not in cache:
+ cache[cid] = decode(os.path.join(root, prog['clips'][cid]), SR, 2)
+ s0, s1 = sample(p['a'], fps), sample(p['b'], fps)
+ x = cache[cid][s0:s1].copy()
+ if len(x) < s1 - s0:
+ x = np.vstack([x, np.zeros((s1 - s0 - len(x), 2), np.float32)])
+ fi = int(FADE_IN * SR)
+ fo = int(p.get('fade_out', FADE_OUT) * SR)
+ x[:fi] *= np.linspace(0, 1, fi, dtype=np.float32)[:, None]
+ x[-fo:] *= np.linspace(1, 0, fo, dtype=np.float32)[:, None]
+ parts.append(x)
+ y = np.vstack(parts)
+ rawp = os.path.join(work, 'prog-raw.wav')
+ write_wav(rawp, y)
+ i0, tp0, lra0 = loudness(rawp)
+
+ pre = f'highpass=f={a.highpass},' if a.highpass else ''
+ want = a.target - i0
+ room = a.ceiling - tp0
+ outp = os.path.join(work, 'prog.wav')
+ if want <= room or not a.limiter:
+ g = min(want, room)
+ ffmpeg('-i', rawp, '-af', f'{pre}volume={g:.2f}dB', '-ar', str(SR), '-c:a', 'pcm_s24le', outp)
+ how = 'linear gain'
+ else:
+ g = want
+ lim = 10 ** ((a.ceiling - 0.5) / 20)
+ ffmpeg('-i', rawp, '-af', f'{pre}volume={g:.2f}dB,alimiter=limit={lim:.4f}:attack=5:release=60:level=disabled',
+ '-ar', str(SR), '-c:a', 'pcm_s24le', outp)
+ how = 'gain + gentle limiter'
+ i1, tp1, lra1 = loudness(outp)
+ print(f'audio: {fmt_time(len(y) / SR)} {i0:.1f} LUFS (true peak {tp0:.1f}) -> {i1:.1f} LUFS, true peak {tp1:.1f} dBTP, '
+ f'LRA {lra1:.1f} LU ({how} {g:+.1f} dB)')
+ if not a.limiter and want > room + 0.3:
+ print(f'note: the true-peak ceiling stopped the gain {want - room:.1f} dB short of {a.target} LUFS. '
+ f'Ask the user before using --limiter (a gentle peak limiter), and let them listen to both.')
+ if tp1 > a.ceiling + 0.2:
+ print(f'warning: true peak {tp1:.1f} dBTP is above the ceiling')
+
+
+def build_video(root, work, prog, a):
+ fps = prog['fps']
+ seg_dir = os.path.join(work, 'seg-final' if a.final else 'seg')
+ os.makedirs(seg_dir, exist_ok=True)
+ for f in os.listdir(seg_dir):
+ if f.endswith('.mp4') or f == 'list.txt':
+ os.remove(os.path.join(seg_dir, f))
+ if a.final:
+ enc = ['-c:v', 'libx264', '-preset', 'medium', '-crf', '14', '-profile:v', 'high']
+ vf = 'format=yuv420p'
+ elif a.hw:
+ enc = ['-c:v', 'h264_videotoolbox', '-b:v', '12M', '-profile:v', 'high']
+ vf = 'scale=-2:1080:flags=lanczos,format=yuv420p'
+ else:
+ enc = ['-c:v', 'libx264', '-preset', 'veryfast', '-crf', '20']
+ vf = 'scale=-2:1080:flags=lanczos,format=yuv420p'
+ common = ['-pix_fmt', 'yuv420p', '-g', str(fps), '-r', str(fps), '-video_track_timescale', str(fps * 1000),
+ '-color_primaries', 'bt709', '-color_trc', 'bt709', '-colorspace', 'bt709', '-an']
+
+ def seg(i):
+ p = prog['pieces'][i]
+ src = os.path.join(root, prog['clips'][p['clip']])
+ # seek half a frame early: the first decoded frame is then exactly frame a
+ ffmpeg('-ss', f'{(p["a"] - 0.5) / fps:.5f}', '-i', src, '-frames:v', str(p['b'] - p['a']), '-vf', vf, *enc,
+ *common, os.path.join(seg_dir, f'{i:05d}.mp4'))
+
+ with ThreadPoolExecutor(a.workers) as ex:
+ list(ex.map(seg, range(len(prog['pieces']))))
+ lst = os.path.join(seg_dir, 'list.txt')
+ with open(lst, 'w') as f:
+ f.write(''.join(f"file '{seg_dir}/{i:05d}.mp4'\n" for i in range(len(prog['pieces']))))
+ vid = os.path.join(work, 'prog-final.mp4' if a.final else 'proxy-video.mp4')
+ ffmpeg('-f', 'concat', '-safe', '0', '-i', lst, '-c', 'copy', '-movflags', '+faststart', vid)
+ n = int(subprocess.run(['ffprobe', '-v', 'error', '-count_packets', '-select_streams', 'v', '-show_entries',
+ 'stream=nb_read_packets', '-of', 'csv=p=0', vid], capture_output=True, text=True).stdout.strip())
+ print(f'video: {n} frames (expected {prog["frames"]})' + ('' if n == prog['frames'] else ' <-- MISMATCH'))
+ if not a.final:
+ wav = os.path.join(work, 'prog.wav')
+ if not os.path.exists(wav):
+ sys.exit('work/prog.wav missing: run the audio step first')
+ ffmpeg('-i', vid, '-i', wav, '-map', '0:v', '-map', '1:a', '-c:v', 'copy', '-c:a', 'aac', '-b:a', '256k',
+ '-movflags', '+faststart', os.path.join(work, 'proxy.new.mp4'))
+ os.replace(os.path.join(work, 'proxy.new.mp4'), os.path.join(work, 'proxy.mp4'))
+ os.remove(vid)
+ print('preview: work/proxy.mp4')
+ else:
+ print('render background: work/prog-final.mp4')
+ for f in os.listdir(seg_dir):
+ os.remove(os.path.join(seg_dir, f))
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument('steps', nargs='*', default=['audio', 'video'])
+ ap.add_argument('--project', default='.')
+ ap.add_argument('--final', action='store_true')
+ ap.add_argument('--target', type=float, default=-14.0)
+ ap.add_argument('--ceiling', type=float, default=-1.0)
+ ap.add_argument('--limiter', action='store_true')
+ ap.add_argument('--highpass', type=float, default=None)
+ ap.add_argument('--hw', action='store_true')
+ ap.add_argument('--workers', type=int, default=4)
+ a = ap.parse_args()
+ root, work = project_paths(a.project)
+ prog = load_json(os.path.join(work, 'program.json'))
+ if 'audio' in a.steps:
+ build_audio(root, work, prog, a)
+ if 'video' in a.steps:
+ build_video(root, work, prog, a)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/scripts/cuts.py b/scripts/cuts.py
new file mode 100644
index 0000000..b06086e
--- /dev/null
+++ b/scripts/cuts.py
@@ -0,0 +1,217 @@
+#!/usr/bin/env python3
+"""Edit list -> program: frame-exact pieces whose cut points sit on real word edges.
+
+Cut points come from the 10 ms energy envelope, not from Whisper word times (those are often 0.1-0.4 s off):
+ - long pauses inside a kept utterance are removed (pace: natural / tight)
+ - word ends are extended while the level stays above the soft floor (decaying syllables are kept)
+ - a short release burst after a stop consonant (t, k, p) is kept
+ - word starts are pulled back over soft onsets
+ - frame rounding goes outward, never into a word
+
+usage:
+ python3 scripts/cuts.py --project . # work/edl.json -> work/program.json + work/chapters.txt
+ python3 scripts/cuts.py --project . --peek CLIP A B # print the envelope between A and B seconds (finding cut points)
+"""
+import argparse
+import os
+import sys
+
+import numpy as np
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from _common import ENV_HOP, fmt_time, load_json, project_paths, save_json, yt_time # noqa: E402
+
+PACES = {
+ 'natural': {'head': 0.10, 'tail': 0.16, 'maxgap': 0.35},
+ 'tight': {'head': 0.04, 'tail': 0.06, 'maxgap': 0.15},
+}
+SOFT = -61.0 # a decaying syllable is still "speech" above this level (dB)
+END_EXT = 0.10 # max extension of a word end over a soft decay
+START_EXT = 0.06 # max extension of a word start over a soft onset
+BURST_ON, BURST_OFF, BURST_MAX = -68.0, -72.0, 12 # release burst after a stop consonant (max 12 x 10 ms)
+SNAP_WIN = 0.15 # hand-set points snap to the quietest 10 ms within this window
+
+
+class Clip:
+ def __init__(self, work, cid):
+ tp = os.path.join(work, 'transcripts', f'{cid}.json')
+ ep = os.path.join(work, 'env', f'{cid}.npy')
+ if not os.path.exists(tp) or not os.path.exists(ep):
+ sys.exit(f'clip "{cid}" has no transcript/envelope: run transcribe.py on it first')
+ self.t = load_json(tp)
+ self.env = np.load(ep).astype(np.float64)
+ self.speech = self.t['regions']
+ self.utts = self.t['utterances']
+ self.src = self.t['src']
+ # levels were tuned on a quiet room (noise floor about -80 dB); in a noisier room they follow the floor
+ floor = float(np.percentile(self.env, 10))
+ self.soft = max(SOFT, floor + 6)
+ self.burst_on, self.burst_off = max(BURST_ON, floor + 10), max(BURST_OFF, floor + 5)
+
+ def db(self, t):
+ i = int(t / ENV_HOP)
+ return self.env[min(max(i, 0), len(self.env) - 1)]
+
+ def snap(self, t):
+ e = self.env
+ i0, i1 = max(0, int((t - SNAP_WIN) / ENV_HOP)), min(len(e) - 1, int((t + SNAP_WIN) / ENV_HOP))
+ i = min(range(i0, i1 + 1), key=lambda j: (e[j], abs(j - t / ENV_HOP)))
+ return (i + 0.5) * ENV_HOP
+
+
+def refine(clip, regs, lo_bound, hi_bound):
+ """Extend each speech region over soft word ends, release bursts and soft onsets, staying inside bounds."""
+ env, n = clip.env, len(clip.env)
+ out = []
+ for j, (a, b) in enumerate(regs):
+ lo = regs[j - 1][1] + 0.05 if j else lo_bound
+ hi = regs[j + 1][0] - 0.05 if j + 1 < len(regs) else hi_bound
+ i = int(round(b / ENV_HOP))
+ q = i
+ while q < n and q - i < round(END_EXT / ENV_HOP) and env[q] > clip.soft and (q + 1) * ENV_HOP < hi:
+ q += 1
+ for kb in range(q, min(n, q + 8)): # closure of up to 80 ms, then a short burst, then silence
+ if (kb + 1) * ENV_HOP >= hi:
+ break
+ if env[kb] > clip.burst_on:
+ L = 0
+ while kb + L < n and env[kb + L] > clip.burst_off and L <= BURST_MAX:
+ L += 1
+ if L <= BURST_MAX and kb + L < n and env[kb + L] <= clip.burst_off and (kb + L) * ENV_HOP < hi:
+ q = kb + L
+ break
+ i0 = int(round(a / ENV_HOP))
+ h = i0
+ while h > 0 and i0 - h < round(START_EXT / ENV_HOP) and env[h - 1] > clip.soft and (h - 1) * ENV_HOP > lo:
+ h -= 1
+ out.append([min(a, h * ENV_HOP), max(b, q * ENV_HOP)])
+ return out
+
+
+def build(project):
+ root, work = project_paths(project)
+ edl = load_json(os.path.join(work, 'edl.json'))
+ fps = int(edl.get('fps', 30))
+ pace = PACES[edl.get('pace', 'natural')]
+ clips_map = dict(load_json(os.path.join(work, 'clips.json'))) if os.path.exists(os.path.join(work, 'clips.json')) else {}
+ clips_map.update(edl.get('clips', {}))
+ cache = {}
+
+ def C(cid):
+ if cid not in cache:
+ cache[cid] = Clip(work, cid)
+ return cache[cid]
+
+ pieces, entries, chapters, pf = [], [], [], 0
+ for item in edl['items']:
+ if 'note' in item and len(item) == 1:
+ continue
+ if 'chapter' in item:
+ chapters.append({'title': item['chapter'], 'frame': pf, 'time': round(pf / fps, 3)})
+ continue
+ cid = item['clip']
+ c = C(cid)
+ if 'range' in item:
+ a, b = item['range']
+ af, bf = int(a * fps), -int(-b * fps)
+ pieces.append({'clip': cid, 'a': af, 'b': bf, 'p': pf, 'e': len(entries)})
+ entries.append({'clip': cid, 'range': [a, b], 'pieces': [len(pieces) - 1], 'text': ''})
+ pf += bf - af
+ continue
+ u = item['utt']
+ ui = u if isinstance(u, list) else [u, u]
+ if ui[1] >= len(c.utts):
+ sys.exit(f'{cid}: utterance {ui[1]} does not exist ({len(c.utts)} utterances)')
+ exact = item.get('exact', False)
+ cutS, cutE = item.get('start') is not None, item.get('end') is not None
+ S = (item['start'] if exact else c.snap(item['start'])) if cutS else c.utts[ui[0]]['start']
+ E = (item['end'] if exact else c.snap(item['end'])) if cutE else c.utts[ui[1]]['end']
+ sp = c.speech
+ regs = [[max(a, S), min(b, E)] for a, b in sp if b > S and a < E]
+ regs = [r for r in regs if r[1] - r[0] > 0.03]
+ if not regs:
+ print(f'warning: {cid} utt {u}: no speech between {S:.2f} and {E:.2f}, skipped')
+ continue
+ prev_sp = max([b for a, b in sp if b <= regs[0][0] + 1e-6] or [0.0])
+ next_sp = min([a for a, b in sp if a >= regs[-1][1] - 1e-6] or [1e9])
+ lo_bound = S if cutS else prev_sp + 0.05
+ hi_bound = E if cutE else next_sp - 0.05
+ regs = refine(c, regs, lo_bound, hi_bound)
+ gap = 1e9 if item.get('keep_pauses') else pace['maxgap']
+ merged = []
+ for r in regs:
+ if merged and r[0] - merged[-1][1] <= gap:
+ merged[-1][1] = r[1]
+ else:
+ merged.append(list(r))
+ ent = {'clip': cid, 'utt': ui, 'pieces': [],
+ 'text': ' '.join(c.utts[i]['text'] for i in range(ui[0], ui[1] + 1))}
+ for j, (a, b) in enumerate(merged):
+ pe = max([y for x, y in sp if y <= a + 1e-6] or [0.0])
+ ns = min([x for x, y in sp if x >= b - 1e-6] or [1e9])
+ a2 = a - 0.02 if (j == 0 and cutS) else max(a - pace['head'], pe + 0.04, (a + pe) / 2)
+ b2 = b + 0.02 if (j == len(merged) - 1 and cutE) else min(b + pace['tail'], ns - 0.04, (b + ns) / 2)
+ af, bf = int(max(0.0, a2) * fps), -int(-b2 * fps)
+ if bf <= af:
+ continue
+ p = {'clip': cid, 'a': af, 'b': bf, 'p': pf, 'e': len(entries)}
+ if j == len(merged) - 1 and cutE and exact:
+ p['fade_out'] = 0.05 # a hand-set end inside running speech fades over 50 ms
+ pieces.append(p)
+ ent['pieces'].append(len(pieces) - 1)
+ pf += bf - af
+ entries.append(ent)
+
+ words = []
+ for p in pieces:
+ a, b = p['a'] / fps, p['b'] / fps
+ for u in C(p['clip']).utts:
+ if u['end'] < a or u['start'] > b:
+ continue
+ for w0, w1, w in u['words']:
+ if w1 > a + 0.04 and w0 < b - 0.04:
+ s0, e0 = max(w0, a), min(w1, b)
+ words.append([round(p['p'] / fps + s0 - a, 3), round(p['p'] / fps + e0 - a, 3), w, p['e']])
+ words.sort()
+ joins = [round(p['p'] / fps, 3) for p in pieces[1:]]
+ prog = {'fps': fps, 'frames': pf, 'duration': round(pf / fps, 3), 'clips': clips_map, 'pieces': pieces,
+ 'entries': entries, 'chapters': chapters, 'joins': joins, 'words': words}
+ save_json(os.path.join(work, 'program.json'), prog)
+
+ raw = sum(C(k).speech[-1][1] for k in {p['clip'] for p in pieces} if C(k).speech)
+ print(f'{len(pieces)} pieces, {len(entries)} entries, program {fmt_time(pf / fps)} (speech in used clips {fmt_time(raw)})')
+ if chapters:
+ if chapters[0]['frame'] != 0:
+ print('note: the first chapter does not start at 0:00; YouTube needs one there')
+ lines = [f"{yt_time(ch['time'])} {ch['title']}" for ch in chapters]
+ with open(os.path.join(work, 'chapters.txt'), 'w', encoding='utf-8') as f:
+ f.write('\n'.join(lines) + '\n')
+ print('YouTube chapters (work/chapters.txt):')
+ for ln in lines:
+ print(' ' + ln)
+ short = [ch['title'] for ch, nx in zip(chapters, chapters[1:] + [{'time': pf / fps}]) if nx['time'] - ch['time'] < 10]
+ if short or len(chapters) < 3:
+ print('note: YouTube needs at least 3 chapters, each 10 s or longer')
+
+
+def peek(project, cid, a, b):
+ _, work = project_paths(project)
+ c = Clip(work, cid)
+ print(f'{cid} envelope {a:.2f}-{b:.2f} s (dB per 10 ms; threshold {c.t["threshold"]:.1f}, soft floor {c.soft:.1f})')
+ words = [w for u in c.utts for w in u['words'] if w[1] > a and w[0] < b]
+ for i in range(int(a / ENV_HOP), int(b / ENV_HOP)):
+ t = i * ENV_HOP
+ lab = ' '.join(w[2] for w in words if abs(w[0] - t) < ENV_HOP / 2)
+ bar = '#' * max(0, int((c.env[i] + 80) / 2))
+ print(f'{t:8.2f} {c.env[i]:6.1f} {bar:<40} {lab}')
+
+
+if __name__ == '__main__':
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument('--project', default='.')
+ ap.add_argument('--peek', nargs=3, metavar=('CLIP', 'A', 'B'))
+ a = ap.parse_args()
+ if a.peek:
+ peek(a.project, a.peek[0], float(a.peek[1]), float(a.peek[2]))
+ else:
+ build(a.project)
diff --git a/scripts/loudness.py b/scripts/loudness.py
new file mode 100644
index 0000000..8ba802e
--- /dev/null
+++ b/scripts/loudness.py
@@ -0,0 +1,38 @@
+#!/usr/bin/env python3
+"""Loudness report for any audio or video file: integrated LUFS, true peak, loudness range, with a plain verdict.
+
+usage: python3 scripts/loudness.py FILE [FILE ...] [--target -14]
+Measures the real channels (a mono downmix with -ac 1 would report a false peak about 3 dB too high).
+"""
+import argparse
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from _common import loudness # noqa: E402
+
+
+def verdict(i, tp, lra, target):
+ out = []
+ if i < target - 2:
+ out.append(f'quiet: {target - i:.1f} dB under {target} LUFS. Platforms do not turn quiet videos up.')
+ elif i > target + 1:
+ out.append(f'loud: platforms will turn it down by about {i - target:.1f} dB; peaks get no benefit.')
+ else:
+ out.append('loudness is on target.')
+ if tp > -1.0:
+ out.append(f'true peak {tp:.1f} dBTP is above -1 dBTP: risk of distortion after encoding.')
+ if lra > 12:
+ out.append(f'loudness range {lra:.1f} LU is wide: some parts are much quieter than others.')
+ return ' '.join(out)
+
+
+if __name__ == '__main__':
+ ap = argparse.ArgumentParser(description=__doc__)
+ ap.add_argument('files', nargs='+')
+ ap.add_argument('--target', type=float, default=-14.0)
+ a = ap.parse_args()
+ for f in a.files:
+ i, tp, lra = loudness(f)
+ print(f'{os.path.basename(f)}: {i:.1f} LUFS, true peak {tp:.1f} dBTP, LRA {lra:.1f} LU')
+ print(' ' + verdict(i, tp, lra, a.target))
diff --git a/scripts/mix.py b/scripts/mix.py
new file mode 100644
index 0000000..a7bb521
--- /dev/null
+++ b/scripts/mix.py
@@ -0,0 +1,84 @@
+#!/usr/bin/env python3
+"""Final mix: rendered video + program voice + sound-effects track -> one file.
+
+The voice keeps the level build.py gave it. Effects are added under it. If the sum would pass the true-peak
+ceiling, the whole mix is lowered by the excess (linear, no limiter), and the report says so.
+
+usage:
+ python3 scripts/mix.py --project . --video out/frames --out out/FINAL.mp4 [--sfx-gain 0] [--no-sfx]
+ --video a render folder from render.mjs (part_*.mp4 + sfx.json) or a single video file
+"""
+import argparse
+import glob
+import json
+import os
+import re
+import sys
+import tempfile
+
+import numpy as np
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from _common import decode, ffmpeg, loudness, project_paths, write_wav # noqa: E402
+from sfx import SR, MAKERS, make # noqa: E402
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument('--project', default='.')
+ ap.add_argument('--video', required=True)
+ ap.add_argument('--out', required=True)
+ ap.add_argument('--sfx-gain', type=float, default=0.0)
+ ap.add_argument('--no-sfx', action='store_true')
+ ap.add_argument('--ceiling', type=float, default=-1.0)
+ a = ap.parse_args()
+ root, work = project_paths(a.project)
+ tmp = tempfile.mkdtemp(prefix='ve-mix-')
+
+ if os.path.isdir(a.video):
+ parts = sorted(glob.glob(os.path.join(a.video, 'part_*.mp4')),
+ key=lambda p: int(re.search(r'part_(\d+)', p).group(1)))
+ if not parts:
+ sys.exit(f'no part_*.mp4 in {a.video}')
+ lst = os.path.join(tmp, 'parts.txt')
+ with open(lst, 'w') as f:
+ f.write(''.join(f"file '{os.path.abspath(p)}'\n" for p in parts))
+ video_in = ['-f', 'concat', '-safe', '0', '-i', lst]
+ cues_path = os.path.join(a.video, 'sfx.json')
+ else:
+ video_in = ['-i', a.video]
+ cues_path = os.path.join(os.path.dirname(a.video), 'sfx.json')
+
+ voice = decode(os.path.join(work, 'prog.wav'), SR, 2).astype(np.float64)
+ mix = voice.copy()
+ cues = []
+ if not a.no_sfx and os.path.exists(cues_path):
+ with open(cues_path, encoding='utf-8') as f:
+ cues = json.load(f)
+ lib = {}
+ for c in cues:
+ if c['name'] not in MAKERS:
+ sys.exit(f'unknown effect {c["name"]}')
+ if c['name'] not in lib:
+ lib[c['name']] = make(c['name'], a.sfx_gain)
+ x = lib[c['name']] * 10 ** (c.get('gain', 0) / 20)
+ s = int(c['t'] * SR)
+ if s < len(mix):
+ mix[s:s + len(x)] += x[:len(mix) - s]
+ wav = os.path.join(tmp, 'mix.wav')
+ write_wav(wav, mix)
+ i, tp, lra = loudness(wav)
+ if tp > a.ceiling:
+ g = a.ceiling - tp - 0.1
+ mix *= 10 ** (g / 20)
+ write_wav(wav, mix)
+ print(f'note: effects pushed the true peak to {tp:.1f} dBTP; whole mix lowered by {-g:.1f} dB')
+ i, tp, lra = loudness(wav)
+
+ ffmpeg(*video_in, '-i', wav, '-map', '0:v', '-map', '1:a', '-c:v', 'copy', '-c:a', 'aac', '-b:a', '320k',
+ '-shortest', '-movflags', '+faststart', a.out)
+ print(f'{a.out}: {len(cues)} effects, {i:.1f} LUFS, true peak {tp:.1f} dBTP, LRA {lra:.1f} LU')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/scripts/render.mjs b/scripts/render.mjs
new file mode 100644
index 0000000..df95343
--- /dev/null
+++ b/scripts/render.mjs
@@ -0,0 +1,131 @@
+// Frame-exact render of a scene page in headless Chrome, piped into ffmpeg. Parallel workers, resumable.
+//
+// usage:
+// node scripts/render.mjs URL --out out/frames [--workers 4] [--dpr 2] [--from 0] [--to END] [--crf 18]
+// node scripts/render.mjs URL --stills out/stills --at 3.5,12,40.2 (check frames as JPG)
+//
+// The page must be a scene from the template: ?still is added, and every frame is prepared with
+// window.__scene.render(t). The stage size comes from the page (1920x1080 -> 3840x2160 at --dpr 2).
+// Each slice is written to part_<i>.mp4; a slice that already exists is skipped, so a stopped render resumes.
+// sfx.json (the effect cues of the scene) is written next to the parts for mix.py.
+import { spawn } from 'node:child_process';
+import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { ensureWebSocket, openPage, withParam } from './_cdp.mjs';
+
+if (!ensureWebSocket()) await new Promise(() => {});
+
+const args = process.argv.slice(2);
+const opt = (k, d) => { const i = args.indexOf(`--${k}`); return i >= 0 ? args[i + 1] : d; };
+const URL0 = args[0];
+if (!URL0 || URL0.startsWith('--')) { console.error('usage: node scripts/render.mjs URL --out DIR [--workers 4] [--dpr 2]'); process.exit(1); }
+const OUT = opt('out', null), STILLS = opt('stills', null), DPR = +opt('dpr', 2), CRF = opt('crf', '18');
+const WORKERS = +opt('workers', 4), WORKER = opt('worker', null);
+const url = withParam(URL0, 'still');
+
+async function pageInfo() {
+ const p = await openPage({ width: 640, height: 360 });
+ await p.goto(url);
+ const info = await p.evaluate(`({ w: +document.body.dataset.w || 1920, h: +document.body.dataset.h || 1080,
+ fps: window.__scene.fps || 30, duration: window.__scene.duration, missing: window.__scene.missing, sfx: window.__scene.SFX })`);
+ p.close();
+ return info;
+}
+
+/* ---------- stills ---------- */
+if (STILLS) {
+ const info = await pageInfo();
+ mkdirSync(STILLS, { recursive: true });
+ const p = await openPage({ width: info.w, height: info.h, dpr: +opt('dpr', 1) });
+ await p.goto(url);
+ for (const t of opt('at', '0').split(',').map(Number)) {
+ await p.evaluate(`window.__scene.render(${t})`);
+ await p.evaluate('new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)))');
+ const f = join(STILLS, `t${t.toFixed(2)}.jpg`);
+ writeFileSync(f, await p.shot(92));
+ console.log(f);
+ }
+ p.close();
+ process.exit(0);
+}
+
+if (!OUT) { console.error('--out DIR is required'); process.exit(1); }
+mkdirSync(OUT, { recursive: true });
+const planPath = join(OUT, 'plan.json');
+
+/* ---------- coordinator ---------- */
+if (WORKER === null) {
+ const info = await pageInfo();
+ if (info.missing && info.missing.length) {
+ console.error(`the scene has phrases that were not found in the words: ${JSON.stringify(info.missing)}`);
+ console.error('fix them (or remove the beats) before rendering');
+ process.exit(3);
+ }
+ const fps = info.fps, total = Math.round(info.duration * fps);
+ const f0 = Math.round(+opt('from', 0) * fps), f1 = Math.min(total, Math.round(+opt('to', info.duration) * fps));
+ const nSlices = Math.max(1, Math.min(WORKERS * 4, Math.ceil((f1 - f0) / 60)));
+ const per = Math.ceil((f1 - f0) / nSlices);
+ const slices = [...Array(nSlices).keys()].map((i) => [f0 + i * per, Math.min(f1, f0 + (i + 1) * per)]).filter(([a, b]) => b > a);
+ writeFileSync(planPath, JSON.stringify({ url, fps, dpr: DPR, w: info.w, h: info.h, crf: CRF, slices }, null, 1));
+ writeFileSync(join(OUT, 'sfx.json'), JSON.stringify(info.sfx || []));
+ console.log(`render: ${f1 - f0} frames (${((f1 - f0) / fps).toFixed(2)} s) at ${info.w * DPR}x${info.h * DPR}, ${slices.length} slices, ${WORKERS} workers`);
+ const t0 = Date.now();
+ const runOne = (i) => new Promise((res) => {
+ const k = spawn(process.execPath, [...process.execArgv, fileURLToPath(import.meta.url), URL0, '--out', OUT, '--worker', String(i)], { stdio: 'inherit' });
+ k.on('close', (c) => res(c ?? 1));
+ });
+ const codes = slices.map(() => null);
+ let next = 0;
+ const lane = async () => {
+ while (next < slices.length) {
+ const i = next++;
+ if (existsSync(join(OUT, `part_${i}.mp4`))) { codes[i] = 0; continue; }
+ let c = 1;
+ for (let k = 0; k < 3 && c !== 0; k++) { if (k) console.log(`slice ${i}: retry ${k}`); c = await runOne(i); }
+ codes[i] = c;
+ }
+ };
+ await Promise.all([...Array(Math.min(WORKERS, slices.length))].map(lane));
+ const bad = codes.filter((c) => c).length;
+ console.log(`${bad ? bad + ' slice(s) failed' : 'all slices done'} in ${((Date.now() - t0) / 60000).toFixed(1)} min -> ${OUT}`);
+ process.exit(bad ? 1 : 0);
+}
+
+/* ---------- worker: one slice ---------- */
+const P = JSON.parse(readFileSync(planPath, 'utf8'));
+const wi = +WORKER, [a, b] = P.slices[wi];
+let beat = Date.now();
+setInterval(() => { if (Date.now() - beat > 90000) { console.error(`slice ${wi}: no progress for 90 s`); process.exit(4); } }, 5000).unref();
+
+const page = await openPage({ width: P.w, height: P.h, dpr: P.dpr });
+await page.goto(P.url);
+const tmp = join(OUT, `part_${wi}.tmp.mp4`);
+const ff = spawn('ffmpeg', [
+ '-v', 'error', '-y', '-f', 'image2pipe', '-framerate', String(P.fps), '-c:v', 'mjpeg', '-i', '-',
+ // Chrome's JPEG is full-range BT.601; video platforms expect limited-range BT.709
+ '-vf', 'scale=in_range=full:out_range=tv:in_color_matrix=bt601:out_color_matrix=bt709,format=yuv420p',
+ '-c:v', 'libx264', '-preset', 'medium', '-crf', String(P.crf), '-profile:v', 'high', '-g', String(P.fps * 2),
+ '-color_primaries', 'bt709', '-color_trc', 'bt709', '-colorspace', 'bt709', '-color_range', 'tv',
+ '-r', String(P.fps), '-an', tmp,
+], { stdio: ['pipe', 'inherit', 'inherit'] });
+
+const n = b - a, t0 = Date.now();
+for (let i = 0; i < n; i++) {
+ const t = (a + i) / P.fps + 0.0005; // half a millisecond into the frame: a seek never lands on the previous frame
+ await page.evaluate(`window.__scene.render(${t.toFixed(5)})`);
+ await page.evaluate('new Promise((r) => { let k = 0; const f = () => (++k >= 2 ? r() : requestAnimationFrame(f)); requestAnimationFrame(f); setTimeout(r, 400); })');
+ const buf = await page.shot(96);
+ beat = Date.now();
+ if (!ff.stdin.write(buf)) await new Promise((r) => ff.stdin.once('drain', r));
+ if (i % 150 === 0 || i === n - 1) {
+ const rate = (i + 1) / ((Date.now() - t0) / 1000);
+ console.log(`slice ${wi}: ${i + 1}/${n} · ${rate.toFixed(1)} fps · ~${((n - i - 1) / rate / 60).toFixed(1)} min left`);
+ }
+}
+ff.stdin.end();
+const code = await new Promise((r) => ff.on('close', r));
+page.close();
+if (code !== 0) { console.error(`slice ${wi}: ffmpeg exited ${code}`); process.exit(5); }
+renameSync(tmp, join(OUT, `part_${wi}.mp4`));
+process.exit(0);
diff --git a/scripts/serve.py b/scripts/serve.py
new file mode 100644
index 0000000..86e7adc
--- /dev/null
+++ b/scripts/serve.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python3
+"""Static file server with HTTP Range support (browsers need it to seek inside video files).
+
+usage: python3 scripts/serve.py --project . [--port 5600] -> http://127.0.0.1:5600/scene/
+"""
+import argparse
+import http.server
+import os
+import re
+
+
+class RangeHandler(http.server.SimpleHTTPRequestHandler):
+ def end_headers(self):
+ self.send_header('Cache-Control', 'no-store')
+ self.send_header('Accept-Ranges', 'bytes')
+ super().end_headers()
+
+ def send_head(self):
+ rng = self.headers.get('Range')
+ path = self.translate_path(self.path)
+ if not rng or not os.path.isfile(path):
+ return super().send_head()
+ m = re.match(r'bytes=(\d*)-(\d*)', rng)
+ size = os.path.getsize(path)
+ if not m:
+ return super().send_head()
+ start = int(m.group(1)) if m.group(1) else max(0, size - int(m.group(2) or 0))
+ end = int(m.group(2)) if m.group(1) and m.group(2) else size - 1
+ if start >= size:
+ self.send_error(416)
+ return None
+ end = min(end, size - 1)
+ f = open(path, 'rb')
+ f.seek(start)
+ self.send_response(206)
+ self.send_header('Content-Type', self.guess_type(path))
+ self.send_header('Content-Range', f'bytes {start}-{end}/{size}')
+ self.send_header('Content-Length', str(end - start + 1))
+ self.end_headers()
+ self._remaining = end - start + 1
+ return f
+
+ def copyfile(self, source, outputfile):
+ left = getattr(self, '_remaining', None)
+ if left is None:
+ return super().copyfile(source, outputfile)
+ try:
+ while left > 0:
+ buf = source.read(min(1 << 16, left))
+ if not buf:
+ break
+ outputfile.write(buf)
+ left -= len(buf)
+ except (BrokenPipeError, ConnectionResetError):
+ pass
+ finally:
+ self._remaining = None
+
+ def log_message(self, *args):
+ pass
+
+
+if __name__ == '__main__':
+ ap = argparse.ArgumentParser(description=__doc__)
+ ap.add_argument('--project', default='.')
+ ap.add_argument('--port', type=int, default=5600)
+ a = ap.parse_args()
+ os.chdir(os.path.abspath(a.project))
+ srv = http.server.ThreadingHTTPServer(('127.0.0.1', a.port), RangeHandler)
+ print(f'serving {os.getcwd()} on http://127.0.0.1:{a.port}/scene/')
+ srv.serve_forever()
diff --git a/scripts/sfx.py b/scripts/sfx.py
new file mode 100644
index 0000000..52b9cf4
--- /dev/null
+++ b/scripts/sfx.py
@@ -0,0 +1,198 @@
+#!/usr/bin/env python3
+"""Sound effects synthesized from math. No downloads, no licences, the same file every time (fixed seeds).
+
+ whoosh filtered noise whose band sweeps up and back down, panned left to right (chapter veils)
+ soft-whoosh lower, longer, darker whoosh (calm videos)
+ tick tiny high sine blip (a counter step, a checkbox)
+ click mouse click: short bright noise burst + a small low thump
+ key one mechanical key press: bright contact click, a woody body, a softer bottom-out
+ typing a burst of key presses at human pace (pitch, level and timing vary a little)
+ pop short sine with a falling pitch (a card or a badge appearing)
+ chime soft bar-like bell from inharmonic partials (a success / done moment)
+
+Levels are peaks of each effect alone, set low on purpose (see reference/audio.md). Shift them all with --gain.
+
+usage:
+ python3 scripts/sfx.py lib --out scene/sfx [--gain 0] # write every effect as WAV
+ python3 scripts/sfx.py track --cues out/sfx.json --duration 612.4 --out work/sfx.wav [--gain 0]
+ cues: [{"t": 12.30, "name": "whoosh", "gain": 0}, ...] (exported by the scene / render.mjs)
+"""
+import argparse
+import json
+import os
+import sys
+
+import numpy as np
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from _common import write_wav # noqa: E402
+
+SR = 48000
+LEVELS = { # default peak in dBFS of each effect on its own
+ 'whoosh': -32, 'soft-whoosh': -32, 'tick': -30, 'click': -30, 'key': -32, 'typing': -32, 'pop': -30, 'chime': -30,
+}
+
+
+def t_axis(dur):
+ return np.arange(int(dur * SR)) / SR
+
+
+def one_pole_lowpass(x, fc):
+ """Lowpass whose cutoff may change per sample (fc array in Hz)."""
+ a = np.exp(-2 * np.pi * np.asarray(fc, dtype=np.float64) / SR) * np.ones(len(x))
+ y = np.empty(len(x))
+ s = 0.0
+ for i in range(len(x)):
+ s = (1 - a[i]) * x[i] + a[i] * s
+ y[i] = s
+ return y
+
+
+def bandpass_noise(n, lo, hi, rng):
+ x = rng.standard_normal(n)
+ y = one_pole_lowpass(x, np.full(n, hi))
+ return y - one_pole_lowpass(y, np.full(n, lo))
+
+
+def stereo(sig, pan0=0.5, pan1=None):
+ """Equal-power pan, 0 = left, 1 = right; a sweep when pan1 is given."""
+ p = np.full(len(sig), pan0) if pan1 is None else np.linspace(pan0, pan1, len(sig))
+ return np.stack([sig * np.cos(p * np.pi / 2), sig * np.sin(p * np.pi / 2)], 1)
+
+
+def whoosh(dur=1.15, f0=260, f1=2600, f2=700, pan=(0.15, 0.85), seed=7, peak_at=0.58):
+ rng = np.random.default_rng(seed)
+ n = int(dur * SR)
+ u = np.arange(n) / n
+ fc = np.where(u < peak_at, f0 + (f1 - f0) * (u / peak_at) ** 1.4, f1 + (f2 - f1) * ((u - peak_at) / (1 - peak_at)))
+ lp = one_pole_lowpass(rng.standard_normal(n), fc)
+ hp = lp - np.convolve(lp, np.ones(64) / 64, mode='same')
+ sig = 0.6 * lp + 0.4 * hp
+ env = np.where(u < peak_at, np.sin(np.pi / 2 * u / peak_at) ** 2, np.cos(np.pi / 2 * (u - peak_at) / (1 - peak_at)) ** 2)
+ return stereo(sig * env, *pan)
+
+
+def soft_whoosh():
+ return whoosh(dur=1.45, f0=160, f1=1300, f2=420, pan=(0.3, 0.7), seed=11, peak_at=0.5)
+
+
+def tick(f=2300, seed=3):
+ t = t_axis(0.05)
+ sig = np.sin(2 * np.pi * f * t) * np.exp(-t / 0.009)
+ rng = np.random.default_rng(seed)
+ sig[:96] += 0.25 * rng.standard_normal(96) * np.linspace(1, 0, 96)
+ return stereo(sig)
+
+
+def click(seed=5):
+ rng = np.random.default_rng(seed)
+ t = t_axis(0.08)
+ burst = bandpass_noise(len(t), 1800, 7000, rng) * np.exp(-t / 0.0025)
+ thump = np.sin(2 * np.pi * 170 * t) * np.exp(-t / 0.02) * 0.5
+ return stereo(burst / (np.abs(burst).max() + 1e-9) + thump)
+
+
+def key(seed=1, pitch=1.0, level=1.0):
+ """One key press: contact click, body resonance, bottom-out."""
+ rng = np.random.default_rng(seed)
+ t = t_axis(0.16)
+ n = len(t)
+ contact = bandpass_noise(n, 2500, 9000, rng) * np.exp(-t / 0.0018)
+ contact /= np.abs(contact).max() + 1e-9
+ f_body = 300 * pitch * (1 + 0.06 * rng.standard_normal())
+ body = (np.sin(2 * np.pi * f_body * t) + 0.4 * np.sin(2 * np.pi * f_body * 2.3 * t)) * np.exp(-t / 0.028) * 0.55
+ d = int((0.018 + 0.012 * rng.random()) * SR)
+ bottom = np.zeros(n)
+ bt = t[:n - d]
+ bottom[d:] = (bandpass_noise(n - d, 900, 5000, rng) * np.exp(-bt / 0.004))
+ bottom /= np.abs(bottom).max() + 1e-9
+ sig = contact * 0.9 + body + bottom * 0.45
+ return stereo(sig * level, 0.5 + 0.08 * rng.standard_normal())
+
+
+def typing(chars=14, seed=2, mean_gap=0.105):
+ """A burst of key presses at human pace; a space bar is a little lower and longer."""
+ rng = np.random.default_rng(seed)
+ times, t = [], 0.0
+ for i in range(chars):
+ times.append(t)
+ t += max(0.045, rng.normal(mean_gap, mean_gap * 0.35))
+ out = np.zeros((int((t + 0.2) * SR), 2))
+ for i, s in enumerate(times):
+ space = rng.random() < 0.15
+ k = key(seed=seed * 1000 + i, pitch=0.8 if space else 1 + 0.05 * rng.standard_normal(),
+ level=0.8 + 0.25 * rng.random())
+ a = int(s * SR)
+ out[a:a + len(k)] += k[:len(out) - a]
+ return out
+
+
+def pop(seed=0):
+ t = t_axis(0.09)
+ f = 300 + 600 * np.exp(-t / 0.012)
+ phase = 2 * np.pi * np.cumsum(f) / SR
+ sig = np.sin(phase) * np.exp(-t / 0.03) * np.minimum(1, t / 0.002)
+ return stereo(sig)
+
+
+def chime(f=880.0):
+ t = t_axis(1.6)
+ ratios, decays, amps = [1.0, 2.756, 5.404, 8.933], [0.55, 0.25, 0.12, 0.06], [1.0, 0.45, 0.25, 0.12]
+ sig = sum(a * np.sin(2 * np.pi * f * r * t) * np.exp(-t / d) for r, d, a in zip(ratios, decays, amps))
+ sig *= np.minimum(1, t / 0.003)
+ return stereo(sig)
+
+
+MAKERS = {'whoosh': whoosh, 'soft-whoosh': soft_whoosh, 'tick': tick, 'click': click, 'key': key,
+ 'typing': typing, 'pop': pop, 'chime': chime}
+
+
+def make(name, gain=0.0):
+ x = MAKERS[name]()
+ x = x / (np.abs(x).max() + 1e-12) * 10 ** ((LEVELS[name] + gain) / 20)
+ return x.astype(np.float32)
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ sub = ap.add_subparsers(dest='cmd', required=True)
+ p = sub.add_parser('lib')
+ p.add_argument('--out', required=True)
+ p.add_argument('--gain', type=float, default=0.0, help='dB added to every default level')
+ p = sub.add_parser('track')
+ p.add_argument('--cues', required=True)
+ p.add_argument('--duration', type=float, required=True)
+ p.add_argument('--out', required=True)
+ p.add_argument('--gain', type=float, default=0.0)
+ a = ap.parse_args()
+
+ if a.cmd == 'lib':
+ os.makedirs(a.out, exist_ok=True)
+ for name in MAKERS:
+ x = make(name, a.gain)
+ write_wav(os.path.join(a.out, f'{name}.wav'), x, bits=16)
+ print(f'{name:12s} {len(x) / SR:.2f} s peak {LEVELS[name] + a.gain:.0f} dBFS')
+ return
+
+ with open(a.cues, encoding='utf-8') as f:
+ cues = json.load(f)
+ lib = {}
+ out = np.zeros((int(a.duration * SR) + 1, 2), np.float32)
+ for c in cues:
+ name = c['name']
+ if name not in MAKERS:
+ sys.exit(f'unknown effect "{name}"; known: {", ".join(MAKERS)}')
+ if name not in lib:
+ lib[name] = make(name, a.gain)
+ x = lib[name] * 10 ** (c.get('gain', 0) / 20)
+ s = int(c['t'] * SR)
+ if s >= len(out):
+ continue
+ out[s:s + len(x)] += x[:len(out) - s]
+ write_wav(a.out, out)
+ peak = 20 * np.log10(np.abs(out).max() + 1e-12)
+ print(f'{len(cues)} cues -> {a.out} ({a.duration:.1f} s, peak {peak:.1f} dBFS)')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/scripts/transcribe.py b/scripts/transcribe.py
new file mode 100644
index 0000000..dfbdda0
--- /dev/null
+++ b/scripts/transcribe.py
@@ -0,0 +1,196 @@
+#!/usr/bin/env python3
+"""Transcribe raw clips into numbered utterances with word times.
+
+Each clip is split at pauses into short chunks (<= 16 s). Every chunk is transcribed on its own, padded with
+silence (not with neighbouring audio, which makes Whisper invent half words). Transcribing whole files hides
+retakes: Whisper merges repeated sentences and drops repeated words.
+
+usage:
+ python3 scripts/transcribe.py --project . src/*.mov [--lang en] [--backend auto|faster-whisper|whisperkit]
+ [--model large-v3] [--thr -50]
+writes:
+ work/clips.json clip id -> source path
+ work/env/<id>.npy 10 ms energy envelope (dB), used by cuts.py
+ work/transcripts/<id>.json/.txt utterances: start, end, text, words [[start, end, word], ...] in source seconds
+"""
+import argparse
+import os
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+
+import numpy as np
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from _common import (ENV_HOP, envelope, fmt_time, load_json, project_paths, save_json, # noqa: E402
+ speech_regions, speech_threshold)
+
+SR = 16000
+PAD = 0.3 # seconds of silence around each chunk
+SPLIT_GAP = 0.42 # a pause this long starts a new utterance
+MAX_CHUNK = 16.0 # longer utterance groups are split at their largest pause
+
+
+def clip_id(path, taken):
+ base = re.sub(r'[^a-z0-9]+', '-', os.path.splitext(os.path.basename(path))[0].lower()).strip('-') or 'clip'
+ cid, k = base, 2
+ while cid in taken and taken[cid] != path:
+ cid, k = f'{base}-{k}', k + 1
+ return cid
+
+
+def plan_chunks(regions):
+ groups = []
+ for a, b in regions:
+ if groups and a - groups[-1][-1][1] < SPLIT_GAP:
+ groups[-1].append([a, b])
+ else:
+ groups.append([[a, b]])
+ out = []
+
+ def cut(rs):
+ if rs[-1][1] - rs[0][0] <= MAX_CHUNK or len(rs) < 2:
+ out.append([rs[0][0], rs[-1][1]])
+ return
+ gi = max(range(1, len(rs)), key=lambda i: rs[i][0] - rs[i - 1][1])
+ cut(rs[:gi])
+ cut(rs[gi:])
+
+ for rs in groups:
+ cut(rs)
+ return out
+
+
+def pick_backend(name):
+ if name in ('auto', 'faster-whisper'):
+ try:
+ import faster_whisper # noqa: F401
+ return 'faster-whisper'
+ except ImportError:
+ if name == 'faster-whisper':
+ sys.exit('faster-whisper is not installed: pip install faster-whisper')
+ if name in ('auto', 'whisperkit') and shutil.which('whisperkit-cli'):
+ return 'whisperkit'
+ sys.exit('No Whisper backend found. Install one: pip install faster-whisper (any OS) '
+ 'or brew install whisperkit-cli (Apple Silicon).')
+
+
+_FW = {}
+
+
+def transcribe_arrays(chunks, lang, backend, model):
+ """chunks: list of float32 mono arrays at 16 kHz. Returns a list of (text, [[s, e, word], ...]) per chunk,
+ times relative to the chunk start (padding removed)."""
+ pad = np.zeros(int(PAD * SR), np.float32)
+ tmp = tempfile.mkdtemp(prefix='ve-tr-')
+ try:
+ paths = []
+ for i, x in enumerate(chunks):
+ p = os.path.join(tmp, f'c{i:05d}.wav')
+ y = np.concatenate([pad, x.astype(np.float32), pad])
+ subprocess.run(['ffmpeg', '-v', 'error', '-y', '-f', 'f32le', '-ar', str(SR), '-ac', '1', '-i', '-', p],
+ input=y.tobytes(), check=True)
+ paths.append(p)
+ res = []
+ if backend == 'faster-whisper':
+ from faster_whisper import WhisperModel
+ if model not in _FW:
+ _FW[model] = WhisperModel(model, device='auto', compute_type='int8')
+ m = _FW[model]
+ for p in paths:
+ segs, _ = m.transcribe(p, language=lang, word_timestamps=True, condition_on_previous_text=False,
+ vad_filter=False, beam_size=5)
+ words, text = [], []
+ for s in segs:
+ text.append(s.text.strip())
+ for w in s.words or []:
+ if w.word.strip():
+ words.append([round(w.start - PAD, 3), round(w.end - PAD, 3), w.word.strip()])
+ res.append((' '.join(text).strip(), words))
+ else:
+ out = os.path.join(tmp, 'out')
+ os.makedirs(out)
+ cmd = ['whisperkit-cli', 'transcribe', '--audio-folder', tmp, '--word-timestamps', '--skip-special-tokens',
+ '--report', '--report-path', out]
+ if lang:
+ cmd += ['--language', lang]
+ cmd += ['--model-path', model] if os.path.isdir(model) else ['--model', model]
+ tok = os.environ.get('WHISPERKIT_TOKENIZER', os.path.expanduser('~/.cache/whisperkit/tok'))
+ if os.path.isdir(tok): # an offline tokenizer folder avoids a network fetch that can hang
+ cmd += ['--download-tokenizer-path', tok]
+ r = subprocess.run(cmd, capture_output=True, text=True)
+ for p in paths:
+ js = os.path.join(out, os.path.basename(p)[:-4] + '.json')
+ if not os.path.exists(js):
+ if r.returncode:
+ sys.exit(f'whisperkit-cli failed: {r.stderr[-800:]}')
+ res.append(('', []))
+ continue
+ d = load_json(js)
+ words = [[round(w['start'] - PAD, 3), round(w['end'] - PAD, 3), w['word'].strip()]
+ for s in d.get('segments', []) for w in s.get('words', []) if w['word'].strip()]
+ res.append((d.get('text', '').strip(), words))
+ return res
+ finally:
+ shutil.rmtree(tmp, ignore_errors=True)
+
+
+def load_mono(path):
+ raw = subprocess.run(['ffmpeg', '-v', 'error', '-i', path, '-vn', '-f', 'f32le', '-ac', '1', '-ar', str(SR), '-'],
+ capture_output=True).stdout
+ return np.frombuffer(raw, np.float32)
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument('clips', nargs='+')
+ ap.add_argument('--project', default='.')
+ ap.add_argument('--lang', default=None, help='language code (en, tr, de ...); auto-detect if omitted')
+ ap.add_argument('--backend', default='auto')
+ ap.add_argument('--model', default='large-v3', help='model name or local model folder')
+ ap.add_argument('--thr', type=float, default=None, help='speech threshold in dB (default: noise floor + 18)')
+ a = ap.parse_args()
+
+ root, work = project_paths(a.project)
+ backend = pick_backend(a.backend)
+ os.makedirs(os.path.join(work, 'env'), exist_ok=True)
+ os.makedirs(os.path.join(work, 'transcripts'), exist_ok=True)
+ cpath = os.path.join(work, 'clips.json')
+ clips = load_json(cpath) if os.path.exists(cpath) else {}
+
+ for src in a.clips:
+ rel = os.path.relpath(os.path.abspath(src), root)
+ cid = next((k for k, v in clips.items() if v == rel), None) or clip_id(rel, clips)
+ clips[cid] = rel
+ save_json(cpath, clips)
+
+ x = load_mono(os.path.abspath(src))
+ if not len(x):
+ print(f'{cid}: no audio, skipped')
+ continue
+ env = envelope(os.path.abspath(src))
+ np.save(os.path.join(work, 'env', f'{cid}.npy'), env.astype(np.float32))
+ thr = speech_threshold(env, a.thr)
+ regions = speech_regions(env, thr)
+ chunks = plan_chunks(regions)
+ print(f'{cid}: {len(x) / SR:.1f} s, threshold {thr:.1f} dB, {len(chunks)} chunks, backend {backend}')
+
+ arrays = [x[int(s * SR):int(e * SR)] for s, e in chunks]
+ res = transcribe_arrays(arrays, a.lang, backend, a.model)
+ utts = []
+ for (s, e), (text, words) in zip(chunks, res):
+ ws = [[round(w0 + s, 3), round(w1 + s, 3), w] for w0, w1, w in words]
+ utts.append({'start': s, 'end': e, 'text': text, 'words': ws})
+ save_json(os.path.join(work, 'transcripts', f'{cid}.json'),
+ {'clip': cid, 'src': rel, 'threshold': thr, 'hop': ENV_HOP, 'regions': regions, 'utterances': utts})
+ with open(os.path.join(work, 'transcripts', f'{cid}.txt'), 'w', encoding='utf-8') as f:
+ f.write(f'# {cid} ({rel}) utterance index [start-end] text\n')
+ for i, u in enumerate(utts):
+ f.write(f"#{i:<4d}[{fmt_time(u['start'])}-{fmt_time(u['end'])}] {u['text']}\n")
+ print(f' -> work/transcripts/{cid}.txt ({len(utts)} utterances)')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/scripts/verify.py b/scripts/verify.py
new file mode 100644
index 0000000..3d91ee4
--- /dev/null
+++ b/scripts/verify.py
@@ -0,0 +1,110 @@
+#!/usr/bin/env python3
+"""Check every join of the built program: clipped words, cuts through sound, leftover repeats.
+
+Two checks, both measurements (a human still has to listen to the flagged spots):
+ 1. energy at each cut in the source: a piece that ends or starts while the voice is still sounding is flagged
+ 2. the program audio around each join is transcribed again; doubled words ("and and") and doubled phrases are flagged
+
+usage:
+ python3 scripts/verify.py --project . [--lang en] [--window 1.6] [--all]
+writes work/verify.txt (every join with its transcript; flagged ones marked with !)
+"""
+import argparse
+import os
+import re
+import sys
+
+import numpy as np
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from _common import ENV_HOP, fmt_time, load_json, project_paths # noqa: E402
+from cuts import Clip # noqa: E402
+from transcribe import SR, load_mono, pick_backend, transcribe_arrays # noqa: E402
+
+
+def norm(w):
+ return re.sub(r'[^\w]+', '', w.lower())
+
+
+def repeats(words):
+ ws = [norm(w) for w in words if norm(w)]
+ hits = []
+ for i in range(1, len(ws)):
+ if ws[i] == ws[i - 1] and len(ws[i]) > 1:
+ hits.append(ws[i])
+ for n in (2, 3):
+ for i in range(n, len(ws) - n + 1):
+ if ws[i - n:i] == ws[i:i + n]:
+ hits.append(' '.join(ws[i:i + n]))
+ return hits
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument('--project', default='.')
+ ap.add_argument('--lang', default=None)
+ ap.add_argument('--backend', default='auto')
+ ap.add_argument('--model', default='large-v3')
+ ap.add_argument('--window', type=float, default=1.6)
+ ap.add_argument('--all', action='store_true', help='print every join, not only flagged ones')
+ a = ap.parse_args()
+ root, work = project_paths(a.project)
+ prog = load_json(os.path.join(work, 'program.json'))
+ fps, pieces = prog['fps'], prog['pieces']
+ clips = {}
+
+ def C(cid):
+ if cid not in clips:
+ clips[cid] = Clip(work, cid)
+ return clips[cid]
+
+ edge = []
+ for i, p in enumerate(pieces):
+ c = C(p['clip'])
+ nxt = pieces[i + 1] if i + 1 < len(pieces) else None
+ prv = pieces[i - 1] if i else None
+ contig_out = nxt and nxt['clip'] == p['clip'] and nxt['a'] == p['b']
+ contig_in = prv and prv['clip'] == p['clip'] and prv['b'] == p['a']
+ out_db = float(np.mean(c.env[max(0, int(p['b'] / fps / ENV_HOP) - 2):int(p['b'] / fps / ENV_HOP)]))
+ in_db = float(np.mean(c.env[int(p['a'] / fps / ENV_HOP):int(p['a'] / fps / ENV_HOP) + 2]))
+ notes = []
+ if not contig_out and nxt is not None and out_db > c.soft + 3:
+ notes.append(f'piece ends while sounding ({out_db:.0f} dB)')
+ if not contig_in and prv is not None and in_db > c.soft + 3:
+ notes.append(f'piece starts mid-sound ({in_db:.0f} dB)')
+ edge.append(notes)
+
+ wav = os.path.join(work, 'prog.wav')
+ if not os.path.exists(wav):
+ sys.exit('work/prog.wav missing: run build.py audio first')
+ x = load_mono(wav)
+ joins = [p['p'] / fps for p in pieces[1:]]
+ wins = [x[int(max(0, t - a.window) * SR):int((t + a.window) * SR)] for t in joins]
+ backend = pick_backend(a.backend)
+ print(f'{len(joins)} joins, transcribing windows with {backend} ...')
+ res = transcribe_arrays(wins, a.lang, backend, a.model) if wins else []
+
+ lines, flagged = [], 0
+ for k, (t, (text, words)) in enumerate(zip(joins, res)):
+ notes = edge[k] + edge[k + 1]
+ rep = repeats([w for _, _, w in words])
+ if rep:
+ notes.append('repeat: ' + ', '.join(sorted(set(rep))))
+ mark = '!' if notes else ' '
+ flagged += bool(notes)
+ if notes or a.all:
+ pa, pb = pieces[k], pieces[k + 1]
+ lines.append(f"{mark} join {k + 1:<4d} {fmt_time(t)} [{pa['clip']} {pa['b'] / fps:.2f} -> {pb['clip']} "
+ f"{pb['a'] / fps:.2f}] {text}")
+ for n in notes:
+ lines.append(f' - {n}')
+ out = os.path.join(work, 'verify.txt')
+ with open(out, 'w', encoding='utf-8') as f:
+ f.write('\n'.join(lines) + '\n')
+ print('\n'.join(lines))
+ print(f'{flagged} of {len(joins)} joins flagged -> work/verify.txt. Listen to the flagged spots; '
+ f'a clean report does not mean every join sounds right.')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/template/demo.js b/template/demo.js
new file mode 100644
index 0000000..2e1e645
--- /dev/null
+++ b/template/demo.js
@@ -0,0 +1,33 @@
+/* A tiny built-in program so the template can be opened with ?demo before any footage exists.
+ * Same shape as work/program.json: words are [start, end, word] in program seconds. */
+(() => {
+ const lines = [
+ [0.6, 'This scene shows how the graphics follow the voice.'],
+ [4.2, 'Every card appears on the word that is spoken.'],
+ [10.6, 'First we transcribe the raw takes.'],
+ [13.0, 'Then we cut on real word edges.'],
+ [15.4, 'Then we animate and render.'],
+ [20.6, 'The voice is measured, not heard.'],
+ [23.0, 'We aim for minus fourteen LUFS.'],
+ ];
+ const words = [];
+ for (const [t0, text] of lines) {
+ let t = t0;
+ for (const w of text.split(' ')) {
+ const d = 0.12 + 0.045 * w.replace(/\W/g, '').length;
+ words.push([+t.toFixed(3), +(t + d).toFixed(3), w]);
+ t += d + 0.06;
+ }
+ }
+ window.DEMO_PROGRAM = {
+ fps: 30,
+ duration: 27,
+ frames: 27 * 30,
+ words,
+ chapters: [
+ { title: 'Intro', time: 0 },
+ { title: 'Workflow', time: 8.0 },
+ { title: 'Sound', time: 18.2 },
+ ],
+ };
+})();
diff --git a/template/engine.js b/template/engine.js
new file mode 100644
index 0000000..ea5f082
--- /dev/null
+++ b/template/engine.js
@@ -0,0 +1,190 @@
+/* Scene engine: one GSAP timeline driven by the program clock.
+ *
+ * Preview: the program video plays with its sound; the timeline follows video.currentTime.
+ * Render: ?still — nothing plays; render.mjs calls window.__scene.render(t) for every frame.
+ * Keys: Space play/pause · ←/→ 5 s · R restart · M mute effects
+ * URL: ?t=12.5 freeze at 12.5 s · ?src=FILE program video (default ../work/proxy.mp4, "none" for no video)
+ * ?demo built-in demo program (no project needed) · ?still render mode · ?nohud hide the timecode
+ *
+ * script.js defines window.buildScene(api) and adds tweens to api.TL at times from api.at('spoken phrase').
+ */
+(() => {
+ const Q = new URLSearchParams(location.search);
+ const STILL = Q.has('still'), DEMO = Q.has('demo');
+ const body = document.body;
+ const W = +body.dataset.w || 1920, H = +body.dataset.h || 1080;
+ const stage = document.querySelector('#stage');
+ const video = document.querySelector('#v');
+
+ /* ---- stage: fixed design size, scaled to the window ---- */
+ stage.style.width = W + 'px';
+ stage.style.height = H + 'px';
+ const fit = () => {
+ const s = Math.min(innerWidth / W, innerHeight / H);
+ stage.style.transform = `translate(${(innerWidth - W * s) / 2}px, ${(innerHeight - H * s) / 2}px) scale(${s})`;
+ };
+ addEventListener('resize', fit);
+ fit();
+
+ const TL = gsap.timeline({ paused: true });
+ const SFX = [], missing = [], ASSETS = [], frameHooks = [];
+ let PROGRAM = null, duration = 0, words = [], normWords = [];
+
+ const norm = (s) => s.toLocaleLowerCase().normalize('NFC').replace(/[^\p{L}\p{N}]+/gu, '');
+
+ /* at('phrase'): time just before the first word of the phrase is spoken (lead 0.1 s).
+ * Options: { from: seconds to search after, end: true for the end of the phrase's last word, lead }.
+ * A phrase that is not found is recorded in window.__scene.missing (render.mjs refuses to render then). */
+ function at(phrase, opt = {}) {
+ const want = phrase.split(/\s+/).map(norm).filter(Boolean);
+ const from = opt.from ?? 0, lead = opt.lead ?? 0.1;
+ for (let i = 0; i + want.length <= normWords.length; i++) {
+ if (words[i][0] < from) continue;
+ let ok = true;
+ for (let k = 0; k < want.length && ok; k++) ok = normWords[i + k] === want[k] || (k === want.length - 1 && normWords[i + k].startsWith(want[k]));
+ if (ok) return opt.end ? words[i + want.length - 1][1] + 0.05 : Math.max(0, words[i][0] - lead);
+ }
+ missing.push(phrase);
+ return null;
+ }
+
+ /* cue(t, 'whoosh', gainDb): a sound effect at program time t. Same clock as the picture. */
+ function cue(t, name, gain = 0) {
+ if (t == null) return;
+ SFX.push({ t: +t.toFixed(3), name, gain });
+ }
+
+ /* ---- preview sound: effects play live through WebAudio from ./sfx/<name>.wav ---- */
+ let actx = null, muted = Q.has('mute');
+ const buffers = {};
+ async function loadSfx() {
+ if (STILL || !SFX.length) return;
+ actx = new AudioContext();
+ for (const name of new Set(SFX.map((c) => c.name))) {
+ try {
+ const r = await fetch(`sfx/${name}.wav`);
+ if (r.ok) buffers[name] = await actx.decodeAudioData(await r.arrayBuffer());
+ } catch (e) { /* missing effect file: the preview stays silent, the mix still has it */ }
+ }
+ }
+ function playCue(c) {
+ if (muted || !actx || !buffers[c.name]) return;
+ if (actx.state === 'suspended') actx.resume();
+ const src = actx.createBufferSource(), g = actx.createGain();
+ src.buffer = buffers[c.name];
+ g.gain.value = Math.pow(10, (c.gain || 0) / 20);
+ src.connect(g).connect(actx.destination);
+ src.start();
+ }
+
+ /* ---- clock ---- */
+ let clock = 0, last = performance.now(), playing = false, prevClock = 0;
+ const hasVideo = () => video && video.src && !video.dataset.none;
+
+ function apply(t) {
+ TL.seek(Math.min(t, TL.duration() || t), false);
+ frameHooks.forEach((f) => f(t));
+ }
+
+ function tick(now) {
+ const dt = (now - last) / 1000;
+ last = now;
+ if (playing) {
+ if (hasVideo()) {
+ const vt = video.currentTime;
+ if (video.paused || video.seeking) clock = vt;
+ else if (Math.abs(vt - clock) > 0.25) clock = vt;
+ else clock += dt + (vt - clock) * 0.03; // follow the video smoothly: currentTime alone is jittery
+ } else {
+ clock += dt;
+ }
+ if (clock >= duration) { clock = duration; playing = false; if (hasVideo()) video.pause(); }
+ for (const c of SFX) if (c.t > prevClock && c.t <= clock) playCue(c);
+ }
+ prevClock = clock;
+ apply(clock);
+ hud();
+ requestAnimationFrame(tick);
+ }
+
+ function play() {
+ playing = !playing;
+ if (hasVideo()) playing ? video.play() : video.pause();
+ }
+ function seek(t) {
+ clock = prevClock = Math.max(0, Math.min(duration, t));
+ if (hasVideo()) video.currentTime = clock;
+ apply(clock);
+ }
+
+ /* ---- render mode: one exact frame per call ---- */
+ async function render(t) {
+ playing = false;
+ if (hasVideo()) {
+ video.pause();
+ if (Math.abs(video.currentTime - t) > 0.0005) {
+ await new Promise((res) => { video.addEventListener('seeked', res, { once: true }); video.currentTime = t; });
+ }
+ if (video.readyState < 2) await new Promise((res) => video.addEventListener('canplay', res, { once: true }));
+ }
+ await Promise.all(ASSETS);
+ clock = t;
+ apply(t);
+ return true;
+ }
+
+ /* ---- HUD (preview only) ---- */
+ const hudEl = document.querySelector('#hud');
+ function hud() {
+ if (!hudEl || STILL || Q.has('nohud')) return;
+ const m = Math.floor(clock / 60), s = (clock % 60).toFixed(2).padStart(5, '0');
+ hudEl.textContent = `${m}:${s} / ${(duration / 60) | 0}:${String(Math.round(duration % 60)).padStart(2, '0')}` +
+ (missing.length ? ` · ${missing.length} phrase(s) not found: ${missing.slice(0, 3).join(' | ')}` : '') +
+ (playing ? '' : ' · Space to play');
+ }
+
+ addEventListener('keydown', (e) => {
+ if (e.code === 'Space') { e.preventDefault(); play(); }
+ else if (e.code === 'ArrowRight') seek(clock + 5);
+ else if (e.code === 'ArrowLeft') seek(clock - 5);
+ else if (e.code === 'KeyR') seek(0);
+ else if (e.code === 'KeyM') muted = !muted;
+ });
+
+ /* ---- boot ---- */
+ async function loadProgram() {
+ if (DEMO) return window.DEMO_PROGRAM;
+ try {
+ const r = await fetch(Q.get('program') || '../work/program.json', { cache: 'no-store' });
+ if (r.ok) return await r.json();
+ } catch (e) { /* no project yet */ }
+ return window.DEMO_PROGRAM;
+ }
+
+ (async () => {
+ PROGRAM = await loadProgram();
+ words = (PROGRAM.words || []).map((w) => [w[0], w[1], w[2]]);
+ normWords = words.map((w) => norm(w[2]));
+ duration = PROGRAM.duration || (PROGRAM.frames / PROGRAM.fps) || 30;
+ const src = Q.get('src') || (PROGRAM === window.DEMO_PROGRAM ? 'none' : '../work/proxy.mp4');
+ if (src === 'none') { video.dataset.none = '1'; video.removeAttribute('src'); video.style.display = 'none'; }
+ else {
+ video.src = src;
+ video.muted = STILL;
+ ASSETS.push(new Promise((res) => (video.readyState >= 1 ? res() : video.addEventListener('loadedmetadata', res, { once: true }))));
+ }
+ if (document.fonts) ASSETS.push(document.fonts.ready);
+
+ window.buildScene({ TL, at, cue, words, chapters: PROGRAM.chapters || [], duration, W, H, stage, ASSETS,
+ onFrame: (f) => frameHooks.push(f), still: STILL });
+ if (TL.duration() < duration) TL.set({}, {}, duration); // the timeline spans the whole program
+
+ window.__scene = { render, SFX, missing, duration, TL, fps: PROGRAM.fps || 30 };
+ window.__sceneReady = () => Promise.all(ASSETS);
+ await loadSfx();
+ const t0 = Q.has('t') ? +Q.get('t') : 0;
+ if (STILL) { await render(t0); return; }
+ seek(t0);
+ requestAnimationFrame((n) => { last = n; tick(n); });
+ })();
+})();
diff --git a/template/index.html b/template/index.html
new file mode 100644
index 0000000..5a2e43b
--- /dev/null
+++ b/template/index.html
@@ -0,0 +1,62 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>Scene</title>
+ <link rel="preconnect" href="https://fonts.googleapis.com">
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@500;600;700;800&family=JetBrains+Mono:wght@500;600;700&display=block&subset=latin,latin-ext" rel="stylesheet">
+ <link rel="stylesheet" href="style.css">
+</head>
+<!-- data-w / data-h: stage size (1080 x 1920 for a Short). data-theme="light" for the paper look. -->
+<body data-w="1920" data-h="1080">
+ <div id="stage">
+ <svg id="bgLines" width="1920" height="1080" aria-hidden="true"></svg>
+ <video id="v" playsinline preload="auto"></video>
+
+ <!-- keep-out area: the speaker's face (audit.mjs checks that no card covers it). Adjust to your framing. -->
+ <div data-keepout style="position:absolute;left:720px;top:120px;width:560px;height:960px;pointer-events:none"></div>
+
+ <div id="chip" class="chip card" data-box><span class="no">01</span><span class="tt"></span></div>
+
+ <div id="kw" class="card" data-box>
+ <div class="kick">Key idea</div>
+ <div class="roll"></div>
+ </div>
+
+ <div id="steps" class="card" data-box>
+ <div class="kick">Workflow</div>
+ </div>
+
+ <div id="counter" class="card" data-box>
+ <div class="kick">Loudness target</div>
+ <div class="num">0</div>
+ <div class="unit">LUFS</div>
+ <div class="bar"><i></i></div>
+ </div>
+
+ <div id="lower" class="card" data-box>
+ <div class="bar"></div>
+ <div><div class="name">Your Name</div><div class="role">Your role · Your channel</div></div>
+ </div>
+
+ <div id="veil" class="veil">
+ <div class="pane"></div>
+ <div class="edge"></div>
+ <div class="inner">
+ <div class="kick"></div>
+ <div class="t1"></div>
+ <div class="t2"></div>
+ <div class="prog"></div>
+ </div>
+ </div>
+ </div>
+ <div id="hud"></div>
+
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/gsap.min.js"></script>
+ <script src="demo.js"></script>
+ <script src="script.js"></script>
+ <script src="engine.js"></script>
+</body>
+</html>
diff --git a/template/script.js b/template/script.js
new file mode 100644
index 0000000..46a44d6
--- /dev/null
+++ b/template/script.js
@@ -0,0 +1,123 @@
+/* The scene: every beat is a tween on TL at a time taken from the spoken words.
+ * Replace the demo beats below with the beats of your video. Keep the helpers.
+ * at('phrase') time just before the phrase is said
+ * at('phrase', {end:true}) time just after the phrase ends
+ * at('phrase', {from: t}) search only after t (for words said more than once)
+ * cue(t, 'whoosh', -3) sound effect at t, 3 dB under its default level
+ */
+window.buildScene = ({ TL, at, cue, chapters, duration, stage, still }) => {
+ const $ = (s) => stage.querySelector(s);
+ const IN = 'power3.out', OUT = 'power2.in', MOVE = 'power2.inOut';
+ const hasVideo = !!$('#v').getAttribute('src');
+ const css = (name) => getComputedStyle(document.body).getPropertyValue(name).trim();
+
+ /* card in / out: rise 24 px and fade; visibility is handled by autoAlpha */
+ const cardIn = (el, t, d = 0.7) => t != null && TL.fromTo(el, { autoAlpha: 0, y: 24 }, { autoAlpha: 1, y: 0, duration: d, ease: IN, immediateRender: false }, t);
+ const cardOut = (el, t, d = 0.5) => t != null && TL.to(el, { autoAlpha: 0, y: -12, duration: d, ease: OUT }, t);
+ TL.set(stage.querySelectorAll('.card'), { autoAlpha: 0 }, 0);
+
+ /* subtle line texture when there is no video (lines, never radial glows) */
+ if (!hasVideo) {
+ const svg = $('#bgLines');
+ let d = '';
+ for (let y = 60; y < 1080; y += 60) d += `M0 ${y}H1920`;
+ for (let x = 60; x < 1920; x += 60) d += `M${x} 0V1080`;
+ svg.innerHTML = `<path d="${d}" stroke="rgba(255,255,255,0.035)" stroke-width="1"/>` +
+ '<rect x="720" y="120" width="560" height="960" rx="18" fill="none" stroke="rgba(255,255,255,0.12)" stroke-dasharray="8 10"/>' +
+ '<text x="1000" y="610" fill="rgba(255,255,255,0.25)" font-family="Inter, sans-serif" font-size="26" text-anchor="middle">speaker</text>';
+ }
+
+ /* ---------- chapters: a veil for every chapter after the first, a chip for each ---------- */
+ const VEIL = 2.4; // seconds: wipe in, hold, wipe out
+ chapters.forEach((ch, i) => {
+ const no = String(i + 1).padStart(2, '0');
+ const chip = $('#chip').cloneNode(true);
+ chip.id = `chip${i}`;
+ TL.set(chip, { autoAlpha: 0 }, 0);
+ chip.querySelector('.no').textContent = no;
+ chip.querySelector('.tt').textContent = ch.title;
+ $('#chip').after(chip);
+ const end = i + 1 < chapters.length ? chapters[i + 1].time : duration;
+ const shown = i === 0 ? ch.time + 0.6 : ch.time + VEIL - 0.2;
+ cardIn(chip, shown, 0.6);
+ cardOut(chip, Math.max(shown + 1, end - 0.05), 0.3);
+ if (i === 0) return;
+
+ const v = $('#veil').cloneNode(true), t = ch.time;
+ v.id = `veil${i}`;
+ $('#veil').after(v);
+ v.querySelector('.kick').textContent = `Chapter ${no} / ${String(chapters.length).padStart(2, '0')}`;
+ v.querySelector('.t1').textContent = ch.title;
+ v.querySelector('.t2').textContent = ch.subtitle || '';
+ v.querySelector('.prog').innerHTML = chapters.map((c, k) => `<span class="${k === i ? 'on' : ''}">${String(k + 1).padStart(2, '0')}</span>`).join('<b></b>');
+ TL.set(v, { autoAlpha: 1 }, t);
+ TL.fromTo(v.querySelector('.pane'), { clipPath: 'inset(0 100% 0 0)' }, { clipPath: 'inset(0 0% 0 0)', duration: 0.9, ease: MOVE, immediateRender: false }, t);
+ TL.fromTo(v.querySelector('.edge'), { x: 0, opacity: 1 }, { x: 1917, duration: 0.9, ease: MOVE, immediateRender: false }, t);
+ TL.set(v.querySelector('.edge'), { opacity: 0 }, t + 0.9);
+ TL.fromTo(v.querySelector('.inner'), { autoAlpha: 0, x: -30 }, { autoAlpha: 1, x: 0, duration: 0.6, ease: IN, immediateRender: false }, t + 0.45);
+ TL.to(v.querySelector('.inner'), { autoAlpha: 0, x: 30, duration: 0.4, ease: OUT }, t + VEIL - 1.0);
+ TL.fromTo(v.querySelector('.pane'), { clipPath: 'inset(0 0% 0 0)' }, { clipPath: 'inset(0 0% 0 100%)', duration: 0.8, ease: MOVE, immediateRender: false }, t + VEIL - 0.8);
+ TL.set(v, { autoAlpha: 0 }, t + VEIL);
+ cue(t, 'whoosh');
+ cue(t + VEIL - 0.8, 'whoosh', -4);
+ });
+
+ /* ---------- lower third: once, early ---------- */
+ const lower = $('#lower');
+ TL.fromTo(lower, { autoAlpha: 0, x: -40 }, { autoAlpha: 1, x: 0, duration: 0.8, ease: IN, immediateRender: false }, at('This scene'));
+ TL.to(lower, { autoAlpha: 0, x: -40, duration: 0.6, ease: OUT }, at('spoken', { end: true }) + 0.4);
+
+ /* ---------- keyword card: one idea at a time, swapped on its word ---------- */
+ const kw = $('#kw'), roll = kw.querySelector('.roll');
+ const kwSay = (t, a, b) => {
+ if (t == null) return;
+ const el = document.createElement('div');
+ el.innerHTML = `<div class="t1">${a}</div>` + (b ? `<div class="t2">${b}</div>` : '');
+ roll.appendChild(el);
+ TL.set(el, { autoAlpha: 0 }, 0);
+ const prev = roll.children[roll.children.length - 2];
+ if (prev) TL.to(prev, { yPercent: -60, autoAlpha: 0, duration: 0.45, ease: OUT }, t);
+ TL.fromTo(el, { yPercent: 60, autoAlpha: 0 }, { yPercent: 0, autoAlpha: 1, duration: 0.6, ease: IN, immediateRender: false }, t + (prev ? 0.12 : 0));
+ return el;
+ };
+ cardIn(kw, at('graphics'));
+ kwSay(at('graphics'), 'Graphics', 'follow the voice');
+ kwSay(at('Every card'), 'On the word', 'not before it');
+ cardOut(kw, chapters[1] ? chapters[1].time - 0.4 : null);
+
+ /* ---------- steps: the list grows as each step is said ---------- */
+ const steps = $('#steps');
+ cardIn(steps, at('First'));
+ [['transcribe', 'Transcribe'], ['cut', 'Cut on word edges'], ['animate', 'Animate'], ['render', 'Render']].forEach(([w, label], i) => {
+ const row = document.createElement('div');
+ row.className = 'row';
+ row.innerHTML = `<span class="n">${String(i + 1).padStart(2, '0')}</span><span>${label}</span>`;
+ steps.appendChild(row);
+ const t = at(w, { from: chapters[1] ? chapters[1].time : 0 });
+ TL.fromTo(row, { autoAlpha: 0, x: -16, height: 0, paddingTop: 0, paddingBottom: 0 },
+ { autoAlpha: 1, x: 0, height: 'auto', paddingTop: 16, paddingBottom: 16, duration: 0.5, ease: IN, immediateRender: false }, t);
+ TL.fromTo(row.querySelector('.n'), { color: css('--label') }, { color: css('--accent'), duration: 0.3, immediateRender: false }, t);
+ if (i) TL.to(steps.querySelectorAll('.row .n')[i - 1], { color: css('--label'), duration: 0.3 }, t);
+ cue(t, 'tick');
+ });
+ TL.set(steps.querySelectorAll('.row'), { autoAlpha: 0, height: 0, paddingTop: 0, paddingBottom: 0 }, 0);
+ cardOut(steps, chapters[2] ? chapters[2].time - 0.4 : null);
+
+ /* ---------- sound chapter: keyword with a drawn underline, then a counter ---------- */
+ const s3 = chapters[2] ? chapters[2].time : 0;
+ const tm = at('measured', { from: s3 });
+ if (tm != null) {
+ cardIn(kw, tm);
+ const el = kwSay(tm, '<span class="u">Measured,<i></i></span>', 'not heard');
+ TL.to(el.querySelector('.u > i'), { scaleX: 1, duration: 0.5, ease: IN }, at('heard', { from: s3 }));
+ }
+ const counter = $('#counter'), num = counter.querySelector('.num'), tc = at('minus', { from: s3 });
+ if (tc != null) {
+ cardIn(counter, tc);
+ cue(tc, 'pop');
+ const o = { v: 0 };
+ TL.fromTo(o, { v: 0 }, { v: -14, duration: 1.2, ease: 'power2.out', immediateRender: false,
+ onUpdate: () => { num.textContent = Math.round(o.v) === 0 ? '0' : `−${Math.abs(Math.round(o.v))}`; } }, tc + 0.3);
+ TL.fromTo(counter.querySelector('.bar > i'), { scaleX: 0 }, { scaleX: 0.72, duration: 1.2, ease: 'power2.out', immediateRender: false }, tc + 0.3);
+ }
+};
diff --git a/template/sfx/.gitkeep b/template/sfx/.gitkeep
new file mode 100644
index 0000000..e69de29
diff --git a/template/style.css b/template/style.css
new file mode 100644
index 0000000..4ea85ff
--- /dev/null
+++ b/template/style.css
@@ -0,0 +1,101 @@
+/* Neutral default palette. Replace --accent / --accent-ink with the channel's brand colour (see reference/style.md). */
+:root {
+ --bg: #0b0c0e;
+ --glass: rgba(18, 20, 24, 0.62);
+ --glass-solid: #16181c;
+ --line: rgba(255, 255, 255, 0.1);
+ --ink: #f4f4f1;
+ --ink-2: #bfc3ca;
+ --label: #9198a3;
+ --accent: #3d8bff;
+ --accent-ink: #a8c8ff;
+ --good: #35c27d;
+ --bad: #f0524d;
+ --warn: #f2b53c;
+ --sans: "Inter", system-ui, -apple-system, "Segoe UI", sans-serif;
+ --mono: "JetBrains Mono", ui-monospace, "SF Mono", Menlo, monospace;
+ --r: 14px;
+}
+body[data-theme="light"] {
+ --bg: #f3f2ee;
+ --glass: rgba(255, 255, 255, 0.78);
+ --glass-solid: #ffffff;
+ --line: rgba(0, 0, 0, 0.09);
+ --ink: #141518;
+ --ink-2: #4a4f57;
+ --label: #6b717b;
+ --accent: #1f6feb;
+ --accent-ink: #1557c0;
+}
+
+* { box-sizing: border-box; margin: 0; padding: 0; }
+html, body { width: 100%; height: 100%; overflow: hidden; background: #000; }
+body { font-family: var(--sans); color: var(--ink); -webkit-font-smoothing: antialiased; }
+
+#stage { position: absolute; left: 0; top: 0; transform-origin: 0 0; overflow: hidden; background: var(--bg); }
+#v { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
+#bgLines { position: absolute; inset: 0; opacity: 0.5; }
+
+/* ---------- glass card ---------- */
+.card {
+ position: absolute;
+ background: var(--glass);
+ border: 1px solid var(--line);
+ border-radius: var(--r);
+ padding: 22px 28px;
+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.28);
+ visibility: hidden;
+}
+.card.blur { -webkit-backdrop-filter: blur(18px); backdrop-filter: blur(18px); }
+.kick { font: 600 20px/1 var(--mono); letter-spacing: 0.08em; text-transform: uppercase; color: var(--label); display: flex; align-items: center; gap: 10px; }
+.kick::before { content: ""; width: 8px; height: 8px; border-radius: 50%; background: var(--accent); flex: none; }
+.t1 { font: 750 46px/1.08 var(--sans); letter-spacing: -0.01em; color: var(--ink); }
+.t2 { font: 750 46px/1.08 var(--sans); letter-spacing: -0.01em; color: var(--accent-ink); }
+.kick + .t1 { margin-top: 16px; }
+.body { font: 600 32px/1.25 var(--sans); color: var(--ink-2); }
+.u { position: relative; display: inline-block; }
+.u > i { position: absolute; left: 0; right: 0; bottom: -6px; height: 4px; border-radius: 2px; background: var(--accent); transform-origin: 0 50%; transform: scaleX(0); }
+
+/* ---------- keyword card (one big idea, swaps on its word) ---------- */
+#kw { left: 64px; top: 120px; min-width: 520px; }
+#kw .roll { position: relative; height: 112px; margin-top: 16px; overflow: hidden; }
+#kw .roll > div { position: absolute; left: 0; top: 0; }
+
+/* ---------- step list ---------- */
+#steps { left: 64px; top: 120px; width: 620px; }
+#steps .row { overflow: hidden; display: flex; align-items: center; gap: 18px; padding: 16px 0; border-top: 1px solid var(--line); font: 650 34px/1.1 var(--sans); }
+#steps .row:first-of-type { margin-top: 18px; }
+#steps .n { font: 600 20px/1 var(--mono); color: var(--label); width: 34px; }
+
+/* ---------- counter ---------- */
+#counter { right: 64px; top: 120px; width: 460px; }
+#counter .num { font: 800 120px/1 var(--sans); letter-spacing: -0.03em; margin-top: 14px; font-variant-numeric: tabular-nums; }
+#counter .unit { font: 650 30px/1 var(--sans); color: var(--accent-ink); margin-top: 6px; }
+#counter .bar { height: 8px; border-radius: 4px; background: var(--line); margin-top: 22px; overflow: hidden; }
+#counter .bar > i { display: block; height: 100%; width: 100%; background: var(--accent); transform-origin: 0 50%; transform: scaleX(0); }
+
+/* ---------- lower third ---------- */
+#lower { left: 64px; bottom: 72px; padding: 18px 26px 18px 22px; display: flex; gap: 18px; align-items: stretch; }
+#lower .bar { width: 5px; border-radius: 3px; background: var(--accent); }
+#lower .name { font: 750 40px/1.1 var(--sans); }
+#lower .role { font: 600 26px/1.2 var(--sans); color: var(--ink-2); margin-top: 6px; }
+
+/* ---------- chapter chip (cloned per chapter) ---------- */
+.chip { left: 64px; top: 52px; padding: 10px 16px; border-radius: 10px; display: flex; gap: 12px; align-items: center; }
+.chip .no { font: 700 20px/1 var(--mono); color: #fff; background: var(--accent); border-radius: 6px; padding: 6px 8px; }
+.chip .tt { font: 650 24px/1 var(--sans); }
+
+/* ---------- chapter veil (cloned per chapter) ---------- */
+.veil { position: absolute; inset: 0; visibility: hidden; }
+.veil .pane { position: absolute; inset: 0; background: var(--glass-solid); clip-path: inset(0 100% 0 0); }
+.veil .edge { position: absolute; top: 0; bottom: 0; width: 3px; background: var(--accent); left: 0; opacity: 0; }
+.veil .inner { position: absolute; left: 160px; top: 50%; transform: translateY(-50%); width: 1500px; }
+.veil .kick { font-size: 22px; }
+.veil .t1, .veil .t2 { font-size: 84px; }
+.veil .kick + .t1 { margin-top: 28px; }
+.veil .prog { display: flex; gap: 14px; margin-top: 44px; align-items: center; }
+.veil .prog span { font: 600 20px/1 var(--mono); color: var(--label); }
+.veil .prog span.on { color: var(--ink); }
+.veil .prog b { width: 56px; height: 2px; background: var(--line); }
+
+#hud { position: fixed; left: 12px; bottom: 10px; font: 500 12px/1 var(--mono); color: rgba(255, 255, 255, 0.55); z-index: 10; pointer-events: none; }