Art and animation, written as code. Illustrations, loops, interactive web art, launch-videos and scored films in dozens of styles, identical on every render.
TypeScript agent-skillsanimationcanvasclaude-codeclaude-pluginclaude-skillscodex-plugincreative-codecreative-codingcreative-toolsdeterministicgenerative-arthand-drawnillustrationlaunch-videomotion-designmotion-graphicspluginprocedural-generationskill
site art on any page and brand; a delivery master, room tone and shape checks for film sound; phone-safe recordings; a sound scorecard; 0.9.0
Alex Greenshpun21519c70b00f
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex 3c64b66..86e0f4e 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -13,7 +13,7 @@"name": "anidoodle","source": "./","description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 32 styles, with scores composed in code.",- "version": "0.8.0",+ "version": "0.9.0","author": {"name": "Alex Greenshpun","url": "https://linkedin.com/in/alexgreensh"diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 5d8d2bb..e3572bf 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -2,7 +2,7 @@"name": "anidoodle","displayName": "anidoodle","description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 32 styles, with scores composed in code.",- "version": "0.8.0",+ "version": "0.9.0","icon": "./assets/icon.png","author": {"name": "Alex Greenshpun",diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 4012701..150b76d 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "anidoodle",- "version": "0.8.0",+ "version": "0.9.0","description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 32 styles, with scores composed in code.","skills": "./skills/","interface": {diff --git a/.grok-plugin/marketplace.json b/.grok-plugin/marketplace.jsonindex f3b566c..28919da 100644--- a/.grok-plugin/marketplace.json+++ b/.grok-plugin/marketplace.json@@ -10,7 +10,7 @@"name": "anidoodle","source": "./plugins/anidoodle","description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 32 styles, with scores composed in code.",- "version": "0.8.0",+ "version": "0.9.0","author": {"name": "Alex Greenshpun","url": "https://linkedin.com/in/alexgreensh"diff --git a/README.es-ES.md b/README.es-ES.mdindex bdc3d34..cdf454f 100644--- a/README.es-ES.md+++ b/README.es-ES.md@@ -162,7 +162,7 @@ Pregunta cómo dibujar algo, o trae un dibujo, y anidoodle lo reconstruye como l| **Presentaciones y documentos** | Una familia de ilustraciones de sección desde un solo programa. Una nueva semilla da una imagen hermana en el mismo estilo. || **Historias** | Storyboards y animatics que crecen hasta convertirse en una película terminada de cualquier duración, con banda sonora original. || **Tu propia imagen** | Trae un dibujo para aplicar su estilo a otro motivo, o una foto para recrearla en cualquiera de las 32 formas de dibujar, con cada trazo hecho en código. |-| **Páginas web** | Ilustraciones interactivas que siguen el cursor, reaccionan a clics y formularios, o se dibujan al desplazarte por la página. |+| **Páginas web** | Ilustraciones interactivas que siguen el cursor, reaccionan a clics y formularios, o se dibujan al desplazarte por la página. Arte de portada y spots junto a tu titular, en el color y la marca de tu página, en claro u oscuro. || **Aprendizaje** | Lecciones de dibujo con láminas paso a paso y timelapses que enseñan cómo se construye una imagen, qué observar y qué errores evitar. || **Personajes** | Un personaje creado una sola vez que se mantiene idéntico entre planos, poses y estilos. || **Tu lanzamiento** | Un vídeo de lanzamiento para tu producto a partir de una plantilla: tus peticiones, tus imágenes, tus palabras y tus líneas de instalación, montado sobre una banda sonora. |diff --git a/README.fr-FR.md b/README.fr-FR.mdindex 1a729da..1714dfd 100644--- a/README.fr-FR.md+++ b/README.fr-FR.md@@ -162,7 +162,7 @@ Demandez comment dessiner quelque chose, ou apportez un de vos dessins, et anido| **Présentations et documents** | Une famille d'illustrations de section issues d'un seul programme. Une nouvelle graine donne une image sœur dans le même style. || **Récits** | Des storyboards et des animatics qui grandissent jusqu’à devenir un film achevé, de n’importe quelle durée, avec une bande originale. || **Votre propre image** | Apportez un dessin et reprenez son style pour un nouveau sujet, ou apportez une photo et recréez-la dans l’une des 32 manières, chaque trait tracé par le code. |-| **Pages web** | Des illustrations interactives qui suivent le curseur, réagissent aux clics et aux formulaires, ou se dessinent au fil du défilement. |+| **Pages web** | Des illustrations interactives qui suivent le curseur, réagissent aux clics et aux formulaires, ou se dessinent au fil du défilement. Des visuels de une et des spots à côté de votre titre, aux couleurs de votre page et de votre marque, en clair ou en sombre. || **Apprentissage** | Des leçons de dessin en étapes et en accéléré, pour comprendre la construction d’une image, les points à observer et les erreurs courantes. || **Personnages** | Un personnage créé une fois, qui reste identique d’un plan, d’une pose et d’un style à l’autre. || **Votre lancement** | Un film de lancement pour votre produit à partir d'un modèle : vos demandes, vos images, vos mots et vos lignes d'installation, montés sur une musique. |diff --git a/README.ja-JP.md b/README.ja-JP.mdindex 627ad3d..0903a0b 100644--- a/README.ja-JP.md+++ b/README.ja-JP.md@@ -162,7 +162,7 @@ https://github.com/user-attachments/assets/1cf7f75c-b040-4c00-bf0c-cf1885f8b8da| **資料やドキュメント** | ひとつのプログラムから生まれる、章ごとのイラストのファミリー。シード値を変えるだけで、同じスタイルの姉妹画像が手に入る。 || **物語** | 絵コンテやアニマティックから、オリジナルスコア付きの、長さを問わない完成映像へと育っていく。 || **手持ちの画像** | 絵を持ち込めば、そのスタイルで別の題材を描ける。写真を持ち込めば、32のどの画風でも、一筆ずつコードで描き直せる。 |-| **ウェブページ** | カーソルを追い、クリックやフォームに反応し、スクロールに合わせて描き上がるインタラクティブなイラスト。 |+| **ウェブページ** | カーソルを追い、クリックやフォームに反応し、スクロールに合わせて描き上がるインタラクティブなイラスト。見出しの横に置くヒーロー画像やスポットも、ページの色とブランドに合わせて、ライトでもダークでも。 || **学習** | 絵の組み立て方を、注目すべき点やよくある間違いとともに教える作画手順シートとタイムラプス。 || **キャラクター** | 一度作ったキャラクターを、カットやポーズ、スタイルが変わっても同じ姿に保てる。 || **あなたのローンチ** | テンプレートから作るプロダクトのローンチ映像。プロンプト、絵、言葉、インストール行を渡せば、音楽に合わせて編集される。 |diff --git a/README.ko-KR.md b/README.ko-KR.mdindex 7812ed0..d9afcec 100644--- a/README.ko-KR.md+++ b/README.ko-KR.md@@ -162,7 +162,7 @@ https://github.com/user-attachments/assets/1cf7f75c-b040-4c00-bf0c-cf1885f8b8da| **덱과 문서** | 하나의 프로그램에서 나온 한 세트의 섹션 일러스트. 시드값만 바꾸면 같은 스타일의 자매 이미지가 나와요. || **스토리** | 스토리보드와 애니매틱이 오리지널 스코어를 갖춘, 길이에 제한 없는 완성된 영화로 자라나요. || **내 이미지** | 그림을 가져오면 그 스타일로 새로운 소재를 그려요. 사진을 가져오면 32가지 화풍 중 하나로 다시 만들고, 모든 획을 코드로 그려요. |-| **웹페이지** | 커서를 따라 움직이고 클릭과 폼에 반응하며, 페이지를 스크롤하면 스스로 그려지는 인터랙티브 일러스트. |+| **웹페이지** | 커서를 따라 움직이고 클릭과 폼에 반응하며, 페이지를 스크롤하면 스스로 그려지는 인터랙티브 일러스트. 헤드라인 옆에 놓이는 히어로 아트와 스팟도 페이지 색과 브랜드에 맞춰, 라이트든 다크든. || **학습** | 그림이 만들어지는 과정을 알려주는 단계별 시트와 타임랩스. 어디를 살펴봐야 하는지, 흔한 실수는 무엇인지도 배워요. || **캐릭터** | 한 번 만든 캐릭터를 장면과 포즈, 스타일이 달라져도 똑같이 유지해요. || **내 런칭** | 템플릿으로 만드는 제품 런칭 영상이에요. 프롬프트, 그림, 문구, 설치 명령어를 넣으면 음악에 맞춰 편집돼요. |diff --git a/README.md b/README.mdindex 151355d..396a3fc 100644--- a/README.md+++ b/README.md@@ -169,7 +169,7 @@ Ask how to draw something, or bring a drawing, and anidoodle rebuilds it as a le| **Decks and docs** | A family of section illustrations from one program. A new seed gives a sister image in the same style. || **Stories** | Storyboards and animatics that grow into a finished film of any length, with an original score. || **Your own image** | Bring a picture and get its style on a new subject, or bring a photo and get it recreated in any of the 32 hands, every mark drawn in code. |-| **Web pages** | Interactive illustrations that watch the cursor, react to clicks and forms, or draw themselves as the page scrolls. |+| **Web pages** | Interactive illustrations that watch the cursor, react to clicks and forms, or draw themselves as the page scrolls. Hero art and spots that sit beside your headline on your page's own colour and brand, light or dark. || **Learning** | Drawing lessons: step sheets and timelapses that teach how a picture is built, with what to look for and the common mistakes. || **Characters** | One character, built once and kept identical across shots, poses and styles. || **Your launch** | A launch film for your product from a template: your prompts, your pictures, your words and your install lines, cut to a score. |diff --git a/README.zh-CN.md b/README.zh-CN.mdindex 0be25ca..a66e371 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -162,7 +162,7 @@ https://github.com/user-attachments/assets/1cf7f75c-b040-4c00-bf0c-cf1885f8b8da| **幻灯片和文档** | 一个程序生成一整套章节插画。换个种子,就能得到风格相同的姊妹图。 || **故事** | 分镜和动态预览,一步步长成一部任意时长、配有原创配乐的完整影片。 || **你自己的图片** | 带来一张画,就能用它的风格画新主题;带来一张照片,就能用 32 种画风中的任意一种重新创作,每一笔都由代码绘制。 |-| **网页** | 会追随光标、响应点击和表单,或随着页面滚动自行绘制的互动插画。 |+| **网页** | 会追随光标、响应点击和表单,或随着页面滚动自行绘制的互动插画。还有放在标题旁的主视觉和小插图,贴合你页面的底色和品牌,浅色深色都行。 || **学习** | 用分步图和延时视频教你一幅画如何完成,还会指出该看什么、常见错误有哪些。 || **角色** | 一个角色只需构建一次,在不同镜头、姿势和风格中始终保持一致。 || **你的发布** | 用模板为你的产品做一支发布片:你的提示、你的画面、你的文字和安装命令,配着音乐剪好。 |diff --git a/plugins/anidoodle/.claude-plugin/plugin.json b/plugins/anidoodle/.claude-plugin/plugin.jsonindex 5d8d2bb..e3572bf 100644--- a/plugins/anidoodle/.claude-plugin/plugin.json+++ b/plugins/anidoodle/.claude-plugin/plugin.json@@ -2,7 +2,7 @@"name": "anidoodle","displayName": "anidoodle","description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 32 styles, with scores composed in code.",- "version": "0.8.0",+ "version": "0.9.0","icon": "./assets/icon.png","author": {"name": "Alex Greenshpun",diff --git a/plugins/anidoodle/.codex-plugin/plugin.json b/plugins/anidoodle/.codex-plugin/plugin.jsonindex 4012701..150b76d 100644--- a/plugins/anidoodle/.codex-plugin/plugin.json+++ b/plugins/anidoodle/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "anidoodle",- "version": "0.8.0",+ "version": "0.9.0","description": "Code-drawn stills, drawing timelapses, films, explainers and interactive web animations in 32 styles, with scores composed in code.","skills": "./skills/","interface": {diff --git a/plugins/anidoodle/skills/anidoodle/SKILL.md b/plugins/anidoodle/skills/anidoodle/SKILL.mdindex 5b78254..6d84259 100644--- a/plugins/anidoodle/skills/anidoodle/SKILL.md+++ b/plugins/anidoodle/skills/anidoodle/SKILL.md@@ -37,7 +37,7 @@ say why in one line. Write the answers into a short brief before drawing.| A story film, any length | Film workflow below, `references/workflows/long-film.md` || An explainer or infographic; a machine that comes apart to explain an idea, in any style | `references/workflows/explainer.md`, `references/workflows/machines.md` || A launch or product video (their screenshots welcome) | `references/workflows/launch-video.md`; build it on `references/workflows/launch-video-kit.md` |-| An interactive web animation that reacts to the UI | `references/workflows/interactive.md` |+| Art for a site (hero by a headline, tiles, spots, share card) on its page colour and brand; or a web animation that reacts to the UI | `references/workflows/site-art.md`; `references/workflows/interactive.md` || A drawing lesson, or "how do I draw this?" | `references/workflows/teach-drawing.md` || A character kept identical in any style (woodcut to toy brick) | `references/workflows/character-consistency.md`, `references/anatomy.md` || A style matched from their image | `references/workflows/adapt-a-style.md` |diff --git a/plugins/anidoodle/skills/anidoodle/engine/package.json b/plugins/anidoodle/skills/anidoodle/engine/package.jsonindex a201729..b0aba70 100644--- a/plugins/anidoodle/skills/anidoodle/engine/package.json+++ b/plugins/anidoodle/skills/anidoodle/engine/package.json@@ -1,6 +1,6 @@{"name": "anidoodle-engine",- "version": "0.8.0",+ "version": "0.9.0","private": true,"type": "module","description": "Portable art core + backend adapters for illustrations, animations and films drawn entirely in code.",diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/assetKit.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/assetKit.tsnew file mode 100644index 0000000..558979d--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/assetKit.ts@@ -0,0 +1,96 @@+// ASSET KIT. Art that lives on someone's page: a hero beside a headline, a feature tile, a row of spots,+// a social card. Three things change when a picture leaves its own card and sits on a site:+// 1. placement: the art has a region, and the headline has a zone the art must never enter;+// 2. ground: the paper IS the page colour, so every neutral moves to suit it, light or dark;+// 3. brand: one hex becomes a whole material (body) or only its marks (ink), in either theme.+// Placement is plain numbers. Ground and brand are a palette: `setPalette(pagePalette(...))` and every+// material the kit paints is moved through it, so a machine is restyled without touching its parts.+import type { Material } from "./mechanismKit";++export type Rect = { x: number; y: number; w: number; h: number };+export type Placement = { W: number; H: number; art: Rect; safe?: Rect; pad: number; note: string };++/** canvases by where the art sits. Sizes are about 1 unit per CSS pixel at the size the art is shown. */+export const PLACEMENTS: Record<string, Placement> = {+ heroRight: { W: 1200, H: 640, art: { x: 520, y: 40, w: 640, h: 560 }, safe: { x: 0, y: 0, w: 480, h: 640 }, pad: 24, note: "headline left, art right; the moment faces the text" },+ heroLeft: { W: 1200, H: 640, art: { x: 40, y: 40, w: 640, h: 560 }, safe: { x: 720, y: 0, w: 480, h: 640 }, pad: 24, note: "the mirror of heroRight" },+ heroCentre: { W: 1200, H: 720, art: { x: 180, y: 210, w: 840, h: 480 }, safe: { x: 0, y: 0, w: 1200, h: 190 }, pad: 24, note: "headline above, a wide low object below" },+ art: { W: 800, H: 600, art: { x: 0, y: 0, w: 800, h: 600 }, pad: 28, note: "the page lays out its own text" },+ tile: { W: 640, H: 480, art: { x: 0, y: 0, w: 640, h: 480 }, pad: 32, note: "a feature card" },+ spot: { W: 320, H: 320, art: { x: 0, y: 0, w: 320, h: 320 }, pad: 20, note: "one small object; cut detail, never shrink it to mush" },+ banner: { W: 1600, H: 400, art: { x: 0, y: 24, w: 1600, h: 352 }, pad: 24, note: "a section divider; may bleed off a clean straight edge" },+ social: { W: 1200, H: 630, art: { x: 560, y: 40, w: 600, h: 550 }, safe: { x: 0, y: 0, w: 520, h: 630 }, pad: 24, note: "a share card: words left, object right, carries its own ground" },+ slide: { W: 1920, H: 1080, art: { x: 800, y: 80, w: 1060, h: 920 }, safe: { x: 0, y: 0, w: 760, h: 1080 }, pad: 32, note: "a deck slide" },+};+/** the art region shrunk by its pad, as the corner box [x0, y0, x1, y1] `Cam.fit` takes */+export const fitBox = (p: Placement): [number, number, number, number] => [p.art.x + p.pad, p.art.y + p.pad, p.art.x + p.art.w - p.pad, p.art.y + p.art.h - p.pad];+/** where the eye should land: a third of the way into the art region, on the side nearest the text */+export const strongPoint = (p: Placement): [number, number] => {+ const towardText = p.safe ? (p.safe.x + p.safe.w / 2 < p.art.x + p.art.w / 2 ? 1 / 3 : 2 / 3) : 1 / 2;+ return [p.art.x + p.art.w * towardText, p.art.y + p.art.h * (p.safe && p.safe.w === p.W ? 1 / 3 : 0.45)];+};++// ---------------------------------------------------------------- colour in a perceptual space (OKLab)+type Lab = [number, number, number];+const toLin = (c: number) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4);+const toSrgb = (c: number) => (c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055);+const hexRgb = (h: string): [number, number, number] => { const n = parseInt(h.replace("#", "").slice(0, 6), 16); return [(n >> 16) & 255, (n >> 8) & 255, n & 255].map((v) => v / 255) as [number, number, number]; };+export const toLab = (hex: string): Lab => {+ const [r, g, b] = hexRgb(hex).map(toLin);+ const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b), m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b), s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);+ return [0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s, 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s, 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s];+};+const labRgb = ([L, a, b]: Lab): [number, number, number] => {+ const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3, m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3, s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3;+ return [4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s, -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s, -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s].map(toSrgb) as [number, number, number];+};+/** back to hex; a colour outside sRGB keeps its lightness and hue and gives up chroma until it fits */+export const fromLab = (lab: Lab): string => {+ let [L, a, b] = lab; L = Math.max(0, Math.min(1, L));+ for (let k = 0; k < 24; k++) { const rgb = labRgb([L, a, b]); if (rgb.every((v) => v >= -1e-4 && v <= 1 + 1e-4)) break; a *= 0.88; b *= 0.88; }+ return "#" + labRgb([L, a, b]).map((v) => Math.round(Math.max(0, Math.min(1, v)) * 255).toString(16).padStart(2, "0")).join("");+};+export const isDark = (paper: string) => toLab(paper)[0] < 0.6;++// ---------------------------------------------------------------- the page palette+export type Colour = string | { hex: string; mode?: "body" | "ink" };+export type PageOpts = {+ paper: string; // the exact colour of the page the art sits on+ kitPaper?: string; // the paper the materials were designed on (the kit's cream)+ tint?: number; // 0 keeps neutral greys, 1 takes the page's whole colour cast; 0.5 by default+ accent?: Colour; // the brand colour of the part to watch (materials with accent: true)+ colours?: Record<string, Colour>; // per material name: a brand or material colour (brass, walnut, ebony)+};++/** one hex as a five-step material ramp in a theme: hue and chroma kept, lightness set where four tones still read */+export const rampFrom = (hex: string, dark: boolean): { ramp: Material["ramp"]; seam: string; pigment: string } => {+ const [L0, a, b] = toLab(hex), c = dark ? Math.max(0.32, Math.min(0.64, L0 * 0.78)) : Math.max(0.36, Math.min(0.8, L0));+ const at = (L: number) => fromLab([L, a, b]);+ return { ramp: [at(c - 0.17), at(c - 0.09), at(c - 0.02), at(c + 0.06), at(Math.min(0.97, c + 0.15))], seam: at(c - (dark ? -0.12 : 0.26)), pigment: at(c) };+};++/** a palette for `setPalette`: every material moved onto the page, brand colours put in, light or dark */+export const pagePalette = (o: PageOpts): ((m: Material) => Material) => {+ const dark = isDark(o.paper), P = toLab(o.paper), K = toLab(o.kitPaper ?? "#f3f0e8"), tint = o.tint ?? 0.5;+ const da = (P[1] - K[1]) * tint, db = (P[2] - K[2]) * tint;+ // light page: everything moves by the page's difference in lightness and, by `tint`, in colour.+ // dark page: parts sit a little above the page, the lit top lightest, lines lighter than the faces.+ const move = (hex: string, base: number) => {+ const [L, a, b] = toLab(hex);+ if (!dark) return fromLab([L + (P[0] - K[0]), a + da, b + db]);+ return fromLab([P[0] + 0.07 + Math.max(0, L - base) * 0.85, a * 0.85 + da, b * 0.85 + db]);+ };+ const cache = new Map<string, Material>();+ return (m) => {+ const key = (m.name ?? "") + m.ramp.join("") + m.ink; let out = cache.get(key); if (out) return out;+ const base = toLab(m.ramp[0])[0] - 0.02;+ out = { ...m, ramp: m.ramp.map((c) => move(c, base)) as Material["ramp"], seam: dark ? fromLab([P[0] + 0.2, da, db]) : move(m.seam, base), ink: dark ? fromLab([Math.min(0.93, P[0] + 0.62), da, db]) : move(m.ink, base), pigment: m.pigment ? move(m.pigment, base - 0.25) : m.pigment };+ const want = (m.accent ? o.accent : undefined) ?? (m.name ? o.colours?.[m.name] : undefined);+ if (want) {+ const { hex, mode = "body" } = typeof want === "string" ? { hex: want } : want, r = rampFrom(hex, dark);+ // body: the part is made of the colour. ink: the part stays neutral and only its lines and dots take it.+ out = mode === "body" ? { ...out, ramp: r.ramp, seam: r.seam, pigment: r.pigment } : { ...out, ink: r.pigment, seam: r.pigment };+ }+ cache.set(key, out); return out;+ };+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/film.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/film.tsindex 10d8e94..061da9a 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/film.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/film.ts@@ -21,6 +21,8 @@ export type Film = { meta: {locked?: [from: number, to: number, reason: string][];// a declared hold: the stillness is meant (a word read, an end card); the optional reason is printed by the gateholds?: [from: number, to: number, reason?: string][];+ /** silences the film means (a stop-down before a reveal, a held breath), [fromFrame, toFrame, reason]: verify-export does not count them as holes */+ quiet?: [from: number, to: number, reason?: string][];onTwos?: boolean;step?: 1 | 2 | 3;// the score as fitted to this film: its tempo and form; render prints it next to the grid's bpm.@@ -42,7 +44,7 @@ export const validate = (film: Film): string[] => {if (![W, H, fps, durationFrames].every((n) => Number.isSafeInteger(n) && n > 0)) p.push("W, H, fps and durationFrames must be positive integers");if (!Number.isFinite(bpm) || bpm <= 0 || !Number.isInteger(beat)) p.push(`bpm ${bpm} at ${fps} fps does not give a whole-frame beat`);if (film.meta.step !== undefined && ![1, 2, 3].includes(film.meta.step)) p.push("step must be 1, 2 or 3");- for (const [from, to] of [...(film.meta.holds ?? []), ...(film.meta.locked ?? [])]) if (!Number.isSafeInteger(from) || !Number.isSafeInteger(to) || from < 0 || to > durationFrames || to <= from) p.push(`invalid declared range ${from}-${to}`);+ for (const [from, to] of [...(film.meta.holds ?? []), ...(film.meta.locked ?? []), ...(film.meta.quiet ?? [])]) if (!Number.isSafeInteger(from) || !Number.isSafeInteger(to) || from < 0 || to > durationFrames || to <= from) p.push(`invalid declared range ${from}-${to}`);for (const [, , reason] of film.meta.locked ?? []) if (!reason?.trim()) p.push("locked ranges need a reason");let t = 0;[...film.shots].sort((a, b) => a.start - b.start).forEach((s) => {diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchSound.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchSound.tsindex 874886f..f99c3b7 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchSound.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/launchSound.ts@@ -10,6 +10,7 @@// and one impact, at the big reveal only, and nothing at all on its other cuts.import { placeSfx, sfxDuck, sfxAudibility, type SfxCue, type SfxPlan, type SfxAudibility, type PlacedCue } from "./music/sfx";import { limiter } from "./music/render";+import { deliver, layBed, type Delivered } from "./music/delivery";import { loudness, truePeak } from "./music/meter";import type { FilmAudio } from "./film";@@ -25,7 +26,7 @@ const balance = (L: Float32Array, R: Float32Array, p: number) => {for (let i = 0; i < L.length; i++) { const m = (L[i] + R[i]) / 2, s = (L[i] - R[i]) / 2; L[i] = m * gl + s; R[i] = m * gr - s; }};-export type LaunchMix = { L: Float32Array; R: Float32Array; placed: PlacedCue[]; audibility: SfxAudibility[]; raised: { i: number; role: string; db: number }[]; lufs: number; dbtp: number; ok: boolean };+export type LaunchMix = { L: Float32Array; R: Float32Array; placed: PlacedCue[]; audibility: SfxAudibility[]; raised: { i: number; role: string; db: number }[]; lufs: number; dbtp: number; ok: boolean; delivered?: Delivered };/** Score (null = silent) + the film's cues, panned, ducked, every cue heard, one true-peak ceiling (-1 dBTP). */export const mixLaunch = (music: [Float32Array, Float32Array] | null, plan: LaunchPlan, sr = 48000, maxRaise = 8): LaunchMix => {const n = Math.round((plan.frames / plan.fps) * sr), cues = plan.cues.map((c) => ({ ...c })), raised = new Map<number, number>();@@ -45,11 +46,15 @@ export const mixLaunch = (music: [Float32Array, Float32Array] | null, plan: Laun}const L = new Float32Array(n), R = new Float32Array(n);for (let i = 0; i < n; i++) { L[i] = mL[i] + fxL[i]; R[i] = mR[i] + fxR[i]; }- limiter(L, R, sr, Math.pow(10, -1.3 / 20));+ // no score: the cues sit on room tone instead of dropping to silence between them (delivery.ts)+ if (!music && plan.bed !== false && placed.length) layBed(L, R, [fxL, fxR], sr, plan.cues.length * 7919 + plan.frames, plan.bed ?? 22);+ // a launch film is dense: the whole mix to -14 LUFS, then the ceiling (delivery.ts); plan.master overrides+ let delivered: Delivered | undefined;+ if ((plan.master ?? "dense") === "none") limiter(L, R, sr, Math.pow(10, -1.3 / 20)); else delivered = deliver(L, R, sr, plan.master ?? "dense", { ceilingDb: -1.3 });const tp0 = truePeak([L, R]).dbtp; if (tp0 > -1.05) { const g = Math.pow(10, (-1.1 - tp0) / 20); for (let i = 0; i < n; i++) { L[i] *= g; R[i] *= g; } }const fade = Math.min(n, Math.round(0.015 * sr)); for (let i = 0; i < fade; i++) { const g = i / fade; L[n - 1 - i] *= g; R[n - 1 - i] *= g; }const lu = n >= 0.4 * sr ? loudness([L, R], sr).integrated : NaN;- return { L, R, placed, audibility: aud, raised: [...raised].map(([i, db]) => ({ i, role: cues[i].role, db })), lufs: lu, dbtp: truePeak([L, R]).dbtp, ok: aud.every((a) => a.ok) };+ return { L, R, placed, audibility: aud, raised: [...raised].map(([i, db]) => ({ i, role: cues[i].role, db })), lufs: lu, dbtp: truePeak([L, R]).dbtp, ok: aud.every((a) => a.ok), delivered };};/** What a Film's audio(sampleRate) returns; throws when a cue is still buried after raising it. */export const launchAudio = (music: FilmAudio | null, plan: LaunchPlan) => Object.assign((sr: number): [Float32Array, Float32Array] => {diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanism.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanism.tsindex 6293e8c..e89b771 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanism.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanism.ts@@ -28,7 +28,7 @@ import type { Film } from "./film";import { isometricHand } from "./mechanismHands";import {Cam, V3, P2, Material, Item, prism, box, rrect, circle, turned, cyl, sphere, frameAlong, at, facingAt, screw, slab, leverRing, tubeAlong, stroke, fill,- paintAll, sharesAt, ExplodePlan, card, smooth, clamp01, add, setReveal, tone, ink, inkDot, knock, Hand, setHand, flatHand, hand, freshPen,+ paintAll, sharesAt, ExplodePlan, spin, hull, disc as circleOn, card, smooth, clamp01, add, setReveal, tone, ink, inkDot, knock, Hand, setHand, flatHand, hand, freshPen,} from "./mechanismKit";const W = 1080, H = 1080, FPS = 30, N = 310, N_DRAW = 350;@@ -75,7 +75,7 @@ const CUES = [{ t: T.apart / FPS, apart: true }, { t: T.home / FPS, apart: falseconst REV = 9.6; // seconds per drum turn: 0.3 s a step/** drum angle: it turns while the movement is whole and playing */const rotAt = (f: number) => { const run = (a: number, b: number) => Math.max(0, Math.min(f, b) - a); const fr = run(T.play, T.apart) + run(T.home + 30, N); return (fr / FPS / REV) * 2 * Math.PI; };-export type State = { rot: number; shares: Record<string, number>; lit: string; read: string; bend: number[]; fan: number; crank: number };+export type State = { rot: number; shares: Record<string, number>; lit: string; read: string; bend: number[]; fan: number; crank: number; blur?: number };/** what the drum is doing at angle rot: how far each tooth bends, and which pin last spoke. One model for pins, teeth and words. */export const play = (rot: number, quiet = 0) => {const bend = TEETH.map(() => 0), turn = rot % (2 * Math.PI); let last = -1;@@ -106,6 +106,7 @@ export const stateAt = (f: number): State => {};// ---------------------------------------------------------------- the parts list+const circleAt = (c: Cam, o: V3, r: number, off: P2) => circleOn(c, o, [0, 0, 1], r, 40, off);const vane = (psi: number, side: number): P2[] => { const c = Math.cos(psi), s = Math.sin(psi), e = 0.22; const pts: [number, number][] = side > 0 ? [[0.5, -e], [4.6, -e], [4.6, e], [0.5, e]] : [[-4.6, -e], [-0.5, -e], [-0.5, e], [-4.6, e]]; return pts.map(([x, y]) => [60 + x * c - y * s, 12 + x * s + y * c] as P2); };const bar = (ctx: Ctx, c: Cam, x0: number, x1: number, yR: number, yT: number, z0: number, z1: number, dz: number, m: Material, off: P2) => {const P = (x: number, y: number, z: number): P2 => { const s = c.p([x, y, z + (y < yR ? dz * ((yR - y) / (yR - yT)) ** 1.6 : 0)]); return [s[0] + off[0], s[1] + off[1]]; };@@ -195,7 +196,10 @@ const parts = (c: Cam, s: State): Item[] => {const F = frameAlong([60, 12, 19.4], [0, 0, 1]); turned(ctx, c, F, cyl(0, 4, 1.5), M("governor", STEEL), { off: o, lit: lit("governor") });const KS = Math.round(20 / (hand().coarse ?? 1)); for (let i = 0; i < 9; i++) { const z0 = 0.3 + i * 0.42; for (let k = 0; k < KS; k++) { const th0 = (k / KS) * 2 * Math.PI + s.fan * 0.15, th1 = th0 + (2 * Math.PI) / KS, f = facingAt(c, F, (th0 + th1) / 2); if (f < 0.05) continue; const A = c.p(at(F, z0 + (k / KS) * 0.42, 1.5, th0)), B = c.p(at(F, z0 + ((k + 1) / KS) * 0.42, 1.5, th1)); ink(ctx, [[A[0] + o[0], A[1] + o[1]], [B[0] + o[0], B[1] + o[1]]], "seam", STEEL, false, smooth(0.05, 0.5, f)); } }}, "governor");- [1, -1].forEach((side) => { const ring = vane(s.fan, side), mid = ring.reduce((a, q) => [a[0] + q[0] / 4, a[1] + q[1] / 4], [0, 0]); put(`vane${side}`, [mid[0], mid[1], 26.5], (ctx, o) => prism(ctx, c, ring, 24.6, 4.2, M("governor", ZINC), { off: o, lit: lit("governor") }), "governor", 0); });+ // the fan turns nine times a drum turn; with `blur` (radians of trail) it reads as spinning, not as a still cut-out+ const sweep = (s.blur ?? 0), disc = (ctx: Ctx, o: P2) => () => tone(ctx, hull([...circleAt(c, [60, 12, 24.6], 4.6, o), ...circleAt(c, [60, 12, 28.8], 4.6, o)]), M("governor", ZINC), 4); // one shape: see-through bands would stack into stripes+ [1, -1].forEach((side) => { const ring = vane(s.fan, side), mid = ring.reduce((a, q) => [a[0] + q[0] / 4, a[1] + q[1] / 4], [0, 0]); put(`vane${side}`, [mid[0], mid[1], 26.5], (ctx, o) => spin(s.fan, sweep, (ang) => prism(ctx, c, vane(ang, side), 24.6, 4.2, M("governor", ZINC), { off: o, lit: lit("governor") }), { disc: side > 0 ? disc(ctx, o) : undefined }), "governor", 0); });+ /** the music box at rest on a page, playing: every part home, the drum turning, the fan a blur */put("hub", [60, 12, 26.7], (ctx, o) => turned(ctx, c, frameAlong([60, 12, 24.4], [0, 0, 1]), cyl(0, 4.6, 0.95), M("governor", STEEL), { off: o }), "governor", 0.05);put("gcap", [60, 12, 30.6], (ctx, o) => turned(ctx, c, frameAlong([60, 12, 30.2], [0, 0, 1]), cyl(0, 0.8, 1.3), STEEL, { off: o }), "governor", 2);// travel lines: a chain line from where a part sits to where it went, drawn under everything that moved@@ -260,6 +264,16 @@ export const paintFigure = (ctx: Ctx, s: State, hint: string, o: { cam?: Cam; bureturn CAM;};export const camApart = APART;+/** the box at home, playing at drum angle `rot`, the fan's trail `blur` radians long (site art and loops) */+/** the pins that have just plucked their teeth at drum angle `rot`: which tooth, where its tip is, how long ago (s) */+export const plucks = (rot: number, within = 1.2) => PINS.flatMap((p) => {+ const since = (((rot - p.step * DSTEP) % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI), age = (since / (2 * Math.PI)) * REV;+ return age < within ? [{ tooth: p.tooth, age, tip: [toothX(p.tooth) + 0.67, TIP, 8.4] as V3 }] : [];+});+// the key turns back once a drum turn as the spring runs down, so a loop shows the whole motor working+export const playing = (rot: number, blur = 0): State => { const pl = play(rot); return { rot, shares: Object.fromEntries(PLAN.order.map((id) => [id, 0])), lit: "drum", read: pl.read, bend: pl.bend, fan: pl.fan, crank: Math.PI * 0.3 - rot, blur }; };+/** every corner of the box at home, for fitting a camera to a region */+export const homePoints: V3[] = [...BENCH, [60, 12, 31], [74, 22, 18], [10, 11, 24]];/** the run: it plays (the camera close on the pins), comes apart, tours its parts, folds home, plays on */export const drawMechanism = (ctx: Ctx, f: number, env: Env) => {ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanismHands.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanismHands.tsindex 25f1667..9b15754 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanismHands.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanismHands.ts@@ -14,6 +14,7 @@ import type { Ctx, Env, Layer, P } from "./core";import { Gfx, rng, PENCIL, GRAPHITE } from "./core";import { kit, sheet, border, WHITE, CYAN, DIM, DRAFT } from "./blueprintKit";import { letter } from "./drafting";+import { isDark } from "./assetKit";import { type Hand, type Material, type P2, type Role, offset, path, rawStroke, flatHand, reveal } from "./mechanismKit";const hash = (...v: number[]) => { let h = 2166136261; for (const x of v) { h ^= Math.round(x * 8) | 0; h = Math.imul(h, 16777619); } return h >>> 0; };@@ -169,7 +170,9 @@ export const stippleHand = (ctx0: Ctx, env: Env, frame: number): Hand => {const mixHex = (a: string, b: string, t: number) => { const pa = [1, 3, 5].map((i) => parseInt(a.slice(i, i + 2), 16)), pb = [1, 3, 5].map((i) => parseInt(b.slice(i, i + 2), 16)); return "#" + pa.map((v, i) => Math.round(v + (pb[i] - v) * t).toString(16).padStart(2, "0")).join(""); };export const isometricHand = (paper = "#efe8dc", ink = "#2b2a33"): Hand => {const tones = new Map<string, [string, string, string]>();- const three = (m: Material) => { const k = m.pigment ?? "#9a9a9a"; let t = tones.get(k); if (!t) { t = [mixHex(k, "#1d1a2a", 0.3), k, mixHex(k, "#ffffff", 0.5)]; tones.set(k, t); } return t; };+ // on a dark page a top lifted halfway to white glares, so the lit top steps up less and the far face sinks more+ const dark = isDark(paper), up = dark ? 0.26 : 0.5, down = dark ? 0.38 : 0.3;+ const three = (m: Material) => { const k = m.pigment ?? "#9a9a9a"; let t = tones.get(k); if (!t) { t = [mixHex(k, "#1d1a2a", down), k, mixHex(k, "#ffffff", up)]; tones.set(k, t); } return t; };const flat = (ctx: Ctx, pts: P2[], col: string, a = 1) => { ctx.globalAlpha = a; ctx.fillStyle = col; path(ctx, pts); ctx.fill(); ctx.strokeStyle = col; ctx.lineWidth = 0.5; ctx.lineJoin = "round"; ctx.stroke(); ctx.globalAlpha = 1; };const base = flatHand(paper, "#7a7280", "#b9b0a3");return {@@ -184,7 +187,7 @@ export const isometricHand = (paper = "#efe8dc", ink = "#2b2a33"): Hand => {else if (role === "chain") { ctx.save(); ctx.setLineDash([6, 4]); rawStroke(ctx, pts, ink, 0.8, false, 0.35 * a, prog); ctx.restore(); }},dot: (ctx, at, r, m, a) => { ctx.globalAlpha = a; ctx.fillStyle = three(m)[0]; ctx.beginPath(); ctx.arc(at[0], at[1], r, 0, Math.PI * 2); ctx.fill(); ctx.globalAlpha = 1; },- shadow: (ctx, pts, s) => flat(ctx, pts.map(([x, y]) => [x + 6, y + 9] as P2), "#3a3346", 0.13 * s),+ shadow: (ctx, pts, s) => flat(ctx, pts.map(([x, y]) => [x + 6, y + 9] as P2), dark ? "#000000" : "#3a3346", (dark ? 0.32 : 0.13) * s),};};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanismKit.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanismKit.tsindex 4c4c9ee..4dd3c75 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanismKit.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/mechanismKit.ts@@ -140,10 +140,28 @@ let OFFSET: P2 = [0, 0];/** the screen offset of the part being painted: hands anchor their patterns to it, so marks travel with their part */export const offset = (): P2 => OFFSET;export const setHand = (h: Hand) => { HAND = h; };+// a palette moves every material before the hand sees it: the page colour, the brand, light or dark (assetKit.ts)+let PALETTE: ((m: Material) => Material) | null = null;+export const setPalette = (f: ((m: Material) => Material) | null) => { PALETTE = f; };+const pal = (m: Material) => (PALETTE ? PALETTE(m) : m);+// a ghost is a part drawn faintly where it just was (a spinning blade's trail): no knock, so what is behind shows+let GHOST = 1;+export const ghost = (alpha: number, draw: () => void) => { const g = GHOST; GHOST = g * alpha; try { draw(); } finally { GHOST = g; } };+/**+ * Something that turns fast enough to blur. `draw(angle)` paints the blades at an angle; behind them go+ * `trails` fainter copies, spread over `sweep` radians against the direction of travel, and under all of+ * it the caller's swept `disc`, if any, as a faint sheen. Slow turns (sweep near 0) draw the blades alone.+ */+export const spin = (angle: number, sweep: number, draw: (angle: number) => void, o: { trails?: number; disc?: () => void } = {}) => {+ const n = o.trails ?? 4, blur = Math.min(1, Math.abs(sweep) / 1.2);+ if (blur > 0.02) { if (o.disc) ghost(0.16 * blur, o.disc); for (let k = n; k >= 1; k--) ghost(0.42 * blur * (1 - k / (n + 1)) ** 1.4, () => draw(angle - (sweep * k) / n)); }+ draw(angle);+};export const hand = () => HAND;/** a toned region in the current hand, honouring the making order (inked, then toned left to right) */export const tone = (ctx: Ctx, pts: P2[], m: Material, q: number, alpha = 1) => {- if (pts.length < 3) return;+ if (pts.length < 3) return; m = pal(m);+ if (GHOST < 1) { ctx.save(); ctx.globalAlpha = alpha * GHOST; HAND.region(ctx, pts, q, m, alpha * GHOST); ctx.restore(); return; }if (REVEAL.tone >= 1) { if (!(HAND.opaque && alpha >= 1)) HAND.knock(ctx, pts); HAND.region(ctx, pts, q, m, alpha); return; }if (REVEAL.ink < 1) return;HAND.knock(ctx, pts); if (REVEAL.tone <= 0) return;@@ -151,9 +169,9 @@ export const tone = (ctx: Ctx, pts: P2[], m: Material, q: number, alpha = 1) =>ctx.save(); ctx.beginPath(); ctx.rect(x0 - 1, -1e5, (x1 - x0 + 2) * REVEAL.tone, 2e5); ctx.clip(); HAND.region(ctx, pts, q, m, alpha); ctx.restore();};/** paint the ground back over a shape without toning it (the paper inside a hull) */-export const knock = (ctx: Ctx, pts: P2[]) => { if (pts.length >= 3 && (REVEAL.tone >= 1 || REVEAL.ink >= 1)) HAND.knock(ctx, pts); };-export const ink = (ctx: Ctx, pts: P2[], role: Role, m: Material, close = false, alpha = 1) => { if (pts.length >= 2 && REVEAL.ink > 0) HAND.line(ctx, pts, role, m, close, alpha, REVEAL.ink); };-export const inkDot = (ctx: Ctx, at: P2, r: number, m: Material, alpha = 1) => { if (REVEAL.ink >= 1) HAND.dot(ctx, at, r, m, alpha); };+export const knock = (ctx: Ctx, pts: P2[]) => { if (GHOST >= 1 && pts.length >= 3 && (REVEAL.tone >= 1 || REVEAL.ink >= 1)) HAND.knock(ctx, pts); };+export const ink = (ctx: Ctx, pts: P2[], role: Role, m: Material, close = false, alpha = 1) => { if (pts.length >= 2 && REVEAL.ink > 0) HAND.line(ctx, pts, role, pal(m), close, alpha * GHOST, REVEAL.ink); };+export const inkDot = (ctx: Ctx, at: P2, r: number, m: Material, alpha = 1) => { if (REVEAL.ink >= 1) HAND.dot(ctx, at, r, pal(m), alpha * GHOST); };const ruleFrame = (ctx: Ctx, W: number, H: number, colour: string, p: number, pad = 34) => {if (p <= 0) return; ctx.strokeStyle = colour; ctx.lineWidth = 1.2; ctx.globalAlpha = 1; ctx.lineCap = "butt"; ctx.setLineDash([]);const L = 2 * (W + H - 4 * pad) * clamp01(p), segs: [P2, P2][] = [[[pad, pad], [W - pad, pad]], [[W - pad, pad], [W - pad, H - pad]], [[W - pad, H - pad], [pad, H - pad]], [[pad, H - pad], [pad, pad]]];diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/delivery.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/delivery.tsnew file mode 100644index 0000000..5692f01--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/delivery.ts@@ -0,0 +1,64 @@+// THE DELIVERY MASTER. The last thing a film's whole mix passes through, score and effects together.+// Before this, an effects-only film shipped at -27 LUFS and a scored one landed wherever the sum of its+// parts fell, 4 to 13 LU under its web peers. A film that plays quiet reads unfinished, whatever its timbre.+// One static gain to the target, then the smooth true-peak limiter, whose work is capped: when getting+// to the target would need more than `maxLimitDb` of limiting (a mix of sharp hits on near silence), the+// gain gives way instead of the hits being squashed, and the shortfall is reported, never hidden.+import { loudness, truePeak } from "./meter";+import { smoothLimiter } from "./mixDsp";+import { db } from "./dsp";++export type MasterMode = "gentle" | "dense" | "none" | number;+export type Delivered = { targetLufs: number; gainDb: number; limitDb: number; lufs: number; dbtp: number; shortLu: number };+/** -16 LUFS for gentle films (drawing films, explainers), -14 for dense ones (launch films, trailers) */+export const targetOf = (m: MasterMode) => (typeof m === "number" ? m : m === "dense" ? -14 : -16);++export const deliver = (L: Float32Array, R: Float32Array, sr: number, mode: MasterMode = "gentle", o: { ceilingDb?: number; maxLimitDb?: number } = {}): Delivered => {+ const n = L.length, ceil = o.ceilingDb ?? -1, maxLim = o.maxLimitDb ?? (mode === "dense" ? 6 : 4), target = targetOf(mode);+ const scale = (g: number) => { if (g === 1) return; for (let i = 0; i < n; i++) { L[i] *= g; R[i] *= g; } };+ const before = n >= sr * 0.4 ? loudness([L, R], sr).integrated : -Infinity;+ if (mode === "none" || !Number.isFinite(before)) { const tp = truePeak([L, R]).dbtp; return { targetLufs: target, gainDb: 0, limitDb: 0, lufs: before, dbtp: tp, shortLu: 0 }; }+ // the limiter may take at most maxLim off the loudest peaks: try the gain on copies, and where it would+ // limit harder, give gain back; where the peak estimate left room, take it, up to the target+ const src = [L.slice(), R.slice()];+ let gainDb = target - before, limitDb = 0;+ for (let k = 0; k < 4; k++) {+ L.set(src[0]); R.set(src[1]); scale(db(gainDb));+ limitDb = smoothLimiter(L, R, sr, db(ceil - 0.15));+ const lu = loudness([L, R], sr).integrated, roomLu = target - lu;+ if (limitDb > maxLim + 0.05) gainDb -= limitDb - maxLim;+ else if (roomLu > 0.1 && limitDb < maxLim - 0.1) gainDb += Math.min(roomLu, maxLim - limitDb);+ else break;+ }+ // a last static trim for inter-sample overshoot the limiter's estimate missed+ const tp = truePeak([L, R]).dbtp; if (tp > ceil) { gainDb -= tp - ceil + 0.02; scale(db(-(tp - ceil + 0.02))); }+ const lufs = loudness([L, R], sr).integrated;+ return { targetLufs: target, gainDb, limitDb, lufs, dbtp: truePeak([L, R]).dbtp, shortLu: Math.max(0, target - lufs) };+};++/**+ * Room tone: the quiet air a foley track sits on, so an effects-only film never drops to digital+ * silence between its cues. Seeded pink noise, band-limited (80 Hz to 5 kHz) and nearly mono (the two+ * sides share most of their signal, so a phone's mono fold keeps it), faded in over 20 ms and out over+ * the last 0.4 s. Returned at unit loudness scale; the caller sets its level against the cues.+ */+export const roomTone = (n: number, sr: number, seed = 1): [Float32Array, Float32Array] => {+ let x = (seed * 2654435761) >>> 0; const rnd = () => { x ^= x << 13; x >>>= 0; x ^= x >>> 17; x ^= x << 5; x >>>= 0; return x / 4294967296 * 2 - 1; };+ const pink = () => { let b0 = 0, b1 = 0, b2 = 0; return () => { const w = rnd(); b0 = 0.99765 * b0 + w * 0.099046; b1 = 0.963 * b1 + w * 0.2965164; b2 = 0.57 * b2 + w * 1.0526913; return (b0 + b1 + b2 + w * 0.1848) * 0.2; }; };+ const shared = pink(), sideL = pink(), sideR = pink(), L = new Float32Array(n), R = new Float32Array(n);+ const hp = 1 - Math.exp((-2 * Math.PI * 80) / sr), lp = 1 - Math.exp((-2 * Math.PI * 5000) / sr), st = [0, 0, 0, 0];+ const fin = Math.round(0.02 * sr), fout = Math.round(0.4 * sr);+ for (let i = 0; i < n; i++) {+ const c = shared(), l = c + 0.35 * sideL(), r = c + 0.35 * sideR();+ st[0] += (l - st[0]) * lp; st[1] += (r - st[1]) * lp; st[2] += (st[0] - st[2]) * hp; st[3] += (st[1] - st[3]) * hp;+ const g = Math.min(1, i / fin, (n - 1 - i) / fout); L[i] = (st[0] - st[2]) * g; R[i] = (st[1] - st[3]) * g;+ }+ return [L, R];+};+/** lay room tone under an effects-only mix, `bedDb` under the effects' own loudness (no-op when they are silent) */+export const layBed = (L: Float32Array, R: Float32Array, fx: [Float32Array, Float32Array], sr: number, seed: number, bedDb = 22) => {+ const n = L.length; if (n < sr * 0.4) return;+ const fxLu = loudness(fx, sr).integrated; if (!Number.isFinite(fxLu)) return;+ const [bL, bR] = roomTone(n, sr, seed), bLu = loudness([bL, bR], sr).integrated, g = db(fxLu - bedDb - bLu);+ for (let i = 0; i < n; i++) { L[i] += bL[i] * g; R[i] += bR[i] * g; }+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sampler.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sampler.tsindex 6c909f0..36a0207 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sampler.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sampler.ts@@ -2,10 +2,31 @@import type { Played } from "./perform";import type { PedalSpan } from "./piano";import type { Opts } from "./keysCore";-import { clamp, db } from "./dsp";+import { clamp, db, Biquad } from "./dsp";import { nameOf } from "./theory";import { rng } from "../core";import { pianoVelocity } from "./keysPiano";+import { bandWidth } from "./mixDsp";++// Recordings made with spaced microphones can be out of phase between the sides in the body of the+// sound (150 Hz to 2 kHz: some marimba zones measure -0.72 file after file, which is one side's polarity+// flipped; tubular bells sit near 0, a grand piano about 0.3). On a phone or any mono fold the sides+// cancel and the music goes hollow. Each stereo recording is fixed once, when its bank is registered:+// a side whose body is clearly inverted is flipped back, then the body is narrowed (mono under 150 Hz,+// the side at half up to 2 kHz) while the air above 2 kHz keeps its full width.+export const RECORDING_WIDTH = Object.freeze({ monoHz: 150, splitHz: 2000, mid: 0.5, high: 1, flipBelow: -0.3 });+const narrowed = new WeakSet<Float32Array>();+const bodyCorr = (L: Float32Array, R: Float32Array) => {+ const f = () => [Biquad.make(48000, "hp", 150, 0.707), Biquad.make(48000, "lp", 2000, 0.707)], a = f(), b = f(); let c = 0, x = 0, y = 0;+ for (let i = 0; i < L.length; i++) { const l = a[1].tick(a[0].tick(L[i])), r = b[1].tick(b[0].tick(R[i])); c += l * r; x += l * l; y += r * r; }+ return x * y > 0 ? c / Math.sqrt(x * y) : 1;+};+const narrow = (ch: Float32Array[]): Float32Array[] => {+ if (ch.length !== 2 || narrowed.has(ch[0])) return ch;+ const L = ch[0].slice(), R = ch[1].slice();+ if (bodyCorr(L, R) < RECORDING_WIDTH.flipBelow) for (let i = 0; i < R.length; i++) R[i] = -R[i];+ bandWidth(L, R, 48000, RECORDING_WIDTH); narrowed.add(L); narrowed.add(R); return [L, R];+};export type SampleZone = { file: string; midi: number; layer: number; rr: number; frames: number; channels: number; peakDb: number; rmsDb: number; sha256: string; art?: "sus" | "rel"; unpitched?: boolean; measuredHz?: number; loop?: [number, number] };export type SampleEntry = { title: string; source: string; license: string; kind: "struck" | "sustained"; range: [number, number]; layers: number; layerVelocity?: number[]; sparse?: boolean; maxShift?: number; damped: boolean; normalized?: boolean; zones: SampleZone[] };@@ -49,7 +70,7 @@ export const registerBank = (id: string, bank: SampleBank): RegisteredBank => {});if (!e.zones.some((z) => !z.art)) throw new Error(`${id}: no ordinary sample zones`);if (bank.trim && (new Set(bank.trim.map((t) => t.file)).size !== bank.trim.length || bank.trim.some((t) => !e.zones.some((z) => z.file === t.file && z.midi === t.midi && z.layer === t.layer) || ![t.measuredDb, t.modeledDb, t.correctionDb, t.requestedDb ?? 0, t.medianDb ?? 0, t.bandFractionDb ?? 0, t.bandExcessDb ?? 0].every(Number.isFinite) || (t.medianDb !== undefined && Math.abs(t.correctionDb - t.medianDb) > 9.000001) || (t.boostLimited !== undefined && typeof t.boostLimited !== "boolean")))) throw new Error(`${id}: invalid sampled calibration`);- const identity = bankIdentity(e), b = { ...bank, id, hash: bank.trim ? hash(JSON.stringify([identity, bank.trim])) : identity }; banks.set(id, b); return b;+ const identity = bankIdentity(e), b = { ...bank, zones: bank.zones.map((z) => ({ ...z, channels: narrow(z.channels) })), id, hash: bank.trim ? hash(JSON.stringify([identity, bank.trim])) : identity }; banks.set(id, b); return b;};const layerV = (e: SampleEntry, layer: number) => e.layerVelocity?.[layer - 1] ?? (layer - 0.5) / e.layers;diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sfxKit.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sfxKit.tsindex ae7acc8..d1cad69 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sfxKit.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sfxKit.ts@@ -351,7 +351,7 @@ const impact: Def = {make(c, v) {const { sr, r, P } = c, soft = v === "soft", pre = v === "bloom" ? secs(sr, 0.28) : 0, n = pre + secs(sr, soft ? 4.5 : 7.5), b = new Bus(sr, n);// 1 sub drop, saturated so small speakers still hear its harmonics- const lo = c.j(soft ? 40 : 44, 0.04) * P, subTau = c.j(soft ? 0.32 : 0.6, 0.1), sub = chirp(sr, secs(sr, subTau * 8), (t) => lo + (soft ? 55 : 72) * P * Math.exp(-t / 0.07), ad(0.002, subTau));+ const lo = c.j(soft ? 40 : 44, 0.04) * P, subTau = c.j(soft ? 0.3 : 0.38, 0.1), sub = chirp(sr, secs(sr, subTau * 8), (t) => lo + (soft ? 55 : 72) * P * Math.exp(-t / 0.07), ad(0.002, subTau));b.add(sub.map((x) => Math.tanh(x * 1.8) / Math.tanh(1.8)), pre, 1, 0);// 2 punch: dark noise + two chest modes, a hair wideb.add(burst(sr, r, 0.35, soft ? 0.05 : 0.07, { lp: soft ? 500 : 950, pink: true }), pre, soft ? 0.9 : 1.3, -0.1, 0.4);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sfxMix.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sfxMix.tsindex 3bbc4f5..6e4160b 100644--- a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sfxMix.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/sfxMix.ts@@ -8,6 +8,7 @@ import { Biquad, db } from "./dsp";import { MODES } from "./theory";import type { Piece } from "./plan";import { loudness, truePeak } from "./meter";+import { deliver, layBed, type Delivered, type MasterMode } from "./delivery";export type SfxSnap = "none" | "bar" | "beat" | "8th" | "16th";export type SfxHarshOptions = { mode?: "report" | "throw" | "tame"; maxLiftDb?: number; maxTiltDb?: number; maxPeakDb?: number };@@ -38,6 +39,10 @@ export type SfxPlan = {minDb?: number;/** final true-peak ceiling in dBTP. Default -1. */ceilingDb?: number;+ /** the whole mix's loudness target (delivery.ts): "gentle" -16 LUFS (default), "dense" -14, a number, or "none" for the old peak-only ceiling */+ master?: MasterMode;+ /** an effects-only mix (no score) sits on quiet room tone this many dB under its cues, so it never drops to silence between them. Default 22; false for none. */+ bed?: number | false;/** Default report: samples stay frozen. Caps are cue-minus-score band RMS, band-minus-full RMS,* and absolute sample peak dBFS. Tame scales cues only, never the score or duck envelope. */harsh?: SfxHarshOptions;@@ -52,7 +57,7 @@ export type SfxHarshness = {violations: { metric: "liftDb" | "tiltDb" | "peakDb"; valueDb: number; capDb: number; excessDb: number }[];ok: boolean; reductionDb: number; conflict: "audibility floor" | "tilt cannot be fixed by gain" | null;};-export type SfxMix = { L: Float32Array; R: Float32Array; sfx: SfxStereo; music: SfxStereo; duck: Float32Array; placed: PlacedCue[]; audibility: SfxAudibility[]; harshness: SfxHarshness[]; ok: boolean; lufs: number; dbtp: number; limiterDb: number };+export type SfxMix = { L: Float32Array; R: Float32Array; sfx: SfxStereo; music: SfxStereo; duck: Float32Array; placed: PlacedCue[]; audibility: SfxAudibility[]; harshness: SfxHarshness[]; ok: boolean; lufs: number; dbtp: number; limiterDb: number; delivered?: Delivered };// test/sfxKitSurvey.ts: all 44 variants, default gain/seed 1, C/90 bpm, 48 kHz, silence and// a steady mid-level score. Maxima 16.49 / -0.80 / -1.00; margins 1.01 / 0.55 / 0.50 dB.@@ -245,11 +250,15 @@ export const mixSfx = (music: SfxStereo | null, p: SfxPlan, sr = 48000): SfxMixfor (const pc of placed) { const { L, R } = pc.sound; for (let i = 0; i < L.length && pc.start + i < n; i++) { fxL[pc.start + i] += L[i]; fxR[pc.start + i] += R[i]; } }const L = new Float32Array(n), R = new Float32Array(n);for (let i = 0; i < n; i++) { L[i] = mL[i] + fxL[i]; R[i] = mR[i] + fxR[i]; }- const limiterDb = ceiling(L, R, sr, db((p.ceilingDb ?? -1) - 0.3));+ // no score: lay the cues on room tone, set against the cues' own loudness+ if (!music && p.bed !== false && placed.length) layBed(L, R, [fxL, fxR], sr, mixSeed(p.cues.length, p.frames), p.bed ?? 22);+ // the whole mix to its loudness target, then the ceiling; "none" keeps the old peak-only master+ const delivered = (p.master ?? "gentle") === "none" ? undefined : deliver(L, R, sr, p.master ?? "gentle", { ceilingDb: (p.ceilingDb ?? -1) - 0.3 });+ const limiterDb = delivered ? delivered.limitDb : ceiling(L, R, sr, db((p.ceilingDb ?? -1) - 0.3));const fade = Math.min(n, secs(sr, 0.015)); for (let i = 0; i < fade; i++) { const g = i / fade; L[n - 1 - i] *= g; R[n - 1 - i] *= g; }const audibility = sfxAudibility(placed, [mL, mR], sr, p);const lu = n >= secs(sr, 0.4) ? loudness([L, R], sr).integrated : NaN;- return { L, R, sfx: [fxL, fxR], music: [mL, mR], duck, placed, audibility, harshness, ok: audibility.every((a) => a.ok), lufs: lu, dbtp: truePeak([L, R]).dbtp, limiterDb };+ return { L, R, sfx: [fxL, fxR], music: [mL, mR], duck, placed, audibility, harshness, ok: audibility.every((a) => a.ok), lufs: lu, dbtp: truePeak([L, R]).dbtp, limiterDb, delivered };};export const assertSfxAudible = (m: SfxMix) => {diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/soundcheck.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/soundcheck.tsnew file mode 100644index 0000000..5744f32--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/music/soundcheck.ts@@ -0,0 +1,271 @@+// SOUNDCHECK. The film-sound scorecard as pure functions over a decoded stereo mix, so the tool+// (tools/soundcheck.mjs) and the tests read the same numbers. Nothing here needs a model or ears:+// level BS.1770 integrated / LRA / true peak from meter.ts; 10 ms K-weighted powers for the rest+// shape first sound, holes, dead tail, fade, final moment, an 11-point arc, hits, stop-downs+// spectrum six band shares of the mid, centroid, the loudest third-octave in a band (to name a fix)+// stereo side vs mid, L/R correlation overall and per band, mono-fold loss beyond the expected 3 dB+// picture frame-difference events against onsets, with a chance baseline from shifted events+// Then evaluate() holds every number to a profile and writes the fix a mixer would make.+import { loudness, truePeak, onsetsDetail, centroid, fft } from "./meter";+import { kWeight } from "./sfxCore";++export const BANDS: Record<string, [number, number]> = { sub: [20, 60], low: [60, 250], lowmid: [250, 1000], mid: [1000, 4000], presence: [4000, 8000], air: [8000, 16000] };+/** Where a stereo mix's body sits: decorrelation here is what a phone's one speaker combs away. */+export const BODY: [number, number] = [150, 2000];+const HOP = 0.01, BLK = 0.05;+const lufsOf = (z: number) => -0.691 + 10 * Math.log10(Math.max(z, 1e-20));+const meanOf = (p: ArrayLike<number>, a: number, b: number) => { const lo = Math.max(0, a), hi = Math.min(p.length, b); let s = 0; for (let i = lo; i < hi; i++) s += p[i]; return hi > lo ? s / (hi - lo) : 0; };+const median = (xs: number[]) => { if (!xs.length) return NaN; const s = [...xs].sort((a, b) => a - b), m = s.length >> 1; return s.length & 1 ? s[m] : 0.5 * (s[m - 1] + s[m]); };+const r1 = (x: number, d = 1) => (Number.isFinite(x) ? +x.toFixed(d) : null);++/** K-weighted power per 10 ms hop, channels summed (BS.1770 weights L and R at 1). */+const hopPowers = (k: Float64Array[], sr: number) => {+ const h = Math.round(HOP * sr), n = Math.floor(k[0].length / h), p = new Float64Array(n);+ for (let i = 0; i < n; i++) { let s = 0; for (const c of k) for (let j = i * h; j < (i + 1) * h; j++) s += c[j] * c[j]; p[i] = s / h; }+ return p;+};+/** Gated integrated loudness from hop powers: 400 ms blocks every 100 ms, -70 absolute, -10 relative (meter.ts's gates). */+export const gatedLufs = (p: ArrayLike<number>) => {+ const per = Math.round(0.4 / HOP), step = Math.round(0.1 / HOP), bl: number[] = [];+ for (let a = 0; a + per <= p.length; a += step) bl.push(meanOf(p, a, a + per));+ const abs = bl.filter((z) => lufsOf(z) > -70); if (!abs.length) return -Infinity;+ const rel = lufsOf(abs.reduce((a, b) => a + b, 0) / abs.length) - 10, g = abs.filter((z) => lufsOf(z) > rel);+ return lufsOf(g.reduce((a, b) => a + b, 0) / g.length);+};++/** Welch-averaged auto and cross spectra of L and R (Hann, 50 % overlap). */+const spectra = (L: Float32Array, R: Float32Array, N = 8192) => {+ const bins = N / 2 + 1, ll = new Float64Array(bins), rr = new Float64Array(bins), lr = new Float64Array(bins), w = Float64Array.from({ length: N }, (_, i) => 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / N));+ const n = L.length, starts: number[] = []; for (let a = 0; a + N <= n; a += N / 2) starts.push(a); if (!starts.length) starts.push(0); // shorter than one frame: zero-padded+ for (const a of starts) {+ const lr_ = new Float64Array(N), li = new Float64Array(N), rre = new Float64Array(N), ri = new Float64Array(N);+ for (let i = 0; i < N && a + i < n; i++) { lr_[i] = L[a + i] * w[i]; rre[i] = R[a + i] * w[i]; }+ fft(lr_, li); fft(rre, ri);+ for (let k = 0; k < bins; k++) { ll[k] += lr_[k] * lr_[k] + li[k] * li[k]; rr[k] += rre[k] * rre[k] + ri[k] * ri[k]; lr[k] += lr_[k] * rre[k] + li[k] * ri[k]; }+ }+ return { ll, rr, lr, N };+};++export type Gap = { at: number; len: number; allowed: boolean };+export type Measures = {+ durationS: number; lufs: number; lra: number; truePeak: number; samplePeak: number; crest: number; peakPos: number;+ introLu: number; endLu: number; arc: (number | null)[]; arcDip: number; arcDipAt: number;+ firstSound: number | null; insideGap: number; insideGapAt: number | null; gaps: Gap[]; endSilence: number; endSilenceFrom: number;+ fade: number; finalLu: number; tailLu: number; quietAt: number | null; loudAt: number;+ onsetRate: number; hitRate: number; stopDowns: { at: number; len: number }[];+ bands: Record<string, number>; centroid: number; peakHz: Record<string, number>;+ sideMid: number; corr: number; bandCorr: Record<string, number>; bodyCorr: number; monoDrop: number; monoLoss: number;+ silent: boolean;+};+export type Curves = { momentary: number[]; shortTerm: number[]; hopS: number; levels50: number[]; onsets: number[]; hits: number[] };++/** Every model-free number for one decoded stereo mix. `allow` lists [from, to] seconds where a hole is meant (a declared stop-down). */+export const analyze = (L: Float32Array, R: Float32Array, sr: number, { allow = [] as [number, number][] } = {}): { measures: Measures; curves: Curves } => {+ const dur = L.length / sr, chans = [L, R];+ const lo = loudness(chans, sr), tp = truePeak(chans), I = lo.integrated, silent = !(I > -70);+ const kL = kWeight(L, sr), kR = kWeight(R, sr), p10 = hopPowers([kL, kR], sr);+ // mono fold: K-weighting is linear, so the mid's K-weighted signal is the mean of the channels'+ const kM = new Float64Array(kL.length); for (let i = 0; i < kM.length; i++) kM[i] = 0.5 * (kL[i] + kR[i]);+ const pM = hopPowers([kM], sr), monoDrop = gatedLufs(p10) - gatedLufs(pM);+ // 50 ms block levels: fine enough to time a 0.25 s hole, coarse enough that one quiet cycle is not a gap.+ // Unweighted, against the same gating on unweighted power: K-weighting rings for ~30 ms past an abrupt+ // cut, which would move every hole and every dead tail by a block.+ const pRaw = hopPowers([Float64Array.from(L), Float64Array.from(R)], sr), Iraw = gatedLufs(pRaw);+ const per = Math.round(BLK / HOP), nb = Math.floor(pRaw.length / per), lv: number[] = [];+ for (let j = 0; j < nb; j++) lv.push(lufsOf(meanOf(pRaw, j * per, (j + 1) * per)));+ const body = (j: number) => lv[j] >= Iraw - 20, alive = (j: number) => lv[j] > Iraw - 30 && lv[j] > -70;+ let first = -1, last = -1, lastBody = -1;+ for (let j = 0; j < nb; j++) { if (first < 0 && body(j)) first = j; if (alive(j)) last = j; if (body(j)) lastBody = j; }+ const aliveFirst = lv.findIndex((_, j) => alive(j));+ const gaps: Gap[] = [];+ if (aliveFirst >= 0) for (let j = aliveFirst, run = -1; j <= last + 1; j++) {+ if (j <= last && !alive(j)) { if (run < 0) run = j; continue; }+ if (run >= 0) { const at = run * BLK, len = (j - run) * BLK; gaps.push({ at, len, allowed: allow.some(([a, b]) => at >= a - 0.05 && at + len <= b + 0.05) }); run = -1; }+ }+ const open = gaps.filter((g) => !g.allowed).sort((a, b) => b.len - a.len);+ const endFrom = last >= 0 ? (last + 1) * BLK : 0;+ // the arc: each point the energy mean of the tenth of the film around it, against the whole+ const nh = p10.length, arc: (number | null)[] = [];+ for (let q = 0; q <= 10; q++) { const c = (q / 10) * nh, half = nh / 20, l = lufsOf(meanOf(p10, Math.floor(c - half), Math.ceil(c + half))); arc.push(l > -70 ? r1(l - I) : null); }+ let arcDip = 0, arcDipAt = 0; for (let q = 1; q <= 9; q++) { const v = arc[q] ?? -70 - I; if (v < arcDip) { arcDip = v; arcDipAt = (q / 10) * dur; } } // ends are first sound and end silence's job+ const tenth = Math.max(1, Math.round(nh / 10));+ const introLu = lufsOf(meanOf(p10, 0, tenth)) - I, endLu = lufsOf(meanOf(p10, nh - tenth, nh)) - I;+ // the final moment: the loudest 400 ms block centred in the last 3 s+ const fin = lo.momentary.filter((_, i) => i * lo.hopS + 0.2 >= dur - 3);+ const st = lo.shortTerm; let si = 0; st.forEach((v, i) => { if (v > st[si]) si = i; });+ let qi = -1; st.forEach((v, i) => { if (v > I - 40 && (qi < 0 || v < st[qi])) qi = i; });+ // hits and stop-downs on a 100 ms level every 10 ms+ const S = Array.from({ length: nh }, (_, i) => lufsOf(meanOf(p10, i - 5, i + 5)));+ const hits: number[] = [];+ for (let i = 8; i < nh; i++) if (S[i] - S[i - 8] >= 6 && S[i] >= I - 8 && (!hits.length || i * HOP - hits[hits.length - 1] > 0.3)) hits.push(i * HOP);+ const stopDowns: { at: number; len: number }[] = [];+ for (let i = 50; i < nh; i++) {+ const ref = lufsOf(meanOf(p10, i - 50, i)); if (ref < I - 10 || S[i] >= ref - 10 || S[i - 1] < ref - 10) continue;+ let j = i; while (j < nh && S[j] < ref - 10) j++;+ const len = (j - i) * HOP; let back = false; for (let k = j; k < Math.min(nh, j + 30); k++) if (S[k] >= ref - 6) { back = true; break; }+ if (len >= 0.15 && len <= 1.5 && back) stopDowns.push({ at: i * HOP, len: +len.toFixed(2) });+ i = j;+ }+ const on = silent ? [] : onsetsDetail(chans, sr).times;+ // spectrum and stereo+ const sp = spectra(L, R), df = sr / sp.N, bins = sp.ll.length, mid = new Float64Array(bins), side = new Float64Array(bins);+ for (let k = 0; k < bins; k++) { mid[k] = (sp.ll[k] + sp.rr[k] + 2 * sp.lr[k]) / 4; side[k] = Math.max(0, (sp.ll[k] + sp.rr[k] - 2 * sp.lr[k]) / 4); }+ const sum = (a: Float64Array, f0: number, f1: number) => { let s = 0; for (let k = Math.ceil(f0 / df); k < Math.min(bins, Math.ceil(f1 / df)); k++) s += a[k]; return s; };+ const tot = sum(mid, 20, 16000) || 1e-30, bands: Record<string, number> = {}, bandCorr: Record<string, number> = {}, peakHz: Record<string, number> = {};+ const corrIn = (f0: number, f1: number) => { const d = Math.sqrt(sum(sp.ll, f0, f1) * sum(sp.rr, f0, f1)); return d > 1e-20 ? sum(sp.lr, f0, f1) / d : NaN; };+ const thirds = Array.from({ length: 28 }, (_, i) => 1000 * Math.pow(2, (i - 15) / 3));+ for (const [b, [f0, f1]] of Object.entries(BANDS)) {+ bands[b] = 10 * Math.log10(Math.max(sum(mid, f0, f1), 1e-30) / tot); bandCorr[b] = corrIn(f0, f1);+ let best = -1, bc = 0; for (const c of thirds) if (c >= f0 && c < f1) { const e = sum(mid, c / Math.pow(2, 1 / 6), c * Math.pow(2, 1 / 6)); if (e > best) { best = e; bc = c; } }+ peakHz[b] = Math.round(bc);+ }+ let sl = 0, sr_ = 0, slr = 0, ml = 0, mr = 0; for (let i = 0; i < L.length; i++) { ml += L[i]; mr += R[i]; } ml /= L.length || 1; mr /= L.length || 1;+ for (let i = 0; i < L.length; i++) { const a = L[i] - ml, b = R[i] - mr; sl += a * a; sr_ += b * b; slr += a * b; }+ const sm = sum(side, 20, 20000), mm = sum(mid, 20, 20000);+ const measures: Measures = {+ durationS: dur, lufs: I, lra: lo.lra, truePeak: tp.dbtp, samplePeak: tp.samplePeakDb, crest: lo.shortMax - I, peakPos: Math.min(1, (si * lo.hopS + 1.5) / dur),+ introLu, endLu, arc, arcDip, arcDipAt,+ firstSound: first >= 0 ? first * BLK : null, insideGap: open[0]?.len ?? 0, insideGapAt: open[0]?.at ?? null, gaps, endSilence: Math.max(0, dur - endFrom), endSilenceFrom: endFrom,+ fade: lastBody >= 0 && last >= lastBody ? (last - lastBody) * BLK : 0, finalLu: fin.length ? Math.max(...fin) - I : NaN, tailLu: lv.length ? Math.max(lv[lv.length - 1] - Iraw, -70 - I) : NaN,+ quietAt: qi >= 0 ? qi * lo.hopS + 1.5 : null, loudAt: si * lo.hopS + 1.5,+ onsetRate: on.length / dur, hitRate: hits.length / dur, stopDowns,+ bands, centroid: silent ? 0 : centroid(chans, sr).energyWeighted, peakHz,+ sideMid: 10 * Math.log10(Math.max(sm, 1e-30) / Math.max(mm, 1e-30)), corr: sl > 0 && sr_ > 0 ? slr / Math.sqrt(sl * sr_) : NaN,+ bandCorr, bodyCorr: corrIn(BODY[0], BODY[1]), monoDrop, monoLoss: monoDrop - 10 * Math.log10(2), silent,+ };+ return { measures, curves: { momentary: lo.momentary, shortTerm: lo.shortTerm, hopS: lo.hopS, levels50: lv, onsets: on, hits } };+};++// ---------------------------------------------------------------- picture against sound+/** Frame-difference spikes: a frame whose changed area is 4x the median of the second around it (and at least 2 %), or 15 % outright. `changed[i]` compares frame i with i - 1. */+export const visualEvents = (changed: number[], fps: number) => {+ const ev: number[] = [], win = Math.max(1, Math.round(fps));+ for (let i = 1; i < changed.length; i++) {+ const ctx: number[] = []; for (let k = Math.max(1, i - win); k <= Math.min(changed.length - 1, i + win); k++) if (k !== i) ctx.push(changed[k]);+ const c = median(ctx), d = changed[i];+ if (((d >= 4 * Math.max(c || 0, 0.005) && d >= 0.02) || d >= 0.15) && (!ev.length || i / fps - ev[ev.length - 1] > 0.2)) ev.push(i / fps);+ }+ return ev;+};+/** Share of events with an onset within `tol`, against the same events shifted off their frames (chance), the unanswered ones, and the nearest-onset offsets. */+export const visualSync = (events: number[], onsets: number[], dur: number, tol = 0.1) => {+ const near = (e: number) => onsets.reduce((b, o) => (Math.abs(o - e) < Math.abs(b - e) ? o : b), Infinity);+ const share = (evs: number[]) => (evs.length && onsets.length ? evs.filter((e) => Math.abs(near(e) - e) <= tol).length / evs.length : NaN);+ const shifts = [0.23, 0.31, 0.43, 0.57, 0.71, 0.87, -0.29, -0.41, -0.53, -0.67];+ const chance = median(shifts.map((s) => share(events.map((e) => e + s).filter((e) => e > 0 && e < dur))).filter(Number.isFinite));+ const offsets = events.map((e) => near(e) - e).filter((d) => Math.abs(d) <= 0.25).map((d) => Math.round(d * 1000));+ return { events: events.length, share: share(events), chance, unanswered: events.filter((e) => !(Math.abs(near(e) - e) <= tol)), medianOffsetMs: offsets.length ? median(offsets) : NaN, offsets };+};++// ---------------------------------------------------------------- holding the numbers to a profile+export type Range = { min?: number; max?: number; tol?: number };+export type Status = "PASS" | "WARN" | "FAIL" | "INFO";+export type Profile = { name: string; ranges: Record<string, Range>; allow?: [number, number][] };+/** Drawing films, from the study's pro-reference column, tightened where a drawing film should be (no dead tail, no hole, sound from frame 0). */+export const DEFAULT_PROFILE: Profile = {+ name: "built-in: drawing film",+ ranges: {+ lufs: { min: -16, max: -13, tol: 1 }, truePeak: { max: -1, tol: 0 }, lra: { max: 9, tol: 3 },+ firstSound: { max: 0.5, tol: 0.5 }, insideGap: { max: 0.25, tol: 0.25 }, endSilence: { max: 0.5, tol: 0.5 }, arcDip: { min: -10, tol: 6 }, tailLu: { max: -20, tol: 10 },+ bodyCorr: { min: 0.3, tol: 0.15 }, monoLoss: { max: 1.5, tol: 0.5 }, corr: { min: 0.3, tol: 0.3 }, sideMid: { min: -15, max: -4, tol: 3 },+ sub: { max: -6, tol: 2 }, lowmid: { max: -3, tol: 1.5 },+ },+};+/** Delivery limits a reference set never loosens: a profile built from films can only move the taste ranges. */+export const HARD = ["truePeak", "firstSound", "insideGap", "endSilence", "monoLoss"];+const TOL: Record<string, number> = { lufs: 1, lra: 3, crest: 2, introLu: 3, endLu: 3, arcDip: 4, tailLu: 6, fade: 0.5, finalLu: 4, onsetRate: 1, hitRate: 0.3, corr: 0.2, bodyCorr: 0.15, sideMid: 3, centroid: 400, sub: 2, low: 2, lowmid: 2, mid: 2, presence: 2, air: 2 };++export type Row = { key: string; label: string; value: number | null; text: string; status: Status; range?: Range; fix?: string; at?: number; covered?: boolean };+const fmtT = (s: number) => `${Math.floor(s / 60)}:${(s % 60).toFixed(1).padStart(4, "0")}`;+export { fmtT };+const f1 = (x: number | null, d = 1) => (x === null || !Number.isFinite(x) ? "n/a" : x.toFixed(d));+const sign = (x: number, d = 1) => (x > 0 ? "+" : "") + x.toFixed(d);+export const grade = (v: number | null, r?: Range): Status => {+ if (!r) return "INFO"; if (v === null || !Number.isFinite(v)) return "FAIL";+ const tol = r.tol ?? 0, over = Math.max(r.min !== undefined ? r.min - v : 0, r.max !== undefined ? v - r.max : 0);+ return over <= 1e-9 ? "PASS" : over <= tol + 1e-9 ? "WARN" : "FAIL";+};+const rangeText = (r?: Range) => (!r ? "" : r.min !== undefined && r.max !== undefined ? `${r.min}..${r.max}` : r.min !== undefined ? `>= ${r.min}` : r.max !== undefined ? `<= ${r.max}` : "");++type Def = { key: string; label: string; get: (m: Measures) => number | null; show: (v: number, m: Measures) => string; fix?: (v: number, m: Measures, r: Range) => string; at?: (m: Measures) => number | undefined };+const BAND_LABEL: Record<string, string> = { sub: "sub 20-60 Hz", low: "low 60-250 Hz", lowmid: "low-mid 250-1k", mid: "mid 1-4k", presence: "presence 4-8k", air: "air 8-16k" };+const bandFix = (b: string, v: number, m: Measures, r: Range) => {+ const hot = r.max !== undefined && v > r.max, pk = m.peakHz[b];+ if (b === "sub") return hot ? `too much 20-60 Hz (${f1(v)} dB of the energy, it eats the headroom): high-pass the effects at 30-40 Hz and pull the sub voice down` : `no weight under 60 Hz (${f1(v)} dB): let a low voice or the impact reach 40-60 Hz`;+ if (b === "lowmid") return hot ? `boxy (${f1(v)} dB in 250-1k, loudest around ${pk} Hz): cut ${pk >= 250 && pk <= 800 ? `${Math.round(pk * 0.08) * 10}-${Math.round(pk * 0.125) * 10}` : "300-500"} Hz by 2-3 dB` : `thin (${f1(v)} dB in 250-1k): the body is missing, lift 250-500 Hz 1-2 dB`;+ if (b === "low") return hot ? `boomy (${f1(v)} dB in 60-250, around ${pk} Hz): cut ${pk} Hz 2-3 dB or high-pass the pads at 80-100 Hz` : `no low end (${f1(v)} dB in 60-250): bring the bass or the low pad up`;+ if (b === "mid") return hot ? `honky (${f1(v)} dB in 1-4k, around ${pk} Hz): cut ${pk} Hz 2 dB` : `recessed mids (${f1(v)} dB in 1-4k): the melody needs 1-3 kHz, lift the lead`;+ if (b === "presence") return hot ? `harsh (${f1(v)} dB in 4-8k): cut 4-6 kHz 2 dB or soften the transients` : `dull (${f1(v)} dB in 4-8k): lift 5 kHz 1-2 dB on the lead or the effects' transients`;+ return hot ? `fizzy (${f1(v)} dB in 8-16k): a shelf down 2 dB above 10 kHz` : `no air (${f1(v)} dB in 8-16k): a gentle shelf up above 10 kHz`;+};+const DEFS: Def[] = [+ { key: "lufs", label: "integrated loudness", get: (m) => m.lufs, show: (v) => `${f1(v)} LUFS`, fix: (v, m, r) => v < (r.min ?? -99) ? `plays at ${f1(v)} LUFS, ${f1(-14 - v)} LU under the web target: master the mix to -14 LUFS (or -16 for a gentle film), a static gain then the limiter` : `too loud at ${f1(v)} LUFS: turn the master down to -14 LUFS` },+ { key: "truePeak", label: "true peak", get: (m) => m.truePeak, show: (v) => `${f1(v)} dBTP`, fix: (v) => `true peak ${f1(v)} dBTP: set the limiter ceiling to -1.5 dBTP before the encode, so the AAC overshoot stays under -1` },+ { key: "lra", label: "loudness range", get: (m) => m.lra, show: (v) => `${f1(v)} LU`, fix: (v, m) => `level swings ${f1(v)} LU (loudest at ${fmtT(m.loudAt)}${m.quietAt !== null ? `, quietest at ${fmtT(m.quietAt)}` : ""}): lift the quiet passages or keep a bed under them`, at: (m) => m.quietAt ?? undefined },+ { key: "firstSound", label: "first sound", get: (m) => m.firstSound, show: (v) => `${f1(v, 2)} s`, fix: (v) => `nothing reaches body level until ${fmtT(v)}: start the bed or a sound on frame 0`, at: (m) => m.firstSound ?? 0 },+ { key: "insideGap", label: "longest hole inside", get: (m) => m.insideGap, show: (v, m) => `${f1(v, 2)} s${m.insideGapAt !== null ? ` at ${fmtT(m.insideGapAt)}` : ""}`, fix: (v, m) => `${f1(v)} s hole at ${fmtT(m.insideGapAt ?? 0)}: keep the bed under it, or if it is a deliberate stop-down pass --allow ${f1(m.insideGapAt ?? 0, 2)}:${f1((m.insideGapAt ?? 0) + v, 2)}`, at: (m) => m.insideGapAt ?? undefined },+ { key: "endSilence", label: "dead air at the end", get: (m) => m.endSilence, show: (v) => `${f1(v, 2)} s`, fix: (v, m) => `${f1(v)} s of dead air at the end (from ${fmtT(m.endSilenceFrom)}): carry the bed or a tail to the last frame, or end the film sooner`, at: (m) => m.endSilenceFrom },+ { key: "arcDip", label: "deepest dip in the arc", get: (m) => (m.silent ? null : m.arcDip), show: (v, m) => `${sign(v)} LU at ${fmtT(m.arcDipAt)}`, fix: (v, m) => `the sound drops ${f1(-v)} LU under the film at ${fmtT(m.arcDipAt)} (${Math.round((100 * m.arcDipAt) / m.durationS)} %): keep the bed or room tone under it`, at: (m) => m.arcDipAt },+ { key: "tailLu", label: "level of the last 50 ms", get: (m) => (m.silent ? null : m.tailLu), show: (v, m) => (v + m.lufs <= -70 + 1e-6 ? "silent" : `${sign(v)} LU`), fix: (v) => `ends on a cut (the last 50 ms still at ${sign(v)} LU): end on a tail or fade the last 0.3 s`, at: (m) => m.durationS - 0.05 },+ { key: "bodyCorr", label: "L/R correlation 150-2k", get: (m) => m.bodyCorr, show: (v) => f1(v, 2), fix: (v) => `mids decorrelated (150-2k correlation ${f1(v, 2)}): narrow the stereo width below 2 kHz (mixDsp.bandWidth mid at 1.0, or a mono room send)` },+ { key: "monoLoss", label: "mono fold, extra loss", get: (m) => m.monoLoss, show: (v) => `${f1(v)} dB`, fix: (v) => `folded to mono it loses ${f1(v)} dB more than a centred mix: phones will comb it; narrow the width or check the stereo pair's phase` },+ { key: "corr", label: "L/R correlation", get: (m) => m.corr, show: (v) => f1(v, 2), fix: (v) => `L and R barely agree (correlation ${f1(v, 2)}): pan the lead and bass to the centre, keep width for pads and room` },+ { key: "sideMid", label: "side vs mid", get: (m) => m.sideMid, show: (v) => `${f1(v)} dB`, fix: (v, m, r) => v > (r.max ?? 99) ? `too wide (side ${f1(v)} dB against the mid): narrow the overall width` : `very narrow (side ${f1(v)} dB): widen the pads or the room a little` },+ ...Object.keys(BANDS).map((b): Def => ({ key: b, label: `${BAND_LABEL[b]} share`, get: (m) => (m.silent ? null : m.bands[b]), show: (v) => `${f1(v)} dB`, fix: (v, m, r) => bandFix(b, v, m, r) })),+ { key: "centroid", label: "brightness (centroid)", get: (m) => m.centroid, show: (v) => `${Math.round(v)} Hz`, fix: (v, m, r) => v > (r.max ?? 1e9) ? `brighter than the references (${Math.round(v)} Hz): soften the top` : `darker than the references (${Math.round(v)} Hz): lift the top` },+ { key: "crest", label: "loudest 3 s over integrated", get: (m) => m.crest, show: (v) => `${sign(v)} LU` },+ { key: "introLu", label: "intro level (first 10 %)", get: (m) => m.introLu, show: (v) => `${sign(v)} LU` },+ { key: "endLu", label: "end level (last 10 %)", get: (m) => m.endLu, show: (v) => `${sign(v)} LU` },+ { key: "peakPos", label: "loudest moment", get: (m) => m.peakPos, show: (v, m) => `${Math.round(v * 100)} % (${fmtT(v * m.durationS)})` },+ { key: "fade", label: "fade / ring-out", get: (m) => m.fade, show: (v) => `${f1(v, 2)} s` },+ { key: "finalLu", label: "final moment (last 3 s)", get: (m) => m.finalLu, show: (v) => `${sign(v)} LU` },+ { key: "onsetRate", label: "onsets per second", get: (m) => m.onsetRate, show: (v) => f1(v, 2) },+ { key: "hitRate", label: "salient hits per second", get: (m) => m.hitRate, show: (v) => f1(v, 2) },+ { key: "stopDowns", label: "stop-downs", get: (m) => m.stopDowns.length, show: (v, m) => `${v}${m.stopDowns.length ? ` (${m.stopDowns.slice(0, 4).map((s) => fmtT(s.at)).join(", ")})` : ""}` },+];+/** Fix order: what most makes a film read unfinished goes first. */+const ORDER = ["lufs", "endSilence", "insideGap", "firstSound", "arcDip", "truePeak", "lra", "bodyCorr", "monoLoss", "sub", "lowmid", "sideMid", "corr", "tailLu"];++export const evaluate = (m: Measures, profile: Profile = DEFAULT_PROFILE): Row[] =>+ DEFS.map((d) => {+ const v = d.get(m), r = profile.ranges[d.key], status = m.silent && d.key === "lufs" ? "FAIL" : grade(v, r);+ const row: Row = { key: d.key, label: d.label, value: v === null ? null : r1(v, 3), text: v === null ? "n/a" : d.show(v, m), status, range: r };+ if ((status === "FAIL" || status === "WARN") && r) { row.fix = m.silent ? "the file is silent: there is no sound to check" : v === null ? `${d.label}: not measurable` : d.fix ? d.fix(v, m, r) : `${d.label} ${d.show(v, m)} is outside ${rangeText(r)}`; const at = d.at?.(m); if (at !== undefined) row.at = at; }+ // a dip that sits in a hole or the dead tail is that fault again: one fix, not two+ if (d.key === "arcDip" && row.fix && (m.gaps.some((g) => !g.allowed && g.len > (profile.ranges.insideGap?.max ?? 0.25) && m.arcDipAt >= g.at - m.durationS / 20 && m.arcDipAt <= g.at + g.len + m.durationS / 20) || (m.endSilence > (profile.ranges.endSilence?.max ?? 0.5) && m.arcDipAt >= m.endSilenceFrom - m.durationS / 20))) row.covered = true;+ return row;+ });+/** One fix per cause: the stereo numbers all point at the width, so they fold into the first of them that is out. */+const GROUP: Record<string, string> = { bodyCorr: "stereo", monoLoss: "stereo", corr: "stereo", sideMid: "stereo" };+export const fixFirst = (rows: Row[]) => {+ const out: Row[] = [], seen = new Map<string, Row>();+ for (const r of rows.filter((x) => x.fix && !x.covered).sort((a, b) => (a.status === b.status ? 0 : a.status === "FAIL" ? -1 : 1) || rank(a.key) - rank(b.key))) {+ const g = GROUP[r.key], lead = g && seen.get(g);+ if (lead) { lead.fix += `${lead.fix!.includes("(also ") ? "; " : " (also "}${r.label} ${r.text}`; continue; }+ const copy = { ...r }; if (g) seen.set(g, copy); out.push(copy);+ }+ for (const r of seen.values()) if (r.fix!.includes("(also ")) r.fix += ")";+ return out;+};+const rank = (k: string) => { const i = ORDER.indexOf(k); return i < 0 ? 99 : i; };+export { rangeText };++/** Ranges from films Alex picked: min, max and median of every number, per metric. */+export const buildProfile = (name: string, sets: { file: string; measures: Measures }[]) => {+ const metrics: Record<string, { min: number; max: number; median: number }> = {};+ for (const d of DEFS) {+ const vs = sets.map((s) => d.get(s.measures)).filter((v): v is number => v !== null && Number.isFinite(v));+ if (vs.length) metrics[d.key] = { min: r1(Math.min(...vs), 2)!, max: r1(Math.max(...vs), 2)!, median: r1(median(vs), 2)! };+ }+ return { name, built: "soundcheck profile", from: sets.map((s) => s.file), metrics };+};+/** A built profile as ranges: the references' own span, padded by half a tolerance, over the defaults; HARD limits stay. */+export const profileFrom = (built: { name: string; metrics: Record<string, { min: number; max: number }>; allow?: [number, number][] }): Profile => {+ const ranges: Record<string, Range> = { ...DEFAULT_PROFILE.ranges };+ for (const [k, v] of Object.entries(built.metrics ?? {})) {+ if (HARD.includes(k) || k === "stopDowns" || k === "peakPos") continue;+ const tol = TOL[k] ?? DEFAULT_PROFILE.ranges[k]?.tol ?? 1, pad = tol / 2;+ ranges[k] = { min: +(v.min - pad).toFixed(2), max: +(v.max + pad).toFixed(2), tol };+ }+ return { name: built.name, ranges, allow: built.allow };+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/siteHero.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/siteHero.tsnew file mode 100644index 0000000..5b3363b--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/siteHero.ts@@ -0,0 +1,39 @@+// SITE HERO. The music box as art for a landing page: placed right of a headline (assetKit PLACEMENTS.heroRight),+// on the page's own colour, the part to watch in the brand colour, light and dark from one source. Its motion+// is the object working: the drum plays one full turn, the teeth lift and drop, the air brake spins to a blur.+// One drum turn is the whole loop, so it repeats without a seam; frame 0 is the rest pose a reduced-motion+// visitor sees, so it is composed as the hero frame.+import type { Ctx, Env } from "./core";+import type { Film } from "./film";+import { Cam, paintAll, setHand, setPalette, flatHand, hand, freshPen, rrect } from "./mechanismKit";+import { isometricHand } from "./mechanismHands";+import { parts, playing, homePoints, MOVE, REV } from "./mechanism";+import { PLACEMENTS, fitBox, pagePalette, type Colour } from "./assetKit";++const FPS = 30, N = Math.round(REV * FPS), P = PLACEMENTS.heroRight;+// the fan turns nine times a drum turn; a trail of about a fifth of a second of its travel reads as speed+const BLUR = ((2 * Math.PI * 9) / REV) * 0.2;++export const heroOn = (title: string, paper: string, accent: Colour, colours: Record<string, Colour> = {}): Film => {+ const CAM = Cam.fit(36, 30, homePoints, fitBox(P)), palette = pagePalette({ paper, accent, colours });+ const draw = (ctx: Ctx, f: number, env: Env) => {+ ctx.setTransform(env.scale, 0, 0, env.scale, 0, 0); freshPen(ctx);+ ctx.fillStyle = paper; ctx.fillRect(0, 0, P.W, P.H);+ setHand(isometricHand(paper)); setPalette(palette);+ try {+ const s = playing((2 * Math.PI * f) / N, BLUR);+ hand().shadow?.(ctx, rrect(-3, 4.5, 76, 44.5, 3).map(([x, y]) => CAM.p([x, y, -9])), 1);+ paintAll(ctx, CAM, parts(CAM, s), MOVE, s.shares);+ } finally { setPalette(null); setHand(flatHand()); freshPen(ctx); }+ };+ return {+ // calm by design: site art beside a headline must not pull the eye off it. The box works (drum, teeth,+ // key, air brake) at about 0.2% of the frame a moment, under the film floor, so it is declared, not padded+ meta: { title, W: P.W, H: P.H, fps: FPS, bpm: 100, durationFrames: N, kind: "loop", poster: 0, holds: [[1, N, "site hero: calm by design, the machine working is the only motion"]] },+ assets: { images: {} },+ shots: [{ id: "hero", start: 0, end: N, draw }],+ };+};++/** the light page: a warm off-white site, a vermilion brand */+export const siteHero = heroOn("Site hero · music box on a light page", "#faf7f2", "#e4572e");diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/siteHeroDark.ts b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/siteHeroDark.tsnew file mode 100644index 0000000..bfc40c5--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/canvas-core/siteHeroDark.ts@@ -0,0 +1,4 @@+// The site hero from the same source on a dark page: a blue brand, the plinth in walnut.+import { heroOn } from "./siteHero";++export const siteHeroDark = heroOn("Site hero · music box on a dark page", "#12151f", "#3d7bff", { wood: "#7a5536" });diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-siteHero.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-siteHero.tsnew file mode 100644index 0000000..a186064--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-siteHero.ts@@ -0,0 +1,4 @@+import { siteHero } from "../canvas-core/siteHero";+import { mountFilm } from "./page";++mountFilm(siteHero);diff --git a/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-siteHeroDark.ts b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-siteHeroDark.tsnew file mode 100644index 0000000..327b2f6--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/src/hosts/page-siteHeroDark.ts@@ -0,0 +1,4 @@+import { siteHeroDark } from "../canvas-core/siteHeroDark";+import { mountFilm } from "./page";++mountFilm(siteHeroDark);diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/assetKit.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/assetKit.test.tsnew file mode 100644index 0000000..a371bef--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/test/assetKit.test.ts@@ -0,0 +1,47 @@+// ASSET KIT TESTS. Site art's claims: the colour maths round-trips, a brand ramp steps light to dark in+// its own hue, a page palette keeps every material's light order on a light page and on a dark one, the+// brand lands only on the part to watch, and a placement's art region never overlaps its headline zone.+// node tools/test.mjs assetKit+import { toLab, fromLab, rampFrom, pagePalette, isDark, PLACEMENTS, fitBox } from "../src/canvas-core/assetKit";+import type { Material } from "../src/canvas-core/mechanismKit";++export const name = "assetKit";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const L = (h: string) => toLab(h)[0], hue = (h: string) => { const [, a, b] = toLab(h); return Math.atan2(b, a); };+ const near = (a: string, b: string) => { const x = parseInt(a.slice(1), 16), y = parseInt(b.slice(1), 16); return [16, 8, 0].every((s) => Math.abs(((x >> s) & 255) - ((y >> s) & 255)) <= 1); };++ // 1. colour maths+ ok(["#000000", "#ffffff", "#e4572e", "#3d7bff", "#12151f", "#faf7f2"].every((h) => near(fromLab(toLab(h)), h)), "OKLab round-trips to the same hex");+ ok(Math.abs(L("#ffffff") - 1) < 1e-3 && L("#000000") < 1e-3, "white is lightness 1, black 0");+ ok(/^#[0-9a-f]{6}$/.test(fromLab([0.7, 0.4, 0.4])), "a colour outside sRGB gives up chroma and still comes back as a hex");+ ok(isDark("#12151f") && !isDark("#faf7f2"), "a navy page is dark, an off-white page is light");++ // 2. a brand ramp: five tones, dark to light, in the brand's own hue, in either theme+ for (const dark of [false, true]) for (const hex of ["#e4572e", "#3d7bff", "#2a9d5c"]) {+ const r = rampFrom(hex, dark), ls = r.ramp.map(L);+ ok(ls.every((v, i) => !i || v > ls[i - 1] + 0.03), `${hex} ${dark ? "dark" : "light"}: the ramp steps up in lightness (${ls.map((v) => v.toFixed(2)).join(" ")})`);+ ok(r.ramp.every((c) => Math.abs(hue(c) - hue(hex)) < 0.12), `${hex} ${dark ? "dark" : "light"}: every tone keeps the brand's hue`);+ }+ ok(L(rampFrom("#e4572e", true).ramp[4]) < 0.85, "on a dark page the brand's lit top does not glare");++ // 3. a page palette keeps light order and puts the brand only on the part to watch+ const zinc: Material = { name: "zinc", ramp: ["#a9a69f", "#bdbab3", "#cfccc4", "#dedbd3", "#f4f1ea"], ink: "#232227", seam: "#8a877f", pigment: "#8d8b86" };+ const watch: Material = { ...zinc, name: "accent", accent: true, pigment: "#d0502a" };+ for (const paper of ["#faf7f2", "#12151f", "#f0f4ff"]) {+ const p = pagePalette({ paper, accent: "#3d7bff" }), z = p(zinc), ls = z.ramp.map(L);+ ok(ls.every((v, i) => !i || v >= ls[i - 1]), `on ${paper}: zinc keeps its light order`);+ ok(isDark(paper) ? ls[0] > L(paper) : ls[4] <= L(paper) + 0.06, `on ${paper}: parts sit ${isDark(paper) ? "above" : "at or below"} the page`);+ ok(!near(p(watch).pigment!, z.pigment!) && Math.abs(hue(p(watch).pigment!) - hue("#3d7bff")) < 0.12, `on ${paper}: the part to watch takes the brand`);+ ok(near(p({ ...zinc }).ramp[2], z.ramp[2]), `on ${paper}: a plain part does not`);+ }+ const ink = pagePalette({ paper: "#faf7f2", colours: { zinc: { hex: "#e4572e", mode: "ink" } } })(zinc);+ ok(Math.abs(hue(ink.ink) - hue("#e4572e")) < 0.12 && near(ink.ramp[2], pagePalette({ paper: "#faf7f2" })(zinc).ramp[2]), "ink mode colours the lines and leaves the body neutral");+ ok(near(pagePalette({ paper: "#f3f0e8" })(zinc).ramp[2], zinc.ramp[2]), "on the kit's own paper nothing moves");++ // 4. placements+ for (const [id, p] of Object.entries(PLACEMENTS)) {+ const [x0, y0, x1, y1] = fitBox(p), s = p.safe;+ ok(x0 >= 0 && y0 >= 0 && x1 <= p.W && y1 <= p.H && x1 > x0 && y1 > y0, `${id}: the fit box lies inside the canvas`);+ if (s) ok(x1 <= s.x || x0 >= s.x + s.w || y1 <= s.y || y0 >= s.y + s.h, `${id}: the art never overlaps the headline zone`);+ }+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/delivery.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/delivery.test.tsnew file mode 100644index 0000000..849f9f0--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/test/delivery.test.ts@@ -0,0 +1,42 @@+// DELIVERY TESTS. The whole film mix lands on its loudness target under the -1 dBTP ceiling, a quiet+// effects-only film is brought up instead of shipping at -27 LUFS, the limiter's work is capped (the gain+// gives way and says so), and "none" leaves the mix alone.+// node tools/test.mjs delivery+import { deliver, targetOf } from "../src/canvas-core/music/delivery";+import { loudness, truePeak } from "../src/canvas-core/music/meter";+import { mixSfx } from "../src/canvas-core/music/sfxMix";+// @ts-ignore: a plain ES module shared with the tools+import { filmShape } from "../tools/filmshape.mjs";++export const name = "delivery";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const sr = 48000, n = sr * 4;+ const tone = (amp: number, hits = false) => { const L = new Float32Array(n), R = new Float32Array(n); for (let i = 0; i < n; i++) { const t = i / sr, h = hits ? (i % (sr / 2) < 200 ? 0.9 : 0) : 0, v = amp * Math.sin(2 * Math.PI * 220 * t) * (0.6 + 0.4 * Math.sin(2 * Math.PI * 0.5 * t)) + h * Math.sin(2 * Math.PI * 3000 * t); L[i] = v; R[i] = v * 0.95; } return [L, R] as [Float32Array, Float32Array]; };++ for (const mode of ["gentle", "dense"] as const) {+ const [L, R] = tone(0.01), d = deliver(L, R, sr, mode);+ ok(Math.abs(d.lufs - targetOf(mode)) <= 0.5 && d.dbtp <= -1 + 1e-6, `${mode}: a quiet mix lands on ${targetOf(mode)} LUFS (${d.lufs.toFixed(2)}) under -1 dBTP (${d.dbtp.toFixed(2)})`);+ }+ const [L2, R2] = tone(0.002, true), d2 = deliver(L2, R2, sr, "gentle");+ ok(d2.limitDb <= 4 + 0.1 && d2.dbtp <= -1 + 1e-6, `sharp hits over near silence: the limiter takes at most 4 dB (${d2.limitDb.toFixed(2)})`);+ ok(d2.shortLu < 0.1 || d2.limitDb > 3.8, `and uses its allowance before falling short (${d2.limitDb.toFixed(2)} dB limited, ${d2.shortLu.toFixed(2)} LU short)`);+ ok(Math.abs(d2.shortLu - Math.max(0, -16 - d2.lufs)) < 1e-9, `and any shortfall is reported (${d2.shortLu.toFixed(2)} LU short)`);+ const [L3, R3] = tone(0.3), before = L3.slice(), d3 = deliver(L3, R3, sr, "none");+ ok(d3.gainDb === 0 && L3.every((v, i) => v === before[i]), "none leaves the mix untouched");+ ok(Math.abs(loudness(tone(0.01), sr).integrated - loudness(tone(0.01), sr).integrated) < 1e-12, "the master is deterministic in, deterministic out");++ // an effects-only film used to ship wherever its cues fell; now it is delivered at the gentle target+ const fx = mixSfx(null, { fps: 30, frames: 120, cues: [{ frame: 10, kind: "tick" }, { frame: 40, kind: "pop" }, { frame: 80, kind: "impact" }] } as never, sr);+ ok(fx.delivered !== undefined && fx.dbtp <= -1 + 1e-6, `effects-only mix: delivered (${fx.lufs.toFixed(1)} LUFS, ${fx.dbtp.toFixed(2)} dBTP, limiter ${fx.limiterDb.toFixed(1)} dB)`);+ const old = mixSfx(null, { fps: 30, frames: 120, master: "none", cues: [{ frame: 10, kind: "tick" }, { frame: 40, kind: "pop" }, { frame: 80, kind: "impact" }] } as never, sr);+ ok(Math.abs(fx.lufs + 16) <= 0.5, `on target, where the old peak-only master left it wherever its cues fell (${old.lufs.toFixed(1)} LUFS)`);+ void truePeak;++ // between its cues an effects-only film sits on room tone, never on digital silence+ const sparse = { fps: 30, frames: 240, cues: [{ frame: 6, kind: "tick" }, { frame: 150, kind: "impact" }] } as never;+ const bedded = mixSfx(null, sparse, sr), bare = mixSfx(null, { ...(sparse as object), bed: false } as never, sr);+ ok(filmShape(bare.L, bare.R, sr).problems.some((p: { kind: string }) => p.kind === "hole"), "without a bed, two cues 5 s apart leave a hole");+ ok(!filmShape(bedded.L, bedded.R, sr).problems.some((p: { kind: string }) => p.kind === "hole"), "with room tone the hole is gone");+ let c = 0, l2 = 0, r2 = 0; for (let i = sr; i < 3 * sr; i++) { c += bedded.L[i] * bedded.R[i]; l2 += bedded.L[i] ** 2; r2 += bedded.R[i] ** 2; }+ ok(c / Math.sqrt(l2 * r2) > 0.7, `room tone is nearly mono, so a phone keeps it (correlation ${(c / Math.sqrt(l2 * r2)).toFixed(2)})`);+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/filmshape.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/filmshape.test.tsnew file mode 100644index 0000000..dca4263--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/test/filmshape.test.ts@@ -0,0 +1,20 @@+// FILM SHAPE TESTS. A finished film's sound starts with the picture, never drops out, and ends with it;+// a silence the film declares in meta.quiet is not a fault.+// node tools/test.mjs filmshape+// @ts-ignore: a plain ES module shared with the tools+import { filmShape } from "../tools/filmshape.mjs";++export const name = "filmshape";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const sr = 8000, film = (secs: number, on: (t: number) => boolean) => { const n = sr * secs, L = new Float32Array(n), R = new Float32Array(n); for (let i = 0; i < n; i++) { const t = i / sr, v = on(t) ? 0.2 * Math.sin(2 * Math.PI * 330 * t) : 0; L[i] = v; R[i] = v; } return [L, R] as const; };+ const kinds = (r: ReturnType<typeof filmShape>) => r.problems.map((p: { kind: string }) => p.kind).join(",");+ ok(kinds(filmShape(...film(6, () => true), sr)) === "", "sound from start to end: a finished shape");+ ok(kinds(filmShape(...film(6, (t) => t > 1.2), sr)) === "late start", "a film that starts 1.2 s late is caught");+ const dead = filmShape(...film(16, (t) => t < 5.4), sr);+ ok(kinds(dead) === "dead end" && Math.abs(dead.endS - 10.6) < 0.15, `sound that stops at 5.4 s of 16 is a dead end (${dead.endS.toFixed(1)} s)`);+ const hole = filmShape(...film(8, (t) => t < 3.1 || t > 6.4), sr);+ ok(kinds(hole) === "hole" && Math.abs(hole.holeS - 3.3) < 0.15, `a 3.3 s hole in the middle is caught (${hole.holeS.toFixed(1)} s)`);+ ok(kinds(filmShape(...film(8, (t) => t < 3.1 || t > 3.3), sr)) === "", "a 0.2 s breath is not a hole");+ ok(kinds(filmShape(...film(8, (t) => t < 3.1 || t > 4.0), sr, { fps: 30, quiet: [[90, 123, "stop-down before the reveal"]] })) === "", "a declared stop-down is not a fault");+ ok(kinds(filmShape(...film(4, () => false), sr)) === "silent", "a silent film is caught");+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/mechanism.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/mechanism.test.tsindex 5523d22..7fccd5c 100644--- a/plugins/anidoodle/skills/anidoodle/engine/test/mechanism.test.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/test/mechanism.test.ts@@ -2,7 +2,7 @@// light ladder is monotone, the springs are exact closed forms, an exploded view staggers out and folds// back last-out-first-home, hatching stays inside its shape, and the music box's words come from its pins.// node tools/test.mjs mechanism-import { Cam, level, springAt, sharesAt, type ExplodePlan, hand, flatHand } from "../src/canvas-core/mechanismKit";+import { Cam, level, springAt, sharesAt, type ExplodePlan, hand, flatHand, spin } from "../src/canvas-core/mechanismKit";import { Iso } from "../src/canvas-core/isometricKit";import { hatchSegs } from "../src/canvas-core/mechanismHands";import { play, PLAN, REV } from "../src/canvas-core/mechanism";@@ -64,4 +64,9 @@ export const run = (ok: (cond: boolean, label: string) => void) => {ok(loop.read === first.read && loop.bend.every((v, i) => near(v, first.bend[i], 0.05)), "the drum's story repeats every turn");ok(REV > 0 && hand().id === "flat", "the kit's default hand is the plain reference hand");void flatHand;++ // 7. spin: a slow turn draws the blades once; a fast one trails fainter copies behind, against the travel+ const calls = (sweep: number) => { const a: number[] = []; spin(1, sweep, (ang) => a.push(ang)); return a; };+ ok(calls(0).length === 1 && calls(0)[0] === 1, "a slow turn draws only the blades");+ const fast = calls(1.2); ok(fast.length === 5 && fast[fast.length - 1] === 1 && fast.slice(0, -1).every((v) => v < 1), `a fast turn trails ${fast.length - 1} copies behind the blades, drawn first`);};diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/recordingWidth.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/recordingWidth.test.tsnew file mode 100644index 0000000..7027800--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/test/recordingWidth.test.ts@@ -0,0 +1,23 @@+// RECORDING WIDTH TESTS. A stereo recording whose sides are out of phase in the body of the sound is+// narrowed when its bank is registered, so a mono fold keeps it; the air above 2 kHz stays wide; a mono+// recording and a second registration are left alone.+// node tools/test.mjs recordingWidth+import { registerBank, clearBanks, type SampleBank } from "../src/canvas-core/music/sampler";++export const name = "recordingWidth";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const sr = 48000, n = sr, tone = (f: number, ph: number) => Float32Array.from({ length: n }, (_, i) => 0.3 * Math.sin(2 * Math.PI * f * (i / sr) + ph));+ const corr = (a: Float32Array, b: Float32Array) => { let c = 0, x = 0, y = 0; for (let i = sr / 4; i < n; i++) { c += a[i] * b[i]; x += a[i] ** 2; y += b[i] ** 2; } return c / Math.sqrt(x * y); };+ const zone = (ch: number) => ({ file: `z${ch}.flac`, midi: 60, layer: 1, rr: 1, frames: n, channels: ch, peakDb: -10, rmsDb: -20, sha256: "a".repeat(64) });+ const bank = (chs: Float32Array[]): SampleBank => ({ entry: { title: "t", source: "s", license: "CC0", kind: "struck", range: [48, 72], layers: 1, damped: false, zones: [zone(chs.length)] }, zones: [{ zone: zone(chs.length), channels: chs }] });+ clearBanks();+ const low = registerBank("t.low", bank([tone(500, 0), tone(500, Math.PI * 0.85)])).zones[0].channels;+ ok(corr(tone(500, 0), tone(500, Math.PI * 0.85)) < -0.8 && corr(low[0], low[1]) > 0.3, `a 500 Hz body recorded out of phase (${corr(tone(500, 0), tone(500, Math.PI * 0.85)).toFixed(2)}) is narrowed until a mono fold keeps it (${corr(low[0], low[1]).toFixed(2)})`);+ const high = registerBank("t.high", bank([tone(6000, 0), tone(6000, Math.PI / 2)])).zones[0].channels;+ ok(Math.abs(corr(high[0], high[1])) < 0.1, `the air above 2 kHz keeps its width (${corr(high[0], high[1]).toFixed(2)})`);+ const mono = tone(500, 0), m = registerBank("t.mono", bank([mono])).zones[0].channels;+ ok(m.length === 1 && m[0] === mono, "a mono recording is left alone");+ const again = registerBank("t.again", { ...bank([low[0], low[1]]) }).zones[0].channels;+ ok(again[0] === low[0], "a recording already narrowed is not narrowed twice");+ clearBanks();+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/sfxHarsh.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/sfxHarsh.test.tsindex 624cfb8..c9bfd8e 100644--- a/plugins/anidoodle/skills/anidoodle/engine/test/sfxHarsh.test.ts+++ b/plugins/anidoodle/skills/anidoodle/engine/test/sfxHarsh.test.ts@@ -57,11 +57,14 @@ export const run = (ok: (cond: boolean, label: string) => void) => {message = ""; try { mixSfx(null, { ...plan, harsh: harsh as SfxHarshOptions }, sr); } catch (e) { message = (e as Error).message; }ok(/harsh\./.test(message), `invalid harsh option rejected: ${JSON.stringify(harsh)}`);}+ // Plan 2 re-captured in 0.9.0, when the impact boom's sub tail was shortened (0.6 to 0.38 s decay):+ // it rang at 44 Hz for nearly 5 s and ate the headroom. Plans 0 and 1 are untouched.// Captured from production sources at c1beddfe4264a34d12531dbe931acef611fb0a02,// loaded by git show and bundled with these fixtures before the mixer was edited.- const hashes = ["5db7c646b1e61b0016c5dd8a114e875f6cedbaed17f6b702a225ba2dcc187a85", "3064c924f76acb857c509a5c294cf043380451d544fda0b5372ce06d33ef133a", "3a42c3f453a9a1a0285bd2287bc9874e6e330fc3bd6baa263587e10443eaa94e"];+ const hashes = ["5db7c646b1e61b0016c5dd8a114e875f6cedbaed17f6b702a225ba2dcc187a85", "3064c924f76acb857c509a5c294cf043380451d544fda0b5372ce06d33ef133a", "f2fb798441ecf453b18de3ee2c849810e6fd56f4eaa14fd2002600985fb189f6"];const frozen = frozenPlans(sr);- frozen.plans.forEach((p, i) => { const m = mixSfx(frozen.music, p, sr), f = filmSfx(() => frozen.music, p)(sr);+ // the old peak-only master stays bit-identical when asked for; the loudness master is tested in delivery.test.ts+ frozen.plans.forEach((p0, i) => { const p = { ...p0, master: "none" as const }, m = mixSfx(frozen.music, p, sr), f = filmSfx(() => frozen.music, p)(sr);ok(hash(m.L, m.R) === hashes[i] && hash(...f) === hashes[i], `launch cue plan ${i}: mixSfx and filmSfx match base SHA-256 ${hashes[i]}`);});for (const row of survey()) ok(row.ok, `${row.kind}:${row.variant} over ${row.context}: default gain passes the measured default caps`);diff --git a/plugins/anidoodle/skills/anidoodle/engine/test/soundcheck.test.ts b/plugins/anidoodle/skills/anidoodle/engine/test/soundcheck.test.tsnew file mode 100644index 0000000..47dd464--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/test/soundcheck.test.ts@@ -0,0 +1,101 @@+// SOUNDCHECK TESTS. Each fault the scorecard exists to catch, built on purpose in code (a hole, a+// dead tail, a late start, a decorrelated pair, a sub-heavy mix, a boxy mix, a quiet master, a cut+// ending), and each must show up in its own metric, with a fix that names the time or the band.+import { analyze, evaluate, fixFirst, visualEvents, visualSync, buildProfile, profileFrom, grade, DEFAULT_PROFILE } from "../src/canvas-core/music/soundcheck";+import { loudness } from "../src/canvas-core/music/meter";++export const name = "soundcheck";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const sr = 48000;+ // mulberry32: a plain LCG's interleaved outputs are correlated per band (it read as a -0.99 low-band correlation)+ let seed = 9; const rnd = () => { seed = (seed + 0x6d2b79f5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return (((t ^ (t >>> 14)) >>> 0) / 4294967296) * 2 - 1; };+ /** A plucked chord every 0.25 s over a soft pad: music-like, steady, correlated (the same in both ears). */+ const music = (secs: number, { from = 0, to = secs, amp = 0.2 } = {}) => {+ const n = Math.round(secs * sr), L = new Float32Array(n), R = new Float32Array(n);+ for (let i = Math.round(from * sr); i < Math.min(n, Math.round(to * sr)); i++) {+ const t = i / sr, ph = t % 0.25, env = Math.exp(-ph * 10);+ const v = amp * (0.5 * Math.sin(2 * Math.PI * 330 * t) + 0.3 * Math.sin(2 * Math.PI * 495 * t) * env + 0.3 * Math.sin(2 * Math.PI * 1320 * t) * env + 0.15 * Math.sin(2 * Math.PI * 110 * t) + 0.05 * rnd());+ L[i] = v; R[i] = v;+ }+ return [L, R] as [Float32Array, Float32Array];+ };+ const at = (L: Float32Array, R: Float32Array, opts?: { allow?: [number, number][] }) => analyze(L, R, sr, opts).measures;+ const row = (m: ReturnType<typeof at>, k: string) => evaluate(m).find((r) => r.key === k)!;++ // a clean, steady, centred mix: no holes, no tail, sound from frame 0, nothing lost in mono+ const clean = at(...music(6));+ ok(clean.firstSound === 0 && clean.insideGap === 0 && clean.endSilence < 0.06, `clean mix: first sound ${clean.firstSound} s, longest hole ${clean.insideGap} s, end silence ${clean.endSilence.toFixed(2)} s`);+ ok(Math.abs(clean.monoLoss) < 0.1 && clean.bodyCorr > 0.99 && clean.corr > 0.99, `identical channels fold to mono with ${clean.monoLoss.toFixed(2)} dB extra loss, 150-2k correlation ${clean.bodyCorr.toFixed(2)}`);+ ok(["insideGap", "endSilence", "firstSound", "bodyCorr", "monoLoss", "sub"].every((k) => row(clean, k).status === "PASS"), "clean mix passes the shape, stereo and sub checks");++ // the loudness number agrees with the meter, and a -27 LUFS master fails with the gain it needs+ const [qL, qR] = music(6, { amp: 0.02 }), q = at(qL, qR), ref = loudness([qL, qR], sr).integrated;+ ok(Math.abs(q.lufs - ref) < 1e-9, `integrated loudness is meter.ts's own (${q.lufs.toFixed(2)} LUFS)`);+ ok(row(q, "lufs").status === "FAIL" && /LU under the web target/.test(row(q, "lufs").fix ?? ""), `a ${q.lufs.toFixed(1)} LUFS master fails: "${row(q, "lufs").fix?.slice(0, 60)}..."`);+ const gain = Math.pow(10, (-14 - ref) / 20), [tL, tR] = [qL.map((x) => x * gain), qR.map((x) => x * gain)], tgt = at(tL, tR);+ ok(Math.abs(tgt.lufs + 14) < 0.05 && row(tgt, "lufs").status === "PASS", `mastered to ${tgt.lufs.toFixed(2)} LUFS: PASS`);++ // a 1 s hole at 2.0 s: caught, timed, and its fix names the time; --allow over it clears it+ const [hL, hR] = music(6); for (let i = 2 * sr; i < 3 * sr; i++) { hL[i] = 0; hR[i] = 0; }+ const hole = at(hL, hR);+ ok(Math.abs(hole.insideGap - 1) <= 0.06 && Math.abs((hole.insideGapAt ?? 0) - 2) <= 0.06, `a 1 s hole at 2.0 s reads ${hole.insideGap.toFixed(2)} s at ${hole.insideGapAt?.toFixed(2)} s`);+ const hf = fixFirst(evaluate(hole)).find((r) => r.key === "insideGap");+ ok(row(hole, "insideGap").status === "FAIL" && /1\.0 s hole at 0:02\.0/.test(hf?.fix ?? ""), `the fix says where: "${hf?.fix?.slice(0, 40)}..."`);+ ok(!fixFirst(evaluate(hole)).some((r) => r.key === "arcDip"), "the arc dip inside that hole is the same fault: one fix, not two");+ ok(at(hL, hR, { allow: [[1.9, 3.1]] }).insideGap === 0, "a declared stop-down (--allow 1.9:3.1) is not a hole");+ const [sL, sR] = music(6); for (let i = 2 * sr; i < 2.15 * sr; i++) { sL[i] = 0; sR[i] = 0; }+ ok(row(at(sL, sR), "insideGap").status === "PASS", `a 0.15 s breath is not a hole (${at(sL, sR).insideGap.toFixed(2)} s)`);++ // a dead tail and a late start+ const tail = at(...music(6, { to: 3 }));+ ok(Math.abs(tail.endSilence - 3) <= 0.06 && row(tail, "endSilence").status === "FAIL" && /from 0:03\.0/.test(row(tail, "endSilence").fix ?? ""), `3 s of dead tail: ${tail.endSilence.toFixed(2)} s from ${tail.endSilenceFrom.toFixed(2)} s, FAIL`);+ const late = at(...music(6, { from: 1.5 }));+ ok(Math.abs((late.firstSound ?? 0) - 1.5) <= 0.06 && row(late, "firstSound").status === "FAIL", `sound starting at 1.5 s: first sound ${late.firstSound} s, FAIL`);++ // a cut ending against a faded one+ const cut = at(...music(4));+ const [fL, fR] = music(4); for (let i = 3.5 * sr; i < 4 * sr; i++) { const g = Math.max(0, 1 - (i - 3.5 * sr) / (0.45 * sr)); fL[i] *= g; fR[i] *= g; }+ ok(row(cut, "tailLu").status === "FAIL" && row(at(fL, fR), "tailLu").status === "PASS", `a film that stops mid-note fails the tail (${cut.tailLu.toFixed(1)} LU); faded, it passes`);++ // a decorrelated pair: independent noise in each ear+ const n = 4 * sr, dL = new Float32Array(n), dR = new Float32Array(n); for (let i = 0; i < n; i++) { dL[i] = 0.1 * rnd(); dR[i] = 0.1 * rnd(); }+ const dec = at(dL, dR), df = fixFirst(evaluate(dec));+ ok(Math.abs(dec.bodyCorr) < 0.1 && Math.abs(dec.monoLoss - 3) < 0.3, `decorrelated pair: 150-2k correlation ${dec.bodyCorr.toFixed(2)}, mono loses ${dec.monoLoss.toFixed(2)} dB past the expected 3`);+ ok(row(dec, "bodyCorr").status === "FAIL" && row(dec, "monoLoss").status === "FAIL" && df.filter((r) => ["bodyCorr", "monoLoss", "corr", "sideMid"].includes(r.key)).length === 1 && /below 2 kHz/.test(df.find((r) => r.key === "bodyCorr")?.fix ?? ""), "it fails, and the four stereo numbers make one fix: narrow the width below 2 kHz");+ // decorrelated only in the body: a 600 Hz tone a quarter-turn apart, a centred 5 kHz tone+ const bL = new Float32Array(n), bR = new Float32Array(n); for (let i = 0; i < n; i++) { const t = i / sr, c = 0.1 * Math.sin(2 * Math.PI * 5000 * t); bL[i] = 0.2 * Math.sin(2 * Math.PI * 600 * t) + c; bR[i] = 0.2 * Math.cos(2 * Math.PI * 600 * t) + c; }+ const body = at(bL, bR);+ ok(Math.abs(body.bodyCorr) < 0.1 && body.bandCorr.presence > 0.95, `body-only decorrelation is seen per band (150-2k ${body.bodyCorr.toFixed(2)}, presence ${body.bandCorr.presence.toFixed(2)})`);++ // a sub-heavy mix and a boxy one, each with a band-specific fix+ const [uL, uR] = music(4, { amp: 0.05 }); for (let i = 0; i < uL.length; i++) { const v = 0.4 * Math.sin(2 * Math.PI * 40 * (i / sr)); uL[i] += v; uR[i] += v; }+ const sub = at(uL, uR);+ ok(sub.bands.sub > -3 && row(sub, "sub").status === "FAIL" && /30-40 Hz/.test(row(sub, "sub").fix ?? ""), `sub-heavy: ${sub.bands.sub.toFixed(1)} dB of the energy under 60 Hz, FAIL, "high-pass ... 30-40 Hz"`);+ ok(clean.bands.sub < -20, `the clean mix keeps ${clean.bands.sub.toFixed(1)} dB under 60 Hz`);+ const [xL, xR] = music(4, { amp: 0.03 }); for (let i = 0; i < xL.length; i++) { const v = 0.3 * Math.sin(2 * Math.PI * 630 * (i / sr)); xL[i] += v; xR[i] += v; }+ const box = at(xL, xR);+ ok(row(box, "lowmid").status === "FAIL" && box.peakHz.lowmid === 630 && /630 Hz/.test(row(box, "lowmid").fix ?? ""), `boxy: low-mid ${box.bands.lowmid.toFixed(1)} dB, loudest third-octave ${box.peakHz.lowmid} Hz named in the fix`);++ // a stop-down: a steady bed that dips 15 dB for 0.4 s and snaps back+ const [pL, pR] = music(6); for (let i = 3 * sr; i < 3.4 * sr; i++) { pL[i] *= 0.18; pR[i] *= 0.18; }+ const sd = at(pL, pR);+ ok(sd.stopDowns.length === 1 && Math.abs(sd.stopDowns[0].at - 3) < 0.1, `a 0.4 s, 15 dB dip reads as one stop-down at ${sd.stopDowns[0]?.at.toFixed(2)} s`);++ // the profile: ranges grade PASS / WARN / FAIL, and a built profile moves taste ranges but never the delivery limits+ ok(grade(-14, { min: -16, max: -13, tol: 1 }) === "PASS" && grade(-16.5, { min: -16, max: -13, tol: 1 }) === "WARN" && grade(-18, { min: -16, max: -13, tol: 1 }) === "FAIL" && grade(5, undefined) === "INFO", "grade: inside PASS, within tolerance WARN, beyond FAIL, no range INFO");+ const built = buildProfile("test", [{ file: "a", measures: clean }, { file: "b", measures: tgt }]), prof = profileFrom(built);+ ok(built.metrics.lufs.min <= built.metrics.lufs.median && built.metrics.lufs.median <= built.metrics.lufs.max && built.from.length === 2, `built profile: lufs ${built.metrics.lufs.min}..${built.metrics.lufs.max}, median ${built.metrics.lufs.median}`);+ ok(JSON.stringify(prof.ranges.endSilence) === JSON.stringify(DEFAULT_PROFILE.ranges.endSilence) && prof.ranges.lufs.min !== DEFAULT_PROFILE.ranges.lufs.min && prof.ranges.presence !== undefined, "a built profile sets the taste ranges (loudness, bands) and keeps the hard ones (end silence)");++ // picture against sound+ const changed = Array.from({ length: 300 }, (_, i) => (i === 30 || i === 120 || i === 210 ? 0.5 : 0.01));+ const ev = visualEvents(changed, 30);+ ok(ev.length === 3 && Math.abs(ev[0] - 1) < 1e-9, `three cuts in a slow-changing picture read as events at ${ev.map((e) => e.toFixed(2)).join(", ")} s`);+ const vs = visualSync([1, 4, 7], [1.03, 5.5, 6.95], 10);+ ok(Math.abs(vs.share - 2 / 3) < 1e-9 && vs.unanswered.length === 1 && vs.unanswered[0] === 4 && vs.medianOffsetMs === -10, `2 of 3 events have an onset within 100 ms (+30 and -50 ms, median ${vs.medianOffsetMs}); the one at 4 s has none`);+ ok(Number.isFinite(vs.chance) && vs.chance <= 2 / 3, `chance baseline from shifted events: ${Math.round(vs.chance * 100)} %`);++ // silence: everything fails cleanly, never NaN-passes+ const z = at(new Float32Array(sr * 2), new Float32Array(sr * 2)), zr = evaluate(z);+ ok(z.silent && zr.find((r) => r.key === "lufs")!.status === "FAIL" && zr.every((r) => r.status !== "PASS" || r.value !== null), "a silent file fails loudness and passes nothing it could not measure");+};diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/filmshape.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/filmshape.mjsnew file mode 100644index 0000000..60032e0--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/filmshape.mjs@@ -0,0 +1,30 @@+// FILM SHAPE. Whether a film's sound has the shape of a finished piece: it starts with the picture, it+// never drops out mid-film, and it ends with the film instead of stopping early and leaving dead air.+// Measured in 100 ms blocks against the mix's own body level (the median of its active blocks), so a+// quiet film and a loud one are judged alike. A silence the film means (a stop-down before a reveal, a+// held breath) is declared in meta.quiet as [fromFrame, toFrame, reason] and is not a fault.+// import { filmShape } from "./filmshape.mjs"; filmShape(L, R, sr, { fps, quiet })+export const SHAPE = Object.freeze({ firstS: 0.5, holeS: 0.25, endS: 0.5, quietDb: 30, bodyDb: 20 });++export const filmShape = (L, R, sr, o = {}) => {+ const B = Math.round(sr * 0.1), nb = Math.floor(L.length / B), lv = new Float64Array(nb);+ for (let b = 0; b < nb; b++) { let s = 0; for (let i = b * B; i < (b + 1) * B; i++) s += L[i] * L[i] + R[i] * R[i]; lv[b] = 10 * Math.log10(s / (2 * B) + 1e-20); }+ const active = [...lv].filter((v) => v > -70).sort((a, b) => a - b), body = active.length ? active[Math.floor(active.length / 2)] : -Infinity;+ const fps = o.fps ?? 30, quiet = (o.quiet ?? []).map(([a, b]) => [a / fps, b / fps]);+ const declared = (t0, t1) => quiet.some(([a, b]) => a <= t0 + 0.05 && b >= t1 - 0.05);+ const silent = (b) => lv[b] < body - SHAPE.quietDb, problems = [];+ if (!Number.isFinite(body)) return { body, problems: [{ kind: "silent", atS: 0, durS: nb / 10, msg: "the whole film is silent" }], firstS: NaN, endS: NaN, holeS: 0 };+ let first = 0; while (first < nb && lv[first] < body - SHAPE.bodyDb) first++;+ const firstS = first / 10; if (firstS > SHAPE.firstS && !declared(0, firstS)) problems.push({ kind: "late start", atS: 0, durS: firstS, msg: `nothing reaches body level until ${fmt(firstS)}` });+ let last = nb - 1; while (last >= 0 && silent(last)) last--;+ const endS = (nb - 1 - last) / 10; if (endS > SHAPE.endS && !declared((last + 1) / 10, nb / 10)) problems.push({ kind: "dead end", atS: (last + 1) / 10, durS: endS, msg: `the sound stops at ${fmt((last + 1) / 10)} and the picture runs ${endS.toFixed(1)} s more` });+ let holeS = 0;+ for (let b = first; b <= last; ) {+ if (!silent(b)) { b++; continue; }+ const a = b; while (b <= last && silent(b)) b++;+ const d = (b - a) / 10; holeS = Math.max(holeS, d);+ if (d > SHAPE.holeS && !declared(a / 10, b / 10)) problems.push({ kind: "hole", atS: a / 10, durS: d, msg: `a ${d.toFixed(1)} s hole at ${fmt(a / 10)}` });+ }+ return { body, problems, firstS, endS, holeS };+};+const fmt = (s) => `${Math.floor(s / 60)}:${(s % 60).toFixed(1).padStart(4, "0")}`;diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/listen.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/listen.mjsindex f8f4199..eea24c7 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tools/listen.mjs+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/listen.mjs@@ -91,7 +91,7 @@ const DARK = `--bg: #101814; --fg: #eef3ef; --panel: #18231e; --line: #33443b; -// from Google Fonts and nothing else off-box; every colour a variable, dark repeated both ways.const STYLE = ` :root {--bg: #f3f5f1; --fg: #14201b; --panel: #ffffff; --line: #c9d3cc; --accent: #0f6b52; --accent-fg: #ffffff;- --display: "Fraunces", Georgia, serif; --body: "Figtree", system-ui, sans-serif;+ --display: "Poppins", system-ui, sans-serif; --body: "Poppins", system-ui, sans-serif;}@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) { ${DARK} } }:root[data-theme="dark"] { ${DARK} }@@ -139,7 +139,7 @@ const takeCard = (t) => ` <div class="take"><audio data-piece="${esc(t.piece)}" controls preload="auto" src="${esc(t.file)}"></audio></div>`;const page = (title, intro, pieces) => `<title>${esc(title)}</title>-<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Fraunces:opsz,[email protected],600&family=Figtree:wght@400;600&display=swap">+<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap"><style>${STYLE}</style>diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/placement.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/placement.mjsnew file mode 100644index 0000000..8db5d57--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/placement.mjs@@ -0,0 +1,37 @@+// PLACEMENT. Site art has a zone the art must never enter: the headline's. This reads a rendered still+// and fails if anything (a part, a shadow, a sheen) is drawn there, then writes the picture at phone+// width so you look at it the size most visitors will.+// node tools/placement.mjs out/hero.png --W 1200 --safe 0,0,480,640 [--paper #faf7f2] [--tol 6] [--phone out/hero-390.png]+// --W is the film's logical width (meta.W); --safe is in the same units (assetKit PLACEMENTS[...].safe).+// --paper defaults to the commonest colour in the picture, which on site art is the page.+import { execFileSync } from "node:child_process";+import { existsSync } from "node:fs";+import { resolve } from "node:path";++const arg = (k, d) => { const i = process.argv.indexOf(`--${k}`); return i > 0 ? process.argv[i + 1] : d; };+const file = process.argv[2] && resolve(process.argv[2]);+if (!file || !existsSync(file)) { console.error("usage: node tools/placement.mjs <still.png> --W <logical width> --safe x,y,w,h [--paper #hex] [--tol 6] [--phone out.png]"); process.exit(2); }+const { width: w, height: h } = JSON.parse(execFileSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "json", file])).streams[0];+const raw = execFileSync("ffmpeg", ["-v", "error", "-i", file, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], { maxBuffer: w * h * 3 + 1024 });+const k = w / Number(arg("W", w)), tol = Number(arg("tol", 6));++let paper = arg("paper");+if (!paper) { const n = new Map(); for (let i = 0; i < raw.length; i += 3 * 7) { const c = (raw[i] << 16) | (raw[i + 1] << 8) | raw[i + 2]; n.set(c, (n.get(c) ?? 0) + 1); } paper = "#" + [...n].sort((a, b) => b[1] - a[1])[0][0].toString(16).padStart(6, "0"); }+const pv = parseInt(paper.slice(1), 16), pr = (pv >> 16) & 255, pg = (pv >> 8) & 255, pb = pv & 255;++let fail = false;+const safe = arg("safe");+if (safe) {+ const [sx, sy, sw, sh] = safe.split(",").map((v) => Math.round(Number(v) * k));+ let count = 0, x0 = 1e9, y0 = 1e9, x1 = -1, y1 = -1;+ for (let y = Math.max(0, sy); y < Math.min(h, sy + sh); y++) for (let x = Math.max(0, sx); x < Math.min(w, sx + sw); x++) {+ const i = (y * w + x) * 3;+ if (Math.abs(raw[i] - pr) > tol || Math.abs(raw[i + 1] - pg) > tol || Math.abs(raw[i + 2] - pb) > tol) { count++; x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y); }+ }+ fail = count > 0;+ console.log(` ${fail ? "FAIL" : "PASS"} headline zone ${safe} on ${paper}: ${count ? `${count} px of art inside, x ${(x0 / k).toFixed(0)}-${(x1 / k).toFixed(0)}, y ${(y0 / k).toFixed(0)}-${(y1 / k).toFixed(0)}` : "clean"}`);+}+const phone = arg("phone");+if (phone) { execFileSync("ffmpeg", ["-v", "error", "-y", "-i", file, "-vf", "scale=390:-1:flags=area", phone]); console.log(` phone width (390 px): ${resolve(phone)} look at it`); }+console.log(`PLACEMENT: ${fail ? "FAIL" : "PASS"}`);+process.exit(fail ? 1 : 0);diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/soundcheck.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/soundcheck.mjsnew file mode 100644index 0000000..48acb8c--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/soundcheck.mjs@@ -0,0 +1,109 @@+// SOUNDCHECK. A film-sound scorecard for an agent that cannot hear: every model-free number on a+// film's decoded mix, each held to a range, then the fixes in the order that matters, with times.+// node tools/soundcheck.mjs <film|file.mp4|file.wav> [--profile references/music/sound-profile.json]+// [--allow 3.1:3.6,...] [--video | --no-video] [--json] [--out f.json]+// node tools/soundcheck.mjs profile <files...> -o references/music/sound-profile.json [--name "drawing film"]+// Decodes what a player would (ffmpeg, stereo float at 48 kHz). The metrics are pure functions in+// src/canvas-core/music/soundcheck.ts (unit-tested on synthetic signals); visual sync reuses+// motion.mjs changedArea and is INFO only (not every picture change is meant to be a cue).+// Exit 1 on any FAIL, 2 on bad input.+import { build } from "esbuild";+import { execFileSync } from "node:child_process";+import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";+import { basename, dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { changedArea } from "./motion.mjs";+import { isMain } from "./is-main.mjs";++const here = dirname(fileURLToPath(import.meta.url)), SR = 48000;+export const loadCheck = async () => {+ const r = await build({ entryPoints: [join(here, "../src/canvas-core/music/soundcheck.ts")], bundle: true, write: false, format: "esm", platform: "neutral", target: "es2022", logLevel: "error" });+ return import("data:text/javascript;base64," + Buffer.from(r.outputFiles[0].text).toString("base64"));+};+/** A film name is out/<name>.mp4, as the other tools read it. */+export const resolveInput = (a) => { const f = resolve(/\.[a-z0-9]{2,4}$/i.test(a) ? a : `out/${a}.mp4`); if (!existsSync(f)) throw new Error(`no such file: ${f}`); return f; };+export const probe = (file) => {+ const j = JSON.parse(execFileSync("ffprobe", ["-v", "error", "-show_entries", "stream=codec_type,avg_frame_rate,width,height:format=duration", "-of", "json", file]).toString());+ const v = j.streams.find((s) => s.codec_type === "video" && s.width), a = j.streams.find((s) => s.codec_type === "audio");+ const [n, d] = (v?.avg_frame_rate ?? "0/1").split("/").map(Number);+ return { audio: !!a, video: v ? { width: v.width, height: v.height, fps: d ? n / d : 0 } : null, duration: Number(j.format?.duration) };+};+export const decode = (file) => {+ const buf = execFileSync("ffmpeg", ["-v", "error", "-i", file, "-vn", "-f", "f32le", "-acodec", "pcm_f32le", "-ac", "2", "-ar", String(SR), "pipe:1"], { maxBuffer: 1 << 30 });+ const f = new Float32Array(buf.buffer, buf.byteOffset, buf.length / 4), n = f.length / 2, L = new Float32Array(n), R = new Float32Array(n);+ for (let i = 0; i < n; i++) { L[i] = f[2 * i]; R[i] = f[2 * i + 1]; }+ return [L, R];+};+export const parseAllow = (s) => (s ? String(s).split(",").filter(Boolean).map((p) => { const [a, b] = p.split(":").map(Number); if (!(b > a)) throw new Error(`--allow wants from:to seconds, got '${p}'`); return [a, b]; }) : []);+export const loadProfile = (C, path) => {+ if (!path) return C.DEFAULT_PROFILE;+ const j = JSON.parse(readFileSync(resolve(path), "utf8"));+ return j.metrics ? C.profileFrom(j) : { ...C.DEFAULT_PROFILE, ...j, ranges: { ...C.DEFAULT_PROFILE.ranges, ...(j.ranges ?? {}) } };+};++/** Everything for one file: measures, curves, visual sync (when there is a picture and `video`), rows and the fix list. */+export const check = async (C, file, { profile, allow = [], video = "auto" } = {}) => {+ const p = probe(file);+ if (!p.audio) throw new Error(`${basename(file)} has no audio stream`);+ const [L, R] = decode(file), prof = profile ?? C.DEFAULT_PROFILE;+ const { measures, curves } = C.analyze(L, R, SR, { allow: [...allow, ...(prof.allow ?? [])] });+ let sync = null;+ if (p.video && video !== false && p.video.fps > 0) {+ const W = 160, H = Math.max(2, Math.round((W * p.video.height) / p.video.width)), changed = await changedArea(file, W, H, 4);+ const events = C.visualEvents(changed, p.video.fps);+ sync = { ...C.visualSync(events, curves.onsets, measures.durationS), times: events, fps: p.video.fps };+ }+ const rows = C.evaluate(measures, prof);+ return { file, profile: prof.name, measures, curves, sync, rows, fixes: C.fixFirst(rows), video: p.video, L, R };+};++const pad = (s, n) => String(s).padEnd(n);+export const report = (C, r) => {+ const m = r.measures, fails = r.rows.filter((x) => x.status === "FAIL").length, warns = r.rows.filter((x) => x.status === "WARN").length;+ const o = [`SOUNDCHECK ${r.file}`, ` ${m.durationS.toFixed(2)} s, profile: ${r.profile}`, ""];+ const head = !fails && !warns ? "Sound is within every range." : `${fails} fail, ${warns} warn. ${r.fixes[0] ? `Worst: ${r.fixes[0].fix.split(":")[0]}.` : ""}`;+ o.push(` ${head}`, "", ` ${pad("status", 7)}${pad("metric", 31)}${pad("value", 24)}range`);+ const graded = r.rows.filter((x) => x.status !== "INFO"), info = r.rows.filter((x) => x.status === "INFO");+ for (const x of [...graded, ...info]) o.push(` ${pad(x.status, 7)}${pad(x.label, 31)}${pad(x.text, 24)}${C.rangeText(x.range)}`);+ if (r.sync) {+ const s = r.sync, pct = (v) => (Number.isFinite(v) ? `${Math.round(v * 100)} %` : "n/a");+ o.push(` ${pad("INFO", 7)}${pad("visual events with an onset", 31)}${pad(`${pct(s.share)} of ${s.events}`, 24)}chance ${pct(s.chance)}`);+ o.push(` ${pad("INFO", 7)}${pad("median onset offset", 31)}${pad(Number.isFinite(s.medianOffsetMs) ? `${s.medianOffsetMs > 0 ? "+" : ""}${s.medianOffsetMs} ms` : "n/a", 24)}pros: -45..+75 ms`);+ if (s.unanswered.length) o.push(` ${pad("INFO", 7)}${pad("events with no sound", 31)}${s.unanswered.slice(0, 8).map(C.fmtT).join(", ")}${s.unanswered.length > 8 ? ` (+${s.unanswered.length - 8})` : ""}`);+ }+ o.push("", r.fixes.length ? "FIX FIRST" : "FIX FIRST: nothing");+ r.fixes.forEach((x, i) => o.push(` ${i + 1}. [${x.status}] ${x.fix}`));+ o.push("", "DETAIL", ` arc (LU vs integrated, 0..100 %): ${m.arc.map((v) => (v === null ? "silent" : (v > 0 ? "+" : "") + v.toFixed(1))).join(" ")}`);+ o.push(` bands (dB share): ${Object.entries(m.bands).map(([k, v]) => `${k} ${v.toFixed(1)}`).join(" ")}`);+ o.push(` band correlation: ${Object.entries(m.bandCorr).map(([k, v]) => `${k} ${Number.isFinite(v) ? v.toFixed(2) : "n/a"}`).join(" ")} 150-2k ${Number.isFinite(m.bodyCorr) ? m.bodyCorr.toFixed(2) : "n/a"}`);+ o.push(` mono fold: -${m.monoDrop.toFixed(1)} dB (3.0 expected) sample peak ${m.samplePeak.toFixed(1)} dBFS`);+ const holes = m.gaps.filter((g) => g.len >= 0.1); if (holes.length) o.push(` holes: ${holes.map((g) => `${C.fmtT(g.at)} ${g.len.toFixed(2)} s${g.allowed ? " (allowed)" : ""}`).join(", ")}`);+ o.push("", `VERDICT: ${fails ? "FAIL" : warns ? "PASS with warnings" : "PASS"}`);+ return o.join("\n");+};+/** The JSON form: no sample buffers, curves trimmed to what a reader can use. */+export const asJson = (r) => ({ file: r.file, profile: r.profile, verdict: r.rows.some((x) => x.status === "FAIL") ? "FAIL" : "PASS", measures: r.measures, sync: r.sync, rows: r.rows, fixes: r.fixes.map((x) => ({ key: x.key, status: x.status, fix: x.fix, at: x.at })), onsets: r.curves.onsets.map((t) => +t.toFixed(3)), hits: r.curves.hits });++if (isMain(import.meta.url)) {+ const argv = process.argv.slice(2), flag = (k) => argv.includes(`--${k}`), opt = (...ks) => { for (const k of ks) { const i = argv.indexOf(k); if (i >= 0) return argv[i + 1]; } return undefined; };+ const VAL = new Set(["--profile", "--out", "--allow", "-o", "--name"]), pos = argv.filter((a, i) => !a.startsWith("-") && !VAL.has(argv[i - 1]));+ const die = (msg, code = 2) => { console.error(msg); process.exit(code); };+ if (!pos.length) die("usage: node tools/soundcheck.mjs <film|file.mp4|file.wav> [--profile p.json] [--allow a:b] [--video|--no-video] [--json] [--out f.json]\n node tools/soundcheck.mjs profile <files...> -o references/music/sound-profile.json [--name \"drawing film\"]");+ const C = await loadCheck();+ try {+ if (pos[0] === "profile") {+ const out = opt("-o", "--out"); if (!out || pos.length < 2) die("profile wants films and -o <path.json>");+ const sets = [];+ for (const a of pos.slice(1)) { const f = resolveInput(a), [L, R] = decode(f); sets.push({ file: basename(f), measures: C.analyze(L, R, SR).measures }); console.log(` measured ${basename(f)}`); }+ const p = C.buildProfile(opt("--name") ?? "picked films", sets);+ mkdirSync(dirname(resolve(out)), { recursive: true }); writeFileSync(resolve(out), JSON.stringify(p, null, 1) + "\n");+ console.log(`profile of ${sets.length} film(s) -> ${out}`); for (const [k, v] of Object.entries(p.metrics)) console.log(` ${pad(k, 12)} ${v.min} .. ${v.max} median ${v.median}`);+ process.exit(0);+ }+ const file = resolveInput(pos[0]), r = await check(C, file, { profile: loadProfile(C, opt("--profile")), allow: parseAllow(opt("--allow")), video: flag("no-video") ? false : "auto" });+ const j = asJson(r);+ if (opt("--out")) { mkdirSync(dirname(resolve(opt("--out"))), { recursive: true }); writeFileSync(resolve(opt("--out")), JSON.stringify(j, null, 1) + "\n"); }+ console.log(flag("json") ? JSON.stringify(j, null, 1) : report(C, r));+ process.exit(j.verdict === "FAIL" ? 1 : 0);+ } catch (e) { die(`soundcheck: ${e.message}`); }+}diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/soundsheet.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/soundsheet.mjsnew file mode 100644index 0000000..1cfed57--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/soundsheet.mjs@@ -0,0 +1,103 @@+// SOUNDSHEET. A listening sheet for an agent that cannot hear: one PNG on one time axis with the+// picture (a frame strip), the spectrogram, the waveform, momentary and short-term loudness against+// the integrated level and the -14 LUFS target, onset ticks, salient hits, visual events, and every+// hole and the dead tail shaded. The hole, the dead tail and a late hit are visible before anyone+// listens. Same analysis as soundcheck.mjs (its verdict and first fixes head the sheet).+// node tools/soundsheet.mjs <film|file.mp4|file.wav> -o out/<name>-sound.png [--profile p.json] [--allow a:b] [--width 1600]+import { execFileSync } from "node:child_process";+import { mkdtempSync, readFileSync, rmSync, mkdirSync, existsSync } from "node:fs";+import { tmpdir } from "node:os";+import { basename, dirname, join, resolve } from "node:path";+import { detect } from "./detect.mjs";+import { loadCheck, resolveInput, check, loadProfile, parseAllow } from "./soundcheck.mjs";++const argv = process.argv.slice(2), opt = (...ks) => { for (const k of ks) { const i = argv.indexOf(k); if (i >= 0) return argv[i + 1]; } return undefined; };+const VAL = new Set(["-o", "--out", "--profile", "--allow", "--width"]), pos = argv.filter((a, i) => !a.startsWith("-") && !VAL.has(argv[i - 1]));+const die = (m) => { console.error(m); process.exit(2); };+if (!pos[0]) die("usage: node tools/soundsheet.mjs <film|file.mp4|file.wav> -o out/<name>-sound.png [--profile p.json] [--allow a:b] [--width 1600]");+const env = detect();+if (!env.pw.ok || !env.browser.ok) die(`no browser to draw the sheet in.\n playwright: ${env.report.playwright}\n browser: ${env.report.browser}\n fix: npm install, then npx playwright-core install chromium`);++let file; try { file = resolveInput(pos[0]); } catch (e) { die(e.message); }+const out = resolve(opt("-o", "--out") ?? `out/${basename(file).replace(/\.[^.]+$/, "")}-sound.png`);+const WIDTH = Number(opt("--width") ?? 1600), LEFT = 92, RIGHT = 24, PW = WIDTH - LEFT - RIGHT;+const C = await loadCheck(), r = await check(C, file, { profile: loadProfile(C, opt("--profile")), allow: parseAllow(opt("--allow")) });+const m = r.measures, dur = m.durationS, tmp = mkdtempSync(join(tmpdir(), "soundsheet-"));+const png64 = (f) => "data:image/png;base64," + readFileSync(f).toString("base64");+try {+ // the picture: ten frames, each at the middle of its tenth, so tile k sits over its own stretch of the axis+ let strip = null;+ if (r.video) {+ const K = 10, tw = Math.floor(PW / K), th = Math.max(2, 2 * Math.round((tw * r.video.height) / r.video.width / 2));+ execFileSync("ffmpeg", ["-v", "error", "-y", "-ss", String(dur / K / 2), "-i", file, "-vf", `fps=${K / dur},scale=${tw}:${th},tile=${K}x1`, "-frames:v", "1", join(tmp, "strip.png")]);+ strip = { src: png64(join(tmp, "strip.png")), w: tw * K, h: th };+ }+ // the spectrogram from ffmpeg, log frequency, both channels combined; drawn across the whole duration+ execFileSync("ffmpeg", ["-v", "error", "-y", "-i", file, "-lavfi", `showspectrumpic=s=${PW}x240:legend=0:mode=combined:fscale=log:scale=log:color=intensity:gain=2`, "-frames:v", "1", join(tmp, "spec.png")]);+ // waveform envelope: min/max of the mid per pixel column+ const env_ = []; const n = r.L.length, per = n / PW;+ for (let x = 0; x < PW; x++) { let lo = 0, hi = 0; for (let i = Math.floor(x * per); i < Math.min(n, Math.floor((x + 1) * per)); i++) { const v = 0.5 * (r.L[i] + r.R[i]); if (v < lo) lo = v; if (v > hi) hi = v; } env_.push([+lo.toFixed(4), +hi.toFixed(4)]); }+ const fails = r.rows.filter((x) => x.status === "FAIL").length, warns = r.rows.filter((x) => x.status === "WARN").length;+ const data = {+ title: basename(file), dur, I: m.lufs, verdict: fails ? `FAIL: ${fails} fail, ${warns} warn` : warns ? `PASS with ${warns} warning${warns > 1 ? "s" : ""}` : "PASS",+ stats: `${m.lufs.toFixed(1)} LUFS · LRA ${m.lra.toFixed(1)} LU · ${m.truePeak.toFixed(1)} dBTP · 150-2k corr ${Number.isFinite(m.bodyCorr) ? m.bodyCorr.toFixed(2) : "n/a"} · sub ${m.bands.sub.toFixed(1)} dB`,+ fixes: r.fixes.slice(0, 4).map((x) => `${x.status} ${x.fix}`),+ strip, spec: png64(join(tmp, "spec.png")), env: env_,+ momentary: r.curves.momentary.map((v, i) => [i * r.curves.hopS + 0.2, v]), shortTerm: r.curves.shortTerm.map((v, i) => [i * r.curves.hopS + 1.5, v]),+ onsets: r.curves.onsets, hits: r.curves.hits, events: r.sync?.times ?? [], unanswered: r.sync?.unanswered ?? [],+ shade: [...m.gaps.filter((g) => g.len >= 0.1).map((g) => ({ a: g.at, b: g.at + g.len, label: g.allowed ? "allowed hole" : `hole ${g.len.toFixed(1)} s` })), ...(m.endSilence >= 0.1 ? [{ a: m.endSilenceFrom, b: dur, label: `dead tail ${m.endSilence.toFixed(1)} s` }] : []), ...(m.firstSound && m.firstSound >= 0.1 ? [{ a: 0, b: m.firstSound, label: "before body level" }] : [])],+ LEFT, PW, WIDTH,+ };+ const html = `<!doctype html><html><head><meta charset="utf-8"><style>+ :root { --ink: #1d1b18; --paper: #f7f5f0; --line: #d9d4ca; --fail: #c0392b; --warn: #b9770e; --accent: #ca4901; --blue: #2c6e9b; }+ * { margin: 0; box-sizing: border-box; } body { background: var(--paper); color: var(--ink); font-family: Poppins, "Helvetica Neue", Arial, sans-serif; width: ${WIDTH}px; }+ header { padding: 22px ${RIGHT}px 12px ${LEFT}px; } h1 { font-size: 22px; font-weight: 600; } .v { font-size: 15px; font-weight: 600; margin-top: 4px; } .s { font-size: 13px; margin-top: 2px; }+ ol { margin: 8px 0 0 18px; font-size: 13px; line-height: 1.45; } canvas { display: block; }+ </style></head><body><header><h1></h1><div class="v"></div><div class="s"></div><ol></ol></header><canvas id="c"></canvas>+ <script>+ const D = ${JSON.stringify(data)};+ document.querySelector("h1").textContent = D.title; const v = document.querySelector(".v"); v.textContent = D.verdict; v.style.color = D.verdict.startsWith("FAIL") ? "var(--fail)" : D.verdict.includes("warn") ? "var(--warn)" : "#1e7d4f";+ document.querySelector(".s").textContent = D.stats; for (const f of D.fixes) { const li = document.createElement("li"); li.textContent = f; document.querySelector("ol").appendChild(li); }+ const css = (k) => getComputedStyle(document.documentElement).getPropertyValue(k).trim();+ const load = (src) => new Promise((ok) => { if (!src) return ok(null); const i = new Image(); i.onload = () => ok(i); i.src = src; });+ Promise.all([load(D.strip && D.strip.src), load(D.spec), document.fonts.ready]).then(([strip, spec]) => {+ const rows = [["picture", strip ? D.strip.h : 0], ["spectrogram", 240], ["waveform", 130], ["loudness", 210], ["onsets / hits / picture", 64]].filter((r) => r[1]);+ const GAP = 14, H = rows.reduce((a, r) => a + r[1] + GAP, 0) + 40, cv = document.getElementById("c"); cv.width = D.WIDTH; cv.height = H;+ const g = cv.getContext("2d"), X = (t) => D.LEFT + (t / D.dur) * D.PW; let y = 4; const top = {};+ g.font = "500 12px Poppins, Arial, sans-serif"; g.textBaseline = "middle";+ for (const [name, h] of rows) { top[name] = [y, h]; g.fillStyle = css("--ink"); g.textAlign = "right"; g.fillText(name === "onsets / hits / picture" ? "onsets" : name, D.LEFT - 10, name === "onsets / hits / picture" ? y + h / 6 : y + h / 2); if (name === "spectrogram") { g.font = "10px Poppins, Arial, sans-serif"; g.fillText("log Hz", D.LEFT - 10, y + h / 2 + 16); g.font = "500 12px Poppins, Arial, sans-serif"; } g.strokeStyle = css("--line"); g.strokeRect(D.LEFT + 0.5, y + 0.5, D.PW - 1, h - 1); y += h + GAP; }+ const bottom = y - GAP;+ // shading first, through every panel: holes, the dead tail, the silent start+ for (const s of D.shade) { g.fillStyle = "rgba(192,57,43,0.13)"; g.fillRect(X(s.a), 4, Math.max(2, X(s.b) - X(s.a)), bottom - 4); g.fillStyle = css("--fail"); g.textAlign = "left"; g.fillText(s.label, Math.min(X(s.a) + 4, D.LEFT + D.PW - g.measureText(s.label).width), bottom + 12); }+ if (strip) { const [t, h] = top.picture; g.drawImage(strip, D.LEFT, t, D.strip.w, h); }+ { const [t, h] = top.spectrogram; g.drawImage(spec, D.LEFT, t, D.PW, h); }+ { const [t, h] = top.waveform, mid = t + h / 2; g.fillStyle = css("--blue"); D.env.forEach(([lo, hi], x) => g.fillRect(D.LEFT + x, mid - hi * h / 2, 1, Math.max(1, (hi - lo) * h / 2))); }+ { const [t, h] = top.loudness, lo = -60, hi = 0, Y = (l) => t + h - ((Math.max(lo, Math.min(hi, l)) - lo) / (hi - lo)) * h;+ g.textAlign = "right"; g.fillStyle = css("--ink"); g.font = "11px Poppins, Arial, sans-serif";+ for (const l of [-50, -40, -30, -20, -10]) { g.strokeStyle = css("--line"); g.beginPath(); g.moveTo(D.LEFT, Y(l)); g.lineTo(D.LEFT + D.PW, Y(l)); g.stroke(); g.fillText(String(l), D.LEFT + D.PW - 4, Y(l) - 7); }+ g.setLineDash([6, 4]); g.strokeStyle = css("--accent"); g.beginPath(); g.moveTo(D.LEFT, Y(-14)); g.lineTo(D.LEFT + D.PW, Y(-14)); g.stroke(); g.textAlign = "left"; g.fillStyle = css("--accent"); g.fillText("target -14", D.LEFT + 6, Y(-14) - 8);+ if (D.I > -70) { g.strokeStyle = css("--ink"); g.beginPath(); g.moveTo(D.LEFT, Y(D.I)); g.lineTo(D.LEFT + D.PW, Y(D.I)); g.stroke(); g.fillStyle = css("--ink"); g.fillText("integrated " + D.I.toFixed(1), D.LEFT + 90, Y(D.I) - 8); }+ g.setLineDash([]);+ const curve = (pts, col, w) => { g.strokeStyle = col; g.lineWidth = w; g.beginPath(); let pen = false; for (const [tt, l] of pts) { if (!(l > -70)) { pen = false; continue; } pen ? g.lineTo(X(tt), Y(l)) : g.moveTo(X(tt), Y(l)); pen = true; } g.stroke(); g.lineWidth = 1; };+ curve(D.momentary, "rgba(44,110,155,0.55)", 1); curve(D.shortTerm, css("--ink"), 2);+ g.fillStyle = css("--ink"); g.textAlign = "left"; g.fillText("momentary (thin), short-term (thick), LUFS", D.LEFT + 6, t + 12); }+ { const [t, h] = top["onsets / hits / picture"], third = h / 3;+ g.strokeStyle = css("--ink"); for (const o of D.onsets) { g.beginPath(); g.moveTo(X(o) + 0.5, t + 2); g.lineTo(X(o) + 0.5, t + third); g.stroke(); }+ g.fillStyle = css("--accent"); for (const o of D.hits) { g.beginPath(); g.arc(X(o), t + third * 1.5, 4, 0, 7); g.fill(); }+ for (const e of D.events) { const miss = D.unanswered.includes(e); g.strokeStyle = miss ? css("--fail") : "#1e7d4f"; g.lineWidth = 2; g.beginPath(); g.moveTo(X(e), t + third * 2 + 2); g.lineTo(X(e), t + h - 2); g.stroke(); g.lineWidth = 1;+ g.strokeStyle = miss ? "rgba(192,57,43,0.35)" : "rgba(30,125,79,0.3)"; g.setLineDash([2, 3]); g.beginPath(); g.moveTo(X(e), 4); g.lineTo(X(e), t); g.stroke(); g.setLineDash([]); }+ g.font = "10px Poppins, Arial, sans-serif"; g.fillStyle = css("--ink"); g.textAlign = "right"; g.fillText("hits", D.LEFT - 10, t + third * 1.5); g.fillText("picture events", D.LEFT - 10, t + third * 2.5); }+ // the time axis+ g.font = "11px Poppins, Arial, sans-serif"; g.fillStyle = css("--ink"); g.textAlign = "center"; const step = D.dur > 40 ? 5 : D.dur > 12 ? 2 : 1;+ for (let s = 0; s <= D.dur + 1e-6; s += step) g.fillText(Math.floor(s / 60) + ":" + String(s % 60).padStart(2, "0"), X(s), bottom + 28);+ document.body.dataset.done = "1";+ });+ </script></body></html>`;+ const browser = await env.pw.lib.chromium.launch({ executablePath: env.browser.executablePath });+ try {+ const page = await browser.newPage({ viewport: { width: WIDTH, height: 600 }, deviceScaleFactor: 1 });+ await page.setContent(html); await page.waitForSelector("body[data-done]", { timeout: 20000 });+ mkdirSync(dirname(out), { recursive: true }); await page.screenshot({ path: out, fullPage: true });+ } finally { await browser.close(); }+ console.log(`${out}\n ${data.verdict} ${data.stats}`);+} finally { rmSync(tmp, { recursive: true, force: true }); }diff --git a/plugins/anidoodle/skills/anidoodle/engine/tools/verify-export.mjs b/plugins/anidoodle/skills/anidoodle/engine/tools/verify-export.mjsindex 1bf95dc..8422f01 100644--- a/plugins/anidoodle/skills/anidoodle/engine/tools/verify-export.mjs+++ b/plugins/anidoodle/skills/anidoodle/engine/tools/verify-export.mjs@@ -36,6 +36,7 @@ import { basename, resolve } from "node:path";import { defaultOutput, requireFilm } from "./names.mjs";import { firstFrameBlank } from "./thumb.mjs";import { mono, onsetNear, xcorrOffset } from "./avsync.mjs";+import { filmShape } from "./filmshape.mjs";const VAL = new Set(["file", "adapter", "width", "first-frame", "tol", "fidelity-psnr", "scale", "frame", "sync-tol"]);const pos = [], opt = {};@@ -117,6 +118,10 @@ if (isMp4) {for (let i = 0; i < dL.length; i++) { dL[i] = di[2 * i]; dR[i] = di[2 * i + 1]; }const master = await s.audio(SR), mb = Buffer.from(master.float32, "base64"), mi = new Float32Array(mb.buffer.slice(mb.byteOffset, mb.byteOffset + mb.byteLength)), mL = new Float32Array(master.frames), mR = new Float32Array(master.frames);for (let i = 0; i < master.frames; i++) { mL[i] = mi[2 * i]; mR[i] = mi[2 * i + 1]; }+ // the shape of a finished piece: sound from the first frame, no hole, no dead air after it stops+ const shape = filmShape(dL, dR, SR, { fps: meta.fps, quiet: meta.quiet });+ for (const [from, to, why] of meta.quiet ?? []) if (why) note(`QUIET ${from}-${to}: ${why}`, "a declared silence");+ say(shape.problems.length === 0, `the sound has a finished shape (starts ${shape.firstS.toFixed(1)} s, longest hole ${shape.holeS.toFixed(1)} s, dead air at the end ${shape.endS.toFixed(1)} s)`, shape.problems.map((p) => p.msg).join("; ") || "sound from the start, no hole over 0.25 s, the last sound within 0.5 s of the end");const ref = mono(mL, mR), got = mono(dL, dR), tol = Number(opt["sync-tol"] ?? 1);const marks = meta.sync?.length ? meta.sync : [0.25, 0.5, 0.75].map((q) => ({ frame: Math.round(q * N), label: `${Math.round(q * 100)} % in` }));if (!meta.sync?.length) note("no sync markers in meta.sync", "checking three points of the mix instead (a launch template film names its presses and its impact)");@@ -137,7 +142,14 @@ if (isMp4) {const eb = spawnSync("ffmpeg", ["-v", "info", "-nostats", "-i", file, "-map", "0:a:0", "-af", "ebur128=peak=true", "-f", "null", "-"], { encoding: "utf8", maxBuffer: 1 << 26 });const txt = eb.stdout + eb.stderr, tp = Number((txt.match(/True peak:\s*\n\s*Peak:\s*(-?[0-9.]+|-inf) dBFS/) ?? [])[1]), il = Number((txt.match(/Integrated loudness:\s*\n\s*I:\s*(-?[0-9.]+) LUFS/) ?? [])[1]);if (!Number.isFinite(tp)) note("true peak unreadable from ffmpeg's ebur128", txt.split("\n").slice(-4).join(" "));- else if (opt.delivery) say(tp <= -1.0, `true peak after the encode ${tp.toFixed(2)} dBTP`, `ceiling -1 dBTP; integrated ${Number.isFinite(il) ? il.toFixed(1) : "?"} LUFS`);+ else if (opt.delivery) {+ say(tp <= -1.0, `true peak after the encode ${tp.toFixed(2)} dBTP`, `ceiling -1 dBTP; integrated ${Number.isFinite(il) ? il.toFixed(1) : "?"} LUFS`);+ // a film that plays quiet reads unfinished: -16 LUFS for gentle films, -14 for dense, a 1 LU window around each+ // -19 is the floor: a gentle score held under -16 by its own peaks (never compressed, by design) may sit near+ // -17.5; under -19 the film is simply quiet. Warn from -17 so the musical cure ("Peaks", music/README.md) is tried+ say(Number.isFinite(il) && il >= -19 && il <= -13, `integrated loudness ${Number.isFinite(il) ? il.toFixed(1) : "?"} LUFS`, "-19..-13 (the delivery master puts gentle films at -16, dense at -14)");+ if (Number.isFinite(il) && il < -17 && il >= -19) note(`quiet: ${il.toFixed(1)} LUFS`, "its peaks hold it down: in a score, stagger the bass under the loudest downbeat and roll the big chord (music/README.md, Peaks); in effects, soften the sharpest cue's attack or lower it a little so the rest can come up");+ }else note(`true peak after the encode ${tp.toFixed(2)} dBTP${tp > -1 ? " (over -1: --delivery fails this)" : ""}`, `integrated ${Number.isFinite(il) ? il.toFixed(1) : "?"} LUFS`);}}diff --git a/plugins/anidoodle/skills/anidoodle/references/craft-bar.md b/plugins/anidoodle/skills/anidoodle/references/craft-bar.mdindex bab6955..b4021c5 100644--- a/plugins/anidoodle/skills/anidoodle/references/craft-bar.md+++ b/plugins/anidoodle/skills/anidoodle/references/craft-bar.md@@ -25,6 +25,9 @@ The test: would a proud human illustrator ship this, or is it mechanical shape-a| Words laid over busy art, a face or the UI | Type gets its own frame by default; over the picture only as a composed label or kinetic line on a calm area (`workflows/launch-video.md`, Type) || A loop playing in place and called "alive" | Real travel through a world that changes as the subject moves || An unmatched hard cut or a sharp swoosh between scenes | A gentle move (a bloom, a flip, a push, the card grows into the frame), or a cut matched on shape, position or beat |+| Site art on its own white or cream while the page is another colour | `paper` is the page's exact colour; neutrals moved onto it, light and dark from one source (`workflows/site-art.md`) |+| A part, shadow or sheen creeping under the headline | The headline zone is empty, proved by `tools/placement.mjs` |+| A spinner drawn as still blades turning slowly | A sheen disc and fading trails (`spin`), so it reads as speed |**No dead air** in anything that moves: something visibly changes in every second, from frame 0.Check it with the tool AND by eye: a creeping camera changes every pixel and satisfies the tooldiff --git a/plugins/anidoodle/skills/anidoodle/references/formats.md b/plugins/anidoodle/skills/anidoodle/references/formats.mdindex 0ffdd51..4190672 100644--- a/plugins/anidoodle/skills/anidoodle/references/formats.md+++ b/plugins/anidoodle/skills/anidoodle/references/formats.md@@ -10,6 +10,8 @@ node <skill>/engine/tools/scaffold.mjs ~/art --film intro # something that## Stills: hero art, spots, covers, cards, diagrams+Art that sits on a site beside a headline, on its page colour and brand: `workflows/site-art.md`.+- **Size is `meta.W` x `meta.H`**, in logical units; `--scale` multiplies it at render time, soone source gives a thumbnail (`--scale 0.5`), the page (`1`) and print (`--scale 3`). Commonshapes: 1600x900 web hero, 1200x630 social card, 1080x1080 square post, 1080x1350 portraitdiff --git a/plugins/anidoodle/skills/anidoodle/references/music/README.md b/plugins/anidoodle/skills/anidoodle/references/music/README.mdindex ddca2be..f0935ac 100644--- a/plugins/anidoodle/skills/anidoodle/references/music/README.md+++ b/plugins/anidoodle/skills/anidoodle/references/music/README.md@@ -11,6 +11,7 @@ without the pack, is synthesized in code exactly as before. See[Recorded instruments](#recorded-instruments-the-optional-sound-pack) below.Code: `engine/src/canvas-core/music/`. Tools: `engine/tools/music.mjs`, `engine/tools/soundfetch.mjs`.+To check a finished film's sound: `engine/tools/soundcheck.mjs` and `soundsheet.mjs` ([how](sound-design.md#checking-the-finished-films-sound)).**Start here: [`compose.md`](compose.md).** It takes you from a brief to an original score. A styleis a vocabulary: sound, grooves, harmony language, melody rules, arrangement grammar. It is never@@ -115,6 +116,8 @@ MusicPlan + notes (you write) -> perform -> instruments (one stem per part)2:1 bus glue) exists but is off by default: Alex's call. If the peak still blocks the gain, the loudness goesdown. The cure is musical (see "Peaks" below): a solo piano with a 10 LU range (the nocturne demo) masters at -17.5.- **Dense styles** (lofiElectronic, lofi, drive, house, synthwave, hipHop, rock, chiptune): **-14 LUFS** through a look-ahead true-peak limiter, then a static trim if an inter-sample peak still passes -1 dBTP.+ - **A film's whole mix** (score plus effects, or effects alone) goes through the delivery master last:+ `sound-design.md`, The finished mix.A film's `audio` is `filmAudio(piece, seconds)`, which returns `(sampleRate) => [L, R]` at exactlythe film's length. It fits the score first (`fitScore`, below), so the music ends on its phrase at@@ -128,6 +131,12 @@ The pack is a separate download (about 390 MB), not part of the skill. Once it iacoustic parts play recordings of real instruments and three rooms are recorded impulse responses.Without it every score still plays, on the modelled voices, unchanged.+Every stereo recording is made phone-safe when its bank loads (`RECORDING_WIDTH` in `sampler.ts`):+some were captured with spaced microphones whose sides cancel in the body of the sound (a marimba at+-0.72 between 150 Hz and 2 kHz, one side's polarity flipped), so a side clearly inverted there is+flipped back and the body narrowed, while the air above 2 kHz keeps its width. On the cheetah score+this took the mids from -0.15 to 0.85 correlation and the mono-fold loss from 3.5 to 0.6 dB.+```bashnode tools/soundfetch.mjs list # the install directory and what is installed; no networknode tools/soundfetch.mjs get harp rooms # the one command that downloads: hash, unpack, install (`all` = 373 MB)diff --git a/plugins/anidoodle/skills/anidoodle/references/music/sound-design.md b/plugins/anidoodle/skills/anidoodle/references/music/sound-design.mdindex 5cdf9b6..04df611 100644--- a/plugins/anidoodle/skills/anidoodle/references/music/sound-design.md+++ b/plugins/anidoodle/skills/anidoodle/references/music/sound-design.md@@ -120,6 +120,83 @@ music, and its test only checked that they existed.)when it starts the groove and mud anywhere else.- Hear it in context before it ships. Render the kit page (`node tools/sfx.mjs kit <dir>`) and ademo over the real score, and check the audibility table.+- **The numbers that keep it designed.** About five effects per ten seconds. Hard cuts and cursor+ drifts get nothing. About two whooshes a film, each starting 100-450 ms before the move and peaking+ on its fastest frame. One riser, then 0.1-0.5 s of near silence, then the impact on the reveal frame,+ the loudest moment of the film, 30-60% of the way in. One click voice for the whole UI: press, then+ release 60-110 ms later, the same level every time. Typing at most about twelve keys a second.+- **Where a cue may land.** A hit's attack no earlier than 45 ms before its frame and its peak no+ later than 75 ms after. A whoosh's loudest point within 45 ms of the move's fastest frame. A riser+ ends between 250 ms before the hit and 30 ms after it. Later than these reads as lag; earlier reads+ as a mistake.+- **The ending.** The music stops on a bar or filters down, 0.2-0.7 s of near silence, one soft note+ in key, and its tail rings out to the last frame, 8-20 dB under the film's peak. Never a cut-off.++## The finished mix++What the whole film's sound must be before it ships, score and effects together:++- **On its loudness target.** The delivery master (`music/delivery.ts`, the last stage of `mixSfx` and+ `mixLaunch`) sets one static gain to -16 LUFS (gentle) or -14 (dense, launch films), then a smooth+ true-peak limiter with its work capped (4 dB gentle, 6 dense): past the cap the gain gives way+ instead of the hits being squashed, and the shortfall is reported. `master: "none"` keeps the old+ peak-only ceiling. A score-only film keeps its own master (music/README.md, Master).+- **Never digital silence.** An effects-only film sits on room tone 22 dB under its cues (`bed`), nearly+ mono so a phone keeps it, from the first frame to the last.+- **A finished shape.** Sound from the first frame (within 0.5 s), no hole over 0.25 s, the last sound+ within 0.5 s of the last frame. A silence the film means (a stop-down, a held breath) is declared in+ `meta.quiet` as `[fromFrame, toFrame, reason]`. `verify-export --delivery` fails the shape, a true+ peak over -1 dBTP after the encode, and loudness under -19 LUFS; it warns from -17.+- **Fix one thing at a time, with one fixer.** Read the film through separate lenses (sync, edges and+ clicks, masking, tone, the director's arc), each proposing its fix as a variant it has measured.+ Then one fixer merges them and re-runs every check, and a fix that breaks another lens is dropped.+ Lenses that each edit the mix fight: a tonal cut at 2-6 kHz undoes the masking lens's raised hit.++## Checking the finished film's sound++You cannot hear the film, so measure the delivered mix before anyone listens. Two tools read the+rendered file (a film name means `out/<name>.mp4`; a `.wav` or `.m4a` works too):++```+node tools/soundcheck.mjs <film|file> # the scorecard; exit 1 on any FAIL+node tools/soundcheck.mjs <film> --json --out x.json # the same, as data+node tools/soundcheck.mjs <film> --allow 3.1:3.6 # a hole there is a declared stop-down+node tools/soundsheet.mjs <film> -o out/<film>-sound.png # one picture of it all+```++`soundcheck` prints a status for every metric (PASS, WARN, FAIL against a range, or INFO), then a+**FIX FIRST** list in the order that matters, each with its time and the concrete fix: "3.4 s hole+at 0:03.4", "boxy: cut 500-790 Hz by 2-3 dB", "mids decorrelated: narrow the stereo width below+2 kHz". It measures:++- level: integrated LUFS, true peak, loudness range, loudest 3 s, intro and end level, an+ 11-point arc, the loudest moment;+- shape: first sound, holes inside the film, dead air at the end, fade, the final moment, a cut+ ending, onsets, salient hits, stop-downs;+- spectrum: six band shares (sub 20-60 Hz up to air 8-16 kHz) and the centroid;+- stereo: side vs mid, L/R correlation overall and per band (150 Hz-2 kHz is where phones comb+ the body away), and how much more than the expected 3 dB the mix loses folded to mono;+- picture (any file with video): frame-difference events, the share with an onset within 100 ms+ against a chance baseline, the events with no sound, and the median onset offset. INFO only:+ not every picture change is meant to be a cue.++The built-in ranges are for drawing films: -16 to -13 LUFS (web target -14, gentle films -16),+true peak at or under -1 dBTP, LRA at most 9 LU, sound by 0.5 s, no hole over 0.25 s, at most+0.5 s of silence at the end, 150 Hz-2 kHz correlation at least 0.3, at most 1.5 dB of extra mono+loss, and the sub at or under -6 dB of the energy.++To grade against films the user loves, build a profile from them:+`node tools/soundcheck.mjs profile <films...> -o references/music/sound-profile.json`, then pass+`--profile references/music/sound-profile.json`. A profile moves the taste ranges (loudness,+bands, width); the delivery limits (true peak, first sound, holes, end silence, mono loss) stay.++`soundsheet` draws a frame strip, the spectrogram, the waveform, momentary and short-term+loudness against the integrated level and -14, onset ticks, hits and picture events (red when no+sound answers them), with every hole and the dead tail shaded. Read it before handing the film+over: the hole, the dead tail and a late hit are visible in it.++The metrics live in `engine/src/canvas-core/music/soundcheck.ts`, tested on synthetic faults in+`engine/test/soundcheck.test.ts`.## Tools and checks@@ -128,6 +205,7 @@ node tools/sfx.mjs list # kinds, variants, levels,node tools/sfx.mjs one whoosh soft 3 out.mp3 # one soundnode tools/sfx.mjs kit <dir> # every variant x3 + demo + page + meters.json + spectra/node tools/sfx.mjs test # the gate+node tools/soundcheck.mjs <film> # the finished film's sound (see above)```The test checks every kind and variant for:diff --git a/plugins/anidoodle/skills/anidoodle/references/workflows/review.md b/plugins/anidoodle/skills/anidoodle/references/workflows/review.mdindex 8f95c12..81b1a89 100644--- a/plugins/anidoodle/skills/anidoodle/references/workflows/review.md+++ b/plugins/anidoodle/skills/anidoodle/references/workflows/review.md@@ -18,7 +18,7 @@ Freeze a copy of the file and note its hash first. Every reading is of that copy| **Director** | the contact sheet at one tile per beat, sound off; then each seam as a before/after pair | Whether someone who has never seen the brief could say what the film is about, and feel the payoff. | point, first second, pacing, seams || **Illustrator** | full-size stills of the hardest frames; crops of faces, hands, feet and joins at `--scale 2` | Whether a proud illustrator would sign it, or it is shapes assembled (`craft-bar.md`). | drawing, style || **Motion and finish** | `popscan.mjs`, `gate.mjs`, strips of consecutive frames across every seam and every fast move | Whether anything pops, stalls, jumps or smears that was not meant to. | motion, finish |-| **Sound and sync** | `music.mjs check` (with its ARC line), `verify-export.mjs`, the cue table against the picture | Whether the sound is one piece with a shape, and lands on the picture. | sound |+| **Sound and sync** | `music.mjs check` (with its ARC line), `verify-export.mjs`, `soundcheck.mjs` and its `soundsheet.mjs` picture, the cue table against the picture | Whether the sound is one piece with a shape, and lands on the picture. | sound |Rules that make a reading worth having:diff --git a/plugins/anidoodle/skills/anidoodle/references/workflows/site-art.md b/plugins/anidoodle/skills/anidoodle/references/workflows/site-art.mdnew file mode 100644index 0000000..bf075dc--- /dev/null+++ b/plugins/anidoodle/skills/anidoodle/references/workflows/site-art.md@@ -0,0 +1,96 @@+# Site art: a picture that works on someone's page++A hero beside a headline, a feature tile, a row of spots, a share card. The picture no longer owns its+canvas: a headline does, a page colour does, a brand does. Kit: `engine/src/canvas-core/assetKit.ts`.+Worked example: `siteHero.ts` (light page) and `siteHeroDark.ts` (dark page), one source.++## 1. The brief, before any drawing++Write five lines, from the request or as defaults you say out loud:++1. **Where it goes:** product, page, section, shown size, what sits beside it.+2. **The one thing it says:** a promise ("ships in a minute"), a feeling ("unhurried"), or a fact ("works offline").+3. **Who looks:** engineers read instruments and machines; a family app wants warm, soft, homely things.+4. **The page:** its exact colour, light or dark or both, and the brand colours.+5. **The style:** any of the 32. Style is free; craft is not.++## 2. One real object that says it++Three kinds, and write one concept of each before choosing:++- **Literal:** the product as a fine object (a camera for a photo app).+- **Metaphor:** a real thing whose working is the promise. Software has no body, so this is usually the strongest.+- **Scene:** a small world on a tray or a shelf, one hero object among a few supporting ones. Good for wide heroes and for sets.++Choose with five quick tests: **glance** (named in a second at its shown size), **promise** (its working says+it, no caption), **parts** (fifty real parts, not a smooth blob), **page** (its silhouette suits the slot:+wide and low beside a headline, tall in a column), **brand** (material and era match the mood). Say which+you pick and why in one line, then build it. If the user already named the object, skip the round.++| The promise | A thing that does it |+|---|---|+| Nothing gets lost | A post-office sorting frame, every letter in its slot, one being placed |+| Fast setup | A flat-pack chair half assembled, the last dowel going in |+| Team chat | A switchboard, one cable mid-plug, a lamp lit |+| Privacy | A letterbox with a combination dial, its flap shut |+| Automation | A marble run: one marble on the track, the next waiting at the gate |+| Insights | A weather station: anemometer turning, barometer needle, a logbook |+| Translation | A typewriter with two type baskets, one key mid-strike |+| Savings | A coin sorter with tubes by size, one coin rolling down the ramp |+| Learning | A desk globe on a brass meridian, a pin in one city |+| Music | A cylinder music box, the drum turning, the governor a blur |++## 3. The moment++A picture shown once gets one place for the eye: a drawer half out, a key mid-strike, a lamp lit, a+coin in the slot. Exactly one, carried by the accent, about a third of the way into the art region on+the side nearest the text (`strongPoint`). If the accent lands on structure, the eye lands on structure.++## 4. Placement++`PLACEMENTS` holds the canvas, the art region and the headline zone for each slot (heroRight, heroLeft,+heroCentre, art, tile, spot, banner, social, slide). `Cam.fit(A, E, points, fitBox(p))` fits the object+into its region; pass every extreme point, lifted parts included. The object leads toward the text: pick+the azimuth that turns its long face and its moment that way. Nothing enters the headline zone, not a+shadow, not a sheen; prove it with `node tools/placement.mjs still.png --W <meta.W> --safe x,y,w,h`.+Keep a few units of air at every edge the object does not deliberately bleed off.++## 5. Page colour, light and dark++`setPalette(pagePalette({ paper, accent, colours, tint }))` moves every material onto the page: on a+light page the neutrals shift by the page's difference in lightness and, by `tint`, its colour cast; on+a dark page the parts sit just above the page, the lit top lightest, the lines lighter than the faces.+The fill colour of the page and of `paper` must be identical, or every part shows a pale halo. A site+with both themes gets both films from one source (`heroOn(title, paper, accent)`).++## 6. Brand colour++`accent: "#hex"` puts the brand on the part to watch (`accent: true`); `colours: { wood: "#7a5536" }`+recolours any material by name, which is also how brass, walnut or ebony are made. Mode **body** makes+the part of the colour (a five-step ramp in its own hue, lightness set so four tones read and nothing+glares on dark). Mode **ink** keeps the part neutral and colours only its lines and dots (an LED, a+pointer, an engraved mark). Default to one brand family: the subject in body, one or two small echoes.+Colour the moment, never the base or the biggest faces, unless the product is that colour.++## 7. Motion is the object working++Loop one full cycle of the machine so it repeats without a seam. Anything that would turn in life turns;+fast spinners get `spin(angle, sweep, draw, { disc })`, a sheen disc and fading trails, because bare blades+read as a paper cut-out. At most three or four kinds of motion, out of step. Beside a headline, calm wins:+if the real machine moves little, declare it with a `meta.holds` reason instead of inventing motion. Frame 0+is what a reduced-motion visitor sees, so compose it as the hero frame.++## 8. Sets and small sizes++Spots in a row share one family of parts (the same screws, feet, bevels, label plates) and similar+weight: add parts to the sparse one, never strip the dense one. Under about 320 px cut detail instead of+shrinking it: bigger screws, fewer ticks, no knurls. Check every piece at its shown size and at 390 px+wide (`placement.mjs --phone out.png`), and look.++| Mood | Shape and parts | Colour |+|---|---|---|+| Precise | Thin plates, fine bevels, rulers, many small screws | Greys and one sharp accent |+| Friendly | Big radii, chunky buttons, rubber feet, few large screws | Warm page, a soft accent on the body |+| Crafted | Wood cheeks, brass fittings, label plates, hinges | Cream page, a deep accent |+| Calm | Few objects with air between, low heights, one slow motion | Low contrast, a muted accent |+| Launch | A diagonal, something lifted or in flight | The accent on the moving thing |diff --git a/skills/anidoodle/engine/package-lock.json b/skills/anidoodle/engine/package-lock.jsonindex 397418f..edfa6ab 100644--- a/skills/anidoodle/engine/package-lock.json+++ b/skills/anidoodle/engine/package-lock.json@@ -1,12 +1,12 @@{"name": "anidoodle-engine",- "version": "0.8.0",+ "version": "0.9.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "anidoodle-engine",- "version": "0.8.0",+ "version": "0.9.0","dependencies": {"esbuild": "0.25.12"},diff --git a/skills/anidoodle/engine/package.json b/skills/anidoodle/engine/package.jsonindex a201729..b0aba70 100644--- a/skills/anidoodle/engine/package.json+++ b/skills/anidoodle/engine/package.json@@ -1,6 +1,6 @@{"name": "anidoodle-engine",- "version": "0.8.0",+ "version": "0.9.0","private": true,"type": "module","description": "Portable art core + backend adapters for illustrations, animations and films drawn entirely in code.",diff --git a/skills/anidoodle/engine/src/canvas-core/launchSound.ts b/skills/anidoodle/engine/src/canvas-core/launchSound.tsindex 4679145..f99c3b7 100644--- a/skills/anidoodle/engine/src/canvas-core/launchSound.ts+++ b/skills/anidoodle/engine/src/canvas-core/launchSound.ts@@ -10,7 +10,7 @@// and one impact, at the big reveal only, and nothing at all on its other cuts.import { placeSfx, sfxDuck, sfxAudibility, type SfxCue, type SfxPlan, type SfxAudibility, type PlacedCue } from "./music/sfx";import { limiter } from "./music/render";-import { deliver, layBed } from "./music/delivery";+import { deliver, layBed, type Delivered } from "./music/delivery";import { loudness, truePeak } from "./music/meter";import type { FilmAudio } from "./film";@@ -26,7 +26,7 @@ const balance = (L: Float32Array, R: Float32Array, p: number) => {for (let i = 0; i < L.length; i++) { const m = (L[i] + R[i]) / 2, s = (L[i] - R[i]) / 2; L[i] = m * gl + s; R[i] = m * gr - s; }};-export type LaunchMix = { L: Float32Array; R: Float32Array; placed: PlacedCue[]; audibility: SfxAudibility[]; raised: { i: number; role: string; db: number }[]; lufs: number; dbtp: number; ok: boolean };+export type LaunchMix = { L: Float32Array; R: Float32Array; placed: PlacedCue[]; audibility: SfxAudibility[]; raised: { i: number; role: string; db: number }[]; lufs: number; dbtp: number; ok: boolean; delivered?: Delivered };/** Score (null = silent) + the film's cues, panned, ducked, every cue heard, one true-peak ceiling (-1 dBTP). */export const mixLaunch = (music: [Float32Array, Float32Array] | null, plan: LaunchPlan, sr = 48000, maxRaise = 8): LaunchMix => {const n = Math.round((plan.frames / plan.fps) * sr), cues = plan.cues.map((c) => ({ ...c })), raised = new Map<number, number>();@@ -49,11 +49,12 @@ export const mixLaunch = (music: [Float32Array, Float32Array] | null, plan: Laun// no score: the cues sit on room tone instead of dropping to silence between them (delivery.ts)if (!music && plan.bed !== false && placed.length) layBed(L, R, [fxL, fxR], sr, plan.cues.length * 7919 + plan.frames, plan.bed ?? 22);// a launch film is dense: the whole mix to -14 LUFS, then the ceiling (delivery.ts); plan.master overrides- if ((plan.master ?? "dense") === "none") limiter(L, R, sr, Math.pow(10, -1.3 / 20)); else deliver(L, R, sr, plan.master ?? "dense", { ceilingDb: -1.3 });+ let delivered: Delivered | undefined;+ if ((plan.master ?? "dense") === "none") limiter(L, R, sr, Math.pow(10, -1.3 / 20)); else delivered = deliver(L, R, sr, plan.master ?? "dense", { ceilingDb: -1.3 });const tp0 = truePeak([L, R]).dbtp; if (tp0 > -1.05) { const g = Math.pow(10, (-1.1 - tp0) / 20); for (let i = 0; i < n; i++) { L[i] *= g; R[i] *= g; } }const fade = Math.min(n, Math.round(0.015 * sr)); for (let i = 0; i < fade; i++) { const g = i / fade; L[n - 1 - i] *= g; R[n - 1 - i] *= g; }const lu = n >= 0.4 * sr ? loudness([L, R], sr).integrated : NaN;- return { L, R, placed, audibility: aud, raised: [...raised].map(([i, db]) => ({ i, role: cues[i].role, db })), lufs: lu, dbtp: truePeak([L, R]).dbtp, ok: aud.every((a) => a.ok) };+ return { L, R, placed, audibility: aud, raised: [...raised].map(([i, db]) => ({ i, role: cues[i].role, db })), lufs: lu, dbtp: truePeak([L, R]).dbtp, ok: aud.every((a) => a.ok), delivered };};/** What a Film's audio(sampleRate) returns; throws when a cue is still buried after raising it. */export const launchAudio = (music: FilmAudio | null, plan: LaunchPlan) => Object.assign((sr: number): [Float32Array, Float32Array] => {diff --git a/skills/anidoodle/engine/src/canvas-core/music/sampler.ts b/skills/anidoodle/engine/src/canvas-core/music/sampler.tsindex 6c909f0..36a0207 100644--- a/skills/anidoodle/engine/src/canvas-core/music/sampler.ts+++ b/skills/anidoodle/engine/src/canvas-core/music/sampler.ts@@ -2,10 +2,31 @@import type { Played } from "./perform";import type { PedalSpan } from "./piano";import type { Opts } from "./keysCore";-import { clamp, db } from "./dsp";+import { clamp, db, Biquad } from "./dsp";import { nameOf } from "./theory";import { rng } from "../core";import { pianoVelocity } from "./keysPiano";+import { bandWidth } from "./mixDsp";++// Recordings made with spaced microphones can be out of phase between the sides in the body of the+// sound (150 Hz to 2 kHz: some marimba zones measure -0.72 file after file, which is one side's polarity+// flipped; tubular bells sit near 0, a grand piano about 0.3). On a phone or any mono fold the sides+// cancel and the music goes hollow. Each stereo recording is fixed once, when its bank is registered:+// a side whose body is clearly inverted is flipped back, then the body is narrowed (mono under 150 Hz,+// the side at half up to 2 kHz) while the air above 2 kHz keeps its full width.+export const RECORDING_WIDTH = Object.freeze({ monoHz: 150, splitHz: 2000, mid: 0.5, high: 1, flipBelow: -0.3 });+const narrowed = new WeakSet<Float32Array>();+const bodyCorr = (L: Float32Array, R: Float32Array) => {+ const f = () => [Biquad.make(48000, "hp", 150, 0.707), Biquad.make(48000, "lp", 2000, 0.707)], a = f(), b = f(); let c = 0, x = 0, y = 0;+ for (let i = 0; i < L.length; i++) { const l = a[1].tick(a[0].tick(L[i])), r = b[1].tick(b[0].tick(R[i])); c += l * r; x += l * l; y += r * r; }+ return x * y > 0 ? c / Math.sqrt(x * y) : 1;+};+const narrow = (ch: Float32Array[]): Float32Array[] => {+ if (ch.length !== 2 || narrowed.has(ch[0])) return ch;+ const L = ch[0].slice(), R = ch[1].slice();+ if (bodyCorr(L, R) < RECORDING_WIDTH.flipBelow) for (let i = 0; i < R.length; i++) R[i] = -R[i];+ bandWidth(L, R, 48000, RECORDING_WIDTH); narrowed.add(L); narrowed.add(R); return [L, R];+};export type SampleZone = { file: string; midi: number; layer: number; rr: number; frames: number; channels: number; peakDb: number; rmsDb: number; sha256: string; art?: "sus" | "rel"; unpitched?: boolean; measuredHz?: number; loop?: [number, number] };export type SampleEntry = { title: string; source: string; license: string; kind: "struck" | "sustained"; range: [number, number]; layers: number; layerVelocity?: number[]; sparse?: boolean; maxShift?: number; damped: boolean; normalized?: boolean; zones: SampleZone[] };@@ -49,7 +70,7 @@ export const registerBank = (id: string, bank: SampleBank): RegisteredBank => {});if (!e.zones.some((z) => !z.art)) throw new Error(`${id}: no ordinary sample zones`);if (bank.trim && (new Set(bank.trim.map((t) => t.file)).size !== bank.trim.length || bank.trim.some((t) => !e.zones.some((z) => z.file === t.file && z.midi === t.midi && z.layer === t.layer) || ![t.measuredDb, t.modeledDb, t.correctionDb, t.requestedDb ?? 0, t.medianDb ?? 0, t.bandFractionDb ?? 0, t.bandExcessDb ?? 0].every(Number.isFinite) || (t.medianDb !== undefined && Math.abs(t.correctionDb - t.medianDb) > 9.000001) || (t.boostLimited !== undefined && typeof t.boostLimited !== "boolean")))) throw new Error(`${id}: invalid sampled calibration`);- const identity = bankIdentity(e), b = { ...bank, id, hash: bank.trim ? hash(JSON.stringify([identity, bank.trim])) : identity }; banks.set(id, b); return b;+ const identity = bankIdentity(e), b = { ...bank, zones: bank.zones.map((z) => ({ ...z, channels: narrow(z.channels) })), id, hash: bank.trim ? hash(JSON.stringify([identity, bank.trim])) : identity }; banks.set(id, b); return b;};const layerV = (e: SampleEntry, layer: number) => e.layerVelocity?.[layer - 1] ?? (layer - 0.5) / e.layers;diff --git a/skills/anidoodle/engine/src/canvas-core/music/sfxKit.ts b/skills/anidoodle/engine/src/canvas-core/music/sfxKit.tsindex ae7acc8..d1cad69 100644--- a/skills/anidoodle/engine/src/canvas-core/music/sfxKit.ts+++ b/skills/anidoodle/engine/src/canvas-core/music/sfxKit.ts@@ -351,7 +351,7 @@ const impact: Def = {make(c, v) {const { sr, r, P } = c, soft = v === "soft", pre = v === "bloom" ? secs(sr, 0.28) : 0, n = pre + secs(sr, soft ? 4.5 : 7.5), b = new Bus(sr, n);// 1 sub drop, saturated so small speakers still hear its harmonics- const lo = c.j(soft ? 40 : 44, 0.04) * P, subTau = c.j(soft ? 0.32 : 0.6, 0.1), sub = chirp(sr, secs(sr, subTau * 8), (t) => lo + (soft ? 55 : 72) * P * Math.exp(-t / 0.07), ad(0.002, subTau));+ const lo = c.j(soft ? 40 : 44, 0.04) * P, subTau = c.j(soft ? 0.3 : 0.38, 0.1), sub = chirp(sr, secs(sr, subTau * 8), (t) => lo + (soft ? 55 : 72) * P * Math.exp(-t / 0.07), ad(0.002, subTau));b.add(sub.map((x) => Math.tanh(x * 1.8) / Math.tanh(1.8)), pre, 1, 0);// 2 punch: dark noise + two chest modes, a hair wideb.add(burst(sr, r, 0.35, soft ? 0.05 : 0.07, { lp: soft ? 500 : 950, pink: true }), pre, soft ? 0.9 : 1.3, -0.1, 0.4);diff --git a/skills/anidoodle/engine/test/recordingWidth.test.ts b/skills/anidoodle/engine/test/recordingWidth.test.tsnew file mode 100644index 0000000..7027800--- /dev/null+++ b/skills/anidoodle/engine/test/recordingWidth.test.ts@@ -0,0 +1,23 @@+// RECORDING WIDTH TESTS. A stereo recording whose sides are out of phase in the body of the sound is+// narrowed when its bank is registered, so a mono fold keeps it; the air above 2 kHz stays wide; a mono+// recording and a second registration are left alone.+// node tools/test.mjs recordingWidth+import { registerBank, clearBanks, type SampleBank } from "../src/canvas-core/music/sampler";++export const name = "recordingWidth";+export const run = (ok: (cond: boolean, label: string) => void) => {+ const sr = 48000, n = sr, tone = (f: number, ph: number) => Float32Array.from({ length: n }, (_, i) => 0.3 * Math.sin(2 * Math.PI * f * (i / sr) + ph));+ const corr = (a: Float32Array, b: Float32Array) => { let c = 0, x = 0, y = 0; for (let i = sr / 4; i < n; i++) { c += a[i] * b[i]; x += a[i] ** 2; y += b[i] ** 2; } return c / Math.sqrt(x * y); };+ const zone = (ch: number) => ({ file: `z${ch}.flac`, midi: 60, layer: 1, rr: 1, frames: n, channels: ch, peakDb: -10, rmsDb: -20, sha256: "a".repeat(64) });+ const bank = (chs: Float32Array[]): SampleBank => ({ entry: { title: "t", source: "s", license: "CC0", kind: "struck", range: [48, 72], layers: 1, damped: false, zones: [zone(chs.length)] }, zones: [{ zone: zone(chs.length), channels: chs }] });+ clearBanks();+ const low = registerBank("t.low", bank([tone(500, 0), tone(500, Math.PI * 0.85)])).zones[0].channels;+ ok(corr(tone(500, 0), tone(500, Math.PI * 0.85)) < -0.8 && corr(low[0], low[1]) > 0.3, `a 500 Hz body recorded out of phase (${corr(tone(500, 0), tone(500, Math.PI * 0.85)).toFixed(2)}) is narrowed until a mono fold keeps it (${corr(low[0], low[1]).toFixed(2)})`);+ const high = registerBank("t.high", bank([tone(6000, 0), tone(6000, Math.PI / 2)])).zones[0].channels;+ ok(Math.abs(corr(high[0], high[1])) < 0.1, `the air above 2 kHz keeps its width (${corr(high[0], high[1]).toFixed(2)})`);+ const mono = tone(500, 0), m = registerBank("t.mono", bank([mono])).zones[0].channels;+ ok(m.length === 1 && m[0] === mono, "a mono recording is left alone");+ const again = registerBank("t.again", { ...bank([low[0], low[1]]) }).zones[0].channels;+ ok(again[0] === low[0], "a recording already narrowed is not narrowed twice");+ clearBanks();+};diff --git a/skills/anidoodle/engine/test/sfxHarsh.test.ts b/skills/anidoodle/engine/test/sfxHarsh.test.tsindex 61233d6..c9bfd8e 100644--- a/skills/anidoodle/engine/test/sfxHarsh.test.ts+++ b/skills/anidoodle/engine/test/sfxHarsh.test.ts@@ -57,9 +57,11 @@ export const run = (ok: (cond: boolean, label: string) => void) => {message = ""; try { mixSfx(null, { ...plan, harsh: harsh as SfxHarshOptions }, sr); } catch (e) { message = (e as Error).message; }ok(/harsh\./.test(message), `invalid harsh option rejected: ${JSON.stringify(harsh)}`);}+ // Plan 2 re-captured in 0.9.0, when the impact boom's sub tail was shortened (0.6 to 0.38 s decay):+ // it rang at 44 Hz for nearly 5 s and ate the headroom. Plans 0 and 1 are untouched.// Captured from production sources at c1beddfe4264a34d12531dbe931acef611fb0a02,// loaded by git show and bundled with these fixtures before the mixer was edited.- const hashes = ["5db7c646b1e61b0016c5dd8a114e875f6cedbaed17f6b702a225ba2dcc187a85", "3064c924f76acb857c509a5c294cf043380451d544fda0b5372ce06d33ef133a", "3a42c3f453a9a1a0285bd2287bc9874e6e330fc3bd6baa263587e10443eaa94e"];+ const hashes = ["5db7c646b1e61b0016c5dd8a114e875f6cedbaed17f6b702a225ba2dcc187a85", "3064c924f76acb857c509a5c294cf043380451d544fda0b5372ce06d33ef133a", "f2fb798441ecf453b18de3ee2c849810e6fd56f4eaa14fd2002600985fb189f6"];const frozen = frozenPlans(sr);// the old peak-only master stays bit-identical when asked for; the loudness master is tested in delivery.test.tsfrozen.plans.forEach((p0, i) => { const p = { ...p0, master: "none" as const }, m = mixSfx(frozen.music, p, sr), f = filmSfx(() => frozen.music, p)(sr);diff --git a/skills/anidoodle/references/music/README.md b/skills/anidoodle/references/music/README.mdindex e2276fa..f0935ac 100644--- a/skills/anidoodle/references/music/README.md+++ b/skills/anidoodle/references/music/README.md@@ -131,6 +131,12 @@ The pack is a separate download (about 390 MB), not part of the skill. Once it iacoustic parts play recordings of real instruments and three rooms are recorded impulse responses.Without it every score still plays, on the modelled voices, unchanged.+Every stereo recording is made phone-safe when its bank loads (`RECORDING_WIDTH` in `sampler.ts`):+some were captured with spaced microphones whose sides cancel in the body of the sound (a marimba at+-0.72 between 150 Hz and 2 kHz, one side's polarity flipped), so a side clearly inverted there is+flipped back and the body narrowed, while the air above 2 kHz keeps its width. On the cheetah score+this took the mids from -0.15 to 0.85 correlation and the mono-fold loss from 3.5 to 0.6 dB.+```bashnode tools/soundfetch.mjs list # the install directory and what is installed; no networknode tools/soundfetch.mjs get harp rooms # the one command that downloads: hash, unpack, install (`all` = 373 MB)