@kriya-ai/harness 0.0.0-stage → 0.2.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.
- package/README.md +379 -2
- package/SAFETY.md +162 -0
- package/THIRD_PARTY_NOTICES.md +7911 -0
- package/bin/kriya.js +577 -0
- package/bundle/cordis.patch.yml +397 -0
- package/contract/SOURCE.md +15 -0
- package/contract/contract.json +1355 -0
- package/package.json +57 -4
- package/plugins/anchor/index.js +56 -0
- package/plugins/anchor/package.json +13 -0
- package/plugins/approvals/index.js +183 -0
- package/plugins/approvals/package.json +13 -0
- package/plugins/brand/DESIGN.md +112 -0
- package/plugins/brand/client.js +826 -0
- package/plugins/brand/index.js +15 -0
- package/plugins/brand/package.json +25 -0
- package/plugins/brand/src/client.js +823 -0
- package/plugins/browser/index.js +218 -0
- package/plugins/browser/package.json +13 -0
- package/plugins/budget/index.js +108 -0
- package/plugins/budget/package.json +13 -0
- package/plugins/changes/client.js +245 -0
- package/plugins/changes/index.js +75 -0
- package/plugins/changes/package.json +22 -0
- package/plugins/edit/client.js +113 -0
- package/plugins/edit/index.js +58 -0
- package/plugins/edit/package.json +23 -0
- package/plugins/fs-freshness/index.js +28 -0
- package/plugins/fs-freshness/package.json +13 -0
- package/plugins/graph/client.js +178 -0
- package/plugins/graph/index.js +4 -0
- package/plugins/graph/package.json +22 -0
- package/plugins/kriya-handoff/index.js +194 -0
- package/plugins/kriya-handoff/package.json +13 -0
- package/plugins/kriya-tools/index.js +189 -0
- package/plugins/kriya-tools/package.json +13 -0
- package/plugins/loop/index.js +743 -0
- package/plugins/loop/package.json +13 -0
- package/plugins/mirror/index.js +235 -0
- package/plugins/mirror/package.json +13 -0
- package/plugins/overview/client.js +276 -0
- package/plugins/overview/index.js +95 -0
- package/plugins/overview/package.json +22 -0
- package/plugins/preview/client.js +337 -0
- package/plugins/preview/index.js +4 -0
- package/plugins/preview/package.json +22 -0
- package/plugins/progress/client.js +290 -0
- package/plugins/progress/index.js +100 -0
- package/plugins/progress/package.json +22 -0
- package/plugins/projects/client.js +249 -0
- package/plugins/projects/index.js +30 -0
- package/plugins/projects/package.json +24 -0
- package/plugins/rea/index.js +256 -0
- package/plugins/rea/package.json +10 -0
- package/plugins/rea/skill/LICENSE +21 -0
- package/plugins/rea/skill/SKILL.md +360 -0
- package/plugins/rea/skill/references/android-applications.md +36 -0
- package/plugins/rea/skill/references/connection-and-recovery.md +127 -0
- package/plugins/rea/skill/references/evidence-workflows.md +71 -0
- package/plugins/rea/skill/references/javascript-applications.md +218 -0
- package/plugins/rea/skill/references/native-and-artifacts.md +297 -0
- package/plugins/rea/skill/references/runtime-observation.md +78 -0
- package/plugins/remote/index.js +297 -0
- package/plugins/remote/package.json +10 -0
- package/plugins/router/index.js +84 -0
- package/plugins/router/package.json +13 -0
- package/plugins/sessions/client.js +68 -0
- package/plugins/sessions/index.js +79 -0
- package/plugins/sessions/package.json +20 -0
- package/plugins/skills/client.js +504 -0
- package/plugins/skills/index.js +166 -0
- package/plugins/skills/package.json +23 -0
- package/src/api.js +97 -0
- package/src/browser.js +286 -0
- package/src/changes.js +191 -0
- package/src/checkpoints.js +313 -0
- package/src/daemon.js +503 -0
- package/src/doctor.js +137 -0
- package/src/edit/core/anchors.js +102 -0
- package/src/edit/core/audio.js +158 -0
- package/src/edit/core/faces.js +99 -0
- package/src/edit/core/ffmpeg.js +258 -0
- package/src/edit/core/handoff.js +220 -0
- package/src/edit/core/history.js +90 -0
- package/src/edit/core/layout.js +92 -0
- package/src/edit/core/mix.js +115 -0
- package/src/edit/core/ops.js +602 -0
- package/src/edit/core/plan.js +266 -0
- package/src/edit/core/project.d.ts +134 -0
- package/src/edit/core/project.js +307 -0
- package/src/edit/core/reframe.js +125 -0
- package/src/edit/core/solver.js +416 -0
- package/src/edit/core/time.js +110 -0
- package/src/edit/core/tonemap.js +57 -0
- package/src/edit/director/ask.js +120 -0
- package/src/edit/director/gateway.js +16 -0
- package/src/edit/director/revise.js +186 -0
- package/src/edit/engine/capabilities.js +33 -0
- package/src/edit/engine/captions.js +154 -0
- package/src/edit/engine/color.js +269 -0
- package/src/edit/engine/confine.js +67 -0
- package/src/edit/engine/dna.js +148 -0
- package/src/edit/engine/index.js +473 -0
- package/src/edit/engine/loudness.js +43 -0
- package/src/edit/engine/media.js +57 -0
- package/src/edit/engine/motion.js +281 -0
- package/src/edit/engine/packs.js +87 -0
- package/src/edit/engine/probe.js +101 -0
- package/src/edit/engine/receipt.js +123 -0
- package/src/edit/engine/tool.js +101 -0
- package/src/edit/gates/copy.js +113 -0
- package/src/edit/gates/index.js +430 -0
- package/src/edit/gates/picture.js +130 -0
- package/src/edit/gates/sound.js +58 -0
- package/src/edit/gates/speech.js +127 -0
- package/src/edit/gates/text.js +196 -0
- package/src/edit/gates/text.swift +22 -0
- package/src/edit/graph/index.js +139 -0
- package/src/edit/graph/journal.js +69 -0
- package/src/edit/graph/scheduler.js +79 -0
- package/src/edit/host/client.js +58 -0
- package/src/edit/host/deliver.js +119 -0
- package/src/edit/host/jobs.js +84 -0
- package/src/edit/host/main.js +135 -0
- package/src/edit/host/paths.js +11 -0
- package/src/edit/host/projects.js +415 -0
- package/src/edit/host/server.js +391 -0
- package/src/edit/host/taste.js +135 -0
- package/src/edit/host/tavi.js +417 -0
- package/src/edit/host/watch.js +141 -0
- package/src/edit/index/db.js +109 -0
- package/src/edit/index/index.js +236 -0
- package/src/edit/index/layers/faces.js +78 -0
- package/src/edit/index/layers/faces.swift +18 -0
- package/src/edit/index/layers/meta.js +35 -0
- package/src/edit/index/layers/music.js +146 -0
- package/src/edit/index/layers/quality.js +120 -0
- package/src/edit/index/layers/retakes.js +132 -0
- package/src/edit/index/layers/screen.js +99 -0
- package/src/edit/index/layers/shots.js +29 -0
- package/src/edit/index/layers/sound.js +42 -0
- package/src/edit/index/layers/words.js +64 -0
- package/src/edit/index/story.js +248 -0
- package/src/edit/index/views.js +71 -0
- package/src/edit/loop/governor.js +112 -0
- package/src/edit/loop/loop.js +69 -0
- package/src/edit/loop/make.js +115 -0
- package/src/edit/loop/repair.js +97 -0
- package/src/edit/loop/replay.js +32 -0
- package/src/edit/recipes/multicam.js +461 -0
- package/src/edit/recipes/reel.js +202 -0
- package/src/edit/recipes/short-from-long.js +237 -0
- package/src/edit/recipes/tutorial.js +137 -0
- package/src/edit/recipes/youtube.js +155 -0
- package/src/edit/runtime/cli.js +126 -0
- package/src/edit/runtime/doctor.js +122 -0
- package/src/edit/runtime/fetch.js +15 -0
- package/src/edit/runtime/licences.js +88 -0
- package/src/edit/runtime/manifest.js +73 -0
- package/src/edit/runtime/setup.js +252 -0
- package/src/failure.js +69 -0
- package/src/gateway-proxy.js +213 -0
- package/src/intent.js +130 -0
- package/src/launch.js +315 -0
- package/src/live.js +81 -0
- package/src/local-skills.js +284 -0
- package/src/login.js +82 -0
- package/src/loop.js +428 -0
- package/src/modes.js +128 -0
- package/src/overview.js +71 -0
- package/src/paths.js +30 -0
- package/src/profiles.js +92 -0
- package/src/projects.js +104 -0
- package/src/recon.js +244 -0
- package/src/rules.js +139 -0
- package/src/runner.bundle.js +21172 -0
- package/src/sentinel.js +248 -0
- package/src/skill-switches.js +130 -0
- package/src/store.js +58 -0
- package/src/strict.js +124 -0
- package/src/verify.js +659 -0
- package/src/world.js +268 -0
- package/studio/dist/index.html +14 -0
- package/studio/dist/studio.css +163 -0
- package/studio/dist/studio.js +1 -0
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
// The Footage Index (PERCEPTION_AND_INDEX): runs each layer once per media and
|
|
2
|
+
// version, in the order that unblocks the edit, and writes what it found to
|
|
3
|
+
// index.sqlite. A missing or failed layer is recorded with a plain notice and
|
|
4
|
+
// lowers what's possible; it never stops the others that don't need it.
|
|
5
|
+
|
|
6
|
+
import { existsSync, mkdirSync, readdirSync, rmSync } from "node:fs"
|
|
7
|
+
import { join } from "node:path"
|
|
8
|
+
|
|
9
|
+
import { probe } from "../engine/probe.js"
|
|
10
|
+
import { EngineFailure, runTool } from "../engine/tool.js"
|
|
11
|
+
import { activeRuntime, childEnv } from "../runtime/setup.js"
|
|
12
|
+
import { FACES_VERSION, faceHelper, frameArgs, readFaces } from "./layers/faces.js"
|
|
13
|
+
import { analyseMusic, MUSIC_VERSION, musicArgs, pcmCollector } from "./layers/music.js"
|
|
14
|
+
import { QUALITY_VERSION, qualityArgs, qualityCollector, scoreShots } from "./layers/quality.js"
|
|
15
|
+
import { RETAKES_VERSION, analyseDelivery } from "./layers/retakes.js"
|
|
16
|
+
import { SHOTS_VERSION, readShots, shotArgs } from "./layers/shots.js"
|
|
17
|
+
import { SOUND_VERSION, readSound, soundArgs } from "./layers/sound.js"
|
|
18
|
+
import { MODEL, WORDS_VERSION, readWords, recogniser, speechArgs, transcribeArgs } from "./layers/words.js"
|
|
19
|
+
|
|
20
|
+
export const PROBE_VERSION = "l0-1"
|
|
21
|
+
export const LAYERS = ["L0", "L1", "L2", "L5", "L6", "L7", "L8"]
|
|
22
|
+
/** The layers for an asset: a sound file also gets its beats (L12, ED9). */
|
|
23
|
+
export const layersFor = (kind) => (kind === "audio" ? [...LAYERS, "L12"] : LAYERS)
|
|
24
|
+
const FLICKS = 705_600_000
|
|
25
|
+
const timeout = (duration, perSecond) => Math.max(120_000, Math.ceil((duration ?? 0) / FLICKS) * perSecond)
|
|
26
|
+
|
|
27
|
+
class Unavailable extends Error {}
|
|
28
|
+
const unavailable = (message) => {
|
|
29
|
+
throw new Unavailable(message)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* @param {{ db: ReturnType<import("./db.js").openIndexDb>, cache: string, binDir: string, language?: string, run?: typeof runTool, runtime?: () => object | null, acquire?: (resources: string[], signal?: AbortSignal) => Promise<() => void> }} options
|
|
34
|
+
*/
|
|
35
|
+
export function createIndexer({ db, cache, binDir, language = "en", run = runTool, runtime = () => activeRuntime(), acquire = async () => () => {} }) {
|
|
36
|
+
const layers = {
|
|
37
|
+
L0: {
|
|
38
|
+
version: PROBE_VERSION,
|
|
39
|
+
async run({ path }) {
|
|
40
|
+
const { facts, timestamps } = await probe(path, { run })
|
|
41
|
+
return { data: { facts, ...(timestamps ? { timestamps } : {}) } }
|
|
42
|
+
},
|
|
43
|
+
},
|
|
44
|
+
L1: {
|
|
45
|
+
version: SOUND_VERSION,
|
|
46
|
+
needs: ["L0"],
|
|
47
|
+
async run({ path, facts, signal, fingerprint }) {
|
|
48
|
+
if (!facts.hasAudio) unavailable("This file has no sound.")
|
|
49
|
+
const { data, silences } = readSound(await run("ffmpeg", soundArgs(path), { signal, timeoutMs: timeout(facts.duration, 2_000) }), facts.duration)
|
|
50
|
+
return { data, write: (sql) => silences.forEach((s) => sql.prepare("insert into events (media, start, \"end\", kind, conf) values (?, ?, ?, 'silence', null)").run(fingerprint, s.start, s.end)) }
|
|
51
|
+
},
|
|
52
|
+
},
|
|
53
|
+
L2: {
|
|
54
|
+
version: `${WORDS_VERSION}:${MODEL}:${language}`,
|
|
55
|
+
needs: ["L0"],
|
|
56
|
+
resources: ["gpu"],
|
|
57
|
+
async run({ path, facts, signal, fingerprint }) {
|
|
58
|
+
if (!facts.hasAudio) unavailable("This file has no sound, so it has no words.")
|
|
59
|
+
const engine = recogniser(runtime())
|
|
60
|
+
if (engine.missing) unavailable(engine.missing)
|
|
61
|
+
const audio = join(cache, "speech", `${fingerprint}.wav`)
|
|
62
|
+
mkdirSync(join(cache, "speech"), { recursive: true })
|
|
63
|
+
try {
|
|
64
|
+
await run("ffmpeg", speechArgs(path, audio), { signal, timeoutMs: timeout(facts.duration, 1_000) })
|
|
65
|
+
// Offline: the model reads only its installed weights
|
|
66
|
+
const env = { ...childEnv(), HF_HUB_OFFLINE: "1", HF_HUB_DISABLE_TELEMETRY: "1" }
|
|
67
|
+
const words = readWords(await run(engine.python, transcribeArgs(engine, audio, language), { signal, env, timeoutMs: timeout(facts.duration, 2_000) }))
|
|
68
|
+
return {
|
|
69
|
+
data: { count: words.length, language, model: MODEL },
|
|
70
|
+
write: (sql) => {
|
|
71
|
+
const insert = sql.prepare('insert into words (media, n, start, "end", text, lang, conf) values (?, ?, ?, ?, ?, ?, ?)')
|
|
72
|
+
const search = sql.prepare("insert into words_fts (text, media, n) values (?, ?, ?)")
|
|
73
|
+
words.forEach((w, n) => {
|
|
74
|
+
insert.run(fingerprint, n, w.start, w.end, w.text, language, w.conf)
|
|
75
|
+
search.run(w.text, fingerprint, n)
|
|
76
|
+
})
|
|
77
|
+
},
|
|
78
|
+
}
|
|
79
|
+
} finally {
|
|
80
|
+
rmSync(audio, { force: true })
|
|
81
|
+
}
|
|
82
|
+
},
|
|
83
|
+
},
|
|
84
|
+
L5: {
|
|
85
|
+
version: RETAKES_VERSION,
|
|
86
|
+
needs: ["L2"],
|
|
87
|
+
async run({ fingerprint }) {
|
|
88
|
+
const words = db.db.prepare('select n, start, "end", text, conf from words where media = ? order by n').all(fingerprint)
|
|
89
|
+
if (!words.length) return { data: { sentences: 0, groups: 0 } }
|
|
90
|
+
const { flags, sentences, takes } = analyseDelivery(words, { language })
|
|
91
|
+
return {
|
|
92
|
+
data: { sentences: sentences.length, groups: new Set(takes.map((t) => t.group)).size },
|
|
93
|
+
write: (sql) => {
|
|
94
|
+
const flag = sql.prepare("update words set flags = ? where media = ? and n = ?")
|
|
95
|
+
flags.forEach((list, i) => flag.run([...new Set(list)].join(","), fingerprint, words[i].n))
|
|
96
|
+
const sentence = sql.prepare('insert into sentences (media, n, start, "end", first_word, last_word, take_group, score) values (?, ?, ?, ?, ?, ?, ?, ?)')
|
|
97
|
+
sentences.forEach((s, n) => sentence.run(fingerprint, n, s.start, s.end, words[s.first].n, words[s.last].n, s.group, s.score))
|
|
98
|
+
const take = sql.prepare('insert into takes (media, "group", sentence, rank, signals) values (?, ?, ?, ?, ?)')
|
|
99
|
+
for (const t of takes) take.run(fingerprint, t.group, t.sentence, t.rank, JSON.stringify(t.signals))
|
|
100
|
+
},
|
|
101
|
+
}
|
|
102
|
+
},
|
|
103
|
+
},
|
|
104
|
+
L6: {
|
|
105
|
+
version: SHOTS_VERSION,
|
|
106
|
+
needs: ["L0"],
|
|
107
|
+
async run({ path, facts, signal, fingerprint }) {
|
|
108
|
+
if (!facts.width) unavailable("This file has no picture.")
|
|
109
|
+
const shots = readShots(await run("ffmpeg", shotArgs(path), { signal, timeoutMs: timeout(facts.duration, 2_000) }), facts.duration)
|
|
110
|
+
return {
|
|
111
|
+
data: { shots: shots.length, transitions: "hard cuts only" },
|
|
112
|
+
write: (sql) => {
|
|
113
|
+
const insert = sql.prepare('insert into shots (media, n, start, "end", kind) values (?, ?, ?, ?, ?)')
|
|
114
|
+
shots.forEach((s, n) => insert.run(fingerprint, n, s.start, s.end, s.kind))
|
|
115
|
+
},
|
|
116
|
+
}
|
|
117
|
+
},
|
|
118
|
+
},
|
|
119
|
+
L7: {
|
|
120
|
+
version: QUALITY_VERSION,
|
|
121
|
+
needs: ["L6"],
|
|
122
|
+
async run({ path, facts, signal, fingerprint }) {
|
|
123
|
+
const collector = qualityCollector()
|
|
124
|
+
await run("ffmpeg", qualityArgs(path), { signal, timeoutMs: timeout(facts.duration, 2_000), onStdout: (chunk) => collector.add(chunk) })
|
|
125
|
+
const shots = db.db.prepare('select n, start, "end" from shots where media = ? order by n').all(fingerprint)
|
|
126
|
+
const scores = scoreShots(collector.finish(), shots)
|
|
127
|
+
return {
|
|
128
|
+
data: { shots: shots.length, calibrated: false },
|
|
129
|
+
write: (sql) => {
|
|
130
|
+
const update = sql.prepare("update shots set blur = ?, exposure = ?, shake = ?, motion = ? where media = ? and n = ?")
|
|
131
|
+
scores.forEach((s, i) => update.run(s.blur, s.exposure, s.shake, s.motion, fingerprint, shots[i].n))
|
|
132
|
+
},
|
|
133
|
+
}
|
|
134
|
+
},
|
|
135
|
+
},
|
|
136
|
+
L8: {
|
|
137
|
+
version: FACES_VERSION,
|
|
138
|
+
needs: ["L6"],
|
|
139
|
+
async run({ path, facts, signal, fingerprint }) {
|
|
140
|
+
if (!facts.width) unavailable("This file has no picture.")
|
|
141
|
+
const helper = await faceHelper(binDir, run)
|
|
142
|
+
if (helper.missing) unavailable(helper.missing)
|
|
143
|
+
const folder = join(cache, "faces", fingerprint)
|
|
144
|
+
rmSync(folder, { recursive: true, force: true })
|
|
145
|
+
mkdirSync(folder, { recursive: true })
|
|
146
|
+
try {
|
|
147
|
+
await run("ffmpeg", frameArgs(path, folder), { signal, timeoutMs: timeout(facts.duration, 1_000) })
|
|
148
|
+
const sampled = existsSync(folder) ? readdirSync(folder).length : 0
|
|
149
|
+
const faces = readFaces(await run(helper.path, [folder], { signal, timeoutMs: timeout(facts.duration, 1_000) }), facts)
|
|
150
|
+
const shots = db.db.prepare('select n, start, "end" from shots where media = ? order by n').all(fingerprint)
|
|
151
|
+
const shotAt = (t) => shots.find((s) => t >= s.start && t < s.end)?.n ?? null
|
|
152
|
+
return {
|
|
153
|
+
data: { sampled, faces: faces.length, tracks: new Set(faces.map((f) => f.identity)).size },
|
|
154
|
+
write: (sql) => {
|
|
155
|
+
const insert = sql.prepare("insert into faces (media, shot, t, box, identity) values (?, ?, ?, ?, ?)")
|
|
156
|
+
for (const f of faces) insert.run(fingerprint, shotAt(f.t), f.t, JSON.stringify(f.box), f.identity)
|
|
157
|
+
},
|
|
158
|
+
}
|
|
159
|
+
} finally {
|
|
160
|
+
rmSync(folder, { recursive: true, force: true })
|
|
161
|
+
}
|
|
162
|
+
},
|
|
163
|
+
},
|
|
164
|
+
L12: {
|
|
165
|
+
version: MUSIC_VERSION,
|
|
166
|
+
needs: ["L0"],
|
|
167
|
+
async run({ path, facts, signal, fingerprint }) {
|
|
168
|
+
if (!facts.hasAudio) unavailable("This file has no sound.")
|
|
169
|
+
if (facts.width) unavailable("Beats are read from sound files.")
|
|
170
|
+
const pcm = pcmCollector()
|
|
171
|
+
await run("ffmpeg", musicArgs(path), { signal, timeoutMs: timeout(facts.duration, 2_000), onStdout: (chunk) => pcm.add(chunk) })
|
|
172
|
+
const { bpm, beats, bars } = analyseMusic(pcm.finish())
|
|
173
|
+
if (!beats.length) unavailable("No steady beat was found in this sound.")
|
|
174
|
+
return {
|
|
175
|
+
data: { bpm, beats: beats.length, bars: bars.length, meter: "4/4 assumed" },
|
|
176
|
+
write: (sql) => {
|
|
177
|
+
const beat = sql.prepare("insert into beats (media, n, t, downbeat, strength) values (?, ?, ?, ?, ?)")
|
|
178
|
+
beats.forEach((b, n) => beat.run(fingerprint, n, b.t, b.downbeat ? 1 : 0, b.strength))
|
|
179
|
+
const bar = sql.prepare('insert into bars (media, n, start, "end", energy) values (?, ?, ?, ?, ?)')
|
|
180
|
+
bars.forEach((b, n) => bar.run(fingerprint, n, b.start, b.end, b.energy))
|
|
181
|
+
},
|
|
182
|
+
}
|
|
183
|
+
},
|
|
184
|
+
},
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// A layer's key: its own version, and when each layer it reads last changed
|
|
188
|
+
const keyOf = (fingerprint, name) => [layers[name].version, ...(layers[name].needs ?? []).map((dep) => `${dep}@${db.layer(fingerprint, dep)?.updated_at ?? "none"}`)].join("|")
|
|
189
|
+
|
|
190
|
+
return {
|
|
191
|
+
layers,
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Runs what's missing for one asset. Identical media re-added does no work (ET-IDX-01).
|
|
195
|
+
* @param {{ id: string, kind: string, fingerprint: string, facts: object }} asset
|
|
196
|
+
* @param {string} path the real source path, already through guardPath
|
|
197
|
+
* @returns {Promise<{ layer: string, status: string, notice: string | null, ran: boolean }[]>}
|
|
198
|
+
*/
|
|
199
|
+
async indexAsset(asset, path, { signal, only = LAYERS, onStep = () => {} } = {}) {
|
|
200
|
+
const fingerprint = asset.fingerprint
|
|
201
|
+
db.setAsset(asset.id, fingerprint, asset.kind)
|
|
202
|
+
const report = []
|
|
203
|
+
for (const [step, name] of only.entries()) {
|
|
204
|
+
const layer = layers[name]
|
|
205
|
+
const key = keyOf(fingerprint, name)
|
|
206
|
+
const before = db.layer(fingerprint, name)
|
|
207
|
+
if (before?.model_version === key && before.status === "ok") {
|
|
208
|
+
report.push({ layer: name, status: "ok", notice: before.notice, ran: false })
|
|
209
|
+
onStep(step + 1, only.length)
|
|
210
|
+
continue
|
|
211
|
+
}
|
|
212
|
+
const blocked = (layer.needs ?? []).find((dep) => db.layer(fingerprint, dep)?.status !== "ok")
|
|
213
|
+
let result
|
|
214
|
+
if (blocked) result = { status: "unavailable", notice: `Needs ${blocked}, which isn't available.` }
|
|
215
|
+
else {
|
|
216
|
+
const release = await acquire(layer.resources ?? ["cpu"], signal)
|
|
217
|
+
try {
|
|
218
|
+
const facts = db.layer(fingerprint, "L0")?.data?.facts ?? asset.facts
|
|
219
|
+
const done = await layer.run({ path, facts, signal, fingerprint })
|
|
220
|
+
result = { status: "ok", notice: null, ...done }
|
|
221
|
+
} catch (error) {
|
|
222
|
+
if (signal?.aborted) throw error
|
|
223
|
+
if (error instanceof Unavailable) result = { status: "unavailable", notice: error.message }
|
|
224
|
+
else result = { status: "failed", notice: error instanceof EngineFailure ? error.message : `This layer failed: ${error.message}` }
|
|
225
|
+
} finally {
|
|
226
|
+
release()
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
db.saveLayer(fingerprint, name, { version: key, status: result.status, notice: result.notice, data: result.data ?? null, write: result.write })
|
|
230
|
+
report.push({ layer: name, status: result.status, notice: result.notice, ran: !blocked })
|
|
231
|
+
onStep(step + 1, only.length)
|
|
232
|
+
}
|
|
233
|
+
return report
|
|
234
|
+
},
|
|
235
|
+
}
|
|
236
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// L8 Faces: boxes sampled once a second and linked into tracks by centroid, for the
|
|
2
|
+
// layout's safe zones. macOS uses Vision through a small helper compiled once; other
|
|
3
|
+
// systems wait for the runtime's MediaPipe or YuNet, and the layer says so.
|
|
4
|
+
// Eye and chin lines and gaze come with landmarks, later.
|
|
5
|
+
|
|
6
|
+
import { createHash } from "node:crypto"
|
|
7
|
+
import { existsSync, mkdirSync, readFileSync, renameSync } from "node:fs"
|
|
8
|
+
import { dirname, join } from "node:path"
|
|
9
|
+
import { fileURLToPath } from "node:url"
|
|
10
|
+
|
|
11
|
+
export const FACES_VERSION = "l8-1"
|
|
12
|
+
export const MIN_CONFIDENCE = 0.5
|
|
13
|
+
const FLICKS = 705_600_000
|
|
14
|
+
const HELPER = join(dirname(fileURLToPath(import.meta.url)), "faces.swift")
|
|
15
|
+
|
|
16
|
+
export const frameArgs = (source, folder) => ["-hide_banner", "-nostdin", "-loglevel", "error", "-protocol_whitelist", "file,pipe", "-i", source, "-an", "-sn", "-dn", "-vf", "fps=1,scale=640:-2", "-q:v", "4", "-y", join(folder, "f%06d.jpg")]
|
|
17
|
+
|
|
18
|
+
/** The compiled helper's path, building it on first use. @returns {Promise<{ path?: string, missing?: string }>} */
|
|
19
|
+
export async function faceHelper(binDir, run, platform = process.platform) {
|
|
20
|
+
if (platform !== "darwin") return { missing: "Face tracking on this system needs the Media Runtime's face model, which isn't in it yet." }
|
|
21
|
+
const source = readFileSync(HELPER)
|
|
22
|
+
const path = join(binDir, `faces-${createHash("sha256").update(source).digest("hex").slice(0, 12)}`)
|
|
23
|
+
if (existsSync(path)) return { path }
|
|
24
|
+
mkdirSync(binDir, { recursive: true })
|
|
25
|
+
try {
|
|
26
|
+
await run("swiftc", ["-O", HELPER, "-o", `${path}.${process.pid}.part`])
|
|
27
|
+
renameSync(`${path}.${process.pid}.part`, path)
|
|
28
|
+
} catch {
|
|
29
|
+
return { missing: "Face tracking needs Apple's command line tools (xcode-select --install)." }
|
|
30
|
+
}
|
|
31
|
+
return { path }
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Helper lines → boxes in source pixels, top-left origin, each with a track id.
|
|
36
|
+
* Frame n of the fps=1 sampling sits at n − 1 seconds.
|
|
37
|
+
*/
|
|
38
|
+
export function readFaces(text, { width, height }) {
|
|
39
|
+
const faces = []
|
|
40
|
+
for (const line of text.split("\n")) {
|
|
41
|
+
if (!line.trim()) continue
|
|
42
|
+
const { frame, faces: found } = JSON.parse(line)
|
|
43
|
+
const t = (Number(/f(\d+)\.jpg$/.exec(frame)[1]) - 1) * FLICKS
|
|
44
|
+
for (const f of found) {
|
|
45
|
+
if (f.c < MIN_CONFIDENCE) continue
|
|
46
|
+
faces.push({ t, box: { x: Math.floor(f.x * width), y: Math.floor((1 - f.y - f.h) * height), w: Math.ceil(f.w * width), h: Math.ceil(f.h * height) } })
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return track(faces)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const centre = ({ box }) => ({ x: box.x + box.w / 2, y: box.y + box.h / 2 })
|
|
53
|
+
|
|
54
|
+
/** Links each box to the nearest track seen in the last two samples, within half a face width. */
|
|
55
|
+
export function track(faces) {
|
|
56
|
+
const live = [] // { id, last }
|
|
57
|
+
let next = 0
|
|
58
|
+
const byTime = [...faces].sort((a, b) => a.t - b.t)
|
|
59
|
+
for (const face of byTime) {
|
|
60
|
+
const here = centre(face)
|
|
61
|
+
let best = null
|
|
62
|
+
for (const candidate of live) {
|
|
63
|
+
const gap = face.t - candidate.last.t
|
|
64
|
+
if (gap <= 0 || gap > 2 * FLICKS) continue
|
|
65
|
+
const there = centre(candidate.last)
|
|
66
|
+
const distance = Math.hypot(here.x - there.x, here.y - there.y)
|
|
67
|
+
if (distance <= face.box.w / 2 && (!best || distance < best.distance)) best = { candidate, distance }
|
|
68
|
+
}
|
|
69
|
+
if (best) {
|
|
70
|
+
face.identity = best.candidate.id
|
|
71
|
+
best.candidate.last = face
|
|
72
|
+
} else {
|
|
73
|
+
face.identity = next++
|
|
74
|
+
live.push({ id: face.identity, last: face })
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return byTime
|
|
78
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// L8 face boxes through Apple's Vision framework: no model download, nothing leaves
|
|
2
|
+
// the machine. Reads every .jpg in one folder; prints one JSON line per frame, boxes
|
|
3
|
+
// normalised with Vision's origin at the bottom left.
|
|
4
|
+
import Foundation
|
|
5
|
+
import Vision
|
|
6
|
+
|
|
7
|
+
let folder = URL(fileURLWithPath: CommandLine.arguments[1])
|
|
8
|
+
let names = (try? FileManager.default.contentsOfDirectory(atPath: folder.path)) ?? []
|
|
9
|
+
for name in names.filter({ $0.hasSuffix(".jpg") }).sorted() {
|
|
10
|
+
let request = VNDetectFaceRectanglesRequest()
|
|
11
|
+
try? VNImageRequestHandler(url: folder.appendingPathComponent(name)).perform([request])
|
|
12
|
+
let faces = (request.results ?? []).map { face -> [String: Double] in
|
|
13
|
+
let box = face.boundingBox
|
|
14
|
+
return ["x": box.minX, "y": box.minY, "w": box.width, "h": box.height, "c": Double(face.confidence)]
|
|
15
|
+
}
|
|
16
|
+
let data = try! JSONSerialization.data(withJSONObject: ["frame": name, "faces": faces])
|
|
17
|
+
print(String(data: data, encoding: .utf8)!)
|
|
18
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// FFmpeg's `metadata=mode=print:file=-` output, read as frames. A frame's time comes
|
|
2
|
+
// from its integer pts in a timebase we set, so no float seconds cross this boundary.
|
|
3
|
+
|
|
4
|
+
const FLICKS = 705_600_000n
|
|
5
|
+
|
|
6
|
+
/** pts in 1/`base` seconds → flicks, rounded down to the flick. */
|
|
7
|
+
export const ptsFlicks = (pts, base) => Number((BigInt(pts) * FLICKS) / BigInt(base))
|
|
8
|
+
|
|
9
|
+
/** "1.999979" → flicks, from its digits. */
|
|
10
|
+
export function decimalFlicks(text) {
|
|
11
|
+
const negative = text.startsWith("-")
|
|
12
|
+
const [whole, fraction = ""] = text.replace(/^-/, "").split(".")
|
|
13
|
+
const value = Number(((BigInt(whole) * 1_000_000_000n + BigInt(fraction.padEnd(9, "0").slice(0, 9))) * FLICKS) / 1_000_000_000n)
|
|
14
|
+
return negative ? -value : value
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** @returns {{ pts: number, values: Record<string, string> }[]} */
|
|
18
|
+
export function metadataFrames(text) {
|
|
19
|
+
const frames = []
|
|
20
|
+
for (const line of text.split("\n")) {
|
|
21
|
+
const head = /^frame:\d+\s+pts:(-?\d+)/.exec(line)
|
|
22
|
+
if (head) frames.push({ pts: Number(head[1]), values: {} })
|
|
23
|
+
else if (frames.length) {
|
|
24
|
+
const at = line.indexOf("=")
|
|
25
|
+
if (at > 0) frames.at(-1).values[line.slice(0, at)] = line.slice(at + 1).trim()
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return frames
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** A number, or null for FFmpeg's nan, inf and missing values. */
|
|
32
|
+
export const finite = (text) => {
|
|
33
|
+
const value = Number(text)
|
|
34
|
+
return text !== undefined && Number.isFinite(value) ? value : null
|
|
35
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
// L12 Music v1 (PERCEPTION_AND_INDEX §2, ED9): beats, downbeats and bar energy from
|
|
2
|
+
// a sound file, by Kriya's own code: an onset envelope, the tempo by autocorrelation,
|
|
3
|
+
// beats by dynamic programming, downbeats by where the low end hits hardest.
|
|
4
|
+
// shortcut: 4/4 assumed and no learned model; beat_this (the Beats pack) replaces it for real music.
|
|
5
|
+
|
|
6
|
+
export const MUSIC_VERSION = "l12-1"
|
|
7
|
+
export const RATE = 11_025
|
|
8
|
+
export const HOP = 128
|
|
9
|
+
const FLICKS = 705_600_000
|
|
10
|
+
const FRAME_FLICKS = (HOP * FLICKS) / RATE // 8 192 000, exactly
|
|
11
|
+
|
|
12
|
+
export const musicArgs = (source) => ["-hide_banner", "-nostdin", "-loglevel", "error", "-protocol_whitelist", "file,pipe", "-i", source, "-vn", "-sn", "-dn", "-ac", "1", "-ar", String(RATE), "-f", "s16le", "pipe:1"]
|
|
13
|
+
|
|
14
|
+
/** Collects s16le from stdout into floats. */
|
|
15
|
+
export function pcmCollector() {
|
|
16
|
+
const chunks = []
|
|
17
|
+
return {
|
|
18
|
+
add: (chunk) => chunks.push(chunk),
|
|
19
|
+
finish() {
|
|
20
|
+
const data = Buffer.concat(chunks)
|
|
21
|
+
const out = new Float32Array(Math.floor(data.length / 2))
|
|
22
|
+
for (let i = 0; i < out.length; i++) out[i] = data.readInt16LE(i * 2) / 32768
|
|
23
|
+
return out
|
|
24
|
+
},
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Log energy per hop, half-wave differenced: how much louder each frame is than the last. */
|
|
29
|
+
function onsets(samples) {
|
|
30
|
+
const frames = Math.floor(samples.length / HOP)
|
|
31
|
+
const energy = new Float64Array(frames)
|
|
32
|
+
for (let f = 0; f < frames; f++) {
|
|
33
|
+
let sum = 0
|
|
34
|
+
for (let i = f * HOP; i < (f + 1) * HOP; i++) sum += samples[i] * samples[i]
|
|
35
|
+
energy[f] = Math.log10(1e-10 + sum / HOP)
|
|
36
|
+
}
|
|
37
|
+
const raw = new Float64Array(frames)
|
|
38
|
+
for (let f = 1; f < frames; f++) raw[f] = Math.max(0, energy[f] - energy[f - 1])
|
|
39
|
+
// A light smoothing, so a hit split across two frames counts once
|
|
40
|
+
const out = raw.map((v, f) => 0.25 * (raw[f - 1] ?? 0) + 0.5 * v + 0.25 * (raw[f + 1] ?? 0))
|
|
41
|
+
// Take off the local mean over about a second, so loud passages don't count as onsets
|
|
42
|
+
const half = Math.round(RATE / HOP / 2)
|
|
43
|
+
const smooth = new Float64Array(frames)
|
|
44
|
+
let acc = 0
|
|
45
|
+
for (let f = 0; f < frames + half; f++) {
|
|
46
|
+
if (f < frames) acc += out[f]
|
|
47
|
+
if (f - 2 * half - 1 >= 0) acc -= out[f - 2 * half - 1]
|
|
48
|
+
const at = f - half
|
|
49
|
+
if (at >= 0 && at < frames) smooth[at] = acc / (Math.min(frames, f + 1) - Math.max(0, f - 2 * half))
|
|
50
|
+
}
|
|
51
|
+
return out.map((v, f) => Math.max(0, v - smooth[f]))
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** One-pole low-pass, for the kick's share of the onsets. */
|
|
55
|
+
function lowPassed(samples, hz) {
|
|
56
|
+
const a = Math.exp((-2 * Math.PI * hz) / RATE)
|
|
57
|
+
const out = new Float32Array(samples.length)
|
|
58
|
+
let y = 0
|
|
59
|
+
for (let i = 0; i < samples.length; i++) out[i] = y = (1 - a) * samples[i] + a * y
|
|
60
|
+
return out
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The beat period in frames, by autocorrelation weighted toward 120 BPM (Ellis 2007), refined to a fraction. */
|
|
64
|
+
export function tempoOf(envelope, { minBpm = 60, maxBpm = 200 } = {}) {
|
|
65
|
+
const fps = RATE / HOP
|
|
66
|
+
const lo = Math.floor((60 * fps) / maxBpm)
|
|
67
|
+
const hi = Math.ceil((60 * fps) / minBpm)
|
|
68
|
+
const r = new Float64Array(2 * hi + 4)
|
|
69
|
+
for (let lag = lo - 1; lag <= 2 * hi + 2; lag++) {
|
|
70
|
+
let sum = 0
|
|
71
|
+
for (let i = lag; i < envelope.length; i++) sum += envelope[i] * envelope[i - lag]
|
|
72
|
+
r[lag] = sum
|
|
73
|
+
}
|
|
74
|
+
let best = lo
|
|
75
|
+
let bestScore = -Infinity
|
|
76
|
+
for (let lag = lo; lag <= hi; lag++) {
|
|
77
|
+
const bpm = (60 * fps) / lag
|
|
78
|
+
const weight = Math.exp(-0.5 * (Math.log2(bpm / 120) / 1) ** 2)
|
|
79
|
+
// A real pulse repeats at twice its period too; half the tempo doesn't add its half
|
|
80
|
+
const pulse = r[lag] + 0.5 * Math.max(r[2 * lag - 1], r[2 * lag], r[2 * lag + 1])
|
|
81
|
+
if (pulse * weight > bestScore) {
|
|
82
|
+
bestScore = pulse * weight
|
|
83
|
+
best = lag
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
const [a, b, c] = [r[best - 1], r[best], r[best + 1]]
|
|
87
|
+
const shift = a - 2 * b + c === 0 ? 0 : (0.5 * (a - c)) / (a - 2 * b + c)
|
|
88
|
+
return best + Math.max(-0.5, Math.min(0.5, shift))
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Beats by dynamic programming: onset strength, less a penalty for straying from the period. */
|
|
92
|
+
export function trackBeats(envelope, period, tightness = 100) {
|
|
93
|
+
const n = envelope.length
|
|
94
|
+
const score = new Float64Array(n)
|
|
95
|
+
const from = new Int32Array(n).fill(-1)
|
|
96
|
+
for (let i = 0; i < n; i++) {
|
|
97
|
+
let best = 0
|
|
98
|
+
for (let j = Math.max(0, Math.round(i - 2 * period)); j <= i - Math.round(period / 2); j++) {
|
|
99
|
+
const value = score[j] - tightness * Math.log((i - j) / period) ** 2
|
|
100
|
+
if (value > best || from[i] === -1) {
|
|
101
|
+
best = value
|
|
102
|
+
from[i] = j
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
score[i] = envelope[i] + Math.max(0, best)
|
|
106
|
+
}
|
|
107
|
+
// Start from the strongest end within the last period
|
|
108
|
+
let at = n - 1
|
|
109
|
+
for (let i = Math.max(0, n - Math.round(period)); i < n; i++) if (score[i] > score[at]) at = i
|
|
110
|
+
const beats = []
|
|
111
|
+
while (at >= 0) {
|
|
112
|
+
beats.push(at)
|
|
113
|
+
at = from[at]
|
|
114
|
+
if (beats.length > n) break
|
|
115
|
+
}
|
|
116
|
+
return beats.reverse()
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* @param {Float32Array} samples mono at RATE
|
|
121
|
+
* @returns {{ bpm: number | null, beats: { t: number, downbeat: boolean, strength: number }[], bars: { start: number, end: number, energy: number }[] }} times in flicks
|
|
122
|
+
*/
|
|
123
|
+
export function analyseMusic(samples) {
|
|
124
|
+
const envelope = onsets(samples)
|
|
125
|
+
if (envelope.length < (RATE / HOP) * 4 || envelope.every((v) => v === 0)) return { bpm: null, beats: [], bars: [] }
|
|
126
|
+
const period = tempoOf(envelope)
|
|
127
|
+
const frames = trackBeats(envelope, period)
|
|
128
|
+
const low = onsets(lowPassed(samples, 150))
|
|
129
|
+
const top = Math.max(...frames.map((f) => envelope[f]), 1e-9)
|
|
130
|
+
// The bar's first beat is the phase where the low end lands hardest
|
|
131
|
+
const near = (f) => Math.max(low[f - 1] ?? 0, low[f], low[f + 1] ?? 0)
|
|
132
|
+
const phase = [0, 1, 2, 3].map((p) => frames.filter((_, i) => i % 4 === p).reduce((sum, f) => sum + near(f), 0) / Math.max(1, frames.filter((_, i) => i % 4 === p).length))
|
|
133
|
+
const first = phase.indexOf(Math.max(...phase))
|
|
134
|
+
// The rise at frame f marks a hit inside frame f: its middle (measured: f − ½ ran 11.6 ms early)
|
|
135
|
+
const beats = frames.map((f, i) => ({ t: Math.round((f + 0.5) * FRAME_FLICKS), downbeat: i % 4 === first, strength: Math.round((envelope[f] / top) * 1000) / 1000 }))
|
|
136
|
+
const downs = beats.filter((b) => b.downbeat).map((b) => b.t)
|
|
137
|
+
const rms = (from, to) => {
|
|
138
|
+
const a = Math.floor((from / FLICKS) * RATE)
|
|
139
|
+
const b = Math.min(samples.length, Math.floor((to / FLICKS) * RATE))
|
|
140
|
+
let sum = 0
|
|
141
|
+
for (let i = a; i < b; i++) sum += samples[i] * samples[i]
|
|
142
|
+
return b > a ? Math.sqrt(sum / (b - a)) : 0
|
|
143
|
+
}
|
|
144
|
+
const bars = downs.slice(0, -1).map((start, i) => ({ start, end: downs[i + 1], energy: Math.round(20 * Math.log10(1e-6 + rms(start, downs[i + 1])) * 10) / 10 }))
|
|
145
|
+
return { bpm: Math.round(((60 * RATE) / (HOP * period)) * 10) / 10, beats, bars }
|
|
146
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// L7 Picture quality per shot: blur, exposure, shake, motion, measured in code on
|
|
2
|
+
// small grey frames FFmpeg decodes at 4 a second. One pass, no OpenCV needed yet.
|
|
3
|
+
|
|
4
|
+
export const QUALITY_VERSION = "l7-1"
|
|
5
|
+
export const W = 160
|
|
6
|
+
export const H = 90
|
|
7
|
+
export const RATE = 4
|
|
8
|
+
const STEP = 705_600_000 / RATE
|
|
9
|
+
const SEARCH = 4 // pixels of shift tried each way, on a half-size copy
|
|
10
|
+
|
|
11
|
+
export const qualityArgs = (source) => ["-hide_banner", "-nostdin", "-loglevel", "error", "-protocol_whitelist", "file,pipe", "-i", source, "-an", "-sn", "-dn", "-vf", `fps=${RATE},scale=${W}:${H},format=gray`, "-f", "rawvideo", "pipe:1"]
|
|
12
|
+
|
|
13
|
+
// Variance of the Laplacian: low when nothing has edges
|
|
14
|
+
function sharpness(f) {
|
|
15
|
+
let sum = 0
|
|
16
|
+
let squares = 0
|
|
17
|
+
let n = 0
|
|
18
|
+
for (let y = 1; y < H - 1; y++) {
|
|
19
|
+
for (let x = 1; x < W - 1; x++) {
|
|
20
|
+
const i = y * W + x
|
|
21
|
+
const v = 4 * f[i] - f[i - 1] - f[i + 1] - f[i - W] - f[i + W]
|
|
22
|
+
sum += v
|
|
23
|
+
squares += v * v
|
|
24
|
+
n++
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return squares / n - (sum / n) ** 2
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function half(f) {
|
|
31
|
+
const w = W / 2
|
|
32
|
+
const h = H / 2
|
|
33
|
+
const out = new Float32Array(w * h)
|
|
34
|
+
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) out[y * w + x] = (f[2 * y * W + 2 * x] + f[2 * y * W + 2 * x + 1] + f[(2 * y + 1) * W + 2 * x] + f[(2 * y + 1) * W + 2 * x + 1]) / 4
|
|
35
|
+
return out
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const CAMERA = 0.7 // shortcut: judged on synthetic charts; tune on real handheld footage
|
|
39
|
+
|
|
40
|
+
function shiftCost(a, b, w, h, dx, dy) {
|
|
41
|
+
let cost = 0
|
|
42
|
+
let n = 0
|
|
43
|
+
for (let y = SEARCH; y < h - SEARCH; y++) {
|
|
44
|
+
for (let x = SEARCH; x < w - SEARCH; x++) {
|
|
45
|
+
cost += Math.abs(a[y * w + x] - b[(y + dy) * w + x + dx])
|
|
46
|
+
n++
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return cost / n
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The whole-frame shift between two frames that matches best, by mean absolute difference. */
|
|
53
|
+
export function globalShift(a, b, w = W / 2, h = H / 2) {
|
|
54
|
+
const tried = []
|
|
55
|
+
for (let dy = -SEARCH; dy <= SEARCH; dy++) for (let dx = -SEARCH; dx <= SEARCH; dx++) tried.push({ dx, dy, cost: shiftCost(a, b, w, h, dx, dy) })
|
|
56
|
+
const lowest = Math.min(...tried.map((t) => t.cost))
|
|
57
|
+
// Near-ties go to the smallest shift: a chart with no vertical detail can't say how it moved vertically
|
|
58
|
+
const best = tried.filter((t) => t.cost <= lowest * 1.05 + 0.05).sort((p, q) => Math.hypot(p.dx, p.dy) - Math.hypot(q.dx, q.dy))[0]
|
|
59
|
+
// Objects moving in a still frame barely help any shift; a moving camera helps a lot
|
|
60
|
+
const still = shiftCost(a, b, w, h, 0, 0)
|
|
61
|
+
return best.cost < still * CAMERA ? best : { dx: 0, dy: 0, cost: still }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Collects frames from FFmpeg's stdout. @returns {{ add: (chunk: Buffer) => void, finish: () => object[] }} */
|
|
65
|
+
export function qualityCollector() {
|
|
66
|
+
const size = W * H
|
|
67
|
+
const samples = []
|
|
68
|
+
let carry = Buffer.alloc(0)
|
|
69
|
+
let previous = null
|
|
70
|
+
const take = (frame) => {
|
|
71
|
+
const small = half(frame)
|
|
72
|
+
let mean = 0
|
|
73
|
+
let clipped = 0
|
|
74
|
+
for (const v of frame) {
|
|
75
|
+
mean += v
|
|
76
|
+
if (v <= 16 || v >= 235) clipped++
|
|
77
|
+
}
|
|
78
|
+
const shift = previous ? globalShift(previous, small) : { dx: 0, dy: 0 }
|
|
79
|
+
samples.push({ t: samples.length * STEP, sharpness: sharpness(frame), luma: mean / size / 255, clipped: clipped / size, dx: shift.dx, dy: shift.dy })
|
|
80
|
+
previous = small
|
|
81
|
+
}
|
|
82
|
+
return {
|
|
83
|
+
add(chunk) {
|
|
84
|
+
carry = Buffer.concat([carry, chunk])
|
|
85
|
+
while (carry.length >= size) {
|
|
86
|
+
take(carry.subarray(0, size))
|
|
87
|
+
carry = carry.subarray(size)
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
finish: () => samples,
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const mean = (values) => (values.length ? values.reduce((sum, v) => sum + v, 0) / values.length : null)
|
|
95
|
+
const round = (value) => (value === null ? null : Math.round(value * 1000) / 1000)
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Per-shot scores, each 0 to 1. shortcut: blur and shake scales are uncalibrated
|
|
99
|
+
* (synthetic charts only); tune on real footage before a gate depends on them.
|
|
100
|
+
*/
|
|
101
|
+
export function scoreShots(samples, shots) {
|
|
102
|
+
return shots.map((shot) => {
|
|
103
|
+
const own = samples.filter((s) => s.t >= shot.start && s.t < shot.end)
|
|
104
|
+
if (!own.length) return { blur: null, exposure: null, shake: null, motion: null }
|
|
105
|
+
// The first sample after a cut compares across it: not motion
|
|
106
|
+
const moves = own.slice(1).map((s) => Math.hypot(s.dx, s.dy))
|
|
107
|
+
// Shake is the jitter left after the steady part of the motion
|
|
108
|
+
const jitter = own.slice(2).map((s, i) => Math.hypot(s.dx - own[i + 1].dx, s.dy - own[i + 1].dy))
|
|
109
|
+
const sharp = mean(own.map((s) => s.sharpness))
|
|
110
|
+
const luma = mean(own.map((s) => s.luma))
|
|
111
|
+
const clipped = mean(own.map((s) => s.clipped))
|
|
112
|
+
return {
|
|
113
|
+
blur: round(1 / (1 + sharp / 100)),
|
|
114
|
+
// 0 is well exposed; 1 is black, white or clipped throughout
|
|
115
|
+
exposure: round(Math.min(1, Math.abs(luma - 0.45) / 0.45 + clipped)),
|
|
116
|
+
shake: moves.length > 1 ? round(Math.min(1, mean(jitter) / SEARCH)) : 0,
|
|
117
|
+
motion: moves.length ? round(Math.min(1, mean(moves) / SEARCH)) : 0,
|
|
118
|
+
}
|
|
119
|
+
})
|
|
120
|
+
}
|