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.
@@ -0,0 +1,161 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { drawtext, ensureDir, esc, ffRun, ffWrite, rmDir } from "./ff.js";
4
+
5
+ // Pull exact frames at the given times in ONE decode pass, scaled to `width`, each stamped
6
+ // with its timestamp. Returns the file paths in time order.
7
+ export function extractFrames(video, times, dir, { width = 320, fps = 30, duration, stamp = true } = {}) {
8
+ ensureDir(dir);
9
+ for (const f of fs.readdirSync(dir)) if (/^f\d+\.jpg$/.test(f)) fs.rmSync(path.join(dir, f));
10
+ if (!times.length) return [];
11
+ const half = 0.5 / fps;
12
+ const last = duration ? duration - 1 / fps : Infinity;
13
+ const ts = [...new Set(times.map((t) => Math.round(Math.max(0, Math.min(last, t)) * fps)))].sort((a, b) => a - b).map((n) => n / fps);
14
+ const expr = ts.map((t) => `between(t\\,${(t - half).toFixed(4)}\\,${(t + half - 0.0001).toFixed(4)})`).join("+");
15
+ const filters = [`select='${expr}'`, `scale=${width}:-2:flags=bicubic`];
16
+ const label = stamp && drawtext("%{pts\\:hms}", { size: Math.max(12, Math.round(width / 18)) });
17
+ if (label) filters.push(label);
18
+ // Long filter expressions go through a script file (Windows command lines are short).
19
+ const script = path.join(dir, "select.txt");
20
+ fs.writeFileSync(script, filters.join(","));
21
+ ffRun(["-i", video, "-an", "-filter_script:v", script, "-fps_mode", "passthrough", "-q:v", "3", path.join(dir, "f%04d.jpg")]);
22
+ fs.rmSync(script, { force: true });
23
+ return fs.readdirSync(dir).filter((f) => /^f\d+\.jpg$/.test(f)).sort().map((f) => path.join(dir, f));
24
+ }
25
+
26
+ // Many sheets from ONE decode pass: gather every requested frame once, then tile each group.
27
+ // groups: [{ times, cols, width, out }]
28
+ export function sheetsBatch(video, groups, { fps, duration, tmp }) {
29
+ const toFrame = (t) => Math.round(Math.max(0, Math.min(duration ? duration - 1 / fps : Infinity, t)) * fps);
30
+ const all = [...new Set(groups.flatMap((g) => g.times.map(toFrame)))].sort((a, b) => a - b);
31
+ const dir = path.join(tmp, "batch");
32
+ const files = extractFrames(video, all.map((n) => n / fps), dir, { width: Math.max(...groups.map((g) => g.width)), fps, duration });
33
+ if (files.length !== all.length) {
34
+ // Variable-frame-rate sources can make the single pass miss a frame: fall back to one pass per sheet.
35
+ rmDir(dir);
36
+ return groups.map((g) => sheet(video, g.times, g.out, { cols: g.cols, width: g.width, fps, duration, tmp }));
37
+ }
38
+ const byFrame = new Map(all.map((n, i) => [n, files[i]]));
39
+ const made = [];
40
+ for (const g of groups) {
41
+ const fs_ = [...new Set(g.times.map(toFrame))].map((n) => byFrame.get(n)).filter(Boolean);
42
+ made.push(tile(fs_, Math.min(g.cols, fs_.length), g.out, g.width));
43
+ }
44
+ rmDir(dir);
45
+ return made;
46
+ }
47
+
48
+ // Lay images out in a grid (all the same size).
49
+ export function tile(files, cols, out, width) {
50
+ if (!files.length) return null;
51
+ ensureDir(path.dirname(out));
52
+ const rows = Math.ceil(files.length / cols);
53
+ const list = path.join(path.dirname(out), `.${path.basename(out)}.txt`);
54
+ const lines = ["ffconcat version 1.0"];
55
+ for (const f of files) lines.push(`file '${f.replace(/\\/g, "/").replace(/'/g, "'\\''")}'`, "duration 0.04");
56
+ lines.push(`file '${files[files.length - 1].replace(/\\/g, "/").replace(/'/g, "'\\''")}'`);
57
+ fs.writeFileSync(list, lines.join("\n"));
58
+ ffRun(["-f", "concat", "-safe", "0", "-i", list, "-frames:v", "1", "-vf", `${width ? `scale=${width}:-2,` : ""}tile=${cols}x${rows}:padding=4:margin=4:color=0x101114`, "-q:v", "3", out]);
59
+ fs.rmSync(list, { force: true });
60
+ return out;
61
+ }
62
+
63
+ // Grab frames, tile them, clean up.
64
+ export function sheet(video, times, out, { cols, width, fps, duration, tmp }) {
65
+ const dir = path.join(tmp, path.basename(out, path.extname(out)));
66
+ const files = extractFrames(video, times, dir, { width, fps, duration });
67
+ const r = tile(files, Math.min(cols, files.length), out);
68
+ rmDir(dir);
69
+ return r;
70
+ }
71
+
72
+ // Two videos, same relative moments: top row reference, bottom row candidate.
73
+ export function pairSheet(refVideo, refTimes, candVideo, candTimes, out, { width = 360, fps = 30, refDuration, candDuration, tmp, labels }) {
74
+ const a = extractFrames(refVideo, refTimes, path.join(tmp, "pa"), { width, fps, duration: refDuration });
75
+ const b = extractFrames(candVideo, candTimes, path.join(tmp, "pb"), { width, fps, duration: candDuration });
76
+ if (!a.length || !b.length) return null;
77
+ const n = Math.min(a.length, b.length);
78
+ // Both rows need the same cell size: pad the candidate frames to the reference size.
79
+ const sized = path.join(tmp, "pc");
80
+ ensureDir(sized);
81
+ const files = [];
82
+ for (let i = 0; i < n; i++) {
83
+ const o1 = path.join(sized, `r${i}.jpg`);
84
+ const o2 = path.join(sized, `c${i}.jpg`);
85
+ const lab = (t) => drawtext(esc(t), { size: 15, x: "8", y: "h-th-10" });
86
+ const fit = `scale=${width}:${Math.round((width * 9) / 16)}:force_original_aspect_ratio=decrease,pad=${width}:${Math.round((width * 9) / 16)}:(ow-iw)/2:(oh-ih)/2:color=0x101114`;
87
+ ffRun(["-i", a[i], "-vf", [fit, i === 0 && labels ? lab(labels[0]) : null].filter(Boolean).join(","), "-q:v", "3", o1]);
88
+ ffRun(["-i", b[i], "-vf", [fit, i === 0 && labels ? lab(labels[1]) : null].filter(Boolean).join(","), "-q:v", "3", o2]);
89
+ files.push(o1);
90
+ }
91
+ for (let i = 0; i < n; i++) files.push(path.join(sized, `c${i}.jpg`));
92
+ const r = tile(files, n, out);
93
+ rmDir(path.join(tmp, "pa"));
94
+ rmDir(path.join(tmp, "pb"));
95
+ rmDir(sized);
96
+ return r;
97
+ }
98
+
99
+ // ── Timeline image: motion, audio energy, beats, hits, cuts on one strip ─────
100
+ export async function timelineImage(out, { duration, motion, fps, cuts, scenes, audio }) {
101
+ const W = 1600;
102
+ const H = 300;
103
+ const px = Buffer.alloc(W * H * 3);
104
+ const set = (x, y, [r, g, b], a = 1) => {
105
+ if (x < 0 || y < 0 || x >= W || y >= H) return;
106
+ const i = (y * W + x) * 3;
107
+ px[i] = px[i] * (1 - a) + r * a;
108
+ px[i + 1] = px[i + 1] * (1 - a) + g * a;
109
+ px[i + 2] = px[i + 2] * (1 - a) + b * a;
110
+ };
111
+ const rect = (x0, y0, x1, y1, c, a = 1) => {
112
+ for (let y = Math.max(0, y0 | 0); y < Math.min(H, y1); y++) for (let x = Math.max(0, x0 | 0); x < Math.min(W, x1); x++) set(x, y, c, a);
113
+ };
114
+ const L = 40;
115
+ const R = W - 12;
116
+ const X = (t) => Math.round(L + (t / duration) * (R - L));
117
+ rect(0, 0, W, H, [16, 17, 20]);
118
+ // Scene bands, alternating shade.
119
+ scenes.forEach((s, i) => rect(X(s.start), 26, X(s.end), 268, i % 2 ? [24, 26, 30] : [20, 22, 25]));
120
+ // Motion (top band 30..130).
121
+ const sorted = [...motion].sort((a, b) => a - b);
122
+ const p95 = sorted[Math.floor(sorted.length * 0.97)] || 1;
123
+ for (let x = L; x < R; x++) {
124
+ const t = ((x - L) / (R - L)) * duration;
125
+ const i = Math.min(motion.length - 1, Math.round(t * fps));
126
+ const v = Math.min(1, motion[i] / p95);
127
+ rect(x, 130 - v * 100, x + 1, 130, [214, 255, 61], 0.9);
128
+ }
129
+ // Audio energy (middle band 145..225), -60..0 dB.
130
+ if (audio?.envelope?.length) {
131
+ for (let x = L; x < R; x++) {
132
+ const t = ((x - L) / (R - L)) * duration;
133
+ const v = audio.envelope[Math.min(audio.envelope.length - 1, Math.round(t * audio.envelopeHz))];
134
+ const h = Math.max(0, Math.min(1, (v + 60) / 60)) * 80;
135
+ rect(x, 225 - h, x + 1, 225, [92, 170, 255], 0.85);
136
+ }
137
+ for (const b of audio.beats) rect(X(b), 232, X(b) + 1, 244, [180, 180, 190]);
138
+ for (const h of audio.hits) rect(X(h.t), 246, X(h.t) + 2, 246 + 20 * h.strength, [255, 120, 60]);
139
+ }
140
+ // Cuts (red) and transitions (amber span).
141
+ for (const c of cuts) {
142
+ if (c.kind === "transition") rect(X(c.from / fps), 26, X(c.to / fps) + 1, 268, [255, 181, 71], 0.28);
143
+ rect(X(c.frame / fps), 26, X(c.frame / fps) + 2, 268, c.kind === "cut" ? [255, 59, 107] : [255, 181, 71]);
144
+ }
145
+ // Ruler.
146
+ for (let t = 0; t <= duration; t += 1) rect(X(t), 270, X(t) + 1, t % 5 === 0 ? 282 : 276, [140, 145, 150]);
147
+ const labels = [];
148
+ const lab = (text, x, y, size = 13) => {
149
+ const d = drawtext(esc(text), { size, x: String(x), y: String(y), box: false });
150
+ if (d) labels.push(d);
151
+ };
152
+ for (let t = 0; t <= duration; t += 5) lab(`${t}s`, X(t) + 3, 283, 12);
153
+ lab("motion", 4, 34, 11);
154
+ lab("audio", 4, 150, 11);
155
+ lab("beats", 4, 231, 10);
156
+ scenes.forEach((s) => {
157
+ if (X(s.end) - X(s.start) >= 18) lab(String(s.index), X(s.start) + 3, 8, 12);
158
+ });
159
+ await ffWrite(["-f", "rawvideo", "-pix_fmt", "rgb24", "-s", `${W}x${H}`, "-i", "-", ...(labels.length ? ["-vf", labels.join(",")] : []), "-frames:v", "1", out], px);
160
+ return out;
161
+ }