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,287 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { corr, mad, SIG_W } from "./frames.js";
|
|
4
|
+
import { sceneSamples } from "./pack.js";
|
|
5
|
+
import { pairSheet } from "./sheets.js";
|
|
6
|
+
import { ensureDir, rel, rmDir } from "./ff.js";
|
|
7
|
+
import { fmtTime, readJsonSync, writeJsonSync } from "../util.js";
|
|
8
|
+
|
|
9
|
+
const round = (x, p = 2) => Math.round(x * 10 ** p) / 10 ** p;
|
|
10
|
+
const POS = [0.12, 0.31, 0.5, 0.69, 0.88];
|
|
11
|
+
|
|
12
|
+
function rgb(hex) {
|
|
13
|
+
const n = parseInt(hex.slice(1), 16);
|
|
14
|
+
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function colorScore(pa, pb) {
|
|
18
|
+
if (!pa.length || !pb.length) return 0.5;
|
|
19
|
+
let s = 0;
|
|
20
|
+
let w = 0;
|
|
21
|
+
for (const c of pa) {
|
|
22
|
+
const x = rgb(c.hex);
|
|
23
|
+
let best = Infinity;
|
|
24
|
+
for (const d of pb) best = Math.min(best, Math.hypot(...x.map((v, i) => v - rgb(d.hex)[i])));
|
|
25
|
+
s += c.share * best;
|
|
26
|
+
w += c.share;
|
|
27
|
+
}
|
|
28
|
+
return Math.max(0, 1 - ((s / Math.max(w, 1e-6)) / 441) * 2.2);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function layoutScore(A, sa, B, sb) {
|
|
32
|
+
const fa = sceneSamples(A, sa, POS);
|
|
33
|
+
const fb = sceneSamples(B, sb, POS);
|
|
34
|
+
let s = 0;
|
|
35
|
+
for (let i = 0; i < POS.length; i++) s += Math.max(0, corr(fa[i], fb[i]));
|
|
36
|
+
return s / POS.length;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function contentDiff(A, sa, B, sb) {
|
|
40
|
+
const pos = Array.from({ length: 12 }, (_, i) => (i + 0.5) / 12);
|
|
41
|
+
const fa = sceneSamples(A, sa, pos);
|
|
42
|
+
const fb = sceneSamples(B, sb, pos);
|
|
43
|
+
let s = 0;
|
|
44
|
+
for (let i = 0; i < pos.length; i++) s += mad(fa[i], fb[i]);
|
|
45
|
+
return s / pos.length;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function motionScore(sa, sb) {
|
|
49
|
+
if (sa.motion < 0.4 && sb.motion < 0.4) return 1;
|
|
50
|
+
const n = sa.profile.length;
|
|
51
|
+
let ma = 0;
|
|
52
|
+
let mb = 0;
|
|
53
|
+
for (let i = 0; i < n; i++) {
|
|
54
|
+
ma += sa.profile[i];
|
|
55
|
+
mb += sb.profile[i];
|
|
56
|
+
}
|
|
57
|
+
ma /= n;
|
|
58
|
+
mb /= n;
|
|
59
|
+
let ab = 0;
|
|
60
|
+
let aa = 0;
|
|
61
|
+
let bb = 0;
|
|
62
|
+
for (let i = 0; i < n; i++) {
|
|
63
|
+
ab += (sa.profile[i] - ma) * (sb.profile[i] - mb);
|
|
64
|
+
aa += (sa.profile[i] - ma) ** 2;
|
|
65
|
+
bb += (sb.profile[i] - mb) ** 2;
|
|
66
|
+
}
|
|
67
|
+
const r = aa > 1e-6 && bb > 1e-6 ? ab / Math.sqrt(aa * bb) : 0;
|
|
68
|
+
const energy = Math.min(sa.motion, sb.motion) / Math.max(sa.motion, sb.motion, 1e-6);
|
|
69
|
+
return 0.6 * ((r + 1) / 2) + 0.4 * energy;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Pair up the shots of two videos (Needleman–Wunsch): handles added, dropped and split shots.
|
|
73
|
+
export function alignScenes(A, B) {
|
|
74
|
+
const R = A.scenes;
|
|
75
|
+
const C = B.scenes;
|
|
76
|
+
const m = R.length;
|
|
77
|
+
const n = C.length;
|
|
78
|
+
const sim = Array.from({ length: m }, (_, i) =>
|
|
79
|
+
Array.from({ length: n }, (_, j) => {
|
|
80
|
+
const dur = Math.min(R[i].duration, C[j].duration) / Math.max(R[i].duration, C[j].duration, 1e-6);
|
|
81
|
+
return 0.45 * layoutScore(A, R[i], B, C[j]) + 0.35 * dur + 0.2 * colorScore(R[i].palette, C[j].palette);
|
|
82
|
+
}),
|
|
83
|
+
);
|
|
84
|
+
const GAP = -0.25;
|
|
85
|
+
const S = Array.from({ length: m + 1 }, () => new Float64Array(n + 1));
|
|
86
|
+
const T = Array.from({ length: m + 1 }, () => new Uint8Array(n + 1));
|
|
87
|
+
for (let i = 1; i <= m; i++) {
|
|
88
|
+
S[i][0] = i * GAP;
|
|
89
|
+
T[i][0] = 1;
|
|
90
|
+
}
|
|
91
|
+
for (let j = 1; j <= n; j++) {
|
|
92
|
+
S[0][j] = j * GAP;
|
|
93
|
+
T[0][j] = 2;
|
|
94
|
+
}
|
|
95
|
+
for (let i = 1; i <= m; i++)
|
|
96
|
+
for (let j = 1; j <= n; j++) {
|
|
97
|
+
const diag = S[i - 1][j - 1] + sim[i - 1][j - 1] - 0.35;
|
|
98
|
+
const up = S[i - 1][j] + GAP;
|
|
99
|
+
const left = S[i][j - 1] + GAP;
|
|
100
|
+
if (diag >= up && diag >= left) {
|
|
101
|
+
S[i][j] = diag;
|
|
102
|
+
T[i][j] = 0;
|
|
103
|
+
} else if (up >= left) {
|
|
104
|
+
S[i][j] = up;
|
|
105
|
+
T[i][j] = 1;
|
|
106
|
+
} else {
|
|
107
|
+
S[i][j] = left;
|
|
108
|
+
T[i][j] = 2;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
const pairs = [];
|
|
112
|
+
let i = m;
|
|
113
|
+
let j = n;
|
|
114
|
+
while (i > 0 || j > 0) {
|
|
115
|
+
const t = i > 0 && j > 0 ? T[i][j] : i > 0 ? 1 : 2;
|
|
116
|
+
if (t === 0) pairs.push({ ref: R[--i], cand: C[--j] });
|
|
117
|
+
else if (t === 1) pairs.push({ ref: R[--i], cand: null });
|
|
118
|
+
else pairs.push({ ref: null, cand: C[--j] });
|
|
119
|
+
}
|
|
120
|
+
return pairs.reverse();
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// 16×9 thumbnails of the candidate's side of a pair: "did this shot change since last time?"
|
|
124
|
+
function thumb(A, s) {
|
|
125
|
+
return sceneSamples(A, s, POS).map((f) => {
|
|
126
|
+
const out = [];
|
|
127
|
+
for (let y = 0; y < 9; y++)
|
|
128
|
+
for (let x = 0; x < 16; x++) {
|
|
129
|
+
let v = 0;
|
|
130
|
+
for (let dy = 0; dy < 4; dy++) for (let dx = 0; dx < 4; dx++) v += f[(y * 4 + dy) * SIG_W + x * 4 + dx];
|
|
131
|
+
out.push(Math.round(v / 16));
|
|
132
|
+
}
|
|
133
|
+
return out;
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const sameThumb = (a, b) => {
|
|
138
|
+
if (!a || !b || a.length !== b.length) return false;
|
|
139
|
+
let s = 0;
|
|
140
|
+
let n = 0;
|
|
141
|
+
for (let i = 0; i < a.length; i++) for (let k = 0; k < a[i].length; k++, n++) s += Math.abs(a[i][k] - b[i][k]);
|
|
142
|
+
return s / n < 2;
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
export async function compare(A, B, { mode, outDir, stateFile, threshold = 0.75, all = false, labels, sceneName }) {
|
|
146
|
+
const fps = B.fps;
|
|
147
|
+
const frameSec = 1 / fps;
|
|
148
|
+
const prev = stateFile ? readJsonSync(stateFile, null) : null;
|
|
149
|
+
const prevByRef = prev && prev.refHash === A.hash ? prev.scenes : {};
|
|
150
|
+
const pairs = alignScenes(A, B);
|
|
151
|
+
const rows = [];
|
|
152
|
+
const state = { refHash: A.hash, candHash: B.hash, at: new Date().toISOString(), scenes: {} };
|
|
153
|
+
ensureDir(outDir);
|
|
154
|
+
for (const f of fs.readdirSync(outDir)) if (/^p\d+\.jpg$/.test(f)) fs.rmSync(path.join(outDir, f));
|
|
155
|
+
const tmp = ensureDir(path.join(outDir, ".tmp"));
|
|
156
|
+
|
|
157
|
+
for (const { ref, cand } of pairs) {
|
|
158
|
+
if (!cand) {
|
|
159
|
+
rows.push({ ref, cand: null, status: mode === "takes" ? "removed" : "missing", score: 0 });
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
if (!ref) {
|
|
163
|
+
rows.push({ ref: null, cand, status: mode === "takes" ? "added" : "extra", score: 0 });
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
const th = thumb(B, cand);
|
|
167
|
+
const before = prevByRef[ref.index];
|
|
168
|
+
const unchanged = before && sameThumb(before.thumb, th) && Math.abs(before.candStart - cand.start) < frameSec / 2;
|
|
169
|
+
const row = {
|
|
170
|
+
ref,
|
|
171
|
+
cand,
|
|
172
|
+
startDelta: round(cand.start - ref.start, 3),
|
|
173
|
+
durDelta: round(cand.duration - ref.duration, 3),
|
|
174
|
+
transition: ref.in === cand.in || ref.in.split(" ")[0] === cand.in.split(" ")[0],
|
|
175
|
+
};
|
|
176
|
+
if (mode === "takes") {
|
|
177
|
+
row.content = round(contentDiff(A, ref, B, cand), 2);
|
|
178
|
+
const retimed = Math.abs(row.durDelta) >= frameSec * 0.9;
|
|
179
|
+
const shifted = Math.abs(row.startDelta) >= frameSec * 0.9;
|
|
180
|
+
const changed = row.content > 1.2;
|
|
181
|
+
row.status = changed && retimed ? "changed + retimed" : changed ? "changed" : retimed ? "retimed" : shifted ? "shifted" : "same";
|
|
182
|
+
row.score = changed ? 0 : 1;
|
|
183
|
+
} else {
|
|
184
|
+
row.layout = round(layoutScore(A, ref, B, cand));
|
|
185
|
+
row.motion = round(motionScore(ref, cand));
|
|
186
|
+
row.color = round(colorScore(ref.palette, cand.palette));
|
|
187
|
+
row.timing = round(Math.max(0, 1 - Math.abs(row.durDelta) / Math.max(0.1, ref.duration * 0.4)));
|
|
188
|
+
row.score = round(0.35 * row.layout + 0.25 * row.motion + 0.15 * row.color + 0.25 * row.timing);
|
|
189
|
+
row.status = unchanged ? "unchanged" : row.score >= threshold ? "ok" : "check";
|
|
190
|
+
}
|
|
191
|
+
if (unchanged && mode !== "takes") row.prevScore = before.score;
|
|
192
|
+
state.scenes[ref.index] = { thumb: th, candStart: cand.start, score: row.score };
|
|
193
|
+
const needsLook = mode === "takes" ? /changed/.test(row.status) : row.status === "check";
|
|
194
|
+
if ((needsLook || (all && row.status !== "unchanged")) && !unchanged) {
|
|
195
|
+
const rt = POS.slice(1, 5).map((p) => ref.start + p * ref.duration);
|
|
196
|
+
const ct = POS.slice(1, 5).map((p) => cand.start + p * cand.duration);
|
|
197
|
+
const out = path.join(outDir, `p${String(ref.index).padStart(2, "0")}.jpg`);
|
|
198
|
+
if (pairSheet(A.file, rt, B.file, ct, out, { fps, refDuration: A.info.duration, candDuration: B.info.duration, tmp, labels })) row.image = rel(out);
|
|
199
|
+
}
|
|
200
|
+
rows.push(row);
|
|
201
|
+
}
|
|
202
|
+
rmDir(tmp);
|
|
203
|
+
if (stateFile) writeJsonSync(stateFile, state);
|
|
204
|
+
|
|
205
|
+
const scored = rows.filter((r) => r.ref && r.cand);
|
|
206
|
+
const totalDur = scored.reduce((s, r) => s + r.ref.duration, 0) || 1;
|
|
207
|
+
const overall = mode === "takes" ? null : round(scored.reduce((s, r) => s + r.score * r.ref.duration, 0) / totalDur);
|
|
208
|
+
const md = mode === "takes" ? takesMd(rows, A, B, labels, sceneName) : matchMd(rows, A, B, overall, threshold, labels);
|
|
209
|
+
fs.writeFileSync(path.join(outDir, mode === "takes" ? "VDIFF.md" : "MATCH.md"), md);
|
|
210
|
+
writeJsonSync(
|
|
211
|
+
path.join(outDir, mode === "takes" ? "vdiff.json" : "match.json"),
|
|
212
|
+
rows.map((r) => ({ ...r, ref: r.ref && pick(r.ref), cand: r.cand && pick(r.cand) })),
|
|
213
|
+
);
|
|
214
|
+
return { rows, overall };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const pick = (s) => ({ index: s.index, start: s.start, duration: s.duration, in: s.in, motion: s.motionLabel });
|
|
218
|
+
const T = (t) => fmtTime(t);
|
|
219
|
+
|
|
220
|
+
function matchMd(rows, A, B, overall, threshold, labels) {
|
|
221
|
+
const [la, lb] = labels;
|
|
222
|
+
const look = rows.filter((r) => r.status === "check").sort((x, y) => x.score - y.score);
|
|
223
|
+
const out = [`# Match: ${lb} vs ${la}`, ""];
|
|
224
|
+
out.push(`Overall **${overall}** (1 = same). ${A.scenes.length} shots in the reference, ${B.scenes.length} in yours, threshold ${threshold}.`);
|
|
225
|
+
out.push(`Length: reference ${A.info.duration.toFixed(2)}s, yours ${B.info.duration.toFixed(2)}s.`);
|
|
226
|
+
out.push("");
|
|
227
|
+
out.push("Scores per shot: **layout** (where things sit, light/dark structure), **motion** (how much and when it moves), **color** (palette), **timing** (shot length). For a remix with new content, layout can be low and still fine; timing and motion should stay high.");
|
|
228
|
+
out.push("");
|
|
229
|
+
if (look.length) {
|
|
230
|
+
out.push("## Look at these first");
|
|
231
|
+
for (const r of look)
|
|
232
|
+
out.push(`- Shot ${r.ref.index} (${T(r.ref.start)}, yours at ${T(r.cand.start)}): score ${r.score} — ${weakest(r)}${r.image ? ` — \`${r.image}\` (top: reference, bottom: yours)` : ""}`);
|
|
233
|
+
out.push("");
|
|
234
|
+
}
|
|
235
|
+
const miss = rows.filter((r) => r.status === "missing");
|
|
236
|
+
const extra = rows.filter((r) => r.status === "extra");
|
|
237
|
+
if (miss.length) out.push(`Missing in yours: ${miss.map((r) => `shot ${r.ref.index} at ${T(r.ref.start)} (${r.ref.duration.toFixed(2)}s)`).join("; ")}`);
|
|
238
|
+
if (extra.length) out.push(`Extra in yours: ${extra.map((r) => `${T(r.cand.start)} (${r.cand.duration.toFixed(2)}s)`).join("; ")}`);
|
|
239
|
+
if (miss.length || extra.length) out.push("");
|
|
240
|
+
out.push("## All shots");
|
|
241
|
+
out.push("| ref # | ref at | yours at | Δstart | Δlength | layout | motion | color | timing | score | status |");
|
|
242
|
+
out.push("| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |");
|
|
243
|
+
for (const r of rows) {
|
|
244
|
+
if (!r.ref || !r.cand) {
|
|
245
|
+
out.push(`| ${r.ref?.index ?? "–"} | ${r.ref ? T(r.ref.start) : "–"} | ${r.cand ? T(r.cand.start) : "–"} | | | | | | | | ${r.status} |`);
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
const sign = (x) => `${x > 0 ? "+" : ""}${x.toFixed(2)}s`;
|
|
249
|
+
out.push(
|
|
250
|
+
`| ${r.ref.index} | ${T(r.ref.start)} | ${T(r.cand.start)} | ${sign(r.startDelta)} | ${sign(r.durDelta)} | ${r.layout} | ${r.motion} | ${r.color} | ${r.timing} | ${r.score} | ${r.status}${r.status === "unchanged" ? ` (was ${r.prevScore})` : ""} |`,
|
|
251
|
+
);
|
|
252
|
+
}
|
|
253
|
+
out.push("");
|
|
254
|
+
out.push("“unchanged” = this shot looks the same as at the last check, so no new image was made. Re-run after each render; only shots that changed or still fail produce images.");
|
|
255
|
+
return out.join("\n") + "\n";
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function weakest(r) {
|
|
259
|
+
const parts = [
|
|
260
|
+
["layout", r.layout, "composition differs"],
|
|
261
|
+
["motion", r.motion, "movement differs (amount or timing)"],
|
|
262
|
+
["color", r.color, "palette differs"],
|
|
263
|
+
["timing", r.timing, `shot is ${r.durDelta > 0 ? "longer" : "shorter"} by ${Math.abs(r.durDelta).toFixed(2)}s`],
|
|
264
|
+
].sort((a, b) => a[1] - b[1]);
|
|
265
|
+
const w = parts.filter((p) => p[1] < 0.7).map((p) => `${p[2]} (${p[0]} ${p[1]})`);
|
|
266
|
+
return w.length ? w.join("; ") : `lowest: ${parts[0][0]} ${parts[0][1]}`;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function takesMd(rows, A, B, labels, sceneName) {
|
|
270
|
+
const [la, lb] = labels;
|
|
271
|
+
const changed = rows.filter((r) => !["same", "shifted"].includes(r.status));
|
|
272
|
+
const out = [`# What changed: ${la} → ${lb}`, ""];
|
|
273
|
+
out.push(`${la} ${A.info.duration.toFixed(2)}s, ${lb} ${B.info.duration.toFixed(2)}s. ${changed.length} of ${rows.length} shots changed; images only for those.`);
|
|
274
|
+
out.push("");
|
|
275
|
+
if (!changed.length) out.push("Nothing visible changed.");
|
|
276
|
+
for (const r of changed) {
|
|
277
|
+
const s = r.cand ?? r.ref;
|
|
278
|
+
const where = sceneName?.(s.start + s.duration / 2);
|
|
279
|
+
const head = r.ref && r.cand ? `${T(r.ref.start)} → ${T(r.cand.start)}` : T(s.start);
|
|
280
|
+
const detail =
|
|
281
|
+
r.status === "added" ? "new shot" : r.status === "removed" ? "shot removed" : [r.status.includes("changed") ? `picture changed (diff ${r.content})` : null, r.status.includes("retimed") ? `length ${r.durDelta > 0 ? "+" : ""}${r.durDelta.toFixed(2)}s` : null].filter(Boolean).join(", ");
|
|
282
|
+
out.push(`- Shot at ${head} (${s.duration.toFixed(2)}s)${where ? ` — ${where}` : ""}: ${detail}${r.image ? ` — \`${r.image}\` (top: ${la}, bottom: ${lb})` : ""}`);
|
|
283
|
+
}
|
|
284
|
+
const shifted = rows.filter((r) => r.status === "shifted");
|
|
285
|
+
if (shifted.length) out.push("", `Shifted in time only (no other change): ${shifted.length} shot${shifted.length === 1 ? "" : "s"}, by ${shifted[0].startDelta > 0 ? "+" : ""}${shifted[0].startDelta.toFixed(2)}s first.`);
|
|
286
|
+
return out.join("\n") + "\n";
|
|
287
|
+
}
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { spawnSync } from "node:child_process";
|
|
4
|
+
import { BRAND } from "../brand.js";
|
|
5
|
+
import { findRoot, Repo } from "../store.js";
|
|
6
|
+
import { probe } from "../media.js";
|
|
7
|
+
import { api, configDir, download, remoteFor, tokenFor } from "../remote.js";
|
|
8
|
+
import { fail, fmtTime, parseTarget, sha256File, writeJsonSync } from "../util.js";
|
|
9
|
+
import { loadFrames, analysisFps, frame } from "./frames.js";
|
|
10
|
+
import { motionCurve, scenesOf, motionPeaks, holds } from "./analyze.js";
|
|
11
|
+
import { analyzeAudio, decodeAudio, loudness, localTranscript } from "./audio.js";
|
|
12
|
+
import { sheetsBatch, timelineImage } from "./sheets.js";
|
|
13
|
+
import { ensureDir, needFfmpeg, rel, rmDir } from "./ff.js";
|
|
14
|
+
|
|
15
|
+
export const PACK_VERSION = 1;
|
|
16
|
+
|
|
17
|
+
export function repoOrNull() {
|
|
18
|
+
const root = findRoot();
|
|
19
|
+
return root ? new Repo(root) : null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function cacheRoot(repo) {
|
|
23
|
+
return repo ? repo.p("cache") : path.join(configDir(), "cache");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Turn whatever the person gave us into a local video file.
|
|
27
|
+
// ./file.mp4 · v3 (a saved version here) · handle/slug[@n] (a Retakes project) · https://… (yt-dlp)
|
|
28
|
+
export async function resolveVideo(input, repo, { remote: remoteOverride } = {}) {
|
|
29
|
+
if (!input) fail("Name a video: a file, a version (v3), handle/slug[@n], or a URL.");
|
|
30
|
+
if (fs.existsSync(input)) return { file: path.resolve(input), label: path.basename(input, path.extname(input)) };
|
|
31
|
+
if (repo && /^v?\d+$/i.test(input)) {
|
|
32
|
+
const v = repo.resolveRef(input);
|
|
33
|
+
if (!v.render) fail(`v${v.n} has no render.`);
|
|
34
|
+
if (repo.hasObj(v.render.h)) return { file: repo.objPath(v.render.h), label: `v${v.n}`, version: v };
|
|
35
|
+
if (v.remote?.versionId) {
|
|
36
|
+
const remote = remoteFor(repo);
|
|
37
|
+
const out = path.join(cacheRoot(repo), "videos", `${v.remote.versionId}.mp4`);
|
|
38
|
+
if (!fs.existsSync(out)) await download(remote, tokenFor(remote), `/media/${v.remote.versionId}/best`, out);
|
|
39
|
+
return { file: out, label: `v${v.n}`, version: v };
|
|
40
|
+
}
|
|
41
|
+
fail(`The render of v${v.n} isn't on this machine.`);
|
|
42
|
+
}
|
|
43
|
+
if (/^https?:\/\//i.test(input)) {
|
|
44
|
+
const known = remoteFor(repo, remoteOverride);
|
|
45
|
+
if (input.startsWith(known)) return resolveProject(parseTarget(input), repo, known);
|
|
46
|
+
const out = path.join(cacheRoot(repo), "downloads", `${input.replace(/[^a-z0-9]+/gi, "-").slice(-80)}.mp4`);
|
|
47
|
+
if (!fs.existsSync(out)) {
|
|
48
|
+
const has = spawnSync(process.platform === "win32" ? "where" : "which", ["yt-dlp"], { encoding: "utf8" });
|
|
49
|
+
if (has.status !== 0) fail("To analyse a URL, install yt-dlp, or download the video and pass the file.");
|
|
50
|
+
ensureDir(path.dirname(out));
|
|
51
|
+
const r = spawnSync("yt-dlp", ["-f", "bv*[height<=1080]+ba/b[height<=1080]/b", "--merge-output-format", "mp4", "-o", out, input], { stdio: "inherit" });
|
|
52
|
+
if (r.status !== 0 || !fs.existsSync(out)) fail("yt-dlp couldn't download that URL.");
|
|
53
|
+
}
|
|
54
|
+
return { file: out, label: "reference" };
|
|
55
|
+
}
|
|
56
|
+
if (/^@?[^/\s]+\/[^/\s]+$/.test(input)) return resolveProject(parseTarget(input), repo, remoteFor(repo, remoteOverride));
|
|
57
|
+
fail(`Can't find "${input}". Pass a video file, v3, handle/slug[@n] or a URL.`);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function resolveProject(target, repo, remote) {
|
|
61
|
+
const token = tokenFor(remote);
|
|
62
|
+
const p = await api(remote, "GET", `/api/p/${target.handle}/${target.slug}`, { token });
|
|
63
|
+
const n = target.number ?? p.versions.find((v) => v.render || v.hasPreview)?.number;
|
|
64
|
+
const v = p.versions.find((x) => x.number === n);
|
|
65
|
+
if (!v) fail(`${target.handle}/${target.slug} has no version ${n ?? ""} with a video.`);
|
|
66
|
+
const out = path.join(cacheRoot(repo), "videos", `${v.id}.mp4`);
|
|
67
|
+
if (!fs.existsSync(out)) await download(remote, token, `/media/${v.id}/best`, out);
|
|
68
|
+
return { file: out, label: `${target.handle}-${target.slug}-v${n}`, remoteVersion: v };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Everything measurable about a video, cached by content hash.
|
|
72
|
+
export async function analyzeVideo(file, repo, { withAudio = true } = {}) {
|
|
73
|
+
needFfmpeg();
|
|
74
|
+
const hash = await sha256File(file);
|
|
75
|
+
const key = hash.slice(0, 16);
|
|
76
|
+
const info = probe(file);
|
|
77
|
+
if (!info.duration) fail(`Can't read ${file} as a video.`);
|
|
78
|
+
const fps = analysisFps(info);
|
|
79
|
+
const fr = await loadFrames(file, { fps, cacheDir: path.join(cacheRoot(repo), "frames"), key });
|
|
80
|
+
const d = motionCurve(fr);
|
|
81
|
+
const { cuts, scenes } = scenesOf(fr, d, info.duration);
|
|
82
|
+
let audio = null;
|
|
83
|
+
if (withAudio && info.hasAudio) {
|
|
84
|
+
const pcm = await decodeAudio(file);
|
|
85
|
+
if (pcm) audio = { ...analyzeAudio(pcm, info.duration), loudness: loudness(file) };
|
|
86
|
+
}
|
|
87
|
+
return { file, hash, key, info, fps, fr, d, cuts, scenes, audio };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// How close each cut lands to a beat.
|
|
91
|
+
function beatAlignment(a) {
|
|
92
|
+
if (!a.audio?.beats?.length || !a.cuts.length) return null;
|
|
93
|
+
const frameSec = 1 / a.fps;
|
|
94
|
+
const offs = a.cuts.map((c) => {
|
|
95
|
+
const t = c.frame / a.fps;
|
|
96
|
+
let best = Infinity;
|
|
97
|
+
for (const b of a.audio.beats) if (Math.abs(b - t) < Math.abs(best)) best = b - t;
|
|
98
|
+
return best;
|
|
99
|
+
});
|
|
100
|
+
const onBeat = offs.filter((o) => Math.abs(o) <= 2 * frameSec).length;
|
|
101
|
+
return { onBeat, total: offs.length, offsets: offs.map((o) => Math.round(o * 1000)) };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export async function buildWatchPack(src, repo, { out, force = false, bursts = 8 } = {}) {
|
|
105
|
+
const a = await analyzeVideo(src.file, repo);
|
|
106
|
+
const dir = out ?? (repo ? repo.p("watch", `${src.label}-${a.key.slice(0, 8)}`) : path.resolve(`${src.label}.watch`));
|
|
107
|
+
const meta = path.join(dir, "watch.json");
|
|
108
|
+
if (!force && fs.existsSync(meta)) {
|
|
109
|
+
try {
|
|
110
|
+
const prev = JSON.parse(fs.readFileSync(meta, "utf8"));
|
|
111
|
+
if (prev.hash === a.hash && prev.packVersion === PACK_VERSION) return { dir, cached: true, a };
|
|
112
|
+
} catch {
|
|
113
|
+
/* rebuild */
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
rmDir(dir);
|
|
117
|
+
ensureDir(dir);
|
|
118
|
+
const tmp = ensureDir(path.join(dir, ".tmp"));
|
|
119
|
+
const { info, fps, scenes, cuts, d } = a;
|
|
120
|
+
const duration = info.duration;
|
|
121
|
+
const opts = { fps, duration, tmp };
|
|
122
|
+
|
|
123
|
+
const groups = [];
|
|
124
|
+
// 1. Overview: evenly spaced frames across the whole video.
|
|
125
|
+
const nOver = Math.max(12, Math.min(48, Math.round(duration / 1.25)));
|
|
126
|
+
const overTimes = Array.from({ length: nOver }, (_, i) => ((i + 0.5) * duration) / nOver);
|
|
127
|
+
groups.push({ times: overTimes, cols: 8, width: 240, out: path.join(dir, "overview.jpg") });
|
|
128
|
+
|
|
129
|
+
// 2. One strip per scene.
|
|
130
|
+
for (const s of scenes) {
|
|
131
|
+
const k = s.duration < 0.4 ? 2 : Math.max(3, Math.min(6, Math.round(s.duration / 0.45)));
|
|
132
|
+
const pad = Math.min(0.04, s.duration / 4);
|
|
133
|
+
const times = Array.from({ length: k }, (_, i) => s.start + pad + (i * (s.duration - 2 * pad)) / Math.max(1, k - 1));
|
|
134
|
+
const f = path.join(dir, "scenes", `s${String(s.index).padStart(2, "0")}.jpg`);
|
|
135
|
+
groups.push({ times, cols: k, width: 320, out: f });
|
|
136
|
+
s.sheet = rel(f);
|
|
137
|
+
s.sampleTimes = times.map((t) => Math.round(t * 1000) / 1000);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// 3. Bursts: every frame through transitions and the busiest moves.
|
|
141
|
+
const peaks = motionPeaks(a.fr, d, cuts, bursts);
|
|
142
|
+
const burstAt = [
|
|
143
|
+
...cuts.filter((c) => c.kind === "transition").map((c) => ({ t: c.frame / fps, why: "transition", span: Math.max(0.5, (c.to - c.from + 6) / fps) })),
|
|
144
|
+
...peaks.map((p) => ({ t: p.t, why: "motion peak", span: 0.6 })),
|
|
145
|
+
]
|
|
146
|
+
.sort((x, y) => x.t - y.t)
|
|
147
|
+
.slice(0, bursts);
|
|
148
|
+
const burstList = [];
|
|
149
|
+
for (const [i, b] of burstAt.entries()) {
|
|
150
|
+
const n = Math.min(24, Math.max(12, Math.round(b.span * fps)));
|
|
151
|
+
const t0 = Math.max(0, b.t - (n / fps) * 0.4);
|
|
152
|
+
const times = Array.from({ length: n }, (_, k) => t0 + k / fps);
|
|
153
|
+
const f = path.join(dir, "bursts", `b${String(i + 1).padStart(2, "0")}.jpg`);
|
|
154
|
+
groups.push({ times, cols: 6, width: 280, out: f });
|
|
155
|
+
burstList.push({ file: rel(f), why: b.why, from: Math.round(t0 * 1000) / 1000, to: Math.round((t0 + (n - 1) / fps) * 1000) / 1000, frames: n });
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
sheetsBatch(a.file, groups, opts);
|
|
159
|
+
|
|
160
|
+
// 4. Timeline strip and audio.
|
|
161
|
+
await timelineImage(path.join(dir, "timeline.png"), { duration, motion: d, fps, cuts, scenes, audio: a.audio });
|
|
162
|
+
let transcript = null;
|
|
163
|
+
if (a.audio && localTranscript(a.file, dir)) {
|
|
164
|
+
const srt = fs.readdirSync(dir).find((f) => f.endsWith(".srt"));
|
|
165
|
+
if (srt) {
|
|
166
|
+
fs.renameSync(path.join(dir, srt), path.join(dir, "transcript.srt"));
|
|
167
|
+
transcript = "transcript.srt";
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
rmDir(tmp);
|
|
171
|
+
|
|
172
|
+
const align = beatAlignment(a);
|
|
173
|
+
const still = holds(a.fr, d);
|
|
174
|
+
const data = {
|
|
175
|
+
packVersion: PACK_VERSION,
|
|
176
|
+
source: src.label,
|
|
177
|
+
file: a.file,
|
|
178
|
+
hash: a.hash,
|
|
179
|
+
duration,
|
|
180
|
+
width: info.width,
|
|
181
|
+
height: info.height,
|
|
182
|
+
fps: info.fps,
|
|
183
|
+
analysisFps: fps,
|
|
184
|
+
hasAudio: !!info.hasAudio,
|
|
185
|
+
scenes: scenes.map(({ startFrame, endFrame, ...s }) => s),
|
|
186
|
+
cuts: cuts.map((c) => ({ t: Math.round((c.frame / fps) * 1000) / 1000, kind: c.kind, frames: c.frames })),
|
|
187
|
+
holds: still,
|
|
188
|
+
bursts: burstList,
|
|
189
|
+
audio: a.audio ? { bpm: a.audio.bpm, beats: a.audio.beats, hits: a.audio.hits, silences: a.audio.silences, loudness: a.audio.loudness, cutsOnBeat: align, transcript } : null,
|
|
190
|
+
};
|
|
191
|
+
writeJsonSync(meta, data);
|
|
192
|
+
fs.writeFileSync(path.join(dir, "WATCH.md"), watchMd(data, dir));
|
|
193
|
+
fs.writeFileSync(path.join(dir, "cuesheet.md"), cueSheetMd(data));
|
|
194
|
+
return { dir, cached: false, a, data };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const t2 = (t) => fmtTime(t);
|
|
198
|
+
|
|
199
|
+
function watchMd(w, dir) {
|
|
200
|
+
const r = (p) => path.relative(dir, path.resolve(p)).split(path.sep).join("/");
|
|
201
|
+
const lines = [];
|
|
202
|
+
lines.push(`# Watch pack: ${w.source}`);
|
|
203
|
+
lines.push("");
|
|
204
|
+
lines.push(`${w.duration.toFixed(2)} s · ${w.width}×${w.height} · ${w.fps} fps · ${w.scenes.length} shots · ${w.hasAudio ? "audio" : "no audio"}`);
|
|
205
|
+
if (w.audio) {
|
|
206
|
+
const l = w.audio.loudness ?? {};
|
|
207
|
+
lines.push(`Audio: ${w.audio.bpm ? `~${w.audio.bpm} BPM` : "no steady tempo"} · ${l.integratedLufs ?? "?"} LUFS · peak ${l.truePeakDbtp ?? "?"} dBTP · ${w.audio.hits.length} hits${w.audio.cutsOnBeat ? ` · ${w.audio.cutsOnBeat.onBeat}/${w.audio.cutsOnBeat.total} cuts within 2 frames of a beat` : ""}`);
|
|
208
|
+
}
|
|
209
|
+
lines.push("");
|
|
210
|
+
lines.push("## How to read this (cheapest first)");
|
|
211
|
+
lines.push("1. `timeline.png`: the whole video as one strip. Green = how much the picture moves per frame, blue = audio energy, grey ticks = beats, orange ticks = hits, red lines = hard cuts, amber spans = transitions. Numbers on top are shot numbers.");
|
|
212
|
+
lines.push("2. `overview.jpg`: evenly spaced frames, timestamps burned in. Enough to understand the story and the look.");
|
|
213
|
+
lines.push("3. The shot table below, then `scenes/sNN.jpg` only for the shots you're working on (left to right in time).");
|
|
214
|
+
lines.push("4. `bursts/bNN.jpg`: every single frame through a transition or fast move. Read these for easing, overshoot and exact timing; they're the motion an image model can't infer from a few stills.");
|
|
215
|
+
lines.push("");
|
|
216
|
+
lines.push("Times are seconds from the start. Frame = round(time × fps).");
|
|
217
|
+
lines.push("");
|
|
218
|
+
lines.push("## Shots");
|
|
219
|
+
lines.push("| # | start | length | in | motion | look (palette) | sheet |");
|
|
220
|
+
lines.push("| --- | --- | --- | --- | --- | --- | --- |");
|
|
221
|
+
for (const s of w.scenes) lines.push(`| ${s.index} | ${t2(s.start)} | ${s.duration.toFixed(2)}s | ${s.in} | ${s.motionLabel} | ${s.palette.slice(0, 4).map((p) => p.hex).join(" ")} | ${r(s.sheet)} |`);
|
|
222
|
+
if (w.bursts.length) {
|
|
223
|
+
lines.push("");
|
|
224
|
+
lines.push("## Bursts (every frame)");
|
|
225
|
+
for (const b of w.bursts) lines.push(`- ${r(b.file)}: ${t2(b.from)} → ${t2(b.to)}, ${b.frames} frames (${b.why})`);
|
|
226
|
+
}
|
|
227
|
+
if (w.holds.length) {
|
|
228
|
+
lines.push("");
|
|
229
|
+
lines.push(`## Holds (picture still for 0.6 s+)\n${w.holds.map((h) => `${t2(h.start)}–${t2(h.end)}`).join(" · ")}`);
|
|
230
|
+
}
|
|
231
|
+
if (w.audio) {
|
|
232
|
+
lines.push("");
|
|
233
|
+
lines.push("## Audio");
|
|
234
|
+
if (w.audio.beats.length) lines.push(`- Beats (first 16): ${w.audio.beats.slice(0, 16).map((b) => b.toFixed(2)).join(", ")}${w.audio.beats.length > 16 ? " …" : ""}`);
|
|
235
|
+
lines.push(`- Strongest hits: ${[...w.audio.hits].sort((a, b) => b.strength - a.strength).slice(0, 12).sort((a, b) => a.t - b.t).map((h) => h.t.toFixed(2)).join(", ") || "none"}`);
|
|
236
|
+
if (w.audio.silences.length) lines.push(`- Silences: ${w.audio.silences.map((s) => `${s.start.toFixed(2)}–${s.end.toFixed(2)}`).join(", ")}`);
|
|
237
|
+
lines.push(`- Transcript: ${w.audio.transcript ? "`transcript.srt` (local Whisper)" : "none (install openai-whisper locally to get one, or ask the person for the script)"}`);
|
|
238
|
+
lines.push("- What the sound *is* (voice, genre, SFX character) can't be measured here: describe it from the beat/hit pattern and ask the person if it matters.");
|
|
239
|
+
}
|
|
240
|
+
lines.push("");
|
|
241
|
+
lines.push("Next: fill `cuesheet.md` (what's on screen, text, motion, sound per shot) from the sheets.");
|
|
242
|
+
return lines.join("\n") + "\n";
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function cueSheetMd(w) {
|
|
246
|
+
const lines = [`# Cue sheet: ${w.source}`, "", "Measured columns are filled in; write the rest from the scene strips and bursts. Keep it terse.", ""];
|
|
247
|
+
lines.push("| # | start | end | length | in | motion | on screen | text | motion notes | sound |");
|
|
248
|
+
lines.push("| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |");
|
|
249
|
+
for (const s of w.scenes) lines.push(`| ${s.index} | ${t2(s.start)} | ${t2(s.end)} | ${s.duration.toFixed(2)}s | ${s.in} | ${s.motionLabel} | | | | |`);
|
|
250
|
+
return lines.join("\n") + "\n";
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// Downsampled frames of a scene at relative positions, for comparing two videos.
|
|
254
|
+
export function sceneSamples(a, s, positions) {
|
|
255
|
+
const n = s.endFrame - s.startFrame;
|
|
256
|
+
return positions.map((p) => frame(a.fr, Math.min(a.fr.count - 1, s.startFrame + Math.round(p * Math.max(0, n - 1)))));
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
export { BRAND };
|