---
name: app-demo-ugc-ad
description: "A creator talks to camera while your real app flow plays on screen: store page, taps, success screen. Opens on a scroll-stopping hook built around your app. Just paste your App Store link."
---

# App Demo UGC Ad

Goal: ONE final 9:16 video that copies the structure of a proven winning app ad (Telicall, Nov 2026):

| Time (≈30 s ad) | Picture | Audio |
|---|---|---|
| 0 → end of hook line (~3.8 s) | **Hook visual**: one oddly satisfying physical shot of THIS app's core idea (its signature gesture, payoff or visual; e.g. cards swiped right for a dating app, word tiles snapping into a row for a language app, SIM cards crushed for a second-number app), generated with Seedance | Actor's voice says the hook |
| hook end → first demo word (~1 s) | Actor full screen ("Here's how.") | Actor |
| demo line → end of the use-case line (~15 s) | **Animated app demo** built in code (App Store page → home screen → app → feature → success), cursor taps, actor **cut out** bottom-right with a white edge + lime dashed outline | Actor + tap / typing / notification / success SFX |
| rest (~9 s) | Blur transition, actor full screen; **app icon + name** pops in at the top on the reframe line | Actor |
| everything | **Yellow word-by-word captions** (heavy italic, black stroke), music bed | Music + SFX added on top; the actor's voice is never modified |

The app demo is code (HTML/CSS/JS with a `render(t)` function) rendered by the Arcads **HTML to Video** tool (`arcads_html_to_video`, Remotion under the hood, 5 credits per started 30 s), so it is pixel-sharp and follows the voice exactly. Scene previews use **HTML to Image** (`arcads_html_to_image`), which is free. Everything else runs on the Arcads MCP, SFX included (`arcads_create_sound_effect`, ElevenLabs Text to Sound v2 inside Arcads): no separate ElevenLabs connector needed.

## Rules

- **Exactly one final video.** No drafts, no alternates. Intermediate files never go to the user, except the two approval points below.
- **Two approval points only:** (1) the actor reference image, (2) the actor clip. After the actor clip is approved, run everything else automatically and deliver only the final video.
- **Show estimated credits and get one "Go?" before the first paid video generation.** Never regenerate anything automatically: if a generation fails or the user reports a problem, explain the likely cause, give the cost of a retry and ask.
- **Never analyze, transcribe for review, or rate a generated video yourself.** The user is the only reviewer. Allowed measurements that the edit needs: `arcads_transcribe` (srt) on the actor clip for caption timing, `hook_peak.py` for the hook's motion peak, and snapshots of YOUR OWN composite to check layout (captions, cut-out, logo), never the actor's performance.
- **The actor's audio is never modified**: no denoise, EQ, compression or normalisation. Music and SFX are added on top (`mix.py` proves it with `voice_untouched: true`). Always add music AND SFX.
- **The filming phone is never visible** (front-camera selfie POV, no propped phone, no mirror).
- **Seedance voices are native** (generated by Seedance itself, no separate TTS).
- One question per message during intake.
- Talk to the user in their language. Prompts to the models stay in English, apart from the script.

## Step 0: Setup (silent)

1. Make a fresh folder (e.g. `ad_<app>_<n>`). Write every file from the Appendix verbatim into it: `demo_template.html`, `demo_events.py`, `make_logo.py`, `hook_peak.py`, `build_timeline.py`, `music_fit.py`, `mix.py`, `compose.py`, `preflight.sh`.
   **Edit style (matches the client's winning ads, measured Nov 2026):** every cut is a fast animated transition, never a plain cut. Hook → actor: hook whips down with vertical motion blur, actor arrives as a zoom-out from a tight close-up. Actor → demo: actor whips up, the demo drops in from the top with vertical motion blur and the cut-out slides up from the bottom. Inside the demo: whip-swipes with horizontal motion blur, iOS-style app-open zoom from the icon. Demo → actor: vertical whip up, actor settles with a zoom-out and motion blur. Actor sections get a jump-cut zoom level change at every sentence. Each big cut has a riser/whoosh + impact hit. The music NEVER stops or restarts: it runs continuously under the whole ad, quiet and ducked under the voice (user feedback Nov 2026: music too loud, and the stop/restart transitions sounded bad). All of this is built into the engine, `compose.py`, `build_timeline.py` and `mix.py`.
2. Run `bash preflight.sh`. Every line must be `OK`. If a line says `FIX`, tell the user exactly what to do and stop. Usually it's "Arcads storage blocked": Settings > Capabilities > allow `*.s3-accelerate.amazonaws.com` (on Team/Enterprise plans, an org owner does this). Nothing needs to be installed on the user's own computer: the pipeline runs in Claude's environment.
3. Load the tool schemas with ToolSearch before calling them: `arcads_list_brands`, `arcads_create_brand`, `arcads_create_project`, `arcads_upload_media`, `arcads_get_upload_url`, `arcads_register_image`, `arcads_register_audio`, `arcads_get_download_link`, `arcads_get_asset`, `arcads_get_credits`, `arcads_generate_image_gpt`, `arcads_generate_video_seedance_25`, `arcads_generate_video_flux_3_max`, `arcads_extract_frame`, `arcads_stitch_videos`, `arcads_remove_background`, `arcads_transcribe`, `arcads_create_music`, `arcads_create_sound_effect`, `arcads_html_to_image`, `arcads_html_to_video`.

## Step 1: Intake (one question per message)

1. **App link**: "What's the App Store (or Google Play) link of the app?"
2. **Script**: ask with AskUserQuestion: "Do you have a script, or should I write one?" with the options "Write one for me (Recommended)" and "I have a script". If they have one, ask them to paste it.
3. **Actor**: "Describe the actor: gender, age, look, style, vibe (e.g. 'Asian guy, 25, short black hair, casual t-shirt, filming in his bedroom')." If they say "you decide", pick one that fits the app's audience.

Format is always 9:16. Ask nothing else unless the app's main use case is truly unclear after reading the store page.

## Step 2: App research

1. Read the store page with `firecrawl_scrape` (or WebFetch): app name, subtitle, description, prices or in-app purchases, rating, developer, and the **screenshot and icon image URLs** (`mzstatic.com` …`/600x1300bb.jpg` for screenshots, …`/400x400bb.jpg` for the icon).
2. **Download the images through Arcads** (the sandbox blocks the image CDN): for each URL, `arcads_upload_media` with `url` → `filePath` → `arcads_register_image` → `arcads_get_download_link` → `curl` into `./screens/` (icon → `icon.png`/`.jpg`).
3. Read every screenshot with the Read tool and note the brand colors (hex), the fonts' feel, the real screen copy, the button styles, and the core flow (what the user taps to get the app's main benefit).
4. Arcads brand: `arcads_list_brands`; if the app isn't there, `arcads_create_brand` (name, description, main features). Then `arcads_create_project` named `<App> – app demo UGC ad`, and pass `productId` + `projectId` to every Arcads call.

## Step 3: Script

If the user gave one, keep their wording. Only propose cleanup in one line: brand names, numbers and URLs written the way they're spoken; no colons, dashes, ellipses or parentheses.

If Claude writes it, follow the winning structure (English, ~80–85 words, ≤ 29 s at a fast conversational pace of ~2.9 words/s):

| Part | Length | Winning example (Telicall) |
|---|---|---|
| Hook: 2 short punchy sentences, a command against the old way | ~3.5 s | "Stop giving out your real number. Get a second one instead." |
| Bridge | ~1 s | "Here's how." |
| Demo narration: open the app, the feature, the payoff, naming the app | ~6 s | "Open Telicall, go to the second number feature, and grab a UK number for almost nothing." |
| Personal touch + 4–5 concrete use cases | ~9 s | "You even pick the number yourself. Use it for app verifications, online orders, dating apps, marketplace listings, anything you don't want tied to your real life." |
| 3 quick verb phrases + reframe + CTA | ~9 s | "Call from it, text from it, receive on it. Keep your real number for what really matters, and let this one handle everything else. Download Telicall now." |

**Script approval (mandatory, never skipped):** the user must SEE the full script before approving it. Text written between tool calls is not shown to the user, and the question dialog hides earlier text, so:
1. Send the full script with `SendUserMessage` (load it with ToolSearch if needed): a title line, then the script split by part (Hook / Bridge / Demo / Use cases / CTA), each line in quotes, plus the word count and the estimated length in seconds.
2. Then ask with AskUserQuestion, and put the FULL script text inside the question itself too (e.g. "Here's the script: « … ». OK with it?"), options "Approve this script (Recommended)", "Change something" (the user types the change in Other or the next message), "Write a different angle".
3. If the user asks for changes, apply them, send the updated full script the same way and ask again. Never move to Step 3b before an explicit approval of the exact final wording. The approved script is used word for word in the actor prompt.

Same rule for EVERY approval in this skill (hook ideas, actor images, plan + credits, actor clip): what the user must approve is sent with `SendUserMessage`, `SendUserFile` or an Arcads widget BEFORE the question, and the question itself repeats the essentials. Never ask the user to approve something they cannot see.

## Step 3b: Hook choice (the client picks)

Every ad opens on a ~3.5 s **hook visual** under the actor's hook line: one oddly satisfying, physical shot that stops the scroll AND instantly says what THIS app is about. The hook is the strongest single image of the app's core idea, made physical. A generic destruction shot (a press crushing random objects) is NOT a default: it only fits when the app's whole promise is replacing one specific old object (Telicall's press crushing SIM cards worked because a second number literally replaces extra SIM cards). User feedback Nov 2026: press/crush hooks proposed for Duolingo and Tinder felt off-brand and weak; the approved hooks were chunky word tiles snapping into a row (Duolingo) and a card stack flicked off to the right (Tinder).

1. Before writing ideas, name in one line each, from the store page and screenshots: the app's **signature gesture** (swipe, tap, scan, snap, streak…), its **signature visual** (brand color, tiles, cards, flame, map pin, chart…), its **core payoff** (a match, fluency, money saved, sleep…) and the **old way it replaces**.
2. Write **4 hook ideas** built from those, so a viewer guesses the app category from the shot alone, with no text. Mix the angles so the options really differ:
   - **Signature gesture made physical** (usually the strongest): the app's core action done on real objects. Dating app: a stack of blank cards flicked off to the right one by one. Language app: chunky 3D word tiles flying in and clicking into a sentence row. Scanner app: paper receipts sucked flat into a glowing slot. Habit app: a row of matches lighting one by one into a streak flame.
   - **The payoff made physical**: what the user gets, exaggerated. Budgeting app: coins pouring into a jar that fills in fast motion. Sleep app: a giant pillow slowly sinking and puffing back up. Fitness app: a ring of colored foam closing with a snap.
   - **Signature visual in motion**: the app's iconic shape or color as a satisfying object. Map app: a giant glossy pin dropping and bouncing onto a city model. Music app: equalizer bars of colored jelly bouncing to a beat.
   - **The old way destroyed** (crush / cut / shred / melt / pop): only when the app clearly replaces one specific object or problem, and the object must be that exact one (SIM cards for a second-number app, paper bills for a budgeting app). Never a generic object.
   Strength test, every idea must pass all four, otherwise replace it: (a) on-brand: someone who knows the app recognizes it from the shot; (b) fits the hook line word for word; (c) oddly satisfying, one clear action peaking at 2.5–4 s; (d) feasible in one 5 s Seedance take.
   Rules: no people, no text or letters, no logos or real brands on the objects, vivid single-color studio backdrop in or near the app's brand color, locked-off camera, the action peaks around 2.5–4 s of a 5 s clip.
3. Ask with AskUserQuestion (one question, single select): "Which hook should open the ad?" with the 4 ideas as options. Each label is 2–5 words (e.g. "Card stack swiped right"); each description is one sentence saying what we see and why it fits this app and the hook line. Mark the most on-brand idea (usually the signature gesture) "(Recommended)" and put it first. The user can also type their own idea via "Other"; if they reject all four, write four new ones from a different angle.
4. Write down the chosen hook: objects, backdrop color, action. It drives the hook prompt (Step 8) and the hook SFX prompt (Step 8, `hook` node). Nothing is generated before the actor clip is approved.

## Step 4: Build the app demo (code, no credits)

1. Map the demo part of the script (demo narration + use cases) to **6–8 screens**, in order: store page (Get → progress ring → Open) → phone home screen (relevant app icons pop in, tap the app) → the app's main screen (zoom-open from the icon) → the feature screens (choose, type, confirm) → a success screen → optionally the payoff in the target context (e.g. a verification code arriving and "Verified!") → the last screen (it whips out automatically).
2. Copy `demo_template.html` to `demo.html`. **Keep the ENGINE and HELPERS blocks unchanged.** Rewrite the APP parts:
   - the scene `<div class="scene" id="sN">` blocks and their CSS (canvas 1080×1920, `font-family: Inter`);
   - `CFG` (all the per-ad values: names, numbers, prices, codes, target app name and color);
   - `SCENES` (ids and demo-time start/end; `zoomFrom:[x,y]` on the app-open scene = the icon center on the home screen);
   - `CUR` (cursor keyframes `[t, x, y, tap?]`; x/y = the center of the button being tapped; ~0.3–0.6 s of travel before each tap);
   - `EVENTS` (`success`, `typing` = its start, `notif`);
   - `animate(t)` (per-element animations: button press states with `press()`, pops with `pop()`, typing by slicing text, notification slide-down, list selection…).
   The template ships with the full Telicall demo as a worked example of every pattern (store page, home grid with icons popping in, list selection, typing, OTP digits + notification, success check). Reuse its CSS and patterns.
3. **Fidelity:** the app's own screens copy the real screenshots: colors (hex), copy, layout, button shapes, icon. Draw icons in SVG/CSS (never download third-party logos). Other companies' apps (WhatsApp, Tinder…) are drawn as generic lookalikes; mention once that showing them in ads is the client's call.
4. Keep the buttons that get tapped in the top ~60 % or the left half where possible: the cut-out actor covers roughly the bottom-right 50 % × 45 % during the demo.
5. **Preview (free):** `arcads_html_to_image` with `html` = the full content of `demo.html`, `width 1080`, `height 1920`, `timeSeconds` = one demo time per scene (e.g. `[1, 3, 5, 7, 9.5, 11.5, 13.8, 16]`, up to 25), `save false`. The frames come back inline: compare them with the screenshots and fix `demo.html` until it looks like the real app. This is your own code and the previews cost nothing, so iterate freely. Check that no text shows a NO GLYPH box (draw that icon in SVG instead).

## Step 5: Actor reference image (approval 1)

`arcads_generate_image_gpt`: `model: "gpt-image-2-6-sunburst"`, `aspectRatio: "9:16"`, `nbGenerations: 1` (exactly ONE image, never more), title `<app>_actor_ref`. Prompt (fill from the actor description):

> Frame from an iPhone front-camera selfie video. [Actor: nationality/look, age, hair with real texture, no or light makeup, real-life clothes], sitting on the edge of a bed in a bright simple bedroom: sheer white curtains over a window right behind, light grey wall, a small shelf with a plant. Soft natural daylight from the window. Seen from his/her own selfie point of view, about 45 cm from the face, eye level; framing head and shoulders, centered, curtains filling the background. One arm is out of frame; the other hand is empty and out of frame. Mouth slightly open mid-word, eyes on the lens. Real unretouched skin, pores, stray hairs. Front-camera look: slight noise, soft highlights, no cinematic depth of field, no studio lighting, no beauty filter, no text, no phone visible.

(Bright window background = clean cut-out later. Change the room only if the user asked for one.) Show the image and ask for approval (AskUserQuestion: "Approve this actor (Recommended)", "Adjust: …" with the change typed in Other). A new image costs a new generation: state it and ask before regenerating, and generate only one image again.

## Step 6: Plan and credits ("Go?")

Duration = script words ÷ 2.9 + 0.5 s, rounded up (4–30 s). If it's over 30 s, cut the script (the ad format is ≤ 30 s). One message, then "Go?":

| Item | Tool | Estimate |
|---|---|---|
| Actor clip, Seedance 2.5 1080p, N s | `arcads_generate_video_seedance_25` | N × 104 credits |
| Hook (the chosen idea), Seedance 2.5 1080p, 5 s, no audio | same | ~520 |
| Actor cut-out (background removal) | `arcads_remove_background` | ~80 |
| Music bed | `arcads_create_music` (elevenlabs) | ~16 |
| 9 SFX | `arcads_create_sound_effect` | 3 credits each (per started 10 s) ≈ 27 |
| App demo render (~15 s) | `arcads_html_to_video` | 5 (per started 30 s) |
| Demo previews, captions, edit, mix | `arcads_html_to_image` + code | 0 |

Show the balance from `arcads_get_credits`.

## Step 7: Actor clip (approval 2)

**English script:** `arcads_generate_video_seedance_25` with `aspectRatio "9:16"`, `resolution "1080p"`, `audioEnabled true`, `duration` N, `referenceImages` [approved image asset id], title `<app>_actor_v1`. Prompt (~300 words, timestamped beats; the word "phone" only in the first sentence and in "phone mic"):

```
Authentic vertical UGC selfie video filmed on an iPhone front camera, one continuous take, no cuts. The person in the first reference image, same face, same hair, same outfit, sits on the edge of the bed in the same place as the first reference image. Soft natural daylight from the window behind. Filmed from their own selfie point of view, about 45 cm from the face, eye level, the filming elbow resting on the knee. That arm is out of frame. The only hand that ever enters the frame is the empty free hand. Framing: head and shoulders, centered, the curtains filling the background. The frame sways slightly as they shift their weight on the bed: organic micro-shake, small tilts, gentle sway.
- 0-4s: already talking, direct and a little serious: "[hook sentences]"
- 4-11s: lifts the elbow off the knee and the frame pushes in close to the face, tight close-up, like sharing a trick with a friend: "[bridge + demo narration]"
- 11-20s: settles back, the frame drops back with a small wobble; gestures with the empty hand and brightens: "[personal touch + use cases]"
- 20-N s: warm and sincere, smiles, nods, then points down: "[verb phrases + reframe + CTA]"

Speaks in English with a natural [accent] accent, fast conversational pace, like a FaceTime to a friend. Says only these lines, word for word. Audio: only the voice recorded by the phone mic, close and dry, light room tone, no music. Realistic skin texture, front-camera softness, auto-exposure shifts as the frame moves.
```
Spread the beat timestamps over N in proportion to each beat's word count (the last beat ends exactly at N).

**Non-English script:** Seedance mispronounces non-English words. Use `arcads_generate_video_flux_3_max` (`resolution "1080p"`, `generateAudio true`, `reasoningLevel "low"`, `aspectRatio "9:16"`), with the approved image as `startFrame` and the same prompt with "The person in the start frame". FLUX clips are ≤ 20 s: split at sentence ends, chain each next clip from the previous clip's last frame (`arcads_extract_frame` `frame:"last"`), open each new clip with "Jump cut: the framing is now slightly closer/wider", then `arcads_stitch_videos`.

Poll `arcads_get_asset` (waitSeconds 40, repeat; ~7–13 min). Download the clip and send it to the user ("Approve the actor clip and I'll make the rest of the ad."). Don't watch, transcribe or rate it.

## Step 8: After approval: generate the rest in parallel (no more questions)

Launch all of these in the same turn:
- **Hook (the one the client picked in Step 3b):** `arcads_generate_video_seedance_25`, 9:16, 1080p, `audioEnabled false`, `duration 5`, title `<app>_hook_v1`. Prompt: "Vertical macro product shot, locked-off static camera, one continuous take. [Objects and their arrangement] on [surface], against a bright saturated [brand-near color] studio backdrop. [The chosen action step by step: what moves, in which direction, how it lands], building to its strongest moment around three seconds. Clean studio lighting, sharp focus, vivid colors, oddly satisfying slow motion feel. No people, no text, no letters, no logos." (For a destroy hook, the action line is the tool and what happens to the object: bends, cracks, splinters.)
- **Cut-out:** `arcads_remove_background` on the actor clip (`mediaType video`). Result: a VP9 WebM with alpha (~7 min).
- **Caption timing:** `arcads_transcribe` on the actor clip, `format "srt"`. Save the SRT text as `actor.srt`. Note any misspelling of the app name (e.g. "Telecall") for `fix` in plan.json.
- **SFX:** 9 `arcads_create_sound_effect` calls in the same turn (one per row below), each with `productId`, `projectId`, `prompt`, `duration` from the table, `promptInfluence: 0.65`, title `<app>_sfx_<label>`. One generation each, never re-run. Ready in a few seconds; poll `arcads_get_asset` and `curl` each `downloadUrl` (WAV) to `sfx/<label>.wav`. Tested Nov 2026: 1.2 s impact, 3 credits, ~2 s to generate, direct download.
  | label → file | duration | prompt |
  |---|---|---|
  | hook → `sfx/hook.wav` | 3.8 | matches the chosen hook's material and action (snap, flick, pour, light, crush, cut, pop…), e.g. tiles: "Chunky plastic game tiles snapping firmly into place one after another, crisp satisfying clicks, the last one heavier, dry, close, no music"; press: "Heavy hydraulic press slowly descending with a low mechanical hiss, then crushing a stack of plastic cards: sharp crunchy plastic cracks and snaps, dry, close, satisfying, no music" |
  | whoosh | 0.8 | "Fast airy swipe whoosh transition, modern social media edit, short and clean, no music" |
  | tap | 0.5 | "Single soft smartphone UI tap click, crisp short digital pop, dry, no music" |
  | notif | 1.0 | "Short smartphone text message notification sound, two quick bright digital notes, clean, no music" |
  | success | 1.0 | "Satisfying app success confirmation sound, quick rising bright digital pop, clean UI feedback, no music" |
  | typing | 1.3 | "Fast smartphone keyboard typing, light soft digital key taps in quick succession, dry, no music" |
  | logo | 1.2 | "Short bright logo reveal: quick swoosh ending in a soft punchy pop, modern brand sting, no melody" |
  | impact | 1.2 | "Punchy modern transition impact hit: tight deep sub boom with a sharp snappy transient and a short airy whoosh tail, social media edit, no music" |
  | riser | 1.2 | "Short fast reverse whoosh riser building tension for one second and ending abruptly, modern edit transition, no music" |

Then, once the SRT is in:
- **Key times** (seconds in the ad, from the SRT): `hook_end` = end of the hook sentences + ~0.07; `demo_start` = start of the first demo word (e.g. "Open"); `demo_end` = end of the use-case sentence (the demo whips out there); `logo_start` = start of the reframe sentence ("Keep your real number…"); `duration` = clip length.
- **Music (high energy, like the client's winners):** `arcads_create_music`, `model "elevenlabs"`, `prompt` "High-energy viral social-media ad track, 124 BPM, hard-hitting punchy drums, booming 808 sub bass, crisp fast hi-hats and claps, bright catchy synth lead hook, modern hype electronic pop, instrumental, loud and polished, constant forward motion", `sections`: Intro build (= demo_start s) "energetic from the first second, punchy kick and claps already hitting, filtered synth hook, snare roll and white-noise riser building in the last two seconds into a big drop"; Drop (= demo_end − demo_start) "huge drop on the first beat, booming 808 sub bass, hard-hitting drums, fast crisp hi-hats, bright catchy synth lead hook, maximum energy, constant intensity to the last second"; Second drop (= duration − demo_end + 2) "second drop even bigger and brighter, euphoric synth chords and lead, booming sub bass, driving drums, uplifting high energy to the last second, no fade out". Download as `music.wav`. Generated tracks rarely drop where the sections say (measured: drop at 13.5 s instead of 5 s): Use the track as is: one continuous bed, never re-cut or spliced. Never regenerate the music for timing.

## Step 9: Edit (code)

Downloads: `actor.mp4` (actor clip), `cutout.webm`, `hook.mp4`, `music.wav`, `sfx/*.wav`, `icon.*`.

1. **Anchors** (`anchors.json`): `[[segTime, demoTime], …]` maps the demo onto the voice. segTime = seconds from `demo_start`; the last pair is `[demo_end − demo_start, DUR]`. Put each scene's start on the word that describes it (e.g. the app's main screen on "second number feature", the choose screen on "grab", the selection tap on "pick the number yourself", the verification screens on the use-case list). Start the store page a bit into its animation (demo 0.5) if the narration is quick. Keep any stretch between 0.4× and 2× speed. Worked example (Telicall, demo_start 5.0): `[[0,0.5],[2.0,4.3],[3.2,6.1],[6.9,7.38],[7.9,8.9],[8.6,10.3],[10.6,12.9],[13.0,15.1],[15.45,16.75],[15.9,17.2]]`.
2. **Render the demo:** `arcads_html_to_video` with `html` = the full content of `demo.html`, `durationSeconds` = `demo_end − demo_start`, `width 1080`, `height 1920`, `timeMap` = the content of `anchors.json` (same format: `[videoSecond, renderSecond]`, starts at `[0, …]`, ends at `[demo_end − demo_start, DUR]`), no `audio` (all SFX go through `mix.py`), `productId`, `projectId`, title `<app>_demo_v1`. Poll `arcads_get_asset` (waitSeconds 40) and `curl` the `downloadUrl` to `demo_seg.mp4` (30 fps, 1080×1920). If the render fails with an error from `render(t)`, fix `demo.html` and render again (the error is in your code; this is not a regeneration).
   Then `python3 demo_events.py demo.html anchors.json <demo_start>` → `demo_events.json` (taps and EVENTS mapped to ad time, read by `build_timeline.py`).
3. `python3 hook_peak.py hook.mp4 <hook_end>` → `hook_fast.mp4`, plus `peak_in_ad` (the crush lands ~0.7 s before the cut).
4. `python3 make_logo.py icon.png "<App name>" "<dark brand hex>"` → `logo.png` (transparent PNG, made locally: `arcads_html_to_image` exports opaque images, tested Nov 2026).
5. `plan.json`: `{"srt":"actor.srt","fix":{"<misspelling>":"<App>"},"duration":D,"hook_end":H,"demo_start":S,"demo_end":E,"logo_start":L,"hook_peak":<peak_in_ad>}` (optional: `caption_y` 1400, `cut_scale` 0.53, `cut_center_x` 815, `music_under_db` 16, `duck_db` 8). Then `python3 build_timeline.py plan.json` → `timeline.json`.
6. Do NOT run `music_fit.py` (it splices the track and created audible stop/restart jumps). `python3 mix.py timeline.json` → `mix.wav` (must print `"voice_untouched": true`). The music runs continuously from `music.wav`, sits 16 dB under the voice RMS and ducks another 8 dB while the actor speaks (smooth 150 ms ramps, 400 ms hold), so every word is clearly audible. No music stops anywhere.
7. `SNAP=<hook_peak>,<demo_start+3>,<demo_start+9>,<logo_start+1> python3 compose.py timeline.json <app>_ugc_ad_final.mp4` (~2 min). Read the `snap_*.jpg` files to check the LAYOUT only (captions readable, cut-out placed bottom-right with the outline, logo at the top). To check transitions, add SNAP times just around `hook_end`, `demo_start` and `demo_end` (e.g. −0.07, +0.03, +0.1). Fix layout values in plan.json and re-run if needed; never comment on the actor's performance.

## Step 10: Deliver

Write the single final file to the outputs folder and send it. Report in a few lines: structure with timestamps, credits actually charged (sum of `creditsCharged` from `arcads_get_asset`, SFX included), and the Arcads project link. Offer variations (one of the other hook ideas from Step 3b, other use case, new actor, other language), each as a new single final video. A new hook only re-runs the hook generation (~520 credits), the hook SFX and the edit: the actor clip, cut-out, demo and music are reused.

## Known pitfalls (already handled in the scripts)

- The cut-out must advance on EVERY frame, not only during the demo, or the cut-out actor lags his own voice (bug seen Nov 2026: 5 s offset). `compose.py` does this.
- The actor clip is 24 fps and the cut-out is 30 fps: `compose.py` resamples everything to 30 fps on the same clock.
- `mzstatic.com` (App Store images) is blocked in the sandbox: relay through `arcads_upload_media` with `url`. SFX come from `arcads_create_sound_effect` and download directly from Arcads storage (no relay).
- The transcription misspells brand names: fix them with `fix` in plan.json (captions only; the audio is untouched).
- Generated music often fades at the end: the CTA section is 2 s longer than needed and `mix.py` fades it out on the last word.
- The Arcads HTML renderer has no system fonts: `demo.html` loads Inter from Google Fonts (keep the `<link>`; add any other font you use). Rare symbols (⌕, ⟳…) render as NO GLYPH boxes even with Noto Sans Symbols 2: draw icons in SVG. Emoji, ★ and ◙ render.
- `demo.html` must stay deterministic: everything in `render(t)` is computed from t alone (no CSS transitions/animations, requestAnimationFrame, timers, Date.now or unseeded Math.random), since frames render in parallel on separate machines. The template's engine already follows this.
- If the hook's motion peak is late, `hook_peak.py` speeds the hook up so the crush is on screen before the cut.
- Never cut, splice or stop the music (bug seen Nov 2026: music stops before cuts + `music_fit.py` splices made the bed cut out and restart, very bad transitions). The riser SFX is placed so its END lands on the cut (`mix.py`).
- Music must stay audible: never scale all added layers down because one SFX peak would clip (bug seen Nov 2026: one impact hit pushed the whole music bed 10 dB down, inaudible). `mix.py` only pulls the added layers down at the clipping samples. Music too loud is the other failure (user feedback Nov 2026: the actor was hard to hear): 16 dB under the voice + 8 dB ducking while the actor speaks is the default; raise `music_under_db` if needed, never set it below 14.

## Appendix: files (write verbatim)

### preflight.sh

````bash
#!/bin/bash
# Checks everything the pipeline needs; installs what it can. Prints OK/FIX lines.
ok(){ echo "OK   $1"; }; fix(){ echo "FIX  $1"; }
command -v ffmpeg >/dev/null || (apt-get install -y ffmpeg >/dev/null 2>&1 || brew install ffmpeg >/dev/null 2>&1)
command -v ffmpeg >/dev/null && ok ffmpeg || fix "ffmpeg missing and could not be installed"
ffmpeg -hide_banner -decoders 2>/dev/null | grep -q libvpx-vp9 && ok "vp9 alpha decoder" || fix "ffmpeg lacks libvpx-vp9 (needed for the cut-out actor)"
python3 -c "import numpy, cv2, PIL, soundfile, scipy" 2>/dev/null || pip install -q numpy opencv-python-headless pillow soundfile scipy --break-system-packages >/dev/null 2>&1
python3 -c "import numpy, cv2, PIL, soundfile, scipy" 2>/dev/null && ok "python libs" || fix "python libs (numpy opencv pillow soundfile scipy)"
fc-list | grep -qi "Inter.*Black" || (apt-get install -y fonts-inter >/dev/null 2>&1; fc-cache -f >/dev/null 2>&1)
fc-list | grep -qi "Inter.*Black" && ok "Inter font" || fix "Inter font missing: captions and logo fall back to DejaVu (install fonts-inter)"
code=$(curl -s -o /dev/null -w "%{http_code}" https://argoseyes.s3-accelerate.amazonaws.com/ 2>/dev/null)
[ "$code" != "000" ] && ok "Arcads storage reachable" || fix "Arcads storage blocked: Settings > Capabilities > allow *.s3-accelerate.amazonaws.com"
````

### demo_template.html

````html
<!DOCTYPE html>
<html><head><meta charset="utf-8">
<!-- The Arcads renderer has no system fonts: load every font used. Draw icons in inline SVG: rare symbols like ⌕ ⟳ render as NO GLYPH boxes even with Noto Sans Symbols 2 (tested Nov 2026). -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&family=Noto+Sans+Symbols+2&display=swap" rel="stylesheet">
<style>
*{box-sizing:border-box;margin:0;padding:0}
html,body{width:1080px;height:1920px;overflow:hidden;background:#fff;font-family:Inter,"Noto Sans Symbols 2",sans-serif;-webkit-font-smoothing:antialiased}
#stage{position:absolute;inset:0;overflow:hidden;background:#fff}
.scene{position:absolute;inset:0;overflow:hidden;opacity:0;will-change:transform}
.abs{position:absolute}
.purple{color:#5B2BD9}
.btn{position:absolute;display:flex;align-items:center;justify-content:center;color:#fff;font-weight:600}
/* app store */
#s1{background:#fff}
.stat{position:absolute;top:432px;width:250px;text-align:center;color:#8e8e93}
.stat .k{font-size:22px;font-weight:600;letter-spacing:1px}
.stat .v{font-size:44px;font-weight:600;color:#6d6d72;margin-top:12px}
.stat .s{font-size:26px;margin-top:6px}
/* home */
#s2{background:radial-gradient(circle at 15% 20%,#ff2d4a 0,rgba(255,45,74,0) 42%),radial-gradient(circle at 85% 30%,#d81e5b 0,rgba(216,30,91,0) 40%),radial-gradient(circle at 25% 75%,#8b2bd6 0,rgba(139,43,214,0) 45%),radial-gradient(circle at 90% 85%,#2f6bff 0,rgba(47,107,255,0) 50%),linear-gradient(160deg,#c3122f,#9c1d8f 45%,#5a2fe0 75%,#2f6bff)}
.app{position:absolute;width:170px;text-align:center}
.app .ic{width:170px;height:170px;border-radius:40px;display:flex;align-items:center;justify-content:center;box-shadow:0 6px 18px rgba(0,0,0,.18)}
.app .lb{color:#fff;font-size:30px;margin-top:12px;font-weight:500;text-shadow:0 1px 4px rgba(0,0,0,.35);white-space:nowrap;margin-left:-40px;margin-right:-40px}
/* telicall app */
.card{position:absolute;left:44px;width:992px;background:#fff;border:2px solid #ececf0;border-radius:36px}
.tile{position:absolute;width:112px;height:112px;border-radius:28px;background:#EFEAFE;display:flex;align-items:center;justify-content:center}
.h{font-weight:700;color:#111}
.g{color:#77777f}
.row{position:absolute;left:44px;width:992px;height:152px;border-bottom:2px solid #ececf0;display:flex;align-items:center;padding:0 44px;font-size:46px;font-weight:500;color:#111;background:#fafafb}
.radio{position:absolute;right:44px;top:50px;width:52px;height:52px;border-radius:50%;border:4px solid #8e8e96;background:#fff}
/* whatsapp */
.wabg{background-color:#efefef}
.wacard{position:absolute;left:84px;width:912px;background:#fff;border-radius:56px;box-shadow:0 10px 40px rgba(0,0,0,.08)}
.wabtn{position:absolute;left:56px;width:800px;height:118px;border-radius:26px;background:#3EE36B;color:#fff;font-size:44px;font-weight:600;display:flex;align-items:center;justify-content:center}
.digit{position:absolute;width:150px;height:150px;border-radius:50%;border:3px solid #e2e2e2;display:flex;align-items:center;justify-content:center;font-size:88px;font-weight:700;color:#111}
#cursor{position:absolute;width:0;height:0;z-index:50}
#ring{position:absolute;left:-52px;top:-52px;width:104px;height:104px;border-radius:50%;border:13px solid #D9FF3A;box-shadow:0 0 22px rgba(160,220,0,.55),inset 0 0 10px rgba(160,220,0,.4)}
#ripple{position:absolute;left:-52px;top:-52px;width:104px;height:104px;border-radius:50%;border:6px solid #D9FF3A;opacity:0}
#arrow{position:absolute;left:4px;top:4px}
#notif{position:absolute;left:30px;top:30px;width:1020px;height:200px;border-radius:44px;background:rgba(235,235,235,.96);box-shadow:0 12px 40px rgba(0,0,0,.15);z-index:40;display:flex;align-items:center;padding:0 36px;backdrop-filter:blur(20px)}
</style></head>
<body>
<svg width="0" height="0" style="position:absolute">
 <defs>
  <filter id="mb" x="-30%" y="-30%" width="160%" height="160%"><feGaussianBlur id="mbg" stdDeviation="0 0"/></filter>
  <symbol id="phone" viewBox="0 0 24 24"><path d="M6.6 10.8c1.4 2.8 3.8 5.1 6.6 6.6l2.2-2.2c.3-.3.7-.4 1-.2 1.1.4 2.3.6 3.6.6.6 0 1 .4 1 1V20c0 .6-.4 1-1 1C11.6 21 3 12.4 3 2c0-.6.4-1 1-1h3.5c.6 0 1 .4 1 1 0 1.3.2 2.5.6 3.6.1.3 0 .7-.2 1L6.6 10.8z"/></symbol>
  <symbol id="tlogo" viewBox="0 0 100 100"><use href="#phone" x="10" y="16" width="62" height="62" fill="#fff"/><circle cx="66" cy="34" r="18" fill="none" stroke="#fff" stroke-width="5"/><path d="M48 34h36M66 16c-7 6-7 30 0 36M66 16c7 6 7 30 0 36" fill="none" stroke="#fff" stroke-width="4"/></symbol>
  <symbol id="wa" viewBox="0 0 100 100"><path d="M50 8a42 42 0 0 0-36 63L8 92l22-6A42 42 0 1 0 50 8z" fill="none" stroke="currentColor" stroke-width="7" stroke-linejoin="round"/><use href="#phone" x="28" y="27" width="44" height="44" fill="currentColor"/></symbol>
  <symbol id="check" viewBox="0 0 100 100"><path d="M22 52l18 18 38-40" fill="none" stroke="currentColor" stroke-width="11" stroke-linecap="round" stroke-linejoin="round"/></symbol>
  <pattern id="doodle" width="260" height="260" patternUnits="userSpaceOnUse">
   <g fill="none" stroke="#dcdcdc" stroke-width="4" stroke-linecap="round">
    <circle cx="40" cy="40" r="22"/><path d="M30 40h20M40 30v20"/>
    <path d="M150 30l10 20 22 3-16 15 4 22-20-11-20 11 4-22-16-15 22-3z"/>
    <path d="M60 150c-10-18 20-28 20-8 0-20 30-10 20 8l-20 20z"/>
    <rect x="170" y="140" width="56" height="40" rx="8"/><path d="M170 146l28 20 28-20"/>
    <path d="M20 220q20-30 40 0t40 0"/><circle cx="215" cy="230" r="12"/><path d="M120 95l20 10-20 10"/>
   </g>
  </pattern>
 </defs>
</svg>

<div id="stage">

<!-- S1 APP STORE -->
<div class="scene" id="s1">
 <div class="abs" style="left:24px;top:30px;color:#007AFF;font-size:40px;display:flex;align-items:center;gap:10px"><svg width="26" height="44" viewBox="0 0 13 22"><path d="M11 2L2 11l9 9" stroke="#007AFF" stroke-width="3" fill="none" stroke-linecap="round"/></svg>Search</div>
 <div class="abs" style="left:34px;top:110px;width:210px;height:210px;border-radius:48px;background:linear-gradient(145deg,#6A38F0,#3E14B0);box-shadow:0 4px 14px rgba(70,20,180,.3)"><svg width="210" height="210"><use href="#tlogo"/></svg></div>
 <div class="abs h" style="left:272px;top:118px;font-size:50px;line-height:58px;font-weight:600">Telicall: Second<br>Phone Number</div>
 <div class="abs g" style="left:272px;top:244px;font-size:32px">Virtual 2nd Mobile Call Text</div>
 <div id="getbtn" class="btn" style="left:272px;top:300px;width:150px;height:64px;border-radius:32px;background:#007AFF;font-size:32px;font-weight:700">Get</div>
 <svg id="prog" class="abs" style="left:304px;top:296px;opacity:0" width="74" height="74" viewBox="0 0 74 74"><circle cx="37" cy="37" r="30" stroke="#d6d6db" stroke-width="6" fill="none"/><circle id="progc" cx="37" cy="37" r="30" stroke="#007AFF" stroke-width="6" fill="none" stroke-dasharray="188.5" stroke-dashoffset="188.5" transform="rotate(-90 37 37)" stroke-linecap="round"/><rect x="30" y="28" width="5" height="18" fill="#007AFF"/><rect x="39" y="28" width="5" height="18" fill="#007AFF"/></svg>
 <svg class="abs" style="left:980px;top:300px" width="50" height="64" viewBox="0 0 25 32"><path d="M12.5 2v18M6 8l6.5-6.5L19 8M5 14H2v16h21V14h-3" stroke="#007AFF" stroke-width="2.4" fill="none"/></svg>
 <div class="abs" style="left:34px;top:405px;width:1012px;border-top:2px solid #e5e5ea"></div>
 <div class="stat" style="left:0"><div class="k">186 RATINGS</div><div class="v">4.4</div><div class="s">★★★★☆</div></div>
 <div class="stat" style="left:250px"><div class="k">AGE</div><div class="v">4+</div><div class="s">Years Old</div></div>
 <div class="stat" style="left:540px"><div class="k">CHART</div><div class="v"><span style="font-size:32px">No.</span>119</div><div class="s">Utilities</div></div>
 <div class="stat" style="left:810px"><div class="k">DEVELOPER</div><div class="v">◙</div><div class="s">GETVERIFY LDA</div></div>
 <div class="abs" style="left:34px;top:650px;width:1012px;border-top:2px solid #e5e5ea"></div>
 <div class="abs h" style="left:34px;top:680px;font-size:46px">Preview</div>
 <div class="abs" style="left:34px;top:770px;width:640px;height:1180px;border-radius:50px;background:linear-gradient(180deg,#EDE6FF,#F7F3FF)">
  <div class="abs" style="left:44px;top:50px;display:flex;align-items:center;gap:14px"><div style="width:72px;height:72px;border-radius:18px;background:#5B2BD9"><svg width="72" height="72"><use href="#tlogo"/></svg></div><span style="font-size:64px;font-weight:800;color:#2a2340;letter-spacing:-1px">telicall</span></div>
  <div class="abs" style="left:44px;top:170px;font-size:66px;line-height:76px;font-weight:800;color:#1d1830">International<br>Phone Calls &amp;<br>2nd Number</div>
  <div class="abs" style="left:44px;top:470px;width:550px;height:200px;border-radius:30px;background:#fff;box-shadow:0 8px 30px rgba(80,40,200,.12);padding:34px;font-size:30px;line-height:62px;color:#333">🇬🇧 +44 2345 678999<br>🇺🇸 +1 201 555 0123</div>
  <div class="abs" style="left:44px;top:720px;width:550px;height:420px;border-radius:30px;background:linear-gradient(160deg,#D9CCFF,#B9A2FF)"></div>
 </div>
 <div class="abs" style="left:700px;top:770px;width:640px;height:1180px;border-radius:50px;background:linear-gradient(180deg,#EDE6FF,#F7F3FF)">
  <div class="abs" style="left:40px;top:150px;font-size:56px;line-height:66px;font-weight:800;color:#1d1830">Call 200+ countries<br>at low rates</div>
  <div class="abs" style="left:40px;top:340px;width:540px;height:560px;border-radius:30px;background:#fff;box-shadow:0 8px 30px rgba(80,40,200,.12)"></div>
 </div>
</div>

<!-- S2 HOME -->
<div class="scene" id="s2">
 <div id="homegrid"></div>
 <div id="dim" class="abs" style="inset:0;background:rgba(10,0,30,.55);opacity:0"></div>
 <div id="telihome" class="app" style="left:99px;top:585px"><div class="ic" style="background:linear-gradient(145deg,#6A38F0,#3E14B0)"><svg width="170" height="170"><use href="#tlogo"/></svg></div><div class="lb">Telicall</div></div>
 <div class="abs" style="left:420px;top:1520px;width:240px;height:72px;border-radius:36px;background:rgba(255,255,255,.28);color:#fff;font-size:32px;display:flex;align-items:center;justify-content:center;gap:10px;font-weight:500"><svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2.6" stroke-linecap="round"><circle cx="10" cy="10" r="7"/><path d="M15.5 15.5L21 21"/></svg>Search</div>
 <div class="abs" style="left:28px;top:1660px;width:1024px;height:230px;border-radius:70px;background:rgba(255,255,255,.25)"></div>
</div>

<!-- S3 EXPLORE -->
<div class="scene" id="s3">
 <div class="card" style="top:40px;height:570px">
  <div class="tile" style="left:44px;top:44px"><svg width="56" height="56" fill="#5B2BD9"><use href="#phone"/></svg></div>
  <div class="abs h" style="left:44px;top:200px;font-size:46px">Make Global Calls</div>
  <div class="abs g" style="left:44px;top:272px;width:900px;font-size:36px;line-height:54px">Call mobile and landlines in 200+ countries at low rates.</div>
  <div class="btn" style="left:44px;top:420px;width:900px;height:110px;border-radius:22px;background:#5B2BD9;font-size:40px">Explore Now</div>
 </div>
 <div class="card" style="top:650px;height:150px;background:#f6f6f8;border:none">
  <svg class="abs" style="left:44px;top:47px" width="56" height="56" viewBox="0 0 24 24" fill="none" stroke="#555" stroke-width="1.6"><circle cx="12" cy="12" r="10"/><path d="M2 12h20M12 2c-3 3-3 17 0 20M12 2c3 3 3 17 0 20"/></svg>
  <div class="abs" style="left:136px;top:46px;font-size:46px;font-weight:500;color:#222">Calling Rates</div>
  <div class="abs g" style="right:44px;top:38px;font-size:56px">›</div>
 </div>
 <div class="card" style="top:840px;height:600px">
  <div class="tile" style="left:44px;top:44px"><svg width="50" height="56" viewBox="0 0 20 24"><path d="M3 1h10l5 5v16H3z" fill="#5B2BD9"/><rect x="7" y="11" width="7" height="7" rx="1" fill="#fff"/></svg></div>
  <div class="abs h" style="left:44px;top:200px;font-size:46px">Add a 2nd Number</div>
  <div class="abs g" style="left:44px;top:272px;width:900px;font-size:36px;line-height:54px">Get a local number from your chosen country to instantly receive calls and SMS.</div>
  <div id="getstarted" class="btn" style="left:44px;top:450px;width:900px;height:110px;border-radius:22px;background:#5B2BD9;font-size:40px">Get Started</div>
 </div>
 <div class="abs" style="left:0;top:1740px;width:1080px;height:180px;border-top:2px solid #ececf0;background:#fff;display:flex;justify-content:space-around;padding-top:26px;font-size:30px;color:#9a9aa2">
  <div style="text-align:center;color:#5B2BD9"><div style="width:56px;height:56px;border-radius:50%;background:#5B2BD9;margin:0 auto 8px"></div>Explore</div>
  <div style="text-align:center"><div style="width:56px;height:56px;border-radius:50%;background:#c9c9cf;margin:0 auto 8px"></div>Message</div>
  <div style="text-align:center"><div style="width:56px;height:56px;border-radius:50%;background:#c9c9cf;margin:0 auto 8px"></div>Calls</div>
  <div style="text-align:center"><div style="width:56px;height:56px;border-radius:50%;background:#c9c9cf;margin:0 auto 8px"></div>Account</div>
 </div>
</div>

<!-- S4 CHOOSE NUMBER -->
<div class="scene" id="s4">
 <div class="abs h" style="left:44px;top:70px;font-size:56px">Choose Your Number</div>
 <div class="abs" style="left:44px;top:170px;font-size:40px;color:#333">Select the local number you want to get.</div>
 <div class="abs" style="left:44px;top:270px;width:992px;height:150px;border-radius:26px;background:#f4f4f6;display:flex;align-items:center;padding:0 40px;font-size:46px;font-weight:500;color:#111">
  <span id="flag" style="font-size:56px;margin-right:26px"></span><span id="country"></span>&nbsp;<span id="dial" style="color:#a0a0a8"></span>
  <span id="price" class="purple" style="margin-left:auto;margin-right:40px"></span><span class="g" style="font-size:60px">›</span>
 </div>
 <div id="numlist" class="abs" style="left:0;top:470px;width:1080px"></div>
 <div class="abs purple" style="left:0;top:1430px;width:1080px;text-align:center;font-size:40px;font-weight:600;display:flex;align-items:center;justify-content:center;gap:14px"><svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="#5B2BD9" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"><path d="M20 12a8 8 0 1 1-2.3-5.6"/><path d="M20 4v5h-5"/></svg>Refresh Numbers</div>
 <div id="continue" class="btn" style="left:44px;top:1540px;width:992px;height:130px;border-radius:30px;background:#5B2BD9;font-size:44px">Continue</div>
</div>

<!-- S5 READY -->
<div class="scene" id="s5">
 <svg id="readycheck" class="abs" style="left:440px;top:600px;color:#5B2BD9" width="200" height="200"><use href="#check"/></svg>
 <div id="readytxt" class="abs h" style="left:0;top:850px;width:1080px;text-align:center;font-size:60px;line-height:76px">Your 2nd number is ready<br>to use!</div>
 <div id="readypill" class="abs" style="left:0;top:1050px;width:1080px;text-align:center"><span id="readynum" style="display:inline-block;background:#5B2BD9;color:#fff;font-size:42px;font-weight:600;padding:20px 44px;border-radius:50px"></span></div>
</div>

<!-- S6 VERIFY -->
<div class="scene wabg" id="s6">
 <svg class="abs" style="inset:0" width="1080" height="1920"><rect width="1080" height="1920" fill="url(#doodle)"/></svg>
 <div class="wacard" style="top:150px;height:1500px">
  <svg class="abs tcolor" style="left:376px;top:150px" width="160" height="160"><use href="#wa"/></svg>
  <div class="abs tname tcolor" style="left:0;top:340px;width:912px;text-align:center;font-size:96px;font-weight:700;letter-spacing:-1px"></div>
  <div class="abs h" style="left:0;top:500px;width:912px;text-align:center;font-size:54px;font-weight:600">Verify your account</div>
  <div class="abs g" style="left:80px;top:600px;width:752px;text-align:center;font-size:36px;line-height:58px">Please enter your number. We will send a code to your phone to verify your account.</div>
  <div class="abs g" style="left:56px;top:790px;font-size:36px">Phone number</div>
  <div class="abs" style="left:56px;top:850px;width:800px;height:130px;border-radius:24px;border:2px solid #e2e2e2;display:flex;align-items:center;padding:0 46px;font-size:46px;font-weight:500;color:#111"><span id="typed"></span><span id="caret" style="display:inline-block;width:4px;height:56px;background:#111;margin-left:4px"></span></div>
  <div id="sendbtn" class="wabtn tbg" style="top:1040px">Send me code</div>
 </div>
</div>

<!-- S7 CODE -->
<div class="scene wabg" id="s7">
 <svg class="abs" style="inset:0" width="1080" height="1920"><rect width="1080" height="1920" fill="url(#doodle)"/></svg>
 <div class="wacard" style="top:150px;height:1500px">
  <svg class="abs tcolor" style="left:396px;top:110px" width="120" height="120"><use href="#wa"/></svg>
  <div class="abs h" style="left:0;top:280px;width:912px;text-align:center;font-size:52px;font-weight:600">Enter your 4 digit code</div>
  <div class="abs" style="left:236px;top:400px;width:440px;height:330px;border-radius:40px;background:#f1f1f1">
   <svg class="abs" style="left:110px;top:55px" width="220" height="220" viewBox="0 0 100 100"><rect x="44" y="52" width="10" height="44" fill="#111"/><rect x="47" y="54" width="5" height="40" class="tfill"/><path d="M30 14h40a14 14 0 0 1 14 14v28H30z" fill="#111"/><path d="M33 17h37a11 11 0 0 1 11 11v25H33z" class="tfill"/><path d="M30 14a14 14 0 0 0-14 14v28h28V28A14 14 0 0 0 30 14z" fill="#111"/><path d="M30 17a11 11 0 0 0-11 11v25h22V28A11 11 0 0 0 30 17z" fill="#fff"/><rect x="8" y="30" width="34" height="22" fill="#fff" stroke="#111" stroke-width="3"/><path d="M8 30l17 12 17-12M8 52l12-10M42 52l-12-10" fill="none" stroke="#111" stroke-width="3"/></svg>
  </div>
  <div id="digits"></div>
  <div class="abs g" style="left:0;top:1000px;width:912px;text-align:center;font-size:36px">Didn't get the code? <span class="tcolor" style="font-weight:600">Resend</span></div>
  <div id="verifybtn" class="wabtn tbg" style="top:1120px">Verify</div>
 </div>
</div>

<!-- S8 VERIFIED -->
<div class="scene wabg" id="s8">
 <svg class="abs" style="inset:0" width="1080" height="1920"><rect width="1080" height="1920" fill="url(#doodle)"/></svg>
 <div class="wacard" style="top:150px;height:1500px">
  <svg class="abs tcolor" style="left:376px;top:100px" width="160" height="160"><use href="#wa"/></svg>
  <div class="abs tname tcolor" style="left:0;top:280px;width:912px;text-align:center;font-size:96px;font-weight:700;letter-spacing:-1px"></div>
  <div id="vcircle" class="abs" style="left:256px;top:470px;width:400px;height:400px;border-radius:50%;background:#E6FBEA;display:flex;align-items:center;justify-content:center"><svg class="tcolor" width="260" height="260"><use href="#check"/></svg></div>
  <div class="abs h" style="left:0;top:940px;width:912px;text-align:center;font-size:60px">Verified!</div>
  <div class="abs g" style="left:100px;top:1040px;width:712px;text-align:center;font-size:36px;line-height:58px">Hurrah!! You have successfully verified the account.</div>
  <div class="wabtn tbg" style="top:1260px">Browse Home</div>
 </div>
</div>

<div id="notif"><div style="width:120px;height:120px;border-radius:50%;background:#bdbdbd;flex:none;overflow:hidden;position:relative"><div style="position:absolute;left:36px;top:20px;width:48px;height:48px;border-radius:50%;background:#fff"></div><div style="position:absolute;left:16px;top:76px;width:88px;height:70px;border-radius:44px;background:#fff"></div></div>
 <div style="margin-left:30px;flex:1"><div style="display:flex;justify-content:space-between"><span class="tname" style="font-size:40px;font-weight:700;color:#111"></span><span style="font-size:32px;color:#888">now</span></div><div id="notiftxt" style="font-size:34px;line-height:44px;color:#333;margin-top:4px"></div></div></div>

<div id="cursor"><div id="ripple"></div><div id="ring"></div><svg id="arrow" width="70" height="80" viewBox="0 0 35 40"><path d="M2 2l28 14-12 3-6 12z" fill="#D9FF3A" stroke="#7a9c00" stroke-width="2" stroke-linejoin="round"/></svg></div>
</div>

<script>
const CFG = window.CFG || {
  country:"United Kingdom", dial:"(+44)", flag:"🇬🇧", price:"$1,29",
  numbers:["+44 7890 040190","+44 7405 179091","+44 7768 999038","+44 7512 725056","+44 7895 819038","+44 7753 159948"],
  pick:4, target:{name:"WhatsApp", color:"#3EE36B", dark:"#25C152"}, code:"3197"
};
const $=id=>document.getElementById(id);
// ---------- build dynamic bits ----------
const homeApps=[
 ["Health","#fff",'<svg width="100" height="100" viewBox="0 0 24 24"><path d="M12 21s-8-5.5-8-11a4.5 4.5 0 0 1 8-2.8A4.5 4.5 0 0 1 20 10c0 5.5-8 11-8 11z" fill="#ff2d55"/></svg>'],
 ["Wallet","#1c1c1e",'<div style="width:110px;height:80px;border-radius:12px;background:linear-gradient(#f5a623 0 25%,#4cd964 25% 50%,#5ac8fa 50% 75%,#ff3b30 75%)"></div>'],
 ["Reminders","#fff",'<div style="font-size:34px;line-height:40px;color:#ccc;text-align:left"><span style="color:#007aff">●</span> ───<br><span style="color:#ff3b30">●</span> ───<br><span style="color:#ff9500">●</span> ───</div>'],
 ["Mail","linear-gradient(#5ac8fa,#007aff)",'<svg width="110" height="80" viewBox="0 0 22 16"><rect x="1" y="1" width="20" height="14" rx="2" fill="#fff"/><path d="M1 2l10 7 10-7" fill="none" stroke="#2a8cf0" stroke-width="1.4"/></svg>'],
 ["Telegram","linear-gradient(#37aee2,#1e96c8)",'<svg width="100" height="100" viewBox="0 0 24 24"><path d="M2 11l19-8-3 18-6-5-3 3v-5l9-8-11 7z" fill="#fff"/></svg>'],
 ["Tinder","linear-gradient(#ff655b,#fd297b)",'<svg width="70" height="90" viewBox="0 0 14 18"><path d="M7 1c1 4 6 6 6 11a6 6 0 0 1-12 0c0-3 2-4 2-6 2 1 2 3 2 3 1-3 2-5 2-8z" fill="#fff"/></svg>'],
 ["Hinge","#fff",'<span style="font-size:110px;font-weight:900;color:#111;font-family:serif">H</span>'],
 ["Bumble","#ffc629",'<div style="width:100px"><div style="height:14px;background:#111;border-radius:7px;margin:10px 15px"></div><div style="height:14px;background:#111;border-radius:7px;margin:10px 0"></div><div style="height:14px;background:#111;border-radius:7px;margin:10px 15px"></div></div>'],
];
const colX=[99,336,574,811], rowY=[60,320];
$("homegrid").innerHTML = homeApps.map((a,i)=>`<div class="app" style="left:${colX[i%4]}px;top:${rowY[i>>2]}px"><div class="ic" style="background:${a[1]}">${a[2]}</div><div class="lb">${a[0]}</div></div>`).join("")
 + [1,2,3].map(n=>`<div class="app wapp" id="wa${n}" style="left:${colX[n]}px;top:585px"><div class="ic" style="background:${CFG.target.color};color:#fff"><svg width="120" height="120"><use href="#wa"/></svg></div><div class="lb">${CFG.target.name} #${n}</div></div>`).join("")
 + `<div class="app" style="left:180px;top:1700px"><div class="ic" style="background:#fff"><svg width="110" height="110" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10" fill="#1a8cff"/><path d="M12 4l3 8-3 8-3-8z" fill="#fff"/><path d="M12 4l3 8h-6z" fill="#ff3b30"/></svg></div></div>`
 + `<div class="app" style="left:440px;top:1700px"><div class="ic" style="background:#3dd65a"><svg width="110" height="110" fill="#fff"><use href="#phone"/></svg></div></div>`
 + `<div class="app" style="left:700px;top:1700px"><div class="ic" style="background:linear-gradient(#5df07a,#28c840)"><svg width="110" height="100" viewBox="0 0 24 22"><ellipse cx="12" cy="10" rx="10" ry="8" fill="#fff"/><path d="M5 15l-2 5 6-3z" fill="#fff"/></svg></div></div>`;
$("flag").textContent=CFG.flag; $("country").textContent=CFG.country; $("dial").textContent=CFG.dial; $("price").textContent=CFG.price;
$("numlist").innerHTML = CFG.numbers.map((n,i)=>`<div class="row" id="row${i}" style="top:${i*152}px;${i==0?'border-radius:26px 26px 0 0;':''}${i==CFG.numbers.length-1?'border-radius:0 0 26px 26px;border-bottom:none;':''}"><span class="num">${n}</span><div class="radio" id="radio${i}"></div></div>`).join("");
$("readynum").textContent=CFG.numbers[CFG.pick];
$("digits").innerHTML=[0,1,2,3].map(i=>`<div class="digit" id="d${i}" style="left:${106+i*180}px;top:800px"></div>`).join("");
$("notiftxt").textContent=`Your verification code is ${CFG.code}. Do not share this code with anyone.`;
document.querySelectorAll(".tname").forEach(e=>e.textContent=CFG.target.name);
document.querySelectorAll(".tcolor").forEach(e=>e.style.color=CFG.target.color);
document.querySelectorAll(".tbg").forEach(e=>e.style.background=CFG.target.color);
document.querySelectorAll(".tfill").forEach(e=>e.setAttribute("fill",CFG.target.color));

// ===================== HELPERS (engine, do not change) =====================
const clamp=(x,a=0,b=1)=>Math.min(b,Math.max(a,x));
const prog=(t,a,b)=>clamp((t-a)/(b-a));               // 0..1 progress of t between a and b
const eio=x=>x<.5?4*x*x*x:1-Math.pow(-2*x+2,3)/2;      // ease in-out
const eout=x=>1-Math.pow(1-x,3);                       // ease out
const eback=x=>{const c=1.70158,c3=c+1;return 1+c3*Math.pow(x-1,3)+c*Math.pow(x-1,2)}; // overshoot pop
const pop=(t,a,b)=>{const p=prog(t,a,b);return p<=0?0:eback(p)};
const press=(t,tap)=>t>tap-0.05&&t<tap+0.2;            // true while a button is being pressed

// ===================== APP TIMELINE (rewrite per app) =====================
// SCENES in demo seconds. Transitions (engine): default = fast whip-swipe from the right with horizontal motion blur;
// zoomFrom:[x,y] = iOS app-open zoom from that point (the app icon on the home screen); enter:"cut" = hard cut + punch-in.
// The LAST scene always whips up with vertical motion blur (hand-off to the actor).
const SCENES=[
 {id:"s1",start:0,end:2.3},{id:"s2",start:2.3,end:4.3},{id:"s3",start:4.3,end:6.1,zoomFrom:[184,670]},
 {id:"s4",start:6.1,end:8.9},{id:"s5",start:8.9,end:10.3},{id:"s6",start:10.3,end:12.9},
 {id:"s7",start:12.9,end:15.1},{id:"s8",start:15.1,end:17.2}];
// Cursor keyframes [demoTime, x, y, tap?]. A tap = ring squeeze + ripple + a tap SFX in the final mix.
const CUR=[[0,760,1250],[0.75,347,332,1],[1.55,347,332],[1.95,347,332,1],[2.3,540,900],[3.25,184,670],[3.55,184,670,1],[4.3,700,1500],[5.25,494,1345,1],[6.1,700,1200],[6.75,600,1150],[7.35,600,1154,1],[8.05,540,1605],[8.35,540,1605,1],[8.9,700,1300],[10.3,700,1500],[11.8,620,1253],[12.25,620,1253,1],[12.9,700,1500],[14.55,540,1330],[14.8,540,1330,1],[15.1,700,1500],[17.2,700,1500]];
// Sound events besides taps, in demo seconds: success | typing (its start) | notif | logo
const EVENTS=[["success",9.0],["typing",10.6],["notif",13.05],["success",15.2]];
// Per-element animations, written for this app. Use prog/pop/press with demo times.
function animate(t){
  // S1 get -> progress -> open
  const dl=prog(t,0.85,1.65);
  $("getbtn").style.opacity = (t<0.85||t>=1.65)?1:0;
  $("getbtn").textContent = t>=1.65?"Open":"Get";
  $("prog").style.opacity = (t>=0.85&&t<1.65)?1:0;
  $("progc").setAttribute("stroke-dashoffset",188.5*(1-eio(dl)));
  // S2 whatsapp pops + dim
  [1,2,3].forEach(n=>{const p=prog(t,2.45+n*0.18,2.75+n*0.18); const e=$("wa"+n); e.style.transform=`scale(${p<=0?0:eback(p)})`; e.style.opacity=p>0?1:0;});
  const dm=prog(t,3.55,3.75); $("dim").style.opacity=dm; document.querySelectorAll(".wapp").forEach(e=>{e.style.filter=`brightness(${1-dm*0.5})`});
  $("telihome").style.transform=`scale(${t>3.5&&t<3.7?0.92:1})`;
  // S3 button press
  $("getstarted").style.background = (t>5.2&&t<5.45)?"#4520B0":"#5B2BD9";
  // S4 select
  const sel=t>=7.38;
  CFG.numbers.forEach((n,i)=>{const r=$("radio"+i), row=$("row"+i);
    const on=sel&&i===CFG.pick; r.style.border=on?"4px solid #5B2BD9":"4px solid #8e8e96"; r.style.boxShadow=on?"inset 0 0 0 9px #fff, inset 0 0 0 30px #5B2BD9":"none";
    row.querySelector(".num").style.color=on?"#5B2BD9":"#111"; row.style.background=on?"#F3EFFF":"#fafafb";});
  $("continue").style.background=(t>8.3&&t<8.55)?"#4520B0":"#5B2BD9";
  // S5 ready
  const ck=prog(t,9.0,9.45); $("readycheck").style.transform=`scale(${ck<=0?0:eback(ck)})`;
  const rt=prog(t,9.2,9.55); $("readytxt").style.opacity=rt; $("readytxt").style.transform=`translateY(${(1-eout(rt))*40}px)`;
  const rp=prog(t,9.45,9.8); $("readypill").style.transform=`scale(${rp<=0?0:eback(rp)})`;
  // S6 typing
  const num=CFG.numbers[CFG.pick]; const nch=Math.floor(clamp((t-10.6)/1.1)*num.length);
  $("typed").textContent=num.slice(0,nch); $("caret").style.opacity=(Math.floor(t*2.5)%2===0||(t>10.6&&t<11.7))?1:0;
  $("sendbtn").style.filter=(t>12.2&&t<12.45)?"brightness(.88)":"none";
  // S7 notification + digits
  const ni=eout(prog(t,13.05,13.4)), no=eio(prog(t,14.5,14.8));
  $("notif").style.transform=`translateY(${(-260)*(1-ni)+(-260)*no}px)`; $("notif").style.opacity=(t>=13&&t<15.1)?1:0;
  [0,1,2,3].forEach(i=>{const at=13.75+i*0.2, p=prog(t,at,at+0.18), d=$("d"+i); d.textContent=t>=at?CFG.code[i]:""; d.style.transform=`scale(${t>=at?eback(p):1})`; d.style.borderColor=t>=at?CFG.target.color:"#e2e2e2";});
  $("verifybtn").style.filter=(t>14.75&&t<15)?"brightness(.88)":"none";
  // S8 verified
  const vc=prog(t,15.2,15.6); $("vcircle").style.transform=`scale(${vc<=0?0:eback(vc)})`;
}

// ===================== ENGINE (do not change) =====================
const DUR=SCENES[SCENES.length-1].end;
const TAPS=CUR.filter(c=>c[3]).map(c=>c[0]);
function cursorAt(t){
  let i=0; while(i<CUR.length-1 && CUR[i+1][0]<=t) i++;
  if(i>=CUR.length-1) return CUR[CUR.length-1];
  const a=CUR[i],b=CUR[i+1],p=eio(prog(t,a[0],b[0]));
  return [0,a[1]+(b[1]-a[1])*p,a[2]+(b[2]-a[2])*p];
}
function render(t){
  t=Number(t);
  let bx=0, by=0;
  SCENES.forEach((sc,k)=>{
    const el=$(sc.id), a=sc.start, b=sc.end, on=t>=a && t<b;
    el.style.opacity=on?1:0; el.style.filter="none"; if(!on) return;
    const last=k===SCENES.length-1, next=SCENES[k+1];
    let tf="none";
    if(sc.zoomFrom){            // iOS-style app open from the icon
      const p=eout(prog(t,a,a+0.3)); tf=`translate(${(1-p)*(sc.zoomFrom[0]-540)}px,${(1-p)*(sc.zoomFrom[1]-960)}px) scale(${0.12+0.88*p})`; el.style.borderRadius=(1-p)*120+"px";
    } else if(sc.enter==="cut"){ // hard cut with a small punch-in
      tf=`scale(${1+0.06*(1-eout(prog(t,a,a+0.2)))})`;
    } else if(k>0){             // default: fast whip-swipe in from the right with horizontal motion blur
      const p=eout(prog(t,a,a+0.16)); tf=`translateX(${(1-p)*480}px)`; bx=Math.max(bx,(1-p)*55);
    }
    if(!last && !(next&&next.zoomFrom) && !(next&&next.enter==="cut")){ // whip out to the left
      const p=prog(t,b-0.07,b); if(p>0){tf=`translateX(${-eio(p)*360}px)`; bx=Math.max(bx,p*55);}
    }
    if(last){                   // hand-off to the actor: vertical whip up with vertical motion blur
      const p=prog(t,b-0.2,b); if(p>0){tf=`translateY(${-eio(p)*1100}px)`; by=p*70;}
    }
    el.style.transform=tf;
    if(bx||by){ $("mbg").setAttribute("stdDeviation",`${bx.toFixed(1)} ${by.toFixed(1)}`); el.style.filter="url(#mb)"; }
  });
  animate(t);
  const c=cursorAt(t), cur=$("cursor");
  cur.style.opacity=(t<0.15||t>=DUR-0.2)?0:1; cur.style.left=c[1]+"px"; cur.style.top=c[2]+"px";
  let sc=1, rip=0, ripS=1;
  TAPS.forEach(tt=>{const d=t-tt; if(d>-0.12&&d<0){sc=Math.min(sc,1-0.3*((d+0.12)/0.12));} else if(d>=0&&d<0.15){sc=Math.min(sc,0.7+0.3*(d/0.15));} if(d>=0&&d<0.45){rip=1-d/0.45; ripS=1+1.4*(d/0.45);} });
  $("ring").style.transform=`scale(${sc})`; $("ripple").style.opacity=rip; $("ripple").style.transform=`scale(${ripS})`;
}
window.render=render; window.DUR=DUR;
window.DEMO_EVENTS=TAPS.map(x=>["tap",x]).concat(EVENTS);   // demo_events.py reads CUR and EVENTS from this file
render(new URLSearchParams(location.search).get("t")||0);
</script>
</body></html>
````

### demo_events.py

````python
"""python3 demo_events.py demo.html anchors.json DEMO_START -> demo_events.json
Reads CUR (taps = keyframes with a 4th value) and EVENTS from demo.html, maps them from demo time to ad time
through anchors.json (the same timeMap given to arcads_html_to_video), and writes [[name, adTime], ...]."""
import json, re, sys
html, anch, ds = open(sys.argv[1], encoding='utf-8').read(), json.load(open(sys.argv[2])), float(sys.argv[3])
grab = lambda name: json.loads(re.search(r'const ' + name + r'\s*=\s*(\[.*?\]);', html, re.S).group(1))
ev = [['tap', c[0]] for c in grab('CUR') if len(c) > 3 and c[3]] + [list(e) for e in grab('EVENTS')]
def inv(d):   # demo time -> segment time (inverse of the piecewise-linear timeMap)
    for (a0, d0), (a1, d1) in zip(anch, anch[1:]):
        if d0 <= d <= d1 and d1 > d0: return a0 + (a1 - a0) * (d - d0) / (d1 - d0)
    return None
out = [[n, round(inv(d) + ds, 3)] for n, d in ev if inv(d) is not None]
json.dump(sorted(out, key=lambda e: e[1]), open('demo_events.json', 'w'))
print(len(out), 'events')
````

### make_logo.py

````python
"""python3 make_logo.py icon.png "AppName" "#2A1F5C" -> logo.png (transparent: rounded app icon + name, white glow + soft shadow)"""
import sys, subprocess
from PIL import Image, ImageDraw, ImageFont, ImageFilter
icon, name, color = sys.argv[1], sys.argv[2], (sys.argv[3] if len(sys.argv) > 3 else '#1d1830')
fp = subprocess.run(['fc-match', '-f', '%{file}', 'Inter:black'], capture_output=True, text=True).stdout or 'DejaVuSans-Bold.ttf'
font = ImageFont.truetype(fp, 130)
ic = Image.open(icon).convert('RGBA').resize((150, 150), Image.LANCZOS)
m = Image.new('L', (150, 150), 0); ImageDraw.Draw(m).rounded_rectangle((0, 0, 149, 149), 34, fill=255); ic.putalpha(m)
tw = int(ImageDraw.Draw(Image.new('L', (1, 1))).textlength(name, font=font)); P = 40
W, H = P + 150 + 22 + tw + P, 150 + 2 * P
fg = Image.new('RGBA', (W, H), (0, 0, 0, 0)); fg.alpha_composite(ic, (P, P))
ImageDraw.Draw(fg).text((P + 172, H // 2), name, font=font, fill=color, anchor='lm')
a = fg.split()[3]
glow = Image.new('RGBA', (W, H), (255, 255, 255, 0)); glow.putalpha(a.filter(ImageFilter.GaussianBlur(18)).point(lambda v: int(v * .9)))
sh = Image.new('RGBA', (W, H), (0, 0, 0, 0)); sh.putalpha(a.filter(ImageFilter.GaussianBlur(10)).point(lambda v: int(v * .18)))
out = Image.new('RGBA', (W, H), (0, 0, 0, 0)); out.alpha_composite(glow); out.alpha_composite(sh, (0, 4)); out.alpha_composite(fg)
out.save('logo.png'); print('logo.png', out.size)
````

### hook_peak.py

````python
"""python3 hook_peak.py hook.mp4 HOOK_END -> prints the motion peak and the speed factor that lands it ~0.7s before HOOK_END; writes hook_fast.mp4"""
import subprocess, sys, numpy as np, json
src, hook_end = sys.argv[1], float(sys.argv[2])
raw = subprocess.run(['ffmpeg','-v','error','-i',src,'-vf','scale=180:320,fps=24','-f','rawvideo','-pix_fmt','gray','-'],capture_output=True).stdout
a = np.frombuffer(raw,np.uint8).reshape(-1,320,180).astype(float)
d = np.abs(np.diff(a,axis=0)).mean((1,2)); d = np.convolve(d,np.ones(3)/3,'same')
peak = (int(np.argmax(d))+1)/24; dur = len(a)/24
target = max(1.0, hook_end-0.7)
speed = max(1.0, peak/target)
if dur/speed < hook_end: speed = dur/hook_end   # never run out of hook footage before the cut
subprocess.run(['ffmpeg','-v','error','-y','-i',src,'-vf',f'setpts=PTS/{speed:.4f}','-an','-c:v','libx264','-crf','14','hook_fast.mp4'],check=True)
print(json.dumps({'motion_peak':round(peak,2),'speed':round(speed,3),'peak_in_ad':round(peak/speed,2),'hook_len':round(dur/speed,2)}))
````

### build_timeline.py

````python
"""python3 build_timeline.py plan.json -> timeline.json
plan.json: {"srt":"actor.srt","fix":{"Telecall":"Telicall"},"duration":30.09,"hook_end":3.8,"demo_start":5.0,
 "demo_end":20.9,"logo_start":24.1,"hook_peak":3.1,"caption_y":1400,"cut_scale":0.53,"cut_center_x":815,"music_under_db":9}
Reads demo_events.json (from demo_events.py). Words: SRT cues split into words, time shared by word length."""
import json, re, sys
p = json.load(open(sys.argv[1]))
txt = open(p['srt'], encoding='utf-8').read()
words = []; sentence_starts = []; prev_end_punct = True
for blk in re.split(r'\n\s*\n', txt.strip()):
    m = re.search(r'(\d+):(\d+):(\d+)[,.](\d+)\s*-->\s*(\d+):(\d+):(\d+)[,.](\d+)', blk)
    if not m: continue
    g = list(map(int, m.groups())); s = g[0]*3600+g[1]*60+g[2]+g[3]/1000; e = g[4]*3600+g[5]*60+g[6]+g[7]/1000
    line = ' '.join(l for l in blk.splitlines()[blk.splitlines().index(next(l for l in blk.splitlines() if '-->' in l))+1:])
    for a, b in p.get('fix', {}).items(): line = line.replace(a, b)
    if prev_end_punct: sentence_starts.append(round(s, 3))
    prev_end_punct = line.rstrip().endswith(('.', '!', '?'))
    ws = [w for w in line.split() if w.strip('.,!?')]
    L = [len(w.strip('.,!?'))+1.5 for w in ws]; tot = sum(L) or 1; t = s
    for w, l in zip(ws, L):
        d = (e-s)*l/tot; words.append([w.strip('.,!?'), round(t,3), round(t+d,3)]); t += d
G = {'impact':.8,'riser':.6,'tap':.5,'whoosh':.55,'notif':.5,'success':.5,'typing':.35,'logo':.6,'hook':.9}
ev = json.load(open('demo_events.json'))
sfx = [[n, t, G.get(n,.5)] for n, t in ev if p['demo_start'] <= t < p['demo_end']]
H, S, E = p['hook_end'], p['demo_start'], p['demo_end']
sfx += [['hook', p['hook_peak'], G['hook']],
        ['whoosh', H - 0.05, .6], ['impact', H, .8],                       # hook -> actor
        ['riser', S, .6], ['whoosh', S, .55], ['impact', S + 0.02, .9],    # actor -> demo (riser ENDS on the cut)
        ['whoosh', E - 0.1, .6], ['impact', E, .8],                        # demo -> actor
        ['logo', p['logo_start'] + 0.1, .6]]
tl = dict(actor='actor.mp4', hook='hook_fast.mp4', demo='demo_seg.mp4', cutout='cutout.webm', cutout_codec='libvpx-vp9',
          logo='logo.png', audio='mix.wav', music='music.wav', duration=p['duration'], hook_end=p['hook_end'],
          demo_start=p['demo_start'], demo_end=p['demo_end'], logo_start=p['logo_start'], caption_y=p.get('caption_y',1400),
          cut_scale=p.get('cut_scale',0.53), cut_center_x=p.get('cut_center_x',815), music_under_db=p.get('music_under_db',16), duck_db=p.get('duck_db',8),
          words=words, sentence_starts=sentence_starts, sfx=sorted(sfx, key=lambda x: x[1]),
          music_dropouts=[])   # no music stops: they made the bed cut out and restart
json.dump(tl, open('timeline.json','w'), indent=0)
print(len(words), 'words;', len(sfx), 'sfx events')
````

### mix.py

````python
"""python3 mix.py timeline.json -> mix.wav. The actor's audio is copied untouched; music + SFX are added on top.
Each SFX is placed so its loudest point lands on its time (typing: its start)."""
import soundfile as sf, numpy as np, json, sys, subprocess
SR = 48000; tl = json.load(open(sys.argv[1]))
subprocess.run(['ffmpeg','-v','error','-y','-i',tl['actor'],'-vn','-ac','2','-ar','48000','dialogue_orig.wav'],check=True)
v,_ = sf.read('dialogue_orig.wav'); v = v if v.ndim==2 else np.stack([v,v],1); N = len(v)
def load(f):
    y,sr = sf.read(f); y = y if y.ndim==2 else np.stack([y,y],1)
    if sr != SR:
        import scipy.signal as ss; y = ss.resample_poly(y, SR, sr, axis=0)
    return y
sfx = np.zeros_like(v)
for name, t, g in tl['sfx']:
    y = load(f'sfx/{name}.wav')*g
    pk = 0 if name == 'typing' else (len(y) - 1 if name == 'riser' else int(np.argmax(np.abs(y).max(1))))   # riser: its END lands on the time
    i = int(t*SR) - pk; y = y[max(0,-i):]; i = max(0,i); j = min(N, i+len(y)); sfx[i:j] += y[:j-i]
m = load(tl['music'])[:N]; m = np.pad(m, ((0,N-len(m)),(0,0)))
rms = lambda x: np.sqrt(np.mean(x**2))+1e-9
vs = rms(v[int(0.5*SR):int((tl['duration']-0.3)*SR)]); ms = rms(m[int(tl['hook_end']*SR):int((tl['duration']-1)*SR)])
g = vs/ms*10**(-tl.get('music_under_db',16)/20)
# Ducking: while the actor speaks the music drops a further duck_db, smooth 150 ms ramps, 400 ms hold through gaps between words
from scipy.ndimage import uniform_filter1d, maximum_filter1d
DUCK = tl.get('duck_db', 8); w = int(0.05*SR)
vr = np.sqrt(uniform_filter1d((v**2).mean(1), w)); speech = (vr > vs*0.25).astype(float)
speech = maximum_filter1d(speech, int(0.4*SR))
duck = 10**(-DUCK*speech/20); duck = uniform_filter1d(duck, int(0.15*SR))
t = np.arange(N)/SR; env = np.clip((tl['duration']-t)/0.6,0,1)**0.5
for a, b in tl.get('music_dropouts', []):   # short music stops right before the big cuts, so the drop hits harder
    env = env * np.where((t >= a) & (t < b), 0.0, 1.0)
env = np.convolve(env, np.ones(240)/240, 'same')   # 5 ms ramps, no clicks
add = m*g*(env*duck)[:,None] + sfx
mix = v + add; pk = np.max(np.abs(mix)); vp = np.max(np.abs(v))
# Peak guard on the ADDED layers only (never the voice), sample-local: where voice+added would clip, the added layers
# are pulled down just there (fast attack, 80 ms release). Never a global scale: one loud hit must not bury the music.
room = np.clip(0.98 - np.abs(v).max(1), 0.02, None); need = np.abs(add).max(1)
gr = np.minimum(1.0, room / np.maximum(need, 1e-9))
rel = int(0.08*SR); k = np.exp(-np.arange(rel)/(rel/4)); k /= k.sum()
gr = np.minimum(gr, np.convolve(gr, k, 'full')[:N])          # smooth the recovery
for _ in range(2): gr = np.minimum(gr, np.r_[gr[1:], 1.0])    # look-ahead of a few samples
add = add * gr[:, None]; mix = v + add
sf.write('mix.wav', mix.astype(np.float32), SR, subtype='FLOAT')
print(json.dumps({'voice_rms_db':round(20*np.log10(vs),1),'music_gain':round(g,3),'peak':round(float(np.max(np.abs(mix))),3),
                  'voice_untouched':bool(np.allclose(mix-add, v))}))
````

### compose.py

````python
"""Compose the final app-demo UGC ad from: actor clip, hook clip, rendered app demo, actor cutout (alpha), logo, word timings.
Usage: python3 compose.py timeline.json out.mp4
"""
import json, subprocess, sys, numpy as np, cv2
from PIL import Image, ImageDraw, ImageFont, ImageFilter

W, H, FPS = 1080, 1920, 30
cfg = json.load(open(sys.argv[1])); OUT = sys.argv[2]

def reader(path, rgba=False, vcodec=None, cover=True):
    pix = 'rgba' if rgba else 'rgb24'; ch = 4 if rgba else 3
    vf = f"scale={W}:{H}:force_original_aspect_ratio=increase,crop={W}:{H},fps={FPS}" if cover else f"scale={W}:{H},fps={FPS}"
    cmd = ['ffmpeg', '-v', 'error'] + (['-c:v', vcodec] if vcodec else []) + ['-i', path, '-vf', vf, '-f', 'rawvideo', '-pix_fmt', pix, '-']
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=10**8)
    last = [None]
    def nxt():
        b = p.stdout.read(W * H * ch)
        if len(b) == W * H * ch: last[0] = np.frombuffer(b, np.uint8).reshape(H, W, ch)
        return last[0]
    return nxt

actor = reader(cfg['actor'])
hook = reader(cfg['hook'])
demo = reader(cfg['demo'])
cut = reader(cfg['cutout'], rgba=True, vcodec=cfg.get('cutout_codec'))
logo = Image.open(cfg['logo']).convert('RGBA')

dur = cfg['duration']; N = int(round(dur * FPS))
hook_end, demo_start, demo_end, logo_start = cfg['hook_end'], cfg['demo_start'], cfg['demo_end'], cfg['logo_start']
words = cfg['words']  # [[text,start,end],...]

# ---- captions ----
import glob
_f = (glob.glob('/usr/share/fonts/**/Inter-BlackItalic.otf', recursive=True) + glob.glob('/usr/share/fonts/**/DejaVuSans-BoldOblique.ttf', recursive=True))
font = ImageFont.truetype(_f[0], 112)
cache = {}
def word_img(w):
    if w in cache: return cache[w]
    w2 = w.upper()
    bb = font.getbbox(w2, stroke_width=12)
    im = Image.new('RGBA', (bb[2] - bb[0] + 40, bb[3] - bb[1] + 50), (0, 0, 0, 0))
    sh = Image.new('RGBA', im.size, (0, 0, 0, 0))
    ImageDraw.Draw(sh).text((20 - bb[0] + 6, 20 - bb[1] + 10), w2, font=font, fill=(0, 0, 0, 170), stroke_width=12, stroke_fill=(0, 0, 0, 170))
    im = Image.alpha_composite(im, sh.filter(ImageFilter.GaussianBlur(6)))
    ImageDraw.Draw(im).text((20 - bb[0], 20 - bb[1]), w2, font=font, fill=(255, 226, 40, 255), stroke_width=12, stroke_fill=(0, 0, 0, 255))
    cache[w] = im; return im

def current_word(t):
    for i, (w, s, e) in enumerate(words):
        nxt = words[i + 1][1] if i + 1 < len(words) else e + 0.3
        if s <= t < max(e, min(nxt, e + 0.35)): return w, t - s
    return None, 0

# ---- cutout placement ----
S = cfg.get('cut_scale', 0.62); CX = cfg.get('cut_center_x', 790)
sw, shh = int(W * S), int(H * S)
ox = int(CX - sw / 2); oy = H - shh
k_white = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11))
k_dash = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (41, 41))
LIME = (232, 255, 58)

def draw_dashed(img, cnt, phase):
    pts = cnt[:, 0, :].astype(np.float32)
    seg = np.r_[0, np.cumsum(np.linalg.norm(np.diff(pts, axis=0), axis=1))]
    on, off = 34, 22
    for i in range(len(pts) - 1):
        m = (seg[i] + phase) % (on + off)
        if m < on and pts[i][1] < H - 6 and pts[i + 1][1] < H - 6:
            cv2.line(img, tuple(map(int, pts[i])), tuple(map(int, pts[i + 1])), LIME, 10, cv2.LINE_AA)

def composite_cutout(base, rgba, t, dy=0):
    small = cv2.resize(rgba, (sw, shh), interpolation=cv2.INTER_AREA)
    dy = int(max(0, min(shh, dy)))
    if dy: small = small[:shh - dy]
    canvas_a = np.zeros((H, W), np.uint8); canvas_rgb = np.zeros((H, W, 3), np.uint8)
    x0, x1 = max(0, ox), min(W, ox + sw); sx0 = x0 - ox; y0 = oy + dy
    canvas_a[y0:H, x0:x1] = small[:, sx0:sx0 + (x1 - x0), 3]
    canvas_rgb[y0:H, x0:x1] = small[:, sx0:sx0 + (x1 - x0), :3]
    mask = (canvas_a > 127).astype(np.uint8) * 255
    white = cv2.dilate(mask, k_white)
    out = base.copy()
    out[white > 0] = (255, 255, 255)
    a = canvas_a[..., None].astype(np.float32) / 255
    out = (out * (1 - a) + canvas_rgb * a).astype(np.uint8)
    dm = cv2.dilate(mask, k_dash)
    cnts, _ = cv2.findContours(dm, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    if cnts:
        c = max(cnts, key=cv2.contourArea)
        draw_dashed(out, c, t * 60)
    return out

def vblur(img, k):  # vertical motion blur
    k = int(k); return img if k < 2 else cv2.blur(img, (1, k))

def shift(img, dy):
    if abs(dy) < 1: return img
    return cv2.warpAffine(img, np.float32([[1, 0, 0], [0, 1, dy]]), (W, H), borderMode=cv2.BORDER_REPLICATE)

def zoom(img, s, cx=540, cy=760):
    if abs(s - 1) < 1e-3: return img
    M = np.float32([[s, 0, cx - s * cx], [0, s, cy - s * cy]])
    return cv2.warpAffine(img, M, (W, H), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)

eout = lambda x: 1 - (1 - min(1, max(0, x))) ** 3
# jump-cut zooms on the actor: a new zoom level at every sentence start (like a creator's edit)
SENT = sorted(cfg.get('sentence_starts', []))
LEVELS = [1.0, 1.16, 1.07, 1.22]
def actor_zoom(t):
    n = sum(1 for x in SENT if x <= t)
    return LEVELS[n % len(LEVELS)]

ff = subprocess.Popen(['ffmpeg', '-v', 'error', '-y', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-s', f'{W}x{H}', '-r', str(FPS), '-i', '-',
                       '-i', cfg['audio'], '-map', '0:v', '-map', '1:a', '-c:v', 'libx264', '-crf', '17', '-preset', 'medium', '-pix_fmt', 'yuv420p',
                       '-c:a', 'aac', '-b:a', '192k', '-shortest', OUT], stdin=subprocess.PIPE)
import os
SNAP=[float(x) for x in os.environ.get('SNAP','').split(',') if x]
LIMIT=int(os.environ.get('LIMIT','0')) or N
for i in range(LIMIT):
    t = i / FPS
    fa = actor(); fh = hook() if t < hook_end + 0.5 else None
    fd = demo() if demo_start <= t < demo_end else None
    fc = cut()  # always advance so the cutout stays frame-synced with the actor audio
    if t < hook_end:                                   # HOOK; last 0.1 s whips down with motion blur
        frame = fh.copy(); p = (t - (hook_end - 0.1)) / 0.1
        if p > 0: frame = vblur(shift(frame, p * 260), 1 + p * 90)
    elif t < demo_start:                               # ACTOR; enters as a zoom-out from a tight close-up
        p = (t - hook_end) / 0.3
        frame = zoom(fa, 1 + 1.0 * (1 - eout(p))) if p < 1 else zoom(fa, actor_zoom(t))
        if p < 0.5: frame = vblur(frame, (1 - p / 0.5) * 80)
        q = (t - (demo_start - 0.08)) / 0.08             # last 0.08 s whips up
        if q > 0: frame = vblur(shift(frame, -q * 300), 1 + q * 90)
    elif t < demo_end:                                 # DEMO drops in from the top, cut-out slides up from the bottom
        p = (t - demo_start) / 0.18
        if p < 1:
            fd = vblur(shift(fd, -(1 - eout(p)) * 700), (1 - p) * 90)
        frame = composite_cutout(fd, fc, t, dy=(1 - eout((t - demo_start - 0.05) / 0.2)) * 900)
    else:                                              # ACTOR back: zoom-out + vertical motion blur settling
        p = (t - demo_end) / 0.25
        frame = zoom(fa, 1 + 0.3 * (1 - eout(p))) if p < 1 else zoom(fa, actor_zoom(t))
        if p < 1: frame = vblur(frame, (1 - p) * 80)
    img = Image.fromarray(frame).convert('RGBA')
    if t >= logo_start:
        p = min(1, (t - logo_start) / 0.25); sc = 0.6 + 0.4 * (1 - (1 - p) ** 3) + 0.06 * np.sin(np.pi * p)
        lw = int(logo.width * 1.15 * sc); lh = int(logo.height * 1.15 * sc)
        L = logo.resize((lw, lh), Image.LANCZOS)
        if p < 1: L.putalpha(L.getchannel('A').point(lambda v: int(v * p)))
        img.alpha_composite(L, (W // 2 - lw // 2, 150 - (lh - int(logo.height * 1.15)) // 2))
    w, dt = current_word(t)
    if w:
        wi = word_img(w); p = min(1, dt / 0.09); sc = 1.25 - 0.25 * p
        if sc != 1: wi = wi.resize((int(wi.width * sc), int(wi.height * sc)), Image.LANCZOS)
        y = cfg.get('caption_y', 1300)
        img.alpha_composite(wi, (W // 2 - wi.width // 2, y - wi.height // 2))
    arr=np.asarray(img.convert('RGB'))
    if any(abs(t-x)<0.5/FPS for x in SNAP): Image.fromarray(arr).save(f'snap_{t:.2f}.jpg')
    ff.stdin.write(arr.tobytes())
ff.stdin.close(); ff.wait(); print('done', N)
````

### music_fit.py

````python
"""python3 music_fit.py music.wav DEMO_START DEMO_END DURATION -> music_fit.wav
Generated tracks rarely drop exactly where the sections say. This finds the track's main drop (biggest loudness jump)
and rebuilds the bed so the drop hits on DEMO_START, and hits again on DEMO_END (second drop for the CTA).
Splices sit inside the music dropouts that mix.py applies just before those cuts, so they are inaudible."""
import soundfile as sf, numpy as np, sys, json
src, S, E, D = sys.argv[1], *map(float, sys.argv[2:5])
y, sr = sf.read(src); y = y if y.ndim == 2 else np.stack([y, y], 1)
mono = y.mean(1); h = int(sr * 0.05)
env = np.array([np.sqrt(np.mean(mono[i:i + h] ** 2)) for i in range(0, len(mono) - h, h)]) + 1e-9
db = 20 * np.log10(env); w = 20  # 1 s windows
jump = np.array([db[i:i + w].mean() - db[i - w:i].mean() if w <= i < len(db) - w else -99 for i in range(len(db))])
i = int(np.argmax(jump)); lo = max(0, i - 10)
i = lo + int(np.argmax(np.diff(db[lo:i + 10])))+1    # sharpest rise near it = the drop's first hit
drop = i * 0.05
tail_end = len(mono) / sr
for k in range(len(db) - 1, 0, -1):                  # where the loud part stops (generated tracks fade early)
    if db[k] > db.max() - 12: tail_end = k * 0.05; break
def seg(a, b): return y[int(max(0, a) * sr):int(b * sr)]
pre = seg(drop - S, drop)
if len(pre) < int(S * sr): pre = np.vstack([np.zeros((int(S * sr) - len(pre), 2)), pre])
def loud(n):                                         # n seconds from the drop, looping the loud part if needed
    out = seg(drop, min(tail_end, drop + n))
    while len(out) < int(n * sr):
        out = np.vstack([out, seg(drop, min(tail_end, drop + n - len(out) / sr))])
    return out[:int(n * sr)]
body = loud(E - S)                                   # exact length, so the second drop lands exactly on DEMO_END
cta = loud(D - E + 0.5)
r = lambda x: np.sqrt(np.mean(x ** 2)) + 1e-9          # the intro is often much quieter: lift it to 3 dB under the drop
pre = pre * min(4.0, max(1.0, r(body) / r(pre) * 10 ** (-3 / 20)))
out = np.vstack([pre, body, cta])[:int((D + 0.5) * sr)]
sf.write('music_fit.wav', out.astype(np.float32), sr, subtype='FLOAT')
print(json.dumps({'drop_in_track': round(drop, 2), 'loud_until': round(tail_end, 2), 'fit_len': round(len(out) / sr, 2)}))
````
