---
name: group-chat-ad
description: "A group chat blowing up on your phone: a confession, emoji reactions, a skeptical voice note, video messages showing the result, then \"SEND THE LINK 😭\". Your product is the secret. Just paste your product link."
---

# Text-Message Chat Ad (group chat, iMessage)

Delivers ONE finished 9:16 video ad (≤ 30 s) that plays like a real group chat on the viewer's phone (validated on Smooche, Nov 2026):

| Time | What we see | Audio |
|---|---|---|
| 0 → ~1.6 s | **Lock screen**: 2 group-chat notifications drop in (the hook line + a friend's reaction), a tap opens the chat | notification dings, tap |
| ~1.6 → ~9 s | **Group chat** (4 people, viewer = "me", blue bubbles): mystery/confession hook, a **photo message**, friends react with emojis, typing dots | receive / send pops, music bed |
| ~9 → ~13 s | **Video message 1** plays inside its bubble (actor's own voice): the product + the setup ("ok. watch.") | actor voice, music ducked |
| ~13 → ~17 s | **Voice note** from a skeptical friend (waveform fills as it plays) | TTS voice |
| ~17 → ~21 s | **Video message 2** plays in its bubble: the payoff / visible result | actor voice |
| ~21 → ~24 s | **Drop**: music cuts, riser, impact + screen shake on the hype text ("SEND THE LINK 😭"), then the **reveal text** naming the product, emoji reactions (❤️ 😭 ‼️) | riser, impact, heart pop |
| last ~2.3 s | **End card**: brand, product image, product name, benefit, proof, CTA | reveal sting |

Edit (automatic in `post.py`): slow push on the lock screen, punch-ins on key texts, zoom into each playing video, push onto the result at the end of video 2, shake on the drop, slow push on the reveal.

The chat, voice notes, SFX and end card render with **`arcads_html_to_video`** (Remotion, 5 credits per started 30 s). That tool takes images, not videos, so the video messages show their poster frames there; `post.py` then plays the real clips inside the bubbles (rounded corners, their own voice), mixes the music and does the edit locally with ffmpeg. **The deliverable is `final.mp4`, never the Arcads chat render.**

## Inputs (ask only these, one per message)

1. "What's the product page URL?"
2. "Upload the product image (clean packshot)." — if they say "use the site's", take the main image from the page.

Nothing else. Everything below is decided by Claude. If the user volunteers more (language, offer/discount code, tone, a specific story angle, iMessage vs WhatsApp), use it.

## Rules

- **Exactly one final video.** No drafts, no alternates, no approval steps: the user asked for a one-shot pipeline. State the estimated credits in one line when starting, then run everything.
- **Never regenerate automatically.** If a generation fails, explain and give the retry cost; the user decides.
- **Never analyze, transcribe for review or rate a generated video yourself.** Allowed: audio level / speech-timing measurements needed for the edit, and snapshots of YOUR OWN composite to check layout.
- **Stay in the conversation**: no full-screen cutaways (reaction shots etc.). User feedback Nov 2026: a cut to a reaction video broke the immersion.
- **No phone visible** in any generated selfie video or image (front-camera POV, the filming arm out of frame). If one appears anyway, crop it in post; never regenerate on your own.
- **Voices stay consistent**: the video-message actor speaks only in her video clips (native FLUX audio). Voice notes come from a DIFFERENT friend (TTS), never from the actor.
- **Claims come from the product page only** (benefits, rating, review count). No prices unless the user gives an offer; no medical claims.
- Talk to the user in their language. Chat text in the ad's language (default English, casual lowercase texting style, emojis).

## Step 0: Setup (silent)

1. New folder `chat_<brand>`. Write `template.html`, `build.py`, `measure.js`, `post.py` from the Appendix verbatim.
2. Check: `ffmpeg`, `node -e "require('playwright')"`, `python3 -c "import numpy, PIL"`. Install what is missing (`pip install numpy pillow --break-system-packages`; `npm i -g playwright && npx playwright install chromium`).
3. ToolSearch-load: `arcads_list_brands`, `arcads_create_brand`, `arcads_create_project`, `arcads_upload_media`, `arcads_get_upload_url`, `arcads_register_image`, `arcads_get_asset`, `arcads_generate_image_gpt`, `arcads_generate_video_flux_3_max`, `arcads_text_to_speech`, `arcads_list_voices`, `arcads_create_music`, `arcads_create_sound_effect`, `arcads_html_to_video`.

## Step 1: Product research

`firecrawl_scrape` the URL: brand name, product name, the ONE visible benefit (what changes on screen), how it is used (gesture), rating / review count, target customer. Brand in Arcads: `arcads_list_brands` (create it if missing), then `arcads_create_project` "<Brand> – chat ad". Pass `productId` + `projectId` to every call.
Product image: user upload → `arcads_get_upload_url` + PUT + `arcads_register_image` (or `arcads_upload_media` with the page image URL + `arcads_register_image`). Keep its asset id = `product_img`.

## Step 2: Story (write it, don't ask)

Cast: a group chat of 4 women or men or mixed matching the target customer, e.g. "Girls 💅" (Mia = the one with the secret/product, Chloé = skeptic who sends the voice note, Priya = hype friend, me = viewer). Pick fitting names/group name/emoji for the market.

Pick the angle that fits the product best (default **Confession**):
- **Confession** — "ok I need to confess something about <event> 😬" → "everyone thinks I <got work done / hired a pro / spent a fortune>" (beauty, fitness, home, fashion).
- **Caught** — "who TOOK this photo of you??" / "why do you look like that at 7am" (sleep, skincare, energy).
- **Busted by results** — "how is your <lawn/kitchen/bank account> like that" (home, tools, finance apps).
- **Mom / partner suspects** — for family products.

Message list (≈11 messages, ≤ 30 s total; `build.py` prints the duration):
1. owner: hook text (also lock banner 1)
2. owner: **photo message** = the "evidence" (her result at the event)
3. owner: the suspicion line `fx: punch`
4. skeptic: "WAIT 😳" `fx: shake` (also lock banner 2)
5. hype: "did you???? 👀"
6. me: short push ("MIA. spill.") `fx: punch`
7. owner: **video message a** (product shown + setup line, e.g. "ok. watch.")
8. skeptic: **voice note** (doubt, 2-4 s: "wait… that's it? it's literally <x>.")
9. owner: **video message b** (the visible payoff + benefit line)
10. hype: "SEND THE LINK 😭" `fx: drop`
11. owner: reveal = "<Brand> <product>. that's the whole secret 🤐" `fx: reveal` (gets the ❤️ 😭 ‼️ reactions)

Keep texts short (≤ 9 words). Hook must create a curiosity gap; the product name appears only at the reveal.

## Step 3: Generate assets (all in one turn, in parallel where possible)

Estimated credits: FLUX 3 Max 8 s video ≈ 330 · voice note 8 · music 16 · 7 SFX ≈ 21 · render 5 · images 0 → **≈ 380**.

1. **Actor start frame** — `arcads_generate_image_gpt`, `model gpt-image-2-6-flare`, `aspectRatio 9:16`, `nbGenerations 1`, `referenceImages [product_img]`:
   > Frame from an iPhone front-camera selfie video. A <age> <look> woman, at home in a softly lit <room> at night, <simple top>, real unretouched skin with pores. Seen from her own selfie point of view, about 40 cm from the face, eye level, head and shoulders. Her free hand holds the <product> from the reference image up next to her cheek, label facing the lens and readable. Conspiratorial little smile, eyes on the lens. Slight front-camera noise, no beauty filter, no text, no phone visible.
2. **Photo message** — `arcads_generate_image_gpt`, same actor description, `aspectRatio 3:4`: a candid selfie at the event from the hook (e.g. wedding party, 11pm), showing the RESULT of the product (glowing skin, great hair, etc.), no product in frame, no phone visible.
3. **Video message clip** (after 1 is ready) — `arcads_generate_video_flux_3_max`, `startFrame` = image 1, `duration 8`, `resolution 720p`, `aspectRatio 9:16`, `generateAudio true`, `reasoningLevel low`:
   > Authentic vertical selfie video filmed on an iPhone front camera, one continuous take, no cuts. The woman in the start frame, <room> at night, filmed from her own selfie point of view, slight natural handheld sway. Only her free hand enters the frame; no phone visible.
   > 0-1.5s: she holds the <product> next to her cheek, conspiratorial smile.
   > 1.5-4s: she lowers it and <applies / uses it: one simple gesture>, then looks into the lens and says: "Okay. Watch."
   > 4-8s: <the visible result happens on camera>. She smiles proudly and says: "<benefit in ≤ 6 words>."
   > Speaks English with a natural <accent> accent, playful voice like sharing a secret with her best friend. Says only these lines, word for word. Audio: only her voice recorded by the phone mic, close, light room tone, no music. Realistic skin texture, front-camera softness, no beauty filter, no text on screen.
   The clip is cut in two: `a = 0-4 s`, `b = 4-8 s`.
4. **Voice note** — `arcads_list_voices` (Female/Young/English unless the cast says otherwise; a warm natural voice, NOT the actor) → `arcads_text_to_speech` with the skeptic line.
5. **Music** — `arcads_create_music` elevenlabs, `duration` 32: "Playful upbeat modern pop bed for a social media ad, bouncy plucked synths, light finger snaps, soft punchy kick, warm bass, cheeky fun gossip vibe, 110 BPM, instrumental, stays light under dialogue, lifting slightly in the last third".
6. **SFX** — `arcads_create_sound_effect` (promptInfluence 0.65), one each:
   send 0.6 s "Single smartphone text message send sound, short soft upward airy swoosh, clean digital UI, no music" · receive 0.7 s "Single smartphone incoming text message sound, short bright glassy two-note ding, clean digital UI, no music" · notif 0.8 s "iPhone lock screen notification banner sound: a single soft bright ding chime, clean and short, no music" · heart 0.7 s "Cute soft bubbly pop for a heart reaction appearing on a message, short sparkly UI pop, no music" · reveal 1.2 s "Short bright brand reveal: quick airy swoosh ending in a soft sparkly shimmer, modern ad sting, no melody" · impact 1.2 s "Punchy modern transition impact hit: tight deep sub boom with a sharp snappy transient and a short airy whoosh tail, no music" · riser 1.2 s "Short fast reverse whoosh riser building tension for one second and ending abruptly, no music".

Poll with `arcads_get_asset`; download `clip.mp4`, `music.wav`, the voice note `vn1.wav`.

## Step 4: Posters + story.json

1. Measure the clip's speech (energy every 0.1 s) only to check that line 1 ends before 4.0 s and line 2 ends before 8.0 s; adjust `clip` cut points if needed (keep each part 3.5-4.5 s).
2. Poster frames: `ffmpeg -ss <a_start> … a_pre.jpg`, `<a_end-0.05> a_post.jpg`, `<b_start> b_pre.jpg`, `<b_end-0.05> b_post.jpg` → for each: `arcads_get_upload_url` (image/jpeg) + `curl -X PUT` + `arcads_register_image` → asset ids. (Register them: raw upload paths expire within minutes.)
3. Write `story.json` (schema below, the Smooche example works as is), then `python3 build.py story.json` → must print ≤ 30 s (shorten texts or drop message 5 if not) → `node measure.js` → read `preview.png` to check layout (bubbles, photo, video bubbles, end card) and that it printed `ok` with no WARN.

```json
{"group":"Girls 💅","unread":24,"time":"11:04","date":"Saturday, June 14","react":"❤️ 😭 ‼️",
 "members":{"mia":{"name":"Mia","color":"#E8798F"},"chloe":{"name":"Chloé","color":"#7C8CF0"},"priya":{"name":"Priya","color":"#F2A541"},"me":{"name":"Jess","color":"#1E8BFF"}},
 "lock":[{"who":"mia","text":"ok I need to confess something about Sarah's wedding 😬"},{"who":"chloe","text":"WAIT 😳"}],
 "messages":[
  {"who":"mia","kind":"text","text":"ok I need to confess something about Sarah's wedding 😬"},
  {"who":"mia","kind":"photo","asset":"photo1"},
  {"who":"mia","kind":"text","text":"everyone thinks I got work done","fx":"punch"},
  {"who":"chloe","kind":"text","text":"WAIT 😳","fx":"shake"},
  {"who":"priya","kind":"text","text":"did you???? 👀"},
  {"who":"me","kind":"text","text":"MIA. spill.","fx":"punch"},
  {"who":"mia","kind":"video","clip":"a"},
  {"who":"chloe","kind":"voice","asset":"<tts asset id>","wav":"vn1.wav"},
  {"who":"mia","kind":"video","clip":"b"},
  {"who":"priya","kind":"text","text":"SEND THE LINK 😭","fx":"drop"},
  {"who":"mia","kind":"text","text":"Smooche color changing foundation. that's the whole secret 🤐","fx":"reveal"}],
 "clip":{"a":[0.0,4.0],"b":[4.0,8.0]},
 "assets":{"product_img":"<id>","a_pre":"<id>","a_post":"<id>","b_pre":"<id>","b_post":"<id>","photo1":"<id>"},
 "sfx":{"send":"<id>","receive":"<id>","notif":"<id>","heart":"<id>","reveal":"<id>","impact":"<id>","riser":"<id>"},
 "end":{"brand":"smooche","product":"Color Changing Foundation","benefit":"Adapts to your skin tone","proof":"★★★★★ 50,000+ 5-star reviews","cta":"Shop now"}}
```
`end.proof` only if the page shows it (else ""); `end.cta` can carry the user's offer ("Shop now · 30% off"); optional `end.bg` (CSS background) in the brand colors.

## Step 5: Render the chat (Arcads)

`arcads_html_to_video` with `html` = the full content of `ad.html`, and `images`, `audio`, `durationSeconds` exactly as in `render.json`, `width 1080`, `height 1920`, `productId`, `projectId`, title `<brand>_chat_render`. Poll `arcads_get_asset` (40 s) and download it as `chat.mp4`. If the call fails with INVALID_REFERENCE_IMAGES, an image path expired: register it and retry (not a regeneration).

## Step 6: Post (local) and deliver

`python3 post.py` → `final.mp4` (~30 s to run). Snapshot 6-8 frames of YOUR composite to check layout only (videos inside bubbles, nothing cut off, end card). If a generated clip shows a phone, crop it (don't regenerate).
Copy to outputs as `<brand>_chat_ad.mp4`, send it, and report in 3 lines: story angle, credits actually charged (sum of `creditsCharged`), and that the file is the deliverable (the Arcads project holds the assets and the chat render without the playing videos). Offer variations: another angle (reuses the clip, ~15 credits: new texts + voice note + render), another language, WhatsApp skin.

## Known pitfalls (handled)

- FLUX native voice can be very quiet (whispers): `post.py` level-matches each clip segment with one uniform gain (cap ×8).
- Raw `external-api-temp-uploads/…` paths expire fast: always `arcads_register_image` posters before the render.
- Video bubbles must not move while playing: `build.py` never sends the next message before a video ends; `measure.js` warns if one moves.
- Rare symbols render as NO GLYPH in the renderer: the template only uses emoji and SVG icons.
- HTML to Video bills per started 30 s: keep the ad ≤ 30 s (5 credits).

## Appendix: files (write verbatim)

### template.html

````html
<!DOCTYPE html>
<html><head><meta charset="utf-8">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
<style>
*{box-sizing:border-box;margin:0;padding:0}
html,body{width:1080px;height:1920px;overflow:hidden;background:#000;font-family:Inter,sans-serif;-webkit-font-smoothing:antialiased}
#lock{position:absolute;inset:0;background:radial-gradient(circle at 30% 20%,#f6b7a6 0,rgba(246,183,166,0) 45%),radial-gradient(circle at 80% 70%,#c0587e 0,rgba(192,88,126,0) 50%),linear-gradient(170deg,#e9967f,#a8436b 60%,#4a1f4f);overflow:hidden}
#lclock{position:absolute;left:0;top:250px;width:1080px;text-align:center;color:#fff;font-size:250px;font-weight:600;letter-spacing:-6px}
#ldate{position:absolute;left:0;top:200px;width:1080px;text-align:center;color:rgba(255,255,255,.9);font-size:50px;font-weight:600}
.ban{position:absolute;left:40px;width:1000px;border-radius:50px;background:rgba(245,240,242,.82);padding:34px 40px;display:flex;gap:30px;align-items:flex-start;box-shadow:0 10px 40px rgba(0,0,0,.15)}
.ban .ic{width:100px;height:100px;border-radius:24px;background:linear-gradient(#5df07a,#28c840);flex:none;display:flex;align-items:center;justify-content:center}
.ban .tt{font-size:40px;font-weight:700;color:#111;display:flex;justify-content:space-between}
.ban .tt span{font-weight:400;color:#777;font-size:34px}
.ban .tx{font-size:42px;line-height:54px;color:#111;margin-top:6px}
#tap{position:absolute;width:150px;height:150px;border-radius:50%;background:rgba(255,255,255,.55);opacity:0}
#chat{position:absolute;inset:0;background:#fff;opacity:0;transform-origin:50% 30%}
#status{position:absolute;left:0;top:0;width:1080px;height:96px;display:flex;align-items:center;justify-content:space-between;padding:0 70px;font-size:40px;font-weight:600;color:#000;z-index:5}
#header{position:absolute;left:0;top:0;width:1080px;height:350px;background:rgba(246,246,248,.97);border-bottom:2px solid #e2e2e6;z-index:4}
#avs{position:absolute;left:390px;top:110px;width:300px;height:150px}
.av{position:absolute;width:120px;height:120px;border-radius:50%;border:5px solid #f6f6f8;display:flex;align-items:center;justify-content:center;color:#fff;font-weight:700}
#name{position:absolute;left:0;top:268px;width:1080px;text-align:center;font-size:38px;font-weight:500;color:#111}
#back{position:absolute;left:30px;top:150px;display:flex;align-items:center;gap:8px}
#viewport{position:absolute;left:0;top:350px;width:1080px;height:1390px;overflow:hidden}
#content{position:absolute;left:0;top:0;width:1080px}
.item{position:absolute;opacity:0}
.b{max-width:740px;padding:26px 40px;border-radius:54px;font-size:52px;line-height:64px;font-weight:400;letter-spacing:-0.3px;word-wrap:break-word}
.in{left:130px;transform-origin:0% 100%}
.in .b{background:#E9E9EB;color:#000;border-bottom-left-radius:16px}
.in .nm{font-size:32px;color:#8a8a90;margin:0 0 8px 30px}
.in .pic{position:absolute;left:-104px;bottom:0;width:84px;height:84px;border-radius:50%;display:flex;align-items:center;justify-content:center;color:#fff;font-size:40px;font-weight:700}
.me{right:40px;transform-origin:100% 100%}
.me .b{background:#1E8BFF;color:#fff;border-bottom-right-radius:16px}
#typing{position:absolute;left:130px;opacity:0;transform-origin:0% 100%}
#typing .b{display:flex;gap:16px;padding:34px 40px;border-bottom-left-radius:16px;background:#E9E9EB}
.dot{width:24px;height:24px;border-radius:50%;background:#8E8E93}
#heart{position:absolute;height:96px;padding:0 22px;border-radius:48px;background:#E9E9EB;border:6px solid #fff;display:flex;align-items:center;gap:8px;opacity:0;font-size:46px}
#inputbar{position:absolute;left:0;top:1740px;width:1080px;height:180px;background:#fff;display:flex;align-items:flex-start;padding:26px 36px;gap:24px;z-index:4}
#plus{width:84px;height:84px;border-radius:50%;background:#EDEDF0;display:flex;align-items:center;justify-content:center}
#field{flex:1;height:84px;border-radius:42px;border:2px solid #D8D8DC;display:flex;align-items:center;padding:0 34px;font-size:40px;color:#A2A2A8}
.vid{position:relative;width:504px;height:896px;border-radius:46px;overflow:hidden;background:#222}
.vid img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}
.vid .post{opacity:0}
.vid .pbtn{position:absolute;left:192px;top:388px;width:120px;height:120px;border-radius:50%;background:rgba(0,0,0,.45);display:flex;align-items:center;justify-content:center}
.vid .chip{position:absolute;left:22px;bottom:22px;background:rgba(0,0,0,.45);color:#fff;font-size:32px;font-weight:600;padding:6px 16px;border-radius:20px}
.vn .b{display:flex;align-items:center;gap:26px;padding:30px 40px 30px 30px;width:720px;max-width:none}
.vn .pp{width:92px;height:92px;border-radius:50%;flex:none;display:flex;align-items:center;justify-content:center;background:#8E8E93;fill:#fff}
.vn .play{margin-left:6px}
.vn .wave{flex:1;min-width:0;height:90px;display:flex;align-items:center;gap:4px}
.vn .wave i{display:block;width:8px;border-radius:4px;flex:none;background:#3a3a3c}
.vn .tm{flex:none;white-space:nowrap;font-size:38px;font-weight:500;width:84px;text-align:right;color:#3a3a3c}
#end{position:absolute;inset:0;opacity:0;background:linear-gradient(180deg,#FFF3EF 0%,#FBDCD3 100%);overflow:hidden}
#wm{position:absolute;left:0;top:150px;width:1080px;text-align:center;font-size:120px;font-weight:900;letter-spacing:-5px;color:#1a1a1a}
#prod{position:absolute;left:170px;top:340px;width:740px;height:740px;border-radius:60px;overflow:hidden;box-shadow:0 30px 80px rgba(160,80,60,.25);background:#fff}
#prod img{width:100%;height:100%;object-fit:cover}
#ttl{position:absolute;left:0;top:1150px;width:1080px;text-align:center;font-size:72px;font-weight:800;letter-spacing:-2px;color:#1a1a1a}
#sub{position:absolute;left:0;top:1250px;width:1080px;text-align:center;font-size:50px;font-weight:500;color:#5a3a33}
#rev{position:absolute;left:0;top:1360px;width:1080px;text-align:center;font-size:44px;font-weight:600;color:#1a1a1a}
#rev span{color:#F5A623;letter-spacing:4px}
.photo img{display:block;width:540px;height:720px;object-fit:cover;border-radius:46px}
#end{background:__ENDBG__}
#cta{position:absolute;left:290px;top:1500px;width:500px;height:140px;border-radius:70px;background:#1a1a1a;color:#fff;font-size:56px;font-weight:700;display:flex;align-items:center;justify-content:center}
</style></head><body>
<div id="lock">
 <div id="ldate">__DATE__</div>
 <div id="lclock">__TIME__</div>
 __BANNERS__
 <div id="tap"></div>
</div>
<div id="chat">
 <div id="status"><span>__TIME__</span><span style="display:flex;gap:16px;align-items:center">
  <svg width="54" height="34" viewBox="0 0 18 12"><rect x="0" y="8" width="3" height="4" rx="1"/><rect x="5" y="5.5" width="3" height="6.5" rx="1"/><rect x="10" y="3" width="3" height="9" rx="1"/><rect x="15" y="0" width="3" height="12" rx="1"/></svg>
  <svg width="80" height="38" viewBox="0 0 27 13"><rect x="0.5" y="0.5" width="23" height="12" rx="3.5" fill="none" stroke="#000" opacity=".4"/><rect x="2" y="2" width="17" height="9" rx="2"/><rect x="24.5" y="4.5" width="2" height="4" rx="1" opacity=".4"/></svg></span></div>
 <div id="header">
  <div id="back"><svg width="30" height="52" viewBox="0 0 15 26"><path d="M13 2L2 13l11 11" stroke="#0A7AFF" stroke-width="3.4" fill="none" stroke-linecap="round" stroke-linejoin="round"/></svg><span style="background:#0A7AFF;color:#fff;border-radius:30px;padding:2px 18px;font-size:34px;font-weight:600">__UNREAD__</span></div>
  <div id="avs">__AVATARS__</div>
  <div id="name">__GROUP__ <span style="color:#9a9aa0">›</span></div>
 </div>
 <div id="viewport"><div id="content">
  __ITEMS__
  <div id="typing"><div class="b"><div class="dot"></div><div class="dot"></div><div class="dot"></div></div></div>
  <div id="heart">__REACT__</div>
 </div></div>
 <div id="inputbar"><div id="plus"><svg width="40" height="40" viewBox="0 0 20 20"><path d="M10 3v14M3 10h14" stroke="#7a7a80" stroke-width="2.4" stroke-linecap="round"/></svg></div><div id="field">iMessage</div></div>
</div>
<div id="end">
 <div id="wm">__BRAND__</div>
 <div id="prod"><img src="{{image:0}}"></div>
 <div id="ttl">__PRODUCT__</div>
 <div id="sub">__BENEFIT__</div>
 <div id="rev">__PROOF__</div>
 <div id="cta">__CTA__</div>
</div>
<script>
const TL=__TL__;
const $=id=>document.getElementById(id);
const clamp=(x,a=0,b=1)=>Math.min(b,Math.max(a,x));
const prog=(t,a,b)=>clamp((t-a)/(b-a));
const eout=x=>1-Math.pow(1-x,3);
const eio=x=>x<.5?4*x*x*x:1-Math.pow(-2*x+2,3)/2;
const eback=x=>{const c=1.70158,c3=c+1;return 1+c3*Math.pow(x-1,3)+c*Math.pow(x-1,2)};
const items=TL.msgs.map((m,i)=>$("m"+i));
const VIEW=1360, TOP=30;
const side=w=>w==="me"?"me":"in";
function layoutAt(tau){
  let y=TOP, prev=null, pos=[];
  TL.msgs.forEach((m,i)=>{ if(m.t<=tau){ y+= prev===null?0:(prev===m.who?14:30); pos[i]=y; y+=items[i].offsetHeight; prev=m.who; } });
  let typ=null; TL.typing.forEach(([a,b])=>{ if(tau>=a&&tau<b){ y+= prev===null?0:30; typ=y; y+=$("typing").offsetHeight; } });
  return {pos,typ,bottom:y};
}
const scrollOf=tau=>Math.max(0,layoutAt(tau).bottom-VIEW);
const EV=[...TL.msgs.map(m=>m.t),...TL.typing.map(x=>x[0]),...TL.typing.map(x=>x[1])].sort((a,b)=>a-b);
function render(t){
  t=Number(t);
  // lock screen
  const LK=TL.lock;
  LK.banners.map((a,k)=>["ban"+k,a]).forEach(([id,a])=>{const p=eout(prog(t,a,a+0.35)); $(id).style.opacity=p; $(id).style.transform=`translateY(${(1-p)*-120}px) scale(${0.92+0.08*p})`;});
  const tp=prog(t,LK.tap,LK.tap+0.35); $("tap").style.left="420px"; $("tap").style.top=(LK.tapY)+"px"; $("tap").style.opacity=(t>=LK.tap&&t<LK.tap+0.35)?(1-tp)*0.9:0; $("tap").style.transform=`scale(${0.5+tp})`;
  $("ban0").style.filter=(t>=LK.tap&&t<LK.tap+0.15)?"brightness(.85)":"none";
  const op=eio(prog(t,LK.open,LK.open+0.35));
  $("chat").style.opacity=op; $("chat").style.transform=`scale(${0.55+0.45*op}) translateY(${(1-op)*600}px)`; $("chat").style.borderRadius=(1-op)*60+"px";
  $("lock").style.opacity=1-prog(t,LK.open+0.2,LK.open+0.4);
  // chat
  const L=layoutAt(t);
  let e=null; EV.forEach(x=>{if(x<=t)e=x;});
  let sc=scrollOf(t);
  if(e!==null){const p=eout(prog(t,e,e+0.3)); sc=scrollOf(e-0.001)+(scrollOf(e)-scrollOf(e-0.001))*p;}
  $("content").style.transform=`translateY(${-sc}px)`;
  TL.msgs.forEach((m,i)=>{const el=items[i];
    if(m.t<=t){const p=prog(t,m.t,m.t+0.28); el.style.top=L.pos[i]+"px"; el.style.opacity=clamp(p*3); el.style.transform=`scale(${0.6+0.4*eback(p)})`;}
    else el.style.opacity=0;});
  TL.msgs.forEach((m,i)=>{ if(m.kind!=="video") return; const el=items[i];
    const played=t>=m.play+m.dur, playing=t>=m.play&&!played;
    el.querySelector(".pre").style.opacity=played?0:1; el.querySelector(".post").style.opacity=played?1:0;
    el.querySelector(".pbtn").style.opacity=playing?0:1; el.querySelector(".chip").style.opacity=playing?0:1;
  });
  TL.msgs.forEach((m,i)=>{ if(m.kind!=="voice") return; const el=items[i];
    const pr=clamp((t-m.play)/m.dur); const playing=t>=m.play&&t<m.play+m.dur;
    el.querySelector(".play").style.display=playing?"none":"block"; el.querySelector(".pause").style.display=playing?"block":"none";
    const bs=el.querySelectorAll(".wave i"); bs.forEach((b,k)=>{const on=(k+0.5)/bs.length<=pr; b.style.opacity=on?1:0.38;
      b.style.transform=`scaleY(${playing&&Math.abs((k+0.5)/bs.length-pr)<0.04?1.18:1})`;});
    const secs=t<m.play?m.dur:(playing?t-m.play:m.dur); el.querySelector(".tm").textContent="0:"+String(Math.max(0,Math.floor(secs))).padStart(2,"0");
    el.querySelector(".pp").style.transform=`scale(${Math.abs(t-m.play)<0.15?0.88:1})`;
  });
  const ty=$("typing");
  if(L.typ!==null){ty.style.top=L.typ+"px"; ty.style.opacity=1; let a=0; TL.typing.forEach(([s,b])=>{if(t>=s&&t<b)a=s;});
    ty.style.transform=`scale(${0.6+0.4*eback(prog(t,a,a+0.2))})`;
    ty.querySelectorAll(".dot").forEach((d,k)=>{const ph=((t-a)*2.6-k*0.18)%1; const b=Math.sin(Math.PI*clamp(ph<0?ph+1:ph,0,0.5)*2); d.style.transform=`translateY(${-Math.max(0,b)*12}px)`; d.style.opacity=.55+.45*Math.max(0,b);});
  } else ty.style.opacity=0;
  const h=$("heart"), li=TL.heartOn;
  if(t>=TL.heart){const p=prog(t,TL.heart,TL.heart+0.3); const el=items[li]; const bb=el.querySelector(".b");
    h.style.left=(TL.msgs[li].who==="me"?(1080-40-bb.offsetWidth-30):(130+bb.offsetWidth-h.offsetWidth+10))+"px"; h.style.top=(L.pos[li]+el.offsetHeight-bb.offsetHeight-60)+"px"; h.style.opacity=1; h.style.transform=`scale(${eback(p)})`;}
  else h.style.opacity=0;
  const E=TL.end, pe=prog(t,E,E+0.45);
  if(t>=E){$("chat").style.transform=`translateY(${-eio(pe)*300}px) scale(${1-0.08*eio(pe)})`; $("chat").style.opacity=1-pe;}
  $("end").style.opacity=pe; $("end").style.transform=`scale(${1.06-0.06*eout(pe)})`;
  const pop=(id,a)=>{const p=prog(t,E+a,E+a+0.35); $(id).style.opacity=clamp(p*2); $(id).style.transform=`translateY(${(1-eout(p))*60}px) scale(${0.85+0.15*eback(p)})`;};
  pop("wm",0.15); pop("prod",0.25); pop("ttl",0.5); pop("sub",0.65); pop("rev",0.8);
  const pc=prog(t,E+1.0,E+1.35); const pulse=t>E+1.6?1+0.04*Math.sin((t-E-1.6)*6):1;
  $("cta").style.opacity=clamp(pc*2); $("cta").style.transform=`scale(${(0.7+0.3*eback(pc))*pulse})`;
}
window.render=render;
render(0);
</script></body></html>
````

### build.py

````python
"""python3 build.py story.json -> ad.html, render.json (images + audio for arcads_html_to_video), meta.json (for measure.js / post.py)
story.json: see SKILL.md. Waveforms for voice notes are computed from their local wav files."""
import json, html, sys, subprocess, numpy as np
S=json.load(open(sys.argv[1])); X=S['sfx']; M=S['members']
def wave(path):
    raw=subprocess.run(['ffmpeg','-v','error','-i',path,'-ac','1','-ar','16000','-f','s16le','-'],capture_output=True).stdout
    y=np.frombuffer(raw,np.int16).astype(float)/32768
    ch=np.array_split(y,34); r=np.array([np.sqrt(np.mean(c**2)) for c in ch]); r=(r/(r.max()+1e-9))**0.7
    return round(len(y)/16000,3),[round(float(max(0.12,v)),2) for v in r]
images=[S['assets']['product_img']]; idx={}
def img(key):
    if key not in idx: idx[key]=len(images); images.append(S['assets'][key])
    return idx[key]
CLIP=S['clip']   # {"a":[start,end],"b":[start,end]} seconds in the video-message clip
nb=len(S['lock']); lock=dict(banners=[round(0.15+0.6*k,2) for k in range(nb)]); lock['tap']=round(lock['banners'][-1]+0.5,2); lock['open']=round(lock['tap']+0.15,2); lock['tapY']=1240
audio=[dict(path=X['notif'],startSeconds=b,volume=0.5-0.1*k) for k,b in enumerate(lock['banners'])]+[dict(path=X['send'],startSeconds=lock['tap'],volume=0.4)]
t=lock['open']+0.2; prev=None; msgs=[]; typing=[]; vids=[]; fx=[]
for k,s in enumerate(S['messages']):
    who,kind=s['who'],s['kind']
    if s.get('fx')=='drop': t+=0.25   # a beat of silence before the drop
    if who!='me':
        if prev is not None and prev!=who: ts=t+0.05; te=ts+0.28; typing.append([round(ts,2),round(te,2)]); t=te
        elif prev is not None: t+=0.12
        audio.append(dict(path=X['receive'],startSeconds=round(t,2),volume=0.4))
    else:
        t+=0.12; audio.append(dict(path=X['send'],startSeconds=round(t,2),volume=0.45))
    m=dict(who=who,kind=kind,t=round(t,2),label=(M[who]['name'] if who!='me' and prev!=who else None),fx=s.get('fx'))
    if kind=='text': m['text']=s['text']; hold=max(0.6,0.13*len(s['text'].split())+0.32)
    elif kind=='photo': m['img']=img(s['asset']); hold=1.3
    elif kind=='video':
        a,b=CLIP[s['clip']]; m.update(play=round(t+0.35,2),dur=round(b-a,3),pre=img(s['clip']+'_pre'),post=img(s['clip']+'_post'),clip=s['clip'],src=a)
        vids.append(dict(clip=s['clip'],play=m['play'],src=a,dur=round(b-a,3),k=len(msgs))); hold=0.35+(b-a)+0.05
    elif kind=='voice':
        d,bars=wave(s['wav']); m.update(play=round(t+0.3,2),dur=d,bars=bars); audio.append(dict(path=s['asset'],startSeconds=m['play'],volume=1.0)); hold=0.3+d+0.05
    if s.get('fx')=='drop': audio+= [dict(path=X['riser'],startSeconds=round(m['t']-1.15,2),volume=0.5),dict(path=X['impact'],startSeconds=round(m['t']-0.04,2),volume=0.7)]
    msgs.append(m); t+=hold; prev=who
last=len(msgs)-1; heart=round(t-0.7,2); audio.append(dict(path=X['heart'],startSeconds=heart,volume=0.55))
end=round(t+0.1,2); audio.append(dict(path=X['reveal'],startSeconds=round(end-0.1,2),volume=0.6))
dur=round(end+2.3,2)
TL=dict(lock=lock,msgs=[{k:v for k,v in m.items() if k in('who','kind','t','play','dur')} for m in msgs],typing=typing,heart=heart,end=end,dur=dur,heartOn=last)
def wrap(i,m,inner,extra=''):
    if m['who']=='me': return f'<div class="item me{extra}" id="m{i}">{inner}</div>'
    nxt=msgs[i+1]['who'] if i+1<len(msgs) else None; P=M[m['who']]
    lab=f'<div class="nm">{html.escape(m["label"])}</div>' if m['label'] else ''
    pic=f'<div class="pic" style="background:{P["color"]}">{P["name"][0]}</div>' if nxt!=m['who'] else ''
    return f'<div class="item in{extra}" id="m{i}">{lab}{inner}{pic}</div>'
items=[]
for i,m in enumerate(msgs):
    if m['kind']=='text': items.append(wrap(i,m,f'<div class="b">{html.escape(m["text"])}</div>'))
    elif m['kind']=='photo': items.append(wrap(i,m,f'<img src="{{{{image:{m["img"]}}}}}" style="display:block;width:540px;height:720px;object-fit:cover;border-radius:46px">',' photo'))
    elif m['kind']=='video':
        items.append(wrap(i,m,f'<div class="vid"><img class="pre" src="{{{{image:{m["pre"]}}}}}"><img class="post" src="{{{{image:{m["post"]}}}}}"><div class="pbtn"><svg width="50" height="56" viewBox="0 0 17 19"><path d="M3 1.5l13 8-13 8z" fill="#fff"/></svg></div><div class="chip">0:0{int(round(m["dur"]))}</div></div>'))
    else:
        bars=''.join(f'<i style="height:{max(10,int(b*78))}px"></i>' for b in m['bars'])
        items.append(wrap(i,m,f'<div class="b"><div class="pp"><svg class="play" width="34" height="38" viewBox="0 0 17 19"><path d="M2 1.5l14 8-14 8z"/></svg><svg class="pause" width="34" height="38" viewBox="0 0 17 19"><rect x="2" y="1.5" width="4.5" height="16" rx="1.5"/><rect x="10.5" y="1.5" width="4.5" height="16" rx="1.5"/></svg></div><div class="wave">{bars}</div><div class="tm">0:00</div></div>',' vn'))
icon='<div class="ic"><svg width="62" height="56" 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>'
ban=''.join(f'<div class="ban" id="ban{k}" style="top:{1180+260*k}px">{icon}<div style="flex:1"><div class="tt">{html.escape(S["group"])}<span>now</span></div><div class="tx"><b>{html.escape(M[b["who"]]["name"])}:</b> {html.escape(b["text"])}</div></div></div>' for k,b in enumerate(S['lock']))
others=[w for w in M if w!='me'][:3]
avs=''.join(f'<div class="av" style="left:{90*k}px;top:10px;background:{M[w]["color"]};font-size:52px">{M[w]["name"][0]}</div>' for k,w in enumerate(others))
E=S['end']
rep={'__ITEMS__':'\n  '.join(items),'__TL__':json.dumps(TL,ensure_ascii=False),'__BANNERS__':ban,'__AVATARS__':avs,'__GROUP__':html.escape(S['group']),
     '__UNREAD__':str(S.get('unread',24)),'__DATE__':S.get('date','Saturday, June 14'),'__TIME__':S.get('time','11:04'),'__REACT__':S.get('react','❤️ 😭 ‼️'),
     '__BRAND__':html.escape(E['brand']),'__PRODUCT__':html.escape(E['product']),'__BENEFIT__':html.escape(E['benefit']),
     '__PROOF__':E.get('proof','').replace('★★★★★','<span>★★★★★</span>'),'__CTA__':html.escape(E.get('cta','Shop now')),'__ENDBG__':E.get('bg','linear-gradient(180deg,#FFF3EF 0%,#FBDCD3 100%)')}
h=open(sys.argv[2] if len(sys.argv)>2 else 'template.html').read()
for k,v in rep.items(): h=h.replace(k,v)
open('ad.html','w').write(h)
json.dump(dict(images=images,audio=audio,durationSeconds=dur),open('render.json','w'),ensure_ascii=False)
json.dump(dict(msgs=msgs,vids=vids,dur=dur,end=end,lock=lock,clip_gain=S.get('clip_gain')),open('meta.json','w'),ensure_ascii=False)
print(f'duration {dur}s (keep <= 30)'); print([(m['who'],m['kind'],m['t']) for m in msgs])
````

### measure.js

````js
// node measure.js  -> pos.json (screen rect of each message + video bubbles) and preview.png (contact strip)
const {chromium}=require('playwright');const fs=require('fs');const {execSync}=require('child_process');
const M=JSON.parse(fs.readFileSync('meta.json'));
let h=fs.readFileSync('ad.html','utf8').replace(/\{\{image:\d+\}\}/g,'data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22/%3E');
fs.writeFileSync('_measure.html',h);
(async()=>{const b=await chromium.launch();const p=await b.newPage({viewport:{width:1080,height:1920}});
let err=null;p.on('pageerror',e=>{err=e.message});
await p.goto('file://'+process.cwd()+'/_measure.html');await p.waitForTimeout(1200);
const msgs=[];for(const [i,m] of M.msgs.entries()){await p.evaluate(t=>render(t),m.t+0.4);
 msgs.push(await p.evaluate(i=>{const e=document.querySelector('#m'+i);const x=e.querySelector('.vid')||e.querySelector('.b')||e.querySelector('img')||e;const r=x.getBoundingClientRect();return [Math.round(r.x),Math.round(r.y),Math.round(r.width),Math.round(r.height)]},i));}
const vids=[];for(const v of M.vids){const r=[];for(const tt of [v.play+0.01,v.play+v.dur-0.01]){await p.evaluate(t=>render(t),tt);r.push(await p.evaluate(i=>{const e=document.querySelector('#m'+i+' .vid').getBoundingClientRect();return [Math.round(e.x),Math.round(e.y),Math.round(e.width),Math.round(e.height)]},v.k));}
 if(r[0].join()!==r[1].join()) console.log('WARN video bubble moves during playback',v.clip,r); vids.push({...v,rect:r[0]});}
fs.writeFileSync('pos.json',JSON.stringify({msgs,vids}));
const ts=[0.6,M.lock.open+0.6,...M.msgs.filter((m,i)=>i%2==0).map(m=>m.t+0.5),M.end+1.5];const files=[];
for(const [k,tt] of ts.entries()){await p.evaluate(t=>render(t),tt);const f=`_pv${k}.png`;await p.screenshot({path:f});files.push(f);}
await b.close();
execSync(`ffmpeg -v error -y ${files.map(f=>'-i '+f).join(' ')} -filter_complex "hstack=${files.length},scale=${216*files.length}:-1" preview.png`);
console.log(err?'PAGE ERROR '+err:'ok', JSON.stringify({vids}));})();
````

### post.py

````python
"""python3 post.py  (needs chat.mp4 from arcads_html_to_video, clip.mp4 = the video-message clip, music.wav, meta.json, pos.json)
-> final.mp4 : video messages play inside their bubbles (rounded corners, their own voice), music bed with a drop,
   and an automatic edit: slow push on the lock screen, punch-ins, zoom into each playing video, shake on the drop, push on the reveal."""
import json, subprocess, math, numpy as np
from PIL import Image, ImageDraw
M=json.load(open('meta.json')); P=json.load(open('pos.json')); W,H,FPS=1080,1920,30
# rounded mask for the bubbles
w0,h0=P['vids'][0]['rect'][2],P['vids'][0]['rect'][3]
m=Image.new('L',(w0*4,h0*4),0); ImageDraw.Draw(m).rounded_rectangle((0,0,w0*4-1,h0*4-1),46*4,fill=255); m.resize((w0,h0),Image.LANCZOS).save('_mask.png')
# 1) composite the clip segments into their bubbles
f=[f'[2:v]format=gray,split={len(P["vids"])}'+''.join(f'[m{i}]' for i in range(len(P['vids'])))+';',
   f'[1:v]fps=30,scale={w0}:-2,crop={w0}:{h0},format=rgba,split={len(P["vids"])}'+''.join(f'[c{i}]' for i in range(len(P['vids'])))+';']
last='0:v'
for i,v in enumerate(P['vids']):
    x,y=v['rect'][0],v['rect'][1]
    f.append(f'[c{i}]trim={v["src"]}:{v["src"]+v["dur"]},setpts=PTS-STARTPTS[t{i}];[m{i}]trim=0:{v["dur"]},setpts=PTS-STARTPTS[k{i}];[t{i}][k{i}]alphamerge,setpts=PTS+{v["play"]}/TB[v{i}];')
    f.append(f'[{last}][v{i}]overlay={x}:{y}:enable=\'between(t,{v["play"]},{v["play"]+v["dur"]-0.01:.2f})\':eof_action=pass[o{i}];'); last=f'o{i}'
subprocess.run(['ffmpeg','-v','error','-y','-i','chat.mp4','-i','clip.mp4','-loop','1','-i','_mask.png','-filter_complex',''.join(f).rstrip(';'),'-map',f'[{last}]','-an','-c:v','libx264','-crf','14','-pix_fmt','yuv420p','-r','30','_comp.mp4'],check=True)
# 2) audio: chat render audio + clip voice (level-matched, uniform gain per segment) + music bed with a drop
def rms(a,b):
    raw=subprocess.run(['ffmpeg','-v','error','-ss',str(a),'-to',str(b),'-i','clip.mp4','-ac','1','-ar','16000','-f','s16le','-'],capture_output=True).stdout
    y=np.frombuffer(raw,np.int16).astype(float)/32768; y=y[np.abs(y)>0.003]; return float(np.sqrt(np.mean(y**2))) if len(y) else 0.01
drops=[mm['t'] for mm in M['msgs'] if mm.get('fx')=='drop']
busy='+'.join([f'between(t,{v["play"]},{v["play"]+v["dur"]})' for v in M['vids']]+[f'between(t,{mm["play"]},{mm["play"]+mm["dur"]})' for mm in M['msgs'] if mm['kind']=='voice']) or '0'
vol='0.24'
for d in drops: vol=f'if(between(t,{d-0.6:.2f},{d+0.15:.2f}),0.03,{vol})'
vol=f'if({busy},0.12,{vol})' if False else vol.replace('0.24',f'if({busy},0.12,0.24)')
af=['[0:a]aresample=48000[ca];',f'[1:a]aresample=48000,asplit={len(M["vids"])}'+''.join(f'[a{i}]' for i in range(len(M['vids'])))+';']
for i,v in enumerate(M['vids']):
    g=min(8.0,0.06/max(rms(v['src'],v['src']+v['dur']),1e-4))
    af.append(f'[a{i}]atrim={v["src"]}:{v["src"]+v["dur"]},asetpts=PTS-STARTPTS,volume={g:.2f},adelay={int(v["play"]*1000)}|{int(v["play"]*1000)}[va{i}];')
af.append(f"[3:a]aresample=48000,volume='{vol}':eval=frame,afade=t=out:st={M['dur']-0.8:.2f}:d=0.8[mu];")
af.append('[ca]'+''.join(f'[va{i}]' for i in range(len(M['vids'])))+f'[mu]amix=inputs={len(M["vids"])+2}:normalize=0:duration=first,alimiter=limit=0.95[aout]')
subprocess.run(['ffmpeg','-v','error','-y','-i','chat.mp4','-i','clip.mp4','-i','chat.mp4','-i','music.wav','-filter_complex',''.join(af),'-map','[aout]','-c:a','pcm_s16le','_mix.wav'],check=True)
# 3) camera: keyframes (t, scale, cx, cy, jump)
L=M['lock']; K=[(0,1.0,540,1100,0),(L['open']-0.02,1.05,540,1100,0),(L['open'],1.0,540,960,1)]; SH=[]
cen=lambda r:(r[0]+r[2]/2, r[1]+r[3]/2)
for i,mm in enumerate(M['msgs']):
    r=P['msgs'][i]; cx,cy=cen(r); t=mm['t']
    if mm['kind']=='video':
        v=next(v for v in P['vids'] if v['k']==i); vx,vy=cen(v['rect']); s,e=v['play'],v['play']+v['dur']
        K+= [(s,1.0,540,960,0),(s+0.4,1.3,vx,vy,0)]
        K+= [(e-2.0,1.3,vx,vy,0),(e-0.1,1.55,vx,vy-v['rect'][3]*0.12,0),(e+0.35,1.0,540,960,0)] if mm.get('fx')=='push' or v['clip']=='b' else [(e-0.2,1.3,vx,vy,0),(e+0.25,1.0,540,960,0)]
    elif mm.get('fx') in ('punch','drop'):
        K+= [(t-0.01,1.0,540,960,0),(t+0.13,1.1,cx,cy,0),(t+0.9,1.1,cx,cy,0),(t+1.15,1.0,540,960,0)]
        if mm['fx']=='drop': SH.append((t,0.25,16))
    elif mm.get('fx')=='shake': SH.append((t,0.25,14))
    elif mm.get('fx')=='reveal' or i==len(M['msgs'])-1:
        K+= [(t,1.0,540,960,0),(M['end']-0.05,1.12,cx,cy,0),(M['end'],1.0,540,960,1)]
K=sorted(K)+[(999,1.0,540,960,0)]
eio=lambda x:4*x*x*x if x<.5 else 1-(-2*x+2)**3/2
def cam(t):
    for a,b in zip(K,K[1:]):
        if a[0]<=t<b[0]:
            if b[4]: return a[1],a[2],a[3]
            p=eio((t-a[0])/(b[0]-a[0])); return tuple(a[j]+(b[j]-a[j])*p for j in (1,2,3))
    return 1.0,540,960
dec=subprocess.Popen(['ffmpeg','-v','error','-i','_comp.mp4','-f','rawvideo','-pix_fmt','rgb24','-'],stdout=subprocess.PIPE)
enc=subprocess.Popen(['ffmpeg','-v','error','-y','-f','rawvideo','-pix_fmt','rgb24','-s','1080x1920','-r','30','-i','-','-i','_mix.wav','-map','0:v','-map','1:a','-c:v','libx264','-crf','17','-pix_fmt','yuv420p','-c:a','aac','-b:a','192k','-shortest','final.mp4'],stdin=subprocess.PIPE)
n=0; fs=W*H*3
while True:
    buf=dec.stdout.read(fs)
    if len(buf)<fs: break
    t=n/FPS; s,cx,cy=cam(t); dx=dy=0
    for t0,d,amp in SH:
        if t0<=t<t0+d: k=1-(t-t0)/d; dx+=amp*k*math.sin(t*95); dy+=amp*k*math.cos(t*77)
    if dx or dy: s=max(s,1.03)
    w,h=W/s,H/s; x=min(max(cx-w/2+dx,0),W-w); y=min(max(cy-h/2+dy,0),H-h)
    im=Image.frombuffer('RGB',(W,H),buf)
    if s!=1.0: im=im.resize((W,H),Image.BICUBIC,box=(x,y,x+w,y+h))
    enc.stdin.write(im.tobytes()); n+=1
enc.stdin.close(); enc.wait(); print('final.mp4', n, 'frames')
````
