launch-film 0.2.0 → 0.3.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 +53 -28
- package/THIRD_PARTY.md +1 -1
- package/bin/launch-film.js +417 -91
- package/package.json +4 -4
- package/skills/launch-film/SKILL.md +23 -19
- package/src/audio.js +79 -7
- package/src/brand.js +123 -21
- package/src/check.js +57 -27
- package/src/chrome.js +471 -53
- package/src/confine.js +164 -0
- package/src/ffmpeg.js +334 -49
- package/src/film.js +488 -36
- package/src/fonts.js +36 -8
- package/src/frames.js +70 -27
- package/src/logo.js +24 -10
- package/src/motion.js +12 -4
- package/src/out.js +1362 -0
- package/src/plan.js +9 -3
- package/src/programs.js +422 -0
- package/src/scene.js +8 -5
- package/src/stills.js +166 -102
- package/src/store.js +3 -2
- package/src/words.js +53 -8
package/src/confine.js
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ─── files a film.json or brand.json names ─────────────────────────────────
|
|
3
|
+
// Run by its own user, launch-film reads any file a film.json or brand.json
|
|
4
|
+
// names: a track kept elsewhere, a kit's logo by an absolute path. Where it
|
|
5
|
+
// runs for others, who give it these files (makersmcp's hosted service),
|
|
6
|
+
// LAUNCH_FILM_CONFINE is set, to anything but 0, and such a file may name
|
|
7
|
+
// only files in its own folder. A name that is absolute or climbs with ..
|
|
8
|
+
// and lands outside the folder is refused, however long it is and whether
|
|
9
|
+
// or not anything is there, and so is one in the folder that a link leads
|
|
10
|
+
// out of it. A file in the folder may not be a list of other files that
|
|
11
|
+
// ffmpeg opens wherever they are, such as an HLS playlist (listOf): a name
|
|
12
|
+
// says nothing of what such a list names.
|
|
13
|
+
|
|
14
|
+
const fs = require("fs");
|
|
15
|
+
const path = require("path");
|
|
16
|
+
|
|
17
|
+
function confined() {
|
|
18
|
+
const value = process.env.LAUNCH_FILM_CONFINE;
|
|
19
|
+
return value !== undefined && value !== "" && value !== "0";
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const inside = (folder, at) => {
|
|
23
|
+
const rel = path.relative(folder, at);
|
|
24
|
+
return rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
// Why `name`, which `of` names from its folder `folder`, may not be read:
|
|
28
|
+
// "is outside <of>'s folder", "leads out of <of>'s folder through a link",
|
|
29
|
+
// or null when it may be read, as always without LAUNCH_FILM_CONFINE. A
|
|
30
|
+
// name that is not there passes, to be told of as missing.
|
|
31
|
+
function outside(folder, name, of) {
|
|
32
|
+
if (!confined()) return null;
|
|
33
|
+
const at = path.resolve(folder, String(name));
|
|
34
|
+
if (!inside(folder, at)) return `is outside ${of}'s folder`;
|
|
35
|
+
let real;
|
|
36
|
+
try {
|
|
37
|
+
real = fs.realpathSync(at);
|
|
38
|
+
} catch {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
let base = folder;
|
|
42
|
+
try {
|
|
43
|
+
base = fs.realpathSync(folder);
|
|
44
|
+
} catch {
|
|
45
|
+
// The folder as it is named.
|
|
46
|
+
}
|
|
47
|
+
return inside(base, real) ? null : `leads out of ${of}'s folder through a link`;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// The lists of other files that ffmpeg opens on its own, by the marks its
|
|
51
|
+
// probes look for in a file's first bytes, read as latin1 so that a byte is
|
|
52
|
+
// a character: ffmpeg reads at most PROBE bytes to tell a file's kind, and
|
|
53
|
+
// its probes stop at the first NUL byte. A playlist named track.wav or
|
|
54
|
+
// logo.png is read as one all the same.
|
|
55
|
+
const LISTS = [
|
|
56
|
+
["an HLS playlist", /^(?:\xEF\xBB\xBF)?\s*#EXTM3U/],
|
|
57
|
+
["a DASH manifest", /<MPD/i],
|
|
58
|
+
["an ffconcat list", /^(?:\xEF\xBB\xBF)?\s*ffconcat\s+version/i],
|
|
59
|
+
["an IMF composition playlist", /<CompositionPlaylist/i],
|
|
60
|
+
];
|
|
61
|
+
const PROBE = 5_000_000;
|
|
62
|
+
|
|
63
|
+
// The length of the ID3v2 tag whose first bytes are `head`, as ffmpeg tells
|
|
64
|
+
// one (ff_id3v2_match and ff_id3v2_tag_len): the bytes "ID3", a version and
|
|
65
|
+
// a revision that are not 0xFF, and a size in four bytes of seven bits each,
|
|
66
|
+
// after the tag's 10-byte header, with a footer of 10 bytes more when its
|
|
67
|
+
// flags say so. 0 when it is no such tag.
|
|
68
|
+
const TAG = 10;
|
|
69
|
+
function tagLength(head) {
|
|
70
|
+
if (head.length < TAG || head.toString("latin1", 0, 3) !== "ID3" || head[3] === 0xff || head[4] === 0xff || head.subarray(6, TAG).some((b) => b & 0x80)) return 0;
|
|
71
|
+
return TAG + head[6] * 2 ** 21 + head[7] * 2 ** 14 + head[8] * 2 ** 7 + head[9] + (head[5] & 0x10 ? TAG : 0);
|
|
72
|
+
}
|
|
73
|
+
// The most tags in a row looked past: no sound or picture has more.
|
|
74
|
+
const TAGS = 1000;
|
|
75
|
+
|
|
76
|
+
// The text of `fd` from `start`, as a probe reads it: up to its first NUL
|
|
77
|
+
// byte, at most PROBE bytes.
|
|
78
|
+
function textAt(fd, start) {
|
|
79
|
+
const chunk = Buffer.alloc(1 << 16);
|
|
80
|
+
const parts = [];
|
|
81
|
+
for (let at = start; at < start + PROBE;) {
|
|
82
|
+
const n = fs.readSync(fd, chunk, 0, Math.min(chunk.length, start + PROBE - at), at);
|
|
83
|
+
if (n <= 0) break;
|
|
84
|
+
const end = chunk.subarray(0, n).indexOf(0);
|
|
85
|
+
parts.push(Buffer.from(chunk.subarray(0, end < 0 ? n : end)));
|
|
86
|
+
if (end >= 0) break;
|
|
87
|
+
at += n;
|
|
88
|
+
}
|
|
89
|
+
return Buffer.concat(parts).toString("latin1");
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// With LAUNCH_FILM_CONFINE set, which of those lists the file `file` is
|
|
93
|
+
// ("an HLS playlist"), or null: always null without it, and for what is
|
|
94
|
+
// not a regular file, which is told of as what it is.
|
|
95
|
+
//
|
|
96
|
+
// ffmpeg skips an ID3v2 tag at a file's start before its probes look at
|
|
97
|
+
// it, and reads past every tag in a row there before a list is read: a
|
|
98
|
+
// playlist behind a tag of 10 bytes, whose header has a NUL byte, was read
|
|
99
|
+
// as one, its files outside the folder too. So the marks are looked for
|
|
100
|
+
// from the file's start, from the end of the first tag, where the probes
|
|
101
|
+
// look, and from the end of the last, where the list is read, each text up
|
|
102
|
+
// to its first NUL. The tags are passed over, not read.
|
|
103
|
+
function listOf(file) {
|
|
104
|
+
if (!confined()) return null;
|
|
105
|
+
let fd = null;
|
|
106
|
+
try {
|
|
107
|
+
const stat = fs.statSync(file);
|
|
108
|
+
if (!stat.isFile()) return null;
|
|
109
|
+
fd = fs.openSync(file, "r");
|
|
110
|
+
const head = Buffer.alloc(TAG);
|
|
111
|
+
let first = null;
|
|
112
|
+
let last = null;
|
|
113
|
+
for (let at = 0, tags = 0; tags < TAGS; tags++) {
|
|
114
|
+
if (fs.readSync(fd, head, 0, TAG, at) < TAG) break;
|
|
115
|
+
const length = tagLength(head);
|
|
116
|
+
if (!length) break;
|
|
117
|
+
at += length;
|
|
118
|
+
if (at >= stat.size) break;
|
|
119
|
+
if (first === null) first = at;
|
|
120
|
+
last = at;
|
|
121
|
+
}
|
|
122
|
+
for (const start of new Set([0, first, last].filter((at) => at !== null))) {
|
|
123
|
+
const text = textAt(fd, start);
|
|
124
|
+
const found = LISTS.find(([, mark]) => mark.test(text));
|
|
125
|
+
if (found) return found[0];
|
|
126
|
+
}
|
|
127
|
+
return null;
|
|
128
|
+
} catch {
|
|
129
|
+
// One that cannot be read is told of when it is read.
|
|
130
|
+
return null;
|
|
131
|
+
} finally {
|
|
132
|
+
if (fd !== null) fs.closeSync(fd);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Why the film given to check or frames, `file`, said as `named`, may not be
|
|
137
|
+
// read, with LAUNCH_FILM_CONFINE set: it is one of those lists, which ffmpeg
|
|
138
|
+
// would follow as it reads the film. null when it may be read.
|
|
139
|
+
function filmListed(file, named) {
|
|
140
|
+
const list = listOf(file);
|
|
141
|
+
return list ? `${named} is ${list}, whose files ffmpeg would open wherever they are, which LAUNCH_FILM_CONFINE does not allow: give the film itself` : null;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// A name as a message shows it, on one line: a line break or another
|
|
145
|
+
// control character in it is written escaped, as a line of its own could
|
|
146
|
+
// pass for one of launch-film's. A film.json, a brand.json or a cues.json can
|
|
147
|
+
// name anything.
|
|
148
|
+
const CONTROL = /[\p{Cc}\u2028\u2029]/u;
|
|
149
|
+
const oneLine = (name) => String(name).replace(new RegExp(CONTROL.source, "gu"), (c) => ({ "\n": "\\n", "\r": "\\r", "\t": "\\t" })[c] || `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
150
|
+
|
|
151
|
+
// A name as it is said in a message: on one line (oneLine), and cut in the
|
|
152
|
+
// middle when it is longer than `room`, as one made to slip past a check,
|
|
153
|
+
// which runs to thousands of characters, is.
|
|
154
|
+
const said = (name, room = 100) => {
|
|
155
|
+
const text = oneLine(name);
|
|
156
|
+
const head = Math.round(room / 2);
|
|
157
|
+
return text.length > room ? `${text.slice(0, head)}...${text.slice(-(room - head - 10))}` : text;
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
// A path made from such a name, as a message says it: cut only past 300
|
|
161
|
+
// characters, so that a folder's own long path is said whole.
|
|
162
|
+
const saidPath = (file) => said(file, 300);
|
|
163
|
+
|
|
164
|
+
module.exports = { confined, outside, listOf, filmListed, said, saidPath, oneLine, CONTROL };
|
package/src/ffmpeg.js
CHANGED
|
@@ -3,8 +3,28 @@
|
|
|
3
3
|
// ffmpeg encodes the frames, reads and writes pictures as raw pixels, joins
|
|
4
4
|
// the clips and lays the sound under them. LAUNCH_FILM_FFMPEG and
|
|
5
5
|
// LAUNCH_FILM_FFPROBE point at other builds.
|
|
6
|
+
//
|
|
7
|
+
// ffmpeg reads a picture's name with a % in it as a numbered sequence (in a
|
|
8
|
+
// folder named take%d, logo.png is looked for as take1/logo.png), both when
|
|
9
|
+
// it reads a picture and when it writes one. So a picture whose name has a %
|
|
10
|
+
// is read with the pattern turned off, and every picture is written with
|
|
11
|
+
// -update 1, which takes its name as it is; ffmpeg 4.4 has both. Only such a
|
|
12
|
+
// name is read that way, since it makes ffmpeg pick the decoder by the
|
|
13
|
+
// name's extension where it otherwise reads what the file holds: a JPEG
|
|
14
|
+
// saved as .png still reads.
|
|
15
|
+
//
|
|
16
|
+
// ffmpeg 4.4 that cannot write the whole of a picture, as on a full disk,
|
|
17
|
+
// leaves it cut short and still exits with 0, so every picture written is
|
|
18
|
+
// read back to its end (writePicture).
|
|
6
19
|
|
|
20
|
+
const fs = require("fs");
|
|
21
|
+
const path = require("path");
|
|
7
22
|
const { spawn, spawnSync } = require("child_process");
|
|
23
|
+
const { track, full } = require("./out");
|
|
24
|
+
const { short } = require("./programs");
|
|
25
|
+
// A file's name as a message says it: on one line, and cut when long, as a
|
|
26
|
+
// film.json or brand.json can name anything (confine.js).
|
|
27
|
+
const confine = require("./confine");
|
|
8
28
|
|
|
9
29
|
const FFMPEG = process.env.LAUNCH_FILM_FFMPEG || "ffmpeg";
|
|
10
30
|
const FFPROBE = process.env.LAUNCH_FILM_FFPROBE || "ffprobe";
|
|
@@ -16,23 +36,127 @@ function available() {
|
|
|
16
36
|
return m ? m[1] : "unknown";
|
|
17
37
|
}
|
|
18
38
|
|
|
19
|
-
|
|
20
|
-
|
|
39
|
+
const PICTURE = /\.(png|jpe?g|webp|bmp|tiff?)$/i;
|
|
40
|
+
|
|
41
|
+
// The arguments that open `file` as an input (see above).
|
|
42
|
+
function input(file) {
|
|
43
|
+
return String(file).includes("%") && PICTURE.test(file) ? ["-f", "image2", "-pattern_type", "none", "-i", file] : ["-i", file];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// The arguments that write one picture to `file` (see above).
|
|
47
|
+
const picture = (file) => ["-update", "1", file];
|
|
48
|
+
|
|
49
|
+
// Whether a picture ffmpeg wrote is whole: a PNG ends with its IEND chunk
|
|
50
|
+
// and a JPEG with its end marker. Another kind only has to be there.
|
|
51
|
+
function whole(file) {
|
|
52
|
+
let fd = null;
|
|
53
|
+
try {
|
|
54
|
+
fd = fs.openSync(file, "r");
|
|
55
|
+
const size = fs.fstatSync(fd).size;
|
|
56
|
+
const tail = Buffer.alloc(Math.min(12, size));
|
|
57
|
+
fs.readSync(fd, tail, 0, tail.length, size - tail.length);
|
|
58
|
+
const ext = path.extname(file).toLowerCase();
|
|
59
|
+
if (ext === ".png") return tail.length === 12 && tail.toString("latin1", 4, 8) === "IEND";
|
|
60
|
+
if (ext === ".jpg" || ext === ".jpeg") return tail.length >= 2 && tail[tail.length - 2] === 0xff && tail[tail.length - 1] === 0xd9;
|
|
61
|
+
return size > 0;
|
|
62
|
+
} catch {
|
|
63
|
+
return false;
|
|
64
|
+
} finally {
|
|
65
|
+
if (fd !== null) fs.closeSync(fd);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Writes one picture to `file` with ffmpeg (`args` up to the output), and
|
|
70
|
+
// fails, after `what` it was doing, when it is not whole. A picture ffmpeg
|
|
71
|
+
// found no frame for, as at a time past the end of a video's picture, is
|
|
72
|
+
// said as `none`: ffmpeg 4.4 then writes nothing and ends well, where newer
|
|
73
|
+
// builds fail, and either was told of as a disk that is full or in ffmpeg's
|
|
74
|
+
// own words. The file is cleared first, so that one left there is never
|
|
75
|
+
// taken for the new one.
|
|
76
|
+
async function writePicture(args, file, what, { none = null, ...opts } = {}) {
|
|
77
|
+
fs.rmSync(file, { force: true });
|
|
78
|
+
const r = await run([...args, ...picture(file)], opts);
|
|
79
|
+
if (r.short) throw Object.assign(new Error(r.short), { short: true });
|
|
80
|
+
const nothing = !fs.existsSync(file) && (r.code === 0 || /Nothing was written into output file|Output file is empty/.test(r.stderr));
|
|
81
|
+
if (nothing && none) throw new Error(`${what}: ${none}`);
|
|
82
|
+
if (r.code !== 0) throw new Error(`${what}: ${why(r, { out: file })}`);
|
|
83
|
+
if (nothing) throw new Error(`${what}: ffmpeg wrote no picture`);
|
|
84
|
+
if (!whole(file)) throw new Error(`${what}: the picture was cut short, most often because the disk is full`);
|
|
85
|
+
return r;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Why a run of ffmpeg or ffprobe ({ code, signal, stderr }) failed: the end
|
|
89
|
+
// of its own words, else the signal that ended it, else its exit code. One
|
|
90
|
+
// killed outright with no word was most often ended by the system running
|
|
91
|
+
// out of memory. ffmpeg's note that it left out a line said again ("Last
|
|
92
|
+
// message repeated 1 times") is no reason. When it says the disk is full as
|
|
93
|
+
// it writes the file `out`, it is said which disk, and what to do.
|
|
94
|
+
function why(r, { lines = 3, name = "ffmpeg", out = null } = {}) {
|
|
95
|
+
// A name in them can hold a control character of its own, as a carriage
|
|
96
|
+
// return that would write over the line: it is written escaped.
|
|
97
|
+
const own = String(r.stderr || "").trim().split("\n").filter((line) => line.trim() && !/^\s*Last message repeated \d+ times?\s*$/.test(line));
|
|
98
|
+
const said = confine.oneLine(own.slice(-lines).join(" | "));
|
|
99
|
+
if (said) return `${name} failed: ${said}${out && /No space left on device/i.test(said) ? `. ${full(out)}` : ""}`;
|
|
100
|
+
if (r.signal) return `${name} was stopped by ${r.signal}${r.signal === "SIGKILL" ? ", most often because the system ran out of memory" : ""}`;
|
|
101
|
+
return `${name} failed with exit code ${r.code}`;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// What ffmpeg and ffprobe say, on 4.4 as on newer builds, when what they
|
|
105
|
+
// were given holds nothing of the kind asked for, as a picture given as a
|
|
106
|
+
// sound, or is no file they read at all, as a text file. Anything else they
|
|
107
|
+
// fail with is said in their own words: a build that refuses the file, as
|
|
108
|
+
// a guard of a hosted service does by its name, is no file without sound.
|
|
109
|
+
const NOTHING = /does not contain any stream|Invalid data found when processing input/;
|
|
110
|
+
|
|
111
|
+
// Why a synchronous run of ffmpeg or ffprobe (spawnSync's result) that
|
|
112
|
+
// failed could not read its input, in its own words, or null when the input
|
|
113
|
+
// holds nothing it reads. One that could not be started, as when there is
|
|
114
|
+
// no ffprobe, says so.
|
|
115
|
+
function unread(r, name) {
|
|
116
|
+
if (r.error) {
|
|
117
|
+
const said = { ENOENT: "no such file", EACCES: "permission denied" }[r.error.code];
|
|
118
|
+
return r.error.code === "ETIMEDOUT" ? `${name} did not end in time` : `${name} could not be started: ${said ? `${said} (${r.error.code})` : r.error.message}`;
|
|
119
|
+
}
|
|
120
|
+
const said = String(r.stderr || "");
|
|
121
|
+
return NOTHING.test(said) ? null : why({ code: r.status, signal: r.signal, stderr: said }, { lines: 1, name });
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// A synchronous run (spawnSync's result) that a signal ended: an error that
|
|
125
|
+
// says so, after `what` it was doing. Its own timeout's is not one; the
|
|
126
|
+
// caller tells of that.
|
|
127
|
+
function stoppedSync(r, name, what) {
|
|
128
|
+
if (!r.signal || (r.error && r.error.code === "ETIMEDOUT")) return null;
|
|
129
|
+
return Object.assign(new Error(`${what}: ${why({ signal: r.signal }, { name })}`), { signal: r.signal });
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Runs ffmpeg and resolves { code, signal, stderr } (the end of it). A
|
|
133
|
+
// filter's own report (ebur128's summary) needs loglevel "info".
|
|
134
|
+
//
|
|
135
|
+
// A process the system had no file descriptor for (EMFILE, ENFILE) comes
|
|
136
|
+
// back from spawn with no pipes, and its error comes next: its error listener
|
|
137
|
+
// is the first thing set, and its pipes are touched only when it has them.
|
|
138
|
+
// Touched as they were, they threw, and the error had no listener, which
|
|
139
|
+
// ended launch-film with Node's stack trace.
|
|
21
140
|
function run(args, { input = null, timeout = 0, loglevel = "error" } = {}) {
|
|
22
141
|
return new Promise((resolve) => {
|
|
23
|
-
const child = spawn(FFMPEG, ["-hide_banner", "-nostats", "-loglevel", loglevel, "-y", ...args], { stdio: [input ? "pipe" : "ignore", "ignore", "pipe"] });
|
|
142
|
+
const child = track(spawn(FFMPEG, ["-hide_banner", "-nostats", "-loglevel", loglevel, "-y", ...args], { stdio: [input ? "pipe" : "ignore", "ignore", "pipe"] }));
|
|
143
|
+
child.on("error", (err) => resolve({ code: -1, signal: null, stderr: err.message, short: short(err, "ffmpeg") }));
|
|
144
|
+
if (!child.stderr) return;
|
|
24
145
|
let stderr = "";
|
|
25
146
|
child.stderr.on("data", (d) => (stderr = (stderr + d).slice(-6000)));
|
|
26
147
|
let timer = null;
|
|
148
|
+
let late = false;
|
|
27
149
|
if (timeout) {
|
|
28
|
-
timer = setTimeout(() =>
|
|
150
|
+
timer = setTimeout(() => {
|
|
151
|
+
late = true;
|
|
152
|
+
child.kill("SIGKILL");
|
|
153
|
+
}, timeout);
|
|
29
154
|
timer.unref();
|
|
30
155
|
}
|
|
31
|
-
child.on("close", (code) => {
|
|
156
|
+
child.on("close", (code, signal) => {
|
|
32
157
|
if (timer) clearTimeout(timer);
|
|
33
|
-
resolve({ code, stderr });
|
|
158
|
+
resolve({ code, signal, stderr: late ? `${stderr}\nit took longer than ${Math.round(timeout / 1000)} s` : stderr });
|
|
34
159
|
});
|
|
35
|
-
child.on("error", (err) => resolve({ code: -1, stderr: err.message }));
|
|
36
160
|
if (input) {
|
|
37
161
|
child.stdin.on("error", () => {});
|
|
38
162
|
child.stdin.end(input);
|
|
@@ -40,9 +164,13 @@ function run(args, { input = null, timeout = 0, loglevel = "error" } = {}) {
|
|
|
40
164
|
});
|
|
41
165
|
}
|
|
42
166
|
|
|
167
|
+
// Runs ffmpeg as run() does, and fails after `what` it was doing. Its last
|
|
168
|
+
// argument is the file it writes, when it writes one.
|
|
43
169
|
async function mustRun(args, what, opts) {
|
|
44
170
|
const r = await run(args, opts);
|
|
45
|
-
if (r.
|
|
171
|
+
if (r.short) throw Object.assign(new Error(r.short), { short: true });
|
|
172
|
+
const out = String(args[args.length - 1]);
|
|
173
|
+
if (r.code !== 0) throw new Error(`${what}: ${why(r, { out: path.isAbsolute(out) ? out : null })}`);
|
|
46
174
|
return r;
|
|
47
175
|
}
|
|
48
176
|
|
|
@@ -52,80 +180,237 @@ const rate = (r) => {
|
|
|
52
180
|
return a && b ? a / b : Number(a) || 0;
|
|
53
181
|
};
|
|
54
182
|
|
|
183
|
+
// "00:00:06.000000000", as Matroska and WebM give a stream's length, in
|
|
184
|
+
// seconds, or 0.
|
|
185
|
+
function clock(text) {
|
|
186
|
+
const m = /^(\d+):(\d{1,2}):(\d{1,2}(?:\.\d+)?)$/.exec(String(text || "").trim());
|
|
187
|
+
return m ? Number(m[1]) * 3600 + Number(m[2]) * 60 + Number(m[3]) : 0;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// Where the picture of a file ends by its packets: the end of the latest, in
|
|
191
|
+
// the stream's own time, or 0 when its packets have no times.
|
|
192
|
+
function lastPacket(file) {
|
|
193
|
+
const r = spawnSync(FFPROBE, ["-v", "error", "-select_streams", "v:0", "-show_entries", "packet=pts_time,duration_time", "-of", "csv=p=0", ...input(file)],
|
|
194
|
+
{ encoding: "utf8", timeout: 60_000, maxBuffer: 64 << 20 });
|
|
195
|
+
const stopped = stoppedSync(r, "ffprobe", `reading ${confine.saidPath(file)}`);
|
|
196
|
+
if (stopped) throw stopped;
|
|
197
|
+
if (short(r.error, "ffprobe")) throw new Error(short(r.error, "ffprobe"));
|
|
198
|
+
let end = 0;
|
|
199
|
+
for (const line of String(r.stdout || "").split("\n")) {
|
|
200
|
+
const [at, length] = line.split(",").map(Number);
|
|
201
|
+
if (Number.isFinite(at)) end = Math.max(end, at + (Number.isFinite(length) ? length : 0));
|
|
202
|
+
}
|
|
203
|
+
return end;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// What ffprobe says of a file: its size, length, frame rate and sound, and
|
|
207
|
+
// `picture`, where its picture ends, from the film's start. A video whose
|
|
208
|
+
// sound runs on past its picture ends its picture before the film ends. The
|
|
209
|
+
// picture's own length is its stream's, which Matroska and WebM give only as
|
|
210
|
+
// a DURATION tag, else where its last packet ends; the film's length when
|
|
211
|
+
// none of them says.
|
|
55
212
|
function probe(file) {
|
|
56
213
|
const r = spawnSync(FFPROBE, ["-v", "error", "-show_entries",
|
|
57
|
-
"format=duration:stream=codec_type,codec_name,width,height,pix_fmt,sample_aspect_ratio,r_frame_rate,avg_frame_rate,sample_rate,channels",
|
|
58
|
-
"-of", "json", file], { encoding: "utf8", timeout: 20_000 });
|
|
214
|
+
"format=duration,start_time:stream=codec_type,codec_name,width,height,pix_fmt,sample_aspect_ratio,r_frame_rate,avg_frame_rate,sample_rate,channels,duration,start_time:stream_tags=DURATION",
|
|
215
|
+
"-of", "json", ...input(file)], { encoding: "utf8", timeout: 20_000 });
|
|
216
|
+
const stopped = stoppedSync(r, "ffprobe", `reading ${confine.saidPath(file)}`);
|
|
217
|
+
if (stopped) throw stopped;
|
|
218
|
+
if (short(r.error, "ffprobe")) throw new Error(short(r.error, "ffprobe"));
|
|
219
|
+
// Why ffprobe could not read it, when that is not that it holds nothing.
|
|
220
|
+
const failed = r.status !== 0 ? unread(r, "ffprobe") : null;
|
|
221
|
+
let info;
|
|
59
222
|
try {
|
|
60
|
-
|
|
61
|
-
const video = (info.streams || []).find((s) => s.codec_type === "video") || {};
|
|
62
|
-
const sound = (info.streams || []).find((s) => s.codec_type === "audio") || null;
|
|
63
|
-
return {
|
|
64
|
-
width: Number(video.width) || 0,
|
|
65
|
-
height: Number(video.height) || 0,
|
|
66
|
-
duration: Number((info.format || {}).duration) || 0,
|
|
67
|
-
audio: Boolean(sound),
|
|
68
|
-
fps: rate(video.avg_frame_rate) || rate(video.r_frame_rate),
|
|
69
|
-
baseFps: rate(video.r_frame_rate),
|
|
70
|
-
codec: video.codec_name || "",
|
|
71
|
-
pixFmt: video.pix_fmt || "",
|
|
72
|
-
sar: video.sample_aspect_ratio || "",
|
|
73
|
-
audioCodec: sound ? sound.codec_name || "" : "",
|
|
74
|
-
sampleRate: sound ? Number(sound.sample_rate) || 0 : 0,
|
|
75
|
-
channels: sound ? Number(sound.channels) || 0 : 0,
|
|
76
|
-
};
|
|
223
|
+
info = JSON.parse(r.stdout);
|
|
77
224
|
} catch {
|
|
78
|
-
return { width: 0, height: 0, duration: 0, audio: false, fps: 0, baseFps: 0, codec: "", pixFmt: "", sar: "", audioCodec: "", sampleRate: 0, channels: 0 };
|
|
225
|
+
return { width: 0, height: 0, duration: 0, picture: 0, audio: false, fps: 0, baseFps: 0, codec: "", pixFmt: "", sar: "", audioCodec: "", sampleRate: 0, channels: 0, failed };
|
|
79
226
|
}
|
|
227
|
+
const video = (info.streams || []).find((s) => s.codec_type === "video") || {};
|
|
228
|
+
const sound = (info.streams || []).find((s) => s.codec_type === "audio") || null;
|
|
229
|
+
const format = info.format || {};
|
|
230
|
+
const duration = Number(format.duration) || 0;
|
|
231
|
+
const tag = Object.entries(video.tags || {}).find(([key]) => key.toUpperCase() === "DURATION");
|
|
232
|
+
const own = Number(video.duration) > 0 ? Number(video.duration) : tag ? clock(tag[1]) : 0;
|
|
233
|
+
let shown = own > 0 ? own + (Number(video.start_time) || 0) - (Number(format.start_time) || 0) : 0;
|
|
234
|
+
// A picture alone has no length to look for.
|
|
235
|
+
if (!(shown > 0) && video.codec_type && duration) {
|
|
236
|
+
const end = lastPacket(file);
|
|
237
|
+
if (end > 0) shown = end - (Number(format.start_time) || 0);
|
|
238
|
+
}
|
|
239
|
+
return {
|
|
240
|
+
width: Number(video.width) || 0,
|
|
241
|
+
height: Number(video.height) || 0,
|
|
242
|
+
duration,
|
|
243
|
+
picture: shown > 0 ? shown : duration,
|
|
244
|
+
audio: Boolean(sound),
|
|
245
|
+
fps: rate(video.avg_frame_rate) || rate(video.r_frame_rate),
|
|
246
|
+
baseFps: rate(video.r_frame_rate),
|
|
247
|
+
codec: video.codec_name || "",
|
|
248
|
+
pixFmt: video.pix_fmt || "",
|
|
249
|
+
sar: video.sample_aspect_ratio || "",
|
|
250
|
+
audioCodec: sound ? sound.codec_name || "" : "",
|
|
251
|
+
sampleRate: sound ? Number(sound.sample_rate) || 0 : 0,
|
|
252
|
+
channels: sound ? Number(sound.channels) || 0 : 0,
|
|
253
|
+
failed,
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// A sound file's first `seconds`, decoded as 48 kHz stereo floats ({ left,
|
|
258
|
+
// right, seconds }), or null when ffmpeg finds no sound in it, or { failed }
|
|
259
|
+
// with ffmpeg's own words when it could not read it for another reason. A
|
|
260
|
+
// mono file plays on both sides. The length is the decoded one: a file's
|
|
261
|
+
// header can be wrong about it (a VBR MP3 without a Xing header).
|
|
262
|
+
function readSound(file, { seconds }) {
|
|
263
|
+
const r = spawnSync(FFMPEG, ["-v", "error", ...input(file), "-vn", "-t", seconds.toFixed(3), "-ac", "2", "-ar", "48000", "-f", "f32le", "-"],
|
|
264
|
+
{ maxBuffer: Math.ceil(seconds * 48000) * 8 + (1 << 20), timeout: 120_000 });
|
|
265
|
+
const stopped = stoppedSync(r, "ffmpeg", `reading ${confine.saidPath(file)}`);
|
|
266
|
+
if (stopped) throw stopped;
|
|
267
|
+
if (r.error) throw new Error(short(r.error, "ffmpeg") || `reading ${confine.saidPath(file)}: ${r.error.message}`);
|
|
268
|
+
if (r.status !== 0) {
|
|
269
|
+
const failed = unread(r, "ffmpeg");
|
|
270
|
+
return failed ? { failed } : null;
|
|
271
|
+
}
|
|
272
|
+
if (!r.stdout || r.stdout.length < 8) return null;
|
|
273
|
+
const n = Math.floor(r.stdout.length / 8);
|
|
274
|
+
const left = new Float32Array(n);
|
|
275
|
+
const right = new Float32Array(n);
|
|
276
|
+
for (let i = 0; i < n; i++) {
|
|
277
|
+
left[i] = r.stdout.readFloatLE(8 * i);
|
|
278
|
+
right[i] = r.stdout.readFloatLE(8 * i + 4);
|
|
279
|
+
}
|
|
280
|
+
return { left, right, seconds: n / 48000 };
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// The loudness of a sound file's first `seconds`, by ebur128: { integrated
|
|
284
|
+
// (LUFS), peak (the sample peak, dBFS) }. Digital silence measures -70 LUFS
|
|
285
|
+
// and a peak of -inf. framelog=verbose keeps the line for every 100 ms out
|
|
286
|
+
// of the info level the summary is read at.
|
|
287
|
+
async function loudnessOf(file, { seconds }) {
|
|
288
|
+
const r = await run([...input(file), "-vn", "-t", seconds.toFixed(3), "-af", "ebur128=peak=sample:framelog=verbose", "-f", "null", "-"], { loglevel: "info" });
|
|
289
|
+
if (r.short) throw Object.assign(new Error(r.short), { short: true });
|
|
290
|
+
if (r.code !== 0) throw new Error(`measuring ${confine.saidPath(file)}: ${why(r, { lines: 2 })}`);
|
|
291
|
+
const num = (re) => {
|
|
292
|
+
const m = re.exec(r.stderr);
|
|
293
|
+
return m ? (m[1] === "-inf" ? -Infinity : Number(m[1])) : null;
|
|
294
|
+
};
|
|
295
|
+
return { integrated: num(/Integrated loudness:\s*\n\s*I:\s*(-?[\d.]+|-inf) LUFS/), peak: num(/Sample peak:\s*\n\s*Peak:\s*(-?[\d.]+|-inf) dBFS/) };
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// A film's sound as check measures it, at 48 kHz by ebur128: { integrated
|
|
299
|
+
// (LUFS), truePeak (dBTP) }. Silence measures -70 LUFS and a peak of -inf.
|
|
300
|
+
async function levelOf(file) {
|
|
301
|
+
const r = await run([...input(file), "-vn", "-af", "aresample=48000,ebur128=peak=true:framelog=verbose", "-f", "null", "-"], { loglevel: "info" });
|
|
302
|
+
if (r.short) throw Object.assign(new Error(r.short), { short: true });
|
|
303
|
+
if (r.code !== 0) throw new Error(`measuring the film's sound: ${why(r, { lines: 2 })}`);
|
|
304
|
+
const num = (re) => {
|
|
305
|
+
const m = re.exec(r.stderr);
|
|
306
|
+
return m ? (m[1] === "-inf" ? -Infinity : Number(m[1])) : null;
|
|
307
|
+
};
|
|
308
|
+
return { integrated: num(/Integrated loudness:\s*\n\s*I:\s*(-?[\d.]+|-inf) LUFS/), truePeak: num(/True peak:\s*\n\s*Peak:\s*(-?[\d.]+|-inf) dBFS/) };
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// What loudnorm measures over a sound file in its first pass, given its
|
|
312
|
+
// `filter` (loudnorm=I= and the rest): { integrated (LUFS), truePeak
|
|
313
|
+
// (dBTP), range (LU) }, or null for a sound it measured no level in, as
|
|
314
|
+
// silence.
|
|
315
|
+
async function loudnormPass(file, filter) {
|
|
316
|
+
const r = await run([...input(file), "-af", `${filter}:print_format=json`, "-f", "null", "-"], { loglevel: "info" });
|
|
317
|
+
if (r.short) throw Object.assign(new Error(r.short), { short: true });
|
|
318
|
+
if (r.code !== 0) throw new Error(`measuring the sound: ${why(r, { lines: 2 })}`);
|
|
319
|
+
let said = null;
|
|
320
|
+
try {
|
|
321
|
+
said = JSON.parse(r.stderr.slice(r.stderr.lastIndexOf("{"), r.stderr.lastIndexOf("}") + 1));
|
|
322
|
+
} catch {
|
|
323
|
+
return null;
|
|
324
|
+
}
|
|
325
|
+
const integrated = Number(said.input_i);
|
|
326
|
+
const truePeak = Number(said.input_tp);
|
|
327
|
+
const range = Number(said.input_lra);
|
|
328
|
+
// Silence measures -70 LUFS, or -inf, which JSON gives as a word.
|
|
329
|
+
if (!(integrated > -70 && integrated <= 0) || !Number.isFinite(truePeak)) return null;
|
|
330
|
+
return { integrated, truePeak, range };
|
|
80
331
|
}
|
|
81
332
|
|
|
82
333
|
// A picture made exactly W x H: scaled to cover the size and cut to it from
|
|
83
334
|
// the middle, as an opaque PNG (stores refuse transparency).
|
|
84
|
-
function coverPng(
|
|
85
|
-
return
|
|
86
|
-
"-frames:v", "1", "-pix_fmt", "rgb24", output
|
|
335
|
+
function coverPng(from, output, W, H) {
|
|
336
|
+
return writePicture([...input(from), "-vf", `scale=${W}:${H}:force_original_aspect_ratio=increase:flags=lanczos,crop=${W}:${H},setsar=1`,
|
|
337
|
+
"-frames:v", "1", "-pix_fmt", "rgb24"], output, `making ${output}`);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// A picture's size, from probe(): a file in which ffprobe finds no picture
|
|
341
|
+
// (a text file, a page saved as .png) fails, where its size of 0 x 0 made a
|
|
342
|
+
// clip that showed nothing, and so does one ffprobe could not read, with
|
|
343
|
+
// its words.
|
|
344
|
+
function pictureSize(file) {
|
|
345
|
+
const info = probe(file);
|
|
346
|
+
if (!info.width || !info.height) throw new Error(`${confine.saidPath(file)} could not be read as a picture${info.failed ? ` (${info.failed})` : ""}`);
|
|
347
|
+
return info;
|
|
87
348
|
}
|
|
88
349
|
|
|
89
350
|
// A picture's pixels as RGBA, at most `max` px on its long side when given:
|
|
90
351
|
// { data, width, height }.
|
|
91
352
|
function readPixels(file, max = 0) {
|
|
92
|
-
const info =
|
|
93
|
-
if (!info.width || !info.height) throw new Error(`${file} could not be read as a picture`);
|
|
353
|
+
const info = pictureSize(file);
|
|
94
354
|
const k = max ? Math.min(1, max / Math.max(info.width, info.height)) : 1;
|
|
95
355
|
const width = Math.max(1, Math.round(info.width * k));
|
|
96
356
|
const height = Math.max(1, Math.round(info.height * k));
|
|
97
|
-
const r = spawnSync(FFMPEG, ["-v", "error",
|
|
357
|
+
const r = spawnSync(FFMPEG, ["-v", "error", ...input(file), "-frames:v", "1", "-vf", `scale=${width}:${height}:flags=area,format=rgba`, "-f", "rawvideo", "-"],
|
|
98
358
|
{ timeout: 30_000, maxBuffer: width * height * 4 + 1024 });
|
|
99
|
-
|
|
359
|
+
const stopped = stoppedSync(r, "ffmpeg", `reading ${confine.saidPath(file)}`);
|
|
360
|
+
if (stopped) throw stopped;
|
|
361
|
+
if (short(r.error, "ffmpeg")) throw new Error(short(r.error, "ffmpeg"));
|
|
362
|
+
const failed = r.status !== 0 ? unread(r, "ffmpeg") : null;
|
|
363
|
+
if (r.status !== 0 || !r.stdout || r.stdout.length !== width * height * 4) throw new Error(`${confine.saidPath(file)} could not be read as a picture${failed ? ` (${failed})` : ""}`);
|
|
100
364
|
return { data: r.stdout, width, height, scale: k, sourceWidth: info.width, sourceHeight: info.height };
|
|
101
365
|
}
|
|
102
366
|
|
|
103
367
|
// RGBA pixels written as a PNG.
|
|
104
368
|
function writePng(file, { data, width, height }) {
|
|
105
|
-
return
|
|
369
|
+
return writePicture(["-f", "rawvideo", "-pix_fmt", "rgba", "-s", `${width}x${height}`, "-i", "-", "-frames:v", "1"], file, "writing a picture", { input: data });
|
|
106
370
|
}
|
|
107
371
|
|
|
108
|
-
// A frame encoder: JPEG frames in, an H.264 MP4 out
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
372
|
+
// A frame encoder: JPEG frames in, an H.264 MP4 out, libx264 given `threads`
|
|
373
|
+
// when it is given (film.js threadsFor).
|
|
374
|
+
function encoder({ output, fps = 25, crf = 15, threads = 0 }) {
|
|
375
|
+
const child = track(spawn(FFMPEG, ["-hide_banner", "-loglevel", "error", "-y", "-f", "image2pipe", "-framerate", String(fps), "-c:v", "mjpeg", "-i", "-",
|
|
376
|
+
"-vf", "scale=out_color_matrix=bt709:out_range=tv,format=yuv420p", "-c:v", "libx264", "-preset", "veryfast", "-crf", String(crf), ...(threads ? ["-threads", String(threads)] : []),
|
|
112
377
|
"-color_primaries", "bt709", "-color_trc", "bt709", "-colorspace", "bt709", "-an", "-r", String(fps), "-movflags", "+faststart", output],
|
|
113
|
-
{ stdio: ["pipe", "ignore", "pipe"] });
|
|
378
|
+
{ stdio: ["pipe", "ignore", "pipe"] }));
|
|
114
379
|
let err = "";
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
380
|
+
let ended = null;
|
|
381
|
+
// One that cannot be started says why here, and closes as one that stopped.
|
|
382
|
+
// One the system had no file descriptor for has no pipes (run, above).
|
|
383
|
+
let unstarted = null;
|
|
384
|
+
child.on("error", (e) => {
|
|
385
|
+
err = e.message;
|
|
386
|
+
unstarted = short(e, "ffmpeg");
|
|
387
|
+
});
|
|
388
|
+
if (child.stderr) child.stderr.on("data", (d) => (err = (err + d).slice(-2000)));
|
|
389
|
+
if (child.stdin) child.stdin.on("error", () => {});
|
|
390
|
+
const closed = new Promise((resolve) => child.on("close", (code, signal) => resolve((ended = { code, signal }))));
|
|
391
|
+
// One the system killed without a word, as it kills one when memory runs
|
|
392
|
+
// out with two clips at once, is said with what to do, as Chrome is then
|
|
393
|
+
// (chrome.js starved): film.js adds that one clip at a time needs less.
|
|
394
|
+
const failed = () => {
|
|
395
|
+
if (unstarted) return Object.assign(new Error(unstarted), { short: true });
|
|
396
|
+
const killed = ended.signal === "SIGKILL" && !err.trim();
|
|
397
|
+
return Object.assign(new Error(`${why({ ...ended, stderr: err }, { lines: 2, out: output })}${killed ? ": run again once more of it is free" : ""}`), { memory: killed });
|
|
398
|
+
};
|
|
118
399
|
return {
|
|
400
|
+
// An ffmpeg that has stopped (a full disk, an output it cannot write)
|
|
401
|
+
// takes no more frames: its error, not a wait for room in the pipe.
|
|
119
402
|
async write(jpeg) {
|
|
120
|
-
if (!child.stdin
|
|
403
|
+
if (!child.stdin) await closed;
|
|
404
|
+
else if (!ended && !child.stdin.write(jpeg)) await Promise.race([new Promise((resolve) => child.stdin.once("drain", resolve)), closed]);
|
|
405
|
+
if (ended) throw failed();
|
|
121
406
|
},
|
|
122
407
|
async end() {
|
|
123
|
-
child.stdin.end();
|
|
124
|
-
|
|
125
|
-
if (code !== 0) throw
|
|
408
|
+
if (child.stdin) child.stdin.end();
|
|
409
|
+
await closed;
|
|
410
|
+
if (ended.code !== 0) throw failed();
|
|
126
411
|
},
|
|
127
412
|
kill: () => child.kill("SIGKILL"),
|
|
128
413
|
};
|
|
129
414
|
}
|
|
130
415
|
|
|
131
|
-
module.exports = { FFMPEG, FFPROBE, available, run, mustRun, probe, coverPng, readPixels, writePng, encoder };
|
|
416
|
+
module.exports = { FFMPEG, FFPROBE, available, input, picture, whole, writePicture, why, stoppedSync, run, mustRun, probe, pictureSize, readSound, loudnessOf, loudnormPass, levelOf, coverPng, readPixels, writePng, encoder };
|