@gentbajko/slopify 4.5.2 → 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 (41) hide show
  1. package/dist/extension/slopify-studio-chrome.zip +0 -0
  2. package/dist/extension/slopify-studio-firefox.zip +0 -0
  3. package/dist/kernel/db/migrations/0079-plan-history-indexes.sql +11 -0
  4. package/dist/kernel/db/migrations/0080-attempts-work-index.sql +4 -0
  5. package/dist/kernel/runner/providers.js +1 -1
  6. package/dist/kernel/runner/queue.js +31 -5
  7. package/dist/kernel/runner/work.js +52 -1
  8. package/dist/main.js +1 -1
  9. package/dist/patch-notes/4.5.3.md +16 -0
  10. package/dist/patch-notes/index.json +6 -0
  11. package/dist/slices/loudness/level-pieces.js +12 -8
  12. package/dist/slices/loudness/sentence-level.js +35 -24
  13. package/dist/slices/narration/breaths-worker.js +126 -0
  14. package/dist/slices/narration/breaths.js +19 -81
  15. package/dist/slices/narration/clean-pieces.js +9 -10
  16. package/dist/slices/narration/pauses.js +18 -17
  17. package/dist/slices/narration/piece-jobs.js +54 -0
  18. package/dist/slices/narration/pronunciation.js +48 -3
  19. package/dist/slices/rebuild/admission-repo.js +14 -1
  20. package/dist/slices/rebuild/narration-history.js +72 -23
  21. package/dist/slices/rebuild/narration-reuse.js +16 -5
  22. package/dist/slices/rebuild/provided-review.js +14 -4
  23. package/dist/slices/rebuild/recipe-document.js +23 -17
  24. package/dist/slices/rebuild/recipe-exports.js +8 -1
  25. package/dist/slices/rebuild/recipe-model.js +48 -4
  26. package/dist/slices/rebuild/recipe-preparation.js +28 -6
  27. package/dist/slices/rebuild/recipe-reviews.js +28 -24
  28. package/dist/slices/rebuild/recovery.js +35 -2
  29. package/dist/slices/rebuild/review-redo.js +15 -7
  30. package/dist/slices/rebuild/runtime-admission.js +5 -0
  31. package/dist/slices/rebuild/runtime-agent-review.js +4 -2
  32. package/dist/slices/rebuild/runtime-materialize.js +14 -0
  33. package/dist/slices/rebuild/runtime-plan.js +86 -40
  34. package/dist/slices/rebuild/runtime-review.js +3 -2
  35. package/dist/slices/rebuild/transition-repo.js +13 -10
  36. package/dist/slices/reviews/outcome.js +5 -3
  37. package/dist/slices/reviews/repo.js +12 -0
  38. package/dist/slices/revisions/view.js +3 -3
  39. package/dist/slices/settings/model.js +6 -2
  40. package/dist/slices/storage/layout.js +15 -0
  41. package/package.json +1 -1
@@ -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,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,10 @@
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
+ },
2
8
  {
3
9
  "id": "4.5.2",
4
10
  "title": "Slopify 4.5.2",
@@ -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
+ }
@@ -1,52 +1,48 @@
1
1
  import { mkdirSync, rmSync } from "node:fs";
2
- import { open, stat } from "node:fs/promises";
3
2
  import { join } from "node:path";
4
3
  import { errorText } from "../../kernel/errors.js";
5
4
  import { editSettings } from "../../kernel/ports/settings-places.js";
6
5
  import { runFfmpeg } from "../video/ffmpeg.js";
7
- import { breathRate, scanBreaths, softenChunk } from "./breaths-detect.js";
6
+ import { breathRate } from "./breaths-detect.js";
7
+ import { pcmWavHeader, softenPcmInWorker } from "./breaths-worker.js";
8
+ import { mapPieces } from "./piece-jobs.js";
8
9
  // Soften breaths, made in the join (`breaths-model.ts` says why there). Each narration piece is
9
10
  // decoded by ffmpeg to 16-bit mono PCM at 48 kHz in a file beside it, read once to find its
10
11
  // breaths (`breaths-detect.ts`) and once more to write it again as a WAV with them turned down. Both
11
- // reads go in chunks, so a long piece never sits in memory whole, and the detector yields to
12
- // the event loop as it goes, so the server stays responsive while it works. A piece without a
12
+ // reads go in chunks of a second, so a long piece never sits in memory whole, and both run in a
13
+ // worker thread (`breaths-worker.ts`), so the server stays responsive while it works and
14
+ // several pieces are worked on at once. A piece without a
13
15
  // breath is written again all the same: the join takes every piece in the one format.
14
- // ceiling: one second of audio per read.
15
- const chunkSamples = breathRate;
16
16
  export async function softenBreaths(run, files, directory) {
17
17
  mkdirSync(directory, { recursive: true, mode: 0o700 });
18
- const written = [];
19
- let softened = 0;
20
- let skipped = 0;
21
- for (const [index, file] of files.entries()) {
22
- run.signal.throwIfAborted();
18
+ // Several pieces at once (`piece-jobs.ts`); the counts are added up after, in order.
19
+ const pieces = await mapPieces(run, files, async (file, index, own) => {
23
20
  const name = `breaths-${String(index + 1).padStart(4, "0")}`;
24
21
  const raw = join(directory, `${name}.pcm`);
25
22
  const output = join(directory, `${name}.wav`);
26
23
  try {
27
24
  await runFfmpeg({
28
- bin: run.bin,
25
+ bin: own.bin,
29
26
  args: decodeArgs(file, raw),
30
- signal: run.signal,
31
- log: run.log,
27
+ signal: own.signal,
28
+ log: own.log,
32
29
  onProgress: () => { },
33
30
  });
34
- const scan = await scanBreaths(pcmChunks(raw));
35
- run.signal.throwIfAborted();
36
- await writeSoftened(raw, output, scan.stretches);
37
- softened += scan.stretches.length;
38
- skipped += scan.skipped.length;
31
+ const counts = await softenPcmInWorker({ raw, output }, own.signal);
32
+ return { output, ...counts };
39
33
  }
40
34
  catch (error) {
41
- if (run.signal.aborted)
35
+ if (own.signal.aborted)
42
36
  throw error;
43
37
  throw new Error(`Soften breaths could not process narration piece ${String(index + 1)} (${errorText(error)}), so the narration can't be joined together. Use Try again; if it fails again, turn off Soften breaths in ${editSettings.sound} and use Save changes, then use Download diagnostics in Settings and report it.`, { cause: error });
44
38
  }
45
39
  finally {
46
40
  rmSync(raw, { force: true });
47
41
  }
48
- written.push(output);
49
- }
42
+ });
43
+ const written = pieces.map((one) => one.output);
44
+ const softened = pieces.reduce((sum, one) => sum + one.softened, 0);
45
+ const skipped = pieces.reduce((sum, one) => sum + one.skipped, 0);
50
46
  return { files: written, softened, skipped };
51
47
  }
52
48
  export function decodeArgs(input, output) {
@@ -72,65 +68,7 @@ export function decodeArgs(input, output) {
72
68
  output,
73
69
  ];
74
70
  }
75
- async function* pcmChunks(path) {
76
- const handle = await open(path, "r");
77
- try {
78
- for (;;) {
79
- const chunk = await readChunk(handle);
80
- if (chunk === undefined)
81
- return;
82
- yield chunk;
83
- }
84
- }
85
- finally {
86
- await handle.close();
87
- }
88
- }
89
- async function readChunk(handle) {
90
- const buffer = Buffer.alloc(chunkSamples * 2);
91
- const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);
92
- const samples = Math.floor(bytesRead / 2);
93
- if (samples === 0)
94
- return undefined;
95
- // A copy into its own buffer: Int16Array needs an aligned, even-length view.
96
- const out = new Int16Array(samples);
97
- for (let at = 0; at < samples; at += 1)
98
- out[at] = buffer.readInt16LE(at * 2);
99
- return out;
100
- }
101
- async function writeSoftened(raw, output, stretches) {
102
- const size = (await stat(raw)).size;
103
- const bytes = size - (size % 2);
104
- const target = await open(output, "w", 0o600);
105
- try {
106
- await target.write(wavHeader(bytes));
107
- let offset = 0;
108
- for await (const chunk of pcmChunks(raw)) {
109
- const soft = softenChunk(chunk, offset, stretches);
110
- // Typed arrays are little-endian on every platform Slopify ships for, as WAV is.
111
- await target.write(Buffer.from(soft.buffer, soft.byteOffset, soft.byteLength));
112
- offset += chunk.length;
113
- }
114
- }
115
- finally {
116
- await target.close();
117
- }
118
- }
119
71
  // A canonical 44-byte header: PCM, mono, 16-bit, 48 kHz.
120
72
  export function wavHeader(dataBytes) {
121
- const header = Buffer.alloc(44);
122
- header.write("RIFF", 0, "ascii");
123
- header.writeUInt32LE(36 + dataBytes, 4);
124
- header.write("WAVE", 8, "ascii");
125
- header.write("fmt ", 12, "ascii");
126
- header.writeUInt32LE(16, 16);
127
- header.writeUInt16LE(1, 20);
128
- header.writeUInt16LE(1, 22);
129
- header.writeUInt32LE(breathRate, 24);
130
- header.writeUInt32LE(breathRate * 2, 28);
131
- header.writeUInt16LE(2, 32);
132
- header.writeUInt16LE(16, 34);
133
- header.write("data", 36, "ascii");
134
- header.writeUInt32LE(dataBytes, 40);
135
- return header;
73
+ return pcmWavHeader(dataBytes, breathRate);
136
74
  }