comfy-ts 2.23.0 → 2.24.0

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 (76) hide show
  1. package/dist/{ServeApp-DolRCMHj.js → ServeApp-fsHtW5zG.js} +3 -3
  2. package/dist/{ServeApp-DolRCMHj.js.map → ServeApp-fsHtW5zG.js.map} +1 -1
  3. package/dist/cli.js +5 -5
  4. package/dist/{exampleAssets-Duneoq6r.js → exampleAssets-DZynSkZm.js} +79 -15
  5. package/dist/exampleAssets-DZynSkZm.js.map +1 -0
  6. package/dist/{findDefinedWorkflow-DjoJA8y7.js → findDefinedWorkflow-qyqFea7q.js} +2 -2
  7. package/dist/{findDefinedWorkflow-DjoJA8y7.js.map → findDefinedWorkflow-qyqFea7q.js.map} +1 -1
  8. package/dist/index.cjs +80 -14
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +53 -19
  11. package/dist/index.d.ts +53 -19
  12. package/dist/index.js +80 -15
  13. package/dist/index.js.map +1 -1
  14. package/dist/{run-run-Cr0L9lCK.js → run-run-Cn2JzKlE.js} +5 -5
  15. package/dist/{run-run-Cr0L9lCK.js.map → run-run-Cn2JzKlE.js.map} +1 -1
  16. package/dist/{run-serve---qA7o_m.js → run-serve-BhGegaCI.js} +4 -4
  17. package/dist/{run-serve---qA7o_m.js.map → run-serve-BhGegaCI.js.map} +1 -1
  18. package/dist/{run-tui-DxXiWo5J.js → run-tui-CrM4ijkH.js} +4 -4
  19. package/dist/{run-tui-DxXiWo5J.js.map → run-tui-CrM4ijkH.js.map} +1 -1
  20. package/dist/{schemaDrift-BTxdABHi.js → schemaDrift-BGYJZGMD.js} +3 -2
  21. package/dist/{schemaDrift-BTxdABHi.js.map → schemaDrift-BGYJZGMD.js.map} +1 -1
  22. package/dist/web.d.ts +53 -19
  23. package/dist/web.js +80 -15
  24. package/dist/web.js.map +1 -1
  25. package/examples/README.md +1 -0
  26. package/examples/depth-explorer/models.ts +6 -56
  27. package/examples/depth-explorer/serve.ts +12 -133
  28. package/examples/depth-explorer/web/App.tsx +20 -91
  29. package/examples/depth-explorer/web/index.html +1 -0
  30. package/examples/depth-explorer/web/state.ts +26 -109
  31. package/examples/depth-explorer/web/styles.css +1 -286
  32. package/examples/explorer-kit/catalog.ts +80 -0
  33. package/examples/explorer-kit/server.ts +167 -0
  34. package/examples/explorer-kit/web/base.css +289 -0
  35. package/examples/explorer-kit/web/runs.ts +160 -0
  36. package/examples/explorer-kit/web/ui.tsx +125 -0
  37. package/examples/rvion/17-relight.cflow.ts +2 -1
  38. package/examples/rvion/19-flythrough.cflow.ts +312 -0
  39. package/examples/rvion/20-grow-splat.cflow.ts +88 -0
  40. package/examples/rvion/21-photo-to-model.cflow.ts +191 -0
  41. package/examples/rvion/flythroughChain.ts +171 -0
  42. package/examples/rvion/flythroughColmap.ts +157 -0
  43. package/examples/rvion/flythroughFuse.ts +199 -0
  44. package/examples/rvion/flythroughGuide.ts +300 -0
  45. package/examples/rvion/flythroughPalette.ts +310 -0
  46. package/examples/rvion/flythroughPath.ts +177 -0
  47. package/examples/rvion/flythroughSplat.ts +73 -0
  48. package/examples/rvion/grow-splat/align.ts +114 -0
  49. package/examples/rvion/grow-splat/grow.ts +198 -0
  50. package/examples/rvion/grow-splat/ply.ts +166 -0
  51. package/examples/rvion/grow-splat/raster.ts +207 -0
  52. package/examples/rvion/grow-splat/sharp.ts +45 -0
  53. package/examples/rvion/splatDataset.ts +80 -0
  54. package/examples/rvion/splatEval.ts +380 -0
  55. package/examples/upscale-explorer/models.ts +341 -0
  56. package/examples/upscale-explorer/serve.ts +19 -0
  57. package/examples/upscale-explorer/web/App.tsx +250 -0
  58. package/examples/upscale-explorer/web/compare.tsx +285 -0
  59. package/examples/upscale-explorer/web/index.html +15 -0
  60. package/examples/upscale-explorer/web/main.tsx +12 -0
  61. package/examples/upscale-explorer/web/state.ts +279 -0
  62. package/examples/upscale-explorer/web/styles.css +241 -0
  63. package/examples/upscale-explorer/web/tsconfig.json +16 -0
  64. package/examples/upscale-explorer/web/viewport.tsx +130 -0
  65. package/examples/world-explorer/web/main.tsx +2 -2
  66. package/package.json +4 -3
  67. package/src/coreExports.ts +5 -0
  68. package/src/host/ComfyHost.ts +6 -0
  69. package/src/runner/ComfyExecution.ts +22 -5
  70. package/src/runner/ComfyWorkflow.ts +22 -0
  71. package/src/runner/ComfyWsApi.ts +1 -1
  72. package/src/runner/comfyOrgApiKey.ts +44 -0
  73. package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +2 -0
  74. package/src/state.ts +2 -0
  75. package/src/vars/DefinedWorkflow.ts +1 -0
  76. package/dist/exampleAssets-Duneoq6r.js.map +0 -1
@@ -0,0 +1,300 @@
1
+ // the guide of 19-flythrough drawn on this machine: the picture's MoGe mesh (a glb) rasterized from
2
+ // every camera of the path, a colour frame, a depth frame (inverse depth, near = bright, spread between
3
+ // its 2nd and 98th percentile, as a monocular depth model draws one) and its coverage. A z-buffered triangle rasterizer, perspective correct, in plain TypeScript: about a
4
+ // tenth of a second a frame where the box's ray tracer takes seconds
5
+ import { levelPoint, type PathCamera } from './flythroughPath.ts'
6
+
7
+ /** a textured triangle mesh in the render's world (y up, -z ahead) */
8
+ export type GuideMesh = {
9
+ positions: Float32Array
10
+ uvs: Float32Array
11
+ indices: Uint32Array
12
+ texture: { width: number; height: number; rgb: Uint8Array }
13
+ }
14
+
15
+ /** `metres`: each pixel's distance along the view axis, Infinity where the mesh has no data */
16
+ export type GuideFrame = { color: Uint8Array; depth: Uint8Array; coverage: Uint8Array; metres: Float32Array }
17
+
18
+ /** the parts of a glb this needs: the first primitive's positions, uvs, indices, and its texture's
19
+ * encoded bytes (decode them with sharp, then pass `texture`) */
20
+ export function readGlb(bytes: Uint8Array): Omit<GuideMesh, 'texture'> & { textureBytes: Uint8Array } {
21
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
22
+ if (view.getUint32(0, true) !== 0x46546c67) throw new Error('readGlb: not a glb file')
23
+ let off = 12
24
+ let json: unknown = null
25
+ let bin: Uint8Array = new Uint8Array()
26
+ while (off < bytes.length) {
27
+ const len = view.getUint32(off, true)
28
+ const type = view.getUint32(off + 4, true)
29
+ const chunk = bytes.subarray(off + 8, off + 8 + len)
30
+ if (type === 0x4e4f534a) json = JSON.parse(new TextDecoder().decode(chunk))
31
+ else if (type === 0x004e4942) bin = chunk
32
+ off += 8 + len
33
+ }
34
+ const gltf = json as GltfJson
35
+ const prim = gltf.meshes?.[0]?.primitives?.[0]
36
+ if (prim == null) throw new Error('readGlb: no mesh primitive')
37
+ const view_ = (i: number) => {
38
+ const bv = gltf.bufferViews?.[i]
39
+ if (bv == null) throw new Error(`readGlb: no buffer view ${i}`)
40
+ return bin.subarray(bv.byteOffset ?? 0, (bv.byteOffset ?? 0) + bv.byteLength)
41
+ }
42
+ const accessor = (i: number | undefined): Uint8Array & { componentType: number; count: number } => {
43
+ const a = i == null ? undefined : gltf.accessors?.[i]
44
+ if (a == null) throw new Error(`readGlb: no accessor ${i}`)
45
+ const raw = view_(a.bufferView).slice(a.byteOffset ?? 0)
46
+ return Object.assign(raw, { componentType: a.componentType, count: a.count })
47
+ }
48
+ const floats = (i: number | undefined, n: number) => {
49
+ const a = accessor(i)
50
+ if (a.componentType !== 5126) throw new Error('readGlb: positions and uvs must be float32')
51
+ return new Float32Array(a.buffer, a.byteOffset, a.count * n)
52
+ }
53
+ const idx = accessor(prim.indices)
54
+ const indices =
55
+ idx.componentType === 5125
56
+ ? new Uint32Array(idx.buffer, idx.byteOffset, idx.count)
57
+ : Uint32Array.from(new Uint16Array(idx.buffer, idx.byteOffset, idx.count))
58
+ const image = gltf.images?.[0]
59
+ if (image?.bufferView == null) throw new Error('readGlb: no embedded texture')
60
+ return {
61
+ positions: floats(prim.attributes.POSITION, 3),
62
+ uvs: floats(prim.attributes.TEXCOORD_0, 2),
63
+ indices,
64
+ textureBytes: view_(image.bufferView),
65
+ }
66
+ }
67
+
68
+ type GltfJson = {
69
+ meshes?: { primitives?: { attributes: { POSITION?: number; TEXCOORD_0?: number }; indices?: number }[] }[]
70
+ accessors?: { bufferView: number; byteOffset?: number; componentType: number; count: number }[]
71
+ bufferViews?: { byteOffset?: number; byteLength: number }[]
72
+ images?: { bufferView?: number }[]
73
+ }
74
+
75
+ /**
76
+ * the mesh without its curtains: a picture's mesh joins a near surface to the far one behind it
77
+ * with long thin triangles, short from the picture's camera (the origin) and long in depth. Seen
78
+ * from the side they stretch into streaks the video model copies, where a hole makes it invent.
79
+ * A triangle goes when an edge is longer than `ratio` times what its angle from the origin spans
80
+ */
81
+ export function dropStretched(mesh: GuideMesh, ratio = 4): GuideMesh {
82
+ const P = mesh.positions
83
+ const kept: number[] = []
84
+ const edge = (i: number, j: number) => {
85
+ const ax = P[i * 3]!
86
+ const ay = P[i * 3 + 1]!
87
+ const az = P[i * 3 + 2]!
88
+ const bx = P[j * 3]!
89
+ const by = P[j * 3 + 1]!
90
+ const bz = P[j * 3 + 2]!
91
+ const la = Math.hypot(ax, ay, az)
92
+ const lb = Math.hypot(bx, by, bz)
93
+ // the angle between the two rays from the origin, times the nearer distance: the edge as the
94
+ // picture's camera saw it
95
+ const across = Math.hypot(ax / la - bx / lb, ay / la - by / lb, az / la - bz / lb) * Math.min(la, lb)
96
+ return Math.hypot(ax - bx, ay - by, az - bz) <= ratio * across + 1e-4
97
+ }
98
+ const idx = mesh.indices
99
+ for (let t = 0; t < idx.length; t += 3) {
100
+ const a = idx[t]!
101
+ const b = idx[t + 1]!
102
+ const c = idx[t + 2]!
103
+ if (edge(a, b) && edge(b, c) && edge(c, a)) kept.push(a, b, c)
104
+ }
105
+ return { ...mesh, indices: Uint32Array.from(kept) }
106
+ }
107
+
108
+ /** the mesh in the path's levelled world: every vertex turned by the picture's `pitch` (levelPoint) */
109
+ export function levelMesh(mesh: GuideMesh, pitch: number): GuideMesh {
110
+ if (pitch === 0) return mesh
111
+ const positions = new Float32Array(mesh.positions.length)
112
+ for (let i = 0; i < positions.length; i += 3) {
113
+ const q = levelPoint([mesh.positions[i]!, mesh.positions[i + 1]!, mesh.positions[i + 2]!], pitch)
114
+ positions.set(q, i)
115
+ }
116
+ return { ...mesh, positions }
117
+ }
118
+
119
+ /** one frame from one camera: `fovY` vertical, degrees; the camera looks at its target, y up.
120
+ * `fill`: the depth frame's holes take the depth around them (fillHoles), so the video model sees a
121
+ * surface to invent rather than a black void it copies */
122
+ export function renderGuideFrame(p: { mesh: GuideMesh; camera: PathCamera; width: number; height: number; fovY: number; fill?: boolean }): GuideFrame {
123
+ const { mesh, camera, width: W, height: H } = p
124
+ const [ex, ey, ez] = camera.position
125
+ // camera axes: forward f, right r, up u (three.js look-at with world up +y)
126
+ let fx = camera.target[0] - ex
127
+ let fy = camera.target[1] - ey
128
+ let fz = camera.target[2] - ez
129
+ const fl = Math.hypot(fx, fy, fz) || 1
130
+ fx /= fl
131
+ fy /= fl
132
+ fz /= fl
133
+ let rx = -fz
134
+ let rz = fx
135
+ const rl = Math.hypot(rx, rz) || 1
136
+ rx /= rl
137
+ rz /= rl
138
+ const ux = -rz * fy
139
+ const uy = rz * fx - rx * fz
140
+ const uz = rx * fy
141
+ const focal = H / 2 / Math.tan((p.fovY * Math.PI) / 360)
142
+ const n = mesh.positions.length / 3
143
+ // every vertex once: screen x, y, its view depth
144
+ const sx = new Float32Array(n)
145
+ const sy = new Float32Array(n)
146
+ const sz = new Float32Array(n)
147
+ for (let i = 0; i < n; i++) {
148
+ const dx = mesh.positions[i * 3]! - ex
149
+ const dy = mesh.positions[i * 3 + 1]! - ey
150
+ const dz = mesh.positions[i * 3 + 2]! - ez
151
+ const z = dx * fx + dy * fy + dz * fz
152
+ sz[i] = z
153
+ sx[i] = W / 2 + (focal * (dx * rx + dz * rz)) / z
154
+ sy[i] = H / 2 - (focal * (dx * ux + dy * uy + dz * uz)) / z
155
+ }
156
+ const zbuf = new Float32Array(W * H).fill(Infinity)
157
+ const ubuf = new Float32Array(W * H)
158
+ const vbuf = new Float32Array(W * H)
159
+ const NEAR = 0.05
160
+ const idx = mesh.indices
161
+ for (let t = 0; t < idx.length; t += 3) {
162
+ const a = idx[t]!
163
+ const b = idx[t + 1]!
164
+ const c = idx[t + 2]!
165
+ const za = sz[a]!
166
+ const zb = sz[b]!
167
+ const zc = sz[c]!
168
+ // a triangle crossing the near plane is dropped whole: at the guide's scale it is a sliver
169
+ if (za < NEAR || zb < NEAR || zc < NEAR) continue
170
+ const ax = sx[a]!
171
+ const ay = sy[a]!
172
+ const bx = sx[b]!
173
+ const by = sy[b]!
174
+ const cx = sx[c]!
175
+ const cy = sy[c]!
176
+ const area = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax)
177
+ if (area === 0 || !Number.isFinite(area)) continue
178
+ const x0 = Math.max(0, Math.floor(Math.min(ax, bx, cx)))
179
+ const x1 = Math.min(W - 1, Math.ceil(Math.max(ax, bx, cx)))
180
+ const y0 = Math.max(0, Math.floor(Math.min(ay, by, cy)))
181
+ const y1 = Math.min(H - 1, Math.ceil(Math.max(ay, by, cy)))
182
+ if (x0 > x1 || y0 > y1) continue
183
+ const ia = 1 / za
184
+ const ib = 1 / zb
185
+ const ic = 1 / zc
186
+ for (let y = y0; y <= y1; y++) {
187
+ const py = y + 0.5
188
+ for (let x = x0; x <= x1; x++) {
189
+ const px = x + 0.5
190
+ const w0 = ((bx - px) * (cy - py) - (by - py) * (cx - px)) / area
191
+ const w1 = ((cx - px) * (ay - py) - (cy - py) * (ax - px)) / area
192
+ const w2 = 1 - w0 - w1
193
+ if (w0 < 0 || w1 < 0 || w2 < 0) continue
194
+ // perspective correct: interpolate 1/z, and uv/z
195
+ const iz = w0 * ia + w1 * ib + w2 * ic
196
+ const z = 1 / iz
197
+ const k = y * W + x
198
+ if (z >= zbuf[k]!) continue
199
+ zbuf[k] = z
200
+ ubuf[k] = (w0 * mesh.uvs[a * 2]! * ia + w1 * mesh.uvs[b * 2]! * ib + w2 * mesh.uvs[c * 2]! * ic) * z
201
+ vbuf[k] = (w0 * mesh.uvs[a * 2 + 1]! * ia + w1 * mesh.uvs[b * 2 + 1]! * ib + w2 * mesh.uvs[c * 2 + 1]! * ic) * z
202
+ }
203
+ }
204
+ }
205
+ const color = new Uint8Array(W * H * 3)
206
+ const depth = new Uint8Array(W * H * 3)
207
+ const coverage = new Uint8Array(W * H * 3)
208
+ // inverse depth between robust ends: a far outlier (the mesh's back wall, 100 m away) must not
209
+ // squash every near surface into one white
210
+ const seen: number[] = []
211
+ for (let k = 0; k < W * H; k += 7) if (zbuf[k]! !== Infinity) seen.push(1 / zbuf[k]!)
212
+ seen.sort((a, b) => a - b)
213
+ const lo = seen[Math.floor(seen.length * 0.02)] ?? 0
214
+ const hi = seen[Math.floor(seen.length * 0.98)] ?? 1
215
+ const range = Math.max(hi - lo, 1e-9)
216
+ const tex = mesh.texture
217
+ for (let k = 0; k < W * H; k++) {
218
+ const z = zbuf[k]!
219
+ if (z === Infinity) continue
220
+ const tu = Math.min(tex.width - 1, Math.max(0, Math.round(ubuf[k]! * (tex.width - 1))))
221
+ const tv = Math.min(tex.height - 1, Math.max(0, Math.round(vbuf[k]! * (tex.height - 1))))
222
+ const o = (tv * tex.width + tu) * 3
223
+ const d = Math.max(0, Math.min(255, Math.round(((1 / z - lo) / range) * 255)))
224
+ for (let ch = 0; ch < 3; ch++) {
225
+ color[k * 3 + ch] = tex.rgb[o + ch]!
226
+ depth[k * 3 + ch] = d
227
+ coverage[k * 3 + ch] = 255
228
+ }
229
+ }
230
+ return { color, depth: p.fill ? fillHoles(depth, coverage, W, H) : depth, coverage, metres: zbuf }
231
+ }
232
+
233
+ /**
234
+ * the holes of a frame filled from what is around them, push-pull: the covered pixels averaged down
235
+ * a pyramid until every cell has some, then each hole takes the coarser level's value on the way up,
236
+ * so a hole gets a smooth blend of its edges. `coverage` is 255 where the frame has data
237
+ */
238
+ export function fillHoles(rgb: Uint8Array, coverage: Uint8Array, W: number, H: number): Uint8Array {
239
+ type Level = { w: number; h: number; v: Float32Array; a: Float32Array }
240
+ const first: Level = { w: W, h: H, v: new Float32Array(W * H * 3), a: new Float32Array(W * H) }
241
+ for (let k = 0; k < W * H; k++) {
242
+ const a = coverage[k * 3]! > 127 ? 1 : 0
243
+ first.a[k] = a
244
+ for (let c = 0; c < 3; c++) first.v[k * 3 + c] = rgb[k * 3 + c]! * a
245
+ }
246
+ const levels = [first]
247
+ while (levels.at(-1)!.w > 1 || levels.at(-1)!.h > 1) {
248
+ const up = levels.at(-1)!
249
+ const w = Math.max(1, Math.ceil(up.w / 2))
250
+ const h = Math.max(1, Math.ceil(up.h / 2))
251
+ const next: Level = { w, h, v: new Float32Array(w * h * 3), a: new Float32Array(w * h) }
252
+ for (let y = 0; y < up.h; y++)
253
+ for (let x = 0; x < up.w; x++) {
254
+ const i = y * up.w + x
255
+ const j = (y >> 1) * w + (x >> 1)
256
+ next.a[j]! += up.a[i]!
257
+ for (let c = 0; c < 3; c++) next.v[j * 3 + c]! += up.v[i * 3 + c]!
258
+ }
259
+ // every level stays premultiplied by its weight, the weight capped at 1
260
+ for (let j = 0; j < w * h; j++) {
261
+ const a = next.a[j]!
262
+ if (a > 1) for (let c = 0; c < 3; c++) next.v[j * 3 + c]! /= a
263
+ next.a[j] = Math.min(1, a)
264
+ }
265
+ levels.push(next)
266
+ }
267
+ // up again: what a cell lacks of its weight comes from its parent, by then complete
268
+ for (let l = levels.length - 2; l >= 0; l--) {
269
+ const fine = levels[l]!
270
+ const coarse = levels[l + 1]!
271
+ for (let y = 0; y < fine.h; y++)
272
+ for (let x = 0; x < fine.w; x++) {
273
+ const i = y * fine.w + x
274
+ const a = fine.a[i]!
275
+ if (a >= 1) continue
276
+ // bilinear in the parent level, else a hole fills in blocks
277
+ const gx = Math.min(coarse.w - 1, Math.max(0, (x + 0.5) / 2 - 0.5))
278
+ const gy = Math.min(coarse.h - 1, Math.max(0, (y + 0.5) / 2 - 0.5))
279
+ const x0 = Math.floor(gx)
280
+ const y0 = Math.floor(gy)
281
+ const x1 = Math.min(coarse.w - 1, x0 + 1)
282
+ const y1 = Math.min(coarse.h - 1, y0 + 1)
283
+ const tx = gx - x0
284
+ const ty = gy - y0
285
+ const at = (cx: number, cy: number, c: number) => {
286
+ const j = cy * coarse.w + cx
287
+ return coarse.v[j * 3 + c]! / Math.max(coarse.a[j]!, 1e-6)
288
+ }
289
+ for (let c = 0; c < 3; c++) {
290
+ const top = at(x0, y0, c) * (1 - tx) + at(x1, y0, c) * tx
291
+ const bottom = at(x0, y1, c) * (1 - tx) + at(x1, y1, c) * tx
292
+ fine.v[i * 3 + c] = fine.v[i * 3 + c]! + (1 - a) * (top * (1 - ty) + bottom * ty)
293
+ }
294
+ fine.a[i] = 1
295
+ }
296
+ }
297
+ const out = new Uint8Array(W * H * 3)
298
+ for (let k = 0; k < out.length; k++) out[k] = Math.max(0, Math.min(255, Math.round(first.v[k]!)))
299
+ return out
300
+ }
@@ -0,0 +1,310 @@
1
+ // how far a fly-through drifts from its picture's palette, and the pull back. Each frame is measured
2
+ // in CIE Lab against the picture cover-cropped to the frame: the mean colour (ΔE between the means,
3
+ // the lightness and the green-red and blue-yellow axes alone), the spread of the lightness (contrast),
4
+ // the mean chroma (saturation) and a chroma weighted hue histogram (Hellinger distance, 0 = the same
5
+ // hues). The match moves each frame's Lab mean and spread to the picture's, with stats smoothed over
6
+ // time so the pull never flickers.
7
+ //
8
+ // run: bun examples/rvion/flythroughPalette.ts measure <picture> <out.png> <label>=<video> …
9
+ // bun examples/rvion/flythroughPalette.ts match <picture> <in.mp4> <out.mp4> [strength]
10
+ import { $ } from 'bun'
11
+ import { writeFileSync } from 'node:fs'
12
+ import sharp from 'sharp'
13
+
14
+ /** sRGB 0..255 to linear, once per byte */
15
+ const LINEAR = Float64Array.from({ length: 256 }, (_, i) => {
16
+ const c = i / 255
17
+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
18
+ })
19
+ const D65 = [0.95047, 1, 1.08883] as const
20
+ const f = (t: number) => (t > 216 / 24389 ? Math.cbrt(t) : (24389 / 27) * t / 116 + 16 / 116)
21
+ const fInv = (t: number) => (t ** 3 > 216 / 24389 ? t ** 3 : (116 * t - 16) / (24389 / 27))
22
+ const toByte = (c: number) => {
23
+ const s = c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055
24
+ return Math.max(0, Math.min(255, Math.round(s * 255)))
25
+ }
26
+
27
+ /** one sRGB pixel to Lab (D65) */
28
+ export function rgbToLab(r: number, g: number, b: number): [number, number, number] {
29
+ const R = LINEAR[r]!
30
+ const G = LINEAR[g]!
31
+ const B = LINEAR[b]!
32
+ const x = f((0.4124564 * R + 0.3575761 * G + 0.1804375 * B) / D65[0])
33
+ const y = f(0.2126729 * R + 0.7151522 * G + 0.072175 * B)
34
+ const z = f((0.0193339 * R + 0.119192 * G + 0.9503041 * B) / D65[2])
35
+ return [116 * y - 16, 500 * (x - y), 200 * (y - z)]
36
+ }
37
+
38
+ /** one Lab colour back to sRGB bytes */
39
+ export function labToRgb(L: number, a: number, b: number): [number, number, number] {
40
+ const fy = (L + 16) / 116
41
+ const X = D65[0] * fInv(fy + a / 500)
42
+ const Y = fInv(fy)
43
+ const Z = D65[2] * fInv(fy - b / 200)
44
+ return [
45
+ toByte(3.2404542 * X - 1.5371385 * Y - 0.4985314 * Z),
46
+ toByte(-0.969266 * X + 1.8760108 * Y + 0.041556 * Z),
47
+ toByte(0.0556434 * X - 0.2040259 * Y + 1.0572252 * Z),
48
+ ]
49
+ }
50
+
51
+ const HUE_BINS = 24
52
+ /** the chroma below which a pixel counts as grey */
53
+ const GREY = 1.5
54
+
55
+ /** a frame's palette: Lab mean and spread per channel, mean chroma, the chroma weighted hue histogram */
56
+ export type Palette = { mean: [number, number, number]; spread: [number, number, number]; chroma: number; hues: Float64Array }
57
+
58
+ export function paletteOf(rgb: Uint8Array): Palette {
59
+ const n = rgb.length / 3
60
+ const sum = [0, 0, 0]
61
+ const sq = [0, 0, 0]
62
+ let chroma = 0
63
+ const hues = new Float64Array(HUE_BINS)
64
+ for (let i = 0; i < n; i++) {
65
+ const lab = rgbToLab(rgb[i * 3]!, rgb[i * 3 + 1]!, rgb[i * 3 + 2]!)
66
+ for (let c = 0; c < 3; c++) {
67
+ const x = lab[c]!
68
+ sum[c]! += x
69
+ sq[c]! += x * x
70
+ }
71
+ const C = Math.hypot(lab[1], lab[2])
72
+ chroma += C
73
+ // a near grey pixel's hue is noise (compression, the VAE): only the chroma past that counts,
74
+ // shared between the two nearest bins so a hue on a bin's edge does not flip the distance
75
+ const w = Math.max(0, C - GREY)
76
+ if (w === 0) continue
77
+ const h = ((Math.atan2(lab[2], lab[1]) + Math.PI) / (2 * Math.PI)) * HUE_BINS - 0.5
78
+ const lo = Math.floor(h)
79
+ const t = h - lo
80
+ hues[(lo + HUE_BINS) % HUE_BINS]! += w * (1 - t)
81
+ hues[(lo + 1) % HUE_BINS]! += w * t
82
+ }
83
+ // and smoothed once over the circle (1, 2, 1): a few degrees of turn is a small distance
84
+ const soft = hues.map((x, k) => x * 2 + hues[(k + HUE_BINS - 1) % HUE_BINS]! + hues[(k + 1) % HUE_BINS]!)
85
+ const total = soft.reduce((a, b) => a + b, 0) || 1
86
+ for (let k = 0; k < HUE_BINS; k++) hues[k] = soft[k]! / total
87
+ const mean = sum.map((s) => s / n) as [number, number, number]
88
+ const spread = sq.map((s, c) => Math.sqrt(Math.max(0, s / n - mean[c]! ** 2))) as [number, number, number]
89
+ return { mean, spread, chroma: chroma / n, hues }
90
+ }
91
+
92
+ /** a frame's drift from the picture, each in its own unit */
93
+ export type Drift = {
94
+ /** ΔE (CIE76) between the two mean colours */
95
+ dE: number
96
+ /** lightness of the mean, frame minus picture (positive: brighter) */
97
+ dL: number
98
+ /** the green (−) to red (+) axis of the mean */
99
+ da: number
100
+ /** the blue (−) to yellow (+) axis of the mean */
101
+ db: number
102
+ /** the frame's lightness spread over the picture's (above 1: more contrast) */
103
+ contrast: number
104
+ /** the frame's mean chroma over the picture's (above 1: more saturated) */
105
+ saturation: number
106
+ /** Hellinger distance of the hue histograms, 0 = the same hues, 1 = none shared */
107
+ hue: number
108
+ }
109
+
110
+ export function driftOf(frame: Palette, picture: Palette): Drift {
111
+ let bc = 0
112
+ for (let k = 0; k < HUE_BINS; k++) bc += Math.sqrt(frame.hues[k]! * picture.hues[k]!)
113
+ const d = frame.mean.map((m, c) => m - picture.mean[c]!) as [number, number, number]
114
+ return {
115
+ dE: Math.hypot(...d),
116
+ dL: d[0],
117
+ da: d[1],
118
+ db: d[2],
119
+ contrast: frame.spread[0] / Math.max(picture.spread[0], 1e-6),
120
+ saturation: frame.chroma / Math.max(picture.chroma, 1e-6),
121
+ hue: Math.sqrt(Math.max(0, 1 - bc)),
122
+ }
123
+ }
124
+
125
+ /** palettes smoothed over time: a gaussian of `sigma` frames over each mean and spread */
126
+ export function smoothPalettes(list: Palette[], sigma: number): Palette[] {
127
+ const r = Math.ceil(sigma * 3)
128
+ return list.map((_, i) => {
129
+ const mean = [0, 0, 0]
130
+ const spread = [0, 0, 0]
131
+ let w = 0
132
+ for (let j = Math.max(0, i - r); j <= Math.min(list.length - 1, i + r); j++) {
133
+ const k = Math.exp(-((j - i) ** 2) / (2 * sigma * sigma))
134
+ for (let c = 0; c < 3; c++) {
135
+ mean[c]! += k * list[j]!.mean[c]!
136
+ spread[c]! += k * list[j]!.spread[c]!
137
+ }
138
+ w += k
139
+ }
140
+ const own = list[i]!
141
+ return { ...own, mean: mean.map((x) => x / w) as Palette['mean'], spread: spread.map((x) => x / w) as Palette['spread'] }
142
+ })
143
+ }
144
+
145
+ /** the frame moved toward the picture's Lab mean and spread, per channel, `strength` of the way
146
+ * (1 = all of it); the spread gain stays within 0.5 to 2, so a frame of one material is not blown up */
147
+ export function matchFrame(rgb: Uint8Array, from: Palette, to: Palette, strength: number): Uint8Array {
148
+ const gain = [0, 1, 2].map((c) => Math.min(2, Math.max(0.5, to.spread[c]! / Math.max(from.spread[c]!, 1e-6))))
149
+ const out = new Uint8Array(rgb.length)
150
+ for (let i = 0; i < rgb.length; i += 3) {
151
+ const lab = rgbToLab(rgb[i]!, rgb[i + 1]!, rgb[i + 2]!)
152
+ const moved = lab.map((x, c) => {
153
+ const matched = (x - from.mean[c]!) * gain[c]! + to.mean[c]!
154
+ return x + (matched - x) * strength
155
+ }) as [number, number, number]
156
+ const back = labToRgb(moved[0], moved[1], moved[2])
157
+ out[i] = back[0]
158
+ out[i + 1] = back[1]
159
+ out[i + 2] = back[2]
160
+ }
161
+ return out
162
+ }
163
+
164
+ /** a picture cover-cropped to `width` × `height`, as raw rgb */
165
+ export async function pictureAt(picture: string, width: number, height: number): Promise<Uint8Array> {
166
+ return new Uint8Array(await sharp(picture).removeAlpha().resize(width, height, { fit: 'cover' }).raw().toBuffer())
167
+ }
168
+
169
+ /** a video's width and height */
170
+ export async function videoSize(file: string): Promise<{ width: number; height: number }> {
171
+ const out = await $`ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of csv=p=0 ${file}`.text()
172
+ const [width, height] = out.trim().split(',').map(Number) as [number, number]
173
+ return { width, height }
174
+ }
175
+
176
+ /** every frame of a video, `width` × `height` rgb, streamed to `each` */
177
+ export async function eachFrame(file: string, width: number, height: number, each: (rgb: Uint8Array, i: number) => void | Promise<void>): Promise<number> {
178
+ const proc = Bun.spawn(['ffmpeg', '-loglevel', 'error', '-i', file, '-vf', `scale=${width}:${height}`, '-pix_fmt', 'rgb24', '-f', 'rawvideo', '-'], { stdout: 'pipe' })
179
+ const size = width * height * 3
180
+ let buf = new Uint8Array(size)
181
+ let fill = 0
182
+ let i = 0
183
+ for await (const chunk of proc.stdout) {
184
+ let off = 0
185
+ while (off < chunk.length) {
186
+ const take = Math.min(size - fill, chunk.length - off)
187
+ buf.set(chunk.subarray(off, off + take), fill)
188
+ fill += take
189
+ off += take
190
+ if (fill === size) {
191
+ await each(buf, i++)
192
+ buf = new Uint8Array(size)
193
+ fill = 0
194
+ }
195
+ }
196
+ }
197
+ if ((await proc.exited) !== 0) throw new Error(`eachFrame: ffmpeg failed on ${file}`)
198
+ return i
199
+ }
200
+
201
+ /** the drift of every frame of a video from the picture, measured at a small size */
202
+ export async function measureVideo(picture: string, file: string): Promise<Drift[]> {
203
+ const size = await videoSize(file)
204
+ const width = 192
205
+ const height = Math.round((size.height / size.width) * width / 2) * 2
206
+ const ref = paletteOf(await pictureAt(picture, width, height))
207
+ const out: Drift[] = []
208
+ await eachFrame(file, width, height, (rgb) => void out.push(driftOf(paletteOf(rgb), ref)))
209
+ return out
210
+ }
211
+
212
+ /** every frame of a video matched to the picture (its stats smoothed over a sixth of a second: wider, a drifting start pulls frame 0 off the picture), into an mp4 at its fps */
213
+ export async function matchVideo(p: { picture: string; input: string; output: string; strength: number }): Promise<void> {
214
+ const size = await videoSize(p.input)
215
+ const fps = (await $`ffprobe -v error -select_streams v:0 -show_entries stream=r_frame_rate -of csv=p=0 ${p.input}`.text()).trim()
216
+ const small = { width: 192, height: Math.round((size.height / size.width) * 96) * 2 }
217
+ const ref = paletteOf(await pictureAt(p.picture, small.width, small.height))
218
+ const own: Palette[] = []
219
+ await eachFrame(p.input, small.width, small.height, (rgb) => void own.push(paletteOf(rgb)))
220
+ const fpsValue = fps.split('/').map(Number).reduce((a, b) => a / b)
221
+ const smooth = smoothPalettes(own, fpsValue / 6)
222
+ const enc = Bun.spawn(
223
+ ['ffmpeg', '-loglevel', 'error', '-y', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-s', `${size.width}x${size.height}`, '-r', fps, '-i', '-', '-c:v', 'libx264', '-crf', '12', '-pix_fmt', 'yuv420p', p.output],
224
+ { stdin: 'pipe' },
225
+ )
226
+ await eachFrame(p.input, size.width, size.height, (rgb, i) => {
227
+ const from = smooth[i]
228
+ if (from == null) throw new Error(`matchVideo: frame ${i} was not measured`)
229
+ enc.stdin.write(matchFrame(rgb, from, ref, p.strength))
230
+ })
231
+ await enc.stdin.end()
232
+ if ((await enc.exited) !== 0) throw new Error(`matchVideo: the encoder failed on ${p.output}`)
233
+ }
234
+
235
+ /** the drift curves of several videos as one picture: a panel per measure, a line per video */
236
+ export async function driftChart(series: { label: string; drift: Drift[] }[], out: string): Promise<void> {
237
+ const panels: { key: keyof Drift; title: string; lo: number; hi: number; mark?: number }[] = [
238
+ { key: 'dE', title: 'ΔE of the mean colour (0 = the picture)', lo: 0, hi: 20 },
239
+ { key: 'dL', title: 'lightness of the mean, against the picture', lo: -25, hi: 25, mark: 0 },
240
+ { key: 'saturation', title: 'saturation, against the picture (1 = the same)', lo: 0, hi: 3, mark: 1 },
241
+ { key: 'contrast', title: 'contrast, against the picture (1 = the same)', lo: 0, hi: 3, mark: 1 },
242
+ { key: 'hue', title: 'hue histogram distance (0 = the same hues)', lo: 0, hi: 0.6 },
243
+ { key: 'da', title: 'green (−) to red (+), against the picture', lo: -8, hi: 8, mark: 0 },
244
+ { key: 'db', title: 'blue (−) to yellow (+), against the picture', lo: -8, hi: 8, mark: 0 },
245
+ ]
246
+ const colours = ['#e6550d', '#3182bd', '#31a354', '#756bb1', '#d6616b', '#8c6d31', '#17becf']
247
+ const W = 520
248
+ const H = 190
249
+ const pad = { l: 44, r: 12, t: 26, b: 20 }
250
+ const cols = 2
251
+ const legend = 28
252
+ const width = W * cols
253
+ const height = legend + H * Math.ceil(panels.length / cols)
254
+ const frames = Math.max(...series.map((s) => s.drift.length), 2)
255
+ const parts: string[] = [`<rect width="${width}" height="${height}" fill="#ffffff"/>`]
256
+ series.forEach((s, i) => {
257
+ const x = 12 + i * 170
258
+ parts.push(`<rect x="${x}" y="9" width="14" height="4" fill="${colours[i % colours.length]}"/><text x="${x + 20}" y="16" font-size="13" font-family="Helvetica" fill="#222">${s.label}</text>`)
259
+ })
260
+ panels.forEach((panel, k) => {
261
+ const ox = (k % cols) * W
262
+ const oy = legend + Math.floor(k / cols) * H
263
+ const pw = W - pad.l - pad.r
264
+ const ph = H - pad.t - pad.b
265
+ const X = (i: number) => ox + pad.l + (i / (frames - 1)) * pw
266
+ const Y = (v: number) => oy + pad.t + (1 - (Math.max(panel.lo, Math.min(panel.hi, v)) - panel.lo) / (panel.hi - panel.lo)) * ph
267
+ parts.push(`<text x="${ox + pad.l}" y="${oy + 16}" font-size="13" font-family="Helvetica" fill="#222">${panel.title}</text>`)
268
+ parts.push(`<rect x="${ox + pad.l}" y="${oy + pad.t}" width="${pw}" height="${ph}" fill="none" stroke="#ccc"/>`)
269
+ for (const v of [panel.lo, panel.hi]) parts.push(`<text x="${ox + pad.l - 4}" y="${Y(v) + 4}" font-size="11" text-anchor="end" font-family="Helvetica" fill="#666">${v}</text>`)
270
+ if (panel.mark != null) parts.push(`<line x1="${X(0)}" x2="${X(frames - 1)}" y1="${Y(panel.mark)}" y2="${Y(panel.mark)}" stroke="#999" stroke-dasharray="3 3"/>`)
271
+ series.forEach((s, i) => {
272
+ const d = s.drift.map((x, j) => `${j === 0 ? 'M' : 'L'}${X(j).toFixed(1)},${Y(x[panel.key]).toFixed(1)}`).join('')
273
+ parts.push(`<path d="${d}" fill="none" stroke="${colours[i % colours.length]}" stroke-width="1.6"/>`)
274
+ })
275
+ })
276
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}">${parts.join('')}</svg>`
277
+ await sharp(Buffer.from(svg)).png().toFile(out)
278
+ }
279
+
280
+ /** one line per video: the mean of each measure over its frames, and its worst ΔE */
281
+ export function driftSummary(label: string, drift: Drift[]): string {
282
+ const avg = (k: keyof Drift) => drift.reduce((a, d) => a + d[k], 0) / Math.max(drift.length, 1)
283
+ const worst = Math.max(...drift.map((d) => d.dE))
284
+ return `${label}: ΔE ${avg('dE').toFixed(1)} (worst ${worst.toFixed(1)}), L ${avg('dL').toFixed(1)}, a ${avg('da').toFixed(1)}, b ${avg('db').toFixed(1)}, contrast ${avg('contrast').toFixed(2)}, saturation ${avg('saturation').toFixed(2)}, hue ${avg('hue').toFixed(3)}`
285
+ }
286
+
287
+ if (import.meta.main) {
288
+ const [mode, picture, ...rest] = process.argv.slice(2)
289
+ if (mode === 'measure' && picture != null && rest.length >= 2) {
290
+ const [out, ...pairs] = rest
291
+ const series: { label: string; drift: Drift[] }[] = []
292
+ for (const pair of pairs) {
293
+ const at = pair.indexOf('=')
294
+ const label = at < 0 ? pair : pair.slice(0, at)
295
+ const drift = await measureVideo(picture, at < 0 ? pair : pair.slice(at + 1))
296
+ series.push({ label, drift })
297
+ console.log(driftSummary(label, drift))
298
+ }
299
+ await driftChart(series, out!)
300
+ writeFileSync(`${out}.json`, JSON.stringify(series.map((s) => ({ label: s.label, summary: driftSummary(s.label, s.drift), drift: s.drift }))))
301
+ console.log(`🟢 ${out}`)
302
+ } else if (mode === 'match' && picture != null && rest.length >= 2) {
303
+ const [input, output, strength] = rest
304
+ await matchVideo({ picture, input: input!, output: output!, strength: Number(strength ?? 1) })
305
+ console.log(`🟢 ${output}`)
306
+ } else
307
+ throw new Error(
308
+ 'usage: bun examples/rvion/flythroughPalette.ts measure <picture> <out.png> <label>=<video> … | match <picture> <in.mp4> <out.mp4> [strength]',
309
+ )
310
+ }