@bendyline/squisq 1.5.2 → 2.0.1

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 (268) hide show
  1. package/README.md +63 -10
  2. package/dist/{Doc-BBVGq1_9.d.ts → Doc-ylqWKDc_.d.ts} +248 -37
  3. package/dist/{ImageEditDoc-FuyGtt6o.d.ts → ImageEditDoc-D828IXJ1.d.ts} +1 -1
  4. package/dist/annotationCoercion-Dr_DY9Hx.d.ts +86 -0
  5. package/dist/{chunk-T5UK6YOB.js → chunk-2PWOO4ZE.js} +60 -17
  6. package/dist/chunk-2PWOO4ZE.js.map +1 -0
  7. package/dist/{chunk-VWUFZ6ZG.js → chunk-3E5F2XMR.js} +2 -29
  8. package/dist/chunk-3E5F2XMR.js.map +1 -0
  9. package/dist/chunk-4X3JQXNM.js +35 -0
  10. package/dist/chunk-4X3JQXNM.js.map +1 -0
  11. package/dist/{chunk-P3K7NLHF.js → chunk-5DKBFXPY.js} +31 -121
  12. package/dist/chunk-5DKBFXPY.js.map +1 -0
  13. package/dist/{chunk-DLXZMS5K.js → chunk-5J4HKRJF.js} +51 -3
  14. package/dist/chunk-5J4HKRJF.js.map +1 -0
  15. package/dist/chunk-5UYI3RJB.js +2503 -0
  16. package/dist/chunk-5UYI3RJB.js.map +1 -0
  17. package/dist/{chunk-BEQODJWV.js → chunk-66QO7XFB.js} +11 -291
  18. package/dist/chunk-66QO7XFB.js.map +1 -0
  19. package/dist/{chunk-HWVFJAAH.js → chunk-AMIR72JP.js} +28 -10
  20. package/dist/chunk-AMIR72JP.js.map +1 -0
  21. package/dist/chunk-CY2R2VPR.js +884 -0
  22. package/dist/chunk-CY2R2VPR.js.map +1 -0
  23. package/dist/chunk-FVJUUTEM.js +74 -0
  24. package/dist/chunk-FVJUUTEM.js.map +1 -0
  25. package/dist/{chunk-Q3ROPT5H.js → chunk-GZY66SDN.js} +1 -1
  26. package/dist/{chunk-Q3ROPT5H.js.map → chunk-GZY66SDN.js.map} +1 -1
  27. package/dist/chunk-JOQYPRDZ.js +127 -0
  28. package/dist/chunk-JOQYPRDZ.js.map +1 -0
  29. package/dist/{chunk-A4O7GIWE.js → chunk-MMPBOUK7.js} +10 -73
  30. package/dist/chunk-MMPBOUK7.js.map +1 -0
  31. package/dist/{chunk-LDQ2HJIX.js → chunk-PXLVXTLW.js} +252 -54
  32. package/dist/chunk-PXLVXTLW.js.map +1 -0
  33. package/dist/{chunk-TQWLI6S2.js → chunk-Q7LROV2H.js} +4 -2
  34. package/dist/{chunk-TQWLI6S2.js.map → chunk-Q7LROV2H.js.map} +1 -1
  35. package/dist/{chunk-GPLTCSXO.js → chunk-R2GC6RLD.js} +7 -7
  36. package/dist/chunk-R2GC6RLD.js.map +1 -0
  37. package/dist/chunk-R2YZTCLO.js +292 -0
  38. package/dist/chunk-R2YZTCLO.js.map +1 -0
  39. package/dist/chunk-S7A5D7ZJ.js +174 -0
  40. package/dist/chunk-S7A5D7ZJ.js.map +1 -0
  41. package/dist/chunk-TFJVXUHH.js +2358 -0
  42. package/dist/chunk-TFJVXUHH.js.map +1 -0
  43. package/dist/{chunk-LTN6I7QW.js → chunk-TUWMK62B.js} +55 -4
  44. package/dist/chunk-TUWMK62B.js.map +1 -0
  45. package/dist/{chunk-IMSCRLLV.js → chunk-VR7UPJ7C.js} +35 -25
  46. package/dist/chunk-VR7UPJ7C.js.map +1 -0
  47. package/dist/{chunk-KKNUBQ6Y.js → chunk-W4O2TX5I.js} +157 -92
  48. package/dist/chunk-W4O2TX5I.js.map +1 -0
  49. package/dist/{chunk-5TYS5V3G.js → chunk-X6DUONGT.js} +4204 -3560
  50. package/dist/chunk-X6DUONGT.js.map +1 -0
  51. package/dist/doc/index.d.ts +2334 -5
  52. package/dist/doc/index.js +127 -33
  53. package/dist/generate/index.d.ts +7 -2
  54. package/dist/generate/index.js +1 -1
  55. package/dist/imageEdit/index.d.ts +9 -6
  56. package/dist/imageEdit/index.js +3 -3
  57. package/dist/index.d.ts +12 -10
  58. package/dist/index.js +246 -80
  59. package/dist/jsonForm/index.d.ts +7 -3
  60. package/dist/jsonForm/index.js +9 -4
  61. package/dist/markdown/index.d.ts +6 -70
  62. package/dist/markdown/index.js +13 -9
  63. package/dist/narration/index.d.ts +618 -0
  64. package/dist/narration/index.js +82 -0
  65. package/dist/recommend/index.d.ts +15 -1
  66. package/dist/recommend/index.js +2 -2
  67. package/dist/schemas/index.d.ts +28 -6
  68. package/dist/schemas/index.js +15 -13
  69. package/dist/spatial/index.d.ts +0 -1
  70. package/dist/spatial/index.js +1 -1
  71. package/dist/storage/index.js +1 -1
  72. package/dist/{themeLibrary-CehcJhzz.d.ts → themeLibrary-RjVgLpUi.d.ts} +10 -11
  73. package/dist/timing/index.js +5 -3
  74. package/dist/transform/index.d.ts +35 -24
  75. package/dist/transform/index.js +9 -10
  76. package/dist/{types-DlAZ7MW4.d.ts → types-BwMPl2CB.d.ts} +1 -1
  77. package/dist/{types-D98li1gV.d.ts → types-C4kiRn_k.d.ts} +3 -1
  78. package/dist/versions/index.d.ts +2 -1
  79. package/dist/versions/index.js +2 -2
  80. package/package.json +6 -6
  81. package/src/__tests__/applyNarrationTiming.test.ts +190 -0
  82. package/src/__tests__/applyRenderStyle.test.ts +3 -3
  83. package/src/__tests__/asciiDiagramBattle.test.ts +246 -0
  84. package/src/__tests__/asciiDiagramDetect.test.ts +162 -0
  85. package/src/__tests__/asciiDiagramMapping.test.ts +38 -0
  86. package/src/__tests__/asciiDiagramParse.test.ts +233 -0
  87. package/src/__tests__/asciiDiagramPipeline.test.ts +273 -0
  88. package/src/__tests__/asciiDiagramRender.test.ts +162 -0
  89. package/src/__tests__/asciiDiagramRepair.test.ts +84 -0
  90. package/src/__tests__/asciiTimelineDetect.test.ts +157 -0
  91. package/src/__tests__/asciiTimelineParse.test.ts +205 -0
  92. package/src/__tests__/asciiTimelinePipeline.test.ts +349 -0
  93. package/src/__tests__/asciiTimelineRender.test.ts +376 -0
  94. package/src/__tests__/attrTokens.test.ts +5 -0
  95. package/src/__tests__/contentContainer.test.ts +43 -0
  96. package/src/__tests__/customTemplatesFrontmatter.test.ts +0 -15
  97. package/src/__tests__/customThemesFrontmatter.test.ts +1 -0
  98. package/src/__tests__/dataTable.test.ts +25 -15
  99. package/src/__tests__/diagramBlock.test.ts +3 -3
  100. package/src/__tests__/diagramText.test.ts +26 -0
  101. package/src/__tests__/docToMarkdownMedia.test.ts +83 -0
  102. package/src/__tests__/drawingBlock.test.ts +3 -3
  103. package/src/__tests__/fixtures/asciiDiagramBattle.ts +512 -0
  104. package/src/__tests__/fixtures/asciiDiagrams.ts +287 -0
  105. package/src/__tests__/fixtures/asciiTimelines.ts +35 -0
  106. package/src/__tests__/fixtures/treeviewFixtures.ts +243 -0
  107. package/src/__tests__/getLayers.test.ts +32 -18
  108. package/src/__tests__/getLayersFallback.test.ts +8 -8
  109. package/src/__tests__/imageEditVersions.test.ts +2 -0
  110. package/src/__tests__/jsonForm.pointer.test.ts +47 -1
  111. package/src/__tests__/layoutBlock.test.ts +3 -3
  112. package/src/__tests__/majorApiTypes.test.ts +18 -0
  113. package/src/__tests__/markdown.test.ts +54 -4
  114. package/src/__tests__/markdownSanitize.test.ts +7 -5
  115. package/src/__tests__/matchFontFamily.test.ts +114 -0
  116. package/src/__tests__/materializeBlockLayers.test.ts +135 -0
  117. package/src/__tests__/materializeTestUtils.ts +17 -0
  118. package/src/__tests__/narrationAlign.test.ts +150 -0
  119. package/src/__tests__/narrationFeatures.test.ts +71 -0
  120. package/src/__tests__/narrationNuclei.test.ts +45 -0
  121. package/src/__tests__/narrationPacing.test.ts +189 -0
  122. package/src/__tests__/narrationScript.test.ts +149 -0
  123. package/src/__tests__/narrationSessionRepro.test.ts +62 -0
  124. package/src/__tests__/narrationSidecar.test.ts +88 -0
  125. package/src/__tests__/narrationSyllables.test.ts +65 -0
  126. package/src/__tests__/narrationTestSignals.ts +167 -0
  127. package/src/__tests__/narrationVad.test.ts +66 -0
  128. package/src/__tests__/resolveDocTheme.test.ts +16 -2
  129. package/src/__tests__/rootExports.test.ts +18 -0
  130. package/src/__tests__/scopedContentContainer.test.ts +20 -0
  131. package/src/__tests__/shapeGeometry.test.ts +12 -0
  132. package/src/__tests__/templateAnnotationParse.test.ts +10 -0
  133. package/src/__tests__/templateInputs.test.ts +69 -0
  134. package/src/__tests__/templateMetadata.test.ts +2 -1
  135. package/src/__tests__/templates.test.ts +143 -17
  136. package/src/__tests__/themeCompile.test.ts +49 -22
  137. package/src/__tests__/transformProvenance.test.ts +160 -0
  138. package/src/__tests__/transformV2.test.ts +40 -14
  139. package/src/__tests__/treeviewBattle.test.ts +76 -0
  140. package/src/__tests__/treeviewDetect.test.ts +168 -0
  141. package/src/__tests__/treeviewParse.test.ts +118 -0
  142. package/src/__tests__/treeviewPipeline.test.ts +183 -0
  143. package/src/__tests__/treeviewRender.test.ts +91 -0
  144. package/src/__tests__/versions.test.ts +44 -0
  145. package/src/doc/applyNarrationTiming.ts +244 -0
  146. package/src/doc/asciiDiagram/chars.ts +210 -0
  147. package/src/doc/asciiDiagram/detect.ts +175 -0
  148. package/src/doc/asciiDiagram/index.ts +38 -0
  149. package/src/doc/asciiDiagram/mapping.ts +225 -0
  150. package/src/doc/asciiDiagram/parse.ts +1095 -0
  151. package/src/doc/asciiDiagram/render.ts +963 -0
  152. package/src/doc/asciiDiagram/repair.ts +400 -0
  153. package/src/doc/asciiDiagram/types.ts +65 -0
  154. package/src/doc/asciiTimeline/detect.ts +138 -0
  155. package/src/doc/asciiTimeline/index.ts +26 -0
  156. package/src/doc/asciiTimeline/mapping.ts +43 -0
  157. package/src/doc/asciiTimeline/parse.ts +870 -0
  158. package/src/doc/asciiTimeline/render.ts +427 -0
  159. package/src/doc/asciiTimeline/types.ts +73 -0
  160. package/src/doc/asciiTimeline/wrappedFlow.ts +427 -0
  161. package/src/doc/audioMapping.ts +60 -46
  162. package/src/doc/customTemplatesFrontmatter.ts +0 -41
  163. package/src/doc/docToMarkdown.ts +70 -2
  164. package/src/doc/index.ts +76 -4
  165. package/src/doc/markdownToDoc.ts +138 -2
  166. package/src/doc/materializeBlockLayers.ts +304 -0
  167. package/src/doc/mediaAnnotations.ts +20 -0
  168. package/src/doc/resolveDocTheme.ts +8 -7
  169. package/src/doc/templateInputs.ts +185 -2
  170. package/src/doc/templates/__tests__/customTemplateRegistry.test.ts +22 -8
  171. package/src/doc/templates/__tests__/listBlock.test.ts +64 -0
  172. package/src/doc/templates/diagramBlock.ts +237 -38
  173. package/src/doc/templates/fallbackBlock.ts +1 -1
  174. package/src/doc/templates/index.ts +134 -279
  175. package/src/doc/templates/inputDescriptors.ts +20 -1
  176. package/src/doc/templates/listBlock.ts +88 -30
  177. package/src/doc/templates/metadata.ts +10 -0
  178. package/src/doc/templates/persistentLayers.ts +12 -126
  179. package/src/doc/templates/registry.ts +88 -0
  180. package/src/doc/templates/templateNames.ts +22 -0
  181. package/src/doc/templates/timelineBlock.ts +613 -0
  182. package/src/doc/templates/treeBlock.ts +131 -0
  183. package/src/doc/treeview/chars.ts +72 -0
  184. package/src/doc/treeview/detect.ts +145 -0
  185. package/src/doc/treeview/index.ts +30 -0
  186. package/src/doc/treeview/mapping.ts +95 -0
  187. package/src/doc/treeview/parse.ts +201 -0
  188. package/src/doc/treeview/render.ts +41 -0
  189. package/src/doc/treeview/types.ts +43 -0
  190. package/src/doc/utils/applyRenderStyle.ts +2 -9
  191. package/src/doc/utils/diagramText.ts +78 -0
  192. package/src/doc/utils/shapeGeometry.ts +67 -5
  193. package/src/doc/validate.ts +1 -1
  194. package/src/generate/templateMapper.ts +7 -0
  195. package/src/imageEdit/export.ts +6 -5
  196. package/src/imageEdit/versionPaths.ts +13 -26
  197. package/src/imageEdit/versions.ts +21 -100
  198. package/src/index.ts +1 -0
  199. package/src/internal/immutable.ts +58 -0
  200. package/src/jsonForm/index.ts +9 -1
  201. package/src/jsonForm/pointer.ts +68 -23
  202. package/src/markdown/attrTokens.ts +7 -5
  203. package/src/markdown/index.ts +1 -0
  204. package/src/markdown/stringify.ts +4 -9
  205. package/src/markdown/utils.ts +36 -14
  206. package/src/narration/align.ts +514 -0
  207. package/src/narration/features.ts +231 -0
  208. package/src/narration/index.ts +86 -0
  209. package/src/narration/nuclei.ts +118 -0
  210. package/src/narration/pacing.ts +211 -0
  211. package/src/narration/script.ts +239 -0
  212. package/src/narration/session.ts +100 -0
  213. package/src/narration/sidecar.ts +187 -0
  214. package/src/narration/syllables.ts +85 -0
  215. package/src/narration/trace.ts +50 -0
  216. package/src/narration/types.ts +299 -0
  217. package/src/narration/vad.ts +131 -0
  218. package/src/recommend/numberHighlight.ts +25 -0
  219. package/src/recommend/templates.ts +108 -12
  220. package/src/schemas/BlockTemplates.ts +156 -7
  221. package/src/schemas/Doc.ts +72 -9
  222. package/src/schemas/Media.ts +12 -2
  223. package/src/schemas/Theme.ts +45 -25
  224. package/src/schemas/Viewport.ts +2 -2
  225. package/src/schemas/fontStacks.ts +79 -0
  226. package/src/schemas/themeCompile.ts +15 -0
  227. package/src/schemas/themeConstants.ts +2 -0
  228. package/src/schemas/themeLibrary.ts +25 -19
  229. package/src/schemas/themeValidator.ts +1 -1
  230. package/src/schemas/themes/gezellig.json +1 -1
  231. package/src/spatial/Geohash.ts +0 -3
  232. package/src/storage/ContentContainer.ts +17 -9
  233. package/src/storage/ScopedContentContainer.ts +45 -15
  234. package/src/transform/applyTransform.ts +5 -5
  235. package/src/transform/index.ts +3 -1
  236. package/src/transform/registry.ts +169 -49
  237. package/src/transform/templateSelector.ts +21 -2
  238. package/src/transform/timingAllocator.ts +152 -21
  239. package/src/transform/types.ts +14 -1
  240. package/src/versions/gitignore.ts +34 -0
  241. package/src/versions/index.ts +2 -0
  242. package/src/versions/operations.ts +18 -104
  243. package/src/versions/paths.ts +13 -28
  244. package/src/versions/snapshotStore.ts +202 -0
  245. package/src/versions/types.ts +3 -1
  246. package/dist/chunk-5TYS5V3G.js.map +0 -1
  247. package/dist/chunk-A4O7GIWE.js.map +0 -1
  248. package/dist/chunk-BEQODJWV.js.map +0 -1
  249. package/dist/chunk-DLXZMS5K.js.map +0 -1
  250. package/dist/chunk-GPLTCSXO.js.map +0 -1
  251. package/dist/chunk-HWVFJAAH.js.map +0 -1
  252. package/dist/chunk-IMSCRLLV.js.map +0 -1
  253. package/dist/chunk-JELIRVDP.js +0 -24
  254. package/dist/chunk-JELIRVDP.js.map +0 -1
  255. package/dist/chunk-KKNUBQ6Y.js.map +0 -1
  256. package/dist/chunk-LDQ2HJIX.js.map +0 -1
  257. package/dist/chunk-LTN6I7QW.js.map +0 -1
  258. package/dist/chunk-P3K7NLHF.js.map +0 -1
  259. package/dist/chunk-T5UK6YOB.js.map +0 -1
  260. package/dist/chunk-UY7KGQ5R.js +0 -192
  261. package/dist/chunk-UY7KGQ5R.js.map +0 -1
  262. package/dist/chunk-VLJJHDAC.js +0 -218
  263. package/dist/chunk-VLJJHDAC.js.map +0 -1
  264. package/dist/chunk-VWUFZ6ZG.js.map +0 -1
  265. package/dist/story/index.d.ts +0 -1801
  266. package/dist/story/index.js +0 -279
  267. package/src/doc/getLayers.ts +0 -195
  268. /package/dist/{story → narration}/index.js.map +0 -0
@@ -0,0 +1,514 @@
1
+ /**
2
+ * Offline narration alignment: refine word/block timestamps from a
3
+ * recorded take.
4
+ *
5
+ * Pipeline: fine-hop features → VAD flags → syllable onsets + silence
6
+ * gaps (the DETECTED event sequence) vs. the script's expected
7
+ * syllable/pause slots (the EXPECTED sequence), aligned with a banded
8
+ * DTW. The band (Sakoe-Chiba style) follows the live prompter trace
9
+ * when one exists — the trace is what the reader actually saw — and a
10
+ * proportional prior otherwise. Matched slots yield word timestamps;
11
+ * block starts snap to the end of the breath gap readers take before a
12
+ * heading; block ranges are made CONTIGUOUS because downstream preview
13
+ * building re-derives start times from durations.
14
+ */
15
+
16
+ import { extractFrameFeatures } from './features.js';
17
+ import { detectSyllableOnsets } from './nuclei.js';
18
+ import { createVadState, vadStep } from './vad.js';
19
+ import type { NarrationTrace } from './trace.js';
20
+ import type {
21
+ AlignConfig,
22
+ FrameFeatures,
23
+ NarrationAlignment,
24
+ NarrationBlockRange,
25
+ NarrationScript,
26
+ WordTiming,
27
+ } from './types.js';
28
+ import { DEFAULT_ALIGN_CONFIG } from './types.js';
29
+
30
+ export interface AlignInput {
31
+ /** Mono PCM of the whole take. */
32
+ pcm: Float32Array;
33
+ sampleRate: number;
34
+ script: NarrationScript;
35
+ /** Live prompter trace recorded during the take, if any. */
36
+ trace?: NarrationTrace;
37
+ }
38
+
39
+ interface DetectedEvent {
40
+ kind: 'syl' | 'gap';
41
+ /** Representative time (onset peak, or gap midpoint). */
42
+ tSec: number;
43
+ startSec: number;
44
+ endSec: number;
45
+ }
46
+
47
+ interface ExpectedSlot {
48
+ kind: 'syl' | 'pause';
49
+ tokenIndex: number;
50
+ /** Syllable index within the token; -1 for pause slots. */
51
+ slotIndex: number;
52
+ /** Prior estimate of when this slot is spoken. */
53
+ priorSec: number;
54
+ }
55
+
56
+ /** Hard cap keeping the banded DP tractable on very long no-trace takes. */
57
+ const MAX_BAND_RADIUS_SEC = 60;
58
+
59
+ export function alignNarration(
60
+ input: AlignInput,
61
+ config?: Partial<AlignConfig>,
62
+ ): NarrationAlignment {
63
+ const c = { ...DEFAULT_ALIGN_CONFIG, ...config };
64
+ const { pcm, sampleRate, script } = input;
65
+ const takeDuration = pcm.length / Math.max(1, sampleRate);
66
+
67
+ if (script.tokens.length === 0 || takeDuration <= 0) {
68
+ return { words: [], blocks: [], detectedSyllables: 0, cost: 0 };
69
+ }
70
+
71
+ // ── 1. Detected events over the whole take ─────────────────────────
72
+ const frames = extractFrameFeatures(pcm, sampleRate, { hopSec: c.hopSec });
73
+ const vadFlags = runVad(frames);
74
+ const onsets = detectSyllableOnsets(frames, vadFlags);
75
+ const gaps = findSilenceGaps(frames, vadFlags, c.gapMinSec);
76
+ const lastSpeechEnd = findLastSpeechEnd(frames, vadFlags);
77
+
78
+ if (onsets.length === 0) {
79
+ return proportionalAlignment(
80
+ script,
81
+ lastSpeechEnd > 0 ? lastSpeechEnd : takeDuration,
82
+ takeDuration,
83
+ c,
84
+ 0,
85
+ );
86
+ }
87
+
88
+ const events: DetectedEvent[] = [
89
+ ...onsets.map((t): DetectedEvent => ({ kind: 'syl', tSec: t, startSec: t, endSec: t })),
90
+ ...gaps,
91
+ ].sort((a, b) => a.tSec - b.tSec);
92
+
93
+ // ── 2. Expected slots with prior times ─────────────────────────────
94
+ const bandRadius = Math.min(
95
+ MAX_BAND_RADIUS_SEC,
96
+ input.trace && input.trace.samples.length >= 2
97
+ ? c.bandRadiusSec
98
+ : Math.max(c.bandRadiusNoTraceSec, 0.1 * takeDuration),
99
+ );
100
+ const slots = buildExpectedSlots(script, takeDuration, input.trace);
101
+
102
+ // ── 3. Banded DP ────────────────────────────────────────────────────
103
+ const { matchedEventBySlot, cost } = bandedDtw(slots, events, bandRadius, c);
104
+
105
+ // ── 4. Word timestamps ──────────────────────────────────────────────
106
+ const words = deriveWordTimings(script, slots, events, matchedEventBySlot);
107
+
108
+ // ── 5. Block ranges ─────────────────────────────────────────────────
109
+ const blocks = deriveBlockRanges(script, words, gaps, takeDuration, lastSpeechEnd, c);
110
+
111
+ return { words, blocks, detectedSyllables: onsets.length, cost };
112
+ }
113
+
114
+ // ── Detection helpers ─────────────────────────────────────────────────
115
+
116
+ function runVad(frames: FrameFeatures[]): boolean[] {
117
+ let vad = createVadState();
118
+ const flags = new Array<boolean>(frames.length);
119
+ for (let i = 0; i < frames.length; i++) {
120
+ vad = vadStep(vad, frames[i]);
121
+ flags[i] = vad.speaking;
122
+ }
123
+ return flags;
124
+ }
125
+
126
+ function findSilenceGaps(
127
+ frames: FrameFeatures[],
128
+ vadFlags: boolean[],
129
+ gapMinSec: number,
130
+ ): DetectedEvent[] {
131
+ const gaps: DetectedEvent[] = [];
132
+ let runStart = -1;
133
+ for (let i = 0; i <= frames.length; i++) {
134
+ const silent = i < frames.length ? !vadFlags[i] : false;
135
+ if (silent && runStart === -1) {
136
+ runStart = i;
137
+ } else if (!silent && runStart !== -1) {
138
+ const startSec = frames[runStart].tSec;
139
+ const endSec = frames[i - 1].tSec;
140
+ if (endSec - startSec >= gapMinSec) {
141
+ gaps.push({ kind: 'gap', tSec: (startSec + endSec) / 2, startSec, endSec });
142
+ }
143
+ runStart = -1;
144
+ }
145
+ }
146
+ return gaps;
147
+ }
148
+
149
+ function findLastSpeechEnd(frames: FrameFeatures[], vadFlags: boolean[]): number {
150
+ for (let i = frames.length - 1; i >= 0; i--) {
151
+ if (vadFlags[i]) return frames[i].tSec;
152
+ }
153
+ return 0;
154
+ }
155
+
156
+ // ── Expected slots + priors ───────────────────────────────────────────
157
+
158
+ function buildExpectedSlots(
159
+ script: NarrationScript,
160
+ takeDuration: number,
161
+ trace: NarrationTrace | undefined,
162
+ ): ExpectedSlot[] {
163
+ const slots: ExpectedSlot[] = [];
164
+ for (let k = 0; k < script.tokens.length; k++) {
165
+ const token = script.tokens[k];
166
+ for (let s = 0; s < token.syllables; s++) {
167
+ slots.push({ kind: 'syl', tokenIndex: k, slotIndex: s, priorSec: 0 });
168
+ }
169
+ if (token.pauseAfter >= 2) {
170
+ slots.push({ kind: 'pause', tokenIndex: k, slotIndex: -1, priorSec: 0 });
171
+ }
172
+ }
173
+
174
+ const useTrace = trace !== undefined && trace.samples.length >= 2;
175
+ if (useTrace) {
176
+ assignTracePriors(slots, script, trace, takeDuration);
177
+ } else {
178
+ const total = Math.max(1, script.totalSyllables);
179
+ for (const slot of slots) {
180
+ const cumBefore =
181
+ slot.kind === 'pause'
182
+ ? script.cumulativeSyllables[slot.tokenIndex + 1]
183
+ : script.cumulativeSyllables[slot.tokenIndex] + slot.slotIndex;
184
+ slot.priorSec = (cumBefore / total) * takeDuration;
185
+ }
186
+ }
187
+
188
+ // Priors must be monotone for the band windows to be monotone.
189
+ let prev = 0;
190
+ for (const slot of slots) {
191
+ if (slot.priorSec < prev) slot.priorSec = prev;
192
+ if (slot.priorSec > takeDuration) slot.priorSec = takeDuration;
193
+ prev = slot.priorSec;
194
+ }
195
+ return slots;
196
+ }
197
+
198
+ /** Invert the (monotonicized) live trace: earliest time the prompter reached each slot's word position. */
199
+ function assignTracePriors(
200
+ slots: ExpectedSlot[],
201
+ script: NarrationScript,
202
+ trace: NarrationTrace,
203
+ takeDuration: number,
204
+ ): void {
205
+ // Monotonicize wordPos (manual back-nudges would break the sweep).
206
+ const times: number[] = [];
207
+ const positions: number[] = [];
208
+ let runningMax = 0;
209
+ for (const sample of trace.samples) {
210
+ runningMax = Math.max(runningMax, sample.wordPos);
211
+ times.push(sample.tMs / 1000);
212
+ positions.push(runningMax);
213
+ }
214
+
215
+ let ptr = 0;
216
+ for (const slot of slots) {
217
+ const token = script.tokens[slot.tokenIndex];
218
+ const target =
219
+ slot.kind === 'pause'
220
+ ? slot.tokenIndex + 1
221
+ : slot.tokenIndex + slot.slotIndex / Math.max(1, token.syllables);
222
+ while (ptr < positions.length - 1 && positions[ptr + 1] < target) ptr++;
223
+ let t: number;
224
+ if (positions[ptr] >= target) {
225
+ t = times[ptr];
226
+ } else if (ptr >= positions.length - 1) {
227
+ t = times[times.length - 1];
228
+ } else {
229
+ const span = positions[ptr + 1] - positions[ptr];
230
+ const frac = span > 0 ? (target - positions[ptr]) / span : 0;
231
+ t = times[ptr] + frac * (times[ptr + 1] - times[ptr]);
232
+ }
233
+ slot.priorSec = Math.min(Math.max(0, t), takeDuration);
234
+ }
235
+ }
236
+
237
+ // ── The banded DP ─────────────────────────────────────────────────────
238
+
239
+ function matchCost(
240
+ slot: ExpectedSlot,
241
+ event: DetectedEvent,
242
+ bandRadius: number,
243
+ c: AlignConfig,
244
+ ): number {
245
+ if (slot.kind === 'syl') {
246
+ if (event.kind === 'syl') {
247
+ return (
248
+ (c.matchTimeWeight * Math.abs(event.tSec - slot.priorSec)) / Math.max(1e-6, bandRadius)
249
+ );
250
+ }
251
+ return c.sylToGapCost;
252
+ }
253
+ return event.kind === 'gap' ? 0 : c.pauseToSylCost;
254
+ }
255
+
256
+ function bandedDtw(
257
+ slots: ExpectedSlot[],
258
+ events: DetectedEvent[],
259
+ bandRadius: number,
260
+ c: AlignConfig,
261
+ ): { matchedEventBySlot: Int32Array; cost: number } {
262
+ const N = slots.length;
263
+ const M = events.length;
264
+ const INF = Number.POSITIVE_INFINITY;
265
+ const eventTimes = events.map((e) => e.tSec);
266
+
267
+ // Column windows per DP row (row i consumed i slots; columns are consumed events).
268
+ const lo = new Int32Array(N + 1);
269
+ const hi = new Int32Array(N + 1);
270
+ for (let i = 1; i <= N; i++) {
271
+ const prior = slots[i - 1].priorSec;
272
+ lo[i] = lowerBound(eventTimes, prior - bandRadius);
273
+ hi[i] = upperBound(eventTimes, prior + bandRadius);
274
+ }
275
+ lo[0] = 0;
276
+ hi[0] = N >= 1 ? hi[1] : M;
277
+ // Forward pass: monotone, connected, in-range.
278
+ for (let i = 1; i <= N; i++) {
279
+ if (lo[i] < lo[i - 1]) lo[i] = lo[i - 1];
280
+ if (lo[i] > hi[i - 1] + 1) lo[i] = hi[i - 1] + 1;
281
+ if (lo[i] > M) lo[i] = M;
282
+ if (hi[i] < hi[i - 1]) hi[i] = hi[i - 1];
283
+ if (hi[i] < lo[i]) hi[i] = lo[i];
284
+ if (hi[i] > M) hi[i] = M;
285
+ }
286
+ hi[N] = M;
287
+ if (lo[N] > M) lo[N] = M;
288
+
289
+ // DP with per-row backpointers (0 = diag/match, 1 = up/delete-slot, 2 = left/insert-event).
290
+ const ptrRows: Uint8Array[] = new Array(N + 1);
291
+ let prevCost = new Float64Array(hi[0] - lo[0] + 1);
292
+ {
293
+ const row = new Uint8Array(hi[0] - lo[0] + 1);
294
+ for (let j = lo[0]; j <= hi[0]; j++) {
295
+ prevCost[j - lo[0]] = j * c.insertCost;
296
+ row[j - lo[0]] = 2;
297
+ }
298
+ ptrRows[0] = row;
299
+ }
300
+
301
+ for (let i = 1; i <= N; i++) {
302
+ const width = hi[i] - lo[i] + 1;
303
+ const cost = new Float64Array(width).fill(INF);
304
+ const ptr = new Uint8Array(width);
305
+ const slot = slots[i - 1];
306
+ for (let j = lo[i]; j <= hi[i]; j++) {
307
+ const idx = j - lo[i];
308
+ let best = INF;
309
+ let bestPtr = 1;
310
+ // Diagonal: match slot i-1 with event j-1.
311
+ if (j >= 1 && j - 1 >= lo[i - 1] && j - 1 <= hi[i - 1]) {
312
+ const v = prevCost[j - 1 - lo[i - 1]] + matchCost(slot, events[j - 1], bandRadius, c);
313
+ if (v < best) {
314
+ best = v;
315
+ bestPtr = 0;
316
+ }
317
+ }
318
+ // Up: delete the slot (unspoken/merged syllable).
319
+ if (j >= lo[i - 1] && j <= hi[i - 1]) {
320
+ const v = prevCost[j - lo[i - 1]] + c.deleteCost;
321
+ if (v < best) {
322
+ best = v;
323
+ bestPtr = 1;
324
+ }
325
+ }
326
+ // Left: insert the event (filler, breath, click).
327
+ if (j - 1 >= lo[i]) {
328
+ const v = cost[idx - 1] + c.insertCost;
329
+ if (v < best) {
330
+ best = v;
331
+ bestPtr = 2;
332
+ }
333
+ }
334
+ cost[idx] = best;
335
+ ptr[idx] = bestPtr;
336
+ }
337
+ ptrRows[i] = ptr;
338
+ prevCost = cost;
339
+ }
340
+
341
+ // Backtrack from (N, M).
342
+ const matchedEventBySlot = new Int32Array(N).fill(-1);
343
+ let i = N;
344
+ let j = M;
345
+ const finalCost = prevCost[M - lo[N]] ?? 0;
346
+ while (i > 0 || j > 0) {
347
+ const row = ptrRows[i];
348
+ const idx = j - lo[i];
349
+ const move = idx >= 0 && idx < row.length ? row[idx] : i > 0 ? 1 : 2;
350
+ if (move === 0 && i > 0 && j > 0) {
351
+ matchedEventBySlot[i - 1] = j - 1;
352
+ i--;
353
+ j--;
354
+ } else if (move === 1 && i > 0) {
355
+ i--;
356
+ } else if (j > 0) {
357
+ j--;
358
+ } else if (i > 0) {
359
+ i--;
360
+ } else {
361
+ break;
362
+ }
363
+ }
364
+
365
+ return { matchedEventBySlot, cost: Number.isFinite(finalCost) ? finalCost : 0 };
366
+ }
367
+
368
+ /** First index with values[idx] >= target. */
369
+ function lowerBound(values: number[], target: number): number {
370
+ let lo = 0;
371
+ let hi = values.length;
372
+ while (lo < hi) {
373
+ const mid = (lo + hi) >> 1;
374
+ if (values[mid] < target) lo = mid + 1;
375
+ else hi = mid;
376
+ }
377
+ return lo;
378
+ }
379
+
380
+ /** Count of values <= target (i.e. exclusive upper index). */
381
+ function upperBound(values: number[], target: number): number {
382
+ let lo = 0;
383
+ let hi = values.length;
384
+ while (lo < hi) {
385
+ const mid = (lo + hi) >> 1;
386
+ if (values[mid] <= target) lo = mid + 1;
387
+ else hi = mid;
388
+ }
389
+ return lo;
390
+ }
391
+
392
+ // ── Outputs ───────────────────────────────────────────────────────────
393
+
394
+ function deriveWordTimings(
395
+ script: NarrationScript,
396
+ slots: ExpectedSlot[],
397
+ events: DetectedEvent[],
398
+ matchedEventBySlot: Int32Array,
399
+ ): WordTiming[] {
400
+ const n = script.tokens.length;
401
+ const raw = new Array<number | undefined>(n);
402
+ for (let s = 0; s < slots.length; s++) {
403
+ const eventIdx = matchedEventBySlot[s];
404
+ if (eventIdx < 0) continue;
405
+ const slot = slots[s];
406
+ if (slot.kind !== 'syl') continue;
407
+ if (raw[slot.tokenIndex] !== undefined) continue; // first matched slot wins
408
+ const event = events[eventIdx];
409
+ // A word matched to a gap starts when speech resumes.
410
+ raw[slot.tokenIndex] = event.kind === 'gap' ? event.endSec : event.tSec;
411
+ }
412
+
413
+ const words: WordTiming[] = new Array(n);
414
+ let prevKnownIdx = -1;
415
+ let prevKnownT = 0;
416
+ for (let k = 0; k < n; k++) {
417
+ if (raw[k] === undefined) continue;
418
+ // Interpolate the run of unknowns between prevKnown and k.
419
+ const t = raw[k]!;
420
+ for (let u = prevKnownIdx + 1; u < k; u++) {
421
+ const frac = (u - prevKnownIdx) / (k - prevKnownIdx);
422
+ const base = prevKnownIdx >= 0 ? prevKnownT : t;
423
+ words[u] = {
424
+ tokenIndex: u,
425
+ tSec: base + (t - base) * (prevKnownIdx >= 0 ? frac : 0),
426
+ interpolated: true,
427
+ };
428
+ }
429
+ words[k] = { tokenIndex: k, tSec: t, interpolated: false };
430
+ prevKnownIdx = k;
431
+ prevKnownT = t;
432
+ }
433
+ for (let u = prevKnownIdx + 1; u < n; u++) {
434
+ words[u] = { tokenIndex: u, tSec: prevKnownT, interpolated: true };
435
+ }
436
+ if (prevKnownIdx === -1) {
437
+ for (let u = 0; u < n; u++) words[u] = { tokenIndex: u, tSec: 0, interpolated: true };
438
+ }
439
+ // Monotonic.
440
+ let running = 0;
441
+ for (const w of words) {
442
+ running = Math.max(running, w.tSec);
443
+ w.tSec = running;
444
+ }
445
+ return words;
446
+ }
447
+
448
+ function deriveBlockRanges(
449
+ script: NarrationScript,
450
+ words: WordTiming[],
451
+ gaps: DetectedEvent[],
452
+ takeDuration: number,
453
+ lastSpeechEnd: number,
454
+ c: AlignConfig,
455
+ ): NarrationBlockRange[] {
456
+ const blocks: NarrationBlockRange[] = [];
457
+ const gapEnds = gaps.map((g) => g.endSec);
458
+ let prevStart = 0;
459
+ for (let b = 0; b < script.blocks.length; b++) {
460
+ const range = script.blocks[b];
461
+ const firstWord = words[range.tokenStart];
462
+ let startSec = b === 0 ? 0 : (firstWord?.tSec ?? prevStart);
463
+ if (b > 0) {
464
+ // Snap to the end of the breath gap just before the block, if close.
465
+ const idx = upperBound(gapEnds, startSec) - 1;
466
+ if (idx >= 0 && startSec - gapEnds[idx] <= c.blockSnapWindowSec && gapEnds[idx] > prevStart) {
467
+ startSec = gapEnds[idx];
468
+ }
469
+ if (startSec < prevStart) startSec = prevStart;
470
+ }
471
+ blocks.push({
472
+ blockId: range.blockId,
473
+ ...(range.heading !== undefined ? { heading: range.heading } : {}),
474
+ blockIndex: b,
475
+ charStart: range.charStart,
476
+ charEnd: range.charEnd,
477
+ startSec,
478
+ endSec: startSec,
479
+ });
480
+ prevStart = startSec;
481
+ }
482
+ // Contiguous ranges: endSec === next.startSec; final block covers the tail.
483
+ for (let b = 0; b < blocks.length - 1; b++) {
484
+ blocks[b].endSec = blocks[b + 1].startSec;
485
+ }
486
+ if (blocks.length > 0) {
487
+ const last = blocks[blocks.length - 1];
488
+ let end = Math.min(
489
+ takeDuration,
490
+ (lastSpeechEnd > 0 ? lastSpeechEnd : takeDuration) + c.tailPadSec,
491
+ );
492
+ if (takeDuration - end <= 1) end = takeDuration;
493
+ last.endSec = Math.max(last.startSec, end);
494
+ }
495
+ return blocks;
496
+ }
497
+
498
+ /** Fallback when nothing was detected: proportional by expected syllables. */
499
+ function proportionalAlignment(
500
+ script: NarrationScript,
501
+ effectiveDuration: number,
502
+ takeDuration: number,
503
+ c: AlignConfig,
504
+ detectedSyllables: number,
505
+ ): NarrationAlignment {
506
+ const total = Math.max(1, script.totalSyllables);
507
+ const words: WordTiming[] = script.tokens.map((_, k) => ({
508
+ tokenIndex: k,
509
+ tSec: (script.cumulativeSyllables[k] / total) * effectiveDuration,
510
+ interpolated: true,
511
+ }));
512
+ const blocks = deriveBlockRanges(script, words, [], takeDuration, effectiveDuration, c);
513
+ return { words, blocks, detectedSyllables, cost: 0 };
514
+ }