retakes-cli 0.0.0-stage → 0.1.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.
- package/LICENSE +75 -0
- package/README.md +48 -2
- package/bin/retake.js +4 -0
- package/package.json +42 -4
- package/skills/retakes/SKILL.md +72 -0
- package/skills/retakes-match/SKILL.md +53 -0
- package/skills/retakes-recreate/SKILL.md +74 -0
- package/skills/retakes-watch/SKILL.md +64 -0
- package/src/adapters/generic.js +18 -0
- package/src/adapters/hyperframes.js +50 -0
- package/src/adapters/index.js +61 -0
- package/src/adapters/locate.js +7 -0
- package/src/adapters/remotion.js +28 -0
- package/src/brand.js +12 -0
- package/src/cli.js +70 -0
- package/src/commands/local.js +253 -0
- package/src/commands/remote.js +387 -0
- package/src/commands/skill.js +53 -0
- package/src/commands/video.js +120 -0
- package/src/diff.js +92 -0
- package/src/ignore.js +48 -0
- package/src/media.js +71 -0
- package/src/remote.js +120 -0
- package/src/snapshot.js +95 -0
- package/src/store.js +132 -0
- package/src/util.js +136 -0
- package/src/video/analyze.js +204 -0
- package/src/video/audio.js +180 -0
- package/src/video/ff.js +87 -0
- package/src/video/frames.js +112 -0
- package/src/video/match.js +287 -0
- package/src/video/pack.js +259 -0
- package/src/video/sheets.js +161 -0
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import { COL_FPS, COL_H, COL_W, corr, frame, hist, histDist, mad, meanLuma } from "./frames.js";
|
|
2
|
+
|
|
3
|
+
const median = (arr) => {
|
|
4
|
+
if (!arr.length) return 0;
|
|
5
|
+
const s = [...arr].sort((a, b) => a - b);
|
|
6
|
+
return s[s.length >> 1];
|
|
7
|
+
};
|
|
8
|
+
const round = (x, p = 3) => Math.round(x * 10 ** p) / 10 ** p;
|
|
9
|
+
|
|
10
|
+
// Frame-to-frame change: how much the picture moves, 0..255 per frame.
|
|
11
|
+
export function motionCurve(fr) {
|
|
12
|
+
const d = new Float32Array(fr.count);
|
|
13
|
+
for (let i = 1; i < fr.count; i++) d[i] = mad(frame(fr, i - 1), frame(fr, i));
|
|
14
|
+
return d;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// Scene boundaries: hard cuts (one-frame jumps) and gradual transitions (dissolves, wipes,
|
|
18
|
+
// fades, animated handoffs) found as prominent changes over ~0.3 s that no hard cut explains.
|
|
19
|
+
export function detectCuts(fr, d) {
|
|
20
|
+
const n = fr.count;
|
|
21
|
+
const fps = fr.fps;
|
|
22
|
+
const W = Math.max(3, Math.round(fps / 2));
|
|
23
|
+
const hists = Array.from({ length: n }, (_, i) => hist(frame(fr, i)));
|
|
24
|
+
const cuts = [];
|
|
25
|
+
|
|
26
|
+
for (let i = 1; i < n; i++) {
|
|
27
|
+
const around = [];
|
|
28
|
+
for (let k = Math.max(1, i - W); k <= Math.min(n - 1, i + W); k++) if (Math.abs(k - i) > 1) around.push(d[k]);
|
|
29
|
+
const local = median(around);
|
|
30
|
+
const hd = histDist(hists[i - 1], hists[i]);
|
|
31
|
+
const layout = corr(frame(fr, i - 1), frame(fr, i));
|
|
32
|
+
const jump = d[i] > 10 && d[i] > 4 * local + 5;
|
|
33
|
+
if ((jump && (hd > 0.1 || layout < 0.6)) || (hd > 0.45 && d[i] > 18)) cuts.push({ frame: i, kind: "cut", strength: d[i], frames: 1 });
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const k = Math.max(3, Math.round(fps * 0.3));
|
|
37
|
+
const G = new Float32Array(n);
|
|
38
|
+
for (let i = k; i < n; i++) G[i] = mad(frame(fr, i - k), frame(fr, i));
|
|
39
|
+
for (let i = k; i < n; i++) {
|
|
40
|
+
if (G[i] < 22) continue;
|
|
41
|
+
let isPeak = true;
|
|
42
|
+
for (let j = Math.max(k, i - k); j <= Math.min(n - 1, i + k); j++) if (G[j] > G[i]) isPeak = false;
|
|
43
|
+
if (!isPeak) continue;
|
|
44
|
+
const win = [];
|
|
45
|
+
for (let j = Math.max(k, i - Math.round(fps)); j <= Math.min(n - 1, i + Math.round(fps)); j++) win.push(G[j]);
|
|
46
|
+
if (G[i] < 1.5 * median(win)) continue;
|
|
47
|
+
if (corr(frame(fr, i - k), frame(fr, i)) > 0.45 && histDist(hists[i - k], hists[i]) < 0.25) continue;
|
|
48
|
+
if (cuts.some((c) => Math.abs(c.frame - (i - (k >> 1))) <= k)) continue;
|
|
49
|
+
// Extent: where frame-to-frame change stays raised around the peak.
|
|
50
|
+
const base = median(win.map((_, idx) => d[Math.max(1, Math.min(n - 1, i - Math.round(fps) + idx))])) * 1.5 + 0.8;
|
|
51
|
+
let a = i - k;
|
|
52
|
+
let b = i;
|
|
53
|
+
while (a > 1 && d[a] > base) a--;
|
|
54
|
+
while (b < n - 1 && d[b + 1] > base) b++;
|
|
55
|
+
cuts.push({ frame: Math.round((a + b) / 2), kind: "transition", strength: G[i], frames: Math.max(2, b - a), from: a, to: b });
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
cuts.sort((x, y) => x.frame - y.frame);
|
|
59
|
+
const minGap = Math.round(fps * 0.25);
|
|
60
|
+
const out = [];
|
|
61
|
+
for (const c of cuts) {
|
|
62
|
+
const last = out[out.length - 1];
|
|
63
|
+
if (last && c.frame - last.frame < minGap) {
|
|
64
|
+
if (c.strength > last.strength) out[out.length - 1] = c;
|
|
65
|
+
} else out.push(c);
|
|
66
|
+
}
|
|
67
|
+
return out.filter((c) => c.frame > minGap && c.frame < n - minGap);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function classify(fr, c) {
|
|
71
|
+
if (c.kind === "cut") return "cut";
|
|
72
|
+
let lo = 255;
|
|
73
|
+
let hi = 0;
|
|
74
|
+
for (let j = c.from; j <= c.to; j++) {
|
|
75
|
+
const l = meanLuma(frame(fr, j));
|
|
76
|
+
lo = Math.min(lo, l);
|
|
77
|
+
hi = Math.max(hi, l);
|
|
78
|
+
}
|
|
79
|
+
if (lo < 14) return `fade through black (${c.frames}f)`;
|
|
80
|
+
if (hi > 242) return `fade through white (${c.frames}f)`;
|
|
81
|
+
return `transition (${c.frames}f)`;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function motionLabel(m) {
|
|
85
|
+
if (m < 0.4) return "still";
|
|
86
|
+
if (m < 1.5) return "low";
|
|
87
|
+
if (m < 4.5) return "medium";
|
|
88
|
+
return "high";
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function palette(fr, t0, t1, max = 5) {
|
|
92
|
+
const px = COL_W * COL_H;
|
|
93
|
+
const a = Math.max(0, Math.floor(t0 * COL_FPS));
|
|
94
|
+
const b = Math.min(fr.colorCount, Math.max(a + 1, Math.ceil(t1 * COL_FPS)));
|
|
95
|
+
const bins = new Map();
|
|
96
|
+
let total = 0;
|
|
97
|
+
for (let f = a; f < b; f++) {
|
|
98
|
+
const base = f * px * 3;
|
|
99
|
+
for (let p = 0; p < px; p++) {
|
|
100
|
+
const r = fr.color[base + p * 3];
|
|
101
|
+
const g = fr.color[base + p * 3 + 1];
|
|
102
|
+
const bl = fr.color[base + p * 3 + 2];
|
|
103
|
+
const key = ((r >> 4) << 8) | ((g >> 4) << 4) | (bl >> 4);
|
|
104
|
+
const e = bins.get(key) ?? { n: 0, r: 0, g: 0, b: 0 };
|
|
105
|
+
e.n++;
|
|
106
|
+
e.r += r;
|
|
107
|
+
e.g += g;
|
|
108
|
+
e.b += bl;
|
|
109
|
+
bins.set(key, e);
|
|
110
|
+
total++;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
const sorted = [...bins.values()].sort((x, y) => y.n - x.n).map((e) => ({ r: e.r / e.n, g: e.g / e.n, b: e.b / e.n, n: e.n }));
|
|
114
|
+
const picked = [];
|
|
115
|
+
for (const c of sorted) {
|
|
116
|
+
const near = picked.find((p) => Math.hypot(p.r - c.r, p.g - c.g, p.b - c.b) < 48);
|
|
117
|
+
if (near) near.n += c.n;
|
|
118
|
+
else picked.push({ ...c });
|
|
119
|
+
if (picked.length >= max * 3) break;
|
|
120
|
+
}
|
|
121
|
+
const hex = (v) => Math.round(v).toString(16).padStart(2, "0");
|
|
122
|
+
return picked
|
|
123
|
+
.sort((x, y) => y.n - x.n)
|
|
124
|
+
.slice(0, max)
|
|
125
|
+
.map((p) => ({ hex: `#${hex(p.r)}${hex(p.g)}${hex(p.b)}`, share: round(p.n / Math.max(1, total), 2) }));
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Resample a curve to n points (motion profiles of scenes with different lengths).
|
|
129
|
+
export function resample(arr, n) {
|
|
130
|
+
const out = new Float32Array(n);
|
|
131
|
+
if (!arr.length) return out;
|
|
132
|
+
for (let i = 0; i < n; i++) {
|
|
133
|
+
const x = (i / Math.max(1, n - 1)) * (arr.length - 1);
|
|
134
|
+
const i0 = Math.floor(x);
|
|
135
|
+
const i1 = Math.min(arr.length - 1, i0 + 1);
|
|
136
|
+
out[i] = arr[i0] + (arr[i1] - arr[i0]) * (x - i0);
|
|
137
|
+
}
|
|
138
|
+
return out;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function scenesOf(fr, d, duration) {
|
|
142
|
+
const cuts = detectCuts(fr, d);
|
|
143
|
+
const fps = fr.fps;
|
|
144
|
+
const bounds = [0, ...cuts.map((c) => c.frame), fr.count];
|
|
145
|
+
const scenes = [];
|
|
146
|
+
for (let s = 0; s < bounds.length - 1; s++) {
|
|
147
|
+
const f0 = bounds[s];
|
|
148
|
+
const f1 = bounds[s + 1];
|
|
149
|
+
const t0 = f0 / fps;
|
|
150
|
+
const t1 = s === bounds.length - 2 ? Math.max(f1 / fps, duration || 0) : f1 / fps;
|
|
151
|
+
const inner = [];
|
|
152
|
+
for (let i = f0 + 2; i < f1 - 1; i++) inner.push(d[i]);
|
|
153
|
+
const m = inner.length ? inner.reduce((x, y) => x + y, 0) / inner.length : 0;
|
|
154
|
+
let lum = 0;
|
|
155
|
+
for (let i = f0; i < f1; i += Math.max(1, Math.round(fps / 4))) lum += meanLuma(frame(fr, i));
|
|
156
|
+
lum /= Math.max(1, Math.ceil((f1 - f0) / Math.max(1, Math.round(fps / 4))));
|
|
157
|
+
scenes.push({
|
|
158
|
+
index: s + 1,
|
|
159
|
+
start: round(t0),
|
|
160
|
+
end: round(t1),
|
|
161
|
+
duration: round(t1 - t0),
|
|
162
|
+
startFrame: f0,
|
|
163
|
+
endFrame: f1,
|
|
164
|
+
in: s === 0 ? "start" : classify(fr, cuts[s - 1]),
|
|
165
|
+
motion: round(m, 2),
|
|
166
|
+
motionLabel: motionLabel(m),
|
|
167
|
+
luma: Math.round(lum),
|
|
168
|
+
palette: palette(fr, t0, t1),
|
|
169
|
+
profile: [...resample(inner, 24)].map((x) => round(x, 2)),
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
return { cuts, scenes };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// The busiest moments that aren't cuts: where to look frame by frame for easing and timing.
|
|
176
|
+
export function motionPeaks(fr, d, cuts, max = 6) {
|
|
177
|
+
const fps = fr.fps;
|
|
178
|
+
const med = median([...d].filter((x) => x > 0)) || 0.5;
|
|
179
|
+
const peaks = [];
|
|
180
|
+
const W = Math.round(fps * 0.4);
|
|
181
|
+
for (let i = 2; i < fr.count - 2; i++) {
|
|
182
|
+
if (d[i] < Math.max(3, med * 3)) continue;
|
|
183
|
+
let top = true;
|
|
184
|
+
for (let j = Math.max(1, i - W); j <= Math.min(fr.count - 1, i + W); j++) if (d[j] > d[i]) top = false;
|
|
185
|
+
if (!top || cuts.some((c) => Math.abs(c.frame - i) < W)) continue;
|
|
186
|
+
peaks.push({ frame: i, t: round(i / fps), strength: round(d[i], 2) });
|
|
187
|
+
}
|
|
188
|
+
return peaks.sort((a, b) => b.strength - a.strength).slice(0, max).sort((a, b) => a.frame - b.frame);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// Long still stretches (title holds, end cards): pacing information.
|
|
192
|
+
export function holds(fr, d, minSec = 0.6) {
|
|
193
|
+
const out = [];
|
|
194
|
+
let a = -1;
|
|
195
|
+
for (let i = 1; i <= fr.count; i++) {
|
|
196
|
+
const still = i < fr.count && d[i] < 0.25;
|
|
197
|
+
if (still && a < 0) a = i - 1;
|
|
198
|
+
if (!still && a >= 0) {
|
|
199
|
+
if ((i - a) / fr.fps >= minSec) out.push({ start: round(a / fr.fps), end: round(i / fr.fps) });
|
|
200
|
+
a = -1;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return out;
|
|
204
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { ffRead, ffStats } from "./ff.js";
|
|
3
|
+
|
|
4
|
+
const SR = 11025;
|
|
5
|
+
const WIN = 1024;
|
|
6
|
+
const HOP = 256;
|
|
7
|
+
const round = (x, p = 3) => Math.round(x * 10 ** p) / 10 ** p;
|
|
8
|
+
|
|
9
|
+
function fft(re, im) {
|
|
10
|
+
const n = re.length;
|
|
11
|
+
for (let i = 1, j = 0; i < n; i++) {
|
|
12
|
+
let bit = n >> 1;
|
|
13
|
+
for (; j & bit; bit >>= 1) j ^= bit;
|
|
14
|
+
j ^= bit;
|
|
15
|
+
if (i < j) {
|
|
16
|
+
[re[i], re[j]] = [re[j], re[i]];
|
|
17
|
+
[im[i], im[j]] = [im[j], im[i]];
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
for (let len = 2; len <= n; len <<= 1) {
|
|
21
|
+
const ang = (-2 * Math.PI) / len;
|
|
22
|
+
const wr = Math.cos(ang);
|
|
23
|
+
const wi = Math.sin(ang);
|
|
24
|
+
for (let i = 0; i < n; i += len) {
|
|
25
|
+
let cr = 1;
|
|
26
|
+
let ci = 0;
|
|
27
|
+
for (let k = 0; k < len / 2; k++) {
|
|
28
|
+
const ar = re[i + k];
|
|
29
|
+
const ai = im[i + k];
|
|
30
|
+
const br = re[i + k + len / 2] * cr - im[i + k + len / 2] * ci;
|
|
31
|
+
const bi = re[i + k + len / 2] * ci + im[i + k + len / 2] * cr;
|
|
32
|
+
re[i + k] = ar + br;
|
|
33
|
+
im[i + k] = ai + bi;
|
|
34
|
+
re[i + k + len / 2] = ar - br;
|
|
35
|
+
im[i + k + len / 2] = ai - bi;
|
|
36
|
+
const t = cr * wr - ci * wi;
|
|
37
|
+
ci = cr * wi + ci * wr;
|
|
38
|
+
cr = t;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export async function decodeAudio(video) {
|
|
45
|
+
try {
|
|
46
|
+
const buf = await ffRead(["-i", video, "-vn", "-ac", "1", "-ar", String(SR), "-f", "s16le", "-"]);
|
|
47
|
+
if (buf.length < SR) return null;
|
|
48
|
+
const pcm = new Float32Array(buf.length >> 1);
|
|
49
|
+
for (let i = 0; i < pcm.length; i++) pcm[i] = buf.readInt16LE(i * 2) / 32768;
|
|
50
|
+
return pcm;
|
|
51
|
+
} catch {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Loudness as platforms measure it (EBU R128).
|
|
57
|
+
export function loudness(video) {
|
|
58
|
+
const err = ffStats(["-i", video, "-vn", "-af", "ebur128=peak=true"]);
|
|
59
|
+
const summary = err.slice(err.lastIndexOf("Summary:"));
|
|
60
|
+
const pick = (re) => {
|
|
61
|
+
const m = re.exec(summary);
|
|
62
|
+
return m ? Number(m[1]) : null;
|
|
63
|
+
};
|
|
64
|
+
return {
|
|
65
|
+
integratedLufs: pick(/I:\s+(-?[\d.]+) LUFS/),
|
|
66
|
+
lra: pick(/LRA:\s+(-?[\d.]+) LU/),
|
|
67
|
+
truePeakDbtp: pick(/Peak:\s+(-?[\d.]+) dBFS/),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function analyzeAudio(pcm, duration) {
|
|
72
|
+
const frames = Math.max(0, Math.floor((pcm.length - WIN) / HOP));
|
|
73
|
+
const hopSec = HOP / SR;
|
|
74
|
+
const energy = new Float32Array(frames);
|
|
75
|
+
const flux = new Float32Array(frames);
|
|
76
|
+
const re = new Float32Array(WIN);
|
|
77
|
+
const im = new Float32Array(WIN);
|
|
78
|
+
let prev = new Float32Array(WIN / 2);
|
|
79
|
+
const hann = Float32Array.from({ length: WIN }, (_, i) => 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / (WIN - 1)));
|
|
80
|
+
for (let f = 0; f < frames; f++) {
|
|
81
|
+
let e = 0;
|
|
82
|
+
for (let i = 0; i < WIN; i++) {
|
|
83
|
+
const x = pcm[f * HOP + i];
|
|
84
|
+
e += x * x;
|
|
85
|
+
re[i] = x * hann[i];
|
|
86
|
+
im[i] = 0;
|
|
87
|
+
}
|
|
88
|
+
energy[f] = 10 * Math.log10(e / WIN + 1e-10);
|
|
89
|
+
fft(re, im);
|
|
90
|
+
const mag = new Float32Array(WIN / 2);
|
|
91
|
+
let fl = 0;
|
|
92
|
+
for (let k = 1; k < WIN / 2; k++) {
|
|
93
|
+
mag[k] = Math.log1p(100 * Math.hypot(re[k], im[k]));
|
|
94
|
+
const diff = mag[k] - prev[k];
|
|
95
|
+
if (diff > 0) fl += diff;
|
|
96
|
+
}
|
|
97
|
+
flux[f] = fl;
|
|
98
|
+
prev = mag;
|
|
99
|
+
}
|
|
100
|
+
// Normalise onset strength.
|
|
101
|
+
let mx = 0;
|
|
102
|
+
for (const v of flux) mx = Math.max(mx, v);
|
|
103
|
+
const onset = flux.map((v) => (mx ? v / mx : 0));
|
|
104
|
+
const mean = onset.reduce((a, b) => a + b, 0) / Math.max(1, onset.length);
|
|
105
|
+
|
|
106
|
+
// Tempo: autocorrelation of the onset envelope between 60 and 190 BPM, biased toward 120.
|
|
107
|
+
let best = { bpm: null, score: -Infinity, lag: 0 };
|
|
108
|
+
const minLag = Math.round(60 / 190 / hopSec);
|
|
109
|
+
const maxLag = Math.round(60 / 60 / hopSec);
|
|
110
|
+
for (let lag = minLag; lag <= maxLag; lag++) {
|
|
111
|
+
let s = 0;
|
|
112
|
+
for (let i = lag; i < onset.length; i++) s += (onset[i] - mean) * (onset[i - lag] - mean);
|
|
113
|
+
const bpm = 60 / (lag * hopSec);
|
|
114
|
+
const w = Math.exp(-0.5 * (Math.log2(bpm / 120) / 0.9) ** 2);
|
|
115
|
+
if (s * w > best.score) best = { bpm, score: s * w, lag };
|
|
116
|
+
}
|
|
117
|
+
let beats = [];
|
|
118
|
+
let bpm = null;
|
|
119
|
+
if (best.lag && best.score > 0) {
|
|
120
|
+
bpm = round(best.bpm, 1);
|
|
121
|
+
const period = best.lag;
|
|
122
|
+
let bestPhase = 0;
|
|
123
|
+
let bestSum = -1;
|
|
124
|
+
for (let ph = 0; ph < period; ph++) {
|
|
125
|
+
let s = 0;
|
|
126
|
+
for (let i = ph; i < onset.length; i += period) s += onset[i];
|
|
127
|
+
if (s > bestSum) {
|
|
128
|
+
bestSum = s;
|
|
129
|
+
bestPhase = ph;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
// Let each beat snap to the strongest onset within ±10% of the period.
|
|
133
|
+
for (let i = bestPhase; i < onset.length; i += period) {
|
|
134
|
+
let j = i;
|
|
135
|
+
const r = Math.max(1, Math.round(period * 0.1));
|
|
136
|
+
for (let k = Math.max(0, i - r); k <= Math.min(onset.length - 1, i + r); k++) if (onset[k] > onset[j]) j = k;
|
|
137
|
+
beats.push(round(j * hopSec + WIN / 2 / SR));
|
|
138
|
+
}
|
|
139
|
+
beats = beats.filter((t) => t <= (duration || Infinity));
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Hits: strong onsets (impacts, whooshes, drum hits) — the moments SFX and cuts tend to sit on.
|
|
143
|
+
const hits = [];
|
|
144
|
+
const W = Math.round(0.12 / hopSec);
|
|
145
|
+
for (let i = 1; i < onset.length - 1; i++) {
|
|
146
|
+
if (onset[i] < 0.35) continue;
|
|
147
|
+
let top = true;
|
|
148
|
+
for (let k = Math.max(0, i - W); k <= Math.min(onset.length - 1, i + W); k++) if (onset[k] > onset[i]) top = false;
|
|
149
|
+
if (top) hits.push({ t: round(i * hopSec + WIN / 2 / SR), strength: round(onset[i], 2) });
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Silences below -45 dBFS for at least 0.3 s.
|
|
153
|
+
const silences = [];
|
|
154
|
+
let a = -1;
|
|
155
|
+
for (let f = 0; f <= frames; f++) {
|
|
156
|
+
const quiet = f < frames && energy[f] < -45;
|
|
157
|
+
if (quiet && a < 0) a = f;
|
|
158
|
+
if (!quiet && a >= 0) {
|
|
159
|
+
if ((f - a) * hopSec >= 0.3) silences.push({ start: round(a * hopSec), end: round(f * hopSec) });
|
|
160
|
+
a = -1;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
// Energy envelope at 20 Hz for the timeline image.
|
|
164
|
+
const step = Math.max(1, Math.round(0.05 / hopSec));
|
|
165
|
+
const envelope = [];
|
|
166
|
+
for (let f = 0; f < frames; f += step) {
|
|
167
|
+
let m = -100;
|
|
168
|
+
for (let k = f; k < Math.min(frames, f + step); k++) m = Math.max(m, energy[k]);
|
|
169
|
+
envelope.push(round(m, 1));
|
|
170
|
+
}
|
|
171
|
+
return { bpm, beats, hits, silences, envelope, envelopeHz: round(1 / (step * hopSec), 2) };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// Optional transcript with a locally installed Whisper (openai-whisper CLI). Never calls an API.
|
|
175
|
+
export function localTranscript(video, outDir) {
|
|
176
|
+
const has = spawnSync(process.platform === "win32" ? "where" : "which", ["whisper"], { encoding: "utf8" });
|
|
177
|
+
if (has.status !== 0) return null;
|
|
178
|
+
const r = spawnSync("whisper", [video, "--model", "base", "--output_format", "srt", "--output_dir", outDir, "--fp16", "False"], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
|
|
179
|
+
return r.status === 0 ? "whisper" : null;
|
|
180
|
+
}
|
package/src/video/ff.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
4
|
+
import { fail } from "../util.js";
|
|
5
|
+
import { hasFfmpeg } from "../media.js";
|
|
6
|
+
|
|
7
|
+
export function needFfmpeg() {
|
|
8
|
+
if (!hasFfmpeg()) fail("ffmpeg and ffprobe must be on PATH for video analysis (https://ffmpeg.org/download.html).");
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// Run ffmpeg and collect stdout as one Buffer (raw frames, PCM).
|
|
12
|
+
export function ffRead(args) {
|
|
13
|
+
return new Promise((resolve, reject) => {
|
|
14
|
+
const p = spawn("ffmpeg", ["-hide_banner", "-loglevel", "error", ...args], { stdio: ["ignore", "pipe", "pipe"] });
|
|
15
|
+
const out = [];
|
|
16
|
+
let err = "";
|
|
17
|
+
p.stdout.on("data", (d) => out.push(d));
|
|
18
|
+
p.stderr.on("data", (d) => (err += d));
|
|
19
|
+
p.on("error", reject);
|
|
20
|
+
p.on("close", (code) => (code === 0 ? resolve(Buffer.concat(out)) : reject(new Error(`ffmpeg: ${err.trim().split("\n").pop()}`))));
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Run ffmpeg feeding a Buffer on stdin (raw RGB images we draw ourselves).
|
|
25
|
+
export function ffWrite(args, input) {
|
|
26
|
+
return new Promise((resolve, reject) => {
|
|
27
|
+
const p = spawn("ffmpeg", ["-hide_banner", "-loglevel", "error", "-y", ...args], { stdio: ["pipe", "ignore", "pipe"] });
|
|
28
|
+
let err = "";
|
|
29
|
+
p.stderr.on("data", (d) => (err += d));
|
|
30
|
+
p.on("error", reject);
|
|
31
|
+
p.on("close", (code) => (code === 0 ? resolve() : reject(new Error(`ffmpeg: ${err.trim().split("\n").pop()}`))));
|
|
32
|
+
p.stdin.end(input);
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function ffRun(args) {
|
|
37
|
+
const r = spawnSync("ffmpeg", ["-hide_banner", "-loglevel", "error", "-y", ...args], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
|
|
38
|
+
if (r.status !== 0) throw new Error(`ffmpeg: ${(r.stderr || "").trim().split("\n").pop()}`);
|
|
39
|
+
return r;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// stderr of a run whose output is discarded (filters that print stats, like ebur128).
|
|
43
|
+
export function ffStats(args) {
|
|
44
|
+
const r = spawnSync("ffmpeg", ["-hide_banner", "-nostats", ...args, "-f", "null", "-"], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
|
|
45
|
+
return r.stderr || "";
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// A font file for burned-in labels. ffmpeg's default font needs fontconfig, which many
|
|
49
|
+
// Windows builds lack, so point at a real file.
|
|
50
|
+
let fontCache;
|
|
51
|
+
export function labelFont() {
|
|
52
|
+
if (fontCache !== undefined) return fontCache;
|
|
53
|
+
const candidates = [
|
|
54
|
+
"C:/Windows/Fonts/consola.ttf",
|
|
55
|
+
"C:/Windows/Fonts/arial.ttf",
|
|
56
|
+
"/System/Library/Fonts/Menlo.ttc",
|
|
57
|
+
"/System/Library/Fonts/Supplemental/Arial.ttf",
|
|
58
|
+
"/Library/Fonts/Arial.ttf",
|
|
59
|
+
"/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf",
|
|
60
|
+
"/usr/share/fonts/TTF/DejaVuSansMono.ttf",
|
|
61
|
+
"/usr/share/fonts/dejavu/DejaVuSansMono.ttf",
|
|
62
|
+
"/usr/share/fonts/truetype/liberation/LiberationMono-Regular.ttf",
|
|
63
|
+
];
|
|
64
|
+
fontCache = candidates.find((f) => fs.existsSync(f)) ?? null;
|
|
65
|
+
return fontCache;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// drawtext filter (or nothing when no font is found). `text` may use ffmpeg expansions like %{pts}.
|
|
69
|
+
export function drawtext(text, { size = 18, x = "8", y = "8", box = true } = {}) {
|
|
70
|
+
const font = labelFont();
|
|
71
|
+
if (!font) return null;
|
|
72
|
+
const ff = font.replace(/\\/g, "/").replace(/:/g, "\\:");
|
|
73
|
+
return `drawtext=fontfile='${ff}':text='${text}':fontsize=${size}:fontcolor=white:x=${x}:y=${y}${box ? ":box=1:boxcolor=black@0.62:boxborderw=5" : ""}`;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export const esc = (s) => String(s).replace(/\\/g, "\\\\").replace(/'/g, "\u2019").replace(/:/g, "\\:").replace(/%/g, "\\%").replace(/,/g, "\\,");
|
|
77
|
+
|
|
78
|
+
export function ensureDir(d) {
|
|
79
|
+
fs.mkdirSync(d, { recursive: true });
|
|
80
|
+
return d;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function rmDir(d) {
|
|
84
|
+
fs.rmSync(d, { recursive: true, force: true });
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export const rel = (p) => path.relative(process.cwd(), p).split(path.sep).join("/") || ".";
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { ffRead } from "./ff.js";
|
|
4
|
+
|
|
5
|
+
// Tiny frames are the basis of every measurement: 64×36 grayscale at the analysis frame
|
|
6
|
+
// rate (cuts, motion, similarity) and 16×9 RGB at 4 fps (colour).
|
|
7
|
+
export const SIG_W = 64;
|
|
8
|
+
export const SIG_H = 36;
|
|
9
|
+
export const SIG_N = SIG_W * SIG_H;
|
|
10
|
+
export const COL_W = 16;
|
|
11
|
+
export const COL_H = 9;
|
|
12
|
+
export const COL_FPS = 4;
|
|
13
|
+
|
|
14
|
+
export function analysisFps(info) {
|
|
15
|
+
const f = info.fps || 30;
|
|
16
|
+
return f > 60 ? 30 : Math.round(f * 1000) / 1000;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async function cached(file, build) {
|
|
20
|
+
if (file && fs.existsSync(file)) return fs.readFileSync(file);
|
|
21
|
+
const buf = await build();
|
|
22
|
+
if (file) {
|
|
23
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
24
|
+
fs.writeFileSync(file, buf);
|
|
25
|
+
}
|
|
26
|
+
return buf;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export async function loadFrames(video, { fps, cacheDir, key }) {
|
|
30
|
+
const gray = await cached(cacheDir && path.join(cacheDir, `${key}-g${fps}.bin`), () =>
|
|
31
|
+
ffRead(["-i", video, "-an", "-vf", `fps=${fps},scale=${SIG_W}:${SIG_H}:flags=area,format=gray`, "-f", "rawvideo", "-"]),
|
|
32
|
+
);
|
|
33
|
+
const color = await cached(cacheDir && path.join(cacheDir, `${key}-c${COL_FPS}.bin`), () =>
|
|
34
|
+
ffRead(["-i", video, "-an", "-vf", `fps=${COL_FPS},scale=${COL_W}:${COL_H}:flags=area,format=rgb24`, "-f", "rawvideo", "-"]),
|
|
35
|
+
);
|
|
36
|
+
return {
|
|
37
|
+
fps,
|
|
38
|
+
gray,
|
|
39
|
+
count: Math.floor(gray.length / SIG_N),
|
|
40
|
+
color,
|
|
41
|
+
colorCount: Math.floor(color.length / (COL_W * COL_H * 3)),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export const frame = (fr, i) => fr.gray.subarray(i * SIG_N, (i + 1) * SIG_N);
|
|
46
|
+
|
|
47
|
+
// Mean absolute difference between two frames, 0..255.
|
|
48
|
+
export function mad(a, b) {
|
|
49
|
+
let s = 0;
|
|
50
|
+
for (let i = 0; i < a.length; i++) s += Math.abs(a[i] - b[i]);
|
|
51
|
+
return s / a.length;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function hist(f, bins = 16) {
|
|
55
|
+
const h = new Float32Array(bins);
|
|
56
|
+
const k = 256 / bins;
|
|
57
|
+
for (let i = 0; i < f.length; i++) h[(f[i] / k) | 0]++;
|
|
58
|
+
for (let i = 0; i < bins; i++) h[i] /= f.length;
|
|
59
|
+
return h;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Histogram distance 0..1 (half the L1 distance).
|
|
63
|
+
export function histDist(a, b) {
|
|
64
|
+
let s = 0;
|
|
65
|
+
for (let i = 0; i < a.length; i++) s += Math.abs(a[i] - b[i]);
|
|
66
|
+
return s / 2;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function meanLuma(f) {
|
|
70
|
+
let s = 0;
|
|
71
|
+
for (let i = 0; i < f.length; i++) s += f[i];
|
|
72
|
+
return s / f.length;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Pearson correlation of two equal-length arrays (layout similarity on 64×36 frames).
|
|
76
|
+
export function corr(a, b) {
|
|
77
|
+
const n = a.length;
|
|
78
|
+
let ma = 0;
|
|
79
|
+
let mb = 0;
|
|
80
|
+
for (let i = 0; i < n; i++) {
|
|
81
|
+
ma += a[i];
|
|
82
|
+
mb += b[i];
|
|
83
|
+
}
|
|
84
|
+
ma /= n;
|
|
85
|
+
mb /= n;
|
|
86
|
+
let sab = 0;
|
|
87
|
+
let saa = 0;
|
|
88
|
+
let sbb = 0;
|
|
89
|
+
for (let i = 0; i < n; i++) {
|
|
90
|
+
const x = a[i] - ma;
|
|
91
|
+
const y = b[i] - mb;
|
|
92
|
+
sab += x * y;
|
|
93
|
+
saa += x * x;
|
|
94
|
+
sbb += y * y;
|
|
95
|
+
}
|
|
96
|
+
if (saa < 1e-6 && sbb < 1e-6) return Math.abs(ma - mb) < 8 ? 1 : 0; // two flat frames
|
|
97
|
+
if (saa < 1e-6 || sbb < 1e-6) return 0;
|
|
98
|
+
return sab / Math.sqrt(saa * sbb);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// Small stable digest of a span of frames, to tell whether a scene changed between takes.
|
|
102
|
+
export function spanDigest(fr, i0, i1) {
|
|
103
|
+
let h = 2166136261;
|
|
104
|
+
for (let i = i0; i < i1; i += 2) {
|
|
105
|
+
const f = frame(fr, i);
|
|
106
|
+
for (let k = 0; k < f.length; k += 7) {
|
|
107
|
+
h ^= f[k] >> 3; // ignore tiny encoder noise
|
|
108
|
+
h = Math.imul(h, 16777619);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return (h >>> 0).toString(16);
|
|
112
|
+
}
|