@gentbajko/slopify 4.3.5 → 4.4.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.
@@ -2,19 +2,15 @@ import { spawn } from "node:child_process";
2
2
  import { isAbsolute, resolve as resolvePath } from "node:path";
3
3
  import { errorText, internalError } from "../../kernel/errors.js";
4
4
  import { bedChains, bedInputs } from "./ambient-mix.js";
5
+ import { bt709Frames, bt709Scale } from "./colour.js";
5
6
  import { codecArgs, defaultEncode, setRenderPriority, } from "./encoding.js";
6
7
  import { gradeFilter, lookChain, placed } from "./look.js";
7
- import { decimal, zoomRange } from "./plan.js";
8
+ import { moveOf } from "./move.js";
9
+ import { decimal } from "./plan.js";
8
10
  import { segments, transitionHalves } from "./transitions.js";
9
11
  // Hand-rolled per the standards: the filtergraph is the load-bearing part of this slice
10
12
  // and a wrapper would hide it. Every value goes into an argument array, never a shell
11
13
  // string, so a title or a filename cannot become a command.
12
- // zoompan works on a still that has been pre-scaled, because it steps the zoom in
13
- // sub-pixel increments and a source at output resolution visibly jitters where the zoom is
14
- // meant to be smooth and linear. A pan steps its crop window in whole source pixels, so
15
- // the same four times gives it quarter-pixel steps on screen. Four times the frame is
16
- // enough at 122.5%.
17
- const prescale = 4;
18
14
  const sampleRate = 44100;
19
15
  const channelLayout = "stereo";
20
16
  // `bundled` is ffmpeg-static's export. It is typed as unknown because the package is
@@ -80,11 +76,11 @@ function clipKey(edit, segment) {
80
76
  : [shot?.source, shot?.motion, shot?.frames, segment.from, segment.count, at]);
81
77
  }
82
78
  // A whole shot as one clip.
83
- export function clipArgs(frame, shot, output, intermediate = false) {
84
- return segmentArgs({ ...frame, shots: [shot] }, { kind: "shot", shot: 0, from: 0, count: shot.frames, start: 0 }, output, intermediate);
79
+ export function clipArgs(frame, shot, output, use = "watched") {
80
+ return segmentArgs({ ...frame, shots: [shot] }, { kind: "shot", shot: 0, from: 0, count: shot.frames, start: 0 }, output, use);
85
81
  }
86
82
  // One clip of the slideshow: part of a shot, or a transition between two, with the Look.
87
- export function segmentArgs(edit, segment, output, intermediate = false,
83
+ export function segmentArgs(edit, segment, output, use = "watched",
88
84
  // The clip's own chapter-card script, beside it in the working folder (`cards.ts`).
89
85
  cardsFile = "cards.ass",
90
86
  // Settings → Production defaults → Rendering (`encoding.ts`).
@@ -95,12 +91,17 @@ encode = defaultEncode) {
95
91
  if (shot === undefined)
96
92
  throw new Error(internalError("the video's edit list lost a shot", "Press Make the video again in the project's Video section"));
97
93
  const at = inputs.filter((one) => one === "-i").length;
98
- const built = pictureChain(edit, shot, from, segment.count, at, label, gradeFilter(edit.look));
94
+ const grade = gradeFilter(edit.look, shot.source.kind === "video" ? "video" : "still");
95
+ const built = pictureChain(edit, shot, from, segment.count, at, label, grade);
99
96
  inputs.push(...built.inputs);
100
97
  chains.push(built.chain);
101
98
  };
102
- const look = lookChain(edit, segment.start, segment.count, "[p]", "[v]", cardsFile);
103
- const picked = look === undefined ? "[v]" : "[p]";
99
+ const own = typeof use === "string" ? undefined : use;
100
+ // The last filter's output label, with the frames' colour tags set on the way out; a clip
101
+ // with its own captions hands its picture to them first.
102
+ const tagged = own === undefined ? `,${bt709Frames}[v]` : "[c]";
103
+ const look = lookChain(edit, segment.start, segment.count, "[p]", tagged, cardsFile);
104
+ const picked = look === undefined ? tagged : "[p]";
104
105
  if (segment.kind === "shot")
105
106
  picture(edit.shots[segment.shot], segment.from, picked);
106
107
  else {
@@ -114,6 +115,14 @@ encode = defaultEncode) {
114
115
  }
115
116
  if (look !== undefined)
116
117
  chains.push(look);
118
+ if (own !== undefined)
119
+ chains.push(...burnIn(inputs, own.portraits ?? [], {
120
+ from: "[c]",
121
+ // Drawn on the pixels the encoder is given, as captions over decoded clips are.
122
+ before: "format=yuv420p,",
123
+ script: own.script,
124
+ fonts: own.fonts,
125
+ }));
117
126
  return [
118
127
  ...progressArgs,
119
128
  ...inputs,
@@ -125,7 +134,7 @@ encode = defaultEncode) {
125
134
  ...(segment.kind === "shot" && segment.from === 0 && look === undefined
126
135
  ? []
127
136
  : ["-frames:v", String(segment.count)]),
128
- ...codecArgs(encode, intermediate ? "intermediate" : "final", edit.look),
137
+ ...codecArgs(encode, own !== undefined ? "captioned" : use === "recaptioned" ? "intermediate" : "final", edit.look),
129
138
  "-an",
130
139
  output,
131
140
  ];
@@ -160,24 +169,42 @@ function pictureChain(frame, shot, from, count, input, label, grade) {
160
169
  `setpts=PTS-STARTPTS,fps=${String(fps)},format=yuv420p${label}`,
161
170
  };
162
171
  }
163
- const move = zoompan(shot.motion, shot.frames, frameExpression(from, count, shot.frames));
164
- // A still that does not move has no sub-pixel steps to smooth, so it is not prescaled.
165
- const factor = move === undefined ? 1 : prescale;
166
- const wide = frame.width * factor;
167
- const tall = frame.height * factor;
172
+ const move = moveOf(frame, shot.motion, shot.frames, frameExpression(from, count, shot.frames), frame.stills?.get(source.path));
168
173
  // Clips that meet in a transition are brought to one pixel format first, since xfade
169
174
  // refuses to blend two that differ; a plain shot is left as it always was.
170
175
  const plain = from === 0 && count === shot.frames;
176
+ const still = `[${String(input)}:v]trim=end_frame=1,setpts=PTS-STARTPTS,` +
177
+ // The grade is applied here, to the one still frame, rather than to every frame after.
178
+ (grade === undefined ? "" : `${grade},`);
179
+ const out = `setsar=1${plain ? "" : ",format=yuv420p"}${label}`;
180
+ // zoompan turns the one still into the shot's frames either way: it is what ends the
181
+ // stream at exactly `count`.
182
+ if (move === undefined)
183
+ return {
184
+ inputs: ["-i", source.path],
185
+ chain: still +
186
+ // Cover the frame and centre-crop, never letterbox.
187
+ `scale=${frame.width}:${frame.height}:force_original_aspect_ratio=increase:${bt709Scale},` +
188
+ `crop=${frame.width}:${frame.height},` +
189
+ `zoompan=z='1':d=${count}:x='${centredX}':y='${centredY}':` +
190
+ `s=${frame.width}x${frame.height}:fps=${frame.fps},${out}`,
191
+ };
192
+ const { base, canvas } = move;
171
193
  return {
172
194
  inputs: ["-i", source.path],
173
- chain: `[${String(input)}:v]trim=end_frame=1,setpts=PTS-STARTPTS,` +
174
- // The grade is applied here, to the one still frame, rather than to every frame after.
175
- (grade === undefined ? "" : `${grade},`) +
176
- // Cover the frame and centre-crop, never letterbox.
177
- `scale=${wide}:${tall}:force_original_aspect_ratio=increase,crop=${wide}:${tall},` +
178
- `zoompan=z='${move?.z ?? "1"}':d=${count}:` +
179
- `x='${move?.x ?? centredX}':y='${move?.y ?? centredY}':` +
180
- `s=${frame.width}x${frame.height}:fps=${frame.fps},setsar=1${plain ? "" : ",format=yuv420p"}${label}`,
195
+ chain: still +
196
+ `scale=${base.width}:${base.height}:force_original_aspect_ratio=increase:flags=lanczos:${bt709Scale},` +
197
+ `crop=${base.width}:${base.height},` +
198
+ // A base under the frame sits top left of it, its last column and row drawn out to
199
+ // the frame's edges, so the sampler never reads black past the still.
200
+ (canvas.width > base.width
201
+ ? `pad=${canvas.width}:${canvas.height}:0:0,` +
202
+ `fillborders=right=${canvas.width - base.width}:bottom=${canvas.height - base.height}:mode=smear,`
203
+ : "") +
204
+ `zoompan=z='1':d=${count}:x='0':y='0':s=${canvas.width}x${canvas.height}:fps=${frame.fps},` +
205
+ `perspective=${move.quad}:sense=source:eval=frame:interpolation=cubic,` +
206
+ (canvas.width > frame.width ? `crop=${frame.width}:${frame.height}:0:0,` : "") +
207
+ out,
181
208
  };
182
209
  }
183
210
  // ceiling: a clip shorter than its shot is slowed to at most half speed, which still reads
@@ -190,7 +217,7 @@ export function slowdown(clip, shot) {
190
217
  return "1";
191
218
  return decimal(Math.round(Math.min(slowestSpeed, shot / clip) * 1000));
192
219
  }
193
- // zoompan's `on` counts the clip's own frames from 0; a clip that starts `from` frames into
220
+ // A filter's `on` counts the clip's own frames from 0; a clip that starts `from` frames into
194
221
  // its shot adds that, and one that reaches before or past the shot holds at its ends.
195
222
  function frameExpression(from, count, frames) {
196
223
  const shifted = from === 0 ? "on" : `(on${from > 0 ? "+" : "-"}${String(Math.abs(from))})`;
@@ -288,7 +315,7 @@ export function burnPartArgs(edit, list, output, start, portraits = [], encode =
288
315
  // back to 25 fps and drops frames.
289
316
  after: `,setpts=PTS-STARTPTS,fps=${String(edit.fps)}`,
290
317
  };
291
- const chains = burnIn(inputs, portraits, shifted.before, shifted.after);
318
+ const chains = burnIn(inputs, portraits, shifted);
292
319
  return [
293
320
  ...progressArgs,
294
321
  ...inputs,
@@ -305,18 +332,18 @@ export function burnPartArgs(edit, list, output, start, portraits = [], encode =
305
332
  // input and under the captions, so the panel's lit outline is drawn over them; a video without
306
333
  // any is burned exactly as before. A still image is one frame, which overlay holds to the end
307
334
  // (`eof_action=repeat`).
308
- function burnIn(inputs, portraits, before = "", after = "") {
335
+ function burnIn(inputs, portraits, draw = {}) {
309
336
  let first = inputs.filter((value) => value === "-i").length;
310
- let source = "[0:v]";
337
+ let source = draw.from ?? "[0:v]";
311
338
  const video = [];
312
339
  portraits.forEach((portrait, at) => {
313
340
  inputs.push("-i", portrait.path);
314
341
  const size = String(portrait.size);
315
- video.push(`[${String(first)}:v]scale=${size}:${size}:force_original_aspect_ratio=increase,crop=${size}:${size},setsar=1[pic${String(at)}]`, `${source}[pic${String(at)}]overlay=x=${String(portrait.x)}:y=${String(portrait.y)}:eof_action=repeat[panel${String(at)}]`);
342
+ video.push(`[${String(first)}:v]scale=${size}:${size}:force_original_aspect_ratio=increase:${bt709Scale},crop=${size}:${size},setsar=1[pic${String(at)}]`, `${source}[pic${String(at)}]overlay=x=${String(portrait.x)}:y=${String(portrait.y)}:eof_action=repeat[panel${String(at)}]`);
316
343
  source = `[panel${String(at)}]`;
317
344
  first += 1;
318
345
  });
319
- video.push(`${source}${before}ass=filename=subtitles.ass:fontsdir=fonts${after}[v]`);
346
+ video.push(`${source}${draw.before ?? ""}ass=filename=${draw.script ?? "subtitles.ass"}:fontsdir=${draw.fonts ?? "fonts"}${draw.after ?? ""},${bt709Frames}[v]`);
320
347
  return video;
321
348
  }
322
349
  const progressArgs = [
@@ -332,44 +359,6 @@ const progressArgs = [
332
359
  ];
333
360
  const centredX = "iw/2-(iw/zoom/2)";
334
361
  const centredY = "ih/2-(ih/zoom/2)";
335
- // zoompan's expressions for a motion, or undefined for one that does not move. `on` is
336
- // zoompan's output frame counter, 0 to d-1 (`at` shifts it for part of a shot), and a
337
- // one-frame shot has no span to divide by, so it holds where it starts. `zoom` in x and y is
338
- // the current zoom, so iw-iw/zoom is the room the crop window has to travel in.
339
- function zoompan(motion, frames, at = "on") {
340
- if (motion.kind === "still")
341
- return undefined;
342
- const range = zoomRange(motion.percent);
343
- if (range === undefined)
344
- return undefined;
345
- const span = frames - 1;
346
- if (motion.kind === "zoom") {
347
- // Zoom in rises from 100%, zoom out falls back to it, linear over the shot.
348
- const z = motion.direction === "in"
349
- ? span < 1
350
- ? range.from
351
- : `${range.from}+${range.by}*${at}/${span}`
352
- : span < 1
353
- ? range.to
354
- : `${range.to}-${range.by}*${at}/${span}`;
355
- return { z, x: centredX, y: centredY };
356
- }
357
- return {
358
- z: range.to,
359
- x: `(iw-iw/zoom)*(${travel(motion.from.x, motion.to.x, span, at)})`,
360
- y: `(ih-ih/zoom)*(${travel(motion.from.y, motion.to.y, span, at)})`,
361
- };
362
- }
363
- // A share of the room from `from` to `to`, linear over the shot. Built in whole
364
- // thousandths as decimal text, like the zoom, so 1 - 0.5 reads 0.5 and never
365
- // 0.49999999999999994.
366
- function travel(from, to, span, at) {
367
- const start = Math.round(from * 1000);
368
- const by = Math.round(to * 1000) - start;
369
- if (span < 1 || by === 0)
370
- return decimal(start);
371
- return `${decimal(start)}${by > 0 ? "+" : "-"}${decimal(Math.abs(by))}*${at}/${span}`;
372
- }
373
362
  function seconds(value) {
374
363
  return value.toFixed(3);
375
364
  }
@@ -1,3 +1,4 @@
1
+ import { bt709Scale } from "./colour.js";
1
2
  // The Look: filters appended to each clip's picture before it is encoded, so they cost one
2
3
  // pass over frames that are being made anyway and the render stays clip by clip. Everything
3
4
  // is ffmpeg's own filters with fixed numbers: no footage, no LUT files, and the same project
@@ -25,20 +26,33 @@ const grainStrength = {
25
26
  export function lookEncoding(look) {
26
27
  return look !== undefined && look.grain !== "off" ? ["-tune", "grain"] : [];
27
28
  }
29
+ // Each grade's filters on RGB, then on YUV.
28
30
  const grades = {
29
31
  // Golden highlights, a touch of amber in the mids, cooler shadows kept for depth.
30
- warm: "colorbalance=rs=0.02:bs=0.04:rm=0.08:gm=0.02:bm=-0.07:rh=0.07:gh=0.03:bh=-0.08," +
31
- "eq=saturation=1.12:contrast=1.04",
32
+ warm: {
33
+ rgb: "colorbalance=rs=0.02:bs=0.04:rm=0.08:gm=0.02:bm=-0.07:rh=0.07:gh=0.03:bh=-0.08",
34
+ yuv: "eq=saturation=1.12:contrast=1.04",
35
+ },
32
36
  // Blue-green shadows and mids, highlights barely touched.
33
- cold: "colorbalance=rs=-0.06:bs=0.08:rm=-0.05:gm=0.01:bm=0.06:rh=-0.02:bh=0.03,eq=saturation=0.9",
34
- desaturated: "eq=saturation=0.55:contrast=1.06",
37
+ cold: {
38
+ rgb: "colorbalance=rs=-0.06:bs=0.08:rm=-0.05:gm=0.01:bm=0.06:rh=-0.02:bh=0.03",
39
+ yuv: "eq=saturation=0.9",
40
+ },
41
+ desaturated: { yuv: "eq=saturation=0.55:contrast=1.06" },
35
42
  // The classic sepia matrix.
36
- sepia: "colorchannelmixer=rr=0.393:rg=0.769:rb=0.189:gr=0.349:gg=0.686:gb=0.168:br=0.272:bg=0.534:bb=0.131",
43
+ sepia: {
44
+ rgb: "colorchannelmixer=rr=0.393:rg=0.769:rb=0.189:gr=0.349:gg=0.686:gb=0.168:br=0.272:bg=0.534:bb=0.131",
45
+ },
37
46
  };
38
47
  // The grade as a filter for a picture's source, or undefined for none: a still is graded once,
39
- // a clip frame by frame.
40
- export function gradeFilter(look) {
41
- return look === undefined || look.grade === "none" ? undefined : grades[look.grade];
48
+ // a clip frame by frame. A still is RGB, so its one step into YUV is made here as BT.709 rather
49
+ // than left to ffmpeg's BT.601 default; a clip's YUV is left as it is.
50
+ export function gradeFilter(look, source) {
51
+ if (look === undefined || look.grade === "none")
52
+ return undefined;
53
+ const { rgb, yuv } = grades[look.grade];
54
+ const toYuv = source === "still" && yuv !== undefined ? `scale=${bt709Scale},format=yuv444p` : undefined;
55
+ return [rgb, toYuv, yuv].filter((step) => step !== undefined).join(",");
42
56
  }
43
57
  export function hasLook(look) {
44
58
  return (look !== undefined &&
@@ -135,7 +149,7 @@ function atmosphereSource(frame, atmosphere, start) {
135
149
  const peak = "max(r(X,Y),max(g(X,Y),b(X,Y)))";
136
150
  const lit = (plane) => `if(gt(${peak},0),255*${plane}(X,Y)/${peak},0)`;
137
151
  const light = `format=gbrap,geq=r='${lit("r")}':g='${lit("g")}':b='${lit("b")}':` +
138
- `a='${peak}*${atmosphereOpacity[atmosphere]}',format=yuva420p`;
152
+ `a='${peak}*${atmosphereOpacity[atmosphere]}',scale=${bt709Scale},format=yuva420p`;
139
153
  const moving = (h, v) => `${light},loop=loop=-1:size=1,setpts=N/(${String(fps)}*TB),` +
140
154
  `scroll=h=${String(h)}:v=${String(v)}:hpos=${position(h, start)}:vpos=${position(v, start)}`;
141
155
  if (atmosphere === "embers")
@@ -0,0 +1,89 @@
1
+ import { decimal, zoomRange } from "./plan.js";
2
+ // How a still moves. Each frame shows a window of the still: a zoom shrinks it about the
3
+ // centre, a pan slides it across the room the zoom leaves. `perspective` reads that window
4
+ // between whole pixels, so a move of a fraction of a pixel a frame advances by that fraction.
5
+ //
6
+ // zoompan, which did this before, can only land the window on a whole source pixel, and on
7
+ // every second one once the picture is 4:2:0 as the encoder asks. On a still enlarged four
8
+ // times that is a step of 0.61 of a frame pixel: a pan of 0.46 a frame stood still and jumped
9
+ // in turn, and a zoom's centre wandered by 0.45. Enlarging further costs the square of the
10
+ // factor and only halves the step.
11
+ //
12
+ // A sampler that interpolates is sharpest where a frame pixel lands on a source pixel and
13
+ // softer between. Where it reads the still at close to one to one, those places form wide
14
+ // bands that drift as the shot moves, and fine detail breathes: with the still at the frame's
15
+ // own size, the start of a zoom measured four and a half times zoompan's change in fine detail
16
+ // from frame to frame. So the still is first brought, once, to a base that keeps the sampler
17
+ // clear of one to one for the whole shot: under the frame for a still with no more pixels
18
+ // than that base holds, so it is only ever enlarged, and above the shot's whole zoom for any
19
+ // other, so it is only ever reduced and keeps the detail a larger still has. Both measured at
20
+ // or under zoompan's own change.
21
+ const smallShare = 0.92;
22
+ const clearOfOne = 1.05;
23
+ // The move of a shot, or undefined for one that does not move. `at` is the shot's frame as
24
+ // the filter counts it, 0 to frames-1; a one-frame shot has no span to divide by and holds
25
+ // where it starts.
26
+ export function moveOf(frame, motion, frames, at, still) {
27
+ if (motion.kind === "still")
28
+ return undefined;
29
+ const range = zoomRange(motion.percent);
30
+ if (range === undefined)
31
+ return undefined;
32
+ const small = shaped(frame, smallShare, -1);
33
+ // What the frame shows of the still is the still cropped to the frame's shape.
34
+ const fits = still !== undefined &&
35
+ Math.min(still.width, (still.height * frame.width) / frame.height) <= small.width;
36
+ const base = fits ? small : shaped(frame, clearOfOne * Number(range.to), 1);
37
+ const canvas = fits ? { width: frame.width, height: frame.height } : base;
38
+ const span = frames - 1;
39
+ const zoom = motion.kind === "pan"
40
+ ? range.to
41
+ : span < 1
42
+ ? motion.direction === "in"
43
+ ? range.from
44
+ : range.to
45
+ : motion.direction === "in"
46
+ ? `(${range.from}+${range.by}*${at}/${String(span)})`
47
+ : `(${range.to}-${range.by}*${at}/${String(span)})`;
48
+ // The window is the base over the zoom, so this is the room it has to travel in.
49
+ const room = (side) => `(${String(side)}-${String(side)}/${zoom})`;
50
+ const x = motion.kind === "pan"
51
+ ? `${room(base.width)}*(${travel(motion.from.x, motion.to.x, span, at)})`
52
+ : `${room(base.width)}/2`;
53
+ const y = motion.kind === "pan"
54
+ ? `${room(base.height)}*(${travel(motion.from.y, motion.to.y, span, at)})`
55
+ : `${room(base.height)}/2`;
56
+ // The corners are where the canvas's own corners read from, and the window is to fill the
57
+ // frame: on a canvas larger than the frame they lie that much further out.
58
+ const reach = (side, whole, shown) => `${String(side)}/${zoom}${whole === shown ? "" : `*${String(whole)}/${String(shown)}`}`;
59
+ const right = `${x}+${reach(base.width, canvas.width, frame.width)}`;
60
+ const bottom = `${y}+${reach(base.height, canvas.height, frame.height)}`;
61
+ return {
62
+ base,
63
+ canvas,
64
+ quad: `x0='${x}':y0='${y}':x1='${right}':y1='${y}':x2='${x}':y2='${bottom}':x3='${right}':y3='${bottom}'`,
65
+ };
66
+ }
67
+ // The size nearest `share` of the frame that keeps the frame's exact shape with both sides
68
+ // even, as 4:2:0 needs: under it when `step` is -1, over it when 1.
69
+ function shaped(frame, share, step) {
70
+ const unit = divisor(frame.width, frame.height);
71
+ const across = frame.width / unit;
72
+ const down = frame.height / unit;
73
+ let units = Math.max(1, step === -1 ? Math.floor(share * unit) : Math.ceil(share * unit));
74
+ while ((across * units) % 2 !== 0 || (down * units) % 2 !== 0)
75
+ units += units === 1 ? 1 : step;
76
+ return { width: across * units, height: down * units };
77
+ }
78
+ function divisor(a, b) {
79
+ return b === 0 ? a : divisor(b, a % b);
80
+ }
81
+ // A share of the room from `from` to `to`, linear over the shot. Built in whole thousandths
82
+ // as decimal text, like the zoom, so 1 - 0.5 reads 0.5 and never 0.49999999999999994.
83
+ function travel(from, to, span, at) {
84
+ const start = Math.round(from * 1000);
85
+ const by = Math.round(to * 1000) - start;
86
+ if (span < 1 || by === 0)
87
+ return decimal(start);
88
+ return `${decimal(start)}${by > 0 ? "+" : "-"}${decimal(Math.abs(by))}*${at}/${String(span)}`;
89
+ }
@@ -1,9 +1,10 @@
1
1
  import { availableParallelism, totalmem } from "node:os";
2
- // zoompan runs on one core, so a render of one clip at a time leaves most of the machine
3
- // idle. Measured on 32 cores with ffmpeg 7 and 15-second clips from a 4x still: one at a time
4
- // 8.1 s a clip, four at once 2.9 s, eight 1.9 s, sixteen 1.6 s. Eight is where the gain
5
- // flattens, and each run holds about 1.4 GB (a transition, two stills, twice that), so the
6
- // memory the process may use caps it as well.
2
+ // One clip's run does not fill the machine, so several go at once. Measured on 32 threads
3
+ // with ffmpeg 7, on the first 24 shots of a real project (11.5 minutes of video, captions
4
+ // burned in): one at a time 215 s, two 156 s, four 141 s, eight 141 s, twelve 142 s. The
5
+ // sampler and x264 both use several cores, so past four the machine is simply full, and eight
6
+ // costs nothing more. Each run holds about 1 GB, most of it x264's own frames, so the memory
7
+ // the process may use caps it as well.
7
8
  const mostJobs = 8;
8
9
  const coresPerJob = 4;
9
10
  const bytesPerJob = 3 * 1024 ** 3;
@@ -1,17 +1,21 @@
1
- import { copyFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2
- import { extname, join } from "node:path";
1
+ import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync, } from "node:fs";
2
+ import { extname, join, resolve } from "node:path";
3
3
  import { errorText, internalError } from "../../kernel/errors.js";
4
4
  import { masterFile, masterReport } from "../loudness/loudnorm.js";
5
5
  import { cardsAss } from "./cards.js";
6
- import { cacheKey, fileIdentity, keepClip, pruneClips, reuseClip } from "./clip-cache.js";
6
+ import { cacheKey, contentIdentity, fileIdentity, keepClip, pruneClips, reuseClip, } from "./clip-cache.js";
7
+ import { captionedClips, drawsOwnCaptions, readCaptions, } from "./clip-captions.js";
7
8
  import { defaultEncode, nvencFallbackNotice, } from "./encoding.js";
8
9
  import { audioMixArgs, burnPartArgs, concatList, joinArgs, runFfmpeg, segmentArgs, slideshowClips, } from "./ffmpeg.js";
9
10
  import { cardsIn } from "./look.js";
10
11
  import { inPool, renderJobs } from "./pool.js";
11
- // estimate: a zoompan frame from a 4x still costs several plain encoded frames, and a
12
+ import { stillSizes } from "./still-sizes.js";
13
+ // estimate: a frame sampled from its still and encoded costs several plain encoded frames, and a
12
14
  // copying join is nearly free, so progress is weighted by that rather than by clock time.
13
15
  const clipWeight = 4;
14
16
  const copyWeight = 0.05;
17
+ // The caption fonts beside the clips, apart from the chapter cards' `fonts`.
18
+ const captionFonts = "caption-fonts";
15
19
  // floor: a burned-in part shorter than a minute is not worth its own run.
16
20
  const leastPartFrames = 60 * 30;
17
21
  // The sound the join plays, as the join itself brings every segment to it.
@@ -41,16 +45,26 @@ async function renderWith(run, encode) {
41
45
  const priority = run.machine?.priority;
42
46
  // The ffmpeg that encodes the picture; copying, sound and probing stay with the bundled one.
43
47
  const encoder = encode.kind === "nvenc" ? encode.bin : run.bin;
44
- const { clips, order } = slideshowClips(edit);
48
+ const distinct = slideshowClips(edit);
49
+ // Captions are burned in one of two ways (`clip-captions.ts`): drawn by each clip's own run,
50
+ // or over the joined clips in a second encode.
51
+ const own = run.burnSubtitles && drawsOwnCaptions(distinct.clips, distinct.order)
52
+ ? ownCaptions(run, edit.fps)
53
+ : undefined;
54
+ const twice = run.burnSubtitles && own === undefined;
55
+ const { clips, order, } = own === undefined
56
+ ? { clips: distinct.clips.map((clip) => ({ name: clip.name, clip })), order: distinct.order }
57
+ : captionedClips(distinct.clips, distinct.order, own.captions, edit.fps);
58
+ const sized = { ...edit, stills: stillSizes(edit.shots, run.log) };
45
59
  const msOf = (frames) => (frames / edit.fps) * 1000;
46
60
  const joinMs = msOf(edit.shots.reduce((sum, shot) => sum + shot.frames, 0));
47
61
  // Progress is reported against the video's length, the longer of picture and sound.
48
62
  const totalMs = Math.max(joinMs, edit.audio.reduce((sum, segment) => sum + segment.seconds * 1000, 0));
49
- const clipMs = clips.reduce((sum, clip) => sum + msOf(clip.frames), 0);
63
+ const clipMs = clips.reduce((sum, one) => sum + msOf(one.clip.frames), 0);
50
64
  const jobs = run.jobs ?? renderJobs();
51
- const parts = run.burnSubtitles ? burnParts(order, clips, jobs) : [];
65
+ const parts = twice ? burnParts(order, distinct.clips, jobs) : [];
52
66
  const work = clipMs * clipWeight +
53
- joinMs * (run.burnSubtitles ? 1 : copyWeight) +
67
+ joinMs * (twice ? 1 : copyWeight) +
54
68
  (parts.length > 1 ? joinMs * copyWeight : 0);
55
69
  const report = (done) => {
56
70
  run.onProgress(work > 0 ? Math.round((Math.min(done, work) / work) * totalMs) : 0);
@@ -66,6 +80,8 @@ async function renderWith(run, encode) {
66
80
  mkdirSync(join(workspace, "fonts"), { mode: 0o700 });
67
81
  copyFileSync(font.path, join(workspace, "fonts", `card${extname(font.path)}`));
68
82
  }
83
+ // And so are a clip's own captions, with their fonts and the speaker portraits.
84
+ const drawn = own === undefined ? undefined : captionFiles(own, run.portraits, workspace);
69
85
  // The sound is mixed, levelled and encoded while the picture renders, on its own run; the
70
86
  // join then only copies it in. Either failing stops the other, and the first failure is
71
87
  // the one reported.
@@ -96,16 +112,25 @@ async function renderWith(run, encode) {
96
112
  const tell = () => {
97
113
  report(rendered + [...running.values()].reduce((sum, one) => sum + one, 0));
98
114
  };
99
- await inPool(clips, jobs, halt, async (clip, signal) => {
100
- const script = clip.name.replace(/\.mp4$/, ".ass");
115
+ await inPool(clips, jobs, halt, async (made, signal) => {
116
+ const { clip } = made;
117
+ const script = made.name.replace(/\.mp4$/, ".ass");
101
118
  const shown = cardsIn(cards, clip.segment.start, clip.segment.count);
102
- const drawn = shown.length > 0 && font !== undefined
119
+ const carded = shown.length > 0 && font !== undefined
103
120
  ? cardsAss(edit, shown, font.name, clip.segment.start, edit.cardColor)
104
121
  : undefined;
105
- if (drawn !== undefined)
106
- writeFileSync(join(workspace, script), drawn, { mode: 0o600 });
107
- const output = join(workspace, clip.name);
108
- const args = segmentArgs(edit, clip.segment, output, run.burnSubtitles, script, encode);
122
+ if (carded !== undefined)
123
+ writeFileSync(join(workspace, script), carded, { mode: 0o600 });
124
+ const spoken = made.name.replace(/\.mp4$/, ".said.ass");
125
+ const said = drawn === undefined ? undefined : made.said;
126
+ if (said !== undefined)
127
+ writeFileSync(join(workspace, spoken), said, { mode: 0o600 });
128
+ const output = join(workspace, made.name);
129
+ const args = segmentArgs(sized, clip.segment, output, drawn !== undefined && said !== undefined
130
+ ? { script: spoken, fonts: drawn.fonts, portraits: drawn.portraits }
131
+ : twice
132
+ ? "recaptioned"
133
+ : "watched", script, encode);
109
134
  const weight = msOf(clip.frames) * clipWeight;
110
135
  const cache = run.cache;
111
136
  let key;
@@ -113,7 +138,18 @@ async function renderWith(run, encode) {
113
138
  // let it go a moment ago) is encoded as if there were none.
114
139
  try {
115
140
  if (cache !== undefined) {
116
- key = cacheKey(encoder, args.map((value) => drawn === undefined ? value : value.replaceAll(script, "\u0000cards")), output, drawn === undefined || font === undefined ? [] : [drawn, fileIdentity(font.path)]);
141
+ key = cacheKey(encoder,
142
+ // The scripts are named after the clip's place in this render; what they say
143
+ // is in the key instead.
144
+ args.map((value) => {
145
+ const unsaid = said === undefined ? value : value.replaceAll(spoken, "\u0000captions");
146
+ return carded === undefined ? unsaid : unsaid.replaceAll(script, "\u0000cards");
147
+ }), output, [
148
+ ...(carded === undefined || font === undefined
149
+ ? []
150
+ : [carded, fileIdentity(font.path)]),
151
+ ...(drawn === undefined || said === undefined ? [] : [said, ...drawn.identity()]),
152
+ ], drawn?.stand());
117
153
  keys.add(key);
118
154
  if (reuseClip(cache, key, output)) {
119
155
  rendered += weight;
@@ -128,17 +164,17 @@ async function renderWith(run, encode) {
128
164
  }
129
165
  await runFfmpeg({
130
166
  bin: encoder,
131
- ...(cards.length > 0 ? { cwd: workspace } : {}),
167
+ ...(cards.length > 0 || drawn !== undefined ? { cwd: workspace } : {}),
132
168
  args,
133
169
  signal,
134
170
  log: run.log,
135
171
  priority,
136
172
  onProgress: (elapsedMs) => {
137
- running.set(clip.name, Math.min(elapsedMs * clipWeight, weight));
173
+ running.set(made.name, Math.min(elapsedMs * clipWeight, weight));
138
174
  tell();
139
175
  },
140
176
  });
141
- running.delete(clip.name);
177
+ running.delete(made.name);
142
178
  rendered += weight;
143
179
  if (cache !== undefined && key !== undefined) {
144
180
  try {
@@ -191,7 +227,7 @@ async function renderWith(run, encode) {
191
227
  throw failed.error;
192
228
  if (played === undefined)
193
229
  throw new Error("the render was canceled");
194
- const burnsHere = run.burnSubtitles && parts.length <= 1;
230
+ const burnsHere = twice && parts.length <= 1;
195
231
  await runFfmpeg({
196
232
  bin: burnsHere ? encoder : run.bin,
197
233
  cwd: run.cwd,
@@ -218,6 +254,55 @@ async function renderWith(run, encode) {
218
254
  rmSync(workspace, { recursive: true, force: true });
219
255
  }
220
256
  }
257
+ // The whole video's captions, read so each clip can draw its own part of them.
258
+ function ownCaptions(run, fps) {
259
+ const again = "Press Make the video again in the project's Video section";
260
+ const folder = run.cwd;
261
+ if (folder === undefined)
262
+ throw new Error(internalError("the captions have no folder", again));
263
+ let script;
264
+ try {
265
+ script = readFileSync(join(folder, "subtitles.ass"), "utf8");
266
+ }
267
+ catch (error) {
268
+ throw new Error(internalError(`the captions could not be read: ${errorText(error)}`, again), {
269
+ cause: error,
270
+ });
271
+ }
272
+ return { captions: readCaptions(script, fps), folder };
273
+ }
274
+ // What the clips draw their own captions with, put beside them: the caption fonts, and the
275
+ // speaker portraits where the caption folder holds them. That folder is written anew for
276
+ // every render, so `identity` and `stand` name the files in a clip's cache key by what they
277
+ // hold rather than by their path and date.
278
+ function captionFiles(own, portraits = [], workspace) {
279
+ const from = join(own.folder, "fonts");
280
+ const to = join(workspace, captionFonts);
281
+ if (existsSync(from))
282
+ cpSync(from, to, { recursive: true });
283
+ else
284
+ mkdirSync(to, { mode: 0o700 });
285
+ const placed = portraits.map((portrait) => ({
286
+ ...portrait,
287
+ path: resolve(own.folder, portrait.path),
288
+ }));
289
+ let identity;
290
+ let stand;
291
+ return {
292
+ fonts: captionFonts,
293
+ portraits: placed,
294
+ identity: () => {
295
+ identity ??= readdirSync(to)
296
+ .toSorted()
297
+ .map((name) => `${name}|${contentIdentity(join(to, name))}`);
298
+ return identity;
299
+ },
300
+ stand: () => {
301
+ stand ??= new Map(placed.map((portrait) => [portrait.path, `portrait:${contentIdentity(portrait.path)}`]));
302
+ return stand;
303
+ },
304
+ };
305
+ }
221
306
  // The video's finished sound as AAC in the working folder: the narration, silences and bed
222
307
  // mixed, and with Level the volume mastered first, alone and then as one file.
223
308
  async function renderSound(run, edit, workspace, signal) {
@@ -0,0 +1,37 @@
1
+ import { closeSync, openSync, readSync } from "node:fs";
2
+ import { errorText } from "../../kernel/errors.js";
3
+ import { pictureSize } from "../designs/picture-size.js";
4
+ // A PNG states its size in its first 24 bytes; a JPEG after its metadata, which a camera's
5
+ // thumbnail and colour profile can make a few hundred kilobytes.
6
+ const headBytes = 512 * 1024;
7
+ // Each still's own size, from the start of its file: a still with no more pixels than the
8
+ // frame is sampled from a smaller base (`move.ts`). One whose size cannot be read is left
9
+ // out and treated as a large one, which loses nothing and only costs time.
10
+ export function stillSizes(shots, log) {
11
+ const sizes = new Map();
12
+ const seen = new Set();
13
+ const head = Buffer.alloc(headBytes);
14
+ for (const { source } of shots) {
15
+ if (source.kind !== "image" || seen.has(source.path))
16
+ continue;
17
+ seen.add(source.path);
18
+ try {
19
+ const file = openSync(source.path, "r");
20
+ try {
21
+ const size = pictureSize(head.subarray(0, readSync(file, head, 0, head.length, 0)));
22
+ if (size !== undefined)
23
+ sizes.set(source.path, size);
24
+ }
25
+ finally {
26
+ closeSync(file);
27
+ }
28
+ }
29
+ catch (error) {
30
+ // The render refuses a still it cannot open, in ffmpeg's own words; this only notes it.
31
+ log.write("warn", "video.still", {
32
+ detail: `could not read the size of ${source.path}: ${errorText(error)}`,
33
+ });
34
+ }
35
+ }
36
+ return sizes;
37
+ }