launch-film 0.1.3 → 0.2.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/README.md +75 -5
- package/THIRD_PARTY.md +1 -0
- package/assets/icon.svg +17 -0
- package/bin/launch-film.js +47 -0
- package/package.json +1 -1
- package/skills/launch-film/SKILL.md +28 -12
- package/src/brand.js +1 -1
- package/src/check.js +433 -0
- package/src/chrome.js +33 -1
- package/src/cues.js +55 -0
- package/src/draw.js +117 -0
- package/src/ffmpeg.js +33 -9
- package/src/film.js +21 -15
- package/src/frames.js +224 -33
- package/src/motion.js +179 -26
- package/src/stills.js +180 -0
package/src/check.js
ADDED
|
@@ -0,0 +1,433 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ─── check ─────────────────────────────────────────────────────────────────
|
|
3
|
+
// A render checked by measurement, for agents that can neither watch it nor
|
|
4
|
+
// listen to it: its size, frame rate and length; black, still and silent
|
|
5
|
+
// stretches; loudness, true peak and clipping; and, given the music's cues,
|
|
6
|
+
// whether the cuts land on the beat. ffmpeg's own filters measure it all
|
|
7
|
+
// (scdet, blackdetect, freezedetect, ebur128, silencedetect). It writes
|
|
8
|
+
// CHECK.md (pass or fail, in words), check.json, sheet.png (a frame for each
|
|
9
|
+
// cut) and wave.png (loudness over time, with the cuts and the cues).
|
|
10
|
+
//
|
|
11
|
+
// Holds are often meant: a title that rests, an end card, a fade at either
|
|
12
|
+
// end. So a black, still or silent stretch is a warning, not a failure,
|
|
13
|
+
// unless it fills most of the film; the short ones RULES allows and the
|
|
14
|
+
// stretches `allow` lists raise nothing at all.
|
|
15
|
+
|
|
16
|
+
const fs = require("fs");
|
|
17
|
+
const path = require("path");
|
|
18
|
+
const { spawnSync } = require("child_process");
|
|
19
|
+
const { FFMPEG, run, probe, writePng } = require("./ffmpeg");
|
|
20
|
+
const frames = require("./frames");
|
|
21
|
+
const { readCues } = require("./cues");
|
|
22
|
+
const draw = require("./draw");
|
|
23
|
+
|
|
24
|
+
const RULES = {
|
|
25
|
+
// What a film may hold at its start and its end (a fade in, an end card).
|
|
26
|
+
start: { black: 1, still: 1.5, silence: 1 },
|
|
27
|
+
end: { black: 2, still: 6, silence: 2 },
|
|
28
|
+
// A stretch inside the film shorter than this is a hold.
|
|
29
|
+
hold: { black: 0.5, still: 2, silence: 1 },
|
|
30
|
+
// A film this share black, still or silent fails.
|
|
31
|
+
most: 0.5,
|
|
32
|
+
// Seconds either side of the length asked for.
|
|
33
|
+
seconds: 0.5,
|
|
34
|
+
// LU either side of the loudness asked for.
|
|
35
|
+
lufs: 1,
|
|
36
|
+
// The true peak most platforms ask for, in dBTP.
|
|
37
|
+
truePeak: -1,
|
|
38
|
+
// Frames a cut may sit from its beat: on it, then near it.
|
|
39
|
+
onBeat: 1,
|
|
40
|
+
nearBeat: 2,
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
const NAMES = { black: "black", still: "still picture", silence: "silence" };
|
|
44
|
+
|
|
45
|
+
// "1920x1080@30", "1920x1080" or "@30".
|
|
46
|
+
function parseExpect(text) {
|
|
47
|
+
if (!text) return {};
|
|
48
|
+
const m = /^(?:(\d+)\s*[x\u00d7]\s*(\d+))?\s*(?:@\s*(\d+(?:\.\d+)?))?$/i.exec(String(text).trim());
|
|
49
|
+
if (!m || (!m[1] && !m[3])) throw new Error(`--expect "${text}" should look like 1920x1080@30`);
|
|
50
|
+
return { width: m[1] ? Number(m[1]) : null, height: m[2] ? Number(m[2]) : null, fps: m[3] ? Number(m[3]) : null };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// "30" (give or take RULES.seconds) or "28-32".
|
|
54
|
+
function parseSeconds(text) {
|
|
55
|
+
if (text === undefined || text === null || text === "") return null;
|
|
56
|
+
const m = /^(\d+(?:\.\d+)?)(?:\s*-\s*(\d+(?:\.\d+)?))?$/.exec(String(text).trim());
|
|
57
|
+
if (!m) throw new Error(`--seconds "${text}" should be a length like 30, or a range like 28-32`);
|
|
58
|
+
const a = Number(m[1]);
|
|
59
|
+
return m[2] ? { min: Math.min(a, Number(m[2])), max: Math.max(a, Number(m[2])), text: `${m[1]} to ${m[2]} s` } : { min: a - RULES.seconds, max: a + RULES.seconds, text: `${m[1]} s, give or take ${RULES.seconds}` };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// "27-30,0-0.5": stretches of the film, in seconds, where a hold is meant.
|
|
63
|
+
function parseAllow(text) {
|
|
64
|
+
if (!text) return [];
|
|
65
|
+
return String(text).split(",").map((s) => s.trim()).filter(Boolean).map((s) => {
|
|
66
|
+
const m = /^(\d+(?:\.\d+)?)\s*-\s*(\d+(?:\.\d+)?)$/.exec(s);
|
|
67
|
+
if (!m) throw new Error(`--allow "${s}" should be a stretch in seconds, like 27-30`);
|
|
68
|
+
return { from: Math.min(Number(m[1]), Number(m[2])), to: Math.max(Number(m[1]), Number(m[2])) };
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// The sound, measured: ebur128's loudness every 100 ms and its summary
|
|
73
|
+
// (integrated loudness, range, sample and true peak), and silencedetect's
|
|
74
|
+
// stretches.
|
|
75
|
+
async function scanAudio(film, { work, duration }) {
|
|
76
|
+
const notes = path.join(work, `.scan-audio-${process.pid}.txt`);
|
|
77
|
+
try {
|
|
78
|
+
const r = await run(["-i", film, "-vn", "-af",
|
|
79
|
+
`ebur128=metadata=1:peak=true+sample:framelog=quiet,silencedetect=n=-50dB:d=0.5,astats=measure_overall=Peak_count+Flat_factor:measure_perchannel=none,ametadata=mode=print:file=${frames.filterPath(notes)}`,
|
|
80
|
+
"-f", "null", "-"], { loglevel: "info" });
|
|
81
|
+
if (r.code !== 0) throw new Error(`reading the sound: ffmpeg failed: ${r.stderr.trim().split("\n").slice(-2).join(" | ")}`);
|
|
82
|
+
const num = (re) => {
|
|
83
|
+
const m = re.exec(r.stderr);
|
|
84
|
+
return m ? (m[1] === "-inf" ? -Infinity : Number(m[1])) : null;
|
|
85
|
+
};
|
|
86
|
+
const summary = {
|
|
87
|
+
integrated: num(/Integrated loudness:\s*\n\s*I:\s*(-?[\d.]+|-inf) LUFS/),
|
|
88
|
+
range: num(/Loudness range:\s*\n\s*LRA:\s*(-?[\d.]+) LU/),
|
|
89
|
+
samplePeak: num(/Sample peak:\s*\n\s*Peak:\s*(-?[\d.]+|-inf) dBFS/),
|
|
90
|
+
truePeak: num(/True peak:\s*\n\s*Peak:\s*(-?[\d.]+|-inf) dBFS/),
|
|
91
|
+
// astats: how often the sound reached its peak, and how flat it stayed
|
|
92
|
+
// there. Clipped sound sits on its peak, flat, many times over.
|
|
93
|
+
peakCount: num(/Peak count:\s*([\d.]+)/),
|
|
94
|
+
flat: num(/Flat factor:\s*(-?[\d.]+)/),
|
|
95
|
+
};
|
|
96
|
+
const loud = [];
|
|
97
|
+
const silence = [];
|
|
98
|
+
let cur = null;
|
|
99
|
+
let from = null;
|
|
100
|
+
for (const line of fs.readFileSync(notes, "utf8").split("\n")) {
|
|
101
|
+
const f = /^frame:\d+\s+pts:\S+\s+pts_time:(\S+)/.exec(line);
|
|
102
|
+
if (f) {
|
|
103
|
+
cur = { t: Number(f[1]), m: -120, s: -120 };
|
|
104
|
+
loud.push(cur);
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
const m = /^lavfi\.([\w.]+)=(\S+)/.exec(line);
|
|
108
|
+
if (!m || !cur) continue;
|
|
109
|
+
const v = Number(m[2]);
|
|
110
|
+
if (m[1] === "r128.M") cur.m = v;
|
|
111
|
+
else if (m[1] === "r128.S") cur.s = v;
|
|
112
|
+
else if (m[1] === "silence_start") from = v;
|
|
113
|
+
else if (m[1] === "silence_end") {
|
|
114
|
+
silence.push({ from: from === null ? 0 : from, to: v });
|
|
115
|
+
from = null;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
if (from !== null) silence.push({ from, to: duration });
|
|
119
|
+
return { ...summary, loud, silence: frames.joinStretches(silence.map((s) => ({ from: Math.max(0, s.from), to: Math.min(duration, s.to) }))) };
|
|
120
|
+
} finally {
|
|
121
|
+
fs.rmSync(notes, { force: true });
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// The sound's outline: the loudest sample in each of `columns` slices, in
|
|
126
|
+
// dBFS, from a mono copy at 4 kHz.
|
|
127
|
+
function envelope(film, { duration, columns }) {
|
|
128
|
+
const r = spawnSync(FFMPEG, ["-v", "error", "-i", film, "-vn", "-ac", "1", "-ar", "4000", "-f", "f32le", "-"], { maxBuffer: Math.ceil(duration * 4000 * 4) + 1e6, timeout: 120_000 });
|
|
129
|
+
if (r.status !== 0 || !r.stdout) return null;
|
|
130
|
+
const n = Math.floor(r.stdout.length / 4);
|
|
131
|
+
const peaks = new Array(columns).fill(0);
|
|
132
|
+
for (let i = 0; i < n; i++) {
|
|
133
|
+
const v = Math.abs(r.stdout.readFloatLE(4 * i));
|
|
134
|
+
const col = Math.min(columns - 1, Math.floor(((i / 4000) / duration) * columns));
|
|
135
|
+
if (v > peaks[col]) peaks[col] = v;
|
|
136
|
+
}
|
|
137
|
+
return peaks.map((p) => (p > 0 ? 20 * Math.log10(p) : -120));
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// Black, still and silent stretches judged: each gets a `verdict` (meant,
|
|
141
|
+
// start, end, hold, warn or fail) and the kind's status is the worst. A film
|
|
142
|
+
// mostly black or silent fails; one mostly still only warns, since a film of
|
|
143
|
+
// slides is still on purpose.
|
|
144
|
+
function judgeStretches(kind, list, duration, allow, frame) {
|
|
145
|
+
const items = list.map((s) => {
|
|
146
|
+
const item = { ...s };
|
|
147
|
+
const whole = s.from <= frame && s.to >= duration - frame;
|
|
148
|
+
const meant = allow.some((a) => s.from >= a.from - 0.1 && s.to <= a.to + 0.1);
|
|
149
|
+
if (meant) item.verdict = "meant";
|
|
150
|
+
else if (whole) item.verdict = "fail";
|
|
151
|
+
else if (s.from <= frame) item.verdict = s.seconds <= RULES.start[kind] ? "start" : "warn";
|
|
152
|
+
else if (s.to >= duration - frame) item.verdict = s.seconds <= RULES.end[kind] ? "end" : "warn";
|
|
153
|
+
else item.verdict = s.seconds < RULES.hold[kind] ? "hold" : "warn";
|
|
154
|
+
return item;
|
|
155
|
+
});
|
|
156
|
+
const share = items.filter((s) => s.verdict !== "meant").reduce((a, s) => a + s.seconds, 0) / Math.max(0.001, duration);
|
|
157
|
+
const most = share >= RULES.most;
|
|
158
|
+
const status = items.some((s) => s.verdict === "fail") || (most && kind !== "still") ? "fail" : items.some((s) => s.verdict === "warn") || most ? "warn" : "pass";
|
|
159
|
+
return { status, share: +share.toFixed(3), stretches: items };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const at = (s) => `${s.toFixed(2)} s`;
|
|
163
|
+
const span = (s) => `${at(s.from)} to ${at(s.to)} (${s.seconds.toFixed(2)} s)`;
|
|
164
|
+
const WHY = { meant: "allowed", start: "at the start, allowed", end: "at the end, allowed", hold: "a short hold, allowed", warn: "look at it", fail: "most of the film" };
|
|
165
|
+
|
|
166
|
+
// The nearest beat to a time, and how far off it is in frames.
|
|
167
|
+
function nearest(list, t, fps) {
|
|
168
|
+
let best = null;
|
|
169
|
+
for (const b of list) if (best === null || Math.abs(b - t) < Math.abs(best - t)) best = b;
|
|
170
|
+
return best === null ? null : { beat: best, off: +((t - best) * fps).toFixed(2) };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// Checks a film. opts: { out, expect, seconds, lufs, cues, cuts, allow }
|
|
174
|
+
// (the command's options as given). Returns { pass, checks, dir, files }.
|
|
175
|
+
async function checkFilm(file, opts = {}) {
|
|
176
|
+
const film = path.resolve(file);
|
|
177
|
+
if (!fs.existsSync(film)) throw new Error(`${file} is not a file`);
|
|
178
|
+
const info = probe(film);
|
|
179
|
+
if (!info.duration || !info.width) throw new Error(`${file} could not be read as a video`);
|
|
180
|
+
const expect = parseExpect(opts.expect);
|
|
181
|
+
const seconds = parseSeconds(opts.seconds);
|
|
182
|
+
const target = opts.lufs === undefined || opts.lufs === null || opts.lufs === "" ? null : Number(opts.lufs);
|
|
183
|
+
if (target !== null && !(target < 0 && target > -70)) throw new Error(`--lufs "${opts.lufs}" should be a loudness like -14`);
|
|
184
|
+
const allow = parseAllow(opts.allow);
|
|
185
|
+
const cues = opts.cues ? readCues(path.resolve(opts.cues)) : null;
|
|
186
|
+
const dir = path.resolve(opts.out || path.join(path.dirname(film), "check"));
|
|
187
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
188
|
+
const duration = info.duration;
|
|
189
|
+
const fps = info.fps || 25;
|
|
190
|
+
const frame = 1.5 / fps;
|
|
191
|
+
|
|
192
|
+
const scan = await frames.scanVideo(film, { work: dir, duration });
|
|
193
|
+
const sound = info.audio ? await scanAudio(film, { work: dir, duration }) : null;
|
|
194
|
+
const { cuts, source } = await frames.findCuts(film, { info, work: dir, scan, given: opts.cuts || null });
|
|
195
|
+
|
|
196
|
+
const checks = [];
|
|
197
|
+
const add = (name, status, expected, found, extra = {}) => checks.push({ name, status, expected, found, ...extra });
|
|
198
|
+
|
|
199
|
+
// Size and frame rate.
|
|
200
|
+
const size = `${info.width}x${info.height}`;
|
|
201
|
+
if (expect.width) add("size", size === `${expect.width}x${expect.height}` ? "pass" : "fail", `${expect.width}x${expect.height}`, size);
|
|
202
|
+
else add("size", "info", "", size);
|
|
203
|
+
const shownFps = +fps.toFixed(3);
|
|
204
|
+
if (expect.fps) add("frame rate", Math.abs(fps - expect.fps) < 0.01 ? "pass" : "fail", `${expect.fps} fps`, `${shownFps} fps`);
|
|
205
|
+
else add("frame rate", "info", "", `${shownFps} fps`);
|
|
206
|
+
if (info.baseFps && Math.abs(info.baseFps - fps) > 0.01) add("steady frame rate", "warn", "one frame rate throughout", `${+info.baseFps.toFixed(3)} fps at most, ${shownFps} on average: the frame rate varies`);
|
|
207
|
+
if (info.sar && info.sar !== "1:1" && info.sar !== "0:1") add("square pixels", "warn", "1:1", info.sar);
|
|
208
|
+
|
|
209
|
+
// Length.
|
|
210
|
+
const length = +duration.toFixed(3);
|
|
211
|
+
if (seconds) add("length", length >= seconds.min && length <= seconds.max ? "pass" : "fail", seconds.text, `${length} s`);
|
|
212
|
+
else add("length", "info", "", `${length} s`);
|
|
213
|
+
|
|
214
|
+
// Black and still stretches. A black stretch is still too; it is told once.
|
|
215
|
+
const black = judgeStretches("black", scan.black, duration, allow, frame);
|
|
216
|
+
const stillOnly = scan.frozen.filter((f) => {
|
|
217
|
+
const covered = scan.black.reduce((a, b) => a + Math.max(0, Math.min(f.to, b.to) - Math.max(f.from, b.from)), 0);
|
|
218
|
+
return covered < 0.8 * f.seconds;
|
|
219
|
+
});
|
|
220
|
+
const still = judgeStretches("still", stillOnly, duration, allow, frame);
|
|
221
|
+
add("black", black.status, "no black stretch in the film", black.stretches.length ? `${black.stretches.length} stretch${black.stretches.length > 1 ? "es" : ""}` : "none", { stretches: black.stretches });
|
|
222
|
+
add("still picture", still.status, "no long still stretch", still.stretches.length ? `${still.stretches.length} stretch${still.stretches.length > 1 ? "es" : ""}` : "none", { stretches: still.stretches });
|
|
223
|
+
|
|
224
|
+
// The sound.
|
|
225
|
+
if (!sound) {
|
|
226
|
+
add("sound", target !== null ? "fail" : "info", target !== null ? "a sound track" : "", "no sound track");
|
|
227
|
+
} else {
|
|
228
|
+
const silence = judgeStretches("silence", sound.silence, duration, allow, frame);
|
|
229
|
+
const silent = !(sound.integrated > -70);
|
|
230
|
+
add("silence", silent ? (target !== null ? "fail" : "warn") : silence.status, "no long silence", silent ? "the sound is silent throughout" : silence.stretches.length ? `${silence.stretches.length} stretch${silence.stretches.length > 1 ? "es" : ""}` : "none", { stretches: silence.stretches });
|
|
231
|
+
const I = sound.integrated;
|
|
232
|
+
const shownI = Number.isFinite(I) ? `${I.toFixed(1)} LUFS` : "silent";
|
|
233
|
+
if (target !== null) add("loudness", Number.isFinite(I) && Math.abs(I - target) <= RULES.lufs ? "pass" : "fail", `${target} LUFS, give or take ${RULES.lufs}`, shownI, { range: sound.range });
|
|
234
|
+
else add("loudness", "info", "", shownI, { range: sound.range });
|
|
235
|
+
const tp = sound.truePeak;
|
|
236
|
+
add("true peak", !Number.isFinite(tp) || tp <= RULES.truePeak ? "pass" : tp <= 0 ? "warn" : "fail", `${RULES.truePeak} dBTP or lower`, Number.isFinite(tp) ? `${tp.toFixed(1)} dBTP` : "silent");
|
|
237
|
+
// Clipping: the sound reaches full scale, or sits flat on its peak many
|
|
238
|
+
// times over (clipped earlier, then turned down).
|
|
239
|
+
const sp = sound.samplePeak;
|
|
240
|
+
const flatTops = sound.flat > 1 && sound.peakCount >= 50;
|
|
241
|
+
add("clipping", (Number.isFinite(sp) && sp >= -0.05) || flatTops ? "fail" : "pass", "below full scale, no flat tops",
|
|
242
|
+
Number.isFinite(sp) ? `sample peak ${sp.toFixed(1)} dBFS${flatTops ? `, flat on its peak ${Math.round(sound.peakCount)} times` : ""}` : "silent");
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// The cuts against the beat. Soft changes found in the picture are shown
|
|
246
|
+
// but not judged: they may be crossfades, or something starting to move.
|
|
247
|
+
const judged = cuts.filter((c) => c.at > frame && c.hard);
|
|
248
|
+
if (cues) {
|
|
249
|
+
for (const c of cuts) {
|
|
250
|
+
const n = nearest(cues.beats, c.at, fps);
|
|
251
|
+
if (!n) continue;
|
|
252
|
+
c.beat = +n.beat.toFixed(3);
|
|
253
|
+
c.off = n.off;
|
|
254
|
+
c.onBar = cues.bars.some((b) => Math.abs(b - n.beat) < 0.001);
|
|
255
|
+
if (c.at > frame && c.hard) c.verdict = Math.abs(n.off) <= RULES.onBeat + 0.01 ? "on" : Math.abs(n.off) <= RULES.nearBeat + 0.01 ? "near" : "off";
|
|
256
|
+
}
|
|
257
|
+
const off = judged.filter((c) => c.verdict === "off").length;
|
|
258
|
+
const near = judged.filter((c) => c.verdict === "near").length;
|
|
259
|
+
const on = judged.length - off - near;
|
|
260
|
+
const soft = cuts.filter((c) => !c.hard).length;
|
|
261
|
+
add("cuts on beats", !judged.length ? "warn" : off ? "fail" : near ? "warn" : "pass", `within ${RULES.onBeat} frame of a beat`,
|
|
262
|
+
judged.length ? `${on} of ${judged.length} on the beat${near ? `, ${near} near it` : ""}${off ? `, ${off} off it` : ""}` : `no cut to judge${soft ? ` (${soft} soft change${soft > 1 ? "s" : ""} found; give --cuts)` : ""}`);
|
|
263
|
+
if (cues.seconds && Math.abs(cues.seconds - duration) > 1) add("cues length", "warn", `${length} s, as the film`, `${cues.seconds.toFixed(2)} s`);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const failed = checks.filter((c) => c.status === "fail");
|
|
267
|
+
const warned = checks.filter((c) => c.status === "warn");
|
|
268
|
+
const pass = !failed.length;
|
|
269
|
+
|
|
270
|
+
// The pictures: a frame for each cut, and the sound over time.
|
|
271
|
+
const shots = frames.shotsOf(cuts, duration);
|
|
272
|
+
const temp = shots.map((s) => ({ at: frames.settled(s), name: `.cut-${process.pid}-${s.index}`, label: s.label }));
|
|
273
|
+
const stills = await frames.grabFrames(film, temp, dir, { duration });
|
|
274
|
+
stills.forEach((s, i) => {
|
|
275
|
+
const c = cuts[i];
|
|
276
|
+
s.number = String(c.index);
|
|
277
|
+
s.at = c.at;
|
|
278
|
+
s.label = [c.label, c.verdict ? { on: "ON BEAT", near: `NEAR BEAT ${c.off > 0 ? "+" : ""}${c.off}F`, off: `OFF BEAT ${c.off > 0 ? "+" : ""}${c.off}F` }[c.verdict] : ""].filter(Boolean).join(" ");
|
|
279
|
+
s.labelColour = c.verdict === "off" ? "#F87171" : c.verdict === "near" ? "#FACC15" : c.verdict === "on" ? "#4ADE80" : "#7D8494";
|
|
280
|
+
});
|
|
281
|
+
const sheet = path.join(dir, "sheet.png");
|
|
282
|
+
try {
|
|
283
|
+
await frames.contactSheet(stills, sheet, { title: `${path.basename(film)} ${length} S ${size} ${shownFps} FPS ${cuts.length} CUT${cuts.length > 1 ? "S" : ""} (${source.toUpperCase()})` });
|
|
284
|
+
} finally {
|
|
285
|
+
for (const s of stills) fs.rmSync(s.file, { force: true });
|
|
286
|
+
}
|
|
287
|
+
const wave = path.join(dir, "wave.png");
|
|
288
|
+
await drawWave(wave, { film, duration, sound, target, cuts, cues, fps });
|
|
289
|
+
|
|
290
|
+
const result = {
|
|
291
|
+
file: path.relative(dir, film),
|
|
292
|
+
pass,
|
|
293
|
+
failed: failed.map((c) => c.name),
|
|
294
|
+
warnings: warned.map((c) => c.name),
|
|
295
|
+
checks,
|
|
296
|
+
video: { width: info.width, height: info.height, fps: shownFps, seconds: length, codec: info.codec, pixFmt: info.pixFmt },
|
|
297
|
+
audio: sound ? { codec: info.audioCodec, sampleRate: info.sampleRate, channels: info.channels, integrated: sound.integrated, range: sound.range, truePeak: sound.truePeak, samplePeak: sound.samplePeak } : null,
|
|
298
|
+
cuts: cuts.map((c) => ({ index: c.index, at: c.at, frame: Math.round(c.at * fps), source: c.source, hard: c.hard, label: c.label || undefined, beat: c.beat, off: c.off, onBar: c.onBar, verdict: c.verdict })),
|
|
299
|
+
cues: cues ? { fps: cues.fps, beats: cues.beats.length, bars: cues.bars.length, hits: cues.hits.map((h) => +h.toFixed(3)), bpm: cues.bpm, seconds: cues.seconds } : null,
|
|
300
|
+
allow,
|
|
301
|
+
rules: RULES,
|
|
302
|
+
files: { report: "CHECK.md", sheet: "sheet.png", wave: "wave.png" },
|
|
303
|
+
};
|
|
304
|
+
fs.writeFileSync(path.join(dir, "check.json"), JSON.stringify(result, null, 2) + "\n");
|
|
305
|
+
fs.writeFileSync(path.join(dir, "CHECK.md"), report(result, { film, source }));
|
|
306
|
+
return { ...result, dir };
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// CHECK.md: the verdict first, then every check, the stretches and the cuts.
|
|
310
|
+
function report(r, { film, source }) {
|
|
311
|
+
const lines = [];
|
|
312
|
+
const verdict = r.pass ? `PASS${r.warnings.length ? ` with ${r.warnings.length} warning${r.warnings.length > 1 ? "s" : ""}` : ""}` : `FAIL (${r.failed.join(", ")})`;
|
|
313
|
+
lines.push(`# ${path.basename(film)}: ${verdict}`, "");
|
|
314
|
+
lines.push(`${r.video.width}x${r.video.height} at ${r.video.fps} fps, ${r.video.seconds} s${r.audio ? `, sound ${r.audio.channels === 2 ? "in stereo" : `on ${r.audio.channels} channel${r.audio.channels > 1 ? "s" : ""}`} at ${r.audio.sampleRate} Hz` : ", no sound"}.`, "");
|
|
315
|
+
lines.push("| Check | Result | Asked for | Found |", "| --- | --- | --- | --- |");
|
|
316
|
+
for (const c of r.checks) lines.push(`| ${c.name} | ${c.status} | ${c.expected || ""} | ${c.found} |`);
|
|
317
|
+
const stretchChecks = r.checks.filter((c) => c.stretches && c.stretches.length);
|
|
318
|
+
if (stretchChecks.length) {
|
|
319
|
+
lines.push("", "## Stretches", "");
|
|
320
|
+
for (const c of stretchChecks) for (const s of c.stretches) lines.push(`- ${c.name === "still picture" ? "Still picture" : c.name[0].toUpperCase() + c.name.slice(1)} from ${span(s)}: ${WHY[s.verdict]}.`);
|
|
321
|
+
lines.push("", `A stretch inside the film shorter than ${RULES.hold.black} s of black, ${RULES.hold.still} s of still picture or ${RULES.hold.silence} s of silence counts as a hold. At the start up to ${RULES.start.black} s of black, ${RULES.start.still} s still or ${RULES.start.silence} s silent is allowed, and at the end up to ${RULES.end.black} s, ${RULES.end.still} s and ${RULES.end.silence} s. Pass --allow with the stretches you meant (like 27-30) to have them counted as meant.`);
|
|
322
|
+
}
|
|
323
|
+
lines.push("", "## Cuts", "");
|
|
324
|
+
const from = { timeline: "the timeline launch-film wrote next to the film", given: "--cuts", picture: "the picture (hard cuts, and soft changes that may be crossfades)" }[source];
|
|
325
|
+
lines.push(`Taken from ${from}.`, "");
|
|
326
|
+
if (r.cues) {
|
|
327
|
+
lines.push("| # | At | Frame | Nearest beat | Off by | On the beat |", "| --- | --- | --- | --- | --- | --- |");
|
|
328
|
+
for (const c of r.cuts) lines.push(`| ${c.index} | ${c.at.toFixed(3)} s | ${c.frame} | ${c.beat !== undefined ? `${c.beat.toFixed(3)} s${c.onBar ? " (bar)" : ""}` : ""} | ${c.off !== undefined ? `${c.off > 0 ? "+" : ""}${c.off} frames` : ""} | ${c.verdict || (c.hard ? "the start" : "soft change, not judged")} |`);
|
|
329
|
+
if (r.cues.hits.length) lines.push("", `Hits in the cues: ${r.cues.hits.map((h) => at(h)).join(", ")}.`);
|
|
330
|
+
} else {
|
|
331
|
+
lines.push("| # | At | Frame | Kind |", "| --- | --- | --- | --- |");
|
|
332
|
+
for (const c of r.cuts) lines.push(`| ${c.index} | ${c.at.toFixed(3)} s | ${c.frame} | ${c.label || (c.hard ? "cut" : "soft change")} |`);
|
|
333
|
+
lines.push("", "Give the music's cues.json with --cues to check the cuts against the beat.");
|
|
334
|
+
}
|
|
335
|
+
lines.push("", "## Pictures", "", "- sheet.png: a frame from each shot, once its entrance has played, with the cut's number and time.",
|
|
336
|
+
"- wave.png: the sound's outline and loudness over time, with the cuts as lines (green on the beat, yellow near it, red off it, white not judged), the beats and bars along the bottom, and the target loudness dashed.", "");
|
|
337
|
+
return lines.join("\n");
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// wave.png: the sound's outline in dBFS, its momentary and short-term
|
|
341
|
+
// loudness, the target, silent stretches, the cuts and the cues, over time.
|
|
342
|
+
async function drawWave(file, { film, duration, sound, target, cuts, cues, fps }) {
|
|
343
|
+
const W = 1600;
|
|
344
|
+
const H = 440;
|
|
345
|
+
const x0 = 70;
|
|
346
|
+
const x1 = W - 24;
|
|
347
|
+
const y0 = 58;
|
|
348
|
+
// The cues get a lane of their own under the chart.
|
|
349
|
+
const lane = cues ? 24 : 0;
|
|
350
|
+
const y1 = H - 48 - lane;
|
|
351
|
+
const c = draw.canvas(W, H, "#101317");
|
|
352
|
+
draw.rect(c, x0, y0, x1 - x0, y1 - y0, "#161A20");
|
|
353
|
+
const X = (t) => x0 + (t / duration) * (x1 - x0);
|
|
354
|
+
const Y = (db) => y0 + (Math.min(0, Math.max(-60, db)) / -60) * (y1 - y0);
|
|
355
|
+
for (let db = 0; db >= -60; db -= 10) {
|
|
356
|
+
draw.line(c, x0, Y(db), x1, Y(db), "#262B33");
|
|
357
|
+
const label = `${db}`;
|
|
358
|
+
draw.text(c, x0 - 10 - draw.textWidth(label, 2), Y(db) - 7, label, "#7D8494", 2);
|
|
359
|
+
}
|
|
360
|
+
// Time along the bottom: a label every 1, 2, 5, 10, 30 or 60 s.
|
|
361
|
+
const step = [1, 2, 5, 10, 15, 30, 60, 120, 300].find((s) => duration / s <= 16) || 600;
|
|
362
|
+
for (let t = 0; t <= duration + 0.001; t += step) {
|
|
363
|
+
draw.line(c, X(t), y1 + lane, X(t), y1 + lane + 6, "#7D8494");
|
|
364
|
+
const label = `${Math.round(t)} S`;
|
|
365
|
+
draw.text(c, Math.min(x1 - draw.textWidth(label, 2), Math.max(0, X(t) - draw.textWidth(label, 2) / 2)), y1 + lane + 14, label, "#AEB4C4", 2);
|
|
366
|
+
}
|
|
367
|
+
if (sound) {
|
|
368
|
+
for (const s of sound.silence) draw.rect(c, X(s.from), y0, Math.max(1, X(s.to) - X(s.from)), y1 - y0, "#7F1D2D", 0.45);
|
|
369
|
+
const env = envelope(film, { duration, columns: Math.round(x1 - x0) });
|
|
370
|
+
if (env) env.forEach((db, i) => db > -60 && draw.line(c, x0 + i, Y(db), x0 + i, y1, "#3A4250"));
|
|
371
|
+
const curve = (key, colour, width, alpha) => {
|
|
372
|
+
let last = null;
|
|
373
|
+
for (const p of sound.loud) {
|
|
374
|
+
const v = p[key];
|
|
375
|
+
const pt = v > -60 ? [X(p.t), Y(v)] : null;
|
|
376
|
+
if (pt && last) draw.line(c, last[0], last[1], pt[0], pt[1], colour, { width, alpha });
|
|
377
|
+
last = pt;
|
|
378
|
+
}
|
|
379
|
+
};
|
|
380
|
+
curve("m", "#4FA3FF", 1, 0.7);
|
|
381
|
+
curve("s", "#7EE0FF", 3, 1);
|
|
382
|
+
}
|
|
383
|
+
if (target !== null) {
|
|
384
|
+
draw.line(c, x0, Y(target), x1, Y(target), "#FFD166", { width: 2, dash: 8 });
|
|
385
|
+
// The label on a dark patch, so the curves don't run through it.
|
|
386
|
+
const label = `TARGET ${target} LUFS`;
|
|
387
|
+
const lx = x1 - draw.textWidth(label, 2) - 10;
|
|
388
|
+
draw.rect(c, lx - 6, Y(target) - 26, draw.textWidth(label, 2) + 12, 22, "#101317", 0.85);
|
|
389
|
+
draw.text(c, lx, Y(target) - 22, label, "#FFD166", 2);
|
|
390
|
+
}
|
|
391
|
+
if (cues) {
|
|
392
|
+
const top = y1 + 4;
|
|
393
|
+
const bottom = y1 + lane - 2;
|
|
394
|
+
draw.rect(c, x0, top, x1 - x0, bottom - top, "#1B2027");
|
|
395
|
+
for (const b of cues.beats) if (b <= duration) draw.line(c, X(b), bottom - 8, X(b), bottom, "#8A97A8");
|
|
396
|
+
for (const b of cues.bars) if (b <= duration) draw.line(c, X(b), top, X(b), bottom, "#D5DCE6", { width: 2 });
|
|
397
|
+
for (const h of cues.hits) {
|
|
398
|
+
if (h > duration) continue;
|
|
399
|
+
draw.line(c, X(h), y0, X(h), y1, "#FF5FA2", { width: 2, dash: 6 });
|
|
400
|
+
draw.rect(c, X(h) - 3, top, 6, bottom - top, "#FF5FA2");
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
for (const cut of cuts) {
|
|
404
|
+
const colour = cut.verdict === "off" ? "#F87171" : cut.verdict === "near" ? "#FACC15" : cut.verdict === "on" ? "#4ADE80" : cut.hard ? "#E5E7EB" : "#9CA3AF";
|
|
405
|
+
draw.line(c, X(cut.at), y0, X(cut.at), y1, colour, { width: 2, dash: cut.hard ? 0 : 5 });
|
|
406
|
+
draw.text(c, Math.min(x1 - 20, X(cut.at) + 4), y0 + 6, String(cut.index), colour, 2);
|
|
407
|
+
}
|
|
408
|
+
// The key, over the chart.
|
|
409
|
+
let kx = x0;
|
|
410
|
+
const key = (colour, label, dashed = false) => {
|
|
411
|
+
draw.line(c, kx, 26, kx + 22, 26, colour, { width: 3, dash: dashed ? 4 : 0 });
|
|
412
|
+
kx += 30 + draw.text(c, kx + 30, 20, label, "#C9CED8", 2) + 24;
|
|
413
|
+
};
|
|
414
|
+
key("#7EE0FF", "SHORT-TERM LUFS");
|
|
415
|
+
key("#4FA3FF", "MOMENTARY");
|
|
416
|
+
key("#3A4250", "PEAK DBFS");
|
|
417
|
+
if (target !== null) key("#FFD166", "TARGET", true);
|
|
418
|
+
key("#E5E7EB", "CUT");
|
|
419
|
+
if (cues) {
|
|
420
|
+
key("#8A97A8", "BEAT");
|
|
421
|
+
key("#D5DCE6", "BAR");
|
|
422
|
+
key("#FF5FA2", "HIT", true);
|
|
423
|
+
}
|
|
424
|
+
if (sound && sound.silence.length) key("#7F1D2D", "SILENCE");
|
|
425
|
+
if (sound && Number.isFinite(sound.integrated)) {
|
|
426
|
+
const label = `I ${sound.integrated.toFixed(1)} LUFS TP ${Number.isFinite(sound.truePeak) ? sound.truePeak.toFixed(1) : "-"} DBTP`;
|
|
427
|
+
draw.text(c, W - 24 - draw.textWidth(label, 2), 20, label, "#FFFFFF", 2);
|
|
428
|
+
} else if (!sound) draw.text(c, W - 24 - draw.textWidth("NO SOUND TRACK", 2), 20, "NO SOUND TRACK", "#F87171", 2);
|
|
429
|
+
await writePng(file, c);
|
|
430
|
+
return file;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
module.exports = { checkFilm, parseExpect, parseSeconds, parseAllow, judgeStretches, RULES };
|
package/src/chrome.js
CHANGED
|
@@ -304,4 +304,36 @@ async function stillOf({ html, files = {}, at = 0, W = 1920, H = 1080, scale = 1
|
|
|
304
304
|
}
|
|
305
305
|
}
|
|
306
306
|
|
|
307
|
-
|
|
307
|
+
// PNGs of pages, one browser for them all. Each page { html, files, W, H,
|
|
308
|
+
// at, until } is shot at `at` ms, or once its entrances have played when
|
|
309
|
+
// `at` is "end" (but not after `until`).
|
|
310
|
+
async function snapshots(pages) {
|
|
311
|
+
const browser = await launch({ W: 1920, H: 1080 });
|
|
312
|
+
const out = [];
|
|
313
|
+
try {
|
|
314
|
+
for (const p of pages) {
|
|
315
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "launch-film-page-"));
|
|
316
|
+
try {
|
|
317
|
+
fs.writeFileSync(path.join(dir, "index.html"), p.html);
|
|
318
|
+
for (const [name, data] of Object.entries(p.files || {})) fs.writeFileSync(path.join(dir, name), data);
|
|
319
|
+
const { page, exceptions } = await openPage(browser, dir, { W: p.W, H: p.H, scale: p.scale || 1 });
|
|
320
|
+
let at = p.at || 0;
|
|
321
|
+
if (at === "end") at = Math.round(Number(await evaluate(page, "window.__end ? window.__end() : 0")) || 0) + 150;
|
|
322
|
+
if (p.until) at = Math.min(at, p.until);
|
|
323
|
+
// The clock moves forward to the time, as in a render.
|
|
324
|
+
for (let ms = 0; ms < at; ms += 40) await evaluate(page, `__lfAdvance(${ms})`);
|
|
325
|
+
await evaluate(page, `__lfAdvance(${at}); if (window.__fit) window.__fit(); true`);
|
|
326
|
+
const shot = await page.call("Page.captureScreenshot", { format: "png" });
|
|
327
|
+
out.push({ png: Buffer.from(shot.data, "base64"), errors: exceptions });
|
|
328
|
+
await browser.send("Target.closeTarget", { targetId: page.targetId }).catch(() => {});
|
|
329
|
+
} finally {
|
|
330
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
} finally {
|
|
334
|
+
browser.close();
|
|
335
|
+
}
|
|
336
|
+
return out;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
module.exports = { findChrome, onPath, launch, openPage, renderPage, stillOf, snapshots, evaluate, CLOCK };
|
package/src/cues.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ─── cues ──────────────────────────────────────────────────────────────────
|
|
3
|
+
// A track's beats as frame numbers, in cues.json: written by a tool that
|
|
4
|
+
// fits music to a cut (musicfit) or by hand, and read by check to see
|
|
5
|
+
// whether the film's cuts land on the beat. Every number is a whole frame
|
|
6
|
+
// at `fps`, and frame 0 is the first frame of the film and of the track:
|
|
7
|
+
//
|
|
8
|
+
// { "fps": 30, "beats": [0, 15, 30, 45], "bars": [0, 60, 120],
|
|
9
|
+
// "hits": [825], "frames": 960, "bpm": 120 }
|
|
10
|
+
//
|
|
11
|
+
// fps and beats are needed. bars (each bar's first beat), hits (accents an
|
|
12
|
+
// edit should land on, such as the drop), frames (the track's length) and
|
|
13
|
+
// bpm are optional. Other keys are left alone, so a tool can add its own.
|
|
14
|
+
|
|
15
|
+
const fs = require("fs");
|
|
16
|
+
|
|
17
|
+
function readCues(file) {
|
|
18
|
+
let raw;
|
|
19
|
+
try {
|
|
20
|
+
raw = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
21
|
+
} catch (err) {
|
|
22
|
+
throw new Error(`${file} could not be read as JSON: ${err.message}`);
|
|
23
|
+
}
|
|
24
|
+
const problems = [];
|
|
25
|
+
const fps = Number(raw && raw.fps);
|
|
26
|
+
if (!(fps > 0 && fps <= 1000)) problems.push('"fps" must be the frames a second the numbers count in');
|
|
27
|
+
const list = (key, needed) => {
|
|
28
|
+
const v = raw && raw[key];
|
|
29
|
+
if (v === undefined || v === null) {
|
|
30
|
+
if (needed) problems.push(`"${key}" is missing`);
|
|
31
|
+
return [];
|
|
32
|
+
}
|
|
33
|
+
if (!Array.isArray(v) || v.some((n) => typeof n !== "number" || !Number.isFinite(n) || n < 0)) {
|
|
34
|
+
problems.push(`"${key}" must be a list of frame numbers`);
|
|
35
|
+
return [];
|
|
36
|
+
}
|
|
37
|
+
return [...new Set(v)].sort((a, b) => a - b);
|
|
38
|
+
};
|
|
39
|
+
const beats = list("beats", true);
|
|
40
|
+
const bars = list("bars", false);
|
|
41
|
+
const hits = list("hits", false);
|
|
42
|
+
if (raw && Array.isArray(raw.beats) && !raw.beats.length) problems.push('"beats" is empty');
|
|
43
|
+
if (problems.length) throw new Error(`${file}: ${problems.join("; ")}`);
|
|
44
|
+
const seconds = (frames) => frames.map((f) => f / fps);
|
|
45
|
+
return {
|
|
46
|
+
fps,
|
|
47
|
+
beats: seconds(beats),
|
|
48
|
+
bars: seconds(bars),
|
|
49
|
+
hits: seconds(hits),
|
|
50
|
+
seconds: Number(raw.frames) > 0 ? Number(raw.frames) / fps : null,
|
|
51
|
+
bpm: Number(raw.bpm) > 0 ? Number(raw.bpm) : null,
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
module.exports = { readCues };
|
package/src/draw.js
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ─── pictures in pixels ────────────────────────────────────────────────────
|
|
3
|
+
// A small raster for the pictures check and frames draw (a contact sheet's
|
|
4
|
+
// labels, a loudness chart): RGBA pixels in a Buffer, written as PNG or JPEG
|
|
5
|
+
// by ffmpeg. Text is set in this file's own 5x7 pixel face, scaled in whole
|
|
6
|
+
// pixels, so the pictures come out the same on every machine and need no
|
|
7
|
+
// font installed.
|
|
8
|
+
|
|
9
|
+
// Each glyph is seven rows of five pixels, top row first, the leftmost
|
|
10
|
+
// pixel the highest bit: two hex digits a row.
|
|
11
|
+
const GLYPHS = {
|
|
12
|
+
"0": "0e11131519110e", "1": "040c040404040e", "2": "0e11010204081f", "3": "1f02040201110e",
|
|
13
|
+
"4": "02060a121f0202", "5": "1f101e0101110e", "6": "0608101e11110e", "7": "1f010204080808",
|
|
14
|
+
"8": "0e11110e11110e", "9": "0e11110f01020c",
|
|
15
|
+
A: "0e11111f111111", B: "1e11111e11111e", C: "0e11101010110e", D: "1c12111111121c",
|
|
16
|
+
E: "1f10101e10101f", F: "1f10101e101010", G: "0e11101711110f", H: "1111111f111111",
|
|
17
|
+
I: "0e04040404040e", J: "0702020202120c", K: "11121418141211", L: "1010101010101f",
|
|
18
|
+
M: "111b1515111111", N: "11111915131111", O: "0e11111111110e", P: "1e11111e101010",
|
|
19
|
+
Q: "0e11111115120d", R: "1e11111e141211", S: "0f10100e01011e", T: "1f040404040404",
|
|
20
|
+
U: "1111111111110e", V: "11111111110a04", W: "1111111515150a", X: "11110a040a1111",
|
|
21
|
+
Y: "1111110a040404", Z: "1f01020408101f",
|
|
22
|
+
" ": "00000000000000", ".": "00000000000c0c", ",": "000000000c0408", "-": "0000000e000000",
|
|
23
|
+
"+": "0004041f040400", ":": "000c0c000c0c00", "/": "01020204080810", "%": "18190204081303",
|
|
24
|
+
"#": "0a0a1f0a1f0a0a", "(": "02040808080402", ")": "08040202020408", "=": "00001f001f0000",
|
|
25
|
+
"@": "0e11171517100e", "<": "02040810080402", ">": "08040201020408", "|": "04040404040404",
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const rows = (code) => Array.from({ length: 7 }, (_, i) => parseInt(code.slice(2 * i, 2 * i + 2), 16));
|
|
29
|
+
const FACE = Object.fromEntries(Object.entries(GLYPHS).map(([ch, code]) => [ch, rows(code)]));
|
|
30
|
+
|
|
31
|
+
// A colour as [r, g, b] from "#RRGGBB".
|
|
32
|
+
const hex = (h) => [1, 3, 5].map((k) => parseInt(String(h).replace("#", "").slice(k - 1, k + 1), 16));
|
|
33
|
+
|
|
34
|
+
function canvas(width, height, fill = "#000000") {
|
|
35
|
+
const data = Buffer.alloc(width * height * 4);
|
|
36
|
+
const [r, g, b] = hex(fill);
|
|
37
|
+
for (let i = 0; i < data.length; i += 4) {
|
|
38
|
+
data[i] = r;
|
|
39
|
+
data[i + 1] = g;
|
|
40
|
+
data[i + 2] = b;
|
|
41
|
+
data[i + 3] = 255;
|
|
42
|
+
}
|
|
43
|
+
return { width, height, data };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// One pixel, blended over what is there.
|
|
47
|
+
function dot(c, x, y, rgb, alpha = 1) {
|
|
48
|
+
x = Math.round(x);
|
|
49
|
+
y = Math.round(y);
|
|
50
|
+
if (x < 0 || y < 0 || x >= c.width || y >= c.height) return;
|
|
51
|
+
const i = 4 * (y * c.width + x);
|
|
52
|
+
for (let k = 0; k < 3; k++) c.data[i + k] = Math.round(c.data[i + k] * (1 - alpha) + rgb[k] * alpha);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function rect(c, x, y, w, h, colour, alpha = 1) {
|
|
56
|
+
const rgb = hex(colour);
|
|
57
|
+
const x0 = Math.max(0, Math.round(x));
|
|
58
|
+
const y0 = Math.max(0, Math.round(y));
|
|
59
|
+
const x1 = Math.min(c.width, Math.round(x + w));
|
|
60
|
+
const y1 = Math.min(c.height, Math.round(y + h));
|
|
61
|
+
for (let yy = y0; yy < y1; yy++) for (let xx = x0; xx < x1; xx++) dot(c, xx, yy, rgb, alpha);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// A line `width` pixels thick; `dash` draws every other `dash` pixels.
|
|
65
|
+
function line(c, x0, y0, x1, y1, colour, { width = 1, alpha = 1, dash = 0 } = {}) {
|
|
66
|
+
const rgb = hex(colour);
|
|
67
|
+
const steps = Math.max(1, Math.ceil(Math.max(Math.abs(x1 - x0), Math.abs(y1 - y0))));
|
|
68
|
+
const r = (width - 1) / 2;
|
|
69
|
+
const seen = new Set();
|
|
70
|
+
for (let s = 0; s <= steps; s++) {
|
|
71
|
+
if (dash && Math.floor(s / dash) % 2) continue;
|
|
72
|
+
const x = x0 + ((x1 - x0) * s) / steps;
|
|
73
|
+
const y = y0 + ((y1 - y0) * s) / steps;
|
|
74
|
+
for (let dy = -Math.floor(r); dy <= Math.ceil(r); dy++) {
|
|
75
|
+
for (let dx = -Math.floor(r); dx <= Math.ceil(r); dx++) {
|
|
76
|
+
const key = `${Math.round(x + dx)},${Math.round(y + dy)}`;
|
|
77
|
+
if (seen.has(key)) continue;
|
|
78
|
+
seen.add(key);
|
|
79
|
+
dot(c, x + dx, y + dy, rgb, alpha);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const textWidth = (str, size = 2) => Math.max(0, String(str).length * 6 * size - size);
|
|
86
|
+
|
|
87
|
+
// Sets text with its top left corner at (x, y). Returns the width it took.
|
|
88
|
+
function text(c, x, y, str, colour, size = 2) {
|
|
89
|
+
const rgb = hex(colour);
|
|
90
|
+
let at = Math.round(x);
|
|
91
|
+
for (const ch of String(str).toUpperCase()) {
|
|
92
|
+
const glyph = FACE[ch] || FACE[" "];
|
|
93
|
+
for (let row = 0; row < 7; row++) {
|
|
94
|
+
for (let col = 0; col < 5; col++) {
|
|
95
|
+
if (!(glyph[row] & (16 >> col))) continue;
|
|
96
|
+
for (let sy = 0; sy < size; sy++) for (let sx = 0; sx < size; sx++) dot(c, at + col * size + sx, Math.round(y) + row * size + sy, rgb);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
at += 6 * size;
|
|
100
|
+
}
|
|
101
|
+
return at - Math.round(x) - size;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Copies a picture ({ data, width, height }, RGBA) in at (x, y).
|
|
105
|
+
function blit(c, img, x, y) {
|
|
106
|
+
for (let yy = 0; yy < img.height; yy++) {
|
|
107
|
+
const ty = y + yy;
|
|
108
|
+
if (ty < 0 || ty >= c.height) continue;
|
|
109
|
+
for (let xx = 0; xx < img.width; xx++) {
|
|
110
|
+
const tx = x + xx;
|
|
111
|
+
if (tx < 0 || tx >= c.width) continue;
|
|
112
|
+
img.data.copy(c.data, 4 * (ty * c.width + tx), 4 * (yy * img.width + xx), 4 * (yy * img.width + xx) + 4);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
module.exports = { canvas, rect, line, text, textWidth, blit, dot, hex, FACE };
|