@gentbajko/slopify 4.5.1 → 4.5.3

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.
Files changed (54) hide show
  1. package/dist/edge/mcp/tools-runs.js +1 -1
  2. package/dist/extension/slopify-studio-chrome.zip +0 -0
  3. package/dist/extension/slopify-studio-firefox.zip +0 -0
  4. package/dist/kernel/db/migrations/0079-plan-history-indexes.sql +11 -0
  5. package/dist/kernel/db/migrations/0080-attempts-work-index.sql +4 -0
  6. package/dist/kernel/runner/providers.js +1 -1
  7. package/dist/kernel/runner/queue.js +31 -5
  8. package/dist/kernel/runner/work.js +52 -1
  9. package/dist/main.js +1 -1
  10. package/dist/patch-notes/4.5.2.md +17 -0
  11. package/dist/patch-notes/4.5.3.md +16 -0
  12. package/dist/patch-notes/index.json +12 -0
  13. package/dist/slices/article/production-note.js +75 -0
  14. package/dist/slices/loudness/level-pieces.js +12 -8
  15. package/dist/slices/loudness/sentence-level.js +35 -24
  16. package/dist/slices/narration/breaths-worker.js +126 -0
  17. package/dist/slices/narration/breaths.js +19 -81
  18. package/dist/slices/narration/clean-pieces.js +9 -10
  19. package/dist/slices/narration/pauses.js +18 -17
  20. package/dist/slices/narration/piece-jobs.js +54 -0
  21. package/dist/slices/narration/pronunciation.js +48 -3
  22. package/dist/slices/rebuild/admission-repo.js +14 -1
  23. package/dist/slices/rebuild/narration-history.js +72 -23
  24. package/dist/slices/rebuild/narration-reuse.js +16 -5
  25. package/dist/slices/rebuild/provided-review.js +14 -4
  26. package/dist/slices/rebuild/recipe-audio.js +6 -0
  27. package/dist/slices/rebuild/recipe-build.js +6 -2
  28. package/dist/slices/rebuild/recipe-document.js +23 -17
  29. package/dist/slices/rebuild/recipe-exports.js +8 -1
  30. package/dist/slices/rebuild/recipe-model.js +48 -4
  31. package/dist/slices/rebuild/recipe-preparation.js +28 -6
  32. package/dist/slices/rebuild/recipe-reviews.js +28 -24
  33. package/dist/slices/rebuild/recipe-save.js +16 -3
  34. package/dist/slices/rebuild/recipe-shorts.js +195 -8
  35. package/dist/slices/rebuild/recovery.js +35 -2
  36. package/dist/slices/rebuild/review-redo.js +15 -7
  37. package/dist/slices/rebuild/runtime-admission.js +5 -0
  38. package/dist/slices/rebuild/runtime-agent-review.js +4 -2
  39. package/dist/slices/rebuild/runtime-materialize.js +14 -0
  40. package/dist/slices/rebuild/runtime-plan.js +86 -40
  41. package/dist/slices/rebuild/runtime-provider.js +11 -4
  42. package/dist/slices/rebuild/runtime-review.js +3 -2
  43. package/dist/slices/rebuild/runtime-shorts.js +53 -13
  44. package/dist/slices/rebuild/transition-repo.js +13 -10
  45. package/dist/slices/reviews/outcome.js +5 -3
  46. package/dist/slices/reviews/repo.js +12 -0
  47. package/dist/slices/revisions/schema.js +1 -0
  48. package/dist/slices/revisions/view.js +3 -3
  49. package/dist/slices/settings/model.js +6 -2
  50. package/dist/slices/shorts/keep.js +37 -17
  51. package/dist/slices/storage/layout.js +15 -0
  52. package/dist/web/assets/{index-C0n0zeuZ.js → index-C8aMp7m3.js} +2 -2
  53. package/dist/web/index.html +1 -1
  54. package/package.json +1 -1
@@ -79,7 +79,7 @@ const revisions = [
79
79
  route: "POST /api/projects/:id/revisions",
80
80
  body: saveBody,
81
81
  title: "Save an edit",
82
- description: "Saves an edit as a new version, like Save in Edit settings; it starts nothing. Body: {baseRevisionId, idempotencyKey: a new UUID, edit: {config, content, regenerate?: [work keys to make again, such as a narration chunk key], uploads?: [{stagedFileId, destination}]}}; send get_revision's revision.config and revision.content with your change. One chunk's wording or delivery note is content.narrationOverrides[chunk key] = {kind: \"text\", text, direction?}. Finished shorts kept through a new pick are content.shortsKeep: leave one out to pick a new moment for it, and lower config.shorts.count as well to drop it. Then preview_rebuild (Choose what to make again) says what it makes and costs, and start_rebuild starts it.",
82
+ description: "Saves an edit as a new version, like Save in Edit settings; it starts nothing. Body: {baseRevisionId, idempotencyKey: a new UUID, edit: {config, content, regenerate?: [work keys to make again, such as a narration chunk key], uploads?: [{stagedFileId, destination}]}}; send get_revision's revision.config and revision.content with your change. One chunk's wording or delivery note is content.narrationOverrides[chunk key] = {kind: \"text\", text, direction?}. Finished shorts kept through a new pick are content.shortsKeep: leave one out to pick a new moment for it, and lower config.shorts.count as well to drop it. Leave content.shortsKeep as get_revision sent it unless the save picks the moments again: a new intro, outro or description never does, and a list sent with such an edit is ignored. Then preview_rebuild (Choose what to make again) says what it makes and costs, and start_rebuild starts it.",
83
83
  },
84
84
  {
85
85
  name: "restore_revision",
@@ -0,0 +1,11 @@
1
+ -- What every plan derivation reads across all of a project's versions: its narration history
2
+ -- (`slices/rebuild/narration-history.ts`) and its narration joins (`slices/revisions/
3
+ -- manifest-repo.ts`). The tables were indexed by version only, so each read scanned every
4
+ -- saved piece and output of every project, gigabytes on a long-running install, after every
5
+ -- finished step of a run. Indexes only: no row changes.
6
+ CREATE INDEX IF NOT EXISTS revision_pieces_project_stage
7
+ ON revision_pieces(project_id, stage_kind, created_at, id);
8
+ CREATE INDEX IF NOT EXISTS revision_pieces_project_key
9
+ ON revision_pieces(project_id, piece_key);
10
+ CREATE INDEX IF NOT EXISTS revision_outputs_project_work
11
+ ON revision_outputs(project_id, work_key);
@@ -0,0 +1,4 @@
1
+ -- A step's attempts, looked up by the step: a save asks whether each earlier step was ever
2
+ -- attempted (`slices/rebuild/transition-repo.ts`), and so do admission and recovery. The table
3
+ -- had no index on it, so every such question read every attempt ever made. Index only.
4
+ CREATE INDEX IF NOT EXISTS attempts_work ON attempts(work_id);
@@ -19,7 +19,7 @@ export function stageProviders(deps, context, pieceId) {
19
19
  ...(pieceId === undefined ? {} : { pieceId }),
20
20
  signal: context.signal,
21
21
  };
22
- const queued = (provider, work) => deps.queue ? deps.queue.run(provider, context.signal, work) : work();
22
+ const queued = (provider, work) => deps.queue ? deps.queue.run(provider, context.signal, work, context.stage.projectId) : work();
23
23
  const waiter = { projectId: context.stage.projectId, stage: context.stage.kind };
24
24
  // A CLI whose plan allowance is used up is waited for here, outside the queue, so the wait
25
25
  // holds no provider slot; the call is then made afresh with a full set of attempts.
@@ -1,13 +1,32 @@
1
- // One app-wide queue: no more than five calls, with lower provider limits.
1
+ // One app-wide queue: no more than twelve calls, each provider up to its own limit (eight at
2
+ // most). The cap was five, so Codex drawing four or five pictures at once left one slot or none
3
+ // for narration and the picture checks, which then waited for hours.
2
4
  // Waiting does not start an attempt or its idle timer. FIFO among eligible calls.
5
+ const totalLimit = 12;
6
+ const providerLimit = 8;
3
7
  export function createProviderQueue(limitFor) {
4
8
  const active = new Map();
9
+ const owned = new Map();
10
+ const ownerKey = (w) => `${w.provider}\u0000${w.owner}`;
5
11
  const waiting = [];
6
12
  let total = 0;
7
13
  function drain() {
8
- while (total < 5) {
9
- const at = waiting.findIndex((w) => (active.get(w.provider) ?? 0) <
10
- Math.max(1, Math.min(5, Math.floor(limitFor(w.provider)) || 1)));
14
+ while (total < totalLimit) {
15
+ // Among the calls whose provider has room, the owner with fewest running goes first;
16
+ // ties keep the order they came in.
17
+ let at = -1;
18
+ let fewest = Number.POSITIVE_INFINITY;
19
+ for (const [index, w] of waiting.entries()) {
20
+ const room = (active.get(w.provider) ?? 0) <
21
+ Math.max(1, Math.min(providerLimit, Math.floor(limitFor(w.provider)) || 1));
22
+ if (!room)
23
+ continue;
24
+ const running = owned.get(ownerKey(w)) ?? 0;
25
+ if (running < fewest) {
26
+ fewest = running;
27
+ at = index;
28
+ }
29
+ }
11
30
  if (at < 0)
12
31
  return;
13
32
  const next = waiting.splice(at, 1)[0];
@@ -20,16 +39,18 @@ export function createProviderQueue(limitFor) {
20
39
  }
21
40
  total++;
22
41
  active.set(next.provider, (active.get(next.provider) ?? 0) + 1);
42
+ owned.set(ownerKey(next), (owned.get(ownerKey(next)) ?? 0) + 1);
23
43
  next.start();
24
44
  }
25
45
  }
26
46
  return {
27
- run: (provider, signal, work) => {
47
+ run: (provider, signal, work, owner = "") => {
28
48
  if (signal.aborted)
29
49
  return Promise.reject(signal.reason);
30
50
  return new Promise((resolve, reject) => {
31
51
  const waiter = {
32
52
  provider,
53
+ owner,
33
54
  signal,
34
55
  cancel: () => {
35
56
  const at = waiting.indexOf(waiter);
@@ -47,6 +68,11 @@ export function createProviderQueue(limitFor) {
47
68
  .then(resolve, reject)
48
69
  .finally(() => {
49
70
  total--;
71
+ const mine = (owned.get(ownerKey(waiter)) ?? 1) - 1;
72
+ if (mine)
73
+ owned.set(ownerKey(waiter), mine);
74
+ else
75
+ owned.delete(ownerKey(waiter));
50
76
  const left = (active.get(provider) ?? 1) - 1;
51
77
  if (left)
52
78
  active.set(provider, left);
@@ -1,9 +1,60 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { z } from "zod";
3
+ // Made once: building a schema for every number fingerprinted was a good share of planning.
4
+ const finiteNumber = z.number().finite();
5
+ // The fingerprint of a value as JSON would write it: the same answer as
6
+ // `fingerprint(JSON.parse(JSON.stringify(value)))` with every number checked finite, in one
7
+ // pass. Planning fingerprints every recipe's whole input (prompts with the article in them) on
8
+ // every derivation; writing it out, reading it back and writing it out again sorted was a large
9
+ // share of the server's time during a run.
10
+ export function fingerprintJson(value) {
11
+ const text = canonicalJson(value);
12
+ if (text === undefined)
13
+ throw new SyntaxError("Nothing to fingerprint");
14
+ return createHash("sha256").update(text).digest("hex");
15
+ }
16
+ function canonicalJson(input) {
17
+ let value = input;
18
+ if (value !== null &&
19
+ typeof value === "object" &&
20
+ typeof value.toJSON === "function")
21
+ value = value.toJSON();
22
+ switch (typeof value) {
23
+ case "number":
24
+ finiteNumber.parse(value);
25
+ return JSON.stringify(value);
26
+ case "string":
27
+ case "boolean":
28
+ return JSON.stringify(value);
29
+ case "bigint":
30
+ // JSON can't write one: throw as it does.
31
+ return JSON.stringify(value);
32
+ case "undefined":
33
+ case "function":
34
+ case "symbol":
35
+ return undefined;
36
+ }
37
+ if (value === null)
38
+ return "null";
39
+ if (Array.isArray(value)) {
40
+ const items = [];
41
+ for (let at = 0; at < value.length; at++)
42
+ items.push(canonicalJson(value[at]) ?? "null");
43
+ return `[${items.join(",")}]`;
44
+ }
45
+ const record = value;
46
+ const parts = [];
47
+ for (const key of Object.keys(record).sort()) {
48
+ const part = canonicalJson(record[key]);
49
+ if (part !== undefined)
50
+ parts.push(`${JSON.stringify(key)}:${part}`);
51
+ }
52
+ return `{${parts.join(",")}}`;
53
+ }
3
54
  export function fingerprint(value) {
4
55
  function canonical(item) {
5
56
  if (typeof item === "number")
6
- z.number().finite().parse(item);
57
+ finiteNumber.parse(item);
7
58
  if (item === null || typeof item !== "object")
8
59
  return JSON.stringify(item);
9
60
  if (Array.isArray(item))
package/dist/main.js CHANGED
@@ -1125,7 +1125,7 @@ renderGate = createRenderGate(() => readSettings({ db, log }).videoRenderConcurr
1125
1125
  changed: (projectId) => hub.emit(projectId, { type: "project.updated", projectId }),
1126
1126
  }),
1127
1127
  queue: createProviderQueue((provider) => isLocalCliProvider(provider)
1128
- ? localCliConcurrency(provider)
1128
+ ? localCliConcurrency(provider, process.env)
1129
1129
  : (catalogue.read().providers[provider]?.maxConcurrent ?? 1)),
1130
1130
  };
1131
1131
  const checkpoints = createCheckpointAuthority({
@@ -0,0 +1,17 @@
1
+ # Slopify 4.5.2
2
+
3
+ Released 18 November 2026.
4
+
5
+ A new intro or outro no longer makes a video's shorts again, and the AI's notes about its own work no longer open an article.
6
+
7
+ ## Shorts stay when the intro or outro changes
8
+
9
+ - **Shorts are now cut on the narration body's own clock.** A new intro or outro (its prompt, text or narration) no longer marks the shorts outdated: their picks, image prompts, pictures and renders stay as they are.
10
+ - **Only a short whose own words changed is picked again.** Rewriting another chapter or voicing another chunk again leaves every other short as it is. A short with a changed word gets a new moment in its own number, instead of the pick stopping with an error.
11
+ - **A short never reaches outside the body:** no intro or silence at its start, and it ends where the body's audio ends.
12
+ - **Existing projects keep their shorts.** The first change that moves the timing picks again once, keeping the finished shorts by their sentences, and only renders them again.
13
+ - **An edit that sends an empty keep list no longer drops every short.** Projects already re-picked before this keep their new shorts; the old ones come back only by restoring the version before that change.
14
+
15
+ ## No production notes in articles
16
+
17
+ - **Short opening paragraphs where the AI talks about its own work** ("I've read all sixteen documents and am now writing…") are now removed from the article before its first heading, and from the first paragraph of an AI-written intro or outro, so they are never narrated.
@@ -0,0 +1,16 @@
1
+ # Slopify 4.5.3
2
+
3
+ Released 21 November 2026.
4
+
5
+ A video is made in a few hours instead of most of a day, the app keeps answering while it works, and a run no longer stops or rewrites its article by itself.
6
+
7
+ ## Faster runs
8
+
9
+ - **Narration and picture checks no longer wait behind the pictures.** Slopify sent at most five calls out at once, across every service. Drawing four or five pictures at a time with Codex left one slot, or none, for the narration and the picture checks, so a video's checks ran one by one for hours and its narration could sit at the start for half an hour. Now up to twelve calls run at once, each service up to its own limit, and the slots of a service are shared between projects: a video's research no longer waits behind another video's 240 picture checks.
10
+ - **The app keeps answering while a video is made.** After every finished step (each picture, each check, each piece of narration) Slopify worked out the whole video's plan again, reading most of its saved history; with a dozen steps finishing together the page and the agent stopped answering for up to half a minute. The plan is now kept until something it is made from changes, and the history it reads is looked up by index (two new database indexes, added on the first start of this version). Turning on Soften breaths or Soften S sounds no longer plans the whole narration four times over.
11
+ - **Joining the narration is about four times faster.** Its pieces are levelled, softened and given their pauses six at a time instead of one after another, and finding the breaths runs beside the app instead of in it. The files made are the same, byte for byte.
12
+ - **A picture that fails its check is drawn again by itself, every time.** The new picture used to wait, held, until someone pressed Try again on the Images step whenever other checks finished at the same moment, or two failed together.
13
+ - **Continue the run after a restart takes the picture checks up again.** They used to stay held for good.
14
+ - **Redrawing a picture no longer checks the article, the opening or the narration again.** Which of the article's files a check looked at changed from one version to the next, so any new version could make the article's check run again, from its first attempt, and a failing article check rewrote the article (and voiced and drew everything after it) up to four more times. A check now looks at the same file each time, finished checks are kept, and an item already flagged after its last attempt is not tried again unless it changed.
15
+ - `SLOPIFY_CODEX_IMAGES_AT_ONCE` (1 to 8) draws more or fewer Codex pictures at once than the four it draws by default.
16
+ - Technical: `kernel/runner/queue.ts` (12 total, 8 per provider, fewest-running owner first); `executionPlan` keyed on its inputs instead of `total_changes()` (`rebuild/runtime-plan.ts`), migrations 0079 (`revision_pieces`/`revision_outputs` project indexes) and 0080 (`attempts(work_id)`); `transitionRevisionWork` in two statements; `narration/piece-jobs.ts` and `narration/breaths-worker.ts`; `selectedAsset` sorts a key's files by slot and `settledRecipe` keeps a review made under an older order (`rebuild/recipe-model.ts`); `nextAttempt` keeps the count for the same file (`reviews/outcome.ts`); automatic redos run one at a time per project and try each waiting redo once per chain (`rebuild/review-redo.ts`).
@@ -1,4 +1,16 @@
1
1
  [
2
+ {
3
+ "id": "4.5.3",
4
+ "title": "Slopify 4.5.3",
5
+ "version": "4.5.3",
6
+ "date": "2026-11-21"
7
+ },
8
+ {
9
+ "id": "4.5.2",
10
+ "title": "Slopify 4.5.2",
11
+ "version": "4.5.2",
12
+ "date": "2026-11-18"
13
+ },
2
14
  {
3
15
  "id": "4.5.1",
4
16
  "title": "Slopify 4.5.1",
@@ -0,0 +1,75 @@
1
+ // A model that works as an agent (the Claude Code provider) sometimes opens its answer with a
2
+ // line about its own work - "I've read all sixteen documents in full and am now writing the
3
+ // narration" - before the text it was asked for. Kept, that line is narrated, and asking for
4
+ // the text again only brings a new one like it. So it goes before the answer is kept.
5
+ //
6
+ // Conservative by design: a paragraph goes only when it is short and plainly about the work -
7
+ // the model saying what it read or is writing, naming the documents, sources, article or
8
+ // narration - or announces the text ("Here is the narration:"). A storyteller who says "I"
9
+ // keeps every word unless the sentence is also about the files. With a heading in the text,
10
+ // the notes before the first heading go; without one, only a first paragraph that is a note.
11
+ // The text is never left empty.
12
+ // ceiling: characters. A note is a sentence or two; a longer paragraph is narration.
13
+ const noteLength = 300;
14
+ // ceiling: paragraphs dropped before the first heading.
15
+ const notesBefore = 4;
16
+ const announcement = /^here(?:'s| is| are)\s+(?:the|your|my)\s+(?:[\w-]+\s+){0,3}?(?:article|narration|script|draft|intro|outro|end matter)\b/i;
17
+ const workStatement = /(?:\bI(?:'ve|'m|'ll|'d)?|\bI (?:have|am|will|had)|\blet me|\bnow|^|[.!?:]\s+)\s*(?:(?:now|just|also|fully|carefully|then|finished|done)\s+)*(?:read|reading|reviewed|reviewing|gone through|went through|been through|going through|looked (?:at|over|through)|studied|checked|drafted|drafting|draft|written|writing|write|compose|composing|produced|producing|prepare|preparing)\b/i;
18
+ const workNoun = /\b(?:documents?|sources?|notes|research|files?|brief|prompt|instructions|narration|article|script|draft|end matter|outline|attachments?|intro|outro)\b/i;
19
+ // A note opens on the model itself ("I", "let me", "now") or on the verb ("Writing the script
20
+ // now."); narration that only goes on to mention a document doesn't.
21
+ const noteOpening = /^\W*(?:okay|ok|alright|sure|great|right|done|i\b|i'|let me|now|writing|drafting|reading|composing)/i;
22
+ const rule = /^\s*(?:-{3,}|\*{3,}|_{3,})\s*$/;
23
+ const headingLine = /^#{1,6}\s/m;
24
+ export function withoutProductionNote(text) {
25
+ const hasHeading = headingLine.test(text);
26
+ let rest = text;
27
+ let dropped = 0;
28
+ for (;;) {
29
+ const block = firstBlock(rest);
30
+ if (block === undefined)
31
+ break;
32
+ if (dropped > 0 && rule.test(block.text)) {
33
+ rest = block.after;
34
+ continue;
35
+ }
36
+ if (!isNote(block.text) || block.after.trim() === "")
37
+ break;
38
+ rest = block.after;
39
+ dropped += 1;
40
+ if (!hasHeading || dropped >= notesBefore)
41
+ break;
42
+ }
43
+ return dropped === 0 ? text : rest;
44
+ }
45
+ function isNote(paragraph) {
46
+ const text = paragraph.replace(/[‘’]/g, "'").replace(/\s+/g, " ").trim();
47
+ if (text === "" || text.length > noteLength || headingLine.test(text))
48
+ return false;
49
+ if (announcement.test(text))
50
+ return true;
51
+ return noteOpening.test(text) && workStatement.test(text) && workNoun.test(text);
52
+ }
53
+ // The first paragraph: its lines up to a blank line or a heading, and the text after it from
54
+ // its next non-blank line.
55
+ function firstBlock(text) {
56
+ const lines = text.replace(/^(?:[ \t]*\r?\n)+/, "").split("\n");
57
+ if (lines.length === 1 && lines[0]?.trim() === "")
58
+ return undefined;
59
+ let end = 1;
60
+ if (!headingLine.test(lines[0] ?? "")) {
61
+ while (end < lines.length) {
62
+ const line = lines[end] ?? "";
63
+ if (line.trim() === "" || headingLine.test(line))
64
+ break;
65
+ end += 1;
66
+ }
67
+ }
68
+ return {
69
+ text: lines.slice(0, end).join("\n"),
70
+ after: lines
71
+ .slice(end)
72
+ .join("\n")
73
+ .replace(/^(?:[ \t]*\r?\n)+/, ""),
74
+ };
75
+ }
@@ -1,5 +1,6 @@
1
1
  import { mkdirSync, rmSync } from "node:fs";
2
2
  import { join } from "node:path";
3
+ import { mapPieces } from "../narration/piece-jobs.js";
3
4
  import { levelFile, measurable } from "./loudnorm.js";
4
5
  import { pieceLufs, pieceTruePeak, spreadOf } from "./model.js";
5
6
  import { lowerLoudPhrases, phrasePasses } from "./phrase-level.js";
@@ -15,12 +16,8 @@ export async function levelPieces(run, files, directory,
15
16
  // Level each sentence takes the place of the phrase step (`sentence-level.ts`).
16
17
  options = { phrases: true }) {
17
18
  mkdirSync(directory, { recursive: true, mode: 0o700 });
18
- const levelled = [];
19
- const before = [];
20
- const after = [];
21
- let skipped = 0;
22
- for (const [index, file] of files.entries()) {
23
- run.signal.throwIfAborted();
19
+ // Each piece on its own, several at once (`narration/piece-jobs.ts`), the report made in order.
20
+ const results = await mapPieces(run, files, async (file, index, own) => {
24
21
  const output = join(directory, `piece-${String(index + 1).padStart(4, "0")}.wav`);
25
22
  // A phrase that bursts out above the narration around it (most of all a request's first
26
23
  // words) comes down first, twice: once loud phrases are lowered, the narration's loud words
@@ -29,14 +26,21 @@ options = { phrases: true }) {
29
26
  const made = [];
30
27
  for (let pass = 1; options.phrases && pass <= phrasePasses; pass++) {
31
28
  const phrased = `${output}.phrases-${String(pass)}.wav`;
32
- if (!(await lowerLoudPhrases(run, source, phrased)))
29
+ if (!(await lowerLoudPhrases(own, source, phrased)))
33
30
  break;
34
31
  made.push(phrased);
35
32
  source = phrased;
36
33
  }
37
- const measured = await levelFile(run, source, output, goal, format);
34
+ const measured = await levelFile(own, source, output, goal, format);
38
35
  for (const one of made)
39
36
  rmSync(one, { force: true });
37
+ return { output, measured };
38
+ });
39
+ const levelled = [];
40
+ const before = [];
41
+ const after = [];
42
+ let skipped = 0;
43
+ for (const { output, measured } of results) {
40
44
  levelled.push(output);
41
45
  if (!measurable(measured.before)) {
42
46
  skipped += 1;
@@ -3,6 +3,7 @@ import { mkdirSync } from "node:fs";
3
3
  import { isAbsolute, join, resolve as resolvePath } from "node:path";
4
4
  import { editSettings } from "../../kernel/ports/settings-places.js";
5
5
  import { measurePiece } from "../narration/pauses.js";
6
+ import { mapPieces } from "../narration/piece-jobs.js";
6
7
  import { runFfmpeg } from "../video/ffmpeg.js";
7
8
  import { sentenceLevel } from "./sentence-level-model.js";
8
9
  import { volumeCommands } from "./volume-commands.js";
@@ -254,13 +255,12 @@ export async function meterFile(run, file) {
254
255
  // were raised and lowered by more than 1 dB.
255
256
  export async function levelSentences(run, files, directory) {
256
257
  mkdirSync(directory, { recursive: true, mode: 0o700 });
257
- const measured = [];
258
- let offset = 0;
259
- for (const file of files) {
260
- run.signal.throwIfAborted();
261
- const { durationSeconds, silences } = await measurePiece(run, file);
258
+ // Measured several pieces at once (`narration/piece-jobs.ts`); each sentence's time on the
259
+ // whole narration is added after, in order, as the gains are found across the joins.
260
+ const pieces = await mapPieces(run, files, async (file, _index, own) => {
261
+ const { durationSeconds, silences } = await measurePiece(own, file);
262
262
  const spans = speechSpans(durationSeconds, silences);
263
- const { power, peaks } = await meterFile(run, file);
263
+ const { power, peaks } = await meterFile(own, file);
264
264
  const readings = spans.map((span) => {
265
265
  let loudest = 0;
266
266
  const a = Math.max(0, Math.floor(span.start * framesPerSecond));
@@ -268,34 +268,45 @@ export async function levelSentences(run, files, directory) {
268
268
  for (let at = a; at < b; at++)
269
269
  loudest = Math.max(loudest, peaks[at] ?? 0);
270
270
  return {
271
- at: offset + (span.start + span.end) / 2,
271
+ middle: (span.start + span.end) / 2,
272
272
  loudness: gatedLoudness(power, span.start, span.end),
273
273
  peakDb: 20 * Math.log10(Math.max(loudest, 1e-9)),
274
274
  };
275
275
  });
276
- measured.push({ spans, readings });
277
- offset += durationSeconds;
276
+ return { durationSeconds, spans, readings };
277
+ });
278
+ const measured = [];
279
+ let offset = 0;
280
+ for (const piece of pieces) {
281
+ measured.push({
282
+ spans: piece.spans,
283
+ readings: piece.readings.map((one) => ({
284
+ at: offset + one.middle,
285
+ loudness: one.loudness,
286
+ peakDb: one.peakDb,
287
+ })),
288
+ });
289
+ offset += piece.durationSeconds;
278
290
  }
279
291
  const gains = sentenceGains(measured.flatMap((one) => one.readings));
280
- const written = [];
292
+ const owned = [];
281
293
  let next = 0;
282
- for (const [index, file] of files.entries()) {
283
- run.signal.throwIfAborted();
284
- const { spans } = measured[index];
285
- const own = gains.slice(next, next + spans.length);
294
+ for (const { spans } of measured) {
295
+ owned.push(gains.slice(next, next + spans.length));
286
296
  next += spans.length;
287
- const changes = gainChanges(spans, own);
288
- if (changes.every((one) => Math.abs(one.gainDb) < changeDb)) {
289
- written.push(file);
290
- continue;
291
- }
297
+ }
298
+ const written = await mapPieces(run, files, async (file, index, own) => {
299
+ const { spans } = measured[index];
300
+ const changes = gainChanges(spans, owned[index] ?? []);
301
+ if (changes.every((one) => Math.abs(one.gainDb) < changeDb))
302
+ return file;
292
303
  const output = join(directory, `sentences-${String(index + 1).padStart(4, "0")}.wav`);
293
304
  const commands = volumeCommands(changes
294
305
  .map((one) => `${one.at.toFixed(3)} volume@sentences volume ${(10 ** (one.gainDb / 20)).toFixed(5)};`)
295
306
  .join("\n"));
296
307
  try {
297
308
  await runFfmpeg({
298
- bin: run.bin,
309
+ bin: own.bin,
299
310
  args: [
300
311
  "-hide_banner",
301
312
  "-nostdin",
@@ -313,16 +324,16 @@ export async function levelSentences(run, files, directory) {
313
324
  "wav",
314
325
  output,
315
326
  ],
316
- signal: run.signal,
317
- log: run.log,
327
+ signal: own.signal,
328
+ log: own.log,
318
329
  onProgress: () => { },
319
330
  });
320
331
  }
321
332
  finally {
322
333
  commands.dispose();
323
334
  }
324
- written.push(output);
325
- }
335
+ return output;
336
+ });
326
337
  return {
327
338
  files: written,
328
339
  raised: gains.filter((gain) => gain > 1).length,
@@ -0,0 +1,126 @@
1
+ import { existsSync } from "node:fs";
2
+ import { open, stat } from "node:fs/promises";
3
+ import { fileURLToPath } from "node:url";
4
+ import { parentPort, Worker, workerData } from "node:worker_threads";
5
+ const marker = "slopify-soften-breaths";
6
+ function sibling(name) {
7
+ const compiled = new URL(`./${name}.js`, import.meta.url);
8
+ return existsSync(fileURLToPath(compiled)) ? compiled : new URL(`./${name}.ts`, import.meta.url);
9
+ }
10
+ // The breaths in `raw` (16-bit mono PCM at 48 kHz) found and turned down, written to `output`
11
+ // as a WAV.
12
+ export async function softenPcm(job) {
13
+ const detect = (await import(sibling("breaths-detect").href));
14
+ const chunkSamples = detect.breathRate;
15
+ const scan = await detect.scanBreaths(pcmChunks(job.raw, chunkSamples));
16
+ const size = (await stat(job.raw)).size;
17
+ const bytes = size - (size % 2);
18
+ const target = await open(job.output, "w", 0o600);
19
+ try {
20
+ await target.write(pcmWavHeader(bytes, detect.breathRate));
21
+ let offset = 0;
22
+ for await (const chunk of pcmChunks(job.raw, chunkSamples)) {
23
+ const soft = detect.softenChunk(chunk, offset, scan.stretches);
24
+ // Typed arrays are little-endian on every platform Slopify ships for, as WAV is.
25
+ await target.write(Buffer.from(soft.buffer, soft.byteOffset, soft.byteLength));
26
+ offset += chunk.length;
27
+ }
28
+ }
29
+ finally {
30
+ await target.close();
31
+ }
32
+ return { softened: scan.stretches.length, skipped: scan.skipped.length };
33
+ }
34
+ // `softenPcm` in a worker; cancelling stops the worker.
35
+ export function softenPcmInWorker(job, signal) {
36
+ signal.throwIfAborted();
37
+ return new Promise((resolve, reject) => {
38
+ const worker = new Worker(sibling("breaths-worker"), {
39
+ workerData: { [marker]: true, ...job },
40
+ });
41
+ let settled = false;
42
+ const settle = (error, counts) => {
43
+ if (settled)
44
+ return;
45
+ settled = true;
46
+ signal.removeEventListener("abort", stop);
47
+ if (error === undefined && counts !== undefined)
48
+ resolve(counts);
49
+ else
50
+ reject(error ?? new Error("the breath worker gave no answer"));
51
+ };
52
+ const stop = () => {
53
+ settle(new Error("Soften breaths was canceled"));
54
+ void worker.terminate();
55
+ };
56
+ signal.addEventListener("abort", stop, { once: true });
57
+ worker.on("message", (message) => {
58
+ if (message.counts !== undefined)
59
+ settle(undefined, message.counts);
60
+ else
61
+ settle(new Error(message.error ?? "the breath worker failed"));
62
+ });
63
+ worker.on("error", (error) => {
64
+ settle(error instanceof Error ? error : new Error(String(error)));
65
+ });
66
+ worker.on("exit", (code) => {
67
+ settle(new Error(`the breath worker stopped (exit code ${String(code)})`));
68
+ });
69
+ });
70
+ }
71
+ async function* pcmChunks(path, chunkSamples) {
72
+ const handle = await open(path, "r");
73
+ try {
74
+ for (;;) {
75
+ const chunk = await readChunk(handle, chunkSamples);
76
+ if (chunk === undefined)
77
+ return;
78
+ yield chunk;
79
+ }
80
+ }
81
+ finally {
82
+ await handle.close();
83
+ }
84
+ }
85
+ async function readChunk(handle, chunkSamples) {
86
+ const buffer = Buffer.alloc(chunkSamples * 2);
87
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);
88
+ const samples = Math.floor(bytesRead / 2);
89
+ if (samples === 0)
90
+ return undefined;
91
+ // A copy into its own buffer: Int16Array needs an aligned, even-length view. PCM is
92
+ // little-endian, as typed arrays are on every platform Slopify ships for.
93
+ const out = new Int16Array(samples);
94
+ new Uint8Array(out.buffer).set(buffer.subarray(0, samples * 2));
95
+ return out;
96
+ }
97
+ // A canonical 44-byte header: PCM, mono, 16-bit, at `rate`.
98
+ export function pcmWavHeader(dataBytes, rate) {
99
+ const header = Buffer.alloc(44);
100
+ header.write("RIFF", 0, "ascii");
101
+ header.writeUInt32LE(36 + dataBytes, 4);
102
+ header.write("WAVE", 8, "ascii");
103
+ header.write("fmt ", 12, "ascii");
104
+ header.writeUInt32LE(16, 16);
105
+ header.writeUInt16LE(1, 20);
106
+ header.writeUInt16LE(1, 22);
107
+ header.writeUInt32LE(rate, 24);
108
+ header.writeUInt32LE(rate * 2, 28);
109
+ header.writeUInt16LE(2, 32);
110
+ header.writeUInt16LE(16, 34);
111
+ header.write("data", 36, "ascii");
112
+ header.writeUInt32LE(dataBytes, 40);
113
+ return header;
114
+ }
115
+ const port = parentPort;
116
+ if (port !== null &&
117
+ typeof workerData === "object" &&
118
+ workerData !== null &&
119
+ workerData[marker] === true) {
120
+ const job = workerData;
121
+ softenPcm({ raw: job.raw, output: job.output }).then((counts) => {
122
+ port.postMessage({ counts });
123
+ }, (error) => {
124
+ port.postMessage({ error: error instanceof Error ? error.message : String(error) });
125
+ });
126
+ }