huashu-motion 0.1.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.en.md +166 -5
  2. package/README.md +167 -6
  3. package/THIRD_PARTY.md +1 -0
  4. package/cli/lib/capture.js +1 -1
  5. package/cli/lib/cdp.js +9 -1
  6. package/cli/lib/check.js +13 -0
  7. package/cli/lib/composed.js +2 -2
  8. package/cli/lib/composer.js +33 -12
  9. package/cli/lib/grab.js +239 -0
  10. package/cli/lib/qa.js +53 -1
  11. package/cli/lib/render-om.js +3 -1
  12. package/cli/lib/render.js +6 -4
  13. package/cli/lib/share.js +101 -0
  14. package/cli/lib/sound.js +4 -0
  15. package/cli/lib/soundprint.js +72 -0
  16. package/cli/lib/swatch.js +7 -3
  17. package/cli/om.js +22 -3
  18. package/package.json +2 -2
  19. package/runtime/om-engine.js +129 -1
  20. package/runtime/om.js +180 -1
  21. package/runtime/three/LICENSE +21 -0
  22. package/runtime/three/entry.js +19 -0
  23. package/runtime/three/om-three.js +280 -0
  24. package/runtime/three/three.min.js +4586 -0
  25. package/skills/huashu-motion/SKILL.md +65 -5
  26. package/skills/huashu-motion/references/about-author.md +101 -0
  27. package/skills/huashu-motion/references/colour.md +16 -11
  28. package/skills/huashu-motion/references/contract.md +27 -1
  29. package/skills/huashu-motion/references/depth.md +109 -0
  30. package/skills/huashu-motion/references/director.md +27 -9
  31. package/skills/huashu-motion/references/library/README.md +1 -1
  32. package/skills/huashu-motion/references/library/languages/3d-object.md +5 -3
  33. package/skills/huashu-motion/references/library/techniques.md +4 -2
  34. package/skills/huashu-motion/references/music.md +411 -0
  35. package/skills/huashu-motion/references/punch-up.md +108 -0
  36. package/skills/huashu-motion/references/scores/first-light.abc +1 -1
  37. package/skills/huashu-motion/references/scores/four-rooms.abc +1 -1
  38. package/skills/huashu-motion/references/sound.md +5 -3
  39. package/templates/object-3d/assets/comment.svg +1 -0
  40. package/templates/object-3d/assets/cursor.svg +1 -0
  41. package/templates/object-3d/assets/studio.jpg +0 -0
  42. package/templates/object-3d/index.html +163 -0
  43. package/templates/object-3d/materials.md +6 -0
  44. package/templates/object-3d/template.json +23 -0
  45. package/templates/ui-space/index.html +150 -0
  46. package/templates/ui-space/materials.md +6 -0
  47. package/templates/ui-space/template.json +22 -0
@@ -11,7 +11,7 @@
11
11
  // !crescendo(! !crescendo)! !diminuendo(! !diminuendo)! !fermata! !accent! (or >), !ped! !ped-up!,
12
12
  // and two extensions: !rit(! … !rit)! (slow down by ~30 % across the span) and !breath!.
13
13
  //
14
- // For launch films: a voice with inst=drums (kit=pop|acoustic|808|cinematic) reads its notes on the General
14
+ // For launch films: a voice with inst=drums (kit=pop|acoustic|808|cinematic|lofi|gated|chip|folk) reads its notes on the General
15
15
  // MIDI drum map — C,, kick, ^C,, rim, D,, snare, ^D,, clap, ^F,, hat, ^A,, open hat, A,, tom, ^C, crash,
16
16
  // ^F, tambourine, ^A shaker. Cue marks become sound design on the beat: !hit! (impact on the reveal),
17
17
  // !rise(! … !rise)! (a riser that lands where it closes), !mark:name! (a named moment, for lining the score
@@ -82,10 +82,13 @@ export function parseAbc(text) {
82
82
  }
83
83
  if (!order.length) vdef('1');
84
84
  const [mn, md] = meterOf(head.M);
85
- const st = Object.fromEntries(order.map((v) => [v, { beat: 0, acc: {}, dyn: DYN.mf, ramp: null, tieFrom: null, repeatStart: 0, lastRepeat: -1 }]));
85
+ const st = Object.fromEntries(order.map((v) => [v, { beat: 0, acc: {}, dyn: DYN.mf, ramp: null, tieFrom: null, repeatStart: 0, lastRepeat: -1, bar: 1, barStart: 0 }]));
86
+ // A key change holds from its beat on, for every voice, whichever voice wrote it (voices are read one after
87
+ // another, so a key kept as running state leaked from the end of one voice into the start of the next).
88
+ const keys = [{ beat: 0, key: keySignature(head.K) }], warnings = [];
86
89
  const cues = [], riseOpen = {};
87
90
  const events = [], tempo = [{ beat: 0, qpm: qpmOf(head.Q) || 90 }], rits = [], breaths = [], fermatas = [], pedal = {}, ramps = [];
88
- let key = keySignature(head.K), meter = [mn, md], L = head.L ? frac(head.L.replace(/^1\//, '1/'), 0.125) : (mn / md < 0.75 ? 1 / 16 : 1 / 8);
91
+ let meter = [mn, md], L = head.L ? frac(head.L.replace(/^1\//, '1/'), 0.125) : (mn / md < 0.75 ? 1 / 16 : 1 / 8);
89
92
  let barLen = meter[0] * 4 / meter[1];
90
93
  let vcur = order[0], ritOpen = null;
91
94
 
@@ -118,6 +121,11 @@ export function parseAbc(text) {
118
121
  const k = toks[t];
119
122
  if (k.bar != null) {
120
123
  s.acc = {};
124
+ const got = s.beat - s.barStart;
125
+ if (got > 1e-6) { // a bar that is too long or too short moves everything after it off the other voices
126
+ if (Math.abs(got - barLen) > 1e-4 && !(s.bar === 1 && got < barLen)) warnings.push(`voice ${vid} bar ${s.bar} has ${+got.toFixed(3)} beats, the meter wants ${+barLen.toFixed(3)}`);
127
+ s.bar++; s.barStart = s.beat;
128
+ }
121
129
  if (k.bar.includes(':') && k.bar.indexOf(':') > k.bar.indexOf('|') && k.bar.startsWith('|')) repStart = t + 1;
122
130
  else if (/^:/.test(k.bar) && s.lastRepeat !== t) { s.lastRepeat = t; t = repStart - 1; continue; }
123
131
  else if (/:$/.test(k.bar)) repStart = t + 1;
@@ -125,7 +133,7 @@ export function parseAbc(text) {
125
133
  }
126
134
  if (k.field) {
127
135
  const [f, val] = [k.field[0], k.field.slice(2)];
128
- if (f === 'K') key = keySignature(val);
136
+ if (f === 'K') keys.push({ beat: s.beat, key: keySignature(val) });
129
137
  if (f === 'M') { meter = meterOf(val); barLen = meter[0] * 4 / meter[1]; }
130
138
  if (f === 'L') L = frac(val.replace(/^1\//, '1/'), L);
131
139
  if (f === 'Q') tempo.push({ beat: s.beat, qpm: qpmOf(val) || tempo.at(-1).qpm });
@@ -155,7 +163,8 @@ export function parseAbc(text) {
155
163
  const parts = k.note.startsWith('[') ? [...k.note.slice(1, -1).matchAll(/([\^_=]*)([A-Ga-g])([,']*)([0-9/]*)/g)] : [/^([\^_=]*)([A-Ga-gzxZ])([,']*)/.exec(k.note)];
156
164
  if (k.note.startsWith('[') && !k.len && parts[0]?.[4]) len = frac(parts[0][4], 1) * L * 4;
157
165
  if (tuplet) { len *= tuplet.q / tuplet.n; if (--tuplet.left <= 0) tuplet = null; }
158
- if (/[zxZ]/.test(k.note)) { s.beat += /Z/.test(k.note) ? barLen * frac(k.len, 1) : len; deco = []; continue; }
166
+ if (/Z/.test(k.note)) { const n = frac(k.len, 1); s.beat += barLen * n; s.bar += n - 1; s.barStart += barLen * (n - 1); deco = []; continue; } // Z4: four whole bars
167
+ if (/[zx]/.test(k.note)) { s.beat += len; deco = []; continue; }
159
168
  const fermata = deco.includes('fermata'), accent = deco.includes('accent') || deco.includes('>');
160
169
  if (fermata) fermatas.push(s.beat + len);
161
170
  const chordNotes = [];
@@ -163,14 +172,14 @@ export function parseAbc(text) {
163
172
  const U = letter.toUpperCase(), octave = (letter === U ? 4 : 5) + (oct.match(/'/g) || []).length - (oct.match(/,/g) || []).length;
164
173
  const id = `${U}${octave}`;
165
174
  if (acc) s.acc[id] = acc.startsWith('^') ? acc.length : acc.startsWith('_') ? -acc.length : 0;
166
- const a = s.acc[id] ?? (v.inst === 'drums' ? 0 : key[U] ?? 0);
167
- chordNotes.push(12 * (octave + 1) + LETTER[U] + a + v.transpose);
175
+ const keyed = s.acc[id] == null && v.inst !== 'drums'; // takes the key signature, resolved once every voice is read
176
+ chordNotes.push([12 * (octave + 1) + LETTER[U] + (s.acc[id] ?? 0) + v.transpose, keyed ? U : null]);
168
177
  }
169
178
  const tie = s.tieFrom && s.tieFrom.beat + s.tieFrom.dur >= s.beat - 1e-6;
170
- chordNotes.forEach((midi, ci) => {
171
- const prev = tie ? events.find((e) => e.voice === vid && e.midi === midi && Math.abs(e.beat + e.dur - s.beat) < 1e-6) : null;
179
+ chordNotes.forEach(([midi, keyed], ci) => {
180
+ const prev = tie ? events.find((e) => e.voice === vid && e.midi === midi && e.keyed === keyed && Math.abs(e.beat + e.dur - s.beat) < 1e-6) : null;
172
181
  if (prev) { prev.dur += len; return; }
173
- events.push({ voice: vid, beat: s.beat, dur: len, midi, vel: s.dyn, accent, fermata, top: ci === chordNotes.length - 1 && chordNotes.length > 1, chord: chordNotes.length });
182
+ events.push({ voice: vid, beat: s.beat, dur: len, midi, keyed, vel: s.dyn, accent, fermata, top: ci === chordNotes.length - 1 && chordNotes.length > 1, chord: chordNotes.length });
174
183
  });
175
184
  s.tieFrom = null;
176
185
  s.beat += len;
@@ -183,7 +192,7 @@ export function parseAbc(text) {
183
192
  const parts = item.text.split(/(\[V:[^\]]+\])/);
184
193
  for (const part of parts) {
185
194
  const vm = /^\[V:([^\]]+)\]$/.exec(part);
186
- if (vm) { vcur = vdef(vm[1].trim()); if (!st[vcur]) st[vcur] = { beat: 0, acc: {}, dyn: DYN.mf, ramp: null, tieFrom: null, lastRepeat: -1 }; continue; }
195
+ if (vm) { vcur = vdef(vm[1].trim()); if (!st[vcur]) st[vcur] = { beat: 0, acc: {}, dyn: DYN.mf, ramp: null, tieFrom: null, lastRepeat: -1, bar: 1, barStart: 0 }; continue; }
187
196
  if (part.trim()) run(part, vcur);
188
197
  }
189
198
  }
@@ -194,8 +203,14 @@ export function parseAbc(text) {
194
203
  const start = inside[0]?.vel ?? DYN.mf, endV = after && after.vel !== start ? after.vel : Math.max(0.15, Math.min(0.95, start + 0.2 * r.dir));
195
204
  for (const e of inside) e.vel = start + (endV - start) * ((e.beat - r.from) / Math.max(1e-6, r.to - r.from));
196
205
  }
206
+ keys.sort((a, b) => a.beat - b.beat);
207
+ for (const e of events) {
208
+ if (e.keyed) { let k = keys[0].key; for (const c of keys) if (c.beat <= e.beat + 1e-6) k = c.key; e.midi += k[e.keyed] ?? 0; }
209
+ delete e.keyed;
210
+ }
197
211
  const length = Math.max(0, ...Object.values(st).map((x) => x.beat));
198
- return { title: head.T, meter, barLen, events: events.sort((a, b) => a.beat - b.beat), voices, order, tempo, rits, breaths, fermatas, pedal, cues, length };
212
+ for (const v of order) if (st[v].beat > 0 && length - st[v].beat > 1e-4) warnings.push(`voice ${v} ends at beat ${+st[v].beat.toFixed(3)}, the score at ${+length.toFixed(3)}: write every bar in every voice`);
213
+ return { title: head.T, meter, barLen, events: events.sort((a, b) => a.beat - b.beat), voices, order, tempo, rits, breaths, fermatas, pedal, cues, length, warnings };
199
214
  }
200
215
 
201
216
  // Beats (quarter notes) → seconds, through the tempo changes, ritardandos (tempo eases down to 70 %),
@@ -319,6 +334,12 @@ export const DRUM_KITS = {
319
334
  acoustic: { kick: 'kicksoft', snare: 'snare', hat: 'hat', ohat: 'ohat', tamb: 'shaker' },
320
335
  808: { kick: 'kick808', snare: 'clap', hat: 'hat808', tamb: 'shaker' },
321
336
  cinematic: { kick: 'taiko', snare: 'snarebig', hat: 'shaker', ohat: 'crash', tom: 'taiko' },
337
+ // the rest of score.js's drum voices, reachable from a score: a dusty boom-bap kit, the gated 80s snare,
338
+ // the 8-bit kit, and body percussion (stomp, snaps, frame drum) for folk and acoustic songs
339
+ lofi: { kick: 'kicksoft', snare: 'snarelofi', clap: 'snap', hat: 'hat', ohat: 'ohat', tamb: 'shaker' },
340
+ gated: { kick: 'kick', snare: 'snaregated', clap: 'snaregated', hat: 'hat', ohat: 'ohat', tamb: 'shaker' },
341
+ chip: { kick: 'kickchip', snare: 'snarechip', clap: 'snarechip', hat: 'hatchip', ohat: 'hatchip', tamb: 'hatchip' },
342
+ folk: { kick: 'stomp', snare: 'snap', clap: 'clap', hat: 'shaker', ohat: 'shaker', tom: 'frame', rim: 'woodblock', tamb: 'shaker' },
322
343
  };
323
344
  // A bowed or blown note is shaped by the player, not the sample: the bow or breath eases in (slower when
324
345
  // soft), a long note swells and relaxes (messa di voce), and its tail eases out instead of stopping.
@@ -0,0 +1,239 @@
1
+ // om grab — the product's real material into <project>/materials/, before any direction is drawn. A film about a
2
+ // product is made of the product: its logo as a file, its own colours and typefaces, its real interface. Agents that had
3
+ // to collect these by hand drew grey boxes instead; this collects them in one command.
4
+ //
5
+ // om grab <url> [dir] a website or a GitHub repo page: screenshots down the page (2x), the images on it, logo
6
+ // candidates (icons, og:image, inline SVG logos), the colours and typefaces it really uses
7
+ // om grab <folder> [dir] the product's own project on this machine: README images, screenshots, media, icons, and
8
+ // the colours and fonts its stylesheets declare
9
+ //
10
+ // Every file gets a line in materials/manifest.json and materials.md saying where it came from.
11
+ import { spawnSync } from 'node:child_process';
12
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync, appendFileSync } from 'node:fs';
13
+ import { basename, extname, join, relative, resolve } from 'node:path';
14
+ import { findChrome, NO_CHROME } from './browser.js';
15
+ import { launch, newPage } from './cdp.js';
16
+ import { OmError } from './project.js';
17
+
18
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
19
+ const MEDIA = /\.(png|jpe?g|webp|gif|svg|avif|mp4|mov|webm|icns|ico)$/i;
20
+ const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', 'out', '.om', '_archive', '.next', 'coverage', 'vendor', 'Pods', 'DerivedData', '.cache']);
21
+
22
+ function slug(s) { return String(s).toLowerCase().replace(/^https?:\/\//, '').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 48) || 'source'; }
23
+
24
+ // The materials folder and its two indexes: manifest.json for tools, materials.md for people and the treatment.
25
+ function ledger(root) {
26
+ const dir = join(root, 'materials');
27
+ mkdirSync(dir, { recursive: true });
28
+ const file = join(dir, 'manifest.json');
29
+ let m = { sources: [] };
30
+ try { m = JSON.parse(readFileSync(file, 'utf8')); } catch { /* new */ }
31
+ return { dir, add(source) { m.sources = m.sources.filter((s) => s.from !== source.from).concat(source); writeFileSync(file, JSON.stringify(m, null, 2)); } };
32
+ }
33
+
34
+ function writeMd(root, source) {
35
+ const md = join(root, 'materials.md');
36
+ if (!existsSync(md)) writeFileSync(md, `# Materials\n\nWhat the film is made of, and where each piece came from. Real material first: the logo as a file, the product's own colours and type, its real interface. Anything rebuilt is traced over a capture listed here.\n`);
37
+ const rel = (f) => relative(root, f).split('\\').join('/');
38
+ const lines = [`\n## ${source.kind === 'web' ? 'Web' : 'Local'} · ${source.from} (${source.at.slice(0, 10)})\n`];
39
+ const by = (k) => source.files.filter((f) => f.kind === k);
40
+ for (const [k, label] of [['logo', 'Logo / icon'], ['screen', 'Screenshots of the page'], ['image', 'Images'], ['video', 'Video'], ['media', 'Media files']]) {
41
+ const fs = by(k);
42
+ if (fs.length) lines.push(`- ${label} (${fs.length}): ${fs.slice(0, 12).map((f) => `\`${rel(f.file)}\`${source.kind === 'local' ? ` ← ${f.from}` : ''}${f.note ? ` ${f.note}` : ''}`).join(', ')}${fs.length > 12 ? ', …' : ''}`);
43
+ }
44
+ if (source.colours?.length) lines.push(`- Colours it uses: ${source.colours.slice(0, 10).map((c) => `${c.hex} (${c.role})`).join(' · ')}`);
45
+ if (source.fonts?.length) lines.push(`- Typefaces: ${source.fonts.slice(0, 6).map((f) => f.family).join(' · ')}`);
46
+ if (source.missing?.length) lines.push(`- Not captured: ${source.missing.join('; ')}`);
47
+ appendFileSync(md, lines.join('\n') + '\n');
48
+ return md;
49
+ }
50
+
51
+ function curl(url, file, referer) {
52
+ const r = spawnSync('curl', ['-sSL', '--max-time', '40', '--max-filesize', String(30 << 20), '-A', 'Mozilla/5.0 (huashu-motion om grab)', ...(referer ? ['-e', referer] : []), '-o', file, url], { encoding: 'utf8' });
53
+ return r.status === 0 && existsSync(file) && statSync(file).size > 200;
54
+ }
55
+
56
+ // ---------- web ----------
57
+ const PAGE_FACTS = `(() => {
58
+ const vis = (el) => { const r = el.getBoundingClientRect(), s = getComputedStyle(el); return r.width > 1 && r.height > 1 && s.visibility !== 'hidden' && s.display !== 'none' && Number(s.opacity) > 0.05; };
59
+ const abs = (u) => { try { return new URL(u, location.href).href; } catch (e) { return null; } };
60
+ const images = [];
61
+ for (const im of document.images) if (im.naturalWidth >= 240 && im.naturalHeight >= 120) images.push({ src: abs(im.currentSrc || im.src), w: im.naturalWidth, h: im.naturalHeight, alt: (im.alt || '').slice(0, 80) });
62
+ for (const el of document.querySelectorAll('*')) { const b = getComputedStyle(el).backgroundImage; const m = b && /url\\(["']?([^"')]+)["']?\\)/.exec(b); if (m && el.getBoundingClientRect().width >= 240) images.push({ src: abs(m[1]), w: Math.round(el.getBoundingClientRect().width), h: Math.round(el.getBoundingClientRect().height), alt: 'background' }); }
63
+ const videos = [...document.querySelectorAll('video')].map((v) => ({ src: abs(v.currentSrc || v.src || (v.querySelector('source') || {}).src), poster: abs(v.poster) })).filter((v) => v.src || v.poster);
64
+ const logos = [];
65
+ for (const l of document.querySelectorAll('link[rel~="icon"],link[rel="apple-touch-icon"],link[rel="mask-icon"]')) logos.push({ src: abs(l.href), note: l.rel + (l.sizes && l.sizes.value ? ' ' + l.sizes.value : '') });
66
+ for (const m of document.querySelectorAll('meta[property="og:image"],meta[name="twitter:image"]')) logos.push({ src: abs(m.content), note: m.getAttribute('property') || m.getAttribute('name') });
67
+ const isLogo = (el) => /logo|brand|wordmark|lockup/i.test([el.id, el.getAttribute('class'), el.getAttribute('alt'), el.getAttribute('aria-label'), el.getAttribute('src')].join(' '));
68
+ for (const im of document.querySelectorAll('img')) if (isLogo(im) || isLogo(im.parentElement || im)) logos.push({ src: abs(im.currentSrc || im.src), note: 'img ' + (im.alt || '') });
69
+ const svgs = [];
70
+ for (const s of document.querySelectorAll('svg')) { if (!vis(s) || s.parentElement.closest('svg')) continue; const host = s.closest('a,header,nav,[class*=logo],[id*=logo]'); if (isLogo(s) || (host && (isLogo(host) || host.matches('header a:first-of-type, nav a:first-of-type')))) svgs.push(s.outerHTML.slice(0, 200000)); }
71
+ // colours, weighted: grounds by area, type by characters, accents from buttons and links
72
+ const tally = {}, add = (c, role, w) => { if (!c || /rgba?\\(0, 0, 0, 0\\)|transparent/.test(c)) return; const k = role + '|' + c; tally[k] = (tally[k] || 0) + w; };
73
+ const all = [...document.querySelectorAll('body, body *')].slice(0, 6000);
74
+ for (const el of all) {
75
+ if (!vis(el)) continue;
76
+ const s = getComputedStyle(el), r = el.getBoundingClientRect();
77
+ add(s.backgroundColor, 'ground', Math.min(r.width * r.height, 4e6));
78
+ const own = [...el.childNodes].filter((n) => n.nodeType === 3).map((n) => n.textContent.trim()).join('').length;
79
+ if (own) add(s.color, 'type', own);
80
+ if (el.matches('button, a[class*=btn], a[class*=button], [role=button], .btn, .button')) { add(s.backgroundColor, 'accent', 400); add(s.borderColor, 'accent', 100); }
81
+ if (el.matches('a')) add(s.color, 'accent', 30);
82
+ }
83
+ const fonts = {};
84
+ for (const el of all) { if (!vis(el)) continue; const own = [...el.childNodes].filter((n) => n.nodeType === 3).map((n) => n.textContent.trim()).join('').length; if (!own) continue; const f = getComputedStyle(el).fontFamily.split(',')[0].replace(/["']/g, '').trim(); fonts[f] = (fonts[f] || 0) + own; }
85
+ const vars = {};
86
+ for (const sh of document.styleSheets) { let rules; try { rules = sh.cssRules; } catch (e) { continue; } for (const r of rules) { if (!r.style) continue; for (const p of r.style) if (p.startsWith('--')) { const v = r.style.getPropertyValue(p).trim(); if (/^(#[0-9a-f]{3,8}|rgba?\\(|hsla?\\(|oklch\\()/i.test(v)) vars[p] = v; } } }
87
+ return { title: document.title, description: (document.querySelector('meta[name=description]') || {}).content || '', height: document.documentElement.scrollHeight, images, videos, logos, svgs, tally, fonts, vars };
88
+ })()`;
89
+
90
+ const toHex = (c) => { const m = /rgba?\(([^)]+)\)/.exec(c); if (!m) return c; const [r, g, b] = m[1].split(/[\s,/]+/).map(Number); return '#' + [r, g, b].map((x) => Math.round(x).toString(16).padStart(2, '0')).join(''); };
91
+
92
+ export async function grabWeb(root, url, { maxShots = 8, maxImages = 40, onLog = () => {} } = {}) {
93
+ const chrome = findChrome();
94
+ if (!chrome) throw new OmError(NO_CHROME);
95
+ const L = ledger(root);
96
+ const host = slug(url);
97
+ const dir = join(L.dir, `web-${host}`);
98
+ mkdirSync(dir, { recursive: true });
99
+ const conn = await launch(chrome, { args: ['--window-size=1440,900'] });
100
+ const files = [], missing = [];
101
+ let facts;
102
+ try {
103
+ const page = await newPage(conn);
104
+ await Promise.all([page.send('Page.enable'), page.send('Runtime.enable')]);
105
+ await page.send('Emulation.setDeviceMetricsOverride', { width: 1440, height: 900, deviceScaleFactor: 2, mobile: false });
106
+ const loaded = new Promise((ok) => page.on('Page.loadEventFired', ok));
107
+ const nav = await page.send('Page.navigate', { url });
108
+ if (nav.errorText) throw new OmError(`could not open ${url}: ${nav.errorText}`);
109
+ await Promise.race([loaded, sleep(30_000)]);
110
+ await sleep(1500);
111
+ // walk the page once so lazy images load, then back to the top
112
+ const h0 = await page.evaluate('document.documentElement.scrollHeight');
113
+ for (let y = 0; y < Math.min(h0, 900 * maxShots); y += 700) { await page.evaluate(`window.scrollTo(0, ${y})`); await sleep(150); }
114
+ await page.evaluate('window.scrollTo(0, 0)'); await sleep(800);
115
+ facts = await page.evaluate(PAGE_FACTS);
116
+ const shots = Math.max(1, Math.min(maxShots, Math.ceil(facts.height / 900)));
117
+ for (let i = 0; i < shots; i++) {
118
+ await page.evaluate(`window.scrollTo(0, ${i * 900})`); await sleep(500);
119
+ const { data } = await page.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, 30_000);
120
+ const file = join(dir, `screen-${String(i + 1).padStart(2, '0')}.png`);
121
+ writeFileSync(file, Buffer.from(data, 'base64'));
122
+ files.push({ kind: 'screen', file, from: url, note: `y=${i * 900}px, 2x` });
123
+ }
124
+ if (facts.height > 900 * maxShots) missing.push(`page continues below ${900 * maxShots}px (raise --shots)`);
125
+ } finally { await conn.close(); }
126
+
127
+ // downloads: logos first, then the largest images, then video posters/sources
128
+ const seen = new Set();
129
+ const take = (src, kind, note, n) => {
130
+ if (!src || seen.has(src) || src.startsWith('data:') && src.length > 2e6) return;
131
+ seen.add(src);
132
+ const ext = (/\.(png|jpe?g|webp|gif|svg|avif|ico|mp4|webm|mov)(\?|#|$)/i.exec(src)?.[1] || (kind === 'video' ? 'mp4' : 'png')).toLowerCase();
133
+ const file = join(dir, `${kind}-${String(n).padStart(2, '0')}.${ext}`);
134
+ let ok;
135
+ if (src.startsWith('data:')) { const m = /^data:[^;,]+(;base64)?,(.*)$/s.exec(src); ok = !!m; if (m) writeFileSync(file, m[1] ? Buffer.from(m[2], 'base64') : decodeURIComponent(m[2])); }
136
+ else ok = curl(src, file, url);
137
+ if (ok) files.push({ kind, file, from: src, note });
138
+ else missing.push(`${kind} ${src.slice(0, 90)}`);
139
+ };
140
+ let n = 0;
141
+ for (const l of facts.logos) take(l.src, 'logo', l.note, ++n);
142
+ facts.svgs.forEach((s, i) => { const file = join(dir, `logo-svg-${i + 1}.svg`); writeFileSync(file, s.includes('xmlns=') ? s : s.replace('<svg', '<svg xmlns="http://www.w3.org/2000/svg"')); files.push({ kind: 'logo', file, from: url, note: 'inline SVG from the page' }); });
143
+ n = 0;
144
+ for (const im of facts.images.sort((a, b) => b.w * b.h - a.w * a.h).slice(0, maxImages)) take(im.src, 'image', `${im.w}×${im.h}${im.alt ? ` "${im.alt}"` : ''}`, ++n);
145
+ n = 0;
146
+ for (const v of facts.videos) { if (v.src) take(v.src, 'video', 'video on the page', ++n); if (v.poster) take(v.poster, 'image', 'video poster', ++n); }
147
+
148
+ const colours = Object.entries(facts.tally).map(([k, w]) => { const [role, c] = k.split('|'); return { role, hex: toHex(c), w }; });
149
+ const merged = {};
150
+ for (const c of colours) { const k = c.role + c.hex; merged[k] = merged[k] ? { ...merged[k], w: merged[k].w + c.w } : c; }
151
+ const top = (role, n) => Object.values(merged).filter((c) => c.role === role).sort((a, b) => b.w - a.w).slice(0, n);
152
+ const palette = [...top('ground', 4), ...top('type', 3), ...top('accent', 4)];
153
+ for (const [k, v] of Object.entries(facts.vars).slice(0, 24)) palette.push({ role: `css ${k}`, hex: v });
154
+ const fonts = Object.entries(facts.fonts).sort((a, b) => b[1] - a[1]).slice(0, 6).map(([family, chars]) => ({ family, chars }));
155
+ const source = { kind: 'web', from: url, at: new Date().toISOString(), title: facts.title, description: facts.description, files: files.map((f) => ({ ...f, file: relative(root, f.file).split('\\').join('/') })), colours: palette, fonts, missing };
156
+ L.add(source);
157
+ const md = writeMd(root, { ...source, files });
158
+ return { dir, files, colours: palette, fonts, missing, md, title: facts.title };
159
+ }
160
+
161
+ // ---------- local project ----------
162
+ export function grabLocal(root, folder, { maxFiles = 60, onLog = () => {} } = {}) {
163
+ const src = resolve(folder);
164
+ if (!existsSync(src) || !statSync(src).isDirectory()) throw new OmError(`${src} is not a folder`);
165
+ const L = ledger(root);
166
+ const dir = join(L.dir, `local-${slug(basename(src))}`);
167
+ mkdirSync(dir, { recursive: true });
168
+ const found = [], css = [];
169
+ const walk = (d, depth) => {
170
+ if (depth > 6) return;
171
+ let entries; try { entries = readdirSync(d, { withFileTypes: true }); } catch { return; }
172
+ for (const e of entries) {
173
+ if (e.name.startsWith('.') && e.name !== '.github') continue;
174
+ const p = join(d, e.name);
175
+ if (e.isDirectory()) { if (!SKIP_DIRS.has(e.name) && resolve(p) !== resolve(root)) walk(p, depth + 1); continue; }
176
+ if (!e.isFile()) continue;
177
+ if ((/\.(css|scss|less)$/i.test(e.name) || (/\.html?$/i.test(e.name) && statSync(p).size < 400_000)) && css.length < 60) css.push(p);
178
+ if (!MEDIA.test(e.name)) continue;
179
+ const size = statSync(p).size;
180
+ const icon = /icon|logo|favicon|appicon|brand|wordmark/i.test(p);
181
+ if (size < (icon ? 200 : 15_000) || size > 80 << 20) continue;
182
+ found.push({ p, size, icon });
183
+ }
184
+ };
185
+ walk(src, 0);
186
+ // what the README shows first: those images are the product as its maker presents it
187
+ const readme = readdirSync(src).find((n) => /^readme(\.[a-z]+)?\.md$/i.test(n));
188
+ const featured = new Set();
189
+ if (readme) {
190
+ const text = readFileSync(join(src, readme), 'utf8');
191
+ for (const m of text.matchAll(/!\[[^\]]*\]\(([^)\s]+)|<img[^>]+src=["']([^"']+)["']/g)) {
192
+ const ref = (m[1] || m[2] || '').split(/[?#]/)[0];
193
+ if (ref && !/^https?:/.test(ref)) { const f = resolve(src, ref); if (existsSync(f)) featured.add(f); }
194
+ }
195
+ }
196
+ const rank = (x) => (featured.has(x.p) ? 0 : x.icon ? 1 : /screen|shot|截屏|截图|demo|media|preview|素材|promo|banner/i.test(x.p) ? 2 : 3);
197
+ const pick = found.sort((a, b) => rank(a) - rank(b) || b.size - a.size).slice(0, maxFiles);
198
+ const files = [];
199
+ const used = new Set();
200
+ for (const x of pick) {
201
+ let name = basename(x.p);
202
+ while (used.has(name)) name = '_' + name;
203
+ used.add(name);
204
+ const file = join(dir, name);
205
+ copyFileSync(x.p, file);
206
+ const kind = x.icon ? 'logo' : /\.(mp4|mov|webm)$/i.test(x.p) ? 'video' : /screen|shot|截屏|截图/i.test(x.p) ? 'screen' : 'media';
207
+ files.push({ kind, file, from: relative(src, x.p).split('\\').join('/'), note: featured.has(x.p) ? '(in the README)' : '' });
208
+ }
209
+ // the colours and fonts the stylesheets declare: custom properties first, then the most used values
210
+ const counts = {}, vars = {}, fonts = {};
211
+ for (const f of css) {
212
+ const t = readFileSync(f, 'utf8');
213
+ for (const m of t.matchAll(/(--[\w-]+)\s*:\s*(#[0-9a-fA-F]{3,8}|rgba?\([^)]+\)|hsla?\([^)]+\)|oklch\([^)]+\))/g)) vars[m[1]] = m[2];
214
+ for (const m of t.matchAll(/#[0-9a-fA-F]{6}\b/g)) counts[m[0].toLowerCase()] = (counts[m[0].toLowerCase()] || 0) + 1;
215
+ for (const m of t.matchAll(/font-family\s*:\s*([^;}{]+)/g)) { const fam = m[1].split(',')[0].replace(/["']/g, '').trim(); if (fam && !fam.startsWith('var(')) fonts[fam] = (fonts[fam] || 0) + 1; }
216
+ }
217
+ const colours = [...Object.entries(vars).slice(0, 24).map(([k, v]) => ({ role: `css ${k}`, hex: v })), ...Object.entries(counts).sort((a, b) => b[1] - a[1]).slice(0, 8).map(([hex, c]) => ({ role: `used ${c}×`, hex }))];
218
+ const fontList = Object.entries(fonts).sort((a, b) => b[1] - a[1]).slice(0, 6).map(([family, n]) => ({ family, n }));
219
+ const missing = [];
220
+ if (!files.some((f) => f.kind === 'logo')) missing.push('no logo or icon file found — look in the app bundle, the site (om grab <url>) or ask the user');
221
+ if (!files.some((f) => f.kind === 'screen' || f.kind === 'video')) missing.push('no screenshots or recordings — run the product and capture it');
222
+ const source = { kind: 'local', from: src, at: new Date().toISOString(), files: files.map((f) => ({ ...f, file: relative(root, f.file).split('\\').join('/') })), colours, fonts: fontList, missing };
223
+ L.add(source);
224
+ const md = writeMd(root, { ...source, files });
225
+ return { dir, files, colours, fonts: fontList, missing, md };
226
+ }
227
+
228
+ export async function grab(root, target, opts = {}) {
229
+ const r = /^https?:\/\//i.test(target) ? await grabWeb(root, target, opts) : grabLocal(root, target, opts);
230
+ const count = (k) => r.files.filter((f) => f.kind === k).length;
231
+ const rel = (f) => relative(root, f).split('\\').join('/');
232
+ const lines = [`grab ${target}${r.title ? ` "${r.title}"` : ''}`,
233
+ ` ${rel(r.dir)}/ logo ${count('logo')} · screens ${count('screen')} · images ${count('image') + count('media')} · video ${count('video')}`,
234
+ r.colours.length ? ` colours ${r.colours.slice(0, 8).map((c) => `${c.hex} ${c.role}`).join(' · ')}` : ' colours none found',
235
+ r.fonts.length ? ` type ${r.fonts.map((f) => f.family).join(' · ')}` : ' type none found',
236
+ ` ${rel(r.md)} updated — look at every file before choosing a direction (om still can't see them for you)`];
237
+ for (const m of r.missing.slice(0, 6)) lines.push(` ! ${m}`);
238
+ return lines.join('\n');
239
+ }
package/cli/lib/qa.js CHANGED
@@ -3,7 +3,8 @@
3
3
  // (stretches where nothing moves), hard cuts, whether the last frame matches the first (loops), and
4
4
  // the motion curve per second so a flat film is visible as a flat line.
5
5
  import { spawnSync } from 'node:child_process';
6
- import { existsSync } from 'node:fs';
6
+ import { existsSync, mkdirSync, readdirSync, unlinkSync } from 'node:fs';
7
+ import { basename, join } from 'node:path';
7
8
  import { OmError } from './project.js';
8
9
 
9
10
  const W = 96, H = 54;
@@ -59,10 +60,37 @@ export function qa(file, { loop = false } = {}) {
59
60
  const mean = perSec.reduce((a, b) => a + b, 0) / (perSec.length || 1);
60
61
  const sd = Math.sqrt(perSec.reduce((a, b) => a + (b - mean) ** 2, 0) / (perSec.length || 1));
61
62
  const loopGap = +diff(f[0], f[f.length - 1]).toFixed(2);
63
+ // The opening and the whole: what separates a film people watch from a slide deck that happens to move. Measured on
64
+ // 15 films the user signed off (2026-10) against a one-line film by a new user: their strongest second in the first
65
+ // 5 s was 2.0–24 (median ~6) with no still stretch over 1.1 s there, and the whole film averaged 0.85–5.8; the
66
+ // one-line film peaked at 0.9 in its first 5 s, stood still from 0.95 to 4.2 s and averaged 0.18 with no cut.
67
+ const head = perSec.slice(0, 5), stillHead = dead.filter((x) => x.from < 5 && x.seconds >= 1.5);
68
+ const opening = { peak: head.length ? Math.max(...head) : 0, still: stillHead, flat: info.duration >= 6 && ((head.length ? Math.max(...head) : 0) < 1.5 || stillHead.length > 0) };
69
+ const flatFilm = info.duration >= 6 && mean < 0.6 && cuts.length / info.duration * 60 < 3;
70
+ // Frame 0 is the poster: feeds and players show it before the film plays, a README GIF shows it while it loads, a
71
+ // share preview often is it. "Content" = pixels away from the frame's median grey and edges between neighbours.
72
+ // Measured 2026-10-22: films that open on their subject had 7–94 % such pixels and 2–18 % edges in frame 0; a blank
73
+ // page, black, or a lone small mark on black had under 2.5 % and 1.2 % (three of the user's approved films opened
74
+ // that way, fading up over ~2 s — fine to watch, an empty poster).
75
+ const content = (px) => {
76
+ const m = median(px);
77
+ let far = 0, edges = 0;
78
+ for (let i = 0; i < px.length; i++) {
79
+ if (Math.abs(px[i] - m) > 16) far++;
80
+ if (i % W < W - 1 && Math.abs(px[i] - px[i + 1]) > 20) edges++;
81
+ }
82
+ return { far: far / px.length, edges: edges / (H * (W - 1)) };
83
+ };
84
+ const filled = (c) => c.far >= 0.05 && c.edges >= 0.015;
85
+ const c0 = f.length ? content(f[0]) : { far: 0, edges: 0 };
86
+ let arrives = null;
87
+ for (let i = 0; i < f.length && i < fps * 10; i++) if (filled(content(f[i]))) { arrives = t(i); break; }
88
+ const firstFrame = { far: +c0.far.toFixed(3), edges: +c0.edges.toFixed(3), empty: c0.far < 0.03 && c0.edges < 0.012, contentAt: arrives };
62
89
  return {
63
90
  file, ...info, frames: f.length,
64
91
  pops, cuts, dead,
65
92
  motion: { perSecond: perSec, mean: +mean.toFixed(2), contrast: +(sd / (mean + 1e-6)).toFixed(2) },
93
+ opening, flatFilm, firstFrame,
66
94
  loop: { firstLastDiff: loopGap, seamless: loopGap < 1.5, checked: loop },
67
95
  };
68
96
  }
@@ -73,6 +101,30 @@ export function report(r) {
73
101
  lines.push(r.dead.length ? `${r.dead.some((x) => x.seconds > 2) ? '✗' : '·'} still for ≥1 s: ${r.dead.map((x) => `${x.from}–${x.to}s`).join(', ')} — fine for a reading hold or an end card, dead time anywhere else` : '✓ no stretch of ≥1 s without motion');
74
102
  lines.push(`· ${r.cuts.length} hard cut(s)${r.cuts.length ? ': ' + r.cuts.slice(0, 20).join(', ') + 's' : ''} (average shot ${(r.duration / (r.cuts.length + 1)).toFixed(1)} s)`);
75
103
  lines.push(`· motion per second: ${r.motion.perSecond.join(' ')} (contrast ${r.motion.contrast}${r.motion.contrast < 0.35 ? ' — very even: the film may feel flat; give it fast and slow moments' : ''})`);
104
+ if (r.firstFrame && r.firstFrame.empty) lines.push(`✗ frame 0 is nearly empty — it is the poster feeds, players and README GIFs show before the film plays${r.firstFrame.contentAt != null ? `; the frame fills at ${r.firstFrame.contentAt}s` : ''}. Open on the subject already in frame (in motion), not on a blank, a black or a lone small mark the film builds from`);
105
+ if (r.opening && r.opening.flat) lines.push(`✗ flat opening: the strongest second of the first 5 s moves ${r.opening.peak}${r.opening.still.length ? `, still ${r.opening.still.map((x) => `${x.from}–${x.to}s`).join(', ')}` : ''} — films people kept peaked at 2–24 (median ~6) there with no still stretch over 1 s. Open on a big move (a push, a whip, a flood, the result slammed in) and land the first burst before 5 s, unless the brief asked for calm`);
106
+ if (r.flatFilm) lines.push(`✗ the whole film barely moves (mean ${r.motion.mean}, ${r.cuts.length} cuts) — it reads as slides. Films people kept averaged 0.85–5.8: cut, change shot scale, bring in a montage burst (rhythm.md)`);
76
107
  if (r.loop.checked) lines.push(r.loop.seamless ? `✓ last frame matches the first (diff ${r.loop.firstLastDiff}) — loops cleanly` : `✗ last frame differs from the first (diff ${r.loop.firstLastDiff}) — it will stutter as a loop`);
77
108
  return lines.join('\n');
78
109
  }
110
+
111
+ // om qa --sheet — the whole film as a few pictures: frames at a steady rate, tiled left to right, top to
112
+ // bottom. Looking at one still per scene finds layout faults; looking at every quarter second finds what a
113
+ // viewer feels: a stretch where neighbouring tiles are the same picture (dead), a run of scenes that are all
114
+ // the same picture with different content (slides), the one frame where something is half-way and ugly.
115
+ export function sheet(file, outDir, { fps = 4, cols = 6, rows = 6, width = 384 } = {}) {
116
+ if (!existsSync(file)) throw new OmError(`no such video: ${file}`);
117
+ const p = probe(file), per = cols * rows, stem = basename(file).replace(/\.[^.]+$/, '');
118
+ mkdirSync(outDir, { recursive: true });
119
+ for (const f of readdirSync(outDir)) if (f.startsWith(`${stem}-sheet`)) unlinkSync(join(outDir, f));
120
+ const r = spawnSync('ffmpeg', ['-v', 'error', '-y', '-i', file, '-vf', `fps=${fps},scale=${width}:-2,tile=${cols}x${rows}`, join(outDir, `${stem}-sheet%d.jpg`)]);
121
+ if (r.status !== 0) throw new OmError(`ffmpeg could not tile ${file}`);
122
+ const files = readdirSync(outDir).filter((f) => f.startsWith(`${stem}-sheet`)).sort((a, b) => parseInt(a.split('sheet').pop(), 10) - parseInt(b.split('sheet').pop(), 10)).map((f) => join(outDir, f));
123
+ return { files, fps, cols, rows, sheets: files.map((f, i) => ({ file: f, from: i * per / fps, to: Math.min(p.duration, (i + 1) * per / fps) })) };
124
+ }
125
+
126
+ export function sheetReport(s) {
127
+ return [`sheets ${s.fps} frames a second, read left to right; one row is ${(s.cols / s.fps).toFixed(2)} s`,
128
+ ...s.sheets.map((x) => ` ${x.from.toFixed(1)}–${x.to.toFixed(1)} s ${x.file}`),
129
+ ' look for: neighbouring tiles that are the same picture (dead), scenes that are the same layout with other content (slides), a tile caught half-way that is ugly'].join('\n');
130
+ }
@@ -57,7 +57,7 @@ const CONTAINERS = {
57
57
  };
58
58
  export const FORMATS = Object.keys(CONTAINERS);
59
59
 
60
- export async function renderOm(project, { fps, out, format = 'mp4', transparent = false, blur = 1, video = 'extract', frameFormat = 'png', workers = defaultWorkers(), shotFormat = null, paintWaits = 0, chunk = 8, preset = 'veryfast', crf = 16, software = false, onFrame = null, variables = null, allowPageErrors = false, prepare = null, verify = null, onLog = () => {}, onWarn = () => {} }) {
60
+ export async function renderOm(project, { fps, out, format = 'mp4', transparent = false, blur = 1, video = 'extract', frameFormat = 'png', workers = defaultWorkers(), shotFormat = null, paintWaits = 0, chunk = 8, preset = 'veryfast', crf = 16, software = false, onFrame = null, variables = null, allowPageErrors = false, prepare = null, verify = null, onLog = () => {}, onNote = onLog, onWarn = () => {} }) {
61
61
  if (!['extract', 'seek'].includes(video)) throw new OmError('--video must be extract or seek');
62
62
  if (!['jpg', 'png'].includes(frameFormat)) throw new OmError('--frames must be jpg or png');
63
63
  const box = CONTAINERS[format];
@@ -87,6 +87,8 @@ export async function renderOm(project, { fps, out, format = 'mp4', transparent
87
87
  }
88
88
  }
89
89
  const film = films[0];
90
+ const sig = await film.evaluate('window.__omEngine.signature()').catch(() => null);
91
+ if (sig) onNote(sig.on ? `signature on: "Made with huashu-motion" in a free corner for the last 1.2s (data-om-signature="off" on the root removes it)` : `signature off (${sig.why})`);
90
92
  const tmp = mkdtempSync(join(tmpdir(), 'om-render-'));
91
93
  const forgetTmp = cleanupOnInterrupt(() => rmSync(tmp, { recursive: true, force: true }));
92
94
  const picture = join(tmp, format === 'gif' ? 'picture.mp4' : `picture.${format}`);
package/cli/lib/render.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // om render: the film as a video file, through the huashu-motion renderer (render-om.js). Output always
2
2
  // lands in <project>/out/ with a new name — a render never overwrites a file the user may already have shared.
3
3
  import { spawnSync } from 'node:child_process';
4
- import { existsSync, mkdirSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
4
+ import { existsSync, mkdirSync, readdirSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
5
5
  import { join, sep } from 'node:path';
6
6
  import { OmError, readSource, readVariables } from './project.js';
7
7
  import { FORMATS, renderOm } from './render-om.js';
@@ -14,7 +14,9 @@ export function nextOutput(project, ext) {
14
14
  const dir = join(project.root, 'out');
15
15
  mkdirSync(dir, { recursive: true });
16
16
  const base = project.root.split(sep).pop();
17
- for (let v = 1; ; v++) {
17
+ // one past the highest version of any format: a deleted v1–v3 beside a kept v4 gives v5, never a new "v1"
18
+ const top = Math.max(0, ...readdirSync(dir).map((f) => (f.startsWith(`${base}-v`) ? parseInt(f.slice(base.length + 2), 10) || 0 : 0)));
19
+ for (let v = top + 1; ; v++) {
18
20
  const file = join(dir, `${base}-v${v}.${ext}`);
19
21
  try { writeFileSync(file, '', { flag: 'wx' }); return file; } catch (e) { if (e.code !== 'EEXIST') throw e; }
20
22
  }
@@ -24,7 +26,7 @@ export function nextOutput(project, ext) {
24
26
  // with alpha (WebM VP9 alpha also works); a composition that declares a boolean variable
25
27
  // `transparent` gets it set to true for this render (hide the footage, clear the background); the
26
28
  // sound is dropped because the edit underneath already has it; and the result is checked for alpha.
27
- export async function render(project, { format, fps, out, transparent = false, blur = 1, engine, video = 'extract', workers, frameFormat, tune = {}, allowPageErrors = false, prepare = null, onLog = () => {}, onWarn = () => {} } = {}) {
29
+ export async function render(project, { format, fps, out, transparent = false, blur = 1, engine, video = 'extract', workers, frameFormat, tune = {}, allowPageErrors = false, prepare = null, onLog = () => {}, onNote = onLog, onWarn = () => {} } = {}) {
28
30
  if (engine && engine !== 'om') throw new OmError(engine === 'hyperframes' ? 'the HyperFrames renderer was removed — om render uses its own engine now (drop --engine)' : '--engine must be om');
29
31
  const { html } = readSource(project);
30
32
  format = format || (transparent ? 'mov' : 'mp4');
@@ -45,7 +47,7 @@ export async function render(project, { format, fps, out, transparent = false, b
45
47
  const target = out || nextOutput(project, format);
46
48
  let r;
47
49
  try {
48
- r = await renderOm(project, { fps, out: target, format, transparent, blur, video, variables: switchVar ? { transparent: true } : null, ...(workers ? { workers } : {}), ...(frameFormat ? { frameFormat } : {}), ...tune, allowPageErrors, prepare, verify: transparent ? (file) => checkOverlay(file, switchVar, onWarn) : null, onLog, onWarn });
50
+ r = await renderOm(project, { fps, out: target, format, transparent, blur, video, variables: switchVar ? { transparent: true } : null, ...(workers ? { workers } : {}), ...(frameFormat ? { frameFormat } : {}), ...tune, allowPageErrors, prepare, verify: transparent ? (file) => checkOverlay(file, switchVar, onWarn) : null, onLog, onNote, onWarn });
49
51
  } catch (e) {
50
52
  // the version we claimed stays free for the next try (only the empty placeholder is removed, never a film)
51
53
  if (claimed && existsSync(target) && statSync(target).size === 0) unlinkSync(target);
@@ -0,0 +1,101 @@
1
+ // om share — after the render, the things a person needs to post the film: a GIF small enough for a README, X or a
2
+ // chat (≤ 10 MB: the opening plus the end frame with its signature), and share.md with where each file goes, a slot for
3
+ // the post the agent writes in the user's language, the line that says where the film came from, and a README snippet.
4
+ // Nothing is uploaded or posted: the user decides where it goes.
5
+ import { spawnSync } from 'node:child_process';
6
+ import { existsSync, mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
7
+ import { basename, join, relative } from 'node:path';
8
+ import { OmError } from './project.js';
9
+ import { REPO_URL } from './export.js';
10
+
11
+ const LIMIT = 10 * 1024 * 1024; // GitHub's limit for an image in a README; X and most chats take more
12
+ const END = 1.6; // the end frame and its signature (the engine shows it for the last 1.2 s)
13
+ const run = (args) => spawnSync('ffmpeg', ['-v', 'error', '-y', ...args], { encoding: 'utf8', maxBuffer: 64 << 20 });
14
+
15
+ function probe(file) {
16
+ const r = spawnSync('ffprobe', ['-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=width,height:format=duration', '-of', 'json', file], { encoding: 'utf8' });
17
+ if (r.status !== 0) throw new OmError(`cannot read ${file}: ${(r.stderr || '').trim()}`);
18
+ const j = JSON.parse(r.stdout);
19
+ return { width: j.streams[0].width, height: j.streams[0].height, duration: Number(j.format.duration) };
20
+ }
21
+
22
+ // The newest video in <project>/out (the share folder itself is skipped).
23
+ export function newestRender(project) {
24
+ const dir = join(project.root, 'out');
25
+ const vids = existsSync(dir) ? readdirSync(dir).filter((n) => /\.(mp4|mov|webm)$/i.test(n) && statSync(join(dir, n)).size > 0).map((n) => join(dir, n)) : [];
26
+ if (!vids.length) throw new OmError('nothing rendered yet — run `om render` first');
27
+ return vids.sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs)[0];
28
+ }
29
+
30
+ // The GIF: [from, to] of the film, then its last END seconds when those are not already in it. Tried at falling sizes
31
+ // (then frame rates) until it fits under LIMIT; each try makes its own palette.
32
+ export function makeShareGif(video, target, { from = 0, to = null, limit = LIMIT } = {}) {
33
+ const info = probe(video);
34
+ const d = info.duration;
35
+ to = Math.min(d, to == null ? Math.max(from + 1, Math.min(d, from + 10)) : Number(to));
36
+ from = Math.max(0, Math.min(Number(from) || 0, to - 0.5));
37
+ const withEnd = to < d - END - 0.3;
38
+ const parts = withEnd ? [[from, to], [d - END, d]] : [[from, d - to < 0.3 ? d : to]];
39
+ const landscape = info.width >= info.height;
40
+ const sizes = [960, 800, 640, 540, 480, 400].filter((s) => s <= (landscape ? info.width : info.height));
41
+ if (!sizes.length) sizes.push(landscape ? info.width : info.height);
42
+ const tries = [...sizes.map((s) => [s, 15]), [sizes[sizes.length - 1], 12], [sizes[sizes.length - 1], 10]];
43
+ const palette = target.replace(/\.gif$/i, '.palette.png');
44
+ let last = null;
45
+ try {
46
+ for (const [s, fps] of tries) {
47
+ const scale = landscape ? `scale=${s}:-2:flags=lanczos` : `scale=-2:${s}:flags=lanczos`;
48
+ const cut = parts.map(([a, b], i) => `[0:v]trim=${a.toFixed(3)}:${b.toFixed(3)},setpts=PTS-STARTPTS,fps=${fps},${scale}[p${i}]`).join(';');
49
+ const joined = parts.length > 1 ? `${cut};${parts.map((_, i) => `[p${i}]`).join('')}concat=n=${parts.length}:v=1:a=0[v]` : `${cut};[p0]null[v]`;
50
+ let r = run(['-i', video, '-filter_complex', `${joined};[v]palettegen=max_colors=256:stats_mode=diff[pal]`, '-map', '[pal]', '-frames:v', '1', '-update', '1', palette]);
51
+ if (r.status !== 0) throw new OmError(`could not make the GIF palette: ${(r.stderr || '').trim().split('\n').pop()}`);
52
+ r = run(['-i', video, '-i', palette, '-filter_complex', `${joined};[v][1:v]paletteuse=dither=bayer:bayer_scale=4:diff_mode=rectangle`, '-loop', '0', target]);
53
+ if (r.status !== 0) throw new OmError(`could not write the GIF: ${(r.stderr || '').trim().split('\n').pop()}`);
54
+ last = { size: statSync(target).size, px: s, fps };
55
+ if (last.size <= limit) break;
56
+ }
57
+ } finally { rmSync(palette, { force: true }); }
58
+ return { ...last, parts, fits: last.size <= limit, landscape, source: info };
59
+ }
60
+
61
+ const mb = (n) => (n / 1024 / 1024).toFixed(1) + ' MB';
62
+ const t = (s) => s.toFixed(1) + 's';
63
+
64
+ export function share(project, { from = 0, to = null, video = null } = {}) {
65
+ const src = video || newestRender(project);
66
+ const index = join(project.root, 'index.html');
67
+ const stale = existsSync(index) && statSync(index).mtimeMs > statSync(src).mtimeMs + 1000;
68
+ const dir = join(project.root, 'out', 'share');
69
+ mkdirSync(dir, { recursive: true });
70
+ const name = basename(src).replace(/\.[^.]+$/, '');
71
+ const gif = join(dir, `${name}.gif`);
72
+ const g = makeShareGif(src, gif, { from, to });
73
+ const rel = (f) => relative(project.root, f).split('\\').join('/');
74
+ const span = g.parts.map(([a, b]) => `${t(a)}–${t(b)}`).join(' + ');
75
+ const md = `# 分享包 · Share kit
76
+
77
+ | 文件 File | 用途 Use |
78
+ |---|---|
79
+ | \`${rel(src)}\` | 完整成片(${t(g.source.duration)},${g.source.width}×${g.source.height}):X、视频号、B站、小红书、抖音 |
80
+ | \`${rel(gif)}\` | 动图(${span},${g.px}px,${g.fps} fps,${mb(g.size)}):GitHub README 头图、X、即刻、群聊 |
81
+
82
+ ## 发帖文案 · Post
83
+
84
+ <!-- agent: write 2–3 sentences in the user's language: what the film is about and one concrete detail of how it was made
85
+ (the one-line request, a note given in the studio, the music it composed). Keep the last line as it is. -->
86
+
87
+ Made with huashu-motion · ${REPO_URL} #huashumotion
88
+
89
+ ## README 头图 · README header
90
+
91
+ \`\`\`html
92
+ <a href="${REPO_URL}"><img src="${rel(gif)}" alt="" width="100%"></a>
93
+ <sub>Made with <a href="${REPO_URL}">huashu-motion</a></sub>
94
+ \`\`\`
95
+ `;
96
+ const mdFile = join(dir, 'share.md');
97
+ writeFileSync(mdFile, md);
98
+ const lines = [`share ${dir}`, ` ${rel(gif).padEnd(34)} ${span}, ${g.px}px ${g.fps} fps, ${mb(g.size)}${g.fits ? '' : ` — still over ${mb(LIMIT)}: pass a shorter --from/--to`}`, ` ${rel(mdFile).padEnd(34)} write the post into it (the user's language), then show the user`];
99
+ if (stale) lines.push(` ! ${rel(src)} is older than index.html — run om render first if the film changed since`);
100
+ return lines.join('\n');
101
+ }
package/cli/lib/sound.js CHANGED
@@ -4,6 +4,7 @@
4
4
  // no samples, no network, no dependencies — and the same source always gives the same file.
5
5
  // The music itself is composed in score.js (styles, products, drop, ending, motif); this file renders
6
6
  // the effects in the style's kit, automates and mixes the buses and writes the master.
7
+ import { soundprintReport } from './soundprint.js';
7
8
  import { createHash } from 'node:crypto';
8
9
  import { copyFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
9
10
  import { dirname, join } from 'node:path';
@@ -533,8 +534,11 @@ export async function sound(project, opts = {}, log = () => {}) {
533
534
  : `music ${trackInfo || describe(p)} · ${p.sections.length} section${p.sections.length > 1 ? 's' : ''} (${p.sections.map((s) => `${s.id}${s.drop ? '◆' : ''}:${s.energy.toFixed(1)}`).join(' ')})`,
534
535
  ];
535
536
  if (composed) {
537
+ try { lines.push(...soundprintReport(project.root, readScore(html)).lines); } catch { /* a score the print cannot read still plays */ }
536
538
  lines.push(`fit ${composed.marks.length ? `marks on the picture: ${composed.marks.join(' · ')}` : 'no !mark:name! matched a scene label — the score plays from the start at its written tempo'}${composed.unmatched.length ? ` · unmatched: ${composed.unmatched.join(', ')}` : ''}`);
537
539
  if (composed.stretches.length) lines.push(`tempo ${composed.stretches.map((x) => `${x.from}→${x.to} ${x.qpm.toFixed(1)} bpm (${x.bend >= 0 ? '+' : ''}${(x.bend * 100).toFixed(1)}%)`).join(' · ')}${composed.stretches.some((x) => Math.abs(x.bend) > 0.08) ? ' — a stretch bent more than 8 %: add or remove bars there instead' : ''}`);
540
+ for (const w of (composed.warnings || []).slice(0, 6)) lines.push(`warning score: ${w}`);
541
+ if ((composed.warnings || []).length > 6) lines.push(`warning score: … and ${composed.warnings.length - 6} more bars that do not add up`);
538
542
  if (composed.end > p.duration + 0.3) lines.push(`warning the score runs to ${composed.end.toFixed(2)}s, past the film's end (${p.duration.toFixed(2)}s); it is faded out`);
539
543
  }
540
544
  if (musicOn && !trackInfo && !composed) {