@senseihq/emaki-cli 0.1.1 → 0.1.2

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.
package/src/index.js CHANGED
@@ -1,353 +1,21 @@
1
1
  #!/usr/bin/env node
2
2
  /* eslint-disable no-console */
3
3
  // emaki: set a project up for motion stories, install the Claude plugin, and run the production steps
4
- // (validate, sheet, voice, fit, render, build) per film and per locale.
4
+ // (validate, sheet, voice, fit, render, build) per film and per locale. Each group of commands is in commands/; they are
5
+ // registered in this order, which is the order --help lists them in.
5
6
  import sade from 'sade'
6
7
  import pkg from '../package.json' with { type: 'json' }
7
- import { project } from './config.js'
8
- import { manifest, newFilm, validate } from './films.js'
9
- import { migrate } from './migrate.js'
10
- import { MotionError, parseOpts } from './util.js'
8
+ import { campaignCommands } from './commands/campaign.js'
9
+ import { postingCommands } from './commands/posting.js'
10
+ import { productionCommands } from './commands/production.js'
11
+ import { setupCommands } from './commands/setup.js'
11
12
 
12
13
  const prog = sade('emaki')
13
14
  prog.version(pkg.version)
14
15
 
15
- /** Runs a command; a MotionError prints its message and exits 1, anything else is a bug and shows its stack. */
16
- const act = (fn) => async (...args) => {
17
- try {
18
- await fn(...args)
19
- } catch (e) {
20
- if (e instanceof MotionError) {
21
- console.error(`emaki: ${e.message}`)
22
- process.exit(1)
23
- }
24
- throw e
25
- }
26
- }
27
- const P = () => project()
28
- const loc = (o, p) => o.locale ?? p.site.defaultLocale
29
-
30
- prog.command('init')
31
- .describe('Set this project up: sample content, emaki.config.json, the film source and the /show capture route.')
32
- .option('--framework', 'sveltekit | svelte | react | next | vue | nuxt | vanilla (default: detected)')
33
- .option('--content', 'Content folder', 'content')
34
- .option('--no-sample', 'Skip the sample film')
35
- .option('--plugin', 'Also install the Claude plugin (skills, agents, playbook)', true)
36
- .action(act(async (o) => {
37
- const { init } = await import('./init.js')
38
- const r = init({ framework: o.framework, content: o.content, sample: o.sample !== false })
39
- console.info(`framework: ${r.framework}`)
40
- r.wrote.forEach((f) => console.info(` wrote ${f}`))
41
- r.kept.forEach((f) => console.info(` kept ${f} (exists)`))
42
- if (o.plugin !== false) {
43
- const { installPlugin, report } = await import('./plugin.js')
44
- const x = installPlugin()
45
- report('skill', x.skills); report('agent', x.agents); report('file', x.extras)
46
- }
47
- console.info(`\nNext:\n npm i ${r.packages.join(' ')}\n npm i -D playwright && npx playwright install chromium (sheet, render)\n npx emaki validate && npx emaki tts-check`)
48
- console.info('Then in Claude: "build our motion stories" (the emaki skill interviews you and plans the work).')
49
- }))
50
-
51
- prog.command('plugin install')
52
- .describe('Install the Claude plugin into .claude/: every skill and agent, plus the playbook and templates.')
53
- .option('--force', 'Overwrite what exists', false)
54
- .action(act(async (o) => {
55
- const { installPlugin, report } = await import('./plugin.js')
56
- const x = installPlugin({ force: o.force })
57
- report('skill', x.skills); report('agent', x.agents); report('file', x.extras)
58
- }))
59
-
60
- prog.command('skills [sub]')
61
- .describe('List the bundled skills, or add some: emaki skills add <name...> | --all')
62
- .option('--all', 'Every skill', false)
63
- .option('--force', 'Overwrite', false)
64
- .action(act(async (sub, o) => {
65
- const { listSkills, installSkills, report } = await import('./plugin.js')
66
- if (sub === 'add') return report('skill', installSkills(o.all ? listSkills().map((s) => s.name) : o._, { force: o.force }))
67
- for (const s of listSkills()) console.info(`${s.name}\n ${s.description}`)
68
- console.info('\nInstall with: emaki skills add <name> [...] (or --all)')
69
- }))
70
-
71
- prog.command('agents [sub]')
72
- .describe('List the bundled agents, or add some: emaki agents add <name...> | --all')
73
- .option('--all', 'Every agent', false)
74
- .option('--force', 'Overwrite', false)
75
- .action(act(async (sub, o) => {
76
- const { listAgents, installAgents, report } = await import('./plugin.js')
77
- if (sub === 'add') return report('agent', installAgents(o.all ? listAgents().map((a) => a.name) : o._, { force: o.force }))
78
- for (const a of listAgents()) console.info(`${a.name}\n ${a.description}`)
79
- console.info('\nInstall with: emaki agents add <name> [...] (or --all)')
80
- }))
81
-
82
- prog.command('manifest')
83
- .describe('Write content/films/index.json (the fetch loader reads it).')
84
- .action(act(() => { const r = manifest(P()); console.info(`${r.count} films → ${r.path}`) }))
85
-
86
- prog.command('validate [slug]')
87
- .describe('Check the contracts: files, scene ids, {{keys}} in every locale, voice lines, story bodies.')
88
- .action(act((slug) => {
89
- const r = validate(P(), slug)
90
- r.lines.forEach((l) => console.info(l))
91
- console.info(r.problems ? `${r.problems} problem(s)` : 'ok')
92
- if (r.problems) process.exitCode = 1
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
-
108
- prog.command('new <slug>')
109
- .describe('Scaffold a story and its film in every locale.')
110
- .option('--scenes', 'Scene ids, comma separated (close is added last)', 'hook,idea,how')
111
- .option('--title', 'Film title')
112
- .option('--date', 'Publish date YYYY-MM-DD (default today)')
113
- .action(act((slug, o) => {
114
- const r = newFilm(P(), slug, { scenes: o.scenes, title: o.title, date: o.date })
115
- console.info(`scaffolded ${r.slug}: ${r.scenes} scenes, ${r.locales} locale(s). Next: write the scenes, then \`emaki sheet ${r.slug}\`.`)
116
- }))
117
-
118
- prog.command('sheet <slug>')
119
- .describe('Contact sheet: each scene\'s final picture in both orientations (needs Playwright).')
120
- .option('--locale', 'Locale (default: the site default)')
121
- .option('--url', 'A running site (default: start the dev server)')
122
- .option('--at', 'scene:t,scene:t instead of each scene\'s final picture')
123
- .action(act(async (slug, o) => {
124
- const { sheet } = await import('./capture.js')
125
- const p = P()
126
- await sheet(p, slug, { locale: loc(o, p), url: o.url, at: o.at })
127
- }))
128
-
129
- prog.command('tts-check')
130
- .describe('Which voice provider each locale uses, whether it is ready here, and which offline engines exist.')
131
- .action(act(async () => {
132
- const { ttsCheck } = await import('./voice.js')
133
- const r = ttsCheck(P())
134
- for (const x of r.rows) console.info(`${x.locale}: ${x.provider ? `${x.provider} (${x.label}) ${x.ready ? 'ready' : `not ready: ${x.note}`}` : 'no provider set'}`)
135
- console.info(`offline engines on this machine: ${r.offline.join(', ') || 'none'}`)
136
- }))
137
-
138
- prog.command('set-voice')
139
- .describe('Choose the voice provider for a locale (or "default"); options with --opt key=value. Keys stay in env vars.')
140
- .option('--locale', 'Locale, a language, or default', 'default')
141
- .option('--provider', 'piper | kokoro | macos | espeak | elevenlabs | openai | azure | google | polly | manual')
142
- .option('--opt', 'key=value (voice, voice_id, model, instructions, rate, …); repeatable')
143
- .action(act(async (o) => {
144
- const { setVoice } = await import('./voice.js')
145
- if (!o.provider) throw new MotionError('--provider is required')
146
- const r = setVoice(P(), o.locale, o.provider, parseOpts(o.opt))
147
- r.dropped.forEach((k) => console.info(`dropped "${k}": keys belong in environment variables, not emaki.config.json`))
148
- console.info(`voice.${o.locale} = ${JSON.stringify(r.block)}`)
149
- }))
150
-
151
- prog.command('voices')
152
- .describe('List the voices a provider offers for a locale.')
153
- .option('--locale', 'Locale (default: the site default)')
154
- .option('--provider', 'Override the configured provider')
155
- .action(act(async (o) => {
156
- const { listVoices } = await import('./voice.js')
157
- const p = P()
158
- for (const v of await listVoices(p, loc(o, p), o.provider)) console.info(v)
159
- }))
160
-
161
- prog.command('voice <slug>')
162
- .describe('Synthesise the takes from voice/<locale>.json with the configured provider.')
163
- .option('--locale', 'Locale (default: the site default)')
164
- .option('--only', 'Take numbers, e.g. 2,5')
165
- .option('--provider', 'Override the configured provider for this run')
166
- .option('--opt', 'key=value override, e.g. voice=nova; repeatable')
167
- .action(act(async (slug, o) => {
168
- const { voice } = await import('./voice.js')
169
- const p = P()
170
- await voice(p, slug, { locale: loc(o, p), only: o.only, provider: o.provider, opts: parseOpts(o.opt) })
171
- }))
172
-
173
- prog.command('fit <slug>')
174
- .describe('Fit each scene\'s running time to its take: timing.<locale>.json.')
175
- .option('--locale', 'Locale (default: the site default)')
176
- .option('--check', 'Report only; write nothing', false)
177
- .action(act(async (slug, o) => {
178
- const { fit } = await import('./voice.js')
179
- const p = P()
180
- const r = fit(p, slug, { locale: loc(o, p), check: o.check })
181
- console.info(`${'scene'.padEnd(12)} ${'design'.padStart(6)} ${'holds'.padStart(6)} ${'take'.padStart(6)} ${'runs'.padStart(6)}`)
182
- for (const x of r.rows)
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)'}`)
184
- console.info(`total ${r.total.toFixed(1)} s (${loc(o, p)})${r.written ? `\nwrote ${r.path}` : ''}`)
185
- }))
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
-
198
- prog.command('render <slug>')
199
- .describe('Capture the picture frame by frame (with the score) and the covers (needs Playwright + ffmpeg).')
200
- .option('--locale', 'Locale (default: the site default)')
201
- .option('--url', 'A running site (default: start the dev server)')
202
- .option('--o', 'both | landscape | portrait', 'both')
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)
210
- .action(act(async (slug, o) => {
211
- const { render } = await import('./capture.js')
212
- const p = P()
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
- })
217
- }))
218
-
219
- prog.command('build <slug>')
220
- .describe('Final videos: picture + voice + ducked score, captions (.srt/.vtt and burned in), -14 LUFS.')
221
- .option('--locale', 'Locale (default: the site default)')
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/)')
225
- .action(act(async (slug, o) => {
226
- const { build } = await import('./voice.js')
227
- const p = P()
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)`)
351
- }))
16
+ setupCommands(prog)
17
+ productionCommands(prog)
18
+ postingCommands(prog)
19
+ campaignCommands(prog)
352
20
 
353
21
  prog.parse(process.argv)
package/src/init.js CHANGED
@@ -6,18 +6,14 @@ import { dirname, join } from 'node:path'
6
6
  import { TEMPLATES } from './films.js'
7
7
  import { load, save } from './util.js'
8
8
 
9
+ /** [dependency, framework], most specific first: a meta-framework wins over the library it is built on. */
10
+ const DETECT = [['@sveltejs/kit', 'sveltekit'], ['svelte', 'svelte'], ['next', 'next'], ['nuxt', 'nuxt'], ['react', 'react'], ['vue', 'vue']]
11
+
9
12
  /** Which framework a project uses, from its package.json. */
10
13
  export function detectFramework(cwd) {
11
14
  const pj = join(cwd, 'package.json')
12
- if (!existsSync(pj)) return 'vanilla'
13
- const p = load(pj), deps = { ...p.dependencies, ...p.devDependencies }
14
- if (deps['@sveltejs/kit']) return 'sveltekit'
15
- if (deps.svelte) return 'svelte'
16
- if (deps.next) return 'next'
17
- if (deps.nuxt) return 'nuxt'
18
- if (deps.react) return 'react'
19
- if (deps.vue) return 'vue'
20
- return 'vanilla'
15
+ const p = existsSync(pj) ? load(pj) : {}, deps = { ...p.dependencies, ...p.devDependencies }
16
+ return DETECT.find(([dep]) => deps[dep])?.[1] ?? 'vanilla'
21
17
  }
22
18
 
23
19
  export const PACKAGES = {
package/src/media.js CHANGED
@@ -1,9 +1,14 @@
1
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.
2
+ // chapters, the description. render.js and build-video.js run what these return (Playwright, ffmpeg); the specs test these.
3
+ // Build's own decisions live in build-media.js and are re-exported here.
3
4
  // The reference is the sensei-hq.com website's films/tools/render.py and build.py.
4
5
  import { join, resolve } from 'node:path'
5
6
  import { SUFFIX } from './config.js'
6
- import { die, runningTime } from './util.js'
7
+ import { die } from './util.js'
8
+
9
+ export {
10
+ buildPlan, planTable, ffmeta, ytChapters, chaptersText, description, storyLink, posterSteps, webArgs, webNote, webVoiceArgs, buildArgs
11
+ } from './build-media.js'
7
12
 
8
13
  /** The frames to capture: from `from` (default 0) to `to` (default and at most the film's end), at least one. */
9
14
  export function frameRange(duration, fps, from = 0, to = undefined) {
@@ -68,167 +73,6 @@ export async function retrying(fn, recover, attempts = 8) {
68
73
  }
69
74
  }
70
75
 
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
76
  /** A warning when an existing render no longer runs as long as the film (after a retiming): its frames are stale. */
233
77
  export function staleRender(rendered, film, ranged = false) {
234
78
  if (ranged || Math.abs(rendered - film) <= 0.2) return null