@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.
@@ -122,7 +122,10 @@ export function projectRoutes(deps) {
122
122
  : "This project no longer exists. Go back to Projects to pick another.",
123
123
  });
124
124
  }
125
- if (deps.catalogue !== undefined)
125
+ // Only a project with no saved version yet needs one adopted: asked of one that has,
126
+ // adopting builds that whole version and drops it, on the request every live event
127
+ // and every return to the page repeats.
128
+ if (deps.catalogue !== undefined && currentRevisionId(deps.db, project.id) === undefined)
126
129
  adoptBaseline(deps, project.id);
127
130
  const holds = projectHolds(deps.db, { projectId: project.id });
128
131
  const stopped = holds.stopped.has(project.id);
@@ -0,0 +1,37 @@
1
+ # Slopify 4.4.0
2
+
3
+ Released 13 November 2026.
4
+
5
+ Pans and zooms now move evenly, a video with captions in the picture is made in a little over half the time, videos keep the colours of their pictures, and opening a finished project no longer stalls the app.
6
+
7
+ ## Pans and zooms no longer shake
8
+
9
+ - **A slow pan now moves by the same amount every frame.** Since images are held for their share of the narration, a shot runs about half a minute and a pan advances under half a pixel a frame. The picture could only be placed on whole pixels, so it stood still for a frame and then jumped: measured on a finished video, steps between nothing and 0.73 of a pixel where 0.46 was meant. They now measure 0.39 to 0.50, and what is left is the encoder's own noise.
10
+ - **A zoom holds its centre.** It wandered by up to 0.4 of a pixel from one frame to the next; it now moves by under 0.05.
11
+ - **The picture is placed between pixels,** in one pass at the frame's own size, instead of being enlarged four times and stepped. Fine detail is as sharp as before, within three percent either way.
12
+ - **Files are about three percent larger at the same quality setting,** because a picture that really moves every frame gives the encoder more to describe than one that stands still every other frame.
13
+ - **A still larger than the frame keeps its detail,** as before: it is sampled from a larger copy than a still with no more pixels than the frame, and each is kept away from the one size where fine detail would flicker.
14
+
15
+ ## A video with captions is encoded once
16
+
17
+ - **Where each image is shown once, every clip now draws its own captions.** Until now the clips were encoded, joined, and the whole video encoded a second time to draw the captions over it, so every frame was compressed twice, the second time from a copy the first had already softened. Each frame is now sampled from its still, captioned and encoded in one go, and the join only copies.
18
+ - **It takes a little over half the time.** Measured on the first 24 images (11.5 minutes) of a real project on a 16-core processor: 83 seconds, against 155 in 4.3.5. The picture scores slightly higher against a lossless render (93.8 VMAF against 93.2 for two encodes), since it is compressed once, and the file is 1% larger.
19
+ - **A video whose same clips come round again keeps the two encodes,** because there they are the cheaper way: twelve stills that revolve for two hours at a fixed number of seconds each are a few minutes of distinct clips, and decoding a clip costs less than sampling its still again. Slopify picks per video: clips draw their own captions when the distinct clips are a third of the video or more, which a video whose shots follow the narration always is, since no two shots are the same length.
20
+ - **Changing one image or one caption no longer re-encodes the video.** Clips that draw their own captions are kept with them for the next render, so only the clips that changed are made again; before, any change sent the whole video through the caption encode. A two-hour video with 240 images took 14.7 minutes to make, sound included, and 1.7 minutes to make again with nothing changed.
21
+ - **Captions land on the exact frame.** A caption that starts at the very moment a frame is shown is now on that frame; a rounding used to put a few captions in a hundred one frame late. Checked frame by frame on that 11.5-minute render: 5 frames of 20,655 differ, each by that one frame.
22
+ - **Clip encoding: Fast now means the same for every video with captions,** about a sixth less time for a slightly softer picture. For clips that draw their own captions it is x264's faster preset (69 seconds against 83, 1.2 VMAF less, a sixth smaller); the two-encode route keeps what Fast always did there.
23
+
24
+ ## Videos keep the colours of their pictures
25
+
26
+ - **Every video is now BT.709 and says so.** Pictures were turned into video with the older BT.601 formula and the file carried no colour labels, while players and YouTube read an unlabelled HD video as BT.709. The result was a slight warm cast on every video: reds a few steps too strong, blues a few too weak.
27
+ - **This covers every still that goes into a video:** plain, zooming and panning pictures, the four colour grades, portraits beside captions and the atmosphere layers. A clip that is already video keeps its own colours and only gets the label.
28
+ - **Coloured captions and chapter cards match as well,** with the NVIDIA encoder too. White text never changed.
29
+ - **Videos already made stay as they are;** make one again to get the corrected colours. The first render after updating encodes every clip afresh rather than reusing saved ones, since their colours differ.
30
+
31
+ ## Opening a finished project no longer stalls the app
32
+
33
+ - **A finished project's page opens without freezing everything else.** Working out what Keep outputs only would free read every saved version once for each of the project's files: about two and a half seconds on a two-hour video with 600 files, during which no page got an answer, and it ran again on every visit and every return to the window. It now reads them once, in about two hundredths of a second, and answers the same.
34
+ - **Settings → Storage answers in a couple of seconds,** where it took over twenty with 170 projects. It asked the same question of every project in turn.
35
+ - **A running step no longer keeps the page asking for the whole project.** Each progress report, up to two a second, made the open page fetch everything it shows again, the saved version included (megabytes on a finished project). A report now fetches the meter and the cost, once a second at most, and the rest only every few seconds.
36
+ - **Coming back to the window no longer fetches the saved version and the name checks again.** Live events and saves already keep those fresh. Everything else is still asked again on return, which is how the page learns what the extension did in YouTube Studio.
37
+ - **Reading a saved version takes about half the time,** for every page of a project and every step of a run: its files are looked up once, not one at a time.
@@ -1,4 +1,10 @@
1
1
  [
2
+ {
3
+ "id": "4.4.0",
4
+ "title": "Slopify 4.4.0",
5
+ "version": "4.4.0",
6
+ "date": "2026-11-13"
7
+ },
2
8
  {
3
9
  "id": "4.3.5",
4
10
  "title": "Slopify 4.3.5",
@@ -1,5 +1,4 @@
1
1
  import { readFileSync, statSync } from "node:fs";
2
- import { z } from "zod";
3
2
  import { outputPath } from "../storage/layout.js";
4
3
  import { narrationJoinPiecesOfProject, narrationJoinsOfProject } from "./manifest-repo.js";
5
4
  import { currentRevisionId, outputsForRevision, piecesForRevision, revisionById } from "./repo.js";
@@ -7,15 +6,27 @@ export function getRevisionView(deps, projectId, revisionId) {
7
6
  const revision = revisionById(deps.db, projectId, revisionId);
8
7
  if (revision === undefined)
9
8
  return undefined;
9
+ // The project's files are read once and each looked for on disk once: a finished project's
10
+ // version names over a thousand, and asking for them one at a time was most of this view,
11
+ // which every page of the project and every step of a run builds.
12
+ const paths = new Map();
13
+ for (const row of deps.db
14
+ .prepare("SELECT id,path FROM project_assets WHERE project_id=?")
15
+ .all(projectId))
16
+ if (typeof row.id === "string" && typeof row.path === "string")
17
+ paths.set(row.id, row.path);
18
+ const onDisk = new Map();
10
19
  const available = (assetId) => {
11
- const row = deps.db
12
- .prepare("SELECT path FROM project_assets WHERE project_id=? AND id=?")
13
- .get(projectId, assetId);
14
- if (row === undefined)
20
+ const known = onDisk.get(assetId);
21
+ if (known !== undefined)
22
+ return known;
23
+ const path = paths.get(assetId);
24
+ if (path === undefined)
15
25
  throw new Error(`Revision asset ${assetId} is not registered.`);
16
- const path = z.object({ path: z.string() }).parse(row).path;
17
- return (statSync(outputPath(deps.paths, projectId, path), { throwIfNoEntry: false })?.isFile() ===
18
- true);
26
+ const found = statSync(outputPath(deps.paths, projectId, path), { throwIfNoEntry: false })?.isFile() ===
27
+ true;
28
+ onDisk.set(assetId, found);
29
+ return found;
19
30
  };
20
31
  const outputs = outputsForRevision(deps.db, projectId, revisionId).map((row) => ({
21
32
  ...row,
@@ -158,7 +158,8 @@ export function shortCaptionsAss(words, style) {
158
158
  const title = style.title === undefined || style.title.text.trim() === ""
159
159
  ? undefined
160
160
  : { ...titleLayout(style.title.text, style), seconds: style.title.seconds };
161
- const header = `[Script Info]\nScriptType: v4.00+\nPlayResX: ${String(style.width)}\nPlayResY: ${String(style.height)}\nWrapStyle: 2\nScaledBorderAndShadow: yes\n\n[V4+ Styles]\nFormat: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\nStyle: Short,${name},${String(size)},${white},${white},&H00000000,&H80000000,-1,0,0,0,100,100,0,0,1,7,3,5,${String(sideMargin)},${String(sideMargin)},0,1\n${title === undefined ? "" : `Style: Title,${name},${String(title.size)},${white},${white},&H00000000,&H80000000,-1,0,0,0,100,100,0,0,1,6,3,8,${String(sideMargin)},${String(sideMargin)},0,1\n`}\n[Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n`;
161
+ // YCbCr Matrix: without it, ffmpeg 7.1 and later draw the colours as BT.601 on a BT.709 picture.
162
+ const header = `[Script Info]\nScriptType: v4.00+\nPlayResX: ${String(style.width)}\nPlayResY: ${String(style.height)}\nYCbCr Matrix: TV.709\nWrapStyle: 2\nScaledBorderAndShadow: yes\n\n[V4+ Styles]\nFormat: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\nStyle: Short,${name},${String(size)},${white},${white},&H00000000,&H80000000,-1,0,0,0,100,100,0,0,1,7,3,5,${String(sideMargin)},${String(sideMargin)},0,1\n${title === undefined ? "" : `Style: Title,${name},${String(title.size)},${white},${white},&H00000000,&H80000000,-1,0,0,0,100,100,0,0,1,6,3,8,${String(sideMargin)},${String(sideMargin)},0,1\n`}\n[Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n`;
162
163
  const groups = captionGroups(words);
163
164
  // The headline sits on a layer of its own, so a caption never hides it.
164
165
  const events = title === undefined
@@ -0,0 +1,46 @@
1
+ // Which of `ids` occur anywhere in `texts`, exactly as SQL's instr() would find them, without
2
+ // reading every text once per id: asked that way, a finished project's 600 file ids against 4 MB
3
+ // of saved revisions took over a second, on the one thread that answers every page.
4
+ //
5
+ // Ids of one length that begin with the same character are looked for together: every place
6
+ // their shared beginning occurs is read once and looked up. A project's ids are made close
7
+ // together and share most of their beginning, so those places are the ids themselves.
8
+ export function idsNamedIn(ids, texts) {
9
+ const found = new Set();
10
+ const groups = new Map();
11
+ for (const id of new Set(ids)) {
12
+ if (id === "") {
13
+ if (texts.length > 0)
14
+ found.add(id);
15
+ continue;
16
+ }
17
+ const key = `${String(id.length)}:${id.charAt(0)}`;
18
+ const group = groups.get(key);
19
+ if (group === undefined)
20
+ groups.set(key, [id]);
21
+ else
22
+ group.push(id);
23
+ }
24
+ for (const group of groups.values()) {
25
+ const start = sharedStart(group);
26
+ const length = group[0]?.length ?? 0;
27
+ const wanted = new Set(group);
28
+ for (const text of texts)
29
+ for (let at = text.indexOf(start); at !== -1; at = text.indexOf(start, at + 1)) {
30
+ const candidate = text.slice(at, at + length);
31
+ if (wanted.has(candidate))
32
+ found.add(candidate);
33
+ }
34
+ }
35
+ return found;
36
+ }
37
+ function sharedStart(ids) {
38
+ let shared = ids[0] ?? "";
39
+ for (const id of ids) {
40
+ let same = 0;
41
+ while (same < shared.length && shared.charAt(same) === id.charAt(same))
42
+ same += 1;
43
+ shared = shared.slice(0, same);
44
+ }
45
+ return shared;
46
+ }
@@ -6,6 +6,7 @@ import { bundledSampleProjects } from "../onboarding/state.js";
6
6
  import { notTemplateSample } from "../template-studio/repo.js";
7
7
  import { projectSettled } from "./arrange.js";
8
8
  import { backupsFolderName, outputPath, projectDir } from "./layout.js";
9
+ import { idsNamedIn } from "./named-ids.js";
9
10
  import { pieceFile } from "./reconcile.js";
10
11
  // Keep outputs only: a finished project drops the working files it was made from (narration
11
12
  // parts, subtitle timing, render settings) and keeps what gets published, the images the
@@ -42,14 +43,16 @@ export function projectStorage(deps, projectId) {
42
43
  const files = filesOf(deps.paths, projectId);
43
44
  const outputs = outputPaths(deps.db, projectId);
44
45
  const sample = bundledSampleProjects(deps.db).has(projectId);
46
+ // Read once: what may be removed and what History may drop both turn on it.
47
+ const supplied = sample ? new Set() : suppliedPaths(deps.db, projectId);
45
48
  const removable = sample
46
49
  ? new Set()
47
- : removablePaths(deps.db, projectId, keptPaths(deps.db, projectId));
50
+ : removablePaths(deps.db, projectId, new Set([...outputs, ...supplied]));
48
51
  let outputsBytes = 0;
49
52
  let workingBytes = 0;
50
53
  let removableFiles = 0;
51
54
  let removableBytes = 0;
52
- const history = sample ? new Set() : historyPaths(deps, projectId);
55
+ const history = sample ? new Set() : historyPaths(deps, projectId, supplied);
53
56
  let historyFiles = 0;
54
57
  let historyBytes = 0;
55
58
  for (const [path, bytes] of files) {
@@ -79,8 +82,7 @@ export function projectStorage(deps, projectId) {
79
82
  // Delete old versions: the files of older versions that arranging moved to History/, by their
80
83
  // stored paths. Never a file the user supplied, nor one they put in History themselves. Going
81
84
  // back to such a version makes its files again.
82
- function historyPaths(deps, projectId) {
83
- const supplied = suppliedPaths(deps.db, projectId);
85
+ function historyPaths(deps, projectId, supplied = suppliedPaths(deps.db, projectId)) {
84
86
  const out = new Set();
85
87
  for (const [path, place] of placedFiles(deps.paths, projectId))
86
88
  if (place.startsWith("History/") && !supplied.has(path))
@@ -248,14 +250,24 @@ function keptPaths(db, projectId) {
248
250
  }
249
251
  // The files the user supplied: nothing could make them again, so nothing removes them.
250
252
  function suppliedPaths(db, projectId) {
251
- const kept = new Set();
252
- for (const path of pathsOf(db
253
- .prepare(`SELECT a.path FROM project_assets a WHERE a.project_id=? AND (
254
- EXISTS(SELECT 1 FROM project_revisions r WHERE r.project_id=a.project_id
255
- AND (instr(r.content,a.id)>0 OR instr(r.config,a.id)>0))
256
- OR EXISTS(SELECT 1 FROM projects p WHERE p.id=a.project_id AND instr(p.config,a.id)>0))
257
- UNION SELECT path FROM outputs WHERE project_id=? AND original_filename IS NOT NULL`)
258
- .all(projectId, projectId)))
253
+ const kept = pathsOf(db
254
+ .prepare("SELECT path FROM outputs WHERE project_id=? AND original_filename IS NOT NULL")
255
+ .all(projectId));
256
+ const assets = db.prepare("SELECT id,path FROM project_assets WHERE project_id=?").all(projectId);
257
+ const texts = [];
258
+ const carry = (value) => {
259
+ if (typeof value === "string")
260
+ texts.push(value);
261
+ };
262
+ for (const row of db
263
+ .prepare("SELECT content,config FROM project_revisions WHERE project_id=?")
264
+ .all(projectId)) {
265
+ carry(row.content);
266
+ carry(row.config);
267
+ }
268
+ carry(db.prepare("SELECT config FROM projects WHERE id=?").get(projectId)?.config);
269
+ const named = idsNamedIn(assets.flatMap((row) => (typeof row.id === "string" ? [row.id] : [])), texts);
270
+ for (const path of pathsOf(assets.filter((row) => typeof row.id === "string" && named.has(row.id))))
259
271
  kept.add(path);
260
272
  return kept;
261
273
  }
@@ -88,7 +88,8 @@ export function serializeAss(cues, style) {
88
88
  const name = style.fontName.replace(/[\p{Cc},]/gu, " ").trim();
89
89
  const placement = subtitlePlacement(style.position ?? "bottom", style.height);
90
90
  const position = `{\\an${placement.alignment}\\pos(${style.width / 2},${placement.y})}`;
91
- const header = `[Script Info]\nScriptType: v4.00+\nPlayResX: ${style.width}\nPlayResY: ${style.height}\nWrapStyle: 0\nScaledBorderAndShadow: yes\n\n[V4+ Styles]\nFormat: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\nStyle: Default,${name},${style.fontSize},${assColour(style.color, "&H00FFFFFF")},${assColour(style.color, "&H00FFFFFF")},${assColour(style.outlineColor, "&H00101010")},&H80000000,0,0,0,0,100,100,0,0,1,2.5,1,2,60,60,60,1\n\n[Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n`;
91
+ // YCbCr Matrix: without it, ffmpeg 7.1 and later draw the colours as BT.601 on a BT.709 picture.
92
+ const header = `[Script Info]\nScriptType: v4.00+\nPlayResX: ${style.width}\nPlayResY: ${style.height}\nYCbCr Matrix: TV.709\nWrapStyle: 0\nScaledBorderAndShadow: yes\n\n[V4+ Styles]\nFormat: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\nStyle: Default,${name},${style.fontSize},${assColour(style.color, "&H00FFFFFF")},${assColour(style.color, "&H00FFFFFF")},${assColour(style.outlineColor, "&H00101010")},&H80000000,0,0,0,0,100,100,0,0,1,2.5,1,2,60,60,60,1\n\n[Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n`;
92
93
  return (header +
93
94
  cues
94
95
  .map((cue) => `Dialogue: 0,${assStamp(cue.start)},${assStamp(cue.end)},Default,,0,0,0,,${position}${speakerAss(cue, style.speakers)}${assText(cue.text)}\n`)
@@ -21,6 +21,8 @@ color) {
21
21
  "ScriptType: v4.00+",
22
22
  `PlayResX: ${String(width)}`,
23
23
  `PlayResY: ${String(height)}`,
24
+ // Without it, ffmpeg 7.1 and later draw the colours as BT.601 on a BT.709 picture.
25
+ "YCbCr Matrix: TV.709",
24
26
  "WrapStyle: 0",
25
27
  "ScaledBorderAndShadow: yes",
26
28
  "",
@@ -1,11 +1,12 @@
1
1
  import { createHash } from "node:crypto";
2
- import { constants, copyFileSync, linkSync, mkdirSync, readdirSync, renameSync, rmSync, statfsSync, statSync, utimesSync, } from "node:fs";
2
+ import { constants, copyFileSync, linkSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statfsSync, statSync, utimesSync, } from "node:fs";
3
3
  import { dirname, join } from "node:path";
4
4
  // The clips of a project's last render, kept so the next render encodes only the clips that
5
5
  // changed. A clip is named by what went into its ffmpeg run: the binary, the arguments with
6
- // its own output left out, every input file as it is on disk, and its chapter-card script and
7
- // font. Any change to those is another name, so a clip is never reused for a picture it
8
- // would not have drawn.
6
+ // its own output left out, every input file as it is on disk, its chapter-card script and
7
+ // font, and, for a clip that draws its own captions, their script, fonts and portraits. Any
8
+ // change to those is another name, so a clip is never reused for a picture it would not have
9
+ // drawn.
9
10
  //
10
11
  // The folder is one per project under a hidden folder of Projects, the same disk as the
11
12
  // render's working folder so a clip is linked, not copied; storage reconcile and backups
@@ -18,13 +19,15 @@ const mostBytes = 30 * 1024 ** 3;
18
19
  // floor: the free space a disk keeps before the caches give way; a tenth of a small disk.
19
20
  const leastFree = 20 * 1024 ** 3;
20
21
  const leastFreeShare = 0.1;
21
- export function cacheKey(bin, args, output, extra = []) {
22
+ export function cacheKey(bin, args, output, extra = [],
23
+ // What stands in the key for an argument that is a file written anew for every render.
24
+ stand = new Map()) {
22
25
  const inputs = [];
23
26
  args.forEach((value, at) => {
24
27
  if (args[at - 1] === "-i")
25
- inputs.push(fileIdentity(value));
28
+ inputs.push(stand.get(value) ?? fileIdentity(value));
26
29
  });
27
- const named = args.map((value) => (value === output ? outputMark : value));
30
+ const named = args.map((value) => (value === output ? outputMark : (stand.get(value) ?? value)));
28
31
  return createHash("sha256")
29
32
  .update(JSON.stringify([version, bin, named, inputs, extra]))
30
33
  .digest("hex");
@@ -35,6 +38,11 @@ export function fileIdentity(path) {
35
38
  const stat = statSync(path, { throwIfNoEntry: false });
36
39
  return stat === undefined ? path : `${path}|${String(stat.size)}|${String(stat.mtimeMs)}`;
37
40
  }
41
+ // A file as a key part by what it holds: for one that a render writes anew each time, whose
42
+ // path and date would never be the same twice.
43
+ export function contentIdentity(path) {
44
+ return createHash("sha256").update(readFileSync(path)).digest("hex");
45
+ }
38
46
  // Puts the cached clip at `target`; false when there is none.
39
47
  export function reuseClip(dir, key, target) {
40
48
  const cached = join(dir, `${key}.mp4`);
@@ -0,0 +1,120 @@
1
+ import { internalError } from "../../kernel/errors.js";
2
+ const eventLine = /^(Dialogue:[^,]*),(\d+):(\d\d):(\d\d)\.(\d\d),(\d+):(\d\d):(\d\d)\.(\d\d),(.*)$/s;
3
+ const fade = /\\fad\((\d+),(\d+)\)/;
4
+ // An event is on the frames at or after its start and before its end, as the renderer shows
5
+ // it; whole numbers throughout, so a start that falls on a frame's own time is on that frame.
6
+ export function readCaptions(ass, fps) {
7
+ const head = [];
8
+ const events = [];
9
+ for (const text of ass.split("\n")) {
10
+ if (!text.startsWith("Dialogue:")) {
11
+ if (events.length === 0)
12
+ head.push(text);
13
+ continue;
14
+ }
15
+ const match = eventLine.exec(text);
16
+ if (match === null)
17
+ throw new Error(internalError("a caption's times could not be read", "Press Make the video again in the project's Video section"));
18
+ const [, before = "", h1, m1, s1, c1, h2, m2, s2, c2, after = ""] = match;
19
+ const start = hundredths(h1, m1, s1, c1);
20
+ const end = hundredths(h2, m2, s2, c2);
21
+ events.push({
22
+ from: Math.ceil((start * fps) / 100),
23
+ to: Math.ceil((end * fps) / 100),
24
+ startMs: start * 10,
25
+ endMs: end * 10,
26
+ before,
27
+ after,
28
+ });
29
+ }
30
+ return { head: head.join("\n"), events };
31
+ }
32
+ // The script of the clip that plays `count` frames from frame `start` of the video, its
33
+ // events timed from the clip's own first frame. Two clips that show the same get the same
34
+ // script, so it also tells clips apart (`ffmpeg.ts`, `clip-cache.ts`).
35
+ export function clipCaptions(captions, start, count, fps) {
36
+ const lines = captions.events.flatMap((event) => {
37
+ const from = Math.max(0, event.from - start);
38
+ const to = Math.min(count, event.to - start);
39
+ if (to <= from)
40
+ return [];
41
+ const begins = between(from, fps);
42
+ const after = carried(event, (start * 1000) / fps + begins * 10);
43
+ return [`${event.before},${stamp(begins)},${stamp(between(to, fps))},${after}`];
44
+ });
45
+ return `${[captions.head, ...lines].join("\n")}\n`;
46
+ }
47
+ // A time between frame `frame` and the one before it, in hundredths of a second: a time that
48
+ // fell on a frame's own would be on one side of it or the other by the renderer's rounding.
49
+ // floor: a frame lasts more than the hundredth a script can tell apart, so under 100 a second.
50
+ function between(frame, fps) {
51
+ return frame <= 0 ? 0 : Math.round(((frame - 0.5) * 100) / fps);
52
+ }
53
+ // An event's fade, timed from where the clip's part of it begins: `beginsMs` on the video. A
54
+ // fade in and out are timed from the event's own start and end, so a part given the event's
55
+ // `\fad` would fade out at every cut and in again after it. `\fade` says the same as times
56
+ // from the part's start, and where the part begins inside a fade it carries on from there.
57
+ function carried(event, beginsMs) {
58
+ const match = fade.exec(event.after);
59
+ if (match === null)
60
+ return event.after;
61
+ const fadeIn = Number(match[1]);
62
+ const fadeOut = Number(match[2]);
63
+ const length = event.endMs - event.startMs;
64
+ // The part begins this long after the event (or, under half a frame, before it).
65
+ const offset = Math.round(beginsMs - event.startMs);
66
+ const into = Math.max(0, offset);
67
+ const lead = Math.max(0, -offset);
68
+ const leaves = length - fadeOut;
69
+ const whole = (value) => String(Math.max(0, Math.round(value)));
70
+ const tag = into >= leaves && fadeOut > 0
71
+ ? // Already fading out: one ramp from where it stands.
72
+ `\\fade(${whole((255 * (into - leaves)) / fadeOut)},255,255,0,${whole(length - into)},${whole(length - into)},${whole(length - into)})`
73
+ : `\\fade(${whole(fadeIn > 0 ? 255 * (1 - into / fadeIn) : 0)},0,255,${whole(lead)},${whole(lead + fadeIn - into)},${whole(leaves - offset)},${whole(length - offset)})`;
74
+ return event.after.replace(fade, () => tag);
75
+ }
76
+ function hundredths(hours, minutes, seconds, rest) {
77
+ return ((Number(hours) * 60 + Number(minutes)) * 60 + Number(seconds)) * 100 + Number(rest);
78
+ }
79
+ function stamp(cs) {
80
+ const two = (value) => String(value).padStart(2, "0");
81
+ return `${String(Math.floor(cs / 360_000))}:${two(Math.floor(cs / 6000) % 60)}:${two(Math.floor(cs / 100) % 60)}.${two(cs % 100)}`;
82
+ }
83
+ // measured on 32 threads, all of them busy, on the first 24 shots of a real project
84
+ // (changelog.d/2026-11-13-one-encode.md), in thread-milliseconds a frame: sampled from its
85
+ // still, captioned and encoded, 125; sampled and encoded to be decoded again, 130; decoded,
86
+ // captioned and encoded, 82. Clips that draw their own captions cost the first for every
87
+ // frame of the video; captions over the joined clips cost the second for each distinct clip
88
+ // and the third for every frame. The first is the less when the distinct clips are more than
89
+ // a third of the video (43 in 130): a still shown once, not twelve that come round for hours.
90
+ const leastDistinctShare = 1 / 3;
91
+ export function drawsOwnCaptions(clips, order) {
92
+ const framesOf = new Map(clips.map((clip) => [clip.name, clip.frames]));
93
+ const video = order.reduce((sum, name) => sum + (framesOf.get(name) ?? 0), 0);
94
+ const distinct = clips.reduce((sum, clip) => sum + clip.frames, 0);
95
+ return video > 0 && distinct >= video * leastDistinctShare;
96
+ }
97
+ // The clips of a video whose clips draw their own captions, and the timeline's order of them:
98
+ // one for each distinct picture and what it says while it plays.
99
+ export function captionedClips(clips, order, captions, fps) {
100
+ const pictures = new Map(clips.map((clip) => [clip.name, clip]));
101
+ const made = [];
102
+ const named = new Map();
103
+ let start = 0;
104
+ const played = order.map((picture) => {
105
+ const clip = pictures.get(picture);
106
+ if (clip === undefined)
107
+ throw new Error(internalError("the video's edit list lost a clip", "Press Make the video again in the project's Video section"));
108
+ const said = clipCaptions(captions, start, clip.frames, fps);
109
+ start += clip.frames;
110
+ const key = `${picture}\u0000${said}`;
111
+ let name = named.get(key);
112
+ if (name === undefined) {
113
+ name = `f${String(made.length + 1)}.mp4`;
114
+ named.set(key, name);
115
+ made.push({ name, clip, said });
116
+ }
117
+ return name;
118
+ });
119
+ return { clips: made, order: played };
120
+ }
@@ -0,0 +1,22 @@
1
+ // Every picture Slopify encodes is BT.709 at limited range, and says so: players and YouTube
2
+ // read an untagged HD stream as BT.709, while ffmpeg's own RGB to YUV conversion defaults to
3
+ // BT.601, which shifted every still's colours.
4
+ // The `scale` options that convert RGB to BT.709 YUV at limited range. ffmpeg 7.0 (the bundled
5
+ // one) does not carry colour properties between filters, so the conversion is asked for where
6
+ // it happens rather than left to the encoder's settings.
7
+ export const bt709Scale = "out_color_matrix=bt709:out_range=tv";
8
+ // The frames' own tags, set as they reach the encoder: ffmpeg 7.1 and later take the stream's
9
+ // primaries and transfer from the frames and ignore the encoder options for them. Tags only,
10
+ // no conversion.
11
+ export const bt709Frames = "setparams=colorspace=bt709:color_primaries=bt709:color_trc=bt709:range=tv";
12
+ // The encoder's stream tags.
13
+ export const bt709Tags = [
14
+ "-colorspace",
15
+ "bt709",
16
+ "-color_primaries",
17
+ "bt709",
18
+ "-color_trc",
19
+ "bt709",
20
+ "-color_range",
21
+ "tv",
22
+ ];
@@ -1,5 +1,6 @@
1
1
  import { constants, setPriority } from "node:os";
2
2
  import { errorText } from "../../kernel/errors.js";
3
+ import { bt709Tags } from "./colour.js";
3
4
  import { lookEncoding } from "./look.js";
4
5
  // Settings → Production defaults → Rendering: how this computer encodes a video's picture.
5
6
  // They change how a video is made, never what it is, so no recipe fingerprint carries them and
@@ -23,8 +24,15 @@ const intermediateCrf = "16";
23
24
  // size CRF 23 does, where NVENC scores about 2.5 VMAF below x264 (no NVENC setting tried closed
24
25
  // that gap at that size).
25
26
  export const nvencQuality = { intermediate: 20, final: 28.5 };
27
+ // measured on the first 24 shots of a real project, each still shown once (11.5 minutes, 32
28
+ // threads, changelog.d/2026-11-13-one-encode.md): clips that draw their own captions took
29
+ // 83 s at x264's default preset and 69 s at `faster`, for 1.2 VMAF less. That is the step
30
+ // Fast already was for clips encoded twice (118 s against 145 s, 0.7 VMAF less). `veryfast`
31
+ // cost 4.3 VMAF.
32
+ const captionedFastPreset = "faster";
26
33
  // `final` is a picture someone watches (a clip joined by copying, a burned-in part, the join);
27
- // `intermediate` is a clip decoded again under burned-in captions.
34
+ // `intermediate` is a clip decoded again under burned-in captions; `captioned` is a clip that
35
+ // draws its own captions, watched as it is.
28
36
  export function codecArgs(encode, role, look) {
29
37
  if (encode.kind === "nvenc")
30
38
  return [
@@ -39,7 +47,7 @@ export function codecArgs(encode, role, look) {
39
47
  "-rc",
40
48
  "vbr",
41
49
  "-cq",
42
- String(nvencQuality[role]),
50
+ String(nvencQuality[role === "intermediate" ? "intermediate" : "final"]),
43
51
  "-b:v",
44
52
  "0",
45
53
  // x264's own keyframe interval, so a clip opens on its one keyframe as x264's do and the
@@ -48,16 +56,21 @@ export function codecArgs(encode, role, look) {
48
56
  "250",
49
57
  "-pix_fmt",
50
58
  "yuv420p",
59
+ ...bt709Tags,
51
60
  ];
61
+ const fast = encode.clipSpeed === "fast";
52
62
  return [
53
63
  "-c:v",
54
64
  "libx264",
55
65
  "-pix_fmt",
56
66
  "yuv420p",
67
+ ...bt709Tags,
57
68
  ...lookEncoding(look),
58
69
  ...(role === "intermediate"
59
- ? [...(encode.clipSpeed === "fast" ? ["-preset", "veryfast"] : []), "-crf", intermediateCrf]
60
- : []),
70
+ ? [...(fast ? ["-preset", "veryfast"] : []), "-crf", intermediateCrf]
71
+ : role === "captioned" && fast
72
+ ? ["-preset", captionedFastPreset]
73
+ : []),
61
74
  ];
62
75
  }
63
76
  // Said to a person who may have no NVIDIA card at all: stock ffmpeg builds list the NVIDIA
@@ -88,7 +101,7 @@ const testArgs = [
88
101
  "-",
89
102
  ];
90
103
  // The filters a render runs in the NVENC ffmpeg besides the encoder.
91
- const neededFilters = ["zoompan", "xfade", "ass"];
104
+ const neededFilters = ["zoompan", "perspective", "fillborders", "xfade", "ass"];
92
105
  // Which ffmpeg can encode on an NVIDIA card, asked once and remembered until Slopify restarts.
93
106
  // The bundled ffmpeg first, then the computer's own: unlike everything else, NVENC is the
94
107
  // computer's (its driver and its ffmpeg), and only used when chosen in Settings.