---
name: longform-studio
description: Create 16:9 horizontal longform animated videos (5–8 minutes) as modular ~1-minute standalone HTML5 <canvas> blocks synced to multi-part Google AI Studio TTS voiceovers, browser Whisper timestamps, and procedural sound effects (sfx.json) for preview & Full HD / 4K (30/60 fps) MP4 export inside longform-studio/index.html.
---

# longform-studio: 16:9 Longform Script, Canvas Blocks & Sound Design

You power the user's browser-based **Longform Studio** (`longform-studio/index.html`), which handles multi-part audio slots (1 file per ~1 min chapter), combined Whisper speech-to-text transcription across all parts, block-by-block HTML pasting & individual preview/export, interactive timeline scrubbing + volume + fullscreen, and final stitched **16:9 Full HD (1920×1080) or 4K UHD (3840×2160) at 30 or 60 fps H.264 + AAC MP4** export.

*(Note: `longform-studio` complements `shorts_studio` for horizontal YouTube videos. Use `agents/example.html` — **"The Absurd 1911 Mona Lisa Heist"** — as your current visual, scene, and character style guide, adapting its rich Canvas 2D craftsmanship into **16:9 horizontal (`1920×1080`)**.)*

---

## 0. Channel Identity & Content

**Channel format:** Horizontal 16:9 animated history / storytelling videos (**5–8 minutes**).

**Core DNA (expanded from the channel bio):**
> *Absurd true stories from the past, animated in full detail. Yes, all of this really happened. 🎬*

**Content pillars — every video must check all three:**
1. **True story from history** — real event, real people, verifiable facts. Never invented.
2. **Absurd or hard-to-believe** — makes the viewer think *"wait, this actually happened?!"*
3. **Rich multi-step narrative** — has enough twists, bizarre characters, failed plans, and escalating absurdity to sustain 5–8 compelling minutes with zero filler.

> [!IMPORTANT]
> **Default behavior when given a topic:** Go directly to the full multi-part script — no questions, no hook options to choose from, no intermediate steps. The user wants the complete script structured in ~1-minute parts ready to paste into Google AI Studio TTS on the first response. Only ask questions if the topic itself is missing or genuinely ambiguous.
>
> **Exception:** If the user explicitly asks for *topic ideas* or *what to make next*, provide a list of 5–8 absurd true story ideas (title + one-line premise each) and wait for them to pick one before writing the script.

---

## 1. Workflow Inside `longform-studio/index.html`

1. **Defaults (unless user explicitly requests otherwise):**
   - **Aspect Ratio & Base Resolution:** **16:9 Horizontal (`1920×1080` logical canvas)**, built with native scaling support (`window.__LONGFORM_RESIZE = true`) so exporting at **3840×2160 (4K)** renders crisp vectors.
   - **Language (DEFAULT: English):** Script, voiceover, on-screen text, and captions in **English**.
   - **Optimal Length (DEFAULT: 5–8 minutes / ~300–480 s):** Split cleanly into **5 to 8 Parts (~55–75 seconds each, ~140–185 words per Part, ~750–1,250 words total)**.
2. **Stage A — Multi-Part Script for Google AI Studio TTS:**
   - Deliver the complete spoken script clearly divided into `Part 1`, `Part 2`, ..., `Part N` (each ~1 minute long so Google AI Studio TTS generates clean, natural pacing without timing drift).
   - Tell the user: generate each Part's audio in **Google AI Studio TTS**, load them into the audio slots in Step 1 of `longform-studio/index.html`, click **Transcriure Tots els Àudios (Whisper AI)** -> **Copiar timestamps.json**, and paste that JSON back here.
3. **Stage B — Block-by-Block Canvas HTML (`block_N.html`) + Sound Cues (`sfx_N.json`):**
   - The combined `timestamps.json` from `longform-studio` provides:
     - `total_duration`, full `text`, and `parts[i]` — where each `parts[i]` already has its exact `duration` (`~60s`) and local `words` (`s`, `e` starting from `0.00` for that block!).
   - Generate **one complete standalone `1920×1080` HTML file per block** (producing **Block 1** first or whichever block the user asks for next, with **15–22+ rich animated visual beats** per ~60s block, `2.5–4.5 s` each), plus its matching `sfx.json` (with timestamps local `0 .. part.duration`).
   - Why one block per step? So every minute gets full cinematic environments, character acting, camera moves, props, and crisp `renderAt(t)` choreography without cutting corners or hitting output limits.
   - Match `DURATION` of Block `k` strictly to `parts[k-1].duration` (do not invent durations—use the exact audio length from the JSON!).
   - Tell the user: click **Enganxar HTML** (and **SFX**) in Block `k` of `longform-studio/index.html` -> test with **Previsualitzar** -> repeat for all blocks -> **Exportar MP4 Complet** (Full HD or 4K, 30 or 60 fps).

---

## 2. Longform Scriptwriting Method (5–8 Minutes, Visual-First)

Viewers click longform history for curiosity and stay because every minute escalates. Every sentence must be written **already picturing what happens on the 16:9 screen**:

1. **The 5 Story Ingredients (Verify Facts First):**
   - **One central premise:** What is the core absurdity in one line? Every chapter must serve it.
   - **The surprise & broken belief:** What sounds completely fake yet actually happened, and what normal people assumed at the time.
   - **Escalating causal chain:** Cause -> ridiculous decision -> unintended consequence -> bigger disaster/absurdity.
   - **Tangible numbers & comparisons:** Convert historical scales into concrete everyday visuals (*"the budget of three warships"*, *"tall as a six-story building"*). Never guess facts.
2. **Part 1 Hook (First 15s, Frame 0 Explosive Opening):**
   - **5 Tests:** (1) Names the real subject immediately; (2) Starts in its most absurd, moving moment; (3) Opens a huge curiosity gap; (4) Clear everyday English; (5) Connects visually on frame 0.
   - **NEVER in the hook:** Dates/years/places as dry opener (*"In 1874, in London..."*); *"according to historians"*; news-anchor tone; *"In this video we will explore..."*.
   - Pick the strongest hook directly—do not ask the user to choose.
3. **Chapter Pacing Across Parts 2..N-1 (~1 Min Each):**
   - End each ~1-minute Part with a natural narrative handoff or escalation (*"...and that's when someone made an even worse suggestion."*) so transitioning from Block `k` to Block `k+1` feels seamless.
   - Place a fresh **"wait, it got worse?!" twist** inside every Part (~every 45–60s) to hold attention across the full 5–8 minutes.
   - Always use the **exact same name** for each person/object across all Parts.
   - **Final Part:** Delivers the full payoff, flips the opening assumption, and circles back to Part 1's opening image.
   - **1 key word per sentence:** Mark 1 standout word per sentence for the blue pill caption highlight.

---

## 3. Engineering an Explosive Opening & Beat Impacts (0.00 – 0.65 s)

- **Fast Physical Entry (`0.02 – 0.55 s`):** Never start a major beat static in center. Bring hero subjects in from off-screen (`easeOut3`) with momentum streaks, smoke, dust, or splash.
- **Aggressive Camera Hook:** Pair openings and major twists with crash-zooms or whip-pans (`scale 1.35 -> 1.0`). Always paint backgrounds across **16:9 overscan bounds (`x: -320..2240`, `y: -220..1300`)** so shakes and pans never reveal empty edges.
- **Impact Lock & Micro-Shake:** Trigger decaying camera shake (`±10–14 px`) synced with `whoosh` / `boom` / `impact_ice` / `pop` in `sfx.json`.
- **Instant Opening Caption (`<= 0.12 s`):** Pop the opening words onto screen immediately so motion, audio, and text hit together.

---

## 4. Visual Style: 16:9 Widescreen Flat Illustrated Cartoon (Mona Lisa 1911 Reference Standard)

Match the clean, cinematic **Flat Illustrated Cartoon** style demonstrated in **`agents/example.html`** (*"The Absurd 1911 Mona Lisa Heist"*): layered gradients, radial sconce/sun glows, diagonal light beams, richly detailed props & interiors, `SCENES` array crossfading via `drawFade`, decaying camera shake (`shakeOffset`), `br: true` / `resalta: true` subtitle pacing, and full-bodied expressive cartoon characters—adapted for **1920×1080 horizontal composition** (`window.__LONGFORM_RESIZE = true`, bottom-center captions at `y = 940`, NEVER `1080×1920` vertical):

- **Widescreen 16:9 Staging & 3-Plane Depth:**
  - **Background (`x: -320..2240, y: -220..1300`):** Rich multi-stop sky/interior gradients, radial sun/lamp halos, diagonal light shafts, distant skylines/mountains/architecture with slow horizontal parallax.
  - **Midground Hero & Dialogue Stage (`y: 120..880`):** Use horizontal staging—left-vs-right confrontations (`x ≈ 520` vs `x ≈ 1400`), split-screen comparisons (`x = 0..960` vs `960..1920`), parchment blueprints, maps, or props scaled generously (`s = 1.15 .. 1.65` for characters). Keep heads/faces comfortably inside `y: 150..760` and feet grounded around `y = 820..900`.
  - **Dark Foreground Silhouettes (`y: 860..1150`):** Faster-parallax dark foreground shapes (rails, desks, spectators, hills, crates, waves) framing the bottom corners while keeping the center-bottom subtitle band clean.
- **Cartoon Characters & Props:** Draw all props with crisp primitives (`roundRect`, `quadraticCurveTo`, `arc`). **Every human character** (protagonists, crowds, guards, politicians) MUST follow the exact **Human Character Anatomical & Technical Standard** below (`drawHumanCharacter`, `drawArticulatedLegs`, `drawArticulatedArm`) with breathing, blinking, and expressive faces.
- **Subtitles & Safe Area (16:9 Estilo Casa — CRITICAL RULES):**
  - **Fixed Cinema Position:** Center subtitles cleanly in the lower 16:9 safe zone `x: 260..1660` (`width: 1400`), `y = 940` (centered at `x = 960`). Keep main action and character faces above `y = 850` so captions never cover faces.
  - **Typography & Colors (Estilo Casa):** Always use `Figtree` (`700`, `64 px` at `1920×1080` scale). Active text cream `#f3ead8`, thick dark outline `#14202b` (`10 px`, `lineJoin: round`), spoken words dimmed to `#8796a3`.
  - **STRICT RULE 1 — Zero sentence mixing:** A subtitle block MUST NEVER contain words from two different sentences. As soon as a sentence ends (`.`, `!`, `?`, `…`), close the block immediately. The next sentence starts in a new block.
  - **STRICT RULE 2 — Max 1 highlighted word per block:** In any single subtitle block there can **never be more than one highlighted word simultaneously**. At most one keyword per block gets the teal-blue pill (`#2a8fb0`) with white text `#ffffff`.
  - **Short punchy bursts (`golpes`):** Group into bursts of max **2 to 5 words** (and max **30 characters**).
  - **Fixed positions + responsive 4K transform:** Word `(x, y)` positions are computed once in `1920×1080` space and `dibujarSubtitulos` applies `ctx.setTransform(cw/1920, 0, 0, ch/1080, 0, 0)` so **4K exports (`3840×2160`) stay razor-sharp**.

### 16:9 Paris-Style Reference Pattern (Canvas 2D)

```js
// Layered 16:9 twilight sky + horizon landmark + overscan ground
function drawBackdrop16x9(camX = 0) {
  const sky = ctx.createLinearGradient(0, -220, 0, 1300);
  sky.addColorStop(0, '#1c1d4f'); sky.addColorStop(0.55, '#b9507a'); sky.addColorStop(1, '#ffd99a');
  ctx.fillStyle = sky; ctx.fillRect(-320, -220, 2560, 1520);
  const sun = ctx.createRadialGradient(1320 - camX * 0.15, 760, 0, 1320 - camX * 0.15, 760, 420);
  sun.addColorStop(0, '#fff3c4'); sun.addColorStop(1, 'rgba(255,176,112,0)');
  ctx.fillStyle = sun; ctx.beginPath(); ctx.arc(1320 - camX * 0.15, 760, 420, 0, Math.PI * 2); ctx.fill();
  ctx.fillStyle = '#1a0d24'; ctx.fillRect(-320, 860, 2560, 440);
}
```

### Human Character Anatomical & Technical Standard (MANDATORY FOR ALL HUMANS)

1. **Golden Rule of Anatomical Integrity:** Every human (protagonists, side characters, guards, background crowds) MUST have a complete, connected 2D rig body:
   - **STRICTLY FORBIDDEN:** Floating busts or waist-cut characters; hiding legs/arms behind edges to skip drawing them; Rayman-style floating hands disconnected from sleeves; circle-only feet without boot/shoe shape.
   - **Required Rig:** 2 articulated legs (`hip -> knee -> ankle`), 2 boot/shoe feet with soles facing the character's direction, 1 trapezoidal torso with rounded shoulders + connected neck, 2 articulated arms (`shoulder -> elbow -> wrist`), 2 hands with elliptical palm + thumb aligned to forearm angle, and 1 round head with ear, crescent face shadow, and expressive face.
2. **Coordinate System & Canonical Proportions:** Local origin `(0, 0)` is always the pelvis/hip center, transformed via `ctx.translate(x, y); ctx.scale(s * facing, s);` (`s = 1.0` ≈ `280 px` tall; `facing`: `1` = right, `-1` = left).
   - **Vertical Height Map (local Y relative to hip `Y = 0`):** Hat/hair crown `Y = -210..-185` | Head center `(0, -152)` (`r = 38`) | Neck `Y = -124..-102` (`w = 24`) | Shoulders `Y = -110` (back `X = +28`, front `X = -32`) | Torso `Y = -110..+18` (or `+75` for long coat/robe) | Hips `Y = +5` (`X = -22, +22`) | Knees `Y = +52` | Ankles `Y = +100` (`legLen = 95`) | Shoe soles / ground `Y = +114`.
3. **Strict Painter's Layer Order (Back-to-Front):**
   - **Layer 1:** Ground contact shadow (dark semi-transparent ellipse at `Y = legLen + 14`).
   - **Layer 2:** Full back arm (`shoulder -> elbow -> wrist -> hand with thumb`).
   - **Layer 3:** Articulated legs (back leg + front leg) with both boots/shoes.
   - **Layer 4:** Torso, coat/clothing, left-side `rgba(0,0,0,0.12)` shading band, lapels/buttons/belt.
   - **Layer 5:** Neck and shirt collar.
   - **Layer 6:** Head base, crescent facial shadow (`rgba(180, 95, 50, 0.22)`), ear, eyes (tracking `lookX, lookY`), eyebrows, nose, mouth/mustache, hat.
   - **Layer 7:** Held object (if any) + Full front arm (`shoulder -> elbow -> wrist -> hand with thumb`) in front of torso.

#### Mandatory Base Human Character Code (USE VERBATIM — DO NOT ALTER)

```js
// --- 1. FUNCION UNIVERSAL PARA BRAZO Y MANO ARTICULADOS ---
function drawArticulatedArm(sx, sy, ex, ey, wx, wy, sleeveCol, skinCol, thickness = 24) {
  ctx.save();
  ctx.lineCap = 'round';
  ctx.lineJoin = 'round';

  // Pasada 1: Contorno exterior oscuro del brazo
  ctx.strokeStyle = '#140e0a';
  ctx.lineWidth = thickness + 10;
  ctx.beginPath();
  ctx.moveTo(sx, sy);
  ctx.lineTo(ex, ey);
  ctx.lineTo(wx, wy);
  ctx.stroke();

  // Pasada 2: Relleno interior de la manga
  ctx.strokeStyle = sleeveCol;
  ctx.lineWidth = thickness;
  ctx.beginPath();
  ctx.moveTo(sx, sy);
  ctx.lineTo(ex, ey);
  ctx.lineTo(wx, wy);
  ctx.stroke();

  // Orientacion del antebrazo para alinear puno y mano
  const angle = Math.atan2(wy - ey, wx - ex);
  ctx.translate(wx, wy);
  ctx.rotate(angle);

  // Puno de la manga en la muneca
  roundRect(-6, -thickness * 0.48, 10, thickness * 0.96, 4);
  ctx.fillStyle = sleeveCol;
  ctx.fill();
  ctx.lineWidth = 4;
  ctx.strokeStyle = '#140e0a';
  ctx.stroke();

  // Palma de la mano
  ctx.beginPath();
  ctx.ellipse(10, 0, 13, 10, 0, 0, Math.PI * 2);
  ctx.fillStyle = skinCol;
  ctx.fill();
  ctx.lineWidth = 4.5;
  ctx.strokeStyle = '#140e0a';
  ctx.stroke();

  // Dedo pulgar
  ctx.beginPath();
  ctx.arc(6, -9, 5.5, 0, Math.PI * 2);
  ctx.fillStyle = skinCol;
  ctx.fill();
  ctx.lineWidth = 4;
  ctx.strokeStyle = '#140e0a';
  ctx.stroke();

  ctx.restore();
}

// --- 2. FUNCION UNIVERSAL PARA PIERNAS Y BOTAS ARTICULADAS ---
function drawArticulatedLegs(walkPhase, pantCol = '#2a3342', shoeCol = '#1d1612', legLen = 95) {
  const stride1 = Math.sin(walkPhase) * 24;
  const stride2 = -stride1;
  const lift1 = Math.max(0, -Math.cos(walkPhase)) * 12;
  const lift2 = Math.max(0, Math.cos(walkPhase)) * 12;

  const legs = [
    { hipX: -22, stride: stride1, lift: lift1 },
    { hipX: 22,  stride: stride2, lift: lift2 }
  ];

  for (let i = 0; i < legs.length; i++) {
    const L = legs[i];
    const kx = L.hipX + L.stride * 0.55 + 4;
    const ky = 5 + legLen * 0.50 - L.lift * 0.4;
    const ax = L.hipX + L.stride;
    const ay = 5 + legLen - L.lift;

    ctx.save();
    ctx.lineCap = 'round';
    ctx.lineJoin = 'round';

    // Pasada 1: Contorno exterior oscuro de la pierna
    ctx.strokeStyle = '#140e0a';
    ctx.lineWidth = 32;
    ctx.beginPath();
    ctx.moveTo(L.hipX, 5);
    ctx.lineTo(kx, ky);
    ctx.lineTo(ax, ay);
    ctx.stroke();

    // Pasada 2: Relleno del pantalon
    ctx.strokeStyle = pantCol;
    ctx.lineWidth = 22;
    ctx.beginPath();
    ctx.moveTo(L.hipX, 5);
    ctx.lineTo(kx, ky);
    ctx.lineTo(ax, ay);
    ctx.stroke();

    // Bota / Zapato anclado al tobillo
    ctx.translate(ax, ay);
    ctx.rotate(L.stride * 0.006);
    ctx.beginPath();
    ctx.moveTo(-14, -4);
    ctx.lineTo(18, -4);
    ctx.quadraticCurveTo(32, -4, 32, 10);
    ctx.lineTo(32, 14);
    ctx.lineTo(-16, 14);
    ctx.closePath();
    ctx.fillStyle = shoeCol;
    ctx.fill();
    ctx.lineWidth = 5;
    ctx.strokeStyle = '#140e0a';
    ctx.stroke();

    // Linea de la suela
    ctx.beginPath();
    ctx.moveTo(-15, 11);
    ctx.lineTo(31, 11);
    ctx.strokeStyle = '#140e0a';
    ctx.lineWidth = 3;
    ctx.stroke();

    ctx.restore();
  }
}

// --- 3. FUNCION UNIVERSAL DE PERSONAJE HUMANO COMPLETO ---
function drawHumanCharacter(x, y, s, opts = {}) {
  const facing = opts.facing || 1;
  const coatCol = opts.coatCol || '#3a526b';
  const pantCol = opts.pantCol || '#253342';
  const skinCol = opts.skinCol || '#f7c49c';
  const hatType = opts.hatType || 'bowler'; // 'bowler' | 'kepi' | 'cap' | 'lady' | 'none'
  const hatCol = opts.hatCol || '#231b14';
  const walkPhase = opts.walkPhase !== undefined ? opts.walkPhase : 0.25;
  const expr = opts.expr || 'normal'; // 'normal' | 'shock' | 'panic' | 'smug'
  const lookX = opts.lookX || 0;
  const lookY = opts.lookY || 0;
  const legLen = opts.legLen || 95;

  ctx.save();
  ctx.translate(x, y);
  ctx.scale(s * facing, s);

  const swing = Math.sin(walkPhase) * 16;

  // Coordenadas por defecto de brazos (personalizables via opts.backArm y opts.frontArm)
  const bArm = opts.backArm || {
    sx: 28, sy: -92,
    ex: 38 - swing * 0.5, ey: -42,
    wx: 48 - swing, wy: 4
  };
  const fArm = opts.frontArm || {
    sx: -32, sy: -92,
    ex: -42 + swing * 0.5, ey: -40,
    wx: -30 + swing, wy: 8
  };

  // CAPA 1: Sombra en el suelo
  ctx.fillStyle = 'rgba(15, 10, 6, 0.24)';
  ctx.beginPath();
  ctx.ellipse(0, legLen + 14, 58, 13, 0, 0, Math.PI * 2);
  ctx.fill();

  // CAPA 2: Brazo trasero
  drawArticulatedArm(bArm.sx, bArm.sy, bArm.ex, bArm.ey, bArm.wx, bArm.wy, coatCol, skinCol, 22);

  // CAPA 3: Piernas y zapatos
  drawArticulatedLegs(walkPhase, pantCol, '#1d1612', legLen);

  // CAPA 4: Torso / Ropa
  ctx.beginPath();
  ctx.moveTo(-48, -110);
  ctx.lineTo(48, -110);
  ctx.quadraticCurveTo(58, -45, 54, 18);
  ctx.lineTo(-54, 18);
  ctx.quadraticCurveTo(-58, -45, -48, -110);
  ctx.closePath();
  ctx.fillStyle = coatCol;
  ctx.fill();

  // Sombra lateral del torso para dar volumen
  ctx.fillStyle = 'rgba(0,0,0,0.12)';
  ctx.beginPath();
  ctx.moveTo(-48, -110);
  ctx.lineTo(-18, -110);
  ctx.lineTo(-22, 18);
  ctx.lineTo(-54, 18);
  ctx.closePath();
  ctx.fill();

  // Contorno del torso
  ctx.lineWidth = 5;
  ctx.strokeStyle = '#140e0a';
  ctx.beginPath();
  ctx.moveTo(-48, -110);
  ctx.lineTo(48, -110);
  ctx.quadraticCurveTo(58, -45, 54, 18);
  ctx.lineTo(-54, 18);
  ctx.quadraticCurveTo(-58, -45, -48, -110);
  ctx.closePath();
  ctx.stroke();

  // CAPA 5: Cuello
  roundRect(-12, -124, 24, 22, 6);
  ctx.fillStyle = skinCol;
  ctx.fill();
  ctx.stroke();

  // CAPA 6: Cabeza y Rostro
  ctx.beginPath();
  ctx.arc(0, -152, 38, 0, Math.PI * 2);
  ctx.fillStyle = skinCol;
  ctx.fill();
  ctx.lineWidth = 5;
  ctx.strokeStyle = '#140e0a';
  ctx.stroke();

  // Sombra facial en media luna
  ctx.fillStyle = 'rgba(180, 95, 50, 0.22)';
  ctx.beginPath();
  ctx.arc(0, -152, 35, Math.PI * 0.55, Math.PI * 1.35);
  ctx.arc(8, -152, 32, Math.PI * 1.35, Math.PI * 0.55, true);
  ctx.closePath();
  ctx.fill();

  // Oreja
  ctx.beginPath();
  ctx.ellipse(-38, -150, 9, 13, 0, 0, Math.PI * 2);
  ctx.fillStyle = skinCol;
  ctx.fill();
  ctx.lineWidth = 5;
  ctx.strokeStyle = '#140e0a';
  ctx.stroke();

  // Ojos
  const eyePositions = [-2, 22];
  for (let i = 0; i < eyePositions.length; i++) {
    const ex = eyePositions[i];
    ctx.beginPath();
    ctx.ellipse(ex, -158, 8, expr === 'shock' || expr === 'panic' ? 12 : 9.5, 0, 0, Math.PI * 2);
    ctx.fillStyle = '#ffffff';
    ctx.fill();
    ctx.lineWidth = 3.5;
    ctx.strokeStyle = '#140e0a';
    ctx.stroke();

    ctx.beginPath();
    ctx.arc(ex + 2 + lookX * 3, -158 + lookY * 3, 4, 0, Math.PI * 2);
    ctx.fillStyle = '#140e0a';
    ctx.fill();

    ctx.beginPath();
    ctx.arc(ex + 3.5 + lookX * 3, -160 + lookY * 3, 1.5, 0, Math.PI * 2);
    ctx.fillStyle = '#ffffff';
    ctx.fill();
  }

  // Cejas
  ctx.strokeStyle = '#231b14';
  ctx.lineWidth = 5.5;
  ctx.lineCap = 'round';
  const browLift = (expr === 'shock' || expr === 'panic') ? -7 : 0;
  ctx.beginPath();
  ctx.moveTo(-11, -172 + browLift);
  ctx.lineTo(5, -174 + browLift);
  ctx.moveTo(14, -174 + browLift);
  ctx.lineTo(31, -171 + browLift);
  ctx.stroke();

  // Nariz
  ctx.beginPath();
  ctx.moveTo(10, -155);
  ctx.quadraticCurveTo(23, -150, 12, -143);
  ctx.strokeStyle = '#140e0a';
  ctx.lineWidth = 4;
  ctx.stroke();

  // Boca
  ctx.beginPath();
  if (expr === 'shock' || expr === 'panic') {
    ctx.ellipse(12, -132, 7, 9, 0, 0, Math.PI * 2);
    ctx.fillStyle = '#7a1c1c';
    ctx.fill();
    ctx.lineWidth = 3.5;
    ctx.strokeStyle = '#140e0a';
    ctx.stroke();
  } else {
    ctx.arc(10, -134, 8, 0.15, Math.PI - 0.3);
    ctx.lineWidth = 3.5;
    ctx.strokeStyle = '#140e0a';
    ctx.stroke();
  }

  // Sombrero (segun hatType)
  if (hatType === 'bowler') {
    ctx.fillStyle = hatCol;
    ctx.beginPath();
    ctx.arc(0, -180, 36, Math.PI, 0);
    ctx.closePath();
    ctx.fill();
    ctx.stroke();
    roundRect(-48, -184, 96, 10, 5);
    ctx.fillStyle = hatCol;
    ctx.fill();
    ctx.stroke();
  } else if (hatType === 'cap') {
    ctx.fillStyle = hatCol;
    ctx.beginPath();
    ctx.moveTo(-36, -176);
    ctx.quadraticCurveTo(-5, -206, 36, -182);
    ctx.lineTo(50, -175);
    ctx.lineTo(-36, -174);
    ctx.closePath();
    ctx.fill();
    ctx.stroke();
  }

  // CAPA 7: Brazo delantero (siempre delante del torso)
  drawArticulatedArm(fArm.sx, fArm.sy, fArm.ex, fArm.ey, fArm.wx, fArm.wy, coatCol, skinCol, 22);

  ctx.restore();
}
```

---

## 5. Technical Rules & 16:9 Native-4K Canvas Skeleton (`block_N.html`)

1. **Auto-Detectable Duration & 4K Native Scaling (REQUIRED):**
   - `<canvas id="c" width="1920" height="1080" data-duration="60"></canvas>`
   - `const DURATION = 60;` (set to the exact `parts[k].duration` of this block!)
   - `window.__SHORT_DURATION = DURATION;`
   - `window.__LONGFORM_RESIZE = true;` (allows `longform-studio/index.html` to scale `<canvas>` to `3840×2160` during 4K export for crisp native vectors).
2. **Pure Deterministic `renderAt(t)`:** Every frame at local block time `t` (`0 .. DURATION`) must depend **only on `t`**. Precompute seeded random arrays once via `rng(seed)`—never call `Math.random()` inside `renderAt(t)`, never use CSS animations, and never rely on external images.
3. **Dynamic-Size Offscreen Crossfade (`bufCanvas`):** Keep `bufCanvas` synced to `(cw, ch)` inside `drawFade` so scene crossfades stay razor-sharp in both 1080p and 4K.
4. **Complete Code Only:** Always output the entire standalone HTML from `<!doctype html>` to `</html>` with zero placeholders (`...`).

```html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=1920, height=1080" />
<title>Block 1</title>
<link href="https://fonts.googleapis.com/css2?family=Figtree:wght@500;700;800&display=block" rel="stylesheet">
<style>
html,body{margin:0;padding:0;width:100%;height:100%;overflow:hidden;background:#050a18;display:flex;align-items:center;justify-content:center}
canvas{display:block;width:100%;height:100%;max-width:100vw;max-height:100vh;object-fit:contain;background:#050a18}
</style>
</head>
<body>
<canvas id="c" width="1920" height="1080" data-duration="60"></canvas>
<script>
(function(){
const DURATION = 60;
window.__SHORT_DURATION = DURATION;
window.__LONGFORM_RESIZE = true;
const canvas = document.getElementById('c');
let ctx = canvas.getContext('2d');
const bufCanvas = document.createElement('canvas');
bufCanvas.width = 1920; bufCanvas.height = 1080;
const bufCtx = bufCanvas.getContext('2d');
if (!CanvasRenderingContext2D.prototype.roundRect) {
  CanvasRenderingContext2D.prototype.roundRect = function(x,y,w,h,r){
    const rr=Math.min(typeof r==='number'?r:(r&&r[0]||0), Math.abs(w)/2, Math.abs(h)/2);
    this.moveTo(x+rr,y); this.arcTo(x+w,y,x+w,y+h,rr); this.arcTo(x+w,y+h,x,y+h,rr);
    this.arcTo(x,y+h,x,y,rr); this.arcTo(x,y,x+w,y,rr); this.closePath();
  };
}
function roundRect(x,y,w,h,r){ctx.beginPath();ctx.roundRect(x,y,w,h,r);}
if (document.fonts && document.fonts.load) {
  document.fonts.load('700 64px "Figtree"').catch(()=>{});
}
function rng(a){return function(){a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296;}}

// --- SUBTITLES ESTILO CASA (16:9 HORIZONTAL) ---
const SUB_CASA = {
  tam: 64,
  font: "700 64px 'Figtree', sans-serif",
  color: "#f3ead8",
  dicho: "#8796a3",
  contorno: "#14202b",
  grosorContorno: 10,
  colorPastilla: "#2a8fb0"
};
const ZONA_SUB = { izquierda: 260, ancho: 1400, y: 940 };
const ADELANTO = 0.06;

function rebota(u) { return 1 + 2.8 * Math.pow(u - 1, 3) + 1.8 * Math.pow(u - 1, 2); }
function rango(t, a, b) { return Math.max(0, Math.min(1, (t - a) / (b - a))); }

// Blocks: ZERO sentence mixing + MAX 1 highlighted word per block
function prepararSubtitulos(words, duracionTotal) {
  const golpes = [];
  let actual = [];
  let letras = 0;
  let tieneResaltada = false;

  for (let i = 0; i < words.length; i++) {
    const item = words[i];
    const dice = (item.w || item.dice || '').trim();
    if (!dice) continue;

    const anteriorCorta = actual.length > 0 && /[.!?…]$/.test(actual[actual.length - 1].dice);
    const limiteCaracteres = (letras + dice.length) > 30;
    const limitePalabras = actual.length >= 5;

    if (anteriorCorta || limitePalabras || limiteCaracteres) {
      if (actual.length) golpes.push({ palabras: actual });
      actual = [];
      letras = 0;
      tieneResaltada = false;
    }

    let resaltaEsta = !!(item.resalta || item.highlight || item.resaltada);
    if (resaltaEsta) {
      if (tieneResaltada) resaltaEsta = false;
      else tieneResaltada = true;
    }

    actual.push({ dice, desde: item.s ?? item.desde, hasta: item.e ?? item.hasta, resalta: resaltaEsta });
    letras += dice.length + 1;
  }
  if (actual.length) golpes.push({ palabras: actual });

  golpes.forEach((g, i) => {
    g.desde = Math.max(0, g.palabras[0].desde - ADELANTO);
    const sig = golpes[i + 1];
    g.hasta = sig ? Math.min(sig.palabras[0].desde - ADELANTO, g.palabras[g.palabras.length - 1].hasta + 0.65) : duracionTotal;
  });
  return golpes;
}

function colocarGolpe(ctx, g) {
  if (g.sitios) return g.sitios;
  ctx.font = SUB_CASA.font;
  const anchos = g.palabras.map(w => ctx.measureText(w.dice).width);
  const hueco = SUB_CASA.tam * 0.28;
  const total = anchos.reduce((acc, w, i) => acc + w + (i ? hueco : 0), 0);
  let x = ZONA_SUB.izquierda + (ZONA_SUB.ancho - total) / 2;
  g.sitios = g.palabras.map((w, i) => {
    const pos = { x, w: anchos[i], y: ZONA_SUB.y };
    x += anchos[i] + hueco;
    return pos;
  });
  return g.sitios;
}

function dibujarSubtitulos(ctx, t, listaGolpes, cw = 1920, ch = 1080) {
  const g = listaGolpes.find(x => t >= x.desde && t < x.hasta);
  if (!g) return;
  const sitios = colocarGolpe(ctx, g);

  ctx.save();
  ctx.setTransform(cw / 1920, 0, 0, ch / 1080, 0, 0);
  ctx.textBaseline = "middle";
  ctx.lineJoin = "round";

  g.palabras.forEach((w, i) => {
    const sale = w.desde - ADELANTO;
    const u = rango(t, sale, sale + 0.14);
    if (u <= 0) return;

    const s = sitios[i];
    const sig = g.palabras[i + 1];
    const dicha = !w.resalta && sig && t >= sig.desde - ADELANTO;
    const k = 0.74 + 0.26 * rebota(u);

    if (w.resalta) {
      const uMarca = rango(t, sale + 0.03, sale + 0.22);
      const kP = 0.7 + 0.3 * rebota(uMarca);
      const pad = SUB_CASA.tam * 0.22, alto = SUB_CASA.tam * 1.1;
      ctx.save();
      ctx.translate(s.x + s.w / 2, s.y);
      ctx.scale(kP, kP);
      ctx.globalAlpha = Math.min(1, uMarca * 2);
      ctx.fillStyle = SUB_CASA.colorPastilla;
      ctx.beginPath();
      ctx.roundRect(-s.w / 2 - pad, -alto / 2, s.w + pad * 2, alto, alto / 2);
      ctx.fill();
      ctx.restore();
    }

    ctx.save();
    ctx.translate(s.x + s.w / 2, s.y + (1 - u) * 14);
    ctx.scale(k, k);
    ctx.globalAlpha = Math.min(1, u * 1.6);
    ctx.font = SUB_CASA.font;

    if (!w.resalta && SUB_CASA.contorno) {
      ctx.strokeStyle = SUB_CASA.contorno;
      ctx.lineWidth = SUB_CASA.grosorContorno;
      ctx.strokeText(w.dice, -s.w / 2, 0);
    }
    ctx.fillStyle = w.resalta ? "#ffffff" : (dicha ? SUB_CASA.dicho : SUB_CASA.color);
    ctx.fillText(w.dice, -s.w / 2, 0);
    ctx.restore();
  });
  ctx.restore();
}

// Example: const listaGolpes = prepararSubtitulos(WORDS_DATA, DURATION);
function renderAt(t){
  t = Math.max(0, Math.min(DURATION, t));
  const cw = canvas.width || 1920, ch = canvas.height || 1080;
  ctx.setTransform(cw / 1920, 0, 0, ch / 1080, 0, 0);
  ctx.clearRect(0, 0, 1920, 1080);
  const drawFade = (fn, alpha) => {
    if (alpha <= 0.001) return;
    if (alpha >= 0.999) { fn(t); return; }
    if (bufCanvas.width !== cw || bufCanvas.height !== ch) {
      bufCanvas.width = cw; bufCanvas.height = ch;
    }
    const mainCtx = ctx; ctx = bufCtx;
    ctx.setTransform(cw / 1920, 0, 0, ch / 1080, 0, 0);
    ctx.clearRect(0, 0, 1920, 1080);
    fn(t);
    ctx = mainCtx;
    ctx.save();
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.globalAlpha = alpha;
    ctx.drawImage(bufCanvas, 0, 0);
    ctx.restore();
  };
  /* Call scene functions via renderScene1(t) / drawFade(renderSceneN, alpha), vignette, flashes */
  dibujarSubtitulos(ctx, t, listaGolpes, cw, ch);
}
window.renderAt = renderAt;
window.addEventListener('hf-seek', e => { window.__hfControlled = true; renderAt(e.detail.time); });
renderAt(0);
let t0 = null;
function tick(now){
  const ts = (typeof now === 'number' && !Number.isNaN(now)) ? now : performance.now();
  if(t0 === null) t0 = ts;
  const elapsed = (ts - t0)/1000;
  const t = elapsed <= DURATION ? elapsed : (elapsed <= DURATION + 0.05 ? DURATION : elapsed % DURATION);
  if(!window.__hfControlled) renderAt(t);
  requestAnimationFrame(tick);
}
requestAnimationFrame(tick);
})();
</script>
</body>
</html>
```

---

## 6. Sound Design (`sfx.json` per Block)

Deliver a matching `sfx.json` alongside each block HTML (with `start` timestamps local `0 .. DURATION`). Built-in procedural `kind` effects synthesized by `longform-studio/index.html`:
- **Motion & Impacts:** `whoosh`, `boom`, `impact_ice`, `pop`, `tick`, `glitch`
- **Atmosphere & Props:** `ocean`, `thunder`, `steam`, `horn`, `bell`, `chime`, `bubbles`

```json
{
  "duration": 60.0,
  "voice_gain": 1.0,
  "sfx_gain": 0.9,
  "events": [
    {"kind": "whoosh", "start": 0.02, "duration": 0.65, "gain": 0.85},
    {"kind": "boom", "start": 0.45, "duration": 1.1, "gain": 0.70}
  ]
}
```

---

## 7. Hybrid Mode: Embedding Real `.mp4` Video Clips (`clip1`, `clip2`...)

`longform-studio/index.html` has a top switch between **Només Animació (Canvas)** and **Amb Clips .mp4 Reals (+ Canvas)**. When the user enables **Amb Clips .mp4 Reals** or provides real video clips (such as a politician's statement, archival footage, news clip, or B-roll):

1. **No Manual Pre-Editing Required by the User:**
   - The user does **not** need to cut/trim the `.mp4` in external editing software or splice anything afterward. They simply drop the `.mp4` into the clip tray (`clip1`, `clip2`...) and give you the clip summary (or tell you which timestamps inside the `.mp4` to play, e.g., *"play `clip1` from second 12 to 18"*).
   - `longform-studio` composites the video frames directly onto the `<canvas>` (fullscreen, rounded TV/monitor frame, newspaper cutout, or split-screen) **and** mixes the clip's audio track directly into the final MP4!
2. **Script Structure When Clips Speak (Voice vs. B-Roll):**
   - **If the clip has original spoken audio** (e.g., a politician talking): end the TTS narration part right before the clip, insert a clear cue in the script (e.g., `[PLAY clip1 0:12–0:18 (6s) — Politician quote]`), and start the next TTS audio block right after the quote—OR keep one narrator audio block before/after. Remember that the block's `DURATION` covers narration + any standalone clip segment!
   - **If the clip is silent B-roll** under narration: omit any audio cue for the clip (or set `gain: 0`) and let the narrator keep talking over it.
3. **Mandatory `drawMediaClip` Canvas Helper (Include in `block_N.html` whenever using clips):**
   - Always obtain the `<video>` frame via `window.__getSyncedClip(clipId, clipTime)` so `longform-studio` keeps both interactive scrubbing/preview AND frame-by-frame 4K/60fps MP4 export 100% locked:

```js
// Composites an uploaded .mp4 clip ('clip1', 'clip2'...) at source time clipTime (seconds)
function drawMediaClip(clipId, clipTime, x, y, w, h, radius = 0, objectFit = 'cover') {
  const v = (typeof window.__getSyncedClip === 'function')
    ? window.__getSyncedClip(clipId, clipTime)
    : (window.__CLIPS && window.__CLIPS[clipId]);
  if (!v || v.readyState < 2 || !v.videoWidth || !v.videoHeight) {
    // Fallback frame if opened standalone outside longform-studio
    ctx.save();
    roundRect(x, y, w, h, radius);
    ctx.fillStyle = '#0e1624'; ctx.fill();
    ctx.lineWidth = 5; ctx.strokeStyle = '#140e0a'; ctx.stroke();
    ctx.restore();
    return;
  }
  ctx.save();
  roundRect(x, y, w, h, radius);
  ctx.clip();
  const vw = v.videoWidth, vh = v.videoHeight;
  const srcRatio = vw / vh, dstRatio = w / h;
  let sx = 0, sy = 0, sw = vw, sh = vh;
  if (objectFit === 'cover') {
    if (srcRatio > dstRatio) { sw = vh * dstRatio; sx = (vw - sw) / 2; }
    else { sh = vw / dstRatio; sy = (vh - sh) / 2; }
  }
  ctx.drawImage(v, sx, sy, sw, sh, x, y, w, h);
  ctx.restore();
  if (radius > 0) {
    ctx.save();
    roundRect(x, y, w, h, radius);
    ctx.lineWidth = 6; ctx.strokeStyle = '#140e0a'; ctx.stroke();
    ctx.restore();
  }
}
```

4. **Clip Audio Cue Inside `sfx.json`:**
   - Whenever the `.mp4` clip's **real audio** should play inside the block, add a `"kind": "clip"` event to that block's `sfx.json`:
   ```json
   {"kind": "clip", "clipId": "clip1", "start": 18.0, "clipStart": 12.0, "duration": 6.0, "gain": 1.0}
   ```
   - `start`: second inside the current HTML block when the clip begins.
   - `clipStart`: second inside the source `.mp4` file where playback starts (`0.0` if starting from the beginning).
   - `duration`: how many seconds of the clip to play.
   - `gain`: clip audio volume multiplier (`1.0` default; ignored by SFX slider, controlled by the dedicated *Volum Clips .mp4* setting).

