@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,473 @@
|
|
|
1
|
+
// The Engine (ARCHITECTURE §2): the graph's node implementations for one project.
|
|
2
|
+
// Every expensive thing is a node, cached by what produced it. Sources are read,
|
|
3
|
+
// never written; everything goes to the cache or exports/.
|
|
4
|
+
|
|
5
|
+
import { copyFileSync, existsSync, mkdirSync, readdirSync, realpathSync, renameSync, rmSync, statfsSync, statSync, writeFileSync } from "node:fs"
|
|
6
|
+
import { dirname, extname, isAbsolute, join, sep } from "node:path"
|
|
7
|
+
|
|
8
|
+
import { BUSES, busOf, duckEnvelope, MUSIC_UNDER_VOICE, SFX_UNDER_VOICE } from "../core/audio.js"
|
|
9
|
+
import { animatedZoom, audioArgs, joinArgs, muxArgs, peakArgs, proxyArgs, segmentArgs, stemsMixArgs, thumbArgs } from "../core/ffmpeg.js"
|
|
10
|
+
import { compile, wholeSegment } from "../core/plan.js"
|
|
11
|
+
import { toneMapCube } from "../core/tonemap.js"
|
|
12
|
+
import { createGraph, hashOf } from "../graph/index.js"
|
|
13
|
+
import { activeRuntime } from "../runtime/setup.js"
|
|
14
|
+
import { captionComposition } from "./captions.js"
|
|
15
|
+
import { cubeText, matchCube, measureColour } from "./color.js"
|
|
16
|
+
import { encoderFor } from "./capabilities.js"
|
|
17
|
+
import { masterFilter, measureLoudness } from "./loudness.js"
|
|
18
|
+
import { fingerprint, peakCollector } from "./media.js"
|
|
19
|
+
import { compositionFor, motionRuntime, renderTile, tileSeconds } from "./motion.js"
|
|
20
|
+
import { packsForPlan, packStatus, requirePack } from "./packs.js"
|
|
21
|
+
import { EngineFailure, runTool } from "./tool.js"
|
|
22
|
+
|
|
23
|
+
export const ENGINE_VERSION = "ed8-1"
|
|
24
|
+
const LOUDNESS_TOLERANCE = 0.3 // LU the master step aims inside; QG-06 allows 0.5
|
|
25
|
+
|
|
26
|
+
const FLICKS = 705_600_000
|
|
27
|
+
const GB = 1e9
|
|
28
|
+
// What a render made and can make again
|
|
29
|
+
const PRUNABLE = new Set(["out", "master", "segments", "tiles", "match", "audio"])
|
|
30
|
+
// Disk one second of output may take: a draft segment, its join and a master's encode
|
|
31
|
+
const BYTES_PER_SECOND = 3_000_000
|
|
32
|
+
const STALL_MS = 120_000
|
|
33
|
+
const timeoutFor = (flicks) => Math.max(180_000, Math.ceil(flicks / FLICKS) * 60_000)
|
|
34
|
+
|
|
35
|
+
const inside = (path, root) => path === root || path.startsWith(root.endsWith(sep) ? root : `${root}${sep}`)
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The one check every path goes through (ES-01): the real path, after symlinks,
|
|
39
|
+
* must sit inside a root. @returns {string} the real path
|
|
40
|
+
*/
|
|
41
|
+
export function guardPath(path, roots) {
|
|
42
|
+
let real
|
|
43
|
+
try {
|
|
44
|
+
real = realpathSync(path)
|
|
45
|
+
} catch {
|
|
46
|
+
throw new EngineFailure("input", "missing_file", "A source file is missing. It may have moved.")
|
|
47
|
+
}
|
|
48
|
+
if (!roots.some((root) => inside(real, realpathSync(root)))) throw new EngineFailure("input", "outside_project", "That file isn't in this project's folders.")
|
|
49
|
+
return real
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const defaultFree = (dir) => {
|
|
53
|
+
let at = dir
|
|
54
|
+
while (!existsSync(at)) at = dirname(at)
|
|
55
|
+
const { bavail, bsize } = statfsSync(at)
|
|
56
|
+
return Number(bavail) * Number(bsize)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Writes through a temporary name, so a cancelled or crashed step leaves no half file. */
|
|
60
|
+
async function produce(file, work) {
|
|
61
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
62
|
+
const ext = extname(file)
|
|
63
|
+
// Named per process: a killed Host's FFmpeg can run on, and must not share this file
|
|
64
|
+
const part = `${file.slice(0, -ext.length)}.${process.pid}.part${ext}`
|
|
65
|
+
try {
|
|
66
|
+
await work(part)
|
|
67
|
+
renameSync(part, file)
|
|
68
|
+
} catch (error) {
|
|
69
|
+
rmSync(part, { force: true })
|
|
70
|
+
throw error
|
|
71
|
+
}
|
|
72
|
+
return file
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// DATA_MODEL §5.2: idempotent steps retry at most once
|
|
76
|
+
async function onceMore(work) {
|
|
77
|
+
try {
|
|
78
|
+
return await work()
|
|
79
|
+
} catch (error) {
|
|
80
|
+
if (!(error instanceof EngineFailure) || error.kind !== "render" || error.reason === "timeout") throw error
|
|
81
|
+
return work()
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* @param {{ folder: string, roots: string[], cache: string, exports: string, journal: object, toolVersion: string, capabilities: { filters: Set<string>, encoders: Set<string> }, scheduler?: object, free?: (dir: string) => number, run?: typeof runTool, onTool?: (command: string, args: string[]) => void, motion?: () => ReturnType<typeof motionRuntime> }} options
|
|
87
|
+
* motion: HyperFrames and Chrome for the motion layer, from the Media Runtime
|
|
88
|
+
* cacheBytes: the cache's cap (ES-17); KRIYA_EDIT_CACHE_BYTES, else 20 GB
|
|
89
|
+
*/
|
|
90
|
+
export function createEngine({ folder, roots, cache, exports: exportsDir, journal, toolVersion, capabilities, scheduler, free = defaultFree, run, onTool, motion = () => motionRuntime(activeRuntime()), cacheBytes = Number(process.env.KRIYA_EDIT_CACHE_BYTES) || 20 * GB }) {
|
|
91
|
+
const tool = (command, args, options) => {
|
|
92
|
+
onTool?.(command, args)
|
|
93
|
+
return (run ?? runTool)(command, args, options)
|
|
94
|
+
}
|
|
95
|
+
let project = null
|
|
96
|
+
let index = {}
|
|
97
|
+
|
|
98
|
+
const assetOf = (id) => project.assets.find((asset) => asset.id === id)
|
|
99
|
+
const sourcePath = (asset) => guardPath(isAbsolute(asset.path) ? asset.path : join(folder, asset.path), roots)
|
|
100
|
+
const durationOf = (asset) => asset.facts.duration ?? 0
|
|
101
|
+
const cached = (kind, name) => join(cache, kind, name)
|
|
102
|
+
const exists = (value) => existsSync(value.file)
|
|
103
|
+
|
|
104
|
+
function checkOutput(file) {
|
|
105
|
+
for (const asset of project.assets) {
|
|
106
|
+
const source = isAbsolute(asset.path) ? asset.path : join(folder, asset.path)
|
|
107
|
+
if (file === source) throw new EngineFailure("plan", "would_overwrite_source", "A render can't write over a source file.")
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function toneMap(transfer) {
|
|
112
|
+
const file = cached("lut", `${transfer}.cube`)
|
|
113
|
+
if (!existsSync(file)) {
|
|
114
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
115
|
+
writeFileSync(file, toneMapCube(transfer))
|
|
116
|
+
}
|
|
117
|
+
return file
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const timed = (flicks, signal) => ({ timeoutMs: timeoutFor(flicks), stallMs: STALL_MS, signal })
|
|
121
|
+
|
|
122
|
+
// Paths for one node's inputs: proxies for a draft, sources for a master
|
|
123
|
+
async function inputsFor(ids, useProxy, need) {
|
|
124
|
+
const paths = new Map()
|
|
125
|
+
for (const id of new Set(ids)) {
|
|
126
|
+
const asset = assetOf(id)
|
|
127
|
+
// Only pictures have proxies: a sound file is read as it is, even for a draft (found in ED9)
|
|
128
|
+
paths.set(id, useProxy && asset.kind === "video" ? (await need("proxy", id)).file : sourcePath(asset))
|
|
129
|
+
}
|
|
130
|
+
return paths
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// A node's inputs: footage, LUT files, and the baked .cube of each colour match
|
|
134
|
+
async function pathsFor(node, useProxy, need) {
|
|
135
|
+
const effects = node.picture.flatMap((item) => item.effects)
|
|
136
|
+
const luts = effects.filter((effect) => effect.type === "lut").map((effect) => effect.asset)
|
|
137
|
+
const paths = await inputsFor([...node.picture, ...node.overlays].map((item) => item.asset).concat(luts), useProxy, need)
|
|
138
|
+
for (const key of new Set(effects.filter((effect) => effect.type === "grade" && effect.match).map((effect) => effect.match.key))) paths.set(key, (await need("match", key)).file)
|
|
139
|
+
return paths
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const nodes = {
|
|
143
|
+
// A colour match baked into a .cube (EDITOR_WORKFLOWS §6): both ranges measured from their sources
|
|
144
|
+
match: {
|
|
145
|
+
version: 1,
|
|
146
|
+
resources: ["cpu"],
|
|
147
|
+
valid: exists,
|
|
148
|
+
async run({ input, key, signal }) {
|
|
149
|
+
const { from, to } = await input(`match:${key}`)
|
|
150
|
+
const measure = (range) => measureColour(sourcePath(assetOf(range.asset)), { from: range.in / FLICKS, to: range.out / FLICKS, run: tool, signal })
|
|
151
|
+
const lut = matchCube(await measure(from), await measure(to))
|
|
152
|
+
const file = cached("match", `${key}.cube`)
|
|
153
|
+
await produce(file, async (output) => writeFileSync(output, cubeText(lut)))
|
|
154
|
+
return { file }
|
|
155
|
+
},
|
|
156
|
+
},
|
|
157
|
+
proxy: {
|
|
158
|
+
version: 1,
|
|
159
|
+
resources: ["encoder"],
|
|
160
|
+
valid: exists,
|
|
161
|
+
async run({ input, key, signal }) {
|
|
162
|
+
const { fingerprint: id, duration, color } = await input(`asset:${key}`)
|
|
163
|
+
const file = cached("proxy", `${id}.mp4`)
|
|
164
|
+
const source = sourcePath(assetOf(key))
|
|
165
|
+
await onceMore(() => produce(file, (output) => tool("ffmpeg", proxyArgs({ source, output, encoder: encoderFor(capabilities, "proxy"), color, toneMap }), timed(duration, signal))))
|
|
166
|
+
return { file }
|
|
167
|
+
},
|
|
168
|
+
},
|
|
169
|
+
peaks: {
|
|
170
|
+
version: 1,
|
|
171
|
+
resources: ["cpu"],
|
|
172
|
+
valid: exists,
|
|
173
|
+
async run({ input, key, signal }) {
|
|
174
|
+
const { fingerprint: id, duration } = await input(`asset:${key}`)
|
|
175
|
+
const file = cached("peaks", `${id}.json`)
|
|
176
|
+
const source = sourcePath(assetOf(key))
|
|
177
|
+
await produce(file, async (output) => {
|
|
178
|
+
const peaks = peakCollector()
|
|
179
|
+
await tool("ffmpeg", peakArgs({ source, rate: peaks.rate }), { ...timed(duration, signal), onStdout: (chunk) => peaks.add(chunk) })
|
|
180
|
+
writeFileSync(output, JSON.stringify(peaks.finish()))
|
|
181
|
+
})
|
|
182
|
+
return { file }
|
|
183
|
+
},
|
|
184
|
+
},
|
|
185
|
+
thumbs: {
|
|
186
|
+
version: 1,
|
|
187
|
+
resources: ["cpu"],
|
|
188
|
+
valid: exists,
|
|
189
|
+
async run({ input, key, signal }) {
|
|
190
|
+
const { fingerprint: id, duration } = await input(`asset:${key}`)
|
|
191
|
+
const file = cached("thumbs", `${id}.jpg`)
|
|
192
|
+
const source = sourcePath(assetOf(key))
|
|
193
|
+
const every = Math.max(1, Math.ceil(duration / FLICKS / 100))
|
|
194
|
+
await produce(file, (output) => tool("ffmpeg", thumbArgs({ source, output, every, columns: 10, rows: 10 }), timed(duration, signal)))
|
|
195
|
+
return { file }
|
|
196
|
+
},
|
|
197
|
+
},
|
|
198
|
+
// A caption or block as a transparent tile (EDIT_ENGINE §6): its own short composition, confined
|
|
199
|
+
tile: {
|
|
200
|
+
version: 1,
|
|
201
|
+
resources: ["chrome"],
|
|
202
|
+
valid: exists,
|
|
203
|
+
async run({ input, key, signal }) {
|
|
204
|
+
const { tile, output, canvas } = await input(`tile:${key}`)
|
|
205
|
+
const html = compositionFor(tile, { output, canvas }, captionComposition)
|
|
206
|
+
const file = cached("tiles", `${key}.mov`)
|
|
207
|
+
const work = cached("tiles", `${key}.work`)
|
|
208
|
+
try {
|
|
209
|
+
await produce(file, (out) => renderTile({ html, work, output: out, fps: output.fps, runtime: motion(), run: tool, signal, seconds: tileSeconds(tile.end - tile.at, output.fps) }))
|
|
210
|
+
} finally {
|
|
211
|
+
rmSync(work, { recursive: true, force: true })
|
|
212
|
+
}
|
|
213
|
+
return { file }
|
|
214
|
+
},
|
|
215
|
+
},
|
|
216
|
+
segment: {
|
|
217
|
+
version: 1,
|
|
218
|
+
resources: ["encoder"],
|
|
219
|
+
valid: exists,
|
|
220
|
+
async run({ input, need, key, signal }) {
|
|
221
|
+
const { plan, segment } = await input(`segment:${key}`)
|
|
222
|
+
const { node } = segment
|
|
223
|
+
const paths = await pathsFor(node, plan.input === "proxy", need)
|
|
224
|
+
const file = cached("segments", `${key}.mp4`)
|
|
225
|
+
await onceMore(() => produce(file, (output) => tool("ffmpeg", segmentArgs(plan, segment, { input: (id) => paths.get(id), tile: (id) => cached("tiles", `${id}.mov`), output, encoder: encoderFor(capabilities, "draft"), toneMap }), timed(segment.end - segment.start, signal))))
|
|
226
|
+
return { file }
|
|
227
|
+
},
|
|
228
|
+
},
|
|
229
|
+
// The sound as stems, then one mix (EDIT_ENGINE §10, ED9): the dialogue first, since
|
|
230
|
+
// its measured loudness sets where music and effects sit; mastered when a deliverable asks
|
|
231
|
+
audio: {
|
|
232
|
+
version: 2,
|
|
233
|
+
resources: ["cpu"],
|
|
234
|
+
// The stems too: the gates read them, and the cache may prune one alone (ES-17)
|
|
235
|
+
valid: (value) => existsSync(value.file) && Object.values(value.stems ?? {}).every((stem) => existsSync(stem)),
|
|
236
|
+
async run({ input, need, key, signal }) {
|
|
237
|
+
const plan = await input(`audio:${key}`)
|
|
238
|
+
const paths = await inputsFor(plan.audio.items.map((item) => item.asset), plan.input === "proxy", need)
|
|
239
|
+
const io = { input: (id) => paths.get(id) }
|
|
240
|
+
const file = cached("audio", `${key}.m4a`)
|
|
241
|
+
const pcm = ["-c:a", "pcm_s24le", "-ar", "48000"]
|
|
242
|
+
const encoder = ["-c:a", "aac", "-b:a", "192k", "-ar", "48000"]
|
|
243
|
+
const buses = BUSES.filter((bus) => plan.audio.items.some((item) => busOf(item.role) === bus))
|
|
244
|
+
const stem = (bus) => cached("audio", `${key}.${bus}.wav`)
|
|
245
|
+
const time = timed(plan.duration, signal)
|
|
246
|
+
let envelope
|
|
247
|
+
if (plan.audio.duck && buses.includes("music")) {
|
|
248
|
+
envelope = cached("audio", `${key}.duck.f32`)
|
|
249
|
+
mkdirSync(dirname(envelope), { recursive: true })
|
|
250
|
+
const curve = duckEnvelope(plan.audio.duck.speech, { duration: plan.duration, ...plan.audio.duck })
|
|
251
|
+
writeFileSync(envelope, Buffer.from(curve.buffer, curve.byteOffset, curve.byteLength))
|
|
252
|
+
}
|
|
253
|
+
const render = (bus, gains) => onceMore(() => produce(stem(bus), (output) => tool("ffmpeg", audioArgs(plan, { ...io, output, encoder: pcm, bus, envelope, gains }), time)))
|
|
254
|
+
if (buses.includes("dialogue")) await render("dialogue")
|
|
255
|
+
const voice = buses.includes("dialogue") ? (await measureLoudness(stem("dialogue"), { run: tool, signal })).integrated : null
|
|
256
|
+
// Music and effects levelled against this voice, unless the person set a level
|
|
257
|
+
const gains = {}
|
|
258
|
+
for (const item of plan.audio.items) {
|
|
259
|
+
const under = busOf(item.role) === "music" ? MUSIC_UNDER_VOICE : busOf(item.role) === "sfx" ? SFX_UNDER_VOICE : null
|
|
260
|
+
if (under === null || voice === null || item.asset in gains || item.effects.some((e) => e.type === "level")) continue
|
|
261
|
+
const own = (await measureLoudness(paths.get(item.asset), { run: tool, signal })).integrated
|
|
262
|
+
if (own !== null) gains[item.asset] = Math.max(-40, Math.min(20, voice - under - own))
|
|
263
|
+
}
|
|
264
|
+
for (const bus of buses) if (bus !== "dialogue") await render(bus, gains)
|
|
265
|
+
const stems = buses.map(stem)
|
|
266
|
+
if (!plan.audio.loudness) {
|
|
267
|
+
await onceMore(() => produce(file, (output) => tool("ffmpeg", stems.length ? stemsMixArgs({ stems, duration: plan.duration, output, encoder }) : audioArgs(plan, { ...io, output, encoder }), time)))
|
|
268
|
+
return { file, stems: Object.fromEntries(buses.map((bus) => [bus, stem(bus)])), voice }
|
|
269
|
+
}
|
|
270
|
+
// Mastered to the deliverable: mix losslessly, measure, gain and limit, measure again
|
|
271
|
+
const mix = cached("audio", `${key}.mix.wav`)
|
|
272
|
+
await onceMore(() => produce(mix, (output) => tool("ffmpeg", stems.length ? stemsMixArgs({ stems, duration: plan.duration, output, encoder: pcm }) : audioArgs(plan, { ...io, output, encoder: pcm }), time)))
|
|
273
|
+
const { lufs, tp } = plan.audio.loudness
|
|
274
|
+
const first = await measureLoudness(mix, { run: tool, signal })
|
|
275
|
+
let gain = first.integrated === null ? 0 : lufs - first.integrated
|
|
276
|
+
let margin = 1.5
|
|
277
|
+
for (let pass = 0; pass < 4; pass++) {
|
|
278
|
+
await produce(file, (output) => tool("ffmpeg", ["-nostdin", "-hide_banner", "-i", mix, "-af", masterFilter({ gain, ceiling: tp, margin }), ...encoder, "-y", output], time))
|
|
279
|
+
const now = await measureLoudness(file, { run: tool, signal })
|
|
280
|
+
const loud = first.integrated === null || now.integrated === null || Math.abs(now.integrated - lufs) <= LOUDNESS_TOLERANCE
|
|
281
|
+
// A transient the encoder pushes past the ceiling: limit lower and go again (found in ED9)
|
|
282
|
+
const peak = now.truePeak === null || now.truePeak <= tp - 0.1
|
|
283
|
+
if (loud && peak) break
|
|
284
|
+
if (!loud) gain += lufs - now.integrated
|
|
285
|
+
if (!peak) margin += now.truePeak - tp + 0.3
|
|
286
|
+
}
|
|
287
|
+
rmSync(mix, { force: true })
|
|
288
|
+
return { file, stems: Object.fromEntries(buses.map((bus) => [bus, stem(bus)])), voice }
|
|
289
|
+
},
|
|
290
|
+
},
|
|
291
|
+
join: {
|
|
292
|
+
version: 1,
|
|
293
|
+
valid: exists,
|
|
294
|
+
async run({ input, need, key, signal }) {
|
|
295
|
+
const { segments, audio } = await input(`join:${key}`)
|
|
296
|
+
const [parts, sound] = await Promise.all([Promise.all(segments.map((id) => need("segment", id))), need("audio", audio)])
|
|
297
|
+
const list = cached("segments", `${key}.ffconcat`)
|
|
298
|
+
// Our own list, of our own hex names beside it: nothing here comes from a person
|
|
299
|
+
writeFileSync(list, `ffconcat version 1.0\n${parts.map(({ file }) => `file '${file.slice(file.lastIndexOf(sep) + 1)}'`).join("\n")}\n`)
|
|
300
|
+
const file = cached("out", `${key}.mp4`)
|
|
301
|
+
await produce(file, (output) => tool("ffmpeg", joinArgs({ list, audio: sound.file, output }), { timeoutMs: 600_000, signal }))
|
|
302
|
+
return { file }
|
|
303
|
+
},
|
|
304
|
+
},
|
|
305
|
+
master: {
|
|
306
|
+
version: 1,
|
|
307
|
+
resources: ["encoder"],
|
|
308
|
+
valid: exists,
|
|
309
|
+
async run({ input, need, key, signal }) {
|
|
310
|
+
const { plan, audio } = await input(`master:${key}`)
|
|
311
|
+
const sound = await need("audio", audio)
|
|
312
|
+
const segment = wholeSegment(plan)
|
|
313
|
+
// LUTs too: a master with apply_lut once got no path for its .cube (found in ED13)
|
|
314
|
+
const paths = await pathsFor(segment.node, false, need)
|
|
315
|
+
const picture = cached("master", `${key}.mp4`)
|
|
316
|
+
await produce(picture, (output) => tool("ffmpeg", segmentArgs(plan, segment, { input: (id) => paths.get(id), tile: (id) => cached("tiles", `${id}.mov`), output, encoder: encoderFor(capabilities, "master"), toneMap }), timed(plan.duration * 4, signal)))
|
|
317
|
+
const file = cached("out", `${key}.mp4`)
|
|
318
|
+
await produce(file, (output) => tool("ffmpeg", muxArgs({ video: picture, audio: sound.file, output }), { timeoutMs: 600_000, signal }))
|
|
319
|
+
rmSync(picture, { force: true })
|
|
320
|
+
return { file }
|
|
321
|
+
},
|
|
322
|
+
},
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const graph = createGraph({ journal, nodes, ...(scheduler ? { scheduler } : {}) })
|
|
326
|
+
|
|
327
|
+
// What a crash left half written; nothing finished has this name
|
|
328
|
+
for (const kind of existsSync(cache) ? readdirSync(cache) : []) {
|
|
329
|
+
const dir = join(cache, kind)
|
|
330
|
+
if (!statSync(dir).isDirectory()) continue
|
|
331
|
+
for (const name of readdirSync(dir)) if (/\.part\.\w+$/.test(name)) rmSync(join(dir, name), { force: true })
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// ES-17: after a render the cache is cut to its cap, oldest renders first, never what
|
|
335
|
+
// that render used (its audio stems included: the gates read them next). Per-source
|
|
336
|
+
// proxies, peaks and thumbnails stay. A pruned file is only
|
|
337
|
+
// made again: every node checks its file exists, and touch() makes the graph look again.
|
|
338
|
+
// Oldest made goes first; a reused file isn't touched (a finished step's file keeps its time).
|
|
339
|
+
// Only when no other render of this project is running, so none loses a file mid-join.
|
|
340
|
+
// The cap is per project: each has its own cache.
|
|
341
|
+
// shortcut: a make job's gates still reading its tiles after its render could lose them to
|
|
342
|
+
// another render's prune when over the cap; upgrade to a lease on the files if that's seen
|
|
343
|
+
let rendering = 0
|
|
344
|
+
function prune(keep, audioOf) {
|
|
345
|
+
const files = []
|
|
346
|
+
let total = 0
|
|
347
|
+
for (const kind of existsSync(cache) ? readdirSync(cache) : []) {
|
|
348
|
+
const dir = join(cache, kind)
|
|
349
|
+
if (!statSync(dir).isDirectory()) continue
|
|
350
|
+
for (const name of readdirSync(dir)) {
|
|
351
|
+
const path = join(dir, name)
|
|
352
|
+
const stat = statSync(path, { throwIfNoEntry: false })
|
|
353
|
+
if (!stat?.isFile()) continue
|
|
354
|
+
total += stat.size
|
|
355
|
+
if (PRUNABLE.has(kind) && !keep.has(path) && !path.startsWith(audioOf)) files.push({ path, size: stat.size, at: stat.mtimeMs })
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
if (total <= cacheBytes) return
|
|
359
|
+
for (const file of files.sort((a, b) => a.at - b.at)) {
|
|
360
|
+
rmSync(file.path, { force: true })
|
|
361
|
+
total -= file.size
|
|
362
|
+
if (total <= cacheBytes) break
|
|
363
|
+
}
|
|
364
|
+
graph.touch()
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function setAsset(asset) {
|
|
368
|
+
graph.set(`asset:${asset.id}`, { fingerprint: asset.fingerprint, duration: durationOf(asset), color: asset.facts.color ?? null })
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function preflight(plan) {
|
|
372
|
+
const used = new Set(plan.segments.flatMap((s) => [...s.node.picture, ...s.node.overlays].map((item) => item.asset)).concat(plan.audio.items.map((item) => item.asset)))
|
|
373
|
+
for (const id of used) sourcePath(assetOf(id))
|
|
374
|
+
for (const tile of plan.tiles) {
|
|
375
|
+
if (tile.kind === "caption" && tile.node.style?.burn === true) {
|
|
376
|
+
if (!capabilities.filters.has("drawtext")) throw new EngineFailure("environment", "missing_feature", "This FFmpeg has no drawtext filter, so captions can't be burned in directly.")
|
|
377
|
+
} else if (!existsSync(cached("tiles", `${tile.key}.mov`))) {
|
|
378
|
+
const runtime = motion()
|
|
379
|
+
if (runtime.missing) throw new EngineFailure("environment", "missing_feature", runtime.missing)
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
// A pack the plan needs, checked before anything renders (CAPABILITY_PACKS §3); the colour pack needs only FFmpeg
|
|
383
|
+
const packs = packsForPlan(plan)
|
|
384
|
+
if (packs.length) {
|
|
385
|
+
const status = packStatus({ runtime: null, capabilities })
|
|
386
|
+
for (const id of packs) requirePack(id, status)
|
|
387
|
+
}
|
|
388
|
+
if (plan.segments.some((s) => s.node.picture.some((item) => animatedZoom(item.zoom))) && !capabilities.filters.has("zoompan")) throw new EngineFailure("environment", "missing_feature", "This FFmpeg has no zoompan filter, so focused or smooth zooms can't be drawn.")
|
|
389
|
+
const seconds = plan.duration / FLICKS
|
|
390
|
+
const proxies = plan.input === "proxy" ? [...used].reduce((sum, id) => sum + (durationOf(assetOf(id)) / FLICKS) * 200_000, 0) : 0
|
|
391
|
+
const needed = seconds * BYTES_PER_SECOND + proxies
|
|
392
|
+
const available = free(cache)
|
|
393
|
+
if (available < needed) throw new EngineFailure("environment", "low_disk", `This render needs about ${(needed / GB).toFixed(1)} GB free, and there are ${(available / GB).toFixed(1)} GB free. Nothing was written.`)
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
const unsupported = (error) => (error instanceof RangeError ? new EngineFailure("plan", "unsupported", error.message) : error)
|
|
397
|
+
|
|
398
|
+
return {
|
|
399
|
+
graph,
|
|
400
|
+
checkOutput,
|
|
401
|
+
|
|
402
|
+
/** The project and index everything below works from. */
|
|
403
|
+
load(nextProject, nextIndex = {}) {
|
|
404
|
+
project = nextProject
|
|
405
|
+
index = nextIndex
|
|
406
|
+
for (const asset of project.assets) if (asset.kind === "video" || asset.kind === "audio") setAsset(asset)
|
|
407
|
+
},
|
|
408
|
+
|
|
409
|
+
fingerprint: (path) => fingerprint(path),
|
|
410
|
+
/** The stems of a rendered mix, by bus, and the voice's measured loudness (QG-06). */
|
|
411
|
+
stems: async (audioKey) => {
|
|
412
|
+
const value = await graph.demand("audio", audioKey)
|
|
413
|
+
return { stems: value.stems ?? {}, voice: value.voice ?? null }
|
|
414
|
+
},
|
|
415
|
+
/** Where a rendered tile lives, for the gates that read it. */
|
|
416
|
+
tilePath: (key) => cached("tiles", `${key}.mov`),
|
|
417
|
+
motion,
|
|
418
|
+
proxy: async (id, options) => (await graph.demand("proxy", id, options)).file,
|
|
419
|
+
peaks: async (id, options) => (await graph.demand("peaks", id, options)).file,
|
|
420
|
+
thumbs: async (id, options) => (await graph.demand("thumbs", id, options)).file,
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* @param {{ quality: "draft" | "master", deliverable?: string, job?: number, signal?: AbortSignal, onStep?: (done: number, total: number) => void, project?: object }} request
|
|
424
|
+
* @returns {Promise<{ file: string, plan: object }>}
|
|
425
|
+
*/
|
|
426
|
+
async render({ quality, deliverable, job, signal, onStep = () => {}, project: candidate }) {
|
|
427
|
+
// A candidate version (the Edit Loop's attempt) renders without becoming the project
|
|
428
|
+
const plan = compile(candidate ?? project, index, { engineVersion: ENGINE_VERSION, runtimeVersion: toolVersion, quality, deliverable })
|
|
429
|
+
if (!plan.duration) throw new EngineFailure("plan", "empty", "There's nothing on the timeline to render.")
|
|
430
|
+
preflight(plan)
|
|
431
|
+
const shared = { canvas: plan.canvas, output: plan.output, input: plan.input, tiles: plan.tiles }
|
|
432
|
+
const audio = { audio: plan.audio, duration: plan.duration, input: plan.input }
|
|
433
|
+
graph.set(`audio:${plan.audio.key}`, audio)
|
|
434
|
+
const options = { job, signal }
|
|
435
|
+
const key = hashOf([plan.segments.map((s) => s.key), plan.audio.key, plan.input])
|
|
436
|
+
let done = 0
|
|
437
|
+
const step = (total) => onStep(++done, total)
|
|
438
|
+
rendering++
|
|
439
|
+
try {
|
|
440
|
+
// Tiles first, one Chrome at a time (the scheduler's `chrome` slot); cached by content
|
|
441
|
+
const drawn = plan.tiles.filter((tile) => !(tile.kind === "caption" && tile.node.style?.burn === true))
|
|
442
|
+
for (const tile of drawn) graph.set(`tile:${tile.key}`, { tile, output: plan.output, canvas: plan.canvas })
|
|
443
|
+
for (const segment of plan.segments) for (const item of segment.node.picture) for (const effect of item.effects) if (effect.type === "grade" && effect.match) graph.set(`match:${effect.match.key}`, { from: effect.match.from, to: effect.match.to })
|
|
444
|
+
await Promise.all(drawn.map((tile) => graph.demand("tile", tile.key, options)))
|
|
445
|
+
let value
|
|
446
|
+
if (quality === "master") {
|
|
447
|
+
graph.set(`master:${key}`, { plan, audio: plan.audio.key })
|
|
448
|
+
value = await graph.demand("master", key, options)
|
|
449
|
+
step(1)
|
|
450
|
+
} else {
|
|
451
|
+
const total = plan.segments.length + 1
|
|
452
|
+
for (const segment of plan.segments) graph.set(`segment:${segment.key}`, { plan: shared, segment })
|
|
453
|
+
graph.set(`join:${key}`, { segments: plan.segments.map((s) => s.key), audio: plan.audio.key })
|
|
454
|
+
// Demanded here, not only by the join, so progress can be seen and slots shared
|
|
455
|
+
await Promise.all(plan.segments.map((segment) => graph.demand("segment", segment.key, options).then(() => step(total))))
|
|
456
|
+
value = await graph.demand("join", key, options)
|
|
457
|
+
step(total)
|
|
458
|
+
}
|
|
459
|
+
const name = `${project.name.replace(/[^\p{L}\p{N}_-]+/gu, "-")}-${quality}-${key.slice(0, 8)}.mp4`
|
|
460
|
+
const file = join(exportsDir, name)
|
|
461
|
+
checkOutput(file)
|
|
462
|
+
mkdirSync(exportsDir, { recursive: true })
|
|
463
|
+
copyFileSync(value.file, file)
|
|
464
|
+
if (rendering === 1) prune(new Set([value.file, ...plan.segments.map((s) => cached("segments", `${s.key}.mp4`)), ...plan.tiles.map((t) => cached("tiles", `${t.key}.mov`))]), cached("audio", `${plan.audio.key}.`))
|
|
465
|
+
return { file, plan }
|
|
466
|
+
} catch (error) {
|
|
467
|
+
throw unsupported(error)
|
|
468
|
+
} finally {
|
|
469
|
+
rendering--
|
|
470
|
+
}
|
|
471
|
+
},
|
|
472
|
+
}
|
|
473
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// Loudness by EBU R128 / ITU-R BS.1770, measured by FFmpeg's ebur128 on a file:
|
|
2
|
+
// integrated loudness and true peak. The master step and QG-06 use the same reading.
|
|
3
|
+
|
|
4
|
+
import { runTool } from "./tool.js"
|
|
5
|
+
|
|
6
|
+
const value = (text, key) => {
|
|
7
|
+
let last = null
|
|
8
|
+
let top = null
|
|
9
|
+
for (const line of text.split("\n")) {
|
|
10
|
+
if (line.startsWith(`${key}=`)) {
|
|
11
|
+
const n = Number(line.slice(key.length + 1))
|
|
12
|
+
if (Number.isFinite(n)) {
|
|
13
|
+
last = n
|
|
14
|
+
top = top === null ? n : Math.max(top, n)
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
return { last, top }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export const loudnessArgs = (file) => ["-hide_banner", "-nostdin", "-loglevel", "error", "-protocol_whitelist", "file,pipe", "-i", file, "-vn", "-af", "ebur128=metadata=1:peak=true,ametadata=mode=print:file=-", "-f", "null", "-"]
|
|
22
|
+
|
|
23
|
+
/** @returns {{ integrated: number | null, truePeak: number | null }} LUFS and dBTP; null when silent */
|
|
24
|
+
export function readLoudness(text) {
|
|
25
|
+
const integrated = value(text, "lavfi.r128.I").last
|
|
26
|
+
const peak = value(text, "lavfi.r128.true_peak").top
|
|
27
|
+
return { integrated: integrated !== null && integrated > -70 ? integrated : null, truePeak: peak !== null && peak > 0 ? 20 * Math.log10(peak) : null }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function measureLoudness(file, { run = runTool, signal } = {}) {
|
|
31
|
+
return readLoudness(await run("ffmpeg", loudnessArgs(file), { signal, timeoutMs: 600_000 }))
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The master step's filter: a gain, and a limiter a margin under the true-peak ceiling,
|
|
36
|
+
* since the limiter sees samples and AAC adds a little. The Engine measures and corrects
|
|
37
|
+
* the gain, because limiting lowers loudness.
|
|
38
|
+
*/
|
|
39
|
+
export function masterFilter({ gain, ceiling, margin = 1.5 }) {
|
|
40
|
+
gain = Math.max(-40, Math.min(40, gain))
|
|
41
|
+
const limit = Math.min(1, Math.max(0.0625, 10 ** ((ceiling - margin) / 20)))
|
|
42
|
+
return `volume=${gain.toFixed(2)}dB,alimiter=limit=${limit.toFixed(4)}:level=false:attack=5:release=50`
|
|
43
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// Per-asset work: identity, peaks. Proxies and thumbnails are plain FFmpeg calls in
|
|
2
|
+
// the engine's nodes; peaks are read from a decoded stream as it passes.
|
|
3
|
+
|
|
4
|
+
import { createHash } from "node:crypto"
|
|
5
|
+
import { open, stat } from "node:fs/promises"
|
|
6
|
+
|
|
7
|
+
const SAMPLE = 1 << 20
|
|
8
|
+
const RATE = 8000
|
|
9
|
+
const LEVELS = [100, 10, 1]
|
|
10
|
+
|
|
11
|
+
/** Size, modified time and sha256 of sampled blocks: a 40 GB file isn't read in full (EDIT_ENGINE §7). */
|
|
12
|
+
export async function fingerprint(file) {
|
|
13
|
+
const { size, mtimeMs } = await stat(file)
|
|
14
|
+
const hash = createHash("sha256").update(`${size}:${mtimeMs}`)
|
|
15
|
+
const handle = await open(file)
|
|
16
|
+
try {
|
|
17
|
+
const block = Buffer.alloc(SAMPLE)
|
|
18
|
+
for (const position of [0, Math.max(0, Math.floor(size / 2) - SAMPLE / 2), Math.max(0, size - SAMPLE)]) {
|
|
19
|
+
const { bytesRead } = await handle.read(block, 0, SAMPLE, position)
|
|
20
|
+
hash.update(block.subarray(0, bytesRead))
|
|
21
|
+
}
|
|
22
|
+
} finally {
|
|
23
|
+
await handle.close()
|
|
24
|
+
}
|
|
25
|
+
return hash.digest("hex")
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Folds a stream of s16le samples into peak levels at each zoom. */
|
|
29
|
+
export function peakCollector() {
|
|
30
|
+
const step = RATE / LEVELS[0]
|
|
31
|
+
const fine = []
|
|
32
|
+
let count = 0
|
|
33
|
+
let top = 0
|
|
34
|
+
let carry = null
|
|
35
|
+
return {
|
|
36
|
+
rate: RATE,
|
|
37
|
+
add(chunk) {
|
|
38
|
+
const data = carry ? Buffer.concat([carry, chunk]) : chunk
|
|
39
|
+
const usable = data.length - (data.length % 2)
|
|
40
|
+
carry = usable < data.length ? data.subarray(usable) : null
|
|
41
|
+
for (let at = 0; at < usable; at += 2) {
|
|
42
|
+
top = Math.max(top, Math.abs(data.readInt16LE(at)))
|
|
43
|
+
if (++count === step) {
|
|
44
|
+
fine.push(top / 32768)
|
|
45
|
+
count = 0
|
|
46
|
+
top = 0
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
finish() {
|
|
51
|
+
if (count > step / 2) fine.push(top / 32768)
|
|
52
|
+
const fold = (factor) => Array.from({ length: Math.ceil(fine.length / factor) }, (_, i) => Math.max(...fine.slice(i * factor, (i + 1) * factor)))
|
|
53
|
+
const round = (peaks) => peaks.map((peak) => Math.round(peak * 1000) / 1000)
|
|
54
|
+
return { levels: LEVELS.map((perSecond) => ({ perSecond, peaks: round(fold(LEVELS[0] / perSecond)) })) }
|
|
55
|
+
},
|
|
56
|
+
}
|
|
57
|
+
}
|