@senseihq/emaki-cli 0.1.0 → 0.1.1

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 (48) hide show
  1. package/README.md +42 -7
  2. package/package.json +4 -2
  3. package/plugin/.claude-plugin/plugin.json +1 -1
  4. package/plugin/modules/campaign/README.md +10 -3
  5. package/plugin/modules/campaign/day-script.template.md +2 -1
  6. package/plugin/modules/posting-desk/README.md +2 -2
  7. package/plugin/skills/emaki/references/03-content-model.md +7 -4
  8. package/plugin/skills/emaki/references/04-scene-authoring.md +3 -0
  9. package/plugin/skills/emaki/references/05-voice-and-video.md +41 -8
  10. package/plugin/skills/emaki/references/09-publishing.md +5 -2
  11. package/plugin/skills/story-media/SKILL.md +2 -0
  12. package/plugin/skills/story-publish/SKILL.md +18 -4
  13. package/src/api.js +12 -1
  14. package/src/campaign.js +157 -0
  15. package/src/capture.js +69 -33
  16. package/src/carousel.js +91 -0
  17. package/src/day-script.js +66 -0
  18. package/src/desk-client.js +37 -0
  19. package/src/desk-plan.js +57 -0
  20. package/src/films.js +12 -5
  21. package/src/http.js +30 -0
  22. package/src/index.js +161 -3
  23. package/src/init.js +5 -4
  24. package/src/media.js +236 -0
  25. package/src/migrate.js +67 -0
  26. package/src/publish.js +118 -0
  27. package/src/stage.js +107 -0
  28. package/src/stories.js +66 -0
  29. package/src/upload/instagram.js +34 -0
  30. package/src/upload/youtube.js +90 -0
  31. package/src/util.js +7 -0
  32. package/src/voice.js +119 -40
  33. package/src/youtube-text.js +58 -0
  34. package/templates/content/films/measure-the-right-work/film.json +9 -0
  35. package/templates/content/films/measure-the-right-work/look.css +1 -0
  36. package/templates/content/films/measure-the-right-work/timing.en.json +24 -0
  37. package/templates/content/films/measure-the-right-work/timing.es.json +24 -0
  38. package/templates/content/films/measure-the-right-work/voice/en/close.m4a +0 -0
  39. package/templates/content/films/measure-the-right-work/voice/en/groups.m4a +0 -0
  40. package/templates/content/films/measure-the-right-work/voice/en/hook.m4a +0 -0
  41. package/templates/content/films/measure-the-right-work/voice/en/pair.m4a +0 -0
  42. package/templates/content/films/measure-the-right-work/voice/en/problem.m4a +0 -0
  43. package/templates/content/films/measure-the-right-work/voice/es/close.m4a +0 -0
  44. package/templates/content/films/measure-the-right-work/voice/es/groups.m4a +0 -0
  45. package/templates/content/films/measure-the-right-work/voice/es/hook.m4a +0 -0
  46. package/templates/content/films/measure-the-right-work/voice/es/pair.m4a +0 -0
  47. package/templates/content/films/measure-the-right-work/voice/es/problem.m4a +0 -0
  48. package/templates/film/look.css +1 -0
package/src/index.js CHANGED
@@ -6,6 +6,7 @@ import sade from 'sade'
6
6
  import pkg from '../package.json' with { type: 'json' }
7
7
  import { project } from './config.js'
8
8
  import { manifest, newFilm, validate } from './films.js'
9
+ import { migrate } from './migrate.js'
9
10
  import { MotionError, parseOpts } from './util.js'
10
11
 
11
12
  const prog = sade('emaki')
@@ -91,6 +92,19 @@ prog.command('validate [slug]')
91
92
  if (r.problems) process.exitCode = 1
92
93
  }))
93
94
 
95
+ prog.command('migrate <from>')
96
+ .describe('Move a sensei-hq.com-style site (src/lib/motion, src/lib/content/articles, films/) into content/ and production/. Never overwrites.')
97
+ .option('--locale', 'The locale the site was written in', 'en')
98
+ .action(act((from, o) => {
99
+ const p = P(), r = migrate(p, from, { locale: o.locale })
100
+ r.wrote.forEach((f) => console.info(` wrote ${f}`))
101
+ if (r.kept.length) console.info(` kept ${r.kept.length} existing file(s)`)
102
+ const v = validate(project())
103
+ v.lines.forEach((l) => console.info(l))
104
+ console.info(v.problems ? `${v.problems} problem(s) left: fix them, then \`emaki validate\`` : 'migrated; emaki validate: ok')
105
+ if (v.problems) process.exitCode = 1
106
+ }))
107
+
94
108
  prog.command('new <slug>')
95
109
  .describe('Scaffold a story and its film in every locale.')
96
110
  .option('--scenes', 'Scene ids, comma separated (close is added last)', 'hook,idea,how')
@@ -166,30 +180,174 @@ prog.command('fit <slug>')
166
180
  const r = fit(p, slug, { locale: loc(o, p), check: o.check })
167
181
  console.info(`${'scene'.padEnd(12)} ${'design'.padStart(6)} ${'holds'.padStart(6)} ${'take'.padStart(6)} ${'runs'.padStart(6)}`)
168
182
  for (const x of r.rows)
169
- console.info(`${x.scene.padEnd(12)} ${x.design.toFixed(1).padStart(6)} ${x.holds.toFixed(1).padStart(6)} ${x.take.toFixed(1).padStart(6)} ${x.runs.toFixed(1).padStart(6)}${x.longer ? ' ← longer' : ''}${x.take ? '' : ' (no take)'}`)
183
+ console.info(`${x.scene.padEnd(12)} ${x.design.toFixed(1).padStart(6)} ${x.holds.toFixed(1).padStart(6)} ${x.take.toFixed(1).padStart(6)} ${x.runs.toFixed(1).padStart(6)}${x.longer ? ' ← longer' : x.shorter ? ' ← shorter' : ''}${x.take ? '' : ' (no take)'}`)
170
184
  console.info(`total ${r.total.toFixed(1)} s (${loc(o, p)})${r.written ? `\nwrote ${r.path}` : ''}`)
171
185
  }))
172
186
 
187
+ prog.command('voice-web <slug>')
188
+ .describe('Narration for the browser: each take as voice/<locale>/<scene>.m4a, and its start in timing.<locale>.json (needs ffmpeg).')
189
+ .option('--locale', 'Locale (default: the site default)')
190
+ .action(act(async (slug, o) => {
191
+ const { voiceWeb } = await import('./voice.js')
192
+ const p = P()
193
+ const r = voiceWeb(p, slug, { locale: loc(o, p), log: (l) => console.info(`wrote ${l}`) })
194
+ for (const f of r.removed) console.info(`removed ${f} (no take)`)
195
+ console.info(`wrote ${r.timing}`)
196
+ }))
197
+
173
198
  prog.command('render <slug>')
174
199
  .describe('Capture the picture frame by frame (with the score) and the covers (needs Playwright + ffmpeg).')
175
200
  .option('--locale', 'Locale (default: the site default)')
176
201
  .option('--url', 'A running site (default: start the dev server)')
177
202
  .option('--o', 'both | landscape | portrait', 'both')
178
203
  .option('--fps', 'Frames per second', 30)
204
+ .option('--from', 'Start at this film time (s)', 0)
205
+ .option('--to', 'Stop at this film time (s; default the end)')
206
+ .option('--out', 'Output: a .mp4 file (one layout) or a folder (default production/<slug>/<locale>/render/)')
207
+ .option('--music', 'synth (the film\'s score) | export (audio of production/<slug>/<locale>/<slug>.mp4) | none', 'synth')
208
+ .option('--audio-only', 'Lay the music on the existing render; capture no frames', false)
209
+ .option('--cover-only', 'Just save the cover frames', false)
179
210
  .action(act(async (slug, o) => {
180
211
  const { render } = await import('./capture.js')
181
212
  const p = P()
182
- await render(p, slug, { locale: loc(o, p), url: o.url, o: o.o, fps: Number(o.fps) })
213
+ await render(p, slug, {
214
+ locale: loc(o, p), url: o.url, o: o.o, fps: Number(o.fps), from: Number(o.from), to: o.to == null ? undefined : Number(o.to),
215
+ out: o.out, music: o.music, audioOnly: o['audio-only'], coverOnly: o['cover-only']
216
+ })
183
217
  }))
184
218
 
185
219
  prog.command('build <slug>')
186
220
  .describe('Final videos: picture + voice + ducked score, captions (.srt/.vtt and burned in), -14 LUFS.')
187
221
  .option('--locale', 'Locale (default: the site default)')
188
222
  .option('--no-captions', 'Do not burn captions in')
223
+ .option('--check', 'Print each scene\'s take, freeze and start; build nothing', false)
224
+ .option('--out', 'Output folder (default production/<slug>/<locale>/out/)')
189
225
  .action(act(async (slug, o) => {
190
226
  const { build } = await import('./voice.js')
191
227
  const p = P()
192
- build(p, slug, { locale: loc(o, p), noCaptions: o.captions === false })
228
+ build(p, slug, { locale: loc(o, p), noCaptions: o.captions === false, check: o.check, out: o.out })
229
+ }))
230
+
231
+ // After the build: stage for approval on the posting desk, or publish straight to a platform. Credentials come from
232
+ // the environment only (STAGER_*, MEDIA_URL_SECRET, YT_*, IG_*; see the README).
233
+ const list = (v) => [v ?? []].flat().flatMap((x) => String(x).split(',')).map((x) => x.trim()).filter(Boolean)
234
+
235
+ prog.command('stage <slug>')
236
+ .describe('Upload a finished piece\'s media and post text to the posting desk for approval (STAGER_CLIENT_ID/SECRET).')
237
+ .option('--channels', 'youtube,instagram_reel,instagram_carousel,x (default: all)')
238
+ .option('--locale', 'Locale (default: the site default)')
239
+ .option('--dry-run', 'Print the posts; send nothing', false)
240
+ .action(act(async (slug, o) => {
241
+ const { stage } = await import('./stage.js')
242
+ await stage(P(), slug, { locale: o.locale, channels: o.channels ? list(o.channels) : undefined, dryRun: o['dry-run'] })
243
+ }))
244
+
245
+ prog.command('stage status [slug]')
246
+ .describe('Report each piece\'s script and what is produced to the desk\'s plan.')
247
+ .option('--locale', 'Locale (default: the site default)')
248
+ .action(act(async (slug, o) => {
249
+ const { productionStatus } = await import('./desk-plan.js')
250
+ await productionStatus(P(), slug, { locale: o.locale })
251
+ }))
252
+
253
+ prog.command('stage requests')
254
+ .describe('The open motion requests from the desk, with their threads.')
255
+ .action(act(async () => {
256
+ const { deskRequests } = await import('./desk-plan.js')
257
+ await deskRequests(P())
258
+ }))
259
+
260
+ prog.command('stage reply <id> [text]')
261
+ .describe('Answer a motion request; --working or --done moves it on.')
262
+ .option('--working', 'Mark it working', false)
263
+ .option('--done', 'Mark it done', false)
264
+ .action(act(async (id, text, o) => {
265
+ if (o.working && o.done) throw new MotionError('--working or --done, not both')
266
+ const { deskReply } = await import('./desk-plan.js')
267
+ await deskReply(P(), id, text ?? '', { status: o.done ? 'done' : o.working ? 'working' : undefined })
268
+ }))
269
+
270
+ prog.command('publish <channel> [slug]')
271
+ .describe('Post a finished film straight to youtube or instagram and record the link (YT_* / IG_* keys).')
272
+ .option('--locale', 'Locale (default: the site default)')
273
+ .option('--privacy', 'YouTube: public | unlisted | private', 'unlisted')
274
+ .option('--update', 'YouTube: refresh this uploaded video id in place (no re-upload)')
275
+ .option('--force-new', 'YouTube: upload even when an id is already recorded', false)
276
+ .option('--description-mode', 'With --update: prepend | replace', 'prepend')
277
+ .option('--video-url', 'Instagram: public MP4 URL (skips staging on the desk)')
278
+ .option('--cover-url', 'Instagram: public JPEG URL for the cover (with --video-url)')
279
+ .option('--dry-run', 'Print exactly what would post; touch nothing', false)
280
+ .option('--verify', 'Check the credentials (read-only) and name the account', false)
281
+ .action(act(async (channel, slug, o) => {
282
+ if (!o.verify && !slug) throw new MotionError('a slug is required (or --verify)')
283
+ const { publish } = await import('./publish.js')
284
+ await publish(P(), channel, slug, {
285
+ locale: o.locale, privacy: o.privacy, update: o.update && String(o.update), forceNew: o['force-new'], descriptionMode: o['description-mode'],
286
+ videoUrl: o['video-url'], coverUrl: o['cover-url'], dryRun: o['dry-run'], verify: o.verify
287
+ })
288
+ }))
289
+
290
+ prog.command('carousel [slug]')
291
+ .describe('Render a campaign day\'s Instagram carousel (1080×1350 PNGs) from its day script (needs Playwright).')
292
+ .option('--all', 'Every day script', false)
293
+ .option('--locale', 'Locale (default: the site default)')
294
+ .action(act(async (slug, o) => {
295
+ const { carousel } = await import('./carousel.js')
296
+ await carousel(P(), [slug, ...o._].filter(Boolean).map(String), { all: o.all, locale: o.locale })
297
+ }))
298
+
299
+ prog.command('campaign status')
300
+ .describe('What is due, and for each day what exists: story, film, takes, render, Short, carousel, posts.')
301
+ .option('--days', 'How many days', 14)
302
+ .option('--from', 'First date YYYY-MM-DD (default: today in the site\'s time zone)')
303
+ .action(act(async (o) => {
304
+ const { campaignStatus } = await import('./campaign.js')
305
+ const yes = (b) => (b ? 'yes' : ' - ')
306
+ console.info(`${'date'.padEnd(10)} ${'topic'.padEnd(11)} ${'title'.padEnd(46)} story film takes rndr short car posts`)
307
+ for (const r of campaignStatus(P(), { from: o.from && String(o.from), days: Number(o.days) })) {
308
+ const head = `${r.date} ${r.topic.slice(0, 11).padEnd(11)} ${r.title.slice(0, 46).padEnd(46)}`
309
+ if (!r.script) { console.info(`${head} (no day script yet)`); continue }
310
+ const posts = ['youtube', 'instagram', 'x'].map((k) => (r.posts[k] ? k[0].toUpperCase() : '·')).join('')
311
+ console.info(`${head} ${yes(r.story)} ${yes(r.film)} ${String(r.takes).padStart(4)} ${yes(r.render)} ${yes(r.built)} ${String(r.carousel).padStart(3)} ${posts}`)
312
+ }
313
+ console.info('\nposts: Y = YouTube, I = Instagram, X = X; · = not yet')
314
+ }))
315
+
316
+ prog.command('campaign shortfilm <slug>')
317
+ .describe('Set up a Short\'s film (scenes and voice lines) from its day script\'s voiceover table.')
318
+ .option('--locale', 'Locale (default: the site default)')
319
+ .action(act(async (slug, o) => {
320
+ const { shortFilm } = await import('./campaign.js')
321
+ const r = shortFilm(P(), slug, { locale: o.locale })
322
+ console.info(`wrote ${r.path}: ${r.scenes} beats. Next: build the scenes, then \`emaki voice ${slug}\`, \`emaki fit ${slug}\`, \`emaki render ${slug} --o portrait\`.`)
323
+ }))
324
+
325
+ prog.command('campaign posted <slug>')
326
+ .describe('Record where a piece was posted: the campaign ledger and the story\'s social links.')
327
+ .option('--youtube', 'Video id or URL')
328
+ .option('--instagram', 'Post URL')
329
+ .option('--x', 'Post URL')
330
+ .action(act(async (slug, o) => {
331
+ const { campaignPosted } = await import('./campaign.js')
332
+ const s = (v) => (v === undefined || v === true ? undefined : String(v))
333
+ const r = campaignPosted(P(), slug, { youtube: s(o.youtube), instagram: s(o.instagram), x: s(o.x) })
334
+ console.info(`recorded ${slug}: ${JSON.stringify(r)}. Commit content/stories/index.json; the next build links the posts.`)
335
+ }))
336
+
337
+ prog.command('campaign due')
338
+ .describe('The piece for one day (default today in the site\'s time zone), as JSON, for automation.')
339
+ .option('--date', 'YYYY-MM-DD')
340
+ .action(act(async (o) => {
341
+ const { campaignDue } = await import('./campaign.js')
342
+ console.info(JSON.stringify(campaignDue(P(), { date: o.date && String(o.date) }), null, 2))
343
+ }))
344
+
345
+ prog.command('campaign calendar')
346
+ .describe('Rewrite CALENDAR.md in the campaign folder from calendar.csv.')
347
+ .action(act(async () => {
348
+ const { campaignCalendar } = await import('./campaign.js')
349
+ const r = campaignCalendar(P())
350
+ console.info(`wrote ${r.path} (${r.days} days)`)
193
351
  }))
194
352
 
195
353
  prog.parse(process.argv)
package/src/init.js CHANGED
@@ -40,6 +40,7 @@ const GLOBS = (content) => `const g = {
40
40
  bodies: import.meta.glob('/${content}/stories/*/*.json', { import: 'default' }),
41
41
  logos: import.meta.glob('/${content}/logos/*.svg', { eager: true, query: '?raw', import: 'default' }),
42
42
  site: import.meta.glob('/${content}/site.json', { eager: true, import: 'default' }),
43
+ voice: import.meta.glob('/${content}/films/*/voice/*/*.m4a', { eager: true, query: '?url', import: 'default' }),
43
44
  };`
44
45
 
45
46
  const viteSourceFile = (content) => `// Where films and stories come from (written by \`emaki init\`). Vite expands these globs at build time, so every
@@ -63,18 +64,18 @@ export function startMotion() {
63
64
  const FILES = {
64
65
  sveltekit: (c) => ({
65
66
  'src/lib/emaki-source.ts': viteSourceFile(c),
66
- 'src/routes/show/[film]/+page.ts': `// The capture page the video pipeline drives; client-only.\nexport const ssr = false;\nexport const prerender = false;\nexport const load = ({ params, url }) => ({\n film: params.film,\n capture: url.searchParams.get('capture') === '1',\n layout: url.searchParams.get('o') === 'portrait' ? 'portrait' : 'landscape',\n locale: url.searchParams.get('locale') ?? 'en',\n});\n`,
67
- 'src/routes/show/[film]/+page.svelte': `<script lang="ts">\n import { ShowPage } from '@senseihq/emaki-svelte';\n import { startMotion } from '$lib/emaki-source';\n let { data } = $props();\n startMotion();\n</script>\n\n<ShowPage film={data.film} layout={data.layout} locale={data.locale} capture={data.capture} />\n`
67
+ 'src/routes/show/[film]/+page.ts': `// The capture page the video pipeline drives; client-only.\nexport const ssr = false;\nexport const prerender = false;\nexport const load = ({ params, url }) => ({\n film: params.film,\n capture: url.searchParams.get('capture') === '1',\n layout: url.searchParams.get('o') === 'portrait' ? 'portrait' : 'landscape',\n locale: url.searchParams.get('locale') ?? 'en',\n src: url.searchParams.get('src') === 'json' || url.searchParams.get('src') === 'js' ? url.searchParams.get('src') : undefined,\n mode: url.searchParams.get('mode') === 'dark' ? 'dark' : 'light',\n});\n`,
68
+ 'src/routes/show/[film]/+page.svelte': `<script lang="ts">\n import { ShowPage } from '@senseihq/emaki-svelte';\n import { startMotion } from '$lib/emaki-source';\n let { data } = $props();\n startMotion();\n</script>\n\n<ShowPage film={data.film} layout={data.layout} locale={data.locale} capture={data.capture} src={data.src} mode={data.mode} />\n`
68
69
  }),
69
70
  svelte: (c) => ({ 'src/emaki-source.ts': viteSourceFile(c) }),
70
71
  react: (c) => ({ 'src/emaki-source.ts': viteSourceFile(c) }),
71
72
  vue: (c) => ({ 'src/emaki-source.ts': viteSourceFile(c) }),
72
73
  next: () => ({
73
- 'app/show/[film]/page.tsx': `'use client';\n// The capture page the video pipeline drives. Films are read at runtime from /public/content (emaki manifest\n// writes content/films/index.json; copy or symlink content/ into public/).\nimport { useEffect, useState } from 'react';\nimport { useSearchParams, useParams } from 'next/navigation';\nimport { setupMotion } from '@senseihq/emaki';\nimport { fetchFilmSource } from '@senseihq/emaki/loaders/fetch';\nimport { ShowPage } from '@senseihq/emaki-react';\n\nexport default function Page() {\n const { film } = useParams<{ film: string }>();\n const q = useSearchParams();\n const [ready, setReady] = useState(false);\n useEffect(() => { setupMotion({ source: fetchFilmSource('/content') }); setReady(true); }, []);\n if (!ready) return null;\n return <ShowPage film={film} capture={q.get('capture') === '1'} layout={q.get('o') === 'portrait' ? 'portrait' : 'landscape'} locale={q.get('locale') ?? 'en'} />;\n}\n`
74
+ 'app/show/[film]/page.tsx': `'use client';\n// The capture page the video pipeline drives. Films are read at runtime from /public/content (emaki manifest\n// writes content/films/index.json; copy or symlink content/ into public/).\nimport { useEffect, useState } from 'react';\nimport { useSearchParams, useParams } from 'next/navigation';\nimport { setupMotion } from '@senseihq/emaki';\nimport { fetchFilmSource } from '@senseihq/emaki/loaders/fetch';\nimport { ShowPage } from '@senseihq/emaki-react';\n\nexport default function Page() {\n const { film } = useParams<{ film: string }>();\n const q = useSearchParams();\n const [ready, setReady] = useState(false);\n useEffect(() => { setupMotion({ source: fetchFilmSource('/content') }); setReady(true); }, []);\n if (!ready) return null;\n return <ShowPage film={film} capture={q.get('capture') === '1'} layout={q.get('o') === 'portrait' ? 'portrait' : 'landscape'} locale={q.get('locale') ?? 'en'} src={(q.get('src') as 'json' | 'js' | null) ?? undefined} mode={q.get('mode') === 'dark' ? 'dark' : 'light'} />;\n}\n`
74
75
  }),
75
76
  nuxt: () => ({}),
76
77
  vanilla: () => ({
77
- 'motion.ts': `// Plain pages: films are read at runtime from /content (run \`emaki manifest\` after adding films).\nimport { setupMotion, installCapture } from '@senseihq/emaki';\nimport { fetchFilmSource } from '@senseihq/emaki/loaders/fetch';\nimport { defineMotionElements } from '@senseihq/emaki/elements';\n\nsetupMotion({ source: fetchFilmSource('/content') });\ndefineMotionElements(); // <motion-scene film=… scene=…> and <motion-show film=…>\n\n// The capture page: /show.html?film=<slug>&capture=1&o=landscape&locale=en\nconst q = new URLSearchParams(location.search);\nif (q.get('capture') === '1') installCapture(document.getElementById('stage')!, q.get('film')!, q.get('o') === 'portrait' ? 'portrait' : 'landscape', q.get('locale') ?? 'en');\n`
78
+ 'motion.ts': `// Plain pages: films are read at runtime from /content (run \`emaki manifest\` after adding films).\nimport { setupMotion, installCapture } from '@senseihq/emaki';\nimport { fetchFilmSource } from '@senseihq/emaki/loaders/fetch';\nimport { defineMotionElements } from '@senseihq/emaki/elements';\n\nsetupMotion({ source: fetchFilmSource('/content') });\ndefineMotionElements(); // <motion-scene film=… scene=…> and <motion-show film=…>\n\n// The capture page: /show.html?film=<slug>&capture=1&o=landscape&locale=en\nconst q = new URLSearchParams(location.search);\nif (q.get('capture') === '1') installCapture(document.getElementById('stage')!, q.get('film')!, q.get('o') === 'portrait' ? 'portrait' : 'landscape', q.get('locale') ?? 'en', { src: (q.get('src') as 'json' | 'js' | null) ?? undefined, mode: q.get('mode') === 'dark' ? 'dark' : 'light' });\n`
78
79
  })
79
80
  }
80
81
 
package/src/media.js ADDED
@@ -0,0 +1,236 @@
1
+ // What render and build decide, as pure functions: frame ranges, output paths, ffmpeg arguments, the freeze table,
2
+ // chapters, the description. capture.js and voice.js run what these return (Playwright, ffmpeg); the specs test these.
3
+ // The reference is the sensei-hq.com website's films/tools/render.py and build.py.
4
+ import { join, resolve } from 'node:path'
5
+ import { SUFFIX } from './config.js'
6
+ import { die, runningTime } from './util.js'
7
+
8
+ /** The frames to capture: from `from` (default 0) to `to` (default and at most the film's end), at least one. */
9
+ export function frameRange(duration, fps, from = 0, to = undefined) {
10
+ const t0 = Math.max(0, Number(from ?? 0))
11
+ const end = Math.min(to == null ? duration : Number(to), duration)
12
+ if (!Number.isFinite(t0) || !Number.isFinite(end) || !(end > t0))
13
+ die(`--from ${from ?? 0} --to ${to ?? 'the end'} is not a range inside the film (it runs ${duration.toFixed(1)} s)`)
14
+ const frames = Math.max(1, Math.round((end - t0) * fps))
15
+ return { t0, end, frames, seconds: frames / fps }
16
+ }
17
+
18
+ /** Where a layout's render goes: the render folder by default; --out FILE.mp4 for one layout, --out FOLDER for any. */
19
+ export function renderOut(dir, slug, locale, layout, { out = undefined, layouts = 1 } = {}) {
20
+ const name = `${slug}-${locale}-${SUFFIX[layout]}.mp4`
21
+ if (!out) return join(dir, name)
22
+ if (!/\.mp4$/i.test(out)) return resolve(out, name)
23
+ if (layouts > 1) die(`--out ${out} is one file, so it takes one layout: add --o landscape or --o portrait, or give a folder`)
24
+ return resolve(out)
25
+ }
26
+
27
+ /** Where the music comes from (--music): `synth` the page's score (window.__show.audio(), on the film's own timing),
28
+ * `export` the audio of an exported film (`exportFile`; silent if it is missing), `none` a silent picture. */
29
+ export function musicFor(mode = 'synth', { exportFile = '', exists = (_f) => false } = {}) {
30
+ if (mode === 'synth') return { kind: 'synth' }
31
+ if (mode === 'none') return { kind: 'none' }
32
+ if (mode !== 'export') die(`--music ${mode}: use synth | export | none`)
33
+ if (exists(exportFile)) return { kind: 'file', file: exportFile }
34
+ return { kind: 'none', note: `no ${exportFile}: silent picture` }
35
+ }
36
+
37
+ /** What a render run does: capture frames, lay the music, save the covers. --audio-only lays the music on the
38
+ * existing render; --cover-only saves just the covers. */
39
+ export function renderSteps({ audioOnly = false, coverOnly = false } = {}) {
40
+ if (audioOnly && coverOnly) die('--audio-only and --cover-only exclude each other')
41
+ return { frames: !audioOnly && !coverOnly, music: !coverOnly, cover: true }
42
+ }
43
+
44
+ /** ffmpeg reading JPEG frames from stdin; `audio` (from film time t0) laid under them. */
45
+ export function encodeArgs({ fps, seconds, dst, audio = null, t0 = 0 }) {
46
+ return ['-y', '-loglevel', 'error', '-f', 'image2pipe', '-framerate', String(fps), '-c:v', 'mjpeg', '-i', '-',
47
+ ...(audio ? ['-ss', t0.toFixed(3), '-i', audio, '-map', '0:v', '-map', '1:a'] : []),
48
+ '-c:v', 'libx264', '-preset', 'medium', '-crf', '18', '-pix_fmt', 'yuv420p', '-r', String(fps),
49
+ ...(audio ? ['-c:a', 'aac', '-b:a', '192k'] : []), '-t', seconds.toFixed(3), '-movflags', '+faststart', dst]
50
+ }
51
+
52
+ /** --audio-only: copies the picture and lays `audio` (from film time t0, for dur) under it. */
53
+ export function muxArgs(video, audio, t0, dur, dst) {
54
+ return ['-y', '-loglevel', 'error', '-i', video, '-ss', t0.toFixed(3), '-i', audio, '-map', '0:v', '-map', '1:a',
55
+ '-c:v', 'copy', '-c:a', 'aac', '-b:a', '192k', '-t', dur.toFixed(3), '-movflags', '+faststart', dst]
56
+ }
57
+
58
+ /** Runs `fn`; when it fails (the dev server reloaded the page under it), awaits `recover` (the show coming back)
59
+ * and runs it again, up to `attempts` times in all, then lets the last error through. */
60
+ export async function retrying(fn, recover, attempts = 8) {
61
+ for (let i = 1; ; i++) {
62
+ try {
63
+ return await fn()
64
+ } catch (e) {
65
+ if (i >= attempts) throw e
66
+ await recover(e)
67
+ }
68
+ }
69
+ }
70
+
71
+ /** build.py's plan: each scene's place on the rendered picture (start, dur: film.json plus timing.<locale>.json) and on
72
+ * the output (at, tot). A take is laid `lead` s into its scene; when lead + take + tail is longer than the scene, the
73
+ * scene's last frame is frozen for the difference (ext), so nothing is cut off or sped up. `takes`: scene id →
74
+ * { file, seconds }. After `emaki fit` and a fresh render no scene needs a freeze. */
75
+ export function buildPlan(film, timing, takes, { lead, tail }) {
76
+ const rows = []
77
+ let start = 0, at = 0
78
+ for (const [i, s] of film.scenes.entries()) {
79
+ const dur = runningTime(s, timing?.[s.id])
80
+ const take = takes.get(s.id) ?? null
81
+ const L = take ? take.seconds : 0
82
+ let ext = take ? Math.max(0, lead + L + tail - dur) : 0
83
+ if (ext < 1e-3) ext = 0
84
+ rows.push({ n: i + 1, id: s.id, name: s.name ?? s.id, start, dur, take: take?.file ?? null, L, ext, tot: dur + ext, at })
85
+ start += dur
86
+ at += dur + ext
87
+ }
88
+ return { rows, picture: start, total: at, extended: rows.some((r) => r.ext > 0), missing: rows.filter((r) => !r.take).map((r) => r.id) }
89
+ }
90
+
91
+ const mmss = (t) => `${String(Math.floor(t / 60)).padStart(2, '0')}:${String(Math.floor(t % 60)).padStart(2, '0')}`
92
+
93
+ /** The table build --check prints (build.py's): each scene's length, take, freeze and new length, and where it starts. */
94
+ export function planTable(plan) {
95
+ const f = (x, w) => x.toFixed(1).padStart(w)
96
+ const lines = [`${'#'.padStart(2)} ${'scene'.padEnd(12)} ${'dur'.padStart(5)} ${'take'.padStart(5)} ${'ext'.padStart(5)} ${'new'.padStart(6)} start`]
97
+ for (const r of plan.rows)
98
+ lines.push(`${String(r.n).padStart(2)} ${r.id.padEnd(12)} ${f(r.dur, 5)} ${f(r.L, 5)} ${f(r.ext, 5)} ${f(r.tot, 6)} ${mmss(r.at)}${r.take ? '' : ' (no take)'}`)
99
+ const k = plan.rows.filter((r) => r.ext > 0).length
100
+ lines.push(`total ${plan.total.toFixed(1)} s` + (k ? ` (${k} scene${k > 1 ? 's' : ''} frozen to fit ${k > 1 ? 'their takes' : 'its take'}; \`emaki fit\` and a new render make that unnecessary)` : ''))
101
+ return lines
102
+ }
103
+
104
+ const escMeta = (s) => String(s).replace(/[\\=;#]/g, (c) => `\\${c}`).replace(/\n/g, ' ')
105
+
106
+ /** FFMETADATA with one chapter per scene, on the exact scene boundaries (VLC, QuickTime; YouTube ignores it). */
107
+ export function ffmeta(rows) {
108
+ const lines = [';FFMETADATA1']
109
+ for (const r of rows)
110
+ lines.push('[CHAPTER]', 'TIMEBASE=1/1000', `START=${Math.round(r.at * 1000)}`, `END=${Math.round((r.at + r.tot) * 1000)}`, `title=${escMeta(r.name)}`)
111
+ return lines.join('\n') + '\n'
112
+ }
113
+
114
+ /** YouTube's chapter list: [at, title] from 0:00, every chapter at least 10 s (YouTube shows none unless all its rules
115
+ * hold). Short scenes fold into the chapter they start; a short tail joins the last one. Boundaries stay on cuts. */
116
+ export function ytChapters(rows) {
117
+ const groups = []
118
+ let cur = [], start = 0
119
+ for (const r of rows) {
120
+ cur.push(r)
121
+ if (r.at + r.tot - start >= 10 - 1e-6) {
122
+ groups.push([start, cur])
123
+ cur = []
124
+ start = r.at + r.tot
125
+ }
126
+ }
127
+ if (cur.length) {
128
+ if (groups.length) groups.at(-1)[1].push(...cur)
129
+ else groups.push([start, cur])
130
+ }
131
+ return groups.map(([at, rs]) => [at, rs.map((r) => r.name).join(' + ')])
132
+ }
133
+
134
+ /** chapters.txt: "m:ss title" per line, ready for a video description. */
135
+ export const chaptersText = (chapters) =>
136
+ chapters.map(([at, name]) => `${Math.floor(at / 60)}:${String(Math.floor(at % 60)).padStart(2, '0')} ${name}\n`).join('')
137
+
138
+ /** description.txt: the title, the chapter list and the story link, ready to paste into a video description. */
139
+ export const description = ({ title, chapters, link = null }) => `${title}\n\n${chaptersText(chapters)}${link ? `\n${link}\n` : ''}`
140
+
141
+ /** The story page a video links to: emaki.config.json storyUrl ({site} {locale} {slug}), by default
142
+ * {site}/{locale}/stories/{slug}; null when the pattern needs the site url and site.json has none. */
143
+ export function storyLink(site, cfg, slug, locale) {
144
+ const pattern = cfg?.storyUrl ?? '{site}/{locale}/stories/{slug}'
145
+ const base = String(site?.url ?? '').replace(/\/+$/, '')
146
+ if (pattern.includes('{site}') && !base) return null
147
+ return pattern.replaceAll('{site}', base).replaceAll('{locale}', locale).replaceAll('{slug}', slug)
148
+ }
149
+
150
+ /** poster.jpg, poster-vertical.jpg and <slug>-<locale>-thumb.jpg (1280x720, YouTube's custom thumbnail): from the
151
+ * covers render saved, else a still from the end card of the built video (2.5 s into the last scene, or 0.2 s
152
+ * before its end). Each step is { copy: [src, dst] } or { ffmpeg: args }; a step with no source is left out. */
153
+ export function posterSteps({ render, out, slug, locale, built, last, exists }) {
154
+ const cover = (sfx) => join(render, `${slug}-${locale}-cover-${sfx}.jpg`)
155
+ const still = (last.at + Math.min(last.tot - 0.2, 2.5)).toFixed(2)
156
+ const steps = []
157
+ for (const [sfx, layout, name] of [['16x9', 'landscape', 'poster.jpg'], ['9x16', 'portrait', 'poster-vertical.jpg']]) {
158
+ if (exists(cover(sfx))) steps.push({ copy: [cover(sfx), join(out, name)] })
159
+ else if (built[layout]) steps.push({ ffmpeg: ['-y', '-v', 'error', '-ss', still, '-i', built[layout], '-frames:v', '1', '-q:v', '2', join(out, name)] })
160
+ }
161
+ const thumb = join(out, `${slug}-${locale}-thumb.jpg`)
162
+ if (exists(cover('16x9'))) steps.push({ ffmpeg: ['-y', '-v', 'error', '-i', cover('16x9'), '-vf', 'scale=1280:720', '-q:v', '3', thumb] })
163
+ else if (built.landscape)
164
+ steps.push({ ffmpeg: ['-y', '-v', 'error', '-ss', still, '-i', built.landscape, '-vf', 'scale=1280:720', '-frames:v', '1', '-q:v', '3', thumb] })
165
+ return steps
166
+ }
167
+
168
+ /** The -web.mp4: the 16:9 film at 30 fps, CRF 26, AAC 128k, chapters kept; small enough for static hosting. */
169
+ export const webArgs = (src, dst) => ['-y', '-v', 'error', '-i', src, '-r', '30', '-c:v', 'libx264', '-crf', '26', '-preset', 'slow',
170
+ '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-b:a', '128k', '-map_chapters', '0', '-movflags', '+faststart', dst]
171
+
172
+ /** The web copy's size, flagged above the 25 MiB a static host such as Cloudflare Pages serves. */
173
+ export function webNote(bytes) {
174
+ const mb = bytes / 1048576
175
+ return `${mb.toFixed(1)} MiB${mb > 25 ? ' - OVER 25 MiB, raise -crf' : ''}`
176
+ }
177
+
178
+ /** One take for the browser (voice-web): mono AAC 64k at -16 LUFS (speech heard on its own, under a ducked score),
179
+ * the index up front so it starts streaming at once. */
180
+ export const webVoiceArgs = (src, dst) => ['-y', '-v', 'error', '-i', src, '-vn', '-ac', '1', '-ar', '48000',
181
+ '-af', 'loudnorm=I=-16:TP=-1.5:LRA=11', '-c:a', 'aac', '-b:a', '64k', '-movflags', '+faststart', dst]
182
+
183
+ const LOUDNORM = 'loudnorm=I=-14:TP=-1.5:LRA=11'
184
+
185
+ /** ffmpeg for one final video: the rendered picture (`pic`, its own audio track the music when `music`), the voice
186
+ * (`voice`, already on the output timeline), the score ducked under the voice, -14 LUFS, `subtitles` (a filter) burned
187
+ * in. When the plan freezes a scene, each scene is cut from the picture on its own input, the frozen one padded with
188
+ * its last frame and its music looped under the hold (5 ms fades hide the seam), and the scenes joined again.
189
+ * `chapters`: an FFMETADATA file (ffmeta) whose chapters are written in the same pass. */
190
+ export function buildArgs({ pic, voice, plan, music, subtitles = null, chapters = null, scoreLevel = 0.55, dst }) {
191
+ const inputs = [], fc = []
192
+ let vid, mu = null
193
+ if (plan.extended) {
194
+ const n = plan.rows.length
195
+ for (const r of plan.rows) inputs.push('-ss', r.start.toFixed(3), '-t', r.dur.toFixed(3), '-i', pic)
196
+ plan.rows.forEach((r, i) => {
197
+ fc.push(`[${i}:v]${r.ext ? `tpad=stop_mode=clone:stop_duration=${r.ext.toFixed(3)},` : ''}setpts=PTS-STARTPTS[v${i}]`)
198
+ if (music) {
199
+ const loop = r.ext ? `afade=t=in:st=0:d=0.005,afade=t=out:st=${(r.dur - 0.005).toFixed(3)}:d=0.005,aloop=loop=-1:size=2e9,` : ''
200
+ fc.push(`[${i}:a]aresample=48000,aformat=channel_layouts=stereo,${loop}apad,atrim=0:${r.tot.toFixed(3)},asetpts=PTS-STARTPTS[m${i}]`)
201
+ }
202
+ })
203
+ fc.push(`${plan.rows.map((_, i) => `[v${i}]`).join('')}concat=n=${n}:v=1:a=0[pv]`)
204
+ if (music) fc.push(`${plan.rows.map((_, i) => `[m${i}]`).join('')}concat=n=${n}:v=0:a=1[mu]`)
205
+ vid = '[pv]'
206
+ mu = music ? '[mu]' : null
207
+ } else {
208
+ inputs.push('-i', pic)
209
+ vid = '0:v'
210
+ if (music) {
211
+ fc.push('[0:a]aresample=48000,aformat=channel_layouts=stereo[mu]')
212
+ mu = '[mu]'
213
+ }
214
+ }
215
+ const vo = inputs.filter((x) => x === '-i').length
216
+ inputs.push('-i', voice)
217
+ const meta = chapters ? ['-map_metadata', String(vo + 1), '-map_chapters', String(vo + 1)] : []
218
+ if (chapters) inputs.push('-i', chapters)
219
+ if (mu)
220
+ fc.push(`${mu}volume=${scoreLevel}[sc]`, `[${vo}:a]aresample=48000,asplit=2[vo][key]`,
221
+ '[sc][key]sidechaincompress=threshold=0.05:ratio=6:release=400[duck]', `[duck][vo]amix=inputs=2:normalize=0,${LOUDNORM}[a]`)
222
+ else fc.push(`[${vo}:a]${LOUDNORM}[a]`)
223
+ if (subtitles) {
224
+ fc.push(`${vid.startsWith('[') ? vid : `[${vid}]`}${subtitles}[v]`)
225
+ vid = '[v]'
226
+ }
227
+ return ['-y', '-v', 'error', ...inputs, '-filter_complex', fc.join(';'), '-map', vid, '-map', '[a]', ...meta,
228
+ '-c:v', 'libx264', '-crf', '18', '-preset', 'medium', '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-b:a', '192k',
229
+ '-t', plan.total.toFixed(3), '-movflags', '+faststart', dst]
230
+ }
231
+
232
+ /** A warning when an existing render no longer runs as long as the film (after a retiming): its frames are stale. */
233
+ export function staleRender(rendered, film, ranged = false) {
234
+ if (ranged || Math.abs(rendered - film) <= 0.2) return null
235
+ return `the render runs ${rendered.toFixed(1)} s but the film now runs ${film.toFixed(1)} s; render the frames again`
236
+ }
package/src/migrate.js ADDED
@@ -0,0 +1,67 @@
1
+ // emaki migrate <website>: moves a sensei-hq.com-style site's motion content into emaki's layout, once, so `emaki`
2
+ // can take over its films (issue #1, gap 4). Nothing that already exists is overwritten; the report lists what was
3
+ // written and what was kept, and `emaki validate` checks the result.
4
+ //
5
+ // src/lib/motion/films/<slug>/ → content/films/<slug>/ (base.css becomes look.css)
6
+ // src/lib/motion/logos/ → content/logos/
7
+ // src/lib/content/articles/index.json → content/stories/index.json, minus the reader-facing text …
8
+ // src/lib/content/articles/<slug>.json → content/stories/<locale>/<slug>.json, plus that text (title, dek, …)
9
+ // films/<slug>/film.json scenes → content/films/<slug>/voice/<locale>.json (the narration)
10
+ // films/<slug>/takes/*.wav → production/<slug>/<locale>/takes/ (recorded takes: keep, don't regenerate)
11
+ import { copyFileSync, mkdirSync, readdirSync, writeFileSync } from 'node:fs'
12
+ import { dirname, join } from 'node:path'
13
+ import { die, exists, load } from './util.js'
14
+
15
+ /** Index fields that are words for the reader: emaki keeps them per locale, in the story body. */
16
+ const TEXT = ['title', 'dek', 'kanjiGloss', 'series']
17
+
18
+ export function migrate(p, from, { locale = 'en' } = {}) {
19
+ const films = join(from, 'src/lib/motion/films'), articles = join(from, 'src/lib/content/articles')
20
+ if (!exists(films) && !exists(articles)) die(`${from} has neither src/lib/motion/films nor src/lib/content/articles`)
21
+ const wrote = [], kept = []
22
+ const put = (dst, write) => {
23
+ const rel = p.rel(dst)
24
+ if (exists(dst)) return kept.push(rel)
25
+ mkdirSync(dirname(dst), { recursive: true })
26
+ write(dst)
27
+ wrote.push(rel)
28
+ }
29
+ const copy = (src, dst) => put(dst, (d) => copyFileSync(src, d))
30
+ const json = (dst, data) => put(dst, (d) => writeFileSync(d, JSON.stringify(data, null, 1) + '\n'))
31
+ const tree = (src, dst, rename = (n) => n) => {
32
+ for (const e of readdirSync(src, { withFileTypes: true }))
33
+ if (e.isDirectory()) tree(join(src, e.name), join(dst, e.name))
34
+ else copy(join(src, e.name), join(dst, rename(e.name)))
35
+ }
36
+
37
+ if (exists(films))
38
+ for (const slug of readdirSync(films).filter((d) => exists(join(films, d, 'film.json'))))
39
+ tree(join(films, slug), join(p.films, slug), (n) => (n === 'base.css' ? 'look.css' : n))
40
+ const logos = join(from, 'src/lib/motion/logos')
41
+ if (exists(logos)) tree(logos, join(p.content, 'logos'))
42
+
43
+ if (exists(join(articles, 'index.json'))) {
44
+ const index = load(join(articles, 'index.json'))
45
+ json(join(p.content, 'stories', 'index.json'), index.map((e) => Object.fromEntries(Object.entries(e).filter(([k]) => !TEXT.includes(k)))))
46
+ for (const e of index) {
47
+ const src = join(articles, `${e.slug}.json`)
48
+ if (!exists(src)) continue
49
+ const text = Object.fromEntries(TEXT.filter((k) => k in e).map((k) => [k, e[k]]))
50
+ json(join(p.content, 'stories', locale, `${e.slug}.json`), { ...text, ...load(src) })
51
+ }
52
+ }
53
+
54
+ const masters = join(from, 'films')
55
+ if (exists(masters))
56
+ for (const slug of readdirSync(masters).filter((d) => exists(join(masters, d, 'film.json')))) {
57
+ const scenes = load(join(masters, slug, 'film.json')).scenes ?? []
58
+ if (scenes.length && exists(join(p.films, slug)))
59
+ json(join(p.films, slug, 'voice', `${locale}.json`), scenes.map((s) => ({ scene: s.id, text: s.text ?? '', say: s.say ?? null })))
60
+ const takes = join(masters, slug, 'takes')
61
+ if (exists(takes))
62
+ for (const f of readdirSync(takes).filter((n) => n.endsWith('.wav'))) copy(join(takes, f), p.prod(slug, locale, 'takes', f))
63
+ }
64
+
65
+ if (!exists(join(p.content, 'site.json'))) json(join(p.content, 'site.json'), { name: '', url: '', locales: [locale], defaultLocale: locale })
66
+ return { wrote, kept }
67
+ }