@kriya-ai/harness 0.2.5 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/RELEASE_NOTES.md +121 -0
  2. package/SAFETY.md +181 -0
  3. package/THIRD_PARTY_NOTICES.md +113 -0
  4. package/bin/kriya.js +188 -2
  5. package/bundle/cordis.patch.yml +60 -5
  6. package/contract/SOURCE.md +3 -3
  7. package/contract/contract.json +498 -3
  8. package/contract/schemas/api.json +64 -0
  9. package/contract/schemas/auth_matrix.json +44 -0
  10. package/contract/schemas/component_states.json +33 -0
  11. package/contract/schemas/design_tokens.json +34 -0
  12. package/contract/schemas/scene_direction.json +82 -0
  13. package/contract/schemas/threat_model.json +44 -0
  14. package/package.json +2 -1
  15. package/plugins/changes/client.js +5 -3
  16. package/plugins/deploy/index.js +215 -0
  17. package/plugins/deploy/package.json +13 -0
  18. package/plugins/grounding/index.js +81 -0
  19. package/plugins/grounding/lookup.js +373 -0
  20. package/plugins/grounding/package.json +13 -0
  21. package/plugins/kriya-tools/index.js +2 -1
  22. package/plugins/loop/index.js +381 -10
  23. package/plugins/mcp/index.js +79 -0
  24. package/plugins/mcp/package.json +13 -0
  25. package/plugins/mirror/index.js +17 -0
  26. package/plugins/overview/client.js +5 -2
  27. package/plugins/preview/client.js +12 -6
  28. package/plugins/progress/client.js +7 -4
  29. package/plugins/repo/index.js +230 -0
  30. package/plugins/repo/package.json +13 -0
  31. package/plugins/repo/repo.js +348 -0
  32. package/plugins/runstrip/client.js +436 -0
  33. package/plugins/runstrip/index.js +312 -0
  34. package/plugins/runstrip/package.json +23 -0
  35. package/src/cartridges.js +133 -0
  36. package/src/contracts.js +130 -0
  37. package/src/critic.js +78 -0
  38. package/src/daemon.js +7 -1
  39. package/src/doctor.js +67 -0
  40. package/src/edit/core/effects.js +185 -0
  41. package/src/edit/core/ffmpeg.js +65 -6
  42. package/src/edit/core/layout.js +46 -1
  43. package/src/edit/core/ops.js +169 -2
  44. package/src/edit/core/plan.js +65 -9
  45. package/src/edit/core/project.d.ts +24 -0
  46. package/src/edit/core/project.js +64 -0
  47. package/src/edit/core/solver.js +34 -6
  48. package/src/edit/core/style-brief.js +211 -0
  49. package/src/edit/core/style-packs.js +57 -0
  50. package/src/edit/core/type-kit.js +173 -0
  51. package/src/edit/director/ask.js +37 -3
  52. package/src/edit/director/assembly.js +829 -0
  53. package/src/edit/director/continuity.js +9 -1
  54. package/src/edit/director/custom-motion.js +88 -0
  55. package/src/edit/director/graphics.js +44 -10
  56. package/src/edit/director/intent.js +125 -0
  57. package/src/edit/director/mentions.js +52 -0
  58. package/src/edit/director/plan.js +43 -11
  59. package/src/edit/director/revise.js +132 -9
  60. package/src/edit/director/viewer.js +136 -0
  61. package/src/edit/director/watch-fix.js +119 -0
  62. package/src/edit/engine/captions.js +110 -5
  63. package/src/edit/engine/confine.js +81 -4
  64. package/src/edit/engine/custom.js +243 -0
  65. package/src/edit/engine/dna2.js +893 -0
  66. package/src/edit/engine/fonts.js +218 -0
  67. package/src/edit/engine/graphics.js +271 -10
  68. package/src/edit/engine/index.js +14 -5
  69. package/src/edit/engine/motion.js +148 -13
  70. package/src/edit/engine/music-bed.js +59 -1
  71. package/src/edit/engine/packs.js +11 -0
  72. package/src/edit/engine/reference2.js +26 -0
  73. package/src/edit/engine/sfx.js +56 -1
  74. package/src/edit/engine/tool.js +21 -5
  75. package/src/edit/gates/assembly.js +194 -0
  76. package/src/edit/gates/copy.js +7 -4
  77. package/src/edit/gates/index.js +72 -7
  78. package/src/edit/gates/reference.js +115 -0
  79. package/src/edit/gates/tile.js +96 -0
  80. package/src/edit/host/client.js +8 -3
  81. package/src/edit/host/clips.js +33 -0
  82. package/src/edit/host/jobs.js +9 -3
  83. package/src/edit/host/layers.js +134 -0
  84. package/src/edit/host/main.js +10 -3
  85. package/src/edit/host/paths.js +21 -3
  86. package/src/edit/host/preview.js +108 -0
  87. package/src/edit/host/projects.js +443 -34
  88. package/src/edit/host/server.js +235 -20
  89. package/src/edit/host/tavi.js +77 -0
  90. package/src/edit/index/index.js +3 -2
  91. package/src/edit/loop/make.js +28 -3
  92. package/src/edit/recipes/assembly.js +352 -0
  93. package/src/edit/recipes/graphic-clips.js +4 -2
  94. package/src/edit/recipes/openings.js +36 -0
  95. package/src/edit/recipes/reel.js +104 -14
  96. package/src/edit/recipes/reference-look.js +29 -0
  97. package/src/edit/recipes/short-from-long.js +3 -3
  98. package/src/edit/recipes/sound.js +71 -0
  99. package/src/edit/runtime/cli.js +26 -5
  100. package/src/edit/runtime/fetch.js +4 -4
  101. package/src/edit/runtime/licences.js +7 -1
  102. package/src/explore.js +103 -0
  103. package/src/failure.js +1 -1
  104. package/src/gate-commands.js +114 -0
  105. package/src/gates/api.js +127 -0
  106. package/src/gates/commands.js +111 -0
  107. package/src/gates/detectors.js +370 -0
  108. package/src/gates/http.js +62 -0
  109. package/src/gates/index.js +196 -0
  110. package/src/gates/page.js +264 -0
  111. package/src/gates/sast.js +64 -0
  112. package/src/gates/stack.js +110 -0
  113. package/src/gates/tenant.js +162 -0
  114. package/src/gates/three.js +431 -0
  115. package/src/gates/ui.js +111 -0
  116. package/src/gateway-proxy.js +20 -2
  117. package/src/launch.js +39 -5
  118. package/src/loop.js +199 -7
  119. package/src/mcp.js +126 -0
  120. package/src/milestones.js +188 -0
  121. package/src/modes.js +67 -0
  122. package/src/orchestra.js +50 -0
  123. package/src/outcomes.js +88 -0
  124. package/src/profiles.js +5 -0
  125. package/src/receipts.js +238 -0
  126. package/src/release.js +356 -0
  127. package/src/runstrip.js +122 -0
  128. package/src/stack.js +120 -0
  129. package/src/verify.js +67 -20
  130. package/studio/dist/fonts/fraunces.woff2 +0 -0
  131. package/studio/dist/fonts/geist.woff2 +0 -0
  132. package/studio/dist/fonts/jetbrains-mono.woff2 +0 -0
  133. package/studio/dist/studio.css +449 -1
  134. package/studio/dist/studio.js +3 -3
@@ -0,0 +1,893 @@
1
+ // Edit DNA 2 (TP6, CRAFT_UPGRADE §4.1, EDD-65), behind editing.referenceIntent: a reference's
2
+ // method, measured on this computer by code and kept as numbers and fixed words only. Frames
3
+ // and samples are read through a pipe, measured and dropped; nothing of the reference's picture,
4
+ // sound or wording is kept, and checkDna2 proves it before anything stores a result. No model
5
+ // sees a reference (EDD-66 stays off).
6
+ // Heavier than dna.js, so it runs only as a job with progress and a cancel, over a bounded
7
+ // number of sampled frames, never inside a plan or a make (EH-73). A trait code can't read
8
+ // well says so (`read: "no"`, or a null number): "couldn't read", never a guess.
9
+ // Thresholds are spike TPX-03's, measured on references Kriya rendered itself (SPIKES.md §8).
10
+
11
+ import { analyseMusic, musicArgs, pcmCollector, RATE as PCM_RATE } from "../index/layers/music.js"
12
+ import { statsOf } from "./color.js"
13
+ import { paceOf } from "./dna.js"
14
+ import { loudnessArgs, readLoudness } from "./loudness.js"
15
+ import { probe } from "./probe.js"
16
+ import { runTool } from "./tool.js"
17
+
18
+ const FLICKS = 705_600_000
19
+ export const DNA2_VERSION = "dna-2"
20
+ // The bound on work (EH-73): a longer reference is sampled more thinly, never read longer
21
+ export const LIMITS = { motionFrames: 7200, motionFps: 15, detailFrames: 1200, detailFps: 4, colourFrames: 48, soundSeconds: 600, motionSide: 96, detailSide: 480 }
22
+ // Below this rate a gradual join has too few samples to tell its kind
23
+ const KIND_FPS = 10
24
+ export const JOIN_KINDS = ["cut", "fade", "dip", "flash", "wipe", "slide", "zoom"]
25
+ // Under this confidence a trait is reported as not read
26
+ export const CONFIDENCE_FLOOR = 0.5
27
+
28
+ const round = (value, places = 3) => (value === null || value === undefined || !Number.isFinite(value) ? null : Math.round(value * 10 ** places) / 10 ** places)
29
+ const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v))
30
+ const median = (list) => (list.length ? [...list].sort((a, b) => a - b)[Math.floor(list.length / 2)] : null)
31
+ const even = (n) => Math.max(2, Math.round(n / 2) * 2)
32
+
33
+ /* ───────────────────────────── frames through a pipe ───────────────────────────── */
34
+
35
+ /** Calls onFrame(bytes, n) for each sampled frame; `bytes` is only valid during the call. */
36
+ async function eachFrame(file, { fps, width, height, format, max, run, signal }, onFrame) {
37
+ const size = width * height * (format === "gray" ? 1 : 3)
38
+ let carry = Buffer.alloc(0)
39
+ let n = 0
40
+ const take = (chunk) => {
41
+ carry = carry.length ? Buffer.concat([carry, chunk]) : chunk
42
+ let at = 0
43
+ for (; carry.length - at >= size && n < max; at += size) onFrame(carry.subarray(at, at + size), n++)
44
+ carry = carry.subarray(at)
45
+ }
46
+ await run("ffmpeg", ["-hide_banner", "-nostdin", "-loglevel", "error", "-protocol_whitelist", "file,pipe", "-i", file, "-an", "-sn", "-dn", "-vf", `fps=${fps.toFixed(4)},scale=${width}:${height}:flags=area,format=${format}`, "-frames:v", String(max), "-f", "rawvideo", "-"], { onStdout: take, signal, stallMs: 60_000 })
47
+ return n
48
+ }
49
+
50
+ /* ───────────────────────────── small-frame measures ───────────────────────────── */
51
+
52
+ const mad = (a, b) => {
53
+ let sum = 0
54
+ for (let i = 0; i < a.length; i++) sum += Math.abs(a[i] - b[i])
55
+ return sum / a.length
56
+ }
57
+ // The share of the picture that changed: a join changes most of it, a caption or a graphic arriving only its own patch
58
+ const changed = (a, b) => {
59
+ let n = 0
60
+ for (let i = 0; i < a.length; i++) if (Math.abs(a[i] - b[i]) > 12) n++
61
+ return n / a.length
62
+ }
63
+ const meanOf = (a) => {
64
+ let sum = 0
65
+ for (let i = 0; i < a.length; i++) sum += a[i]
66
+ return sum / a.length
67
+ }
68
+
69
+ /** `a` scaled by `s` about (cx, cy) in 0…1, nearest pixel: what a punch-in or a zoom shows. */
70
+ function zoomed(a, w, h, s, cx = 0.5, cy = 0.5, out = new Uint8Array(a.length)) {
71
+ const [px, py] = [cx * (w - 1), cy * (h - 1)]
72
+ for (let y = 0; y < h; y++) {
73
+ const sy = clamp(Math.round(py + (y - py) / s), 0, h - 1) * w
74
+ for (let x = 0; x < w; x++) out[y * w + x] = a[sy + clamp(Math.round(px + (x - px) / s), 0, w - 1)]
75
+ }
76
+ return out
77
+ }
78
+
79
+ /**
80
+ * Is `b` a scaled `a`? The best scale (above 1: closer; below 1: wider) and how much of the
81
+ * change it explains (1 − residual ÷ the plain difference).
82
+ */
83
+ export function scaleFit(a, b, w, h, scales, centres = [0.3, 0.4, 0.5, 0.6, 0.7]) {
84
+ // Each pixel's difference counts up to a ceiling, so a caption changing over the picture at the same moment doesn't hide the move
85
+ const mad = (x, y) => {
86
+ let sum = 0
87
+ for (let i = 0; i < x.length; i++) sum += Math.min(SCALE_CEILING, Math.abs(x[i] - y[i]))
88
+ return sum / x.length
89
+ }
90
+ const plain = mad(a, b)
91
+ if (plain < 0.3) return { scale: 1, gain: 0, plain }
92
+ const scratch = new Uint8Array(a.length)
93
+ let best = { scale: 1, gain: 0, plain }
94
+ for (const s of scales) {
95
+ for (const cx of centres) {
96
+ for (const cy of centres) {
97
+ // Closer: b is a zoomed; wider: a is b zoomed
98
+ const closer = 1 - mad(zoomed(a, w, h, s, cx, cy, scratch), b) / plain
99
+ if (closer > best.gain) best = { scale: s, gain: closer, plain }
100
+ const wider = 1 - mad(zoomed(b, w, h, s, cx, cy, scratch), a) / plain
101
+ if (wider > best.gain) best = { scale: 1 / s, gain: wider, plain }
102
+ }
103
+ }
104
+ }
105
+ return best
106
+ }
107
+ const PUNCH_SCALES = [1.08, 1.12, 1.16, 1.2, 1.25, 1.3, 1.35, 1.4, 1.5, 1.6]
108
+ const EASE_SCALES = [1.02, 1.04, 1.06, 1.09, 1.12, 1.16, 1.2]
109
+ // A scale must explain this much of the change to be called a zoom (TPX-03)
110
+ const SCALE_GAIN = 0.55
111
+ const SCALE_CEILING = 24
112
+
113
+ /** The least-squares mix of `a` toward `b` that gives `m`, and what it leaves unexplained (a mean absolute difference). */
114
+ function blendFit(a, b, m) {
115
+ let [num, den] = [0, 0]
116
+ for (let i = 0; i < a.length; i++) {
117
+ const d = b[i] - a[i]
118
+ num += (m[i] - a[i]) * d
119
+ den += d * d
120
+ }
121
+ const alpha = den ? clamp(num / den, 0, 1) : 0
122
+ let sum = 0
123
+ for (let i = 0; i < a.length; i++) sum += Math.abs(m[i] - (a[i] + alpha * (b[i] - a[i])))
124
+ return { alpha, residual: sum / a.length }
125
+ }
126
+
127
+ /** The best straight moving edge: `m` is `a` on one side and `b` on the other. Every split in O(pixels). */
128
+ function wipeFit(a, b, m, w, h) {
129
+ let best = Infinity
130
+ for (const across of [true, false]) {
131
+ const n = across ? w : h
132
+ const errA = new Float64Array(n)
133
+ const errB = new Float64Array(n)
134
+ for (let y = 0; y < h; y++)
135
+ for (let x = 0; x < w; x++) {
136
+ const i = y * w + x
137
+ errA[across ? x : y] += Math.abs(m[i] - a[i])
138
+ errB[across ? x : y] += Math.abs(m[i] - b[i])
139
+ }
140
+ const [allA, allB] = [errA.reduce((s, v) => s + v, 0), errB.reduce((s, v) => s + v, 0)]
141
+ let [headA, headB] = [0, 0]
142
+ for (let k = 1; k < n; k++) {
143
+ headA += errA[k - 1]
144
+ headB += errB[k - 1]
145
+ // a first then b, or b first then a
146
+ best = Math.min(best, headA + (allB - headB), headB + (allA - headA))
147
+ }
148
+ }
149
+ return best / a.length
150
+ }
151
+
152
+ /** The best push: `a` slides out as `b` slides in, in any of four directions. */
153
+ function slideFit(a, b, m, w, h) {
154
+ let best = Infinity
155
+ for (const across of [true, false]) {
156
+ const n = across ? w : h
157
+ for (let k = 2; k < n - 1; k += 2) {
158
+ // k: how far the incoming picture has come. forward: a leaves toward 0, b enters from the far edge
159
+ let [forward, backward] = [0, 0]
160
+ for (let y = 0; y < h; y++)
161
+ for (let x = 0; x < w; x++) {
162
+ const p = across ? x : y
163
+ const at = (q) => (across ? y * w + q : q * w + x)
164
+ const i = y * w + x
165
+ forward += Math.abs(m[i] - (p < n - k ? a[at(p + k)] : b[at(p - (n - k))]))
166
+ backward += Math.abs(m[i] - (p < k ? b[at(p + (n - k))] : a[at(p - k)]))
167
+ }
168
+ best = Math.min(best, forward, backward)
169
+ }
170
+ }
171
+ return best / a.length
172
+ }
173
+
174
+ /** A zoom into `a` mixing to `b`: what FFmpeg's and most editors' zoom joins draw. */
175
+ function zoomFit(a, b, m, w, h) {
176
+ let best = Infinity
177
+ const scratch = new Uint8Array(a.length)
178
+ for (const s of [1.2, 1.5, 2, 3, 5]) best = Math.min(best, blendFit(zoomed(a, w, h, s, 0.5, 0.5, scratch), b, m).residual)
179
+ return best
180
+ }
181
+
182
+ /**
183
+ * The kind of a gradual join, from the frames inside it: each is fitted as a mix (dissolve), a
184
+ * straight moving edge (wipe), a push (slide) and a zoom into the outgoing picture; through black
185
+ * and through white are read from brightness alone. The models' mean misses are returned too.
186
+ * @param {Uint8Array} a the last frame before it
187
+ * @param {Uint8Array} b the first frame after it
188
+ * @param {Uint8Array[]} mids the frames inside it
189
+ * @returns {{ kind: string, miss: Record<string, number> }} kind "unread" when no model fits
190
+ */
191
+ export function joinKind(a, b, mids, w, h) {
192
+ const apart = mad(a, b)
193
+ const [meanA, meanB] = [meanOf(a), meanOf(b)]
194
+ const means = mids.map(meanOf)
195
+ // Darker than both ends: through black. A dissolve never is. Brighter than both: through white
196
+ if (Math.min(...means) < 0.5 * Math.min(meanA, meanB)) return { kind: "dip", miss: {} }
197
+ const top = Math.max(meanA, meanB)
198
+ // Most of the way to white: a zoom into a bright middle (out of bars and dark corners) brightens too, but not this far
199
+ if (Math.max(...means) > top + FLASH * (255 - top)) return { kind: "flash", miss: {} }
200
+ // Only frames that are really between the two pictures say anything
201
+ const telling = mids.filter((m) => Math.min(mad(m, a), mad(m, b)) > 0.12 * apart)
202
+ if (!telling.length || apart < 1) return { kind: "unread", miss: {} }
203
+ const miss = { fade: 0, wipe: 0, slide: 0, zoom: 0 }
204
+ for (const m of telling) {
205
+ miss.fade += blendFit(a, b, m).residual / apart / telling.length
206
+ miss.wipe += wipeFit(a, b, m, w, h) / apart / telling.length
207
+ miss.slide += slideFit(a, b, m, w, h) / apart / telling.length
208
+ miss.zoom += zoomFit(a, b, m, w, h) / apart / telling.length
209
+ }
210
+ for (const key of Object.keys(miss)) miss[key] = round(miss[key])
211
+ // A zoom is a dissolve with one more freedom, so it must fit clearly better to be named
212
+ const ranked = Object.entries({ ...miss, zoom: miss.zoom / JOIN_FIT.zoomEdge }).sort((x, y) => x[1] - y[1])
213
+ const [kind, least] = ranked[0]
214
+ return { kind: least <= JOIN_FIT.miss ? kind : "unread", miss }
215
+ }
216
+ // A model must leave no more than this share of the join unexplained; a zoom must beat a dissolve by this factor (TPX-03)
217
+ const FLASH = 0.6
218
+ export const JOIN_FIT = { miss: 0.3, zoomEdge: 0.7 }
219
+
220
+ /* ───────────────────────────── pass A: motion ───────────────────────────── */
221
+
222
+ // A frame differs from the one before by more than this (grey levels, mean) when the picture is changing
223
+ const ACTIVE = 1.2
224
+ // A one-frame change at least this large is a cut
225
+ const CUT = 6
226
+ // and a join changes at least this share of the picture (a caption page changing is a few percent of it)
227
+ const JOIN_SHARE = 0.25
228
+
229
+ /**
230
+ * Picture changes from small grey frames: hard cuts, gradual joins by kind, punch-ins, eased
231
+ * zooms, and how much the frame shakes. Keeps a ring of the last second and a half of frames.
232
+ * @returns {{ add: (frame: Uint8Array) => void, finish: () => object }}
233
+ */
234
+ export function motionReader(w, h, fps) {
235
+ const keep = Math.ceil(fps * 1.5) + 3
236
+ const ring = [] // { n, frame }
237
+ const frameAt = (n) => ring.find((r) => r.n === n)?.frame ?? null
238
+ const joins = [] // { t, end, kind }
239
+ const zooms = [] // { t, scale, ease }
240
+ const misses = []
241
+ let n = 0
242
+ let run = null // { from, last, peak }
243
+ let moving = false
244
+ let quietFor = 0
245
+ let [motionSum, motionN] = [0, 0]
246
+ let opening = 0
247
+ let [shake, shakeN] = [0, 0]
248
+ let lastShift = null
249
+ let eased = null // { t, scale, n }
250
+ let lastJoin = -1 // the last frame of the last join or zoom: the half-second look back never reaches across one
251
+ const recent = [] // the last few differences, to spot a cut inside movement
252
+ const t = (frame) => frame / fps
253
+
254
+ // How far the picture moved as a whole, from its column and row sums
255
+ const profile = (frame) => {
256
+ const cols = new Float64Array(w)
257
+ const rows = new Float64Array(h)
258
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) (cols[x] += frame[y * w + x], rows[y] += frame[y * w + x])
259
+ return { cols, rows }
260
+ }
261
+ const shiftOf = (p, q, len) => {
262
+ let [best, at] = [Infinity, 0]
263
+ for (let s = -4; s <= 4; s++) {
264
+ let sum = 0
265
+ for (let i = 4; i < len - 4; i++) sum += Math.abs(p[i] - q[i + s])
266
+ if (sum < best) [best, at] = [sum, s]
267
+ }
268
+ return at
269
+ }
270
+ let lastProfile = null
271
+
272
+ function close(endFrame) {
273
+ const { from, last, peak, peakAt, sum } = run
274
+ run = null
275
+ const length = last - from + 1
276
+ // One frame carries the change (anything else moving with it is small): a cut or a punch-in, at that frame
277
+ if (length <= 2 || peak >= 0.7 * sum) {
278
+ const [a, b] = [frameAt(peakAt - 1), frameAt(peakAt)]
279
+ if (!a || !b || peak < ACTIVE) return
280
+ const fit = scaleFit(a, b, w, h, PUNCH_SCALES)
281
+ if (fit.gain >= SCALE_GAIN) return void (zooms.push({ t: t(peakAt), scale: fit.scale, ease: "snap" }), (lastJoin = last))
282
+ if (peak >= CUT && changed(a, b) >= JOIN_SHARE) (joins.push({ t: t(peakAt), end: t(peakAt), kind: "cut" }), (lastJoin = last))
283
+ return
284
+ }
285
+ const a = frameAt(from - 1)
286
+ const b = frameAt(last)
287
+ if (!a || !b) return
288
+ const apart = mad(a, b)
289
+ // In and straight back out inside one stretch (a punch-in on a single word): the middle is the picture, closer
290
+ const middle = frameAt(Math.round((from + last) / 2))
291
+ const through = middle && changed(a, b) < JOIN_SHARE ? scaleFit(a, middle, w, h, PUNCH_SCALES) : null
292
+ if (through?.gain >= SCALE_GAIN && through.scale > 1) return void (zooms.push({ t: t(from), scale: through.scale, ease: "snap" }), (lastJoin = last))
293
+ // The picture came back to itself, only scaled: a move inside a shot, not a join
294
+ const fit = scaleFit(a, b, w, h, PUNCH_SCALES)
295
+ if (fit.gain >= SCALE_GAIN) return void (zooms.push({ t: t(from), scale: fit.scale, ease: "eased" }), (lastJoin = last))
296
+ // Back to a picture like the one before, but most of the frame changed on the way: a join between two alike shots
297
+ if ((apart < CUT || changed(a, b) < JOIN_SHARE) && !(middle && changed(a, middle) >= JOIN_SHARE)) return
298
+ const mids = []
299
+ for (let i = from; i < last; i++) frameAt(i) && mids.push(frameAt(i))
300
+ const found = fps >= KIND_FPS && mids.length ? joinKind(a, b, mids, w, h) : { kind: "unread", miss: {} }
301
+ misses.push(found.miss)
302
+ joins.push({ t: t(from), end: t(endFrame), kind: found.kind })
303
+ lastJoin = last
304
+ }
305
+
306
+ return {
307
+ add(bytes) {
308
+ const frame = Uint8Array.from(bytes)
309
+ const prev = ring.at(-1)?.frame
310
+ ring.push({ n, frame })
311
+ if (ring.length > keep) ring.shift()
312
+ if (prev) {
313
+ const d = mad(frame, prev)
314
+ const active = d > ACTIVE
315
+ if (t(n) <= 3) opening += d
316
+ if (moving) {
317
+ // Inside long movement, a cut is a change far above the movement around it
318
+ const around = recent.length ? recent.reduce((s, v) => s + v, 0) / recent.length : 0
319
+ if (d >= CUT && d > 3 * around && changed(prev, frame) >= JOIN_SHARE) (joins.push({ t: t(n), end: t(n), kind: "cut" }), (lastJoin = n))
320
+ quietFor = active ? 0 : quietFor + 1
321
+ if (quietFor >= 2) moving = false
322
+ } else if (active) {
323
+ run ??= { from: n, last: n, peak: 0, peakAt: n, sum: 0 }
324
+ run.last = n
325
+ run.sum += d
326
+ if (d > run.peak) [run.peak, run.peakAt] = [d, n]
327
+ quietFor = 0
328
+ // Longer than any join: movement, read for cuts by their size instead
329
+ if (run.last - run.from + 1 > fps * 1.2) {
330
+ run = null
331
+ moving = true
332
+ }
333
+ } else if (run && ++quietFor >= 2) {
334
+ // Held on black or white in the middle of a dip or a flash: the join isn't over
335
+ const before = frameAt(run.from - 1)
336
+ const [was, now] = [before ? meanOf(before) : 0, meanOf(frame)]
337
+ const held = before && ((now < 0.5 * was && now < 28) || now > Math.max(228, was + 20))
338
+ if (!held || n - run.from > fps * 1.2) close(n)
339
+ }
340
+ if (!active && !run) {
341
+ motionSum += d
342
+ motionN++
343
+ }
344
+ recent.push(d)
345
+ if (recent.length > 4) recent.shift()
346
+ // Shake: the whole picture's jitter between quiet frames, as a share of its width
347
+ const now = profile(frame)
348
+ if (lastProfile && d < CUT) {
349
+ const shift = [shiftOf(lastProfile.cols, now.cols, w), shiftOf(lastProfile.rows, now.rows, h)]
350
+ if (lastShift) (shake += Math.hypot(shift[0] - lastShift[0], shift[1] - lastShift[1]) / w, shakeN++)
351
+ lastShift = shift
352
+ } else lastShift = null
353
+ lastProfile = now
354
+ // An eased zoom: the picture half a second ago, scaled, is the picture now
355
+ const back = Math.max(2, Math.round(fps / 2))
356
+ if (n % back === 0 && n - back > lastJoin && !run) {
357
+ const old = frameAt(n - back)
358
+ const fit = old ? scaleFit(old, frame, w, h, EASE_SCALES, [0.4, 0.5, 0.6]) : { gain: 0, plain: 0 }
359
+ if (fit.gain >= SCALE_GAIN && fit.plain >= ACTIVE * 0.6) {
360
+ if (eased && eased.n === n - back) (eased.scale *= fit.scale, (eased.n = n))
361
+ else {
362
+ if (eased) zooms.push({ t: eased.t, scale: eased.scale, ease: "eased" })
363
+ eased = { t: t(n - back), scale: fit.scale, n }
364
+ }
365
+ }
366
+ }
367
+ }
368
+ n++
369
+ },
370
+ finish() {
371
+ if (run) close(n - 1)
372
+ if (eased) zooms.push({ t: eased.t, scale: eased.scale, ease: "eased" })
373
+ return { frames: n, joins: joins.sort((x, y) => x.t - y.t), zooms: zooms.sort((x, y) => x.t - y.t), misses, opening: n ? opening / Math.min(n, Math.ceil(3 * fps)) : null, still: motionN ? motionSum / motionN : null, shake: shakeN ? shake / shakeN : null }
374
+ },
375
+ }
376
+ }
377
+
378
+ /* ───────────────────────────── pass B: detail ───────────────────────────── */
379
+
380
+ const LINEAR = Float64Array.from({ length: 256 }, (_, v) => (v / 255 <= 0.04045 ? v / 255 / 12.92 : ((v / 255 + 0.055) / 1.055) ** 2.4))
381
+ const CELL = 8
382
+ // Behind the letters is a plate when it is darker than this share of the picture around
383
+ const PLATE = 0.62
384
+ // A stroke edge: a step this large across two pixels
385
+ const EDGE = 44
386
+
387
+ /**
388
+ * Text regions of one RGB frame, as boxes in pixels: cells where sharp vertical strokes of both
389
+ * polarities crowd together, joined across a word gap. Only where text is, never what it says.
390
+ * @returns {{ x0: number, y0: number, x1: number, y1: number, lines: number, plate: string | null, contrast: number | null, marked: boolean }[]}
391
+ */
392
+ export function textRegions(rgb, w, h) {
393
+ const luma = new Uint8Array(w * h)
394
+ for (let i = 0; i < w * h; i++) luma[i] = (rgb[i * 3] * 54 + rgb[i * 3 + 1] * 183 + rgb[i * 3 + 2] * 19) >> 8
395
+ const [cw, ch] = [Math.floor(w / CELL), Math.floor(h / CELL)]
396
+ const rise = new Uint16Array(cw * ch)
397
+ const fall = new Uint16Array(cw * ch)
398
+ const edge = new Uint8Array(w * h)
399
+ for (let y = 0; y < ch * CELL; y++)
400
+ for (let x = 1; x < cw * CELL - 1; x++) {
401
+ const step = luma[y * w + x + 1] - luma[y * w + x - 1]
402
+ if (Math.abs(step) < EDGE) continue
403
+ edge[y * w + x] = 1
404
+ const cell = Math.floor(y / CELL) * cw + Math.floor(x / CELL)
405
+ step > 0 ? rise[cell]++ : fall[cell]++
406
+ }
407
+ // Text: both polarities in a cell (a letter's two sides); a box's one edge has only one
408
+ const texty = new Uint8Array(cw * ch)
409
+ for (let i = 0; i < cw * ch; i++) texty[i] = rise[i] >= 3 && fall[i] >= 3 ? 1 : 0
410
+ // Join across one empty cell sideways (a space between words)
411
+ const joined = Uint8Array.from(texty)
412
+ for (let y = 0; y < ch; y++) for (let x = 1; x < cw - 1; x++) if (!texty[y * cw + x] && texty[y * cw + x - 1] && texty[y * cw + x + 1]) joined[y * cw + x] = 1
413
+ const seen = new Uint8Array(cw * ch)
414
+ const regions = []
415
+ for (let start = 0; start < cw * ch; start++) {
416
+ if (!joined[start] || seen[start]) continue
417
+ const stack = [start]
418
+ seen[start] = 1
419
+ let [cx0, cy0, cx1, cy1, cells] = [cw, ch, 0, 0, 0]
420
+ while (stack.length) {
421
+ const i = stack.pop()
422
+ const [x, y] = [i % cw, Math.floor(i / cw)]
423
+ cells += texty[i]
424
+ cx0 = Math.min(cx0, x)
425
+ cx1 = Math.max(cx1, x)
426
+ cy0 = Math.min(cy0, y)
427
+ cy1 = Math.max(cy1, y)
428
+ for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
429
+ const [nx, ny] = [x + dx, y + dy]
430
+ if (nx < 0 || ny < 0 || nx >= cw || ny >= ch) continue
431
+ const j = ny * cw + nx
432
+ if (joined[j] && !seen[j]) (seen[j] = 1), stack.push(j)
433
+ }
434
+ }
435
+ // At least three cells of strokes side by side: a word, not a speck
436
+ if (cx1 - cx0 + 1 < 3 || cells < 3) continue
437
+ // Tight edges in pixels, from the strokes themselves
438
+ let [x0, y0, x1, y1] = [w, h, 0, 0]
439
+ const rowHits = new Uint16Array((cy1 - cy0 + 1) * CELL)
440
+ const colHits = new Uint16Array((cx1 - cx0 + 1) * CELL)
441
+ for (let y = cy0 * CELL; y < (cy1 + 1) * CELL; y++)
442
+ for (let x = cx0 * CELL; x < (cx1 + 1) * CELL; x++)
443
+ if (edge[y * w + x]) {
444
+ rowHits[y - cy0 * CELL]++
445
+ colHits[x - cx0 * CELL]++
446
+ x0 = Math.min(x0, x)
447
+ x1 = Math.max(x1, x)
448
+ y0 = Math.min(y0, y)
449
+ y1 = Math.max(y1, y)
450
+ }
451
+ // Lines: runs of rows with strokes
452
+ let [lines, empty, inside] = [0, 2, false]
453
+ for (const v of rowHits) {
454
+ if (v >= 1) {
455
+ if (!inside && empty >= 2) lines++
456
+ inside = true
457
+ empty = 0
458
+ } else if (++empty >= 2) inside = false
459
+ }
460
+ lines = Math.max(1, lines)
461
+ const lineHeight = (y1 - y0 + 1) / lines
462
+ // What is behind the letters: a plate of its own, a dark outline, or the picture
463
+ let [textN, insideN, insideSum, neutral, coloured, textLight, behindLight] = [0, 0, 0, 0, 0, 0, 0]
464
+ // Relative luminance, as WCAG's contrast counts it
465
+ const light = (i) => 0.2126 * LINEAR[rgb[i * 3]] + 0.7152 * LINEAR[rgb[i * 3 + 1]] + 0.0722 * LINEAR[rgb[i * 3 + 2]]
466
+ const pad = Math.round(lineHeight * 0.2)
467
+ const [bx0, by0, bx1, by1] = [Math.max(0, x0 - pad), Math.max(0, y0 - pad), Math.min(w - 1, x1 + pad), Math.min(h - 1, y1 + pad)]
468
+ for (let y = by0; y <= by1; y++)
469
+ for (let x = bx0; x <= bx1; x++) {
470
+ const i = y * w + x
471
+ if (luma[i] > 170) {
472
+ textN++
473
+ const [r, g, b] = [rgb[i * 3], rgb[i * 3 + 1], rgb[i * 3 + 2]]
474
+ Math.max(r, g, b) - Math.min(r, g, b) > 70 ? coloured++ : neutral++
475
+ textLight += light(i)
476
+ } else {
477
+ insideN++
478
+ insideSum += luma[i]
479
+ behindLight += light(i)
480
+ }
481
+ }
482
+ // The picture well clear of the text, to compare with what sits right behind the letters
483
+ let [ringN, ringSum] = [0, 0]
484
+ const out = Math.round(lineHeight * 1.5) + CELL
485
+ for (let y = Math.max(0, y0 - out); y <= Math.min(h - 1, y1 + out); y++)
486
+ for (let x = Math.max(0, x0 - out); x <= Math.min(w - 1, x1 + out); x++) {
487
+ if (x >= x0 - out + CELL && x <= x1 + out - CELL && y >= y0 - out + CELL && y <= y1 + out - CELL) continue
488
+ ringN++
489
+ ringSum += luma[y * w + x]
490
+ }
491
+ const insideMean = insideN ? insideSum / insideN : 0
492
+ const ringMean = ringN ? ringSum / ringN : null
493
+ // A dark plate behind light letters; an outline can't be told from none at this size, and on a dark
494
+ // picture a plate and no plate look the same, so that isn't read (TPX-03)
495
+ const plate = !textN || ringMean === null || ringMean < 60 ? null : insideMean < PLATE * ringMean ? "box" : "none"
496
+ // The letters against what is right behind them (small frames soften both, so this reads a little low)
497
+ const contrast = textN && insideN ? (textLight / textN + 0.05) / (behindLight / insideN + 0.05) : null
498
+ regions.push({ x0, y0, x1: x1 + 1, y1: y1 + 1, lines, plate, contrast, marked: textN > 0 && coloured / textN > 0.15 && neutral / textN > 0.15 })
499
+ }
500
+ return regions
501
+ }
502
+
503
+ /**
504
+ * Captions, graphics, colour, grain, corner falloff and bars from sampled RGB frames.
505
+ * @returns {{ add: (rgb: Uint8Array) => void, finish: () => object }}
506
+ */
507
+ export function detailReader(w, h, fps, { colourEvery = 1 } = {}) {
508
+ const perFrame = [] // regions as shares of the frame: numbers only
509
+ const thirds = [[], [], []]
510
+ let n = 0
511
+ let [grain, grainN] = [0, 0]
512
+ let [falloff, falloffN] = [0, 0]
513
+ const darkRows = new Uint32Array(h)
514
+ let rowFrames = 0
515
+ let total = null
516
+
517
+ return {
518
+ /** @param {number} of how many frames there will be, for the thirds */
519
+ expect: (of) => (total = of),
520
+ add(rgb) {
521
+ perFrame.push(textRegions(rgb, w, h).map((r) => ({ x0: r.x0 / w, y0: r.y0 / h, x1: r.x1 / w, y1: r.y1 / h, lines: r.lines, plate: r.plate, contrast: r.contrast, marked: r.marked })))
522
+ // Bars: rows that are black in this frame
523
+ let lit = 0
524
+ const rowMean = new Float64Array(h)
525
+ for (let y = 0; y < h; y++) {
526
+ let sum = 0
527
+ for (let x = 0; x < w; x++) sum += rgb[(y * w + x) * 3 + 1]
528
+ rowMean[y] = sum / w
529
+ if (rowMean[y] < 14) darkRows[y]++
530
+ else lit++
531
+ }
532
+ // A frame that is black all over (a dip) says nothing about bars
533
+ if (lit > h * 0.2) rowFrames++
534
+ else for (let y = 0; y < h; y++) if (rowMean[y] < 14) darkRows[y]--
535
+ if (n % colourEvery === 0) {
536
+ const third = thirds[Math.min(2, Math.floor((n * 3) / Math.max(1, total ?? n + 1)))]
537
+ // Every sixteenth pixel is plenty for a mean and a covariance
538
+ for (let i = 0; i < w * h; i += 16) third.push(rgb[i * 3], rgb[i * 3 + 1], rgb[i * 3 + 2])
539
+ // Grain: how far a pixel sits from its four neighbours, where the picture is flat
540
+ let [sum, count] = [0, 0]
541
+ for (let y = 2; y < h - 2; y += 3)
542
+ for (let x = 2; x < w - 2; x += 3) {
543
+ const g = (xx, yy) => rgb[(yy * w + xx) * 3 + 1]
544
+ const around = (g(x - 1, y) + g(x + 1, y) + g(x, y - 1) + g(x, y + 1)) / 4
545
+ // Flat: the wider neighbours agree with each other
546
+ if (Math.abs(g(x - 2, y) - g(x + 2, y)) > 10 || Math.abs(g(x, y - 2) - g(x, y + 2)) > 10 || around < 20) continue
547
+ sum += Math.abs(g(x, y) - around)
548
+ count++
549
+ }
550
+ if (count > 50) (grain += sum / count, grainN++)
551
+ // Corner falloff: the corners against the middle, inside any bars
552
+ const rows = []
553
+ for (let y = 0; y < h; y++) if (rowMean[y] >= 14) rows.push(y)
554
+ if (rows.length > h * 0.3) {
555
+ const [top, bottom] = [rows[0], rows.at(-1)]
556
+ const span = bottom - top + 1
557
+ const patch = (fx, fy) => {
558
+ let [s, c] = [0, 0]
559
+ for (let y = top + Math.floor(fy * span); y < top + Math.floor((fy + 0.12) * span); y++) for (let x = Math.floor(fx * w); x < Math.floor((fx + 0.12) * w); x++) (s += rgb[(y * w + x) * 3 + 1], c++)
560
+ return c ? s / c : 0
561
+ }
562
+ const corners = (patch(0, 0) + patch(0.88, 0) + patch(0, 0.88) + patch(0.88, 0.88)) / 4
563
+ // The middle of each side, so a left-to-right ramp in the picture cancels out
564
+ const sides = (patch(0.44, 0) + patch(0.44, 0.88) + patch(0, 0.44) + patch(0.88, 0.44)) / 4
565
+ const middle = patch(0.44, 0.44)
566
+ if (middle > 30) (falloff += clamp(1 - (corners + sides) / 2 / middle, -1, 1), falloffN++)
567
+ }
568
+ }
569
+ n++
570
+ },
571
+ finish() {
572
+ const minutes = Math.max(n / fps / 60, 1 / 60)
573
+ /* captions: the band where text recurs */
574
+ const all = perFrame.flat()
575
+ const bins = new Array(20).fill(0)
576
+ for (const frame of perFrame) for (const bin of new Set(frame.map((r) => Math.min(19, Math.floor(((r.y0 + r.y1) / 2) * 20))))) bins[bin]++
577
+ const peak = bins.indexOf(Math.max(...bins))
578
+ const present = n > 0 && bins[peak] + (bins[peak - 1] ?? 0) + (bins[peak + 1] ?? 0) >= Math.max(3, n * 0.2)
579
+ const inBand = (r) => present && Math.abs(Math.min(19, Math.floor(((r.y0 + r.y1) / 2) * 20)) - peak) <= 1
580
+ // A caption changes its words; a strap in the same band doesn't. A page: text in the band until it
581
+ // goes, or until its place or width jumps (the next page arriving with no gap)
582
+ let pages = 0
583
+ let last = null
584
+ const captionFrames = []
585
+ for (const frame of perFrame) {
586
+ const here = frame.filter(inBand)
587
+ if (!here.length) {
588
+ last = null
589
+ continue
590
+ }
591
+ captionFrames.push(here)
592
+ const now = { x0: Math.min(...here.map((r) => r.x0)), x1: Math.max(...here.map((r) => r.x1)) }
593
+ if (!last || Math.abs(now.x0 - last.x0) > 0.06 || Math.abs(now.x1 - last.x1) > 0.06) pages++
594
+ last = now
595
+ }
596
+ const cap = captionFrames.flat()
597
+ const plates = cap.map((r) => r.plate).filter(Boolean)
598
+ const mostly = (list) => {
599
+ const counts = {}
600
+ for (const v of list) counts[v] = (counts[v] ?? 0) + 1
601
+ const [word, count] = Object.entries(counts).sort((a, b) => b[1] - a[1])[0] ?? [null, 0]
602
+ return list.length && count / list.length >= 0.6 ? word : null
603
+ }
604
+ const captions = present && pages >= 2
605
+ /* graphics: text outside the caption band (or a band whose words never change), followed from frame to frame */
606
+ const overlap = (p, q) => {
607
+ const [ix, iy] = [Math.min(p.x1, q.x1) - Math.max(p.x0, q.x0), Math.min(p.y1, q.y1) - Math.max(p.y0, q.y0)]
608
+ return ix > 0 && iy > 0 ? (ix * iy) / Math.min((p.x1 - p.x0) * (p.y1 - p.y0), (q.x1 - q.x0) * (q.y1 - q.y0)) : 0
609
+ }
610
+ const shown = [] // { box, frames }
611
+ let open = []
612
+ let full = 0
613
+ for (const frame of perFrame) {
614
+ // Lines of one graphic (a name over a title) are one thing: boxes that share a column and nearly touch
615
+ const here = []
616
+ for (const r of frame.filter((r) => !captions || !inBand(r)).sort((p, q) => p.y0 - q.y0)) {
617
+ const above = here.find((o) => r.y0 - o.y1 < 0.05 && Math.min(o.x1, r.x1) > Math.max(o.x0, r.x0))
618
+ if (above) Object.assign(above, { x0: Math.min(above.x0, r.x0), x1: Math.max(above.x1, r.x1), y1: Math.max(above.y1, r.y1) })
619
+ else here.push({ ...r })
620
+ }
621
+ const next = []
622
+ for (const r of here) {
623
+ const going = open.find((o) => overlap(o.box, r) > 0.3)
624
+ if (going) (going.frames++, next.push(going))
625
+ else {
626
+ const fresh = { box: r, frames: 1 }
627
+ shown.push(fresh)
628
+ next.push(fresh)
629
+ }
630
+ }
631
+ open = next
632
+ if (here.reduce((sum, r) => sum + (r.x1 - r.x0) * (r.y1 - r.y0), 0) > 0.25) full++
633
+ }
634
+ // One sample could be a join passing through: a graphic holds for two or more
635
+ const graphics = shown.filter((g) => g.frames >= 2)
636
+ const merged = new Uint8Array([...thirds[0], ...thirds[1], ...thirds[2]])
637
+ const colour = merged.length ? statsOf(merged) : null
638
+ const parts = thirds.filter((t) => t.length >= 300).map((t) => statsOf(new Uint8Array(t)).mean)
639
+ const drift = colour && parts.length === 3 ? Math.max(...parts.map((m) => Math.hypot(m[0] - colour.mean[0], m[1] - colour.mean[1], m[2] - colour.mean[2]))) : null
640
+ // Bars: rows black in nearly every frame, counted in from the top and the bottom
641
+ const barred = (y) => rowFrames > 0 && darkRows[y] >= rowFrames * 0.95
642
+ let [top, bottom] = [0, 0]
643
+ while (top < h && barred(top)) top++
644
+ while (bottom < h - top && barred(h - 1 - bottom)) bottom++
645
+ return {
646
+ frames: n,
647
+ captions: { present: captions, top: captions ? median(cap.map((r) => r.y0)) : null, bottom: captions ? median(cap.map((r) => r.y1)) : null, height: captions ? median(cap.map((r) => (r.y1 - r.y0) / r.lines)) : null, lines: captions ? median(cap.map((r) => r.lines)) : null, pagesPerMinute: captions ? pages / minutes : null, plate: captions ? mostly(plates) : null, contrast: captions ? median(cap.map((r) => r.contrast).filter((v) => v !== null)) : null, marked: captions ? cap.filter((r) => r.marked).length / cap.length >= 0.3 : null, share: n ? captionFrames.length / n : 0 },
648
+ graphics: { perMinute: graphics.length / minutes, seconds: graphics.length ? graphics.reduce((s, g) => s + g.frames, 0) / graphics.length / fps : null, full: n ? full / n : null, lower: graphics.some((g) => (g.box.x0 + g.box.x1) / 2 < 0.5 && (g.box.y0 + g.box.y1) / 2 > 0.55), count: graphics.length },
649
+ text: { top: all.length ? Math.min(...all.map((r) => r.y0)) : null, bottom: all.length ? 1 - Math.max(...all.map((r) => r.y1)) : null, early: perFrame.slice(0, Math.max(1, Math.round(2 * fps))).some((f) => f.length > 0), earlyGraphic: perFrame.slice(0, Math.max(1, Math.round(2 * fps))).some((f) => f.some((r) => !captions || !inBand(r))) },
650
+ colour,
651
+ drift,
652
+ grain: grainN ? grain / grainN : null,
653
+ vignette: falloffN ? falloff / falloffN : null,
654
+ letterbox: rowFrames ? (top + bottom) / h : null,
655
+ }
656
+ },
657
+ }
658
+ }
659
+
660
+ /* ───────────────────────────── pass C: sound ───────────────────────────── */
661
+
662
+ /** Silence, energy across the running time and a steady pulse, from mono samples. */
663
+ export function soundOf(samples, rate = PCM_RATE) {
664
+ const step = Math.round(rate / 10)
665
+ const windows = Math.floor(samples.length / step)
666
+ if (windows < 10) return null
667
+ const db = new Float64Array(windows)
668
+ for (let i = 0; i < windows; i++) {
669
+ let sum = 0
670
+ for (let k = i * step; k < (i + 1) * step; k++) sum += samples[k] * samples[k]
671
+ db[i] = 10 * Math.log10(1e-10 + sum / step)
672
+ }
673
+ let quiet = 0
674
+ for (const v of db) if (v < -50) quiet++
675
+ const energy = Array.from({ length: 10 }, (_, tenth) => {
676
+ const [from, to] = [Math.floor((tenth * windows) / 10), Math.floor(((tenth + 1) * windows) / 10)]
677
+ let sum = 0
678
+ for (let i = from; i < to; i++) sum += db[i]
679
+ return round(clamp((sum / Math.max(1, to - from) + 60) / 60, 0, 1))
680
+ })
681
+ // What is left in the gaps, against the loud parts: near 0 when something plays throughout (a bed), far below when the gaps are empty
682
+ const sorted = [...db].sort((x, y) => x - y)
683
+ const bed = sorted[Math.floor(windows * 0.1)] - sorted[Math.floor(windows * 0.9)]
684
+ return { silence: quiet / windows, energy, bed }
685
+ }
686
+
687
+ /**
688
+ * How steady a pulse is: the share of tracked beats that have a hit on them. A bed with drums
689
+ * scores near 1; speech, room sound and pads without drums score low (TPX-03: 0.88 or more
690
+ * against 0.36 or less). Beats in seconds.
691
+ */
692
+ export function pulseOf(samples, beats, rate = PCM_RATE) {
693
+ if (beats.length < 8) return 0
694
+ const hop = Math.round(rate * 0.02)
695
+ const frames = Math.floor(samples.length / hop)
696
+ const energy = new Float64Array(frames)
697
+ for (let f = 0; f < frames; f++) {
698
+ let sum = 0
699
+ for (let i = f * hop; i < (f + 1) * hop; i++) sum += samples[i] * samples[i]
700
+ energy[f] = Math.log10(1e-10 + sum / hop)
701
+ }
702
+ const rises = []
703
+ for (let f = 3; f < frames; f++) {
704
+ const at = (f * hop) / rate
705
+ if (energy[f] - Math.min(energy[f - 1], energy[f - 2], energy[f - 3]) > 0.4 && energy[f] > -4.5 && !(rises.length && at - rises.at(-1) < 0.08)) rises.push(at)
706
+ }
707
+ let on = 0
708
+ for (const beat of beats) if (rises.some((r) => Math.abs(r - beat) <= 0.06)) on++
709
+ return on / beats.length
710
+ }
711
+ // A pulse this steady is music with a beat
712
+ export const PULSE = 0.7
713
+
714
+ /* ───────────────────────────── the measure ───────────────────────────── */
715
+
716
+ const READ = { enum: ["yes", "no"] }
717
+ const NUM = "num"
718
+ // The shape an Edit DNA 2 may have: numbers, true or false, and these fixed words. Nothing else
719
+ // (EDD-23, EDD-65): no free text, no path, no word from the reference, no pixel
720
+ export const DNA2_SHAPE = {
721
+ kind: "edit-dna",
722
+ version: DNA2_VERSION,
723
+ seconds: NUM,
724
+ sampled: { motionFps: NUM, motionFrames: NUM, detailFps: NUM, detailFrames: NUM },
725
+ rhythm: { read: READ, confidence: NUM, shots: NUM, cutsPerMinute: NUM, median: NUM, p10: NUM, p90: NUM, curve: [NUM, 10], onBeats: NUM },
726
+ opening: { read: READ, confidence: NUM, firstCut: NUM, motion: NUM, textEarly: "bool", style: { enum: ["cold_open", "title_first", "straight_in"] } },
727
+ transitions: { read: READ, confidence: NUM, perMinute: { cut: NUM, fade: NUM, dip: NUM, flash: NUM, wipe: NUM, slide: NUM, zoom: NUM }, unread: NUM, seconds: NUM },
728
+ moves: { read: READ, confidence: NUM, zoomsPerMinute: NUM, scale: NUM, ease: { enum: ["snap", "eased"] }, shake: NUM },
729
+ captions: { read: READ, confidence: NUM, present: "bool", top: NUM, bottom: NUM, height: NUM, lines: NUM, pagesPerMinute: NUM, plate: { enum: ["box", "none"] }, contrast: NUM, highlight: "bool" },
730
+ graphics: { read: READ, confidence: NUM, perMinute: NUM, seconds: NUM, fullFrame: NUM, lowerBand: "bool" },
731
+ colour: { read: READ, confidence: NUM, mean: [NUM, 3], cov: [[NUM, 3], 3], luma: [NUM, 16], contrast: NUM, saturation: NUM, drift: NUM, grain: NUM, vignette: NUM, letterbox: NUM },
732
+ sound: { read: READ, confidence: NUM, lufs: NUM, range: NUM, truePeak: NUM, bed: NUM, bpm: NUM, silence: NUM },
733
+ structure: { read: READ, confidence: NUM, energy: [NUM, 10] },
734
+ format: { read: READ, confidence: NUM, aspect: NUM, shape: { enum: ["vertical", "portrait", "square", "landscape"] }, fps: NUM, clearTop: NUM, clearBottom: NUM },
735
+ }
736
+
737
+ function conforms(value, shape, path) {
738
+ if (typeof shape === "string" && shape !== NUM && shape !== "bool") {
739
+ if (value !== shape) throw new RangeError(`${path} must be "${shape}"`)
740
+ return
741
+ }
742
+ if (value === null) return
743
+ if (shape === NUM) {
744
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new RangeError(`${path} must be a number`)
745
+ } else if (shape === "bool") {
746
+ if (typeof value !== "boolean") throw new RangeError(`${path} must be true or false`)
747
+ } else if (Array.isArray(shape)) {
748
+ if (!Array.isArray(value) || value.length !== shape[1]) throw new RangeError(`${path} must be a list of ${shape[1]}`)
749
+ value.forEach((item, i) => conforms(item, shape[0], `${path}[${i}]`))
750
+ } else if (Array.isArray(shape.enum)) {
751
+ if (typeof value !== "string" || !shape.enum.includes(value)) throw new RangeError(`${path} must be one of ${shape.enum.join(", ")}`)
752
+ } else {
753
+ if (typeof value !== "object" || Array.isArray(value)) throw new RangeError(`${path} must be an object`)
754
+ const extra = Object.keys(value).find((key) => !Object.hasOwn(shape, key))
755
+ if (extra) throw new RangeError(`${path}.${extra} isn't part of an Edit DNA 2`)
756
+ for (const key of Object.keys(shape)) conforms(value[key], shape[key], `${path}.${key}`)
757
+ }
758
+ }
759
+
760
+ /** Throws unless `dna` is numbers, booleans and the fixed words, in the Edit DNA 2 shape; returns it. */
761
+ export function checkDna2(dna) {
762
+ if (dna === null || typeof dna !== "object" || Array.isArray(dna)) throw new RangeError("dna must be an object")
763
+ conforms(dna, DNA2_SHAPE, "dna")
764
+ return dna
765
+ }
766
+
767
+ /**
768
+ * A kept analysis, read back: an Edit DNA 2 of this version, or null. Anything else (an Edit DNA 1,
769
+ * an older or newer shape, a damaged file, a field that isn't a number or a fixed word) is never
770
+ * read as this shape: it counts as not measured, and is measured again (EH-73).
771
+ */
772
+ export function readDna2(text) {
773
+ try {
774
+ const dna = JSON.parse(text)
775
+ return dna?.kind === "edit-dna" && dna.version === DNA2_VERSION ? checkDna2(dna) : null
776
+ } catch {
777
+ return null
778
+ }
779
+ }
780
+
781
+ // A trait that wasn't read: every number null, so nothing can be taken from it
782
+ const unread = (shape) => Object.fromEntries(Object.keys(shape).map((key) => [key, key === "read" ? "no" : key === "confidence" ? 0 : Array.isArray(shape[key]) && !Array.isArray(shape[key][0]) ? new Array(shape[key][1]).fill(null) : typeof shape[key] === "object" && !Array.isArray(shape[key]) && !shape[key].enum ? Object.fromEntries(Object.keys(shape[key]).map((k) => [k, null])) : null]))
783
+ const trait = (name, confidence, values) => (confidence >= CONFIDENCE_FLOOR ? { read: "yes", confidence: round(confidence, 2), ...values } : unread(DNA2_SHAPE[name]))
784
+
785
+ /** The sampling plan for a video this long and this shape: bounded, whatever its length. */
786
+ export function samplingFor(seconds, width, height) {
787
+ const side = (long) => (width >= height ? [long, even((long * height) / width)] : [even((long * width) / height), long])
788
+ const motionFps = Math.min(LIMITS.motionFps, LIMITS.motionFrames / seconds)
789
+ const detailFps = Math.min(LIMITS.detailFps, LIMITS.detailFrames / seconds)
790
+ return { motion: { fps: motionFps, size: side(LIMITS.motionSide), max: LIMITS.motionFrames }, detail: { fps: detailFps, size: side(LIMITS.detailSide), max: LIMITS.detailFrames } }
791
+ }
792
+
793
+ /**
794
+ * Builds an Edit DNA 2 from what the three passes measured. Pure: the unit tests feed it numbers.
795
+ * @param {{ seconds: number, width: number, height: number, fps: number | null, plan: object, motion: object | null, detail: object | null, sound: object | null }} m
796
+ */
797
+ export function dnaFrom({ seconds, width, height, fps, plan, motion, detail, sound }) {
798
+ const minutes = seconds / 60
799
+ const dna = { kind: "edit-dna", version: DNA2_VERSION, seconds: round(seconds), sampled: { motionFps: round(plan.motion.fps, 2), motionFrames: motion?.frames ?? 0, detailFps: round(plan.detail.fps, 2), detailFrames: detail?.frames ?? 0 } }
800
+ const enough = motion && motion.frames >= 8
801
+ // Every change of picture counts toward the rhythm: joins and punch-ins alike
802
+ const changes = enough ? [...motion.joins.map((j) => j.t), ...motion.zooms.filter((z) => z.ease === "snap").map((z) => z.t)].sort((a, b) => a - b) : []
803
+ const shots = [0, ...changes].map((start, i, list) => ({ start, length: (list[i + 1] ?? seconds) - start }))
804
+ const pace = enough ? paceOf(shots, seconds) : null
805
+ const tolerance = Math.max(2 / (fps || 30), 1 / plan.motion.fps)
806
+ const beats = sound?.beats ?? []
807
+ dna.rhythm = trait("rhythm", !enough ? 0 : shots.length >= 3 ? 0.9 : 0.6, { shots: pace?.shots, cutsPerMinute: pace?.cutsPerMinute, median: pace?.median, p10: pace?.p10, p90: pace?.p90, curve: pace?.curve, onBeats: beats.length >= 8 && changes.length ? round(changes.filter((c) => beats.some((b) => Math.abs(b - c) <= tolerance)).length / changes.length) : null })
808
+ const firstCut = changes[0] ?? null
809
+ const early = detail?.text.early ?? null
810
+ // Title first: text that isn't a caption is up in the first two seconds. Cold open: a first, short piece, then a cut
811
+ const style = detail?.text.earlyGraphic ? "title_first" : firstCut !== null && firstCut >= 1.5 && firstCut <= 6 && shots.length >= 3 && firstCut < (pace?.median ?? 0) * 0.75 ? "cold_open" : "straight_in"
812
+ dna.opening = trait("opening", !enough ? 0 : detail ? 0.7 : 0.5, { firstCut: round(firstCut), motion: round(motion?.opening), textEarly: early, style: detail ? style : null })
813
+ const joins = enough ? motion.joins : []
814
+ const unreadJoins = joins.filter((j) => j.kind === "unread").length
815
+ const gradual = joins.filter((j) => j.kind !== "cut" && j.kind !== "unread")
816
+ dna.transitions = trait("transitions", !enough || plan.motion.fps < KIND_FPS ? 0 : joins.length ? 1 - unreadJoins / joins.length : 0.6, { perMinute: Object.fromEntries(JOIN_KINDS.map((kind) => [kind, round(joins.filter((j) => j.kind === kind).length / minutes, 2)])), unread: round(unreadJoins / minutes, 2), seconds: gradual.length ? round(median(gradual.map((j) => j.end - j.t)), 2) : null })
817
+ // A punch-in's release (the picture going wide again soon after) is the same move, counted once
818
+ const zooms = enough ? motion.zooms.filter((z, i, list) => z.scale > 1 || !list.slice(0, i).some((p) => p.scale > 1 && z.t - p.t < 4)) : []
819
+ const snap = zooms.filter((z) => z.ease === "snap").length
820
+ dna.moves = trait("moves", enough ? 0.8 : 0, { zoomsPerMinute: round(zooms.length / minutes, 2), scale: zooms.length ? round(median(zooms.map((z) => (z.scale >= 1 ? z.scale : 1 / z.scale))), 2) : null, ease: zooms.length ? (snap * 2 >= zooms.length ? "snap" : "eased") : null, shake: round(motion?.shake, 4) })
821
+ const c = detail?.captions
822
+ // Sure that there are none when nothing recurs; sure of what was found by how much of the time it was there
823
+ dna.captions = trait("captions", !detail || detail.frames < 6 ? 0 : c.present ? clamp(0.5 + c.share, 0, 0.95) : 0.8, c ? { present: c.present, top: round(c.top), bottom: round(c.bottom), height: round(c.height, 4), lines: c.lines, pagesPerMinute: round(c.pagesPerMinute, 1), plate: c.plate, contrast: round(c.contrast, 1), highlight: c.marked } : {})
824
+ const g = detail?.graphics
825
+ dna.graphics = trait("graphics", !detail || detail.frames < 6 ? 0 : 0.7, g ? { perMinute: round(g.perMinute, 1), seconds: round(g.seconds, 2), fullFrame: round(g.full), lowerBand: g.lower } : {})
826
+ const col = detail?.colour
827
+ dna.colour = trait("colour", col ? 0.9 : 0, col ? { mean: col.mean.map((v) => round(v, 4)), cov: col.cov.map((row) => row.map((v) => round(v, 5))), luma: col.luma.map((v) => round(v, 4)), contrast: round(col.contrast, 4), saturation: round(col.saturation, 4), drift: round(detail.drift, 4), grain: round(detail.grain, 2), vignette: round(detail.vignette), letterbox: round(detail.letterbox) } : {})
828
+ // Music's share of the time, its level under speech against the gaps, and hits that aren't speech need the voice
829
+ // apart from the rest, which code here can't do: they aren't in an Edit DNA 2 at all. A tempo is read only from a steady pulse
830
+ dna.sound = trait("sound", sound ? 0.8 : 0, sound ? { lufs: round(sound.lufs, 1), range: round(sound.range, 1), truePeak: round(sound.truePeak, 1), bed: round(sound.bed, 1), bpm: sound.pulse >= PULSE ? round(sound.bpm, 0) : null, silence: round(sound.silence) } : {})
831
+ dna.structure = trait("structure", sound?.energy ? 0.7 : 0, { energy: sound?.energy })
832
+ const aspect = width / height
833
+ dna.format = trait("format", width && height ? 1 : 0, { aspect: round(aspect), shape: aspect < 0.7 ? "vertical" : aspect < 0.95 ? "portrait" : aspect <= 1.05 ? "square" : "landscape", fps: round(fps, 2), clearTop: round(detail?.text.top), clearBottom: round(detail?.text.bottom) })
834
+ return checkDna2(dna)
835
+ }
836
+
837
+ /**
838
+ * The three bounded passes through a pipe, as dnaFrom takes them; `onStep` says how far along,
839
+ * `signal` cancels between and inside passes. Join times stay here: the DNA keeps only rates.
840
+ */
841
+ export async function measureDna2(file, { run = runTool, signal, onStep = () => {} } = {}) {
842
+ const { facts } = await probe(file, { run })
843
+ const seconds = (facts.duration ?? 0) / FLICKS
844
+ if (!(seconds > 0) || !facts.width) throw new RangeError("This reference has no picture to measure.")
845
+ const plan = samplingFor(seconds, facts.width, facts.height)
846
+ const steps = 100
847
+ onStep(1, steps)
848
+ const [mw, mh] = plan.motion.size
849
+ const motionRead = motionReader(mw, mh, plan.motion.fps)
850
+ const expected = Math.max(1, Math.min(plan.motion.max, Math.floor(seconds * plan.motion.fps)))
851
+ await eachFrame(file, { fps: plan.motion.fps, width: mw, height: mh, format: "gray", max: plan.motion.max, run, signal }, (frame, n) => {
852
+ motionRead.add(frame)
853
+ if (n % 30 === 0) onStep(1 + Math.floor((45 * n) / expected), steps)
854
+ })
855
+ signal?.throwIfAborted()
856
+ const [dw, dh] = plan.detail.size
857
+ const detailFrames = Math.max(1, Math.min(plan.detail.max, Math.floor(seconds * plan.detail.fps)))
858
+ const detailRead = detailReader(dw, dh, plan.detail.fps, { colourEvery: Math.max(1, Math.ceil(detailFrames / LIMITS.colourFrames)) })
859
+ detailRead.expect(detailFrames)
860
+ await eachFrame(file, { fps: plan.detail.fps, width: dw, height: dh, format: "rgb24", max: plan.detail.max, run, signal }, (frame, n) => {
861
+ detailRead.add(frame)
862
+ if (n % 10 === 0) onStep(46 + Math.floor((40 * n) / detailFrames), steps)
863
+ })
864
+ signal?.throwIfAborted()
865
+ let sound = null
866
+ if (facts.hasAudio !== false) {
867
+ const pcm = pcmCollector()
868
+ await run("ffmpeg", [...musicArgs(file).slice(0, -1), "-t", String(LIMITS.soundSeconds), "pipe:1"], { onStdout: pcm.add, signal, timeoutMs: 600_000 })
869
+ onStep(92, steps)
870
+ const samples = pcm.finish()
871
+ const heard = soundOf(samples)
872
+ if (heard) {
873
+ const music = analyseMusic(samples)
874
+ const beats = music.beats.map((b) => b.t / FLICKS)
875
+ const text = await run("ffmpeg", loudnessArgs(file), { signal, timeoutMs: 600_000 })
876
+ const loud = readLoudness(text)
877
+ const range = [...text.matchAll(/lavfi\.r128\.LRA=(-?[\d.]+)/g)].at(-1)?.[1]
878
+ const pulse = pulseOf(samples, beats)
879
+ sound = { ...heard, lufs: loud.integrated, range: range === undefined ? null : Number(range), truePeak: loud.truePeak, bpm: music.bpm, pulse, beats: pulse >= PULSE ? beats : [] }
880
+ }
881
+ }
882
+ signal?.throwIfAborted()
883
+ onStep(99, steps)
884
+ return { seconds, width: facts.width, height: facts.height, fps: facts.fps ? facts.fps.n / facts.fps.d : null, plan, motion: motionRead.finish(), detail: detailRead.finish(), sound }
885
+ }
886
+
887
+ /**
888
+ * Measures a reference video into an Edit DNA 2.
889
+ * @returns {Promise<object>} checked by checkDna2
890
+ */
891
+ export async function extractDna2(file, options = {}) {
892
+ return dnaFrom(await measureDna2(file, options))
893
+ }