launch-film 0.2.1 → 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/src/film.js CHANGED
@@ -2,24 +2,55 @@
2
2
  // ─── the film ──────────────────────────────────────────────────────────────
3
3
  // film.json in, an MP4 out: each clip is a page rendered on its own (two at a
4
4
  // time), the clips are joined with short crossfades that start on the cut,
5
- // and one sound track (the music bed and every clip's effects at their
6
- // times) is laid under the whole film.
5
+ // and one sound track (the music bed, or the user's own track in its place,
6
+ // and every clip's effects at their times) is laid under the whole film, at
7
+ // the loudness social apps play at.
7
8
 
8
9
  const fs = require("fs");
9
10
  const os = require("os");
10
11
  const path = require("path");
11
12
  const motion = require("./motion");
12
13
  const { parseScene, resolveFonts, iconSvg } = require("./scene");
13
- const { renderPage } = require("./chrome");
14
- const { run, mustRun, probe, readPixels } = require("./ffmpeg");
14
+ const { renderPage, PAGE_FILE_MAX } = require("./chrome");
15
+ const { input, picture, whole, writePicture, run, mustRun, pictureSize, readPixels, readSound, loudnessOf, loudnormPass, levelOf } = require("./ffmpeg");
15
16
  const { prepareLogo, prepareIcon } = require("./logo");
16
17
  const { readBrand } = require("./brand");
17
18
  const audio = require("./audio");
19
+ const { within, heldBackIn, tempDir, release, save, reason } = require("./out");
20
+ const confine = require("./confine");
18
21
 
19
22
  const FPS = 25;
20
23
  // A crossfade between clips, starting on the cut.
21
24
  const FADE = 0.4;
25
+ // The film's sound: -14 LUFS (LUFS), the loudness YouTube, X and most
26
+ // social apps play at and the skill checks a film at, its true peak at -1.5
27
+ // dBTP or under (TRUE_PEAK), as LOUDNORM gives them to loudnorm. loudnorm
28
+ // measures the sound (ffmpeg.js loudnormPass), and one gain sets it to -14
29
+ // (addSound), so the sound keeps the rise and fall it was made with: a
30
+ // track's build and drop, the bed's opening a few dB under its groove
31
+ // (audio.js). loudnorm's own second pass did not: when the peaks a gain
32
+ // raises pass its limit, as they do with nearly every sound, it works in its
33
+ // dynamic mode, which turns quiet stretches up and loud ones down, and it
34
+ // flattened a track's drop from 9.5 dB over its build to 2.8. The gain
35
+ // raises the peaks too, and the AAC encoder lifts a sharp hit by as much as
36
+ // two and a half dB in the films measured, so a limiter on the sound at four
37
+ // times its rate holds the peaks at CEILING, and the film is measured once
38
+ // encoded, as check measures it, and encoded again with the gain moved
39
+ // toward -14, up or down, and the limiter set lower by what the encoded
40
+ // film's true peak passed -1.7 dBTP, a fifth of a dB under TRUE_PEAK. Of
41
+ // these encodes, TRIES at most, the one nearest -14 LUFS at TRUE_PEAK or
42
+ // under is kept.
43
+ const LOUDNORM = "loudnorm=I=-14:TP=-1.5:LRA=11";
44
+ const LUFS = -14;
45
+ const TRUE_PEAK = -1.5;
46
+ const CEILING = -3.5;
47
+ const TRIES = 6;
48
+ // The most the gain moves the sound, in dB, either way.
49
+ const GAIN_MAX = 30;
22
50
  const KINDS = new Set(["scene", "screen", "phone", "scroll", "shots", "logo"]);
51
+ // Why a file that is a list of others for ffmpeg to open is refused, with
52
+ // LAUNCH_FILM_CONFINE set (confine.js listOf).
53
+ const LISTED = "whose files ffmpeg would open wherever they are, and LAUNCH_FILM_CONFINE allows only files in film.json's folder";
23
54
 
24
55
  // Reads and checks a film.json; returns { film, dir, brand, clips, problems }.
25
56
  function loadFilm(file) {
@@ -30,18 +61,31 @@ function loadFilm(file) {
30
61
  } catch (err) {
31
62
  return { problems: [`${file} is not valid JSON: ${err.message}`] };
32
63
  }
64
+ if (!film || typeof film !== "object" || Array.isArray(film)) return { problems: [`${file} must hold an object, such as { "look": "launch", "clips": [] }`] };
33
65
  const problems = [];
34
- if (!motion.LOOKS[film.look]) problems.push(`"look" must be one of ${Object.keys(motion.LOOKS).join(", ")}`);
66
+ // A value of another kind than a field takes is named with the field: a
67
+ // number where a path goes ended the run in Node's own words, which name
68
+ // neither, and "false" for sfx played the effects without a word.
69
+ const shown = (value) => confine.said(JSON.stringify(value));
70
+ const knownLook = Object.hasOwn(motion.LOOKS, String(film.look));
71
+ if (!knownLook) problems.push(`"look" must be one of ${Object.keys(motion.LOOKS).join(", ")}`);
35
72
  if (film.aspect && !["16:9", "9:16"].includes(film.aspect)) problems.push('"aspect" must be "16:9" or "9:16"');
73
+ // With LAUNCH_FILM_CONFINE set, a file named outside the film's folder is
74
+ // a problem like any other (confine.js).
75
+ const outside = (name) => confine.outside(dir, name, "film.json");
76
+ const unconfined = (name, what) => `${what} "${confine.said(name)}" ${outside(name)}, and LAUNCH_FILM_CONFINE allows only files in it`;
36
77
  let brand = null;
37
- if (film.brand) {
78
+ if (film.brand && typeof film.brand !== "string") problems.push(`"brand" must be the path of a brand.json (it is ${shown(film.brand)})`);
79
+ else if (film.brand && outside(film.brand)) problems.push(unconfined(film.brand, '"brand"'));
80
+ else if (film.brand) {
38
81
  try {
39
82
  brand = readBrand(path.resolve(dir, film.brand));
40
83
  } catch (err) {
41
- problems.push(`the brand could not be read from ${film.brand}: ${err.message}`);
84
+ // A file error names the file, which film.json named: it is said once.
85
+ problems.push(`the brand could not be read from ${confine.said(film.brand)}: ${confine.oneLine(reason(err))}`);
42
86
  }
43
87
  }
44
- const mood = audio.MOODS[film.look] || audio.MOODS.launch;
88
+ const mood = (knownLook && audio.MOODS[film.look]) || audio.MOODS.launch;
45
89
  const bar = 240 / mood.bpm;
46
90
  const clips = Array.isArray(film.clips) ? film.clips : [];
47
91
  if (!clips.length) problems.push('"clips" is empty');
@@ -55,8 +99,18 @@ function loadFilm(file) {
55
99
  const seconds = c.seconds !== undefined ? Number(c.seconds) : Number(c.bars || 2) * bar;
56
100
  if (!(seconds >= 2 && seconds <= 12)) problems.push(`${at} must last 2-12 seconds (it is ${seconds.toFixed(2)})`);
57
101
  const fileOf = (rel, what) => {
102
+ if (rel && typeof rel !== "string") {
103
+ problems.push(`${at}.${what} must be the path of a picture (it is ${shown(rel)})`);
104
+ return null;
105
+ }
106
+ if (rel && outside(rel)) {
107
+ problems.push(unconfined(rel, `${at}.${what}`));
108
+ return null;
109
+ }
58
110
  const abs = rel ? path.resolve(dir, rel) : null;
59
- if (!abs || !fs.existsSync(abs)) problems.push(`${at}.${what} "${rel || ""}" is not a file`);
111
+ const list = abs && fs.existsSync(abs) ? confine.listOf(abs) : null;
112
+ if (!abs || !fs.existsSync(abs)) problems.push(`${at}.${what} "${confine.said(rel || "")}" is not a file`);
113
+ else if (list) problems.push(`${at}.${what} "${confine.said(rel)}" is ${list}, ${LISTED}: give the picture itself`);
60
114
  return abs;
61
115
  };
62
116
  const clip = { ...c, index: i, seconds };
@@ -81,7 +135,220 @@ function loadFilm(file) {
81
135
  });
82
136
  const total = out.reduce((s, c) => s + c.seconds, 0);
83
137
  if (total > 90) problems.push(`the film would last ${total.toFixed(1)} s; keep it under 90`);
84
- return { film, dir, brand, clips: out, bar, problems };
138
+ if (![undefined, null, true, false].includes(film.sfx)) problems.push(`"sfx" must be true or false (it is ${shown(film.sfx)})`);
139
+ const music = musicOf(film.music, dir, problems);
140
+ return { film, dir, brand, clips: out, bar, music, seconds: total, problems };
141
+ }
142
+
143
+ // What film.json's "music" asks for: the look's bed (true, or left out), no
144
+ // music (false), the bed at another level ({ "volume": 0.55 }, from 0 to
145
+ // 2), or the user's own track (the path of a sound file, from film.json's
146
+ // folder or absolute), which checkMusic reads when the film renders.
147
+ function musicOf(value, dir, problems) {
148
+ if (value === undefined || value === null || value === true) return { bed: true };
149
+ if (value === false) return { bed: false };
150
+ if (typeof value === "string" && value.trim()) return { bed: false, track: path.resolve(dir, value), name: value };
151
+ if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).every((k) => k === "volume")) {
152
+ const v = value.volume;
153
+ const n = typeof v === "number" || (typeof v === "string" && v.trim()) ? Number(v) : NaN;
154
+ if (v !== undefined && !(n >= 0 && n <= 2)) problems.push(`"music" "volume" must be a number from 0 to 2 (it is ${confine.said(JSON.stringify(v))})`);
155
+ return { bed: true };
156
+ }
157
+ problems.push(`"music" must be true, false, { "volume": 0.55 } or the path of an audio file (it is ${confine.said(JSON.stringify(value))})`);
158
+ return { bed: true };
159
+ }
160
+
161
+ // A path as one word of a command line that an agent runs as it is, or null
162
+ // when no quoting holds in every shell it may run it in. Bare when no shell
163
+ // reads anything in it. For a POSIX shell, in single quotes, inside which
164
+ // nothing is expanded or run. On Windows in double quotes, as cmd.exe takes no
165
+ // single quotes, with / for every \, which Node takes too, since Git Bash
166
+ // reads \\ there as one \. Inside double quotes cmd.exe, PowerShell and Git
167
+ // Bash still expand %, $, ` and !, so a path that holds one gets null. So
168
+ // does one with a line break or another control character in it, which
169
+ // would break the line the command is printed on.
170
+ function shellWord(file, platform = process.platform) {
171
+ if (CONTROL.test(file)) return null;
172
+ if (platform === "win32") {
173
+ const name = String(file).replace(/\\/g, "/");
174
+ if (/^[\w.:/-]+$/.test(name)) return name;
175
+ return /[%$`!"]/.test(name) ? null : `"${name}"`;
176
+ }
177
+ return /^[\w@%+=:,./-]+$/.test(file) ? file : `'${String(file).replace(/'/g, "'\\''")}'`;
178
+ }
179
+
180
+ // A name as a message shows it, on one line (confine.js).
181
+ const { CONTROL, oneLine } = confine;
182
+
183
+ // The musicfit command that fits a track to the film, `seconds` long with
184
+ // its hit at `hit`, into `folder`, as the refusal of a short track gives it:
185
+ // `from` is the track to fit, by its path, or null when it was not found,
186
+ // and `name` the name of that track, when known, else `of` says which track
187
+ // the word in its place stands for. Each path is one word the
188
+ // shell takes as it is (shellWord). In the place of a path that was not
189
+ // found, or that no quoting holds, goes a word in angle brackets, quoted
190
+ // the same way, so a shell that runs the command reads no quote, ; or $( )
191
+ // in it, and no < or > as a file to read or write; what to put there is said
192
+ // after the command. A name no quoting holds either goes in the sentence
193
+ // alone, after the plain word <track>. A name is shown on one line, and cut
194
+ // in the middle when it is long.
195
+ function musicfitCommand({ from, name = "", of = "the track it was made from", folder, seconds, hit }, platform = process.platform) {
196
+ const shown = name ? confine.said(name) : "";
197
+ const stand = shellWord(`<${shown || "track"}>`, platform) ? `<${shown || "track"}>` : "<track>";
198
+ const words = [[from, stand, shown || of], [folder, "<folder>"]].map(([file, word, which]) => {
199
+ const quoted = file && shellWord(file, platform);
200
+ if (quoted) return { text: quoted };
201
+ return { text: shellWord(word, platform), said: file ? `${word} being ${oneLine(file)} quoted for your shell` : `${word} being the path of ${which}` };
202
+ });
203
+ const said = words.filter((w) => w.said).map((w) => w.said);
204
+ return `npx musicfit@latest ${words[0].text} --length ${+seconds.toFixed(3)} --hit ${+hit.toFixed(3)} --fps ${FPS} --out ${words[1].text}${said.length ? `, ${said.join(" and ")}` : ""}`;
205
+ }
206
+
207
+ // Where a link that leads nowhere ends: the first path along it that is not
208
+ // there, after as many links as lead there. null when `file` is no link.
209
+ function linkEnd(file) {
210
+ let at = file;
211
+ for (let hops = 0; hops < 40; hops++) {
212
+ let s;
213
+ try {
214
+ s = fs.lstatSync(at);
215
+ } catch {
216
+ return hops ? at : null;
217
+ }
218
+ if (!s.isSymbolicLink()) return null;
219
+ try {
220
+ at = path.resolve(path.dirname(at), fs.readlinkSync(at));
221
+ } catch {
222
+ return null;
223
+ }
224
+ }
225
+ return null;
226
+ }
227
+
228
+ // The track an earlier fit of musicfit's was made from, when `track` is such
229
+ // a fit: a file musicfit writes (fitted.wav or mix.wav) in `folder`, where the
230
+ // fit the refusal asks for goes, or one that a cues.json of musicfit's beside
231
+ // it lists. null when it is not one, else { name, track }: the name of the
232
+ // track it was fitted from, as that cues.json gives it ("" when none does),
233
+ // and its path when it is found beside the fit or beside film.json (`dir`).
234
+ // With LAUNCH_FILM_CONFINE set, a path outside film.json's folder is not
235
+ // looked at: the command would tell whether any file of the machine is
236
+ // there.
237
+ function earlierFit(track, folder, dir) {
238
+ const beside = path.dirname(track);
239
+ let cues = null;
240
+ try {
241
+ const read = JSON.parse(fs.readFileSync(path.join(beside, "cues.json"), "utf8"));
242
+ if (read && typeof read === "object" && read.musicfit !== undefined) cues = read;
243
+ } catch {
244
+ // No cues.json of musicfit's there.
245
+ }
246
+ const name = path.basename(track);
247
+ const listed = Boolean(cues) && [cues.file, cues.mix].includes(name);
248
+ if (!listed && !(beside === folder && ["fitted.wav", "mix.wav"].includes(name))) return null;
249
+ const was = cues && typeof cues.track === "string" ? cues.track.trim() : "";
250
+ const isTrack = (file) => {
251
+ try {
252
+ return fs.statSync(file).isFile() && file !== track;
253
+ } catch {
254
+ return false;
255
+ }
256
+ };
257
+ const found = was ? [beside, dir].map((d) => path.resolve(d, was)).find((file) => !confine.outside(dir, file, "film.json") && isTrack(file)) : null;
258
+ return { name: path.basename(was), track: found || null };
259
+ }
260
+
261
+ // The user's own track, when film.json names one, read before anything
262
+ // renders: its sound for the film's length, decoded, and its loudness over
263
+ // it. Returns { track, problems }: a file that is missing, has no sound
264
+ // ffmpeg can read, is shorter than the film or is silent is a problem, and
265
+ // each problem says what to give instead.
266
+ async function checkMusic(loaded) {
267
+ const { music, seconds: total, clips, dir } = loaded;
268
+ if (!music || !music.track) return { track: null, problems: [] };
269
+ // The path on one line, and cut when long, in every refusal (confine.js):
270
+ // as a path, so that a track's folder is said whole.
271
+ const at = `"music" "${confine.saidPath(music.name)}"`;
272
+ const refuse = (problem) => ({ track: null, problems: [problem] });
273
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(music.name)) return refuse(`${at} is an address: download the track and give the path of the file, from film.json's folder or absolute`);
274
+ // In the folder, the track named from there, or fitted there: a fit made
275
+ // next to the film's folder, as makersmcp's fit_music makes one by
276
+ // default, is outside it. The track is not looked at, nor named in the
277
+ // command, as it may be any file of the machine (earlierFit).
278
+ const close = clips.length ? total - clips[clips.length - 1].seconds : 0;
279
+ const outside = confine.outside(dir, music.name, "film.json");
280
+ if (outside) {
281
+ return refuse(`${at} ${outside}, and LAUNCH_FILM_CONFINE allows only files in it: copy the track into that folder and give its path from there, or fit it into that folder with ` +
282
+ `${musicfitCommand({ from: null, of: "the track to fit", folder: path.join(dir, "music"), seconds: total, hit: close })}, then set "music" in film.json to "music/fitted.wav"`);
283
+ }
284
+ const instead = "give the path of a track (true plays the look's own music, false none)";
285
+ let kind = null;
286
+ let missed = null;
287
+ try {
288
+ const s = fs.statSync(music.track);
289
+ kind = s.isFile() ? "file" : s.isDirectory() ? "folder" : s.isFIFO() ? "a pipe" : s.isSocket() ? "a socket" : "a device";
290
+ } catch (err) {
291
+ missed = err;
292
+ }
293
+ // A good file the user may not reach would read as one that is not there.
294
+ if (missed && !["ENOENT", "ENOTDIR", "ELOOP"].includes(missed.code)) return refuse(`${at} cannot be read: ${reason(missed)}. Make it readable, or give a copy of it you can read`);
295
+ if (kind === "folder") return refuse(`${at} is a folder, not a file: give the path of the track in it`);
296
+ // The path was right: what is there is no file.
297
+ if (kind && kind !== "file") return refuse(`${at} is ${kind}, not a file: ${instead}`);
298
+ if (!kind) {
299
+ // A link is there, though what it leads to is not: it is told of as one.
300
+ if (missed.code === "ELOOP") return refuse(`${at} is a link that never reaches a file, through too many links one after another: ${instead}`);
301
+ const end = linkEnd(music.track);
302
+ if (end) return refuse(`${at} is a link to ${confine.saidPath(end)}, which is not there: ${instead}`);
303
+ // A relative path is read from film.json's folder, which may not be
304
+ // where the user stood when they wrote it: the message says where it
305
+ // looked.
306
+ return refuse(path.isAbsolute(music.name) ? `${at} is not a file: ${instead}`
307
+ : `${at} is not a file. It was looked for at ${confine.saidPath(music.track)}, as a path there is read from film.json's folder: give the track's path from that folder or an absolute one (true plays the look's own music, false none)`);
308
+ }
309
+ // A good file the user may not read would read as a file with no sound.
310
+ try {
311
+ fs.accessSync(music.track, fs.constants.R_OK);
312
+ } catch (err) {
313
+ return refuse(`${at} cannot be read: ${reason(err)}. Make it readable, or give a copy of it you can read`);
314
+ }
315
+ const list = confine.listOf(music.track);
316
+ if (list) return refuse(`${at} is ${list}, ${LISTED}: give the track itself`);
317
+ // A second past the film's end, so a track as long as the film shows it.
318
+ const sound = readSound(music.track, { seconds: total + 1 });
319
+ if (!sound) return refuse(`${at} has no sound ffmpeg can read: give an audio file, such as a WAV, MP3, M4A or FLAC file, or a video with sound`);
320
+ // An ffmpeg that would not read it says why, as a guard does that opens
321
+ // no file whose name has a % in it.
322
+ if (sound.failed) return refuse(`${at} could not be read: ${sound.failed}`);
323
+ // musicfit gives a length to the millisecond: half a frame short is whole.
324
+ if (sound.seconds < total - 0.5 / FPS) {
325
+ // In a folder of its own in the film's: the path set in film.json stays
326
+ // good, whatever else musicfit is asked to do next to the film. The
327
+ // command is written to be run as it is, from any folder
328
+ // (musicfitCommand).
329
+ const folder = path.join(dir, "music");
330
+ const fit = earlierFit(music.track, folder, dir);
331
+ // An earlier fit is not fitted again: musicfit refuses a track it would
332
+ // replace, and a fit's faded end would play twice.
333
+ const was = fit && fit.name ? confine.said(fit.name) : "";
334
+ const again = !fit ? "" : was ? `That track is musicfit's earlier fit of ${was}, so fit ${was} again: ` : "That track is an earlier fit, so fit the track it was made from again: ";
335
+ const command = musicfitCommand({ from: fit ? fit.track : music.track, name: fit ? fit.name : "", folder, seconds: total, hit: close });
336
+ return { track: null, problems: [`${at} lasts ${sound.seconds.toFixed(2)} s and the film ${total.toFixed(2)} s: give a track at least as long as the film. ${again}` +
337
+ `musicfit makes one exactly that long with its hit on the beat you choose, such as the last clip at ${close.toFixed(2)} s: ${command}, then set "music" in film.json to "music/fitted.wav"`] };
338
+ }
339
+ const level = await loudnessOf(music.track, { seconds: total });
340
+ if (!(level.integrated > -70)) return refuse(`${at} is silent over the film's ${total.toFixed(2)} s: give a track with sound in it, or false for no music`);
341
+ return { track: { ...sound, ...level, name: music.name }, problems: [] };
342
+ }
343
+
344
+ // What the render's note says of the user's track (checkMusic's), in a film
345
+ // `seconds` long. Its path is shown on one line, and cut in the middle when
346
+ // it is longer than a path gets, as one made to run to thousands of
347
+ // characters is.
348
+ function trackNote(track, seconds) {
349
+ const under = (audio.TRACK_LUFS - track.integrated) - 20 * Math.log10(audio.trackGain(track));
350
+ return `The music is ${confine.saidPath(track.name)}${under > 0.05 ? `, ${under.toFixed(1)} dB under the bed's level so its peaks stay under full scale` : ", at the bed's level"}, ` +
351
+ `from the film's first frame to its end at ${seconds.toFixed(2)} s, faded out over the last second.`;
85
352
  }
86
353
 
87
354
  // The colours a brand gives the looks: its accent, a second colour, and a
@@ -111,6 +378,33 @@ function topColour(file) {
111
378
  return `#${sum.map((v) => Math.round(v / (rows * p.width)).toString(16).padStart(2, "0")).join("")}`;
112
379
  }
113
380
 
381
+ // The bytes a page is given for a picture the film names: the file as it is,
382
+ // or, when it is larger than Chrome takes in one file (chrome.js), a copy of
383
+ // what the page shows of it, `part(width, height)` ({ x, y, w, h }, the whole
384
+ // picture when not given), that fits `maxW` x `maxH`, the most the page draws
385
+ // it at, and is never larger than the picture, written to `out` (a PNG, or a
386
+ // JPEG by its name). A screenshot of 80 MB rendered when pages were opened
387
+ // from the disk, and then failed. A copy that is still too large, as one of a
388
+ // detailed picture a zoom draws nearly at its own size, is made smaller until
389
+ // it fits, its size going with its pixels; `named` says which picture of the
390
+ // film's it is, should none fit.
391
+ async function pagePicture(file, { maxW, maxH = Infinity, part = null, out, what, named = file }) {
392
+ if (fs.statSync(file).size <= PAGE_FILE_MAX) return fs.readFileSync(file);
393
+ const info = pictureSize(file);
394
+ const shown = part ? part(info.width, info.height) : { x: 0, y: 0, w: info.width, h: info.height };
395
+ const crop = part ? `crop=${shown.w}:${shown.h}:${shown.x}:${shown.y},` : "";
396
+ let k = Math.min(1, maxW / shown.w, maxH / shown.h);
397
+ for (let tries = 0; tries < 4; tries++) {
398
+ const size = (n) => Math.max(2, 2 * Math.round((n * k) / 2));
399
+ await writePicture([...input(file), "-vf", `${crop}scale=${size(shown.w)}:${size(shown.h)}:flags=lanczos`, "-frames:v", "1", ...(/\.jpe?g$/i.test(out) ? ["-q:v", "2"] : [])], out, what);
400
+ const bytes = fs.statSync(out).size;
401
+ if (bytes <= PAGE_FILE_MAX) return fs.readFileSync(out);
402
+ // A tenth to spare.
403
+ k *= Math.sqrt((0.9 * PAGE_FILE_MAX) / bytes);
404
+ }
405
+ throw new Error(`${named} is more than the ${PAGE_FILE_MAX / 1048576} MB Chrome takes in one file, even as a smaller copy: give a smaller picture, or a JPEG`);
406
+ }
407
+
114
408
  // One clip's page: { html, files, cues, W, H }.
115
409
  async function buildClip(clip, ctx) {
116
410
  const { look, port, fonts, colours, work } = ctx;
@@ -124,26 +418,37 @@ async function buildClip(clip, ctx) {
124
418
  return { html: page.html, files: {}, cues: page.cues, W: page.W, H: page.H };
125
419
  }
126
420
  if (clip.kind === "screen") {
127
- const info = probe(clip.imageFile);
421
+ const info = pictureSize(clip.imageFile);
128
422
  const ext = path.extname(clip.imageFile).toLowerCase() === ".png" ? ".png" : ".jpg";
129
423
  const soft = path.join(work, `soft-${clip.index}.jpg`);
130
- const blurred = await run(["-i", clip.imageFile, "-vf", "scale='min(1400,iw)':-2,gblur=sigma=12", "-q:v", "5", soft]);
424
+ const blurred = await run([...input(clip.imageFile), "-vf", "scale='min(1400,iw)':-2,gblur=sigma=12", "-q:v", "5", ...picture(soft)]);
425
+ if (blurred.short) throw Object.assign(new Error(blurred.short), { short: true });
426
+ // The blurred ground is left out when it could not be made whole.
427
+ const hasSoft = blurred.code === 0 && whole(soft);
131
428
  const page = motion.screenHtml({ mode: clip.mode === "zoom" ? "zoom" : "pan", look, port, seconds, accent: brandAccent, brand: colours,
132
- image: { file: `capture${ext}`, w: info.width, h: info.height }, soft: blurred.code === 0 ? "soft.jpg" : null, box: clip.box || null,
429
+ image: { file: `capture${ext}`, w: info.width, h: info.height }, soft: hasSoft ? "soft.jpg" : null, box: clip.box || null,
133
430
  side: clip.side || "center", phone: info.height > info.width, fonts });
134
- const files = { [`capture${ext}`]: fs.readFileSync(clip.imageFile), ...(blurred.code === 0 ? { "soft.jpg": fs.readFileSync(soft) } : {}) };
431
+ // With a quarter to spare, as the phone's screen below.
432
+ const capture = await pagePicture(clip.imageFile, { maxW: page.drawnW * 1.25, out: path.join(work, `capture-${clip.index}${ext}`), what: `clip ${clip.index + 1}`,
433
+ named: `clips[${clip.index}].image "${confine.said(clip.image)}"` });
434
+ const files = { [`capture${ext}`]: capture, ...(hasSoft ? { "soft.jpg": fs.readFileSync(soft) } : {}) };
135
435
  return { html: page.html, files, cues: page.cues, W: page.W, H: page.H };
136
436
  }
137
437
  if (clip.kind === "shots") {
138
438
  const images = clip.imageFiles.map((file, k) => {
139
- const info = probe(file);
439
+ const info = pictureSize(file);
140
440
  return { file: `shot-${k}${path.extname(file).toLowerCase() === ".png" ? ".png" : ".jpg"}`, w: info.width, h: info.height, src: file };
141
441
  });
142
442
  const page = motion.galleryHtml({ look, port, seconds, accent: brandAccent, brand: colours, images, fonts });
143
- return { html: page.html, files: Object.fromEntries(images.map((im) => [im.file, fs.readFileSync(im.src)])), cues: page.cues, W: page.W, H: page.H };
443
+ const files = {};
444
+ for (const [k, im] of images.entries()) {
445
+ files[im.file] = await pagePicture(im.src, { maxW: Infinity, maxH: page.drawnH * 1.25, out: path.join(work, `shot-${clip.index}-${k}${path.extname(im.file)}`), what: `clip ${clip.index + 1}`,
446
+ named: `clips[${clip.index}].images[${k}] "${confine.said(clip.images[k])}"` });
447
+ }
448
+ return { html: page.html, files, cues: page.cues, W: page.W, H: page.H };
144
449
  }
145
450
  if (clip.kind === "phone" || clip.kind === "scroll") {
146
- const info = probe(clip.imageFile);
451
+ const info = pictureSize(clip.imageFile);
147
452
  const page = motion.deviceHtml({ mode: clip.kind, look, port, seconds, accent: brandAccent, brand: colours, image: { file: "screen.png", w: info.width, h: info.height },
148
453
  top: topColour(clip.imageFile), fonts });
149
454
  // The capture cut to what shows and made no larger than the page draws
@@ -151,7 +456,7 @@ async function buildClip(clip, ctx) {
151
456
  const keepH = Math.min(info.height, Math.ceil(info.height * page.use) + 2);
152
457
  const width = 2 * Math.round(Math.min(info.width, Math.ceil(page.drawnW * 1.25)) / 2);
153
458
  const prepared = path.join(work, `device-${clip.index}.png`);
154
- await mustRun(["-i", clip.imageFile, "-vf", `crop=${info.width}:${keepH}:0:0,scale=${width}:-2:flags=lanczos`, "-frames:v", "1", prepared], `clip ${clip.index + 1}`);
459
+ await writePicture([...input(clip.imageFile), "-vf", `crop=${info.width}:${keepH}:0:0,scale=${width}:-2:flags=lanczos`, "-frames:v", "1"], prepared, `clip ${clip.index + 1}`);
155
460
  return { html: page.html, files: { "screen.png": fs.readFileSync(prepared) }, cues: page.cues, W: page.W, H: page.H };
156
461
  }
157
462
  // The logo close.
@@ -167,7 +472,10 @@ async function buildClip(clip, ctx) {
167
472
  // other logo captures, else its app icon. A capture that cannot close (cut
168
473
  // off, too small, not a logo) is passed over with a note. Returns the
169
474
  // prepared mark ({ file, w, h, ground, icon }), or { refused } when none
170
- // would do.
475
+ // would do. A failure that is not the capture's (a full disk where the mark
476
+ // is written, an ffmpeg the system stopped) fails the run instead: it says
477
+ // nothing about the capture, and passed over for it, the film closed on
478
+ // another logo.
171
479
  async function markFor({ logoFile = null, iconFile = null, brand = null, out, portrait = false, notes = [], what }) {
172
480
  const tries = iconFile ? [{ icon: iconFile }] : [...(logoFile ? [{ logo: logoFile }] : []),
173
481
  ...(brand ? brand.logos.map((l) => ({ logo: l.file })).filter((t) => t.logo !== logoFile) : []),
@@ -176,15 +484,27 @@ async function markFor({ logoFile = null, iconFile = null, brand = null, out, po
176
484
  for (const t of tries) {
177
485
  try {
178
486
  const mark = t.icon ? await prepareIcon(t.icon, out) : await prepareLogo(t.logo, out, { portrait });
179
- if (refused.length) notes.push(`${what} uses ${path.basename(t.icon || t.logo)}: ${refused.join("; ")}.`);
487
+ if (refused.length) notes.push(`${what} uses ${confine.said(path.basename(t.icon || t.logo))}: ${refused.join("; ")}.`);
180
488
  return mark;
181
489
  } catch (err) {
182
- refused.push(`${path.basename(t.icon || t.logo)} was passed over (${err.message})`);
490
+ if (!err.refused) throw err;
491
+ refused.push(`${confine.said(path.basename(t.icon || t.logo))} was passed over (${err.message})`);
183
492
  }
184
493
  }
185
494
  return { file: null, refused };
186
495
  }
187
496
 
497
+ // The threads libx264 is given, in a clip's encoder and in the join, and
498
+ // the join's decoders: one and a half for each processor, as libx264 takes
499
+ // by itself, shared by the clips that render at once, and from 2 to 6, the
500
+ // 6 it takes on a machine of four. Left to choose, it takes them for every
501
+ // processor it sees, and its memory grows with them: a clip's encoder held
502
+ // about 1 GB on a machine of 24 and 410 MB with 6 threads, and two clips at
503
+ // once ran a container of 2 GB out of memory there.
504
+ function threadsFor(jobs) {
505
+ return Math.max(2, Math.min(6, Math.floor((1.5 * os.availableParallelism()) / jobs)));
506
+ }
507
+
188
508
  // Runs tasks with at most `jobs` at once.
189
509
  async function pool(items, jobs, fn) {
190
510
  const results = new Array(items.length);
@@ -199,16 +519,135 @@ async function pool(items, jobs, fn) {
199
519
  return results;
200
520
  }
201
521
 
522
+ // The kinds of file the film is written as without a try first: H.264 and
523
+ // AAC with faststart, as the last ffmpeg call writes them.
524
+ const FILM_KINDS = new Set([".mp4", ".m4v", ".mov", ".mkv"]);
525
+
526
+ // Why the film cannot be written to `out` (--output when `given`), or null.
527
+ // Read before anything renders: the name was first used once every clip had
528
+ // rendered, and the run failed then. Another kind of file than FILM_KINDS is
529
+ // tried on a frame of nothing, in the film's own codecs, so a kind ffmpeg
530
+ // writes them in is taken and one it does not (.webm) refused. The kind is
531
+ // blamed only when ffmpeg refused the try itself and then writes the same
532
+ // frame as an .mp4: an ffmpeg that cannot be started, that a signal ended,
533
+ // or that cannot write the .mp4 either (a build without libx264) says
534
+ // nothing about the kind, so the render goes on and fails in its own words,
535
+ // as it does with a film.mp4.
536
+ async function outputProblem(out, given) {
537
+ const named = given ? `--output ${out}` : out;
538
+ if (path.basename(out).startsWith(".launch-film-")) return `${named}: a name that starts with .launch-film- is one of launch-film's own: give another`;
539
+ let folder = false;
540
+ try {
541
+ folder = fs.statSync(out).isDirectory();
542
+ } catch {
543
+ // Not there yet, as a new film is not.
544
+ }
545
+ if (folder) return given ? `${named} is a folder: give the film's file in it, such as ${path.join(out, "film.mp4")}` : `${named} is a folder, where the film goes: move it, or give --output another file`;
546
+ const kind = path.extname(out).toLowerCase();
547
+ if (FILM_KINDS.has(kind)) return null;
548
+ if (!kind) return `${named} has no extension, so ffmpeg cannot tell what kind of file to write: give a name that ends in .mp4`;
549
+ const work = tempDir("launch-film-work-");
550
+ const write = (name) => run(["-f", "lavfi", "-i", "color=c=black:s=16x16:r=25", "-f", "lavfi", "-i", "anullsrc=r=48000:cl=stereo", "-frames:v", "1", "-t", "0.04",
551
+ "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-movflags", "+faststart", path.join(work, name)]);
552
+ try {
553
+ // ffmpeg's own refusal is an exit code above 0: run() gives -1 for one
554
+ // that could not be started, and a signal leaves the code null.
555
+ const tried = await write(`film${kind}`);
556
+ if (!(tried.code > 0)) return null;
557
+ const mp4 = await write("film.mp4");
558
+ return mp4.code === 0 ? `${named}: ffmpeg cannot write the film as a ${kind} file (H.264 video and AAC sound): give a name that ends in .mp4, .mov or .mkv` : null;
559
+ } finally {
560
+ release(work);
561
+ }
562
+ }
563
+
564
+ // The joined clips (`video`) and the film's sound (`wav`) written as the
565
+ // film `out`, `seconds` long, at LUFS with its true peak at TRUE_PEAK or
566
+ // under (above). `tries(n)` names the file the nth encode is written to:
567
+ // the one kept is renamed to `out`, and the others are removed as soon as a
568
+ // better one is made. Returns the level the film measures, { integrated,
569
+ // truePeak }.
570
+ async function addSound({ video, wav, out, seconds, tries }) {
571
+ // Silence measures no level, and its gain stays at 0.
572
+ const measured = await loudnormPass(wav, LOUDNORM);
573
+ const fits = (level) => level.truePeak <= TRUE_PEAK;
574
+ const off = (level) => Math.abs(level.integrated - LUFS);
575
+ // Of two encodes, one at TRUE_PEAK or under is the better, then the one
576
+ // nearer LUFS; of two that pass TRUE_PEAK, the one that passes it less.
577
+ const better = (a, b) => !b || (fits(a) !== fits(b) ? fits(a) : fits(a) ? off(a) < off(b) : a.truePeak < b.truePeak);
578
+ let gain = measured ? Math.max(-GAIN_MAX, Math.min(GAIN_MAX, LUFS - measured.integrated)) : 0;
579
+ let ceiling = CEILING;
580
+ let best = null;
581
+ let last = null;
582
+ for (let n = 0; n < TRIES; n++) {
583
+ const file = tries(n);
584
+ const limiter = `aformat=channel_layouts=stereo,aresample=192000,alimiter=limit=${(10 ** (ceiling / 20)).toFixed(4)}:attack=1:release=50:level=false,aresample=48000`;
585
+ try {
586
+ await mustRun(["-i", video, "-i", wav, "-map", "0:v", "-map", "1:a", "-c:v", "copy", "-af", `volume=${gain.toFixed(2)}dB,${limiter}`,
587
+ "-c:a", "aac", "-b:a", "192k", "-ar", "48000", "-t", seconds.toFixed(3), "-movflags", "+faststart", file], "adding the sound");
588
+ } catch (err) {
589
+ // An encode is named as the film it would become: its own name is a
590
+ // work file's, which goes with the part folder.
591
+ err.message = err.message.split(file).join(out);
592
+ throw err;
593
+ }
594
+ const level = await levelOf(file);
595
+ // Silence is kept as it is: no gain makes it louder.
596
+ if (!(level.integrated > -70) || !(level.truePeak > -Infinity)) {
597
+ if (best) fs.rmSync(best.file, { force: true });
598
+ best = { file, level };
599
+ break;
600
+ }
601
+ if (better(level, best && best.level)) {
602
+ if (best) fs.rmSync(best.file, { force: true });
603
+ best = { file, level };
604
+ } else fs.rmSync(file, { force: true });
605
+ if (fits(level) && off(level) <= 0.2) break;
606
+ // The limiter takes a part of what a gain adds, so the next gain goes by
607
+ // how far the last one moved the loudness, while the ceiling stayed.
608
+ let slope = 1;
609
+ if (last && last.ceiling === ceiling && Math.abs(gain - last.gain) >= 0.1) slope = Math.min(1, Math.max(0.25, (level.integrated - last.integrated) / (gain - last.gain)));
610
+ last = { gain, ceiling, integrated: level.integrated };
611
+ // A fifth of a dB to spare, as the encoder's lift varies a little from
612
+ // one encode to the next.
613
+ if (level.truePeak > TRUE_PEAK - 0.2) ceiling = Math.max(-12, ceiling - (level.truePeak - (TRUE_PEAK - 0.2)));
614
+ gain = Math.max(-GAIN_MAX, Math.min(GAIN_MAX, gain + Math.max(-12, Math.min(12, (LUFS - level.integrated) / slope))));
615
+ // A sound whose loudness no gain moves, as clicks the limiter holds at
616
+ // its ceiling, is as loud as it gets once the gain is at its end.
617
+ if (gain === last.gain && ceiling === last.ceiling) break;
618
+ }
619
+ fs.renameSync(best.file, out);
620
+ return best.level;
621
+ }
622
+
623
+ // The name of the timeline written next to the film `out`.
624
+ const timelineOf = (out) => path.basename(out).replace(/\.mp4$/i, "") + ".timeline.json";
625
+
202
626
  // Renders film.json to an MP4. Returns { output, seconds, clips, notes }.
203
627
  async function renderFilm(file, { output = null, jobs = 2, log = () => {}, keep = false, offline = false } = {}) {
628
+ const out = path.resolve(output || path.join(path.dirname(path.resolve(file)), "film.mp4"));
629
+ const unfit = await outputProblem(out, Boolean(output));
630
+ if (unfit) throw new Error(unfit);
204
631
  const loaded = loadFilm(file);
205
632
  if (loaded.problems.length) throw new Error(`film.json has problems:\n - ${loaded.problems.join("\n - ")}`);
206
- const { film, dir, brand, clips } = loaded;
633
+ const { track, problems } = await checkMusic(loaded);
634
+ if (problems.length) throw new Error(`film.json has problems:\n - ${problems.join("\n - ")}`);
635
+ // An earlier film or timeline the commit would not replace is refused
636
+ // now, not once every clip has rendered (out.js heldBack).
637
+ const held = heldBackIn(path.dirname(out), [path.basename(out), timelineOf(out)]);
638
+ if (held) throw new Error(held);
639
+ // The clips are made in a work folder outside the film's folder; the film
640
+ // and its timeline go in next to film.json only once both are whole. The
641
+ // run is begun here, so a stop while the clips render says which folder
642
+ // it left as it was.
643
+ return within(path.dirname(out), (job) => renderInto(job, file, loaded, { out, track, jobs, log, keep, offline }));
644
+ }
645
+
646
+ async function renderInto(job, file, { film, brand, clips }, { out, track, jobs, log, keep, offline }) {
207
647
  const look = film.look;
208
648
  const port = film.aspect === "9:16";
209
649
  const colours = brandColours(brand);
210
- const out = path.resolve(output || path.join(dir, "film.mp4"));
211
- const work = fs.mkdtempSync(path.join(os.tmpdir(), "launch-film-work-"));
650
+ const work = keep ? fs.mkdtempSync(path.join(os.tmpdir(), "launch-film-work-")) : tempDir("launch-film-work-");
212
651
  const notes = [...(brand ? brand.notes : [])];
213
652
  try {
214
653
  const fonts = await resolveFonts({ style: look, font: colours.headingFont || "", bodyFont: colours.bodyFont || "" }, { offline });
@@ -222,21 +661,31 @@ async function renderFilm(file, { output = null, jobs = 2, log = () => {}, keep
222
661
  });
223
662
  const total = at;
224
663
  const ctx = { look, port, fonts, colours, work, lang: film.lang || "", brand, notes };
664
+ const threads = threadsFor(Math.min(jobs, clips.length));
225
665
  let done = 0;
226
666
  const rendered = await pool(clips, jobs, async (clip) => {
227
667
  const page = await buildClip(clip, ctx);
228
668
  const mp4 = path.join(work, `clip-${String(clip.index).padStart(2, "0")}.mp4`);
229
669
  const started = Date.now();
230
- const r = await renderPage({ html: page.html, files: page.files, output: mp4, seconds: clip.render, W: page.W, H: page.H, fps: FPS });
670
+ // A failure says which clip it stopped, as ffmpeg's and Chrome's own
671
+ // words do not, and a Chrome too slow to answer or short of memory,
672
+ // when more than one clip renders at once (pool), that one at a time
673
+ // eases the machine. A system short of file descriptors or processes
674
+ // is no clip's.
675
+ const r = await renderPage({ html: page.html, files: page.files, output: mp4, seconds: clip.render, W: page.W, H: page.H, fps: FPS, threads })
676
+ .catch((err) => Promise.reject(err.short ? err : new Error(`rendering clip ${clip.index + 1}: ${err.message}${(err.slow || err.memory) && Math.min(jobs, clips.length) > 1 ? ", or with --jobs 1 to render one clip at a time" : ""}`)));
231
677
  done++;
232
678
  log(`clip ${clip.index + 1}/${clips.length} (${clip.kind}${clip.parsed ? ` ${clip.parsed.type}` : ""}, ${clip.seconds.toFixed(1)} s) rendered in ${((Date.now() - started) / 1000).toFixed(1)} s [${done}/${clips.length}]\n`);
233
679
  if (r.errors.length) notes.push(`clip ${clip.index + 1}: the page reported ${r.errors.slice(0, 2).join("; ")}`);
234
680
  if (r.failedFonts.length) notes.push(`clip ${clip.index + 1}: fonts failed to load: ${r.failedFonts.join(", ")}`);
235
681
  return { mp4, cues: page.cues.map((cue) => ({ ...cue, at: clip.start + cue.at })) };
236
682
  });
237
- // The clips joined: each crossfade starts on its clip's first frame.
683
+ // The clips joined: each crossfade starts on its clip's first frame. The
684
+ // join runs alone, and each clip it reads is decoded with as many
685
+ // threads as it is encoded with.
238
686
  const video = path.join(work, "video.mp4");
239
- const inputs = rendered.flatMap((r) => ["-i", r.mp4]);
687
+ const alone = String(threadsFor(1));
688
+ const inputs = rendered.flatMap((r) => ["-threads", alone, "-i", r.mp4]);
240
689
  let graph = "";
241
690
  let last = "[0:v]";
242
691
  for (let i = 1; i < clips.length; i++) {
@@ -245,24 +694,27 @@ async function renderFilm(file, { output = null, jobs = 2, log = () => {}, keep
245
694
  last = label;
246
695
  }
247
696
  const map = clips.length > 1 ? ["-filter_complex", graph.replace(/;$/, ""), "-map", "[v]"] : ["-map", "0:v"];
248
- await mustRun([...inputs, ...map, "-c:v", "libx264", "-preset", "medium", "-crf", "18", "-pix_fmt", "yuv420p", "-r", String(FPS),
697
+ await mustRun([...inputs, ...map, "-c:v", "libx264", "-preset", "medium", "-crf", "18", "-threads", alone, "-pix_fmt", "yuv420p", "-r", String(FPS),
249
698
  "-color_primaries", "bt709", "-color_trc", "bt709", "-colorspace", "bt709", "-t", total.toFixed(3), "-movflags", "+faststart", video], "joining the clips");
250
- // The sound: the bed for these cuts and every clip's effects.
699
+ // The sound: the bed for these cuts, or the user's own track in its
700
+ // place, and every clip's effects.
251
701
  const cues = film.sfx === false ? [] : rendered.flatMap((r) => r.cues);
252
- const bed = film.music === false ? null : audio.music({ look, seconds: total, cuts: clips.map((c) => c.start), seed: clips.length }).bus;
702
+ if (track) notes.push(trackNote(track, total));
703
+ const bed = film.music === false ? null : track ? audio.trackBus({ left: track.left, right: track.right, seconds: total, gain: audio.trackGain(track) })
704
+ : audio.music({ look, seconds: total, cuts: clips.map((c) => c.start), seed: clips.length }).bus;
253
705
  const wav = path.join(work, "sound.wav");
254
706
  audio.writeWav(wav, audio.mixFilm({ seconds: total, music: bed, cues, musicGain: film.music && film.music.volume !== undefined ? Number(film.music.volume) : 0.55 }));
255
- fs.mkdirSync(path.dirname(out), { recursive: true });
256
- await mustRun(["-i", video, "-i", wav, "-map", "0:v", "-map", "1:a", "-c:v", "copy", "-af", "loudnorm=I=-16:TP=-1.5:LRA=11", "-c:a", "aac", "-b:a", "192k", "-ar", "48000",
257
- "-t", total.toFixed(3), "-movflags", "+faststart", out], "adding the sound");
258
707
  const timeline = { film: path.relative(path.dirname(out), path.resolve(file)), seconds: +total.toFixed(3), look,
259
708
  clips: clips.map((c) => ({ index: c.index + 1, kind: c.kind, type: c.parsed ? c.parsed.type : undefined, start: +c.start.toFixed(3), seconds: +c.seconds.toFixed(3) })) };
260
- fs.writeFileSync(out.replace(/\.mp4$/i, "") + ".timeline.json", JSON.stringify(timeline, null, 2) + "\n");
709
+ // Each encode is made in the part folder, under a name no output can
710
+ // have (out.js), so what is not kept goes with it.
711
+ await addSound({ video, wav, out: job.out(path.basename(out)), seconds: total, tries: (n) => path.join(job.part, `.launch-film-sound-${n}${path.extname(out)}`) });
712
+ save(job.out(timelineOf(out)), JSON.stringify(timeline, null, 2) + "\n");
261
713
  return { output: out, seconds: total, clips: timeline.clips, notes };
262
714
  } finally {
263
- if (!keep) fs.rmSync(work, { recursive: true, force: true });
715
+ if (!keep) release(work);
264
716
  else log(`work files kept in ${work}\n`);
265
717
  }
266
718
  }
267
719
 
268
- module.exports = { loadFilm, renderFilm, buildClip, markFor, brandColours, FPS, FADE };
720
+ module.exports = { loadFilm, checkMusic, shellWord, musicfitCommand, trackNote, renderFilm, addSound, buildClip, markFor, brandColours, pagePicture, threadsFor, FPS, FADE };