@kriya-ai/harness 0.2.2 → 0.2.3
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/package.json +1 -1
- package/src/edit/core/ffmpeg.js +5 -1
- package/src/edit/core/layout.js +2 -0
- package/src/edit/core/ops.js +71 -4
- package/src/edit/core/project.js +6 -1
- package/src/edit/core/solver.js +27 -12
- package/src/edit/director/ask.js +42 -27
- package/src/edit/director/plan.js +298 -0
- package/src/edit/director/revise.js +169 -12
- package/src/edit/engine/motion.js +59 -16
- package/src/edit/engine/music-bed.js +110 -0
- package/src/edit/engine/reference.js +134 -0
- package/src/edit/engine/sfx.js +63 -0
- package/src/edit/host/client.js +28 -4
- package/src/edit/host/jobs.js +43 -0
- package/src/edit/host/main.js +4 -2
- package/src/edit/host/paths.js +25 -0
- package/src/edit/host/projects.js +163 -34
- package/src/edit/host/server.js +66 -8
- package/src/edit/index/db.js +5 -0
- package/src/edit/index/layers/retakes.js +7 -1
- package/src/edit/loop/make.js +2 -2
- package/src/edit/recipes/reel.js +121 -12
- package/studio/dist/studio.css +48 -4
- package/studio/dist/studio.js +4 -2
|
@@ -191,8 +191,9 @@ export function motionRuntime(runtime, platform = `${process.platform}-${process
|
|
|
191
191
|
const cli = join(runtime.dir, ...CLI)
|
|
192
192
|
const chrome = runtime.manifest?.platforms?.[platform]?.artifacts?.find((a) => a.id === "chrome-headless-shell")
|
|
193
193
|
const chromePath = chrome ? join(runtime.dir, chrome.id, chrome.entry) : null
|
|
194
|
-
if (!existsSync(cli)) return { missing: "This Media Runtime has no HyperFrames, so captions and motion can't render. A newer runtime brings it." }
|
|
195
194
|
if (!chromePath || !existsSync(chromePath)) return { missing: "This Media Runtime has no Chrome for the motion layer." }
|
|
195
|
+
// Without HyperFrames, Kriya draws tiles in the runtime's own Chrome, frame by frame (renderTileInChrome)
|
|
196
|
+
if (!existsSync(cli)) return { cli: null, chrome: chromePath, dir: runtime.dir, reads: [runtime.dir, realpathSync(join(runtime.dir, chrome.id))] }
|
|
196
197
|
// The runtime's own folders, after links: all a confined render may read of it
|
|
197
198
|
return { cli, chrome: chromePath, dir: runtime.dir, reads: [runtime.dir, realpathSync(join(runtime.dir, "hyperframes")), realpathSync(join(runtime.dir, chrome.id))] }
|
|
198
199
|
}
|
|
@@ -207,8 +208,9 @@ export function motionEnv(work, runtime, env = process.env) {
|
|
|
207
208
|
* @param {{ html: string, work: string, output: string, fps: { n: number, d: number }, runtime: ReturnType<typeof motionRuntime>, run?: typeof runTool, signal?: AbortSignal, which?: ReturnType<typeof confinement>, seconds?: number }} input
|
|
208
209
|
* work: a folder of this tile's own; output: where the tile goes
|
|
209
210
|
*/
|
|
210
|
-
export async function renderTile({ html, work, output, fps, runtime, run = runTool, signal, which = confinement(), seconds = 10 }) {
|
|
211
|
+
export async function renderTile({ html, work, output, fps, runtime, run = runTool, signal, which = confinement(), seconds = 10, launch }) {
|
|
211
212
|
if (runtime.missing) throw new EngineFailure("environment", "missing_feature", runtime.missing)
|
|
213
|
+
if (!runtime.cli) return renderTileInChrome({ html, work, output, fps, runtime, run, signal, which, seconds, launch })
|
|
212
214
|
const comp = join(work, "comp")
|
|
213
215
|
mkdirSync(join(work, "tmp"), { recursive: true })
|
|
214
216
|
mkdirSync(comp, { recursive: true })
|
|
@@ -220,6 +222,59 @@ export async function renderTile({ html, work, output, fps, runtime, run = runTo
|
|
|
220
222
|
if (!existsSync(output)) throw new EngineFailure("render", "failed", "The motion renderer finished without writing its tile.")
|
|
221
223
|
}
|
|
222
224
|
|
|
225
|
+
/**
|
|
226
|
+
* A tile without HyperFrames: the composition in the runtime's Chrome, inside the same
|
|
227
|
+
* sandbox, every animation paused at each frame's time and the stage captured with its
|
|
228
|
+
* transparency, then encoded by our FFmpeg to the same ProRes 4444 tile. The runtime
|
|
229
|
+
* signed for 2026.11.0 carries Chrome but not HyperFrames, so captions never rendered.
|
|
230
|
+
*/
|
|
231
|
+
export async function renderTileInChrome({ html, work, output, fps, runtime, run = runTool, signal, which = confinement(), seconds = 10, launch }) {
|
|
232
|
+
const frames = Math.max(1, Math.round((seconds * fps.n) / fps.d))
|
|
233
|
+
const dir = join(work, "frames")
|
|
234
|
+
mkdirSync(dir, { recursive: true })
|
|
235
|
+
await withChrome({ work, runtime, which, launch }, async (page) => {
|
|
236
|
+
writeFileSync(join(work, "index.html"), html)
|
|
237
|
+
await page.goto(`file://${join(work, "index.html")}`)
|
|
238
|
+
const [width, height] = await page.evaluate(() => {
|
|
239
|
+
const stage = document.getElementById("stage")
|
|
240
|
+
return [Number(stage.dataset.width), Number(stage.dataset.height)]
|
|
241
|
+
})
|
|
242
|
+
await page.setViewportSize({ width, height })
|
|
243
|
+
const stage = page.locator("#stage")
|
|
244
|
+
for (let i = 0; i < frames; i++) {
|
|
245
|
+
if (signal?.aborted) throw signal.reason
|
|
246
|
+
await page.evaluate((t) => {
|
|
247
|
+
for (const animation of document.getAnimations()) {
|
|
248
|
+
animation.pause()
|
|
249
|
+
animation.currentTime = t
|
|
250
|
+
}
|
|
251
|
+
}, (i * 1000 * fps.d) / fps.n)
|
|
252
|
+
await stage.screenshot({ path: join(dir, `${String(i).padStart(6, "0")}.png`), omitBackground: true, animations: "allow" })
|
|
253
|
+
}
|
|
254
|
+
})
|
|
255
|
+
await run("ffmpeg", ["-hide_banner", "-nostdin", "-loglevel", "error", "-protocol_whitelist", "file,pipe", "-framerate", `${fps.n}/${fps.d}`, "-i", join(dir, "%06d.png"), "-c:v", "prores_ks", "-profile:v", "4444", "-pix_fmt", "yuva444p10le", "-vendor", "apl0", "-y", output], { signal, timeoutMs: 60_000 + seconds * 10_000 })
|
|
256
|
+
if (!existsSync(output)) throw new EngineFailure("render", "failed", "The caption renderer finished without writing its tile.")
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** The runtime's Chrome, started confined by playwright through a sandbox wrapper; one page. */
|
|
260
|
+
async function withChrome({ work, runtime, which, launch }, use) {
|
|
261
|
+
const { chromium } = launch ? {} : await import("playwright-core")
|
|
262
|
+
const open = launch ?? ((dir, options) => chromium.launchPersistentContext(dir, options))
|
|
263
|
+
if ([work, runtime.chrome].some((path) => path.includes("'"))) throw new EngineFailure("environment", "bad_path", "A folder name with a quote can't hold the motion layer's work.")
|
|
264
|
+
mkdirSync(join(work, "tmp"), { recursive: true })
|
|
265
|
+
// Playwright starts this script; the script starts Chrome inside the sandbox
|
|
266
|
+
const { args } = confine(runtime.chrome, [], { read: [...runtime.reads, work], write: [work] }, which)
|
|
267
|
+
writeFileSync(join(work, "chrome.sb"), args[1])
|
|
268
|
+
const wrapper = join(work, "chrome.sh")
|
|
269
|
+
writeFileSync(wrapper, `#!/bin/sh\nexec /usr/bin/sandbox-exec -f '${join(work, "chrome.sb")}' '${runtime.chrome}' "$@"\n`, { mode: 0o755 })
|
|
270
|
+
const context = await open(join(work, "profile"), { executablePath: wrapper, headless: true, offline: true, env: { HOME: work, TMPDIR: join(work, "tmp") } })
|
|
271
|
+
try {
|
|
272
|
+
return await use(context.pages()[0] ?? (await context.newPage()))
|
|
273
|
+
} finally {
|
|
274
|
+
await context.close()
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
223
278
|
// HyperFrames encodes with the FFmpeg on PATH; Homebrew's lives outside the runtime (EDD-06)
|
|
224
279
|
function ffmpegHome() {
|
|
225
280
|
return ["/opt/homebrew", "/usr/local/Cellar", "/usr/local/opt", "/usr/local/bin"].filter((path) => existsSync(path))
|
|
@@ -251,9 +306,6 @@ function readBoxes(times) {
|
|
|
251
306
|
*/
|
|
252
307
|
export async function measureText({ items, work, runtime, which = confinement(), launch }) {
|
|
253
308
|
if (runtime.missing) throw new EngineFailure("environment", "missing_feature", runtime.missing)
|
|
254
|
-
const { chromium } = launch ? {} : await import("playwright-core")
|
|
255
|
-
const open = launch ?? ((dir, options) => chromium.launchPersistentContext(dir, options))
|
|
256
|
-
if ([work, runtime.chrome].some((path) => path.includes("'"))) throw new EngineFailure("environment", "bad_path", "A folder name with a quote can't hold the motion layer's work.")
|
|
257
309
|
mkdirSync(join(work, "tmp"), { recursive: true })
|
|
258
310
|
const files = items.map((item, i) => {
|
|
259
311
|
const dir = join(work, `c${i}`)
|
|
@@ -261,21 +313,12 @@ export async function measureText({ items, work, runtime, which = confinement(),
|
|
|
261
313
|
writeFileSync(join(dir, "index.html"), item.html)
|
|
262
314
|
return join(dir, "index.html")
|
|
263
315
|
})
|
|
264
|
-
|
|
265
|
-
const { args } = confine(runtime.chrome, [], { read: [...runtime.reads, work], write: [work] }, which)
|
|
266
|
-
writeFileSync(join(work, "chrome.sb"), args[1])
|
|
267
|
-
const wrapper = join(work, "chrome.sh")
|
|
268
|
-
writeFileSync(wrapper, `#!/bin/sh\nexec /usr/bin/sandbox-exec -f '${join(work, "chrome.sb")}' '${runtime.chrome}' "$@"\n`, { mode: 0o755 })
|
|
269
|
-
const context = await open(join(work, "profile"), { executablePath: wrapper, headless: true, offline: true, env: { HOME: work, TMPDIR: join(work, "tmp") } })
|
|
270
|
-
try {
|
|
271
|
-
const page = context.pages()[0] ?? (await context.newPage())
|
|
316
|
+
return withChrome({ work, runtime, which, launch }, async (page) => {
|
|
272
317
|
const out = new Map()
|
|
273
318
|
for (const [i, item] of items.entries()) {
|
|
274
319
|
await page.goto(`file://${files[i]}`)
|
|
275
320
|
out.set(item.id, await page.evaluate(readBoxes, item.times))
|
|
276
321
|
}
|
|
277
322
|
return out
|
|
278
|
-
}
|
|
279
|
-
await context.close()
|
|
280
|
-
}
|
|
323
|
+
})
|
|
281
324
|
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// A music bed made by code (2026-11-09): chords, bass and a light beat, written sample by
|
|
2
|
+
// sample to a WAV. Nobody else's recording is in it, so it carries no licence question,
|
|
3
|
+
// and the same mood and length always give the same file. It goes through the ED9 path
|
|
4
|
+
// like any song: its beats are indexed, it's fitted on downbeats and ducked under speech.
|
|
5
|
+
|
|
6
|
+
import { writeFileSync } from "node:fs"
|
|
7
|
+
|
|
8
|
+
const RATE = 48_000
|
|
9
|
+
|
|
10
|
+
/** Moods: tempo, chords (MIDI notes), and how much beat. Data only. */
|
|
11
|
+
export const MOODS = {
|
|
12
|
+
calm: { bpm: 80, chords: [[57, 60, 64], [53, 57, 60], [48, 52, 55], [55, 59, 62]], kick: 0, hat: 0, pulse: 0.15 },
|
|
13
|
+
upbeat: { bpm: 112, chords: [[57, 60, 64], [53, 57, 60], [48, 52, 55], [55, 59, 62]], kick: 0.55, hat: 0.12, pulse: 0.35 },
|
|
14
|
+
warm: { bpm: 92, chords: [[48, 52, 55, 59], [45, 48, 52, 55], [53, 57, 60, 64], [55, 59, 62, 65]], kick: 0.3, hat: 0.06, pulse: 0.25 },
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const hz = (note) => 440 * 2 ** ((note - 69) / 12)
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Writes a stereo 16-bit WAV of `seconds` (plus a short tail) for `mood`.
|
|
21
|
+
* @returns {{ file: string, seconds: number, bpm: number }}
|
|
22
|
+
*/
|
|
23
|
+
export function writeMusicBed(file, { mood = "calm", seconds = 60, bpm } = {}) {
|
|
24
|
+
// A music reference's tempo can set the bed's (classified by analyseReference)
|
|
25
|
+
const spec = { ...(MOODS[mood] ?? MOODS.calm), ...(bpm >= 60 && bpm <= 180 ? { bpm: Math.round(bpm) } : {}) }
|
|
26
|
+
const total = Math.ceil((Math.max(5, seconds) + 2) * RATE)
|
|
27
|
+
const beat = (60 / spec.bpm) * RATE // samples a beat
|
|
28
|
+
const bar = beat * 4
|
|
29
|
+
const chordLength = bar * 2 // each chord holds two bars
|
|
30
|
+
const left = new Float32Array(total)
|
|
31
|
+
const right = new Float32Array(total)
|
|
32
|
+
let seed = 0x9e3779b9
|
|
33
|
+
const noise = () => ((seed = (seed * 1664525 + 1013904223) >>> 0) / 2 ** 32) * 2 - 1
|
|
34
|
+
let lastNoise = 0
|
|
35
|
+
for (let i = 0; i < total; i++) {
|
|
36
|
+
const t = i / RATE
|
|
37
|
+
const c = Math.floor(i / chordLength) % spec.chords.length
|
|
38
|
+
const inChord = (i % chordLength) / chordLength
|
|
39
|
+
// A soft swell into each chord and out of it, so changes never click
|
|
40
|
+
const swell = Math.min(1, inChord * 12) * Math.min(1, (1 - inChord) * 12)
|
|
41
|
+
let l = 0
|
|
42
|
+
let r = 0
|
|
43
|
+
for (const note of spec.chords[c]) {
|
|
44
|
+
const f = hz(note)
|
|
45
|
+
// Two slightly detuned voices per note: one leans left, one right
|
|
46
|
+
const a = Math.sin(2 * Math.PI * f * 0.998 * t) + 0.3 * Math.sin(2 * Math.PI * f * 2 * t)
|
|
47
|
+
const b = Math.sin(2 * Math.PI * f * 1.002 * t) + 0.25 * Math.sin(2 * Math.PI * f * 3 * t)
|
|
48
|
+
l += a
|
|
49
|
+
r += b
|
|
50
|
+
}
|
|
51
|
+
const pad = (0.1 * swell) / spec.chords[c].length
|
|
52
|
+
l *= pad
|
|
53
|
+
r *= pad
|
|
54
|
+
// Bass: the chord's root an octave down, pulsing on the beat
|
|
55
|
+
const inBeat = (i % beat) / beat
|
|
56
|
+
const bass = Math.sin(2 * Math.PI * hz(spec.chords[c][0] - 12) * t) * (1 - spec.pulse * inBeat) * 0.12 * swell
|
|
57
|
+
l += bass
|
|
58
|
+
r += bass
|
|
59
|
+
// Kick on every beat: a falling sine with a fast decay
|
|
60
|
+
if (spec.kick) {
|
|
61
|
+
const k = (i % beat) / RATE
|
|
62
|
+
const kick = Math.sin(2 * Math.PI * (50 + 70 * Math.exp(-k * 30)) * k) * Math.exp(-k * 18) * spec.kick
|
|
63
|
+
l += kick
|
|
64
|
+
r += kick
|
|
65
|
+
}
|
|
66
|
+
// A closed hat on the off-beat: high-passed noise, very short
|
|
67
|
+
if (spec.hat) {
|
|
68
|
+
const off = ((i + beat / 2) % beat) / RATE
|
|
69
|
+
const white = noise()
|
|
70
|
+
const bright = white - lastNoise
|
|
71
|
+
lastNoise = white
|
|
72
|
+
const hat = bright * Math.exp(-off * 90) * spec.hat
|
|
73
|
+
l += hat * 0.9
|
|
74
|
+
r += hat
|
|
75
|
+
}
|
|
76
|
+
// Fade in over 1.5 s, out over the last 2 s
|
|
77
|
+
const fade = Math.min(1, t / 1.5) * Math.min(1, (total - i) / (2 * RATE))
|
|
78
|
+
left[i] = l * fade
|
|
79
|
+
right[i] = r * fade
|
|
80
|
+
}
|
|
81
|
+
writeWav(file, left, right)
|
|
82
|
+
return { file, seconds: total / RATE, bpm: spec.bpm }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** A stereo 16-bit WAV at 48 kHz, peaking at about -6 dBFS (the mix sets the level). */
|
|
86
|
+
export function writeWav(file, left, right) {
|
|
87
|
+
const total = left.length
|
|
88
|
+
let peak = 0
|
|
89
|
+
for (let i = 0; i < total; i++) peak = Math.max(peak, Math.abs(left[i]), Math.abs(right[i]))
|
|
90
|
+
const scale = peak ? 0.5 / peak : 0
|
|
91
|
+
const data = Buffer.alloc(total * 4)
|
|
92
|
+
for (let i = 0; i < total; i++) {
|
|
93
|
+
data.writeInt16LE(Math.round(left[i] * scale * 32767), i * 4)
|
|
94
|
+
data.writeInt16LE(Math.round(right[i] * scale * 32767), i * 4 + 2)
|
|
95
|
+
}
|
|
96
|
+
const head = Buffer.alloc(44)
|
|
97
|
+
head.write("RIFF", 0)
|
|
98
|
+
head.writeUInt32LE(36 + data.length, 4)
|
|
99
|
+
head.write("WAVEfmt ", 8)
|
|
100
|
+
head.writeUInt32LE(16, 16)
|
|
101
|
+
head.writeUInt16LE(1, 20)
|
|
102
|
+
head.writeUInt16LE(2, 22)
|
|
103
|
+
head.writeUInt32LE(RATE, 24)
|
|
104
|
+
head.writeUInt32LE(RATE * 4, 28)
|
|
105
|
+
head.writeUInt16LE(4, 32)
|
|
106
|
+
head.writeUInt16LE(16, 34)
|
|
107
|
+
head.write("data", 36)
|
|
108
|
+
head.writeUInt32LE(data.length, 40)
|
|
109
|
+
writeFileSync(file, Buffer.concat([head, data]))
|
|
110
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// References, classified (2026-11-09): a video gives its editing pace and captions (Edit
|
|
2
|
+
// DNA) and its colour; an image gives its colour grade; a piece of music gives its tempo and
|
|
3
|
+
// energy. Every value is a number or a fixed word, never a pixel, sound or word of the
|
|
4
|
+
// reference (EDD-23), and each turns into something the cut can really do.
|
|
5
|
+
|
|
6
|
+
import { extractDna } from "./dna.js"
|
|
7
|
+
import { measureLoudness } from "./loudness.js"
|
|
8
|
+
import { runTool } from "./tool.js"
|
|
9
|
+
import { analyseMusic, musicArgs, pcmCollector } from "../index/layers/music.js"
|
|
10
|
+
|
|
11
|
+
const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v))
|
|
12
|
+
const round = (v, places = 2) => Math.round(v * 10 ** places) / 10 ** places
|
|
13
|
+
|
|
14
|
+
/** Averages of FFmpeg's signalstats over sampled frames (a frame every 2 s, the first 90 s). */
|
|
15
|
+
export async function colourStats(file, { image = false, run = runTool, signal } = {}) {
|
|
16
|
+
const vf = `${image ? "" : "fps=1/2,"}scale=160:-2,signalstats,metadata=print:file=-`
|
|
17
|
+
const text = await run("ffmpeg", ["-hide_banner", "-nostdin", "-loglevel", "error", "-protocol_whitelist", "file,pipe", ...(image ? [] : ["-t", "90"]), "-i", file, "-vf", vf, "-an", "-f", "null", "-"], { signal, timeoutMs: 180_000 })
|
|
18
|
+
const sums = {}
|
|
19
|
+
const counts = {}
|
|
20
|
+
for (const m of text.matchAll(/lavfi\.signalstats\.(YAVG|UAVG|VAVG|SATAVG|YLOW|YHIGH)=([\d.]+)/g)) {
|
|
21
|
+
sums[m[1]] = (sums[m[1]] ?? 0) + Number(m[2])
|
|
22
|
+
counts[m[1]] = (counts[m[1]] ?? 0) + 1
|
|
23
|
+
}
|
|
24
|
+
if (!counts.YAVG) return null
|
|
25
|
+
return Object.fromEntries(Object.keys(sums).map((key) => [key, sums[key] / counts[key]]))
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The grade that moves a picture toward a reference's colour, and the words for it.
|
|
30
|
+
* shortcut: a fixed mapping from 8-bit averages, approximate by design; a measured match
|
|
31
|
+
* against the person's own footage (colour.js) is the precise path, for a later phase
|
|
32
|
+
*/
|
|
33
|
+
export function gradeFromStats(stats) {
|
|
34
|
+
const warmth = stats.VAVG - stats.UAVG // above 0 leans red and orange, below leans blue
|
|
35
|
+
const grade = {
|
|
36
|
+
// Kept within a tasteful range: a reference leans the cut, it doesn't overpower it
|
|
37
|
+
temperature: Math.round(clamp(6500 - warmth * 60, 4200, 9000) / 100) * 100,
|
|
38
|
+
saturation: round(clamp(stats.SATAVG / 32, 0.75, 1.3)),
|
|
39
|
+
gain: round(clamp((stats.YHIGH - stats.YLOW) / 190, 0.9, 1.2)),
|
|
40
|
+
lift: round(clamp((stats.YAVG - 115) / 700, -0.05, 0.05), 3),
|
|
41
|
+
}
|
|
42
|
+
const words = [warmth > 4 ? "warm" : warmth < -4 ? "cool" : "neutral", grade.saturation > 1.15 ? "saturated" : grade.saturation < 0.85 ? "muted" : "natural colour", grade.gain > 1.08 ? "contrasty" : grade.gain < 0.93 ? "soft contrast" : "even contrast", stats.YAVG > 140 ? "bright" : stats.YAVG < 85 ? "dark" : "mid brightness"]
|
|
43
|
+
return { grade, words }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Tempo and energy of music: the bed's mood and tempo follow it. */
|
|
47
|
+
export async function musicOf(file, { run = runTool, signal } = {}) {
|
|
48
|
+
const pcm = pcmCollector()
|
|
49
|
+
// The first minute is enough to hear a tempo
|
|
50
|
+
await run("ffmpeg", [...musicArgs(file).slice(0, -1), "-t", "60", "pipe:1"], { onStdout: pcm.add, signal, timeoutMs: 180_000 })
|
|
51
|
+
const { bpm } = analyseMusic(pcm.finish())
|
|
52
|
+
const { integrated } = await measureLoudness(file, { run, signal })
|
|
53
|
+
const mood = bpm === null ? (integrated !== null && integrated > -14 ? "upbeat" : "calm") : bpm >= 104 ? "upbeat" : bpm <= 86 ? "calm" : "warm"
|
|
54
|
+
return { bpm: bpm === null ? null : Math.round(bpm), lufs: integrated === null ? null : round(integrated, 1), mood }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* @param {string} file
|
|
59
|
+
* @param {{ width?: number, duration?: number, hasAudio?: boolean }} facts from probe
|
|
60
|
+
* @returns {Promise<{ kind: "video" | "image" | "audio", colour?: object, pace?: object, captions?: boolean, music?: object, lines: string[] }>}
|
|
61
|
+
*/
|
|
62
|
+
export async function analyseReference(file, facts, { run = runTool, signal } = {}) {
|
|
63
|
+
const kind = facts.width ? (facts.duration ? "video" : "image") : "audio"
|
|
64
|
+
// `parts`: each line under the aspect it informs, so a reference taken for one aspect gives only that
|
|
65
|
+
const out = { kind, lines: [], parts: {} }
|
|
66
|
+
const line = (aspect, text) => (out.lines.push(text), (out.parts[aspect] = text))
|
|
67
|
+
if (kind !== "audio") {
|
|
68
|
+
const stats = await colourStats(file, { image: kind === "image", run, signal })
|
|
69
|
+
if (stats) {
|
|
70
|
+
out.colour = gradeFromStats(stats)
|
|
71
|
+
line("colour", `Colour: ${out.colour.words.join(", ")}`)
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
if (kind === "video") {
|
|
75
|
+
const dna = await extractDna(file, { run, signal }).catch(() => null)
|
|
76
|
+
if (dna?.pace?.median) {
|
|
77
|
+
out.pace = { every: dna.pace.median, shots: dna.pace.shots }
|
|
78
|
+
line("editing", `Pace: the picture changes every ${dna.pace.median.toFixed(1)} s (${dna.pace.shots} shots)`)
|
|
79
|
+
}
|
|
80
|
+
if (dna) {
|
|
81
|
+
out.captions = !!dna.captions?.present
|
|
82
|
+
line("graphics", out.captions ? "Captions: yes, on screen" : "Captions: none")
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
// A video's soundtrack is measured too: it's what a reference taken for its sound gives
|
|
86
|
+
if (kind === "audio" || (kind === "video" && facts.hasAudio)) {
|
|
87
|
+
out.music = await musicOf(file, { run, signal }).catch(() => null)
|
|
88
|
+
if (out.music) line("sound", `Music: ${out.music.bpm ? `${out.music.bpm} bpm, ` : ""}${out.music.mood}${out.music.lufs !== null ? `, ${out.music.lufs} LUFS` : ""}`)
|
|
89
|
+
}
|
|
90
|
+
return out
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** What a reference can be taken for: the person picks one per reference, or all of it. */
|
|
94
|
+
export const ASPECTS = {
|
|
95
|
+
all: "Everything it shows",
|
|
96
|
+
editing: "Editing: cuts and pace",
|
|
97
|
+
sound: "Sound: music and feel",
|
|
98
|
+
colour: "Colour grade",
|
|
99
|
+
graphics: "Graphics: captions and text",
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** References as the person sent them: ids, or { id, aspect }; anything else dropped. At most six. */
|
|
103
|
+
export function cleanRefs(list) {
|
|
104
|
+
if (!Array.isArray(list)) return []
|
|
105
|
+
const safe = (v) => typeof v === "string" && /^[A-Za-z0-9:_-]{1,64}$/.test(v)
|
|
106
|
+
const out = []
|
|
107
|
+
for (const item of list) {
|
|
108
|
+
const ref = safe(item) ? { id: item, aspect: "all" } : item && safe(item.id) ? { id: item.id, aspect: Object.hasOwn(ASPECTS, item.aspect) ? item.aspect : "all" } : null
|
|
109
|
+
if (ref && !out.some((r) => r.id === ref.id)) out.push(ref)
|
|
110
|
+
}
|
|
111
|
+
return out.slice(0, 6)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Only what the reference was taken for. "all" keeps the earlier rule for a video's sound: used
|
|
116
|
+
* only when it has no cuts to read, since a cut video's soundtrack is usually speech.
|
|
117
|
+
*/
|
|
118
|
+
export function takeFrom(found, aspect = "all") {
|
|
119
|
+
const wants = (a) => aspect === "all" || aspect === a
|
|
120
|
+
const parts = found.parts ?? {}
|
|
121
|
+
const out = { kind: found.kind, lines: [] }
|
|
122
|
+
const keep = (a, key) => {
|
|
123
|
+
if (!wants(a) || found[key] === undefined || found[key] === null) return
|
|
124
|
+
out[key] = found[key]
|
|
125
|
+
if (parts[a]) out.lines.push(parts[a])
|
|
126
|
+
}
|
|
127
|
+
keep("colour", "colour")
|
|
128
|
+
keep("editing", "pace")
|
|
129
|
+
keep("graphics", "captions")
|
|
130
|
+
if (aspect === "sound" || (aspect === "all" && !(found.kind === "video" && found.pace))) keep("sound", "music")
|
|
131
|
+
// An analysis kept from before `parts` existed: its lines, for everything
|
|
132
|
+
if (!found.parts && aspect === "all") out.lines = [...(found.lines ?? [])]
|
|
133
|
+
return out
|
|
134
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// Sound effects made by code (2026-11-09): a whoosh or a pop for cuts, a riser into the
|
|
2
|
+
// intro, a hit for a cold open's end. Written sample by sample, so no one else's sound is
|
|
3
|
+
// in them, and each knows where its peak is: add_sfx lands that peak on the cut.
|
|
4
|
+
|
|
5
|
+
import { writeWav } from "./music-bed.js"
|
|
6
|
+
|
|
7
|
+
const RATE = 48_000
|
|
8
|
+
const FLICKS = 705_600_000
|
|
9
|
+
|
|
10
|
+
/** Each effect: its length and where its loudest moment falls, in seconds. */
|
|
11
|
+
export const SFX = {
|
|
12
|
+
whoosh: { seconds: 0.7, peak: 0.42 },
|
|
13
|
+
pop: { seconds: 0.14, peak: 0.01 },
|
|
14
|
+
riser: { seconds: 1.6, peak: 1.55 },
|
|
15
|
+
hit: { seconds: 0.9, peak: 0.02 },
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Writes one effect as a stereo WAV.
|
|
20
|
+
* @returns {{ file: string, peak: number }} peak in flicks from the file's start
|
|
21
|
+
*/
|
|
22
|
+
export function writeSfx(file, kind) {
|
|
23
|
+
const spec = SFX[kind]
|
|
24
|
+
if (!spec) throw new RangeError(`There is no "${kind}" sound.`)
|
|
25
|
+
const total = Math.round(spec.seconds * RATE)
|
|
26
|
+
const left = new Float32Array(total)
|
|
27
|
+
const right = new Float32Array(total)
|
|
28
|
+
let seed = 0x2545f491
|
|
29
|
+
const noise = () => ((seed = (seed * 1664525 + 1013904223) >>> 0) / 2 ** 32) * 2 - 1
|
|
30
|
+
let lowL = 0
|
|
31
|
+
let lowR = 0
|
|
32
|
+
for (let i = 0; i < total; i++) {
|
|
33
|
+
const t = i / RATE
|
|
34
|
+
const x = t / spec.seconds // 0 to 1 through the effect
|
|
35
|
+
let l = 0
|
|
36
|
+
let r = 0
|
|
37
|
+
if (kind === "whoosh" || kind === "riser") {
|
|
38
|
+
// Noise through a one-pole low-pass that opens and closes: the sweep you hear
|
|
39
|
+
const open = kind === "whoosh" ? Math.sin(Math.PI * Math.min(1, t / spec.peak / 2 + (t > spec.peak ? 0.5 * ((t - spec.peak) / (spec.seconds - spec.peak)) : 0))) : x * x
|
|
40
|
+
const k = 0.02 + 0.5 * open
|
|
41
|
+
lowL += k * (noise() - lowL)
|
|
42
|
+
lowR += k * (noise() - lowR)
|
|
43
|
+
const env = kind === "whoosh" ? Math.exp(-(((t - spec.peak) / 0.16) ** 2)) : x ** 2.2 * (t < spec.peak ? 1 : Math.max(0, 1 - (t - spec.peak) / 0.05))
|
|
44
|
+
// A riser also climbs in pitch
|
|
45
|
+
const tone = kind === "riser" ? 0.35 * Math.sin(2 * Math.PI * (200 + 900 * x * x) * t) : 0
|
|
46
|
+
// The whoosh moves from left to right as it passes
|
|
47
|
+
const pan = kind === "whoosh" ? x : 0.5
|
|
48
|
+
l = (lowL + tone) * env * (1 - pan * 0.6)
|
|
49
|
+
r = (lowR + tone) * env * (0.4 + pan * 0.6)
|
|
50
|
+
} else if (kind === "pop") {
|
|
51
|
+
const env = Math.exp(-t * 60)
|
|
52
|
+
l = r = Math.sin(2 * Math.PI * (900 - 600 * x) * t) * env
|
|
53
|
+
} else {
|
|
54
|
+
// Hit: a deep falling thump with a short noisy attack
|
|
55
|
+
const env = Math.exp(-t * 6)
|
|
56
|
+
l = r = Math.sin(2 * Math.PI * (40 + 90 * Math.exp(-t * 25)) * t) * env + noise() * Math.exp(-t * 80) * 0.4
|
|
57
|
+
}
|
|
58
|
+
left[i] = l
|
|
59
|
+
right[i] = r
|
|
60
|
+
}
|
|
61
|
+
writeWav(file, left, right)
|
|
62
|
+
return { file, peak: Math.round(spec.peak * FLICKS) }
|
|
63
|
+
}
|
package/src/edit/host/client.js
CHANGED
|
@@ -7,7 +7,7 @@ import { request } from "node:http"
|
|
|
7
7
|
import { join } from "node:path"
|
|
8
8
|
|
|
9
9
|
import { kriyaHome } from "../../paths.js"
|
|
10
|
-
import { editHome, logPath, socketPath } from "./paths.js"
|
|
10
|
+
import { codeStamp, editHome, logPath, socketPath } from "./paths.js"
|
|
11
11
|
|
|
12
12
|
const START_MS = 15_000
|
|
13
13
|
|
|
@@ -33,10 +33,34 @@ export function hostCall(home, method, path, body) {
|
|
|
33
33
|
|
|
34
34
|
const contact = (home) => hostCall(home, "GET", "/internal/info").catch(() => null)
|
|
35
35
|
|
|
36
|
-
|
|
37
|
-
|
|
36
|
+
const gone = async (pid) => {
|
|
37
|
+
for (let i = 0; i < 100; i++) {
|
|
38
|
+
try {
|
|
39
|
+
process.kill(pid, 0)
|
|
40
|
+
} catch {
|
|
41
|
+
return
|
|
42
|
+
}
|
|
43
|
+
await new Promise((done) => setTimeout(done, 50))
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Jobs a Host is running; an old Host doesn't report it, so its job list is asked. */
|
|
48
|
+
const activeOf = async (home, live) =>
|
|
49
|
+
live.busy ?? (await hostCall(home, "GET", "/jobs").then(({ jobs }) => jobs.filter((j) => ["pending", "running"].includes(j.status)).length).catch(() => 1))
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The running Host, started if need be. A Host running older code than this one is
|
|
53
|
+
* stopped and replaced, unless it's in the middle of work: then it's left to finish.
|
|
54
|
+
* @returns {Promise<{ pid: number, port: number }>}
|
|
55
|
+
*/
|
|
56
|
+
export async function ensureHost({ env = process.env, home = kriyaHome(), stamp = codeStamp() } = {}) {
|
|
38
57
|
const live = await contact(home)
|
|
39
|
-
if (live) return live
|
|
58
|
+
if (live && live.stamp === stamp) return live
|
|
59
|
+
if (live) {
|
|
60
|
+
if (await activeOf(home, live)) return live
|
|
61
|
+
await stopHost(home)
|
|
62
|
+
await gone(live.pid)
|
|
63
|
+
}
|
|
40
64
|
mkdirSync(editHome(home), { recursive: true })
|
|
41
65
|
const log = openSync(logPath(home), "a")
|
|
42
66
|
const main = join(import.meta.dirname, "main.js")
|
package/src/edit/host/jobs.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
// The Host owns jobs (EDD-03): each lives in its project's journal, so a job in
|
|
2
2
|
// progress when the Host dies resumes on the next start with no finished node redone.
|
|
3
3
|
|
|
4
|
+
import { existsSync } from "node:fs"
|
|
5
|
+
import { basename, dirname, join, resolve } from "node:path"
|
|
6
|
+
|
|
4
7
|
import { projectAt } from "../core/history.js"
|
|
5
8
|
|
|
6
9
|
// A render is of the version it was asked for, not whatever the project has become by
|
|
@@ -62,6 +65,8 @@ export function createJobs({ projects, emit, log, onDispatch, beforeStory }) {
|
|
|
62
65
|
|
|
63
66
|
return {
|
|
64
67
|
count: () => running.size,
|
|
68
|
+
/** Whether a project has a job running now. */
|
|
69
|
+
runningIn: (project) => [...running.keys()].some((id) => id.startsWith(`${project}.`)),
|
|
65
70
|
|
|
66
71
|
start(state, request) {
|
|
67
72
|
const number = state.journal.addJob({ kind: request.kind ?? "render", projectVersion: state.log.head, request })
|
|
@@ -69,6 +74,44 @@ export function createJobs({ projects, emit, log, onDispatch, beforeStory }) {
|
|
|
69
74
|
return view(state, state.journal.job(number))
|
|
70
75
|
},
|
|
71
76
|
|
|
77
|
+
/**
|
|
78
|
+
* The project's finished films, newest first: renders, and the masters makes and revisions
|
|
79
|
+
* wrote. Only files in its exports folder that still exist; `current` says whether the film
|
|
80
|
+
* shows the project as it is now (a render is of the version it was asked for).
|
|
81
|
+
*/
|
|
82
|
+
renders(state) {
|
|
83
|
+
const exportsDir = resolve(join(state.folder, "exports"))
|
|
84
|
+
const out = []
|
|
85
|
+
for (const row of state.journal.jobs("done")) {
|
|
86
|
+
let file = null
|
|
87
|
+
let version = null
|
|
88
|
+
let quality = "master"
|
|
89
|
+
let verdict = null
|
|
90
|
+
if (row.kind === "render") {
|
|
91
|
+
file = row.dispatch
|
|
92
|
+
version = row.project_version
|
|
93
|
+
try {
|
|
94
|
+
quality = JSON.parse(row.request ?? "{}").quality ?? "draft"
|
|
95
|
+
} catch {}
|
|
96
|
+
} else if (row.kind === "make" || row.kind === "revise") {
|
|
97
|
+
try {
|
|
98
|
+
const done = JSON.parse(row.dispatch ?? "{}")
|
|
99
|
+
;({ file = null, head: version = null, verdict = null } = done)
|
|
100
|
+
} catch {}
|
|
101
|
+
} else continue
|
|
102
|
+
if (typeof file !== "string" || dirname(resolve(file)) !== exportsDir || !existsSync(file)) continue
|
|
103
|
+
out.push({ job: row.id, kind: row.kind, quality, name: basename(file), verdict, current: version !== null && version === state.log.head, at: row.finished_at })
|
|
104
|
+
}
|
|
105
|
+
// The Engine names a film by what it shows, so two jobs can share a file: listed once, newest
|
|
106
|
+
const seen = new Set()
|
|
107
|
+
return out.reverse().filter((r) => !seen.has(r.name) && seen.add(r.name))
|
|
108
|
+
},
|
|
109
|
+
/** A finished film's path, only through renders(): never a path the browser names. */
|
|
110
|
+
renderFile(state, number) {
|
|
111
|
+
const found = this.renders(state).find((r) => r.job === number)
|
|
112
|
+
return found ? join(state.folder, "exports", found.name) : null
|
|
113
|
+
},
|
|
114
|
+
|
|
72
115
|
async list() {
|
|
73
116
|
const jobs = []
|
|
74
117
|
await projects.each((state) => {
|
package/src/edit/host/main.js
CHANGED
|
@@ -12,7 +12,7 @@ import { createScheduler, DEFAULT_SLOTS } from "../graph/scheduler.js"
|
|
|
12
12
|
import { createGovernor } from "../loop/governor.js"
|
|
13
13
|
import { kriyaHome } from "../../paths.js"
|
|
14
14
|
import { createJobs } from "./jobs.js"
|
|
15
|
-
import { editHome, lockPath, portPath, socketPath } from "./paths.js"
|
|
15
|
+
import { codeStamp, editHome, lockPath, portPath, socketPath } from "./paths.js"
|
|
16
16
|
import { createProjects } from "./projects.js"
|
|
17
17
|
import { createHandler } from "./server.js"
|
|
18
18
|
import { createTavi } from "./tavi.js"
|
|
@@ -76,7 +76,9 @@ const watcher = createWatcher({ home, send: tavi.post, log })
|
|
|
76
76
|
let lastActive = Date.now()
|
|
77
77
|
let inFlight = 0 // a request still running isn't idle, however long it takes
|
|
78
78
|
let port = 0
|
|
79
|
-
|
|
79
|
+
// What code this process runs, so an outdated Host is replaced once it's idle (client.js)
|
|
80
|
+
const stamp = codeStamp()
|
|
81
|
+
const handle = createHandler({ home, roots, projects, jobs, tavi, tools: readTools, tokenTtlMs, port: () => port, stamp, busy: () => jobs.count() + tavi.pending(), onActivity: (change = 0) => ((inFlight += change), (lastActive = Date.now())), onStop: () => shutdown(), onLive: () => (liveAt = Date.now()), sse, log, pid: process.pid })
|
|
80
82
|
const web = createServer((req, res) => handle(req, res, false))
|
|
81
83
|
const local = createServer((req, res) => handle(req, res, true))
|
|
82
84
|
|
package/src/edit/host/paths.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
// Where the Host keeps things (ARCHITECTURE §5): never in a synced folder (EF-28).
|
|
2
2
|
|
|
3
|
+
import { createHash } from "node:crypto"
|
|
4
|
+
import { readdirSync, statSync } from "node:fs"
|
|
3
5
|
import { join } from "node:path"
|
|
4
6
|
|
|
5
7
|
import { kriyaHome } from "../../paths.js"
|
|
@@ -9,3 +11,26 @@ export const socketPath = (home) => join(editHome(home), "host.sock")
|
|
|
9
11
|
export const lockPath = (home) => join(editHome(home), "host.lock")
|
|
10
12
|
export const portPath = (home) => join(editHome(home), "port")
|
|
11
13
|
export const logPath = (home) => join(editHome(home), "host.log")
|
|
14
|
+
|
|
15
|
+
const SRC = join(import.meta.dirname, "..", "..")
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* A fingerprint of the code a Host runs: every source file's name, size and time. A
|
|
19
|
+
* running Host keeps the code it started with, so after an update the Studio looked new
|
|
20
|
+
* (its files are read per request) while the Host ran the old Director (found 2026-11-09).
|
|
21
|
+
*/
|
|
22
|
+
export function codeStamp(root = SRC) {
|
|
23
|
+
const hash = createHash("sha256")
|
|
24
|
+
const walk = (dir) => {
|
|
25
|
+
for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1))) {
|
|
26
|
+
const path = join(dir, entry.name)
|
|
27
|
+
if (entry.isDirectory()) walk(path)
|
|
28
|
+
else if (/\.(js|swift)$/.test(entry.name)) {
|
|
29
|
+
const { size, mtimeMs } = statSync(path)
|
|
30
|
+
hash.update(`${path.slice(root.length)}:${size}:${mtimeMs}\n`)
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
walk(root)
|
|
35
|
+
return hash.digest("hex").slice(0, 16)
|
|
36
|
+
}
|