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/src/fonts.js CHANGED
@@ -3,11 +3,22 @@
3
3
  // Typefaces come from Google Fonts by family name and are embedded in the
4
4
  // pages as data URLs (latin and latin-ext faces, so accented letters are
5
5
  // covered). Each family is fetched once and kept in the cache folder;
6
- // a family Google does not have is remembered as missing.
6
+ // a family Google does not have is remembered as missing for a day. A
7
+ // cached file is written under a name of its own and renamed into place once
8
+ // whole, since runs at the same time share the folder and a run may be
9
+ // killed mid-write.
10
+ //
11
+ // Runs share the cache, those of other films and, where launch-film runs for
12
+ // others, other people's: a name is asked for, kept and noted as missing in
13
+ // one form, so that a name spelt otherwise, with two spaces, which Google
14
+ // refuses, notes no other family as missing.
7
15
 
8
16
  const fs = require("fs");
9
17
  const os = require("os");
10
18
  const path = require("path");
19
+ const crypto = require("crypto");
20
+
21
+ const MISSING_FOR = 24 * 60 * 60 * 1000;
11
22
 
12
23
  function cacheDir() {
13
24
  const base = process.env.LAUNCH_FILM_CACHE || path.join(process.env.XDG_CACHE_HOME || path.join(os.homedir(), ".cache"), "launch-film");
@@ -28,18 +39,26 @@ async function get(url) {
28
39
  // @font-face CSS for the family at the weights asked (the nearest it has
29
40
  // when it lacks one), or "" when it cannot be had.
30
41
  async function loadFont(family, weights = [400, 700]) {
31
- const name = String(family || "").trim();
42
+ const name = String(family || "").trim().replace(/\s+/g, " ");
32
43
  if (!/^[A-Za-z0-9 ]{2,60}$/.test(name)) return "";
33
44
  const dir = cacheDir();
34
- const key = `${name.replace(/[^A-Za-z0-9]+/g, "_")}-${weights.join("_")}`;
35
- const file = path.join(dir, `${key}.css`);
45
+ const stem = name.replace(/ /g, "_");
46
+ const file = path.join(dir, `${stem}-${weights.join("_")}.css`);
36
47
  try {
37
- return fs.readFileSync(file, "utf8");
48
+ const cached = fs.readFileSync(file, "utf8");
49
+ // A file cut short (by an older release killed mid-write) is fetched again.
50
+ if (cached.trimEnd().endsWith("}")) return cached;
38
51
  } catch {
39
52
  // Not fetched yet.
40
53
  }
41
- const missing = path.join(dir, `${name.replace(/[^A-Za-z0-9]+/g, "_")}.missing`);
42
- if (fs.existsSync(missing)) return "";
54
+ // Google tells names apart by case, as the file names of a Mac or of
55
+ // Windows do not: the note carries a digest of the name as it is asked.
56
+ const missing = path.join(dir, `${stem}.${crypto.createHash("sha256").update(name).digest("hex").slice(0, 12)}.missing`);
57
+ try {
58
+ if (Date.now() - fs.statSync(missing).mtimeMs < MISSING_FOR) return "";
59
+ } catch {
60
+ // Not noted as missing.
61
+ }
43
62
  const base = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(name).replace(/%20/g, "+")}`;
44
63
  let css;
45
64
  try {
@@ -62,7 +81,16 @@ async function loadFont(family, weights = [400, 700]) {
62
81
  const data = Buffer.from(await (await get(url)).arrayBuffer()).toString("base64");
63
82
  out += block.slice(block.indexOf("@font-face")).replace(url, `data:font/woff2;base64,${data}`) + "\n";
64
83
  }
65
- if (out) fs.writeFileSync(file, out);
84
+ if (out) {
85
+ const part = `${file}.${process.pid}.${Math.random().toString(16).slice(2, 10)}.part`;
86
+ try {
87
+ fs.writeFileSync(part, out);
88
+ fs.renameSync(part, file);
89
+ } catch {
90
+ // Kept for this run only.
91
+ fs.rmSync(part, { force: true });
92
+ }
93
+ }
66
94
  return out;
67
95
  }
68
96
 
package/src/frames.js CHANGED
@@ -11,11 +11,22 @@
11
11
 
12
12
  const fs = require("fs");
13
13
  const path = require("path");
14
- const { mustRun, probe, readPixels, writePng } = require("./ffmpeg");
14
+ const { input, writePicture, mustRun, probe, readPixels, writePng } = require("./ffmpeg");
15
15
  const draw = require("./draw");
16
+ const { within } = require("./out");
17
+ const { filmListed } = require("./confine");
16
18
 
17
- // A path as one value inside an ffmpeg filter graph.
18
- const filterPath = (p) => `'${String(p).replace(/\\/g, "/").replace(/'/g, "\\'").replace(/:/g, "\\:")}'`;
19
+ // A path as one value inside an ffmpeg filter graph. ffmpeg unquotes the
20
+ // graph twice: once to split it into filters, where '...' is taken as it is
21
+ // and \ outside quotes escapes the next character, and once more to split
22
+ // each filter's options at ':', with the same rules. So the path's \, ' and
23
+ // : are escaped for the second, and the whole is quoted for the first, each
24
+ // ' in it closing the quote, coming in escaped and opening it again. On
25
+ // Windows, where \ divides a path, / serves as well.
26
+ function filterPath(p) {
27
+ const s = process.platform === "win32" ? String(p).replace(/\\/g, "/") : String(p);
28
+ return `'${s.replace(/[\\':]/g, (c) => `\\${c}`).replace(/'/g, "'\\''")}'`;
29
+ }
19
30
 
20
31
  // The clips launch-film's render listed next to the film, or null.
21
32
  function readTimeline(film) {
@@ -44,7 +55,7 @@ function joinStretches(list, gap = 0.05) {
44
55
  async function scanVideo(film, { work, duration }) {
45
56
  const notes = path.join(work, `.scan-video-${process.pid}.txt`);
46
57
  try {
47
- await mustRun(["-i", film, "-an", "-vf",
58
+ await mustRun([...input(film), "-an", "-vf",
48
59
  `scale=320:-2,scdet=threshold=100,blackdetect=d=0.04:pix_th=0.10:pic_th=0.98,freezedetect=n=-60dB:d=0.5,metadata=mode=print:file=${filterPath(notes)}`,
49
60
  "-f", "null", "-"], "reading the picture");
50
61
  const frames = [];
@@ -156,7 +167,7 @@ async function findCuts(film, { info, work, scan = null, given = null }) {
156
167
  const frames = (scan || (await scanVideo(film, { work, duration: info.duration }))).frames;
157
168
  cuts = detectCuts(frames).map((c) => ({ ...c, source, label: c.hard ? "" : "soft" }));
158
169
  }
159
- cuts = cuts.filter((c) => c.at < info.duration - 0.05).sort((a, b) => a.at - b.at);
170
+ cuts = cuts.filter((c) => c.at < stillSpan(info).end - 0.05).sort((a, b) => a.at - b.at);
160
171
  if (!cuts.length || cuts[0].at > 0.05) cuts.unshift({ at: 0, hard: true, source, label: "" });
161
172
  cuts.forEach((c, i) => {
162
173
  c.index = i + 1;
@@ -165,19 +176,33 @@ async function findCuts(film, { info, work, scan = null, given = null }) {
165
176
  return { cuts, source };
166
177
  }
167
178
 
179
+ // How much of a film its stills are taken from: `end`, where its picture
180
+ // ends when that is more than a frame before the film's end (its sound runs
181
+ // on), else the film's length, and `last`, the start of its picture's last
182
+ // frame, the latest moment a still can be taken at. A still asked for past
183
+ // the picture found no frame: ffmpeg 4.4 wrote nothing and ended well, and
184
+ // newer builds failed.
185
+ function stillSpan(info) {
186
+ const frame = 1 / (info.fps || 25);
187
+ const picture = info.picture || info.duration;
188
+ const end = picture < info.duration - frame ? picture : info.duration;
189
+ return { end, last: Math.max(0, Math.min(end, picture) - frame) };
190
+ }
191
+
168
192
  // The shots between the cuts: [{ index, start, seconds, label }].
169
193
  const shotsOf = (cuts, duration) => cuts.map((c, i) => ({ index: c.index, start: c.at, seconds: (i + 1 < cuts.length ? cuts[i + 1].at : duration) - c.at, label: c.label, hard: c.hard }));
170
194
 
171
195
  // A shot's settled moment: once its entrance has played.
172
196
  const settled = (shot) => shot.start + Math.min(shot.seconds * 0.55, 2.4);
173
197
 
174
- // Saves a frame at each moment: [{ at, name }] in, [{ file, at, label }] out.
175
- async function grabFrames(film, moments, dir, { duration, ext = "jpg" }) {
198
+ // Saves a frame at each moment, none past `last` (stillSpan): [{ at, name }]
199
+ // in, [{ file, at, label }] out.
200
+ async function grabFrames(film, moments, dir, { last, ext = "jpg" }) {
176
201
  const stills = [];
177
202
  for (const m of moments) {
178
- const at = Math.max(0, Math.min(duration - 0.05, m.at));
203
+ const at = Math.max(0, Math.min(last, m.at));
179
204
  const file = path.join(dir, `${m.name}.${ext}`);
180
- await mustRun(["-ss", at.toFixed(3), "-i", film, "-frames:v", "1", "-q:v", "3", file], "saving a still");
205
+ await writePicture(["-ss", at.toFixed(3), ...input(film), "-frames:v", "1", "-q:v", "3"], file, "saving a still", { none: `${film} has no picture at ${at.toFixed(2)} s` });
181
206
  stills.push({ file, at: +at.toFixed(2), label: m.label || "" });
182
207
  }
183
208
  return stills;
@@ -215,30 +240,48 @@ async function contactSheet(stills, file, { title = "", cols = 4 } = {}) {
215
240
  return file;
216
241
  }
217
242
 
243
+ // The files frames saves of a film of `shots` shots, more than one, as every
244
+ // film launch-film plans is: its contact sheet and two stills a shot, what it
245
+ // replaces in a frames folder there. Without `shots`, the sheet alone: the
246
+ // one-go film knows how many clips its film has only once its plan is made.
247
+ function framesMade(shots = 0) {
248
+ const names = ["sheet.jpg"];
249
+ for (let i = 1; i <= shots; i++) names.push(`clip-${i}-a.jpg`, `clip-${i}-b.jpg`);
250
+ return names;
251
+ }
252
+
218
253
  // The frames command: two stills a shot (once its entrance has played, and
219
254
  // near its end) and a contact sheet of them all. A film with one shot gets
220
- // twelve stills spread evenly.
255
+ // twelve stills spread evenly. They take the place of the earlier ones of
256
+ // the same names once all are made (out.js).
221
257
  async function saveFrames(file, { out = null } = {}) {
222
258
  const film = path.resolve(file);
259
+ // A list of other files, with LAUNCH_FILM_CONFINE set, as check refuses it.
260
+ const listed = filmListed(film, file);
261
+ if (listed) throw new Error(listed);
223
262
  const info = probe(film);
224
- if (!info.duration) throw new Error(`${file} could not be read as a video`);
263
+ if (!info.duration) throw new Error(`${file} could not be read as a video${info.failed ? ` (${info.failed})` : ""}`);
225
264
  const dir = path.resolve(out || path.join(path.dirname(film), "frames"));
226
- fs.mkdirSync(dir, { recursive: true });
227
- const { cuts } = await findCuts(film, { info, work: dir });
228
- const moments = [];
229
- if (cuts.length > 1) {
230
- for (const s of shotsOf(cuts, info.duration)) {
231
- moments.push({ at: settled(s), name: `clip-${s.index}-a`, label: s.label });
232
- moments.push({ at: s.start + s.seconds - 0.3, name: `clip-${s.index}-b`, label: s.label });
265
+ return within(dir, async (run) => {
266
+ const { cuts } = await findCuts(film, { info, work: run.part });
267
+ const span = stillSpan(info);
268
+ const moments = [];
269
+ if (cuts.length > 1) {
270
+ for (const s of shotsOf(cuts, span.end)) {
271
+ moments.push({ at: settled(s), name: `clip-${s.index}-a`, label: s.label });
272
+ moments.push({ at: s.start + s.seconds - 0.3, name: `clip-${s.index}-b`, label: s.label });
273
+ }
274
+ } else {
275
+ for (let i = 0; i < 12; i++) moments.push({ at: ((i + 0.5) * span.end) / 12, name: `still-${i + 1}` });
233
276
  }
234
- } else {
235
- for (let i = 0; i < 12; i++) moments.push({ at: ((i + 0.5) * info.duration) / 12, name: `still-${i + 1}` });
236
- }
237
- const stills = await grabFrames(film, moments, dir, { duration: info.duration });
238
- stills.forEach((s, i) => (s.number = cuts.length > 1 ? `${Math.floor(i / 2) + 1}${i % 2 ? "B" : "A"}` : `${i + 1}`));
239
- const sheet = path.join(dir, "sheet.jpg");
240
- await contactSheet(stills, sheet, { title: `${path.basename(film)} ${info.duration.toFixed(2)} S ${info.width}X${info.height}` });
241
- return { dir, stills, sheet, cuts };
277
+ const stills = await grabFrames(film, moments, run.part, { last: span.last });
278
+ for (const s of stills) run.out(path.basename(s.file));
279
+ stills.forEach((s, i) => (s.number = cuts.length > 1 ? `${Math.floor(i / 2) + 1}${i % 2 ? "B" : "A"}` : `${i + 1}`));
280
+ await contactSheet(stills, run.out("sheet.jpg"), { title: `${path.basename(film)} ${info.duration.toFixed(2)} S ${info.width}X${info.height}` });
281
+ // Where they are once the run has ended.
282
+ for (const s of stills) s.file = path.join(dir, path.basename(s.file));
283
+ return { dir, stills, sheet: path.join(dir, "sheet.jpg"), cuts };
284
+ });
242
285
  }
243
286
 
244
- module.exports = { saveFrames, scanVideo, detectCuts, findCuts, givenCuts, shotsOf, settled, grabFrames, contactSheet, readTimeline, joinStretches, filterPath };
287
+ module.exports = { saveFrames, framesMade, scanVideo, detectCuts, findCuts, givenCuts, stillSpan, shotsOf, settled, grabFrames, contactSheet, readTimeline, joinStretches, filterPath };
package/src/logo.js CHANGED
@@ -5,10 +5,24 @@
5
5
  // recoloured. A capture is checked before it is used: one whose mark runs
6
6
  // off an edge (a header cut through the icon), one that is a photo or a
7
7
  // page, and one too small to close on sharply are refused, so the next
8
- // capture is tried.
8
+ // capture is tried. Such a refusal is marked as one (refused); any other
9
+ // failure, as a full disk where the prepared mark is written or an ffmpeg
10
+ // the system stopped, is the run's, and no other capture is tried for it.
9
11
 
10
12
  const { readPixels, writePng } = require("./ffmpeg");
11
13
 
14
+ const refuse = (why) => Object.assign(new Error(why), { refused: true });
15
+
16
+ // A capture's pixels: one that ffmpeg cannot read as a picture is refused.
17
+ function pixelsOf(file, max) {
18
+ try {
19
+ return readPixels(file, max);
20
+ } catch (err) {
21
+ if (err.signal) throw err;
22
+ throw Object.assign(err, { refused: true });
23
+ }
24
+ }
25
+
12
26
  const hexOf = (c) => `#${c.map((v) => Math.round(v).toString(16).padStart(2, "0")).join("").toUpperCase()}`;
13
27
  const lumOf = (c) => (0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2]) / 255;
14
28
 
@@ -97,7 +111,7 @@ function borderColour(px, sw, sh) {
97
111
  // used. A see-through capture is set on white under a dark mark and on
98
112
  // near-black under a light one first.
99
113
  async function prepareLogo(input, output, { portrait = false } = {}) {
100
- const full = readPixels(input);
114
+ const full = pixelsOf(input);
101
115
  const { width: W0, height: H0 } = full;
102
116
  const px = Buffer.from(full.data);
103
117
  let clear = 0;
@@ -133,7 +147,7 @@ async function prepareLogo(input, output, { portrait = false } = {}) {
133
147
  }
134
148
  const bg = borderColour(small, sw, sh);
135
149
  const { box, keep, trimmed } = measure(small, sw, sh, bg);
136
- if (!box) throw new Error("the picture is one colour");
150
+ if (!box) throw refuse("the picture is one colour");
137
151
  const [x0, y0, x1, y1] = box;
138
152
  // A mark that runs off one edge, with an empty margin on the other side,
139
153
  // is cut off (a tight crop touches both sides and passes).
@@ -143,7 +157,7 @@ async function prepareLogo(input, output, { portrait = false } = {}) {
143
157
  y1 >= sh - 2 && y0 > 0.25 * sh && "bottom",
144
158
  y0 <= 1 && y1 < 0.75 * sh && "top",
145
159
  ].find(Boolean);
146
- if (off) throw new Error(`its mark runs off the ${off} edge`);
160
+ if (off) throw refuse(`its mark runs off the ${off} edge`);
147
161
  // A logo is drawn in a few flat colours: its eight commonest tones cover
148
162
  // most of it. A photo or a page is spread over hundreds.
149
163
  const tones = new Map();
@@ -158,11 +172,11 @@ async function prepareLogo(input, output, { portrait = false } = {}) {
158
172
  }
159
173
  }
160
174
  const common = [...tones.values()].sort((a, b) => b - a).slice(0, 8).reduce((a, b) => a + b, 0);
161
- if (tones.size > 150 && common < 0.6 * marked) throw new Error("it is a photo or a page, not a logo");
175
+ if (tones.size > 150 && common < 0.6 * marked) throw refuse("it is a photo or a page, not a logo");
162
176
  const bw = (x1 - x0 + 1) / k;
163
177
  const bh = (y1 - y0 + 1) / k;
164
178
  const shape = Math.max(W0, H0) / Math.min(W0, H0);
165
- if (Math.min(W0, H0) > 700 && shape >= 1.25 && shape <= 2.5 && bw * bh > 0.5 * W0 * H0) throw new Error("it is a screenshot of a page, not a logo");
179
+ if (Math.min(W0, H0) > 700 && shape >= 1.25 && shape <= 2.5 && bw * bh > 0.5 * W0 * H0) throw refuse("it is a screenshot of a page, not a logo");
166
180
  const room = Math.min((x0 - keep.x0) / k, (keep.x1 - x1) / k, (y0 - keep.y0) / k, (keep.y1 - y1) / k);
167
181
  const margin = trimmed ? Math.max(0, Math.min(Math.max(6, 0.15 * Math.min(bw, bh)), room)) : Math.max(6, 0.15 * Math.min(bw, bh));
168
182
  const cx = Math.max(0, Math.floor(x0 / k - margin));
@@ -173,7 +187,7 @@ async function prepareLogo(input, output, { portrait = false } = {}) {
173
187
  // (9:16: 70% and 14%), and at most twice its captured size.
174
188
  const [PW, PH] = portrait ? [1080, 1920] : [1920, 1080];
175
189
  const scale = Math.min(((portrait ? 0.7 : 0.42) * PW) / bw, ((portrait ? 0.14 : 0.24) * PH) / bh, 2);
176
- if (Math.max(bw, bh) * scale < 0.15 * Math.min(PW, PH)) throw new Error(`its mark is too small to close on (${Math.round(bw)}x${Math.round(bh)} px)`);
190
+ if (Math.max(bw, bh) * scale < 0.15 * Math.min(PW, PH)) throw refuse(`its mark is too small to close on (${Math.round(bw)}x${Math.round(bh)} px)`);
177
191
  // A neutral mid-grey ground is a page dimmed by an open overlay, not the
178
192
  // brand's: the ground becomes white under a dark mark and near-black under
179
193
  // a light one.
@@ -217,9 +231,9 @@ async function prepareLogo(input, output, { portrait = false } = {}) {
217
231
  // An app's store icon for the close: square art shown whole, with rounded
218
232
  // corners drawn by the page.
219
233
  async function prepareIcon(input, output) {
220
- const p = readPixels(input, 1024);
221
- if (Math.abs(p.width / p.height - 1) > 0.05) throw new Error("an app icon is square");
222
- if (p.width < 240) throw new Error("the icon is too small");
234
+ const p = pixelsOf(input, 1024);
235
+ if (Math.abs(p.width / p.height - 1) > 0.05) throw refuse("an app icon is square");
236
+ if (p.width < 240) throw refuse("the icon is too small");
223
237
  await writePng(output, p);
224
238
  return { file: output, w: 360, h: 360, ground: hexOf(borderColour(p.data, p.width, p.height)), icon: true };
225
239
  }
package/src/motion.js CHANGED
@@ -531,7 +531,8 @@ ${timelineTag()}
531
531
  // light, and a cursor (a tap on a phone's screen) points at it; a full screen
532
532
  // keeps easing in while the cursor crosses it. Files: image (the capture, as
533
533
  // served next to the page) and soft (a blurred copy, the window's width).
534
- // box: the block in the capture's pixels (zoom). Returns { html, cues, W, H }.
534
+ // box: the block in the capture's pixels (zoom). Returns { html, cues, W, H,
535
+ // window, drawnW }: drawnW is the widest the capture is drawn.
535
536
  function screenHtml({ mode, look: lookName, port, seconds, accent, image, soft, box: blk = null, side = "center", phone = false, captions = false, fonts = null, brand = null }) {
536
537
  const look = LOOKS[lookName];
537
538
  const [W, H] = port ? FRAME.port : FRAME.land;
@@ -649,7 +650,11 @@ ${timelineTag()}
649
650
  <div class="stage"><div class="ground">${look.ground ? look.ground(t, seed, port) : groundHtml(look.family || lookName, t, seed, port)}</div><div class="world" id="world">${world}</div>${stage}
650
651
  <div class="post"><div class="vignette"></div><div class="grain"></div></div></div>
651
652
  <script>window.__S=${JSON.stringify(cfg)};</script><script>${runtime}</script></body></html>`;
652
- return { html, cues, W, H, window: { w: ww, h: wh } };
653
+ // The widest the capture is drawn, in the page's pixels: the camera's
654
+ // zoom onto the block, its drift and the lifted block at their largest,
655
+ // or the slow push of a pan.
656
+ const drawnW = ww * (cam ? cam.scale * 1.025 * 1.06 * 1.02 : 1.07);
657
+ return { html, cues, W, H, window: { w: ww, h: wh }, drawnW };
653
658
  }
654
659
 
655
660
  // ─── the close ─────────────────────────────────────────────────────────────
@@ -922,7 +927,8 @@ ${timelineTag()}
922
927
  // A store screenshot is often a picture of its own (a phone drawn on a
923
928
  // colour with a line of text over it), so it is shown whole, never put in a
924
929
  // second phone. images: [{ file, w, h }] served next to the page (two or
925
- // three). Returns { html, cues, W, H }.
930
+ // three). Returns { html, cues, W, H, drawnH }: drawnH is the tallest a card
931
+ // is drawn.
926
932
  function galleryHtml({ look: lookName, port, seconds, accent, images, fonts = null, brand = null }) {
927
933
  const look = LOOKS[lookName];
928
934
  const fam = look.family || lookName;
@@ -1001,7 +1007,9 @@ ${timelineTag()}
1001
1007
  <div class="stage"><div class="ground">${look.ground ? look.ground(t, seed, port) : groundHtml(fam, t, seed, port)}${glow}${floor}</div><div class="world" id="world">${world}</div>
1002
1008
  <div class="post"><div class="vignette"></div><div class="grain"></div></div></div>
1003
1009
  <script>window.__S=${JSON.stringify(cfg)};</script><script>${runtime}</script></body></html>`;
1004
- return { html, cues, W, H };
1010
+ // The tallest a card is drawn, in the page's pixels: the front one at its
1011
+ // rest, with the stage's slow push.
1012
+ return { html, cues, W, H, drawnH: ch * 1.024 * 1.05 };
1005
1013
  }
1006
1014
 
1007
1015
  // ─── stills ────────────────────────────────────────────────────────────────