@bendyline/squisq 1.5.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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-VWUFZ6ZG.js → chunk-3E5F2XMR.js} +2 -29
  6. package/dist/chunk-3E5F2XMR.js.map +1 -0
  7. package/dist/chunk-4X3JQXNM.js +35 -0
  8. package/dist/chunk-4X3JQXNM.js.map +1 -0
  9. package/dist/{chunk-2OIBZYKP.js → chunk-5DKBFXPY.js} +31 -121
  10. package/dist/chunk-5DKBFXPY.js.map +1 -0
  11. package/dist/{chunk-DLXZMS5K.js → chunk-5J4HKRJF.js} +51 -3
  12. package/dist/chunk-5J4HKRJF.js.map +1 -0
  13. package/dist/chunk-5UYI3RJB.js +2503 -0
  14. package/dist/chunk-5UYI3RJB.js.map +1 -0
  15. package/dist/{chunk-TEEEILMP.js → chunk-66QO7XFB.js} +19 -292
  16. package/dist/chunk-66QO7XFB.js.map +1 -0
  17. package/dist/{chunk-KKNUBQ6Y.js → chunk-6PJRB2CF.js} +156 -91
  18. package/dist/chunk-6PJRB2CF.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-FVJUUTEM.js +74 -0
  22. package/dist/chunk-FVJUUTEM.js.map +1 -0
  23. package/dist/{chunk-LH7I6SH7.js → chunk-GF3BVNLU.js} +6360 -5723
  24. package/dist/chunk-GF3BVNLU.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-LYNJEOAC.js} +10 -73
  30. package/dist/chunk-LYNJEOAC.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-T5UK6YOB.js → chunk-QTSJOY54.js} +60 -17
  36. package/dist/chunk-QTSJOY54.js.map +1 -0
  37. package/dist/chunk-QVANWDPH.js +2358 -0
  38. package/dist/chunk-QVANWDPH.js.map +1 -0
  39. package/dist/{chunk-6ATE2PSM.js → chunk-R2GC6RLD.js} +7 -7
  40. package/dist/chunk-R2GC6RLD.js.map +1 -0
  41. package/dist/chunk-R2YZTCLO.js +292 -0
  42. package/dist/chunk-R2YZTCLO.js.map +1 -0
  43. package/dist/chunk-S7A5D7ZJ.js +174 -0
  44. package/dist/chunk-S7A5D7ZJ.js.map +1 -0
  45. package/dist/chunk-T3TI7GSZ.js +884 -0
  46. package/dist/chunk-T3TI7GSZ.js.map +1 -0
  47. package/dist/{chunk-RUDYOTA6.js → chunk-TUWMK62B.js} +110 -4
  48. package/dist/chunk-TUWMK62B.js.map +1 -0
  49. package/dist/{chunk-IMSCRLLV.js → chunk-VR7UPJ7C.js} +35 -25
  50. package/dist/chunk-VR7UPJ7C.js.map +1 -0
  51. package/dist/doc/index.d.ts +2334 -5
  52. package/dist/doc/index.js +134 -34
  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 +253 -81
  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__/coverBlock.test.ts +33 -2
  97. package/src/__tests__/customTemplatesFrontmatter.test.ts +0 -15
  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 +41 -0
  114. package/src/__tests__/markdownToDoc.test.ts +5 -2
  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 +49 -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 +126 -39
  164. package/src/doc/index.ts +76 -4
  165. package/src/doc/markdownToDoc.ts +135 -1
  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/coverBlock.ts +49 -13
  172. package/src/doc/templates/diagramBlock.ts +237 -38
  173. package/src/doc/templates/drawingBlock.ts +2 -2
  174. package/src/doc/templates/fallbackBlock.ts +1 -1
  175. package/src/doc/templates/index.ts +134 -279
  176. package/src/doc/templates/inputDescriptors.ts +20 -1
  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 +157 -7
  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/convert.ts +11 -1
  204. package/src/markdown/index.ts +1 -0
  205. package/src/markdown/stringify.ts +4 -9
  206. package/src/markdown/utils.ts +36 -14
  207. package/src/narration/align.ts +514 -0
  208. package/src/narration/features.ts +231 -0
  209. package/src/narration/index.ts +86 -0
  210. package/src/narration/nuclei.ts +118 -0
  211. package/src/narration/pacing.ts +211 -0
  212. package/src/narration/script.ts +239 -0
  213. package/src/narration/session.ts +100 -0
  214. package/src/narration/sidecar.ts +187 -0
  215. package/src/narration/syllables.ts +85 -0
  216. package/src/narration/trace.ts +50 -0
  217. package/src/narration/types.ts +299 -0
  218. package/src/narration/vad.ts +131 -0
  219. package/src/recommend/numberHighlight.ts +25 -0
  220. package/src/recommend/templates.ts +108 -12
  221. package/src/schemas/BlockTemplates.ts +156 -7
  222. package/src/schemas/Doc.ts +72 -9
  223. package/src/schemas/Media.ts +12 -2
  224. package/src/schemas/Theme.ts +45 -25
  225. package/src/schemas/Viewport.ts +2 -2
  226. package/src/schemas/fontStacks.ts +79 -0
  227. package/src/schemas/themeCompile.ts +15 -0
  228. package/src/schemas/themeConstants.ts +2 -0
  229. package/src/schemas/themeLibrary.ts +25 -19
  230. package/src/schemas/themeValidator.ts +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-2OIBZYKP.js.map +0 -1
  247. package/dist/chunk-6ATE2PSM.js.map +0 -1
  248. package/dist/chunk-A4O7GIWE.js.map +0 -1
  249. package/dist/chunk-DLXZMS5K.js.map +0 -1
  250. package/dist/chunk-HWVFJAAH.js.map +0 -1
  251. package/dist/chunk-IMSCRLLV.js.map +0 -1
  252. package/dist/chunk-JELIRVDP.js +0 -24
  253. package/dist/chunk-JELIRVDP.js.map +0 -1
  254. package/dist/chunk-KKNUBQ6Y.js.map +0 -1
  255. package/dist/chunk-LDQ2HJIX.js.map +0 -1
  256. package/dist/chunk-LH7I6SH7.js.map +0 -1
  257. package/dist/chunk-RUDYOTA6.js.map +0 -1
  258. package/dist/chunk-T5UK6YOB.js.map +0 -1
  259. package/dist/chunk-TEEEILMP.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 -1777
  266. package/dist/story/index.js +0 -273
  267. package/src/doc/getLayers.ts +0 -195
  268. /package/dist/{story → narration}/index.js.map +0 -0
@@ -0,0 +1,231 @@
1
+ /**
2
+ * Frame feature extraction: full-band RMS, speech-band energy, and
3
+ * zero-crossing rate over hopped (possibly overlapping) frames.
4
+ *
5
+ * Band energy uses two cascaded RBJ biquads — a high-pass at
6
+ * `bandLowHz` and a low-pass at `bandHighHz` (both Q = 1/√2,
7
+ * Audio-EQ-Cookbook closed forms) — rather than an FFT or Goertzel
8
+ * bins: a Butterworth-ish cascade gives a true maximally-flat band in
9
+ * one O(N) pass, and the filter state persists across hops, which is
10
+ * exactly right for streaming (no window-boundary energy jitter).
11
+ * Goertzel measures single frequencies (DTMF-style) — wrong tool for
12
+ * broadband speech energy.
13
+ */
14
+
15
+ import type { FeatureConfig, FrameFeatures } from './types.js';
16
+ import { DEFAULT_FEATURE_CONFIG } from './types.js';
17
+
18
+ interface BiquadCoeffs {
19
+ b0: number;
20
+ b1: number;
21
+ b2: number;
22
+ a1: number;
23
+ a2: number;
24
+ }
25
+
26
+ interface BiquadState {
27
+ x1: number;
28
+ x2: number;
29
+ y1: number;
30
+ y2: number;
31
+ }
32
+
33
+ export interface BandpassState {
34
+ coeffs: { hp: BiquadCoeffs; lp: BiquadCoeffs };
35
+ hp: BiquadState;
36
+ lp: BiquadState;
37
+ }
38
+
39
+ function highpassCoeffs(sampleRate: number, freqHz: number): BiquadCoeffs {
40
+ const w0 = (2 * Math.PI * freqHz) / sampleRate;
41
+ const cosW0 = Math.cos(w0);
42
+ // alpha = sin(w0) / (2Q) with Butterworth Q = 1/√2.
43
+ const alpha = Math.sin(w0) / (2 * Math.SQRT1_2);
44
+ const a0 = 1 + alpha;
45
+ return {
46
+ b0: (1 + cosW0) / 2 / a0,
47
+ b1: -(1 + cosW0) / a0,
48
+ b2: (1 + cosW0) / 2 / a0,
49
+ a1: (-2 * cosW0) / a0,
50
+ a2: (1 - alpha) / a0,
51
+ };
52
+ }
53
+
54
+ function lowpassCoeffs(sampleRate: number, freqHz: number): BiquadCoeffs {
55
+ const w0 = (2 * Math.PI * freqHz) / sampleRate;
56
+ const cosW0 = Math.cos(w0);
57
+ const alpha = Math.sin(w0) / (2 * Math.SQRT1_2);
58
+ const a0 = 1 + alpha;
59
+ return {
60
+ b0: (1 - cosW0) / 2 / a0,
61
+ b1: (1 - cosW0) / a0,
62
+ b2: (1 - cosW0) / 2 / a0,
63
+ a1: (-2 * cosW0) / a0,
64
+ a2: (1 - alpha) / a0,
65
+ };
66
+ }
67
+
68
+ /** Create bandpass state for a sample rate (corners derived at init). */
69
+ export function createBandpass(
70
+ sampleRate: number,
71
+ lowHz = DEFAULT_FEATURE_CONFIG.bandLowHz,
72
+ highHz = DEFAULT_FEATURE_CONFIG.bandHighHz,
73
+ ): BandpassState {
74
+ return {
75
+ coeffs: { hp: highpassCoeffs(sampleRate, lowHz), lp: lowpassCoeffs(sampleRate, highHz) },
76
+ hp: { x1: 0, x2: 0, y1: 0, y2: 0 },
77
+ lp: { x1: 0, x2: 0, y1: 0, y2: 0 },
78
+ };
79
+ }
80
+
81
+ function biquadRun(
82
+ coeffs: BiquadCoeffs,
83
+ state: BiquadState,
84
+ input: Float32Array,
85
+ output: Float32Array,
86
+ ): BiquadState {
87
+ let { x1, x2, y1, y2 } = state;
88
+ const { b0, b1, b2, a1, a2 } = coeffs;
89
+ for (let i = 0; i < input.length; i++) {
90
+ const x0 = input[i];
91
+ const y0 = b0 * x0 + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2;
92
+ output[i] = y0;
93
+ x2 = x1;
94
+ x1 = x0;
95
+ y2 = y1;
96
+ y1 = y0;
97
+ }
98
+ return { x1, x2, y1, y2 };
99
+ }
100
+
101
+ /**
102
+ * Run the bandpass over a chunk. Pure in the state: returns a NEW state,
103
+ * writes filtered samples into `output` (may alias `input`).
104
+ */
105
+ export function bandpassRun(
106
+ state: BandpassState,
107
+ input: Float32Array,
108
+ output: Float32Array,
109
+ ): BandpassState {
110
+ const hp = biquadRun(state.coeffs.hp, state.hp, input, output);
111
+ const lp = biquadRun(state.coeffs.lp, state.lp, output, output);
112
+ return { coeffs: state.coeffs, hp, lp };
113
+ }
114
+
115
+ export interface FeatureState {
116
+ sampleRate: number;
117
+ config: FeatureConfig;
118
+ /** Hop between frame starts, in samples. */
119
+ hopSamples: number;
120
+ bandpass: BandpassState;
121
+ /** Unconsumed raw samples (the next frame's prefix). */
122
+ rawCarry: Float32Array;
123
+ /** Bandpassed twin of `rawCarry`. */
124
+ bandCarry: Float32Array;
125
+ /** Absolute sample index of `rawCarry[0]` from the start of the signal. */
126
+ carryStartSample: number;
127
+ }
128
+
129
+ export function createFeatureState(
130
+ sampleRate: number,
131
+ config?: Partial<FeatureConfig>,
132
+ ): FeatureState {
133
+ const merged: FeatureConfig = { ...DEFAULT_FEATURE_CONFIG, ...config };
134
+ return {
135
+ sampleRate,
136
+ config: merged,
137
+ hopSamples: Math.max(1, Math.round(merged.hopSec * sampleRate)),
138
+ bandpass: createBandpass(sampleRate, merged.bandLowHz, merged.bandHighHz),
139
+ rawCarry: new Float32Array(0),
140
+ bandCarry: new Float32Array(0),
141
+ carryStartSample: 0,
142
+ };
143
+ }
144
+
145
+ function concatF32(a: Float32Array, b: Float32Array): Float32Array {
146
+ if (a.length === 0) return b;
147
+ const out = new Float32Array(a.length + b.length);
148
+ out.set(a, 0);
149
+ out.set(b, a.length);
150
+ return out;
151
+ }
152
+
153
+ function frameOf(
154
+ raw: Float32Array,
155
+ band: Float32Array,
156
+ start: number,
157
+ size: number,
158
+ startSample: number,
159
+ sampleRate: number,
160
+ ): FrameFeatures {
161
+ let sumSq = 0;
162
+ let bandSumSq = 0;
163
+ let crossings = 0;
164
+ let prev = raw[start];
165
+ for (let i = 0; i < size; i++) {
166
+ const r = raw[start + i];
167
+ const b = band[start + i];
168
+ sumSq += r * r;
169
+ bandSumSq += b * b;
170
+ if (i > 0 && ((r >= 0 && prev < 0) || (r < 0 && prev >= 0))) crossings++;
171
+ prev = r;
172
+ }
173
+ return {
174
+ tSec: (startSample + size / 2) / sampleRate,
175
+ rms: Math.sqrt(sumSq / size),
176
+ bandEnergy: bandSumSq / size,
177
+ zcr: size > 1 ? crossings / (size - 1) : 0,
178
+ };
179
+ }
180
+
181
+ /**
182
+ * Feed a hop of PCM. Returns a new state plus every complete frame the
183
+ * buffered signal now covers (usually 0–1 for worklet-sized hops, more
184
+ * for large chunks).
185
+ */
186
+ export function featureStep(
187
+ state: FeatureState,
188
+ hop: Float32Array,
189
+ ): { state: FeatureState; frames: FrameFeatures[] } {
190
+ const banded = new Float32Array(hop.length);
191
+ const bandpass = bandpassRun(state.bandpass, hop, banded);
192
+
193
+ const raw = concatF32(state.rawCarry, hop);
194
+ const band = concatF32(state.bandCarry, banded);
195
+ const { frameSize } = state.config;
196
+ const frames: FrameFeatures[] = [];
197
+
198
+ let cursor = 0;
199
+ while (raw.length - cursor >= frameSize) {
200
+ frames.push(
201
+ frameOf(raw, band, cursor, frameSize, state.carryStartSample + cursor, state.sampleRate),
202
+ );
203
+ cursor += state.hopSamples;
204
+ }
205
+
206
+ return {
207
+ state: {
208
+ ...state,
209
+ bandpass,
210
+ // slice(), not subarray(): the carry must OWN its memory. `raw` can
211
+ // alias the caller's hop buffer, and callers may recycle those
212
+ // (e.g. Chrome invalidates buffers transferred out of an
213
+ // AudioWorklet after the message handler returns) — a retained
214
+ // view would silently read zeros on the next step.
215
+ rawCarry: raw.slice(cursor),
216
+ bandCarry: band.slice(cursor),
217
+ carryStartSample: state.carryStartSample + cursor,
218
+ },
219
+ frames,
220
+ };
221
+ }
222
+
223
+ /** Batch feature extraction over a whole take (the aligner's entry point). */
224
+ export function extractFrameFeatures(
225
+ pcm: Float32Array,
226
+ sampleRate: number,
227
+ config?: Partial<FeatureConfig>,
228
+ ): FrameFeatures[] {
229
+ const state = createFeatureState(sampleRate, config);
230
+ return featureStep(state, pcm).frames;
231
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * @bendyline/squisq/narration — the narration/teleprompter engine.
3
+ *
4
+ * Pure TypeScript, zero dependencies, no DOM/Node APIs: a script model
5
+ * built from a Doc, streaming DSP (band features → adaptive VAD →
6
+ * syllable nuclei), a deterministic voice-adaptive pacing controller,
7
+ * and an offline DTW aligner that turns a recorded take into word/block
8
+ * timestamps. Determinism is a hard rule here — no Date.now, no
9
+ * Math.random, no timers — so every stage is unit-testable in Node
10
+ * with synthetic PCM.
11
+ */
12
+
13
+ export type {
14
+ ScriptToken,
15
+ ScriptBlockRange,
16
+ NarrationScript,
17
+ FrameFeatures,
18
+ FeatureConfig,
19
+ VadConfig,
20
+ NucleiConfig,
21
+ PacingConfig,
22
+ AlignConfig,
23
+ WordTiming,
24
+ NarrationBlockRange,
25
+ NarrationAlignment,
26
+ } from './types.js';
27
+ export {
28
+ DEFAULT_FEATURE_CONFIG,
29
+ DEFAULT_VAD_CONFIG,
30
+ DEFAULT_NUCLEI_CONFIG,
31
+ DEFAULT_PACING_CONFIG,
32
+ DEFAULT_ALIGN_CONFIG,
33
+ } from './types.js';
34
+
35
+ export { estimateSyllables } from './syllables.js';
36
+
37
+ export {
38
+ buildNarrationScript,
39
+ expectedSyllablesAt,
40
+ wordPosAtExpectedSyllables,
41
+ wordIndexAtChar,
42
+ wordIndexAtTime,
43
+ type BuildScriptOptions,
44
+ } from './script.js';
45
+
46
+ export {
47
+ createBandpass,
48
+ bandpassRun,
49
+ createFeatureState,
50
+ featureStep,
51
+ extractFrameFeatures,
52
+ type BandpassState,
53
+ type FeatureState,
54
+ } from './features.js';
55
+
56
+ export { createVadState, vadStep, type VadState } from './vad.js';
57
+
58
+ export { createNucleiState, nucleiStep, detectSyllableOnsets, type NucleiState } from './nuclei.js';
59
+
60
+ export {
61
+ createPacingState,
62
+ pacingStep,
63
+ reanchorPacing,
64
+ type PacingState,
65
+ type PacingTick,
66
+ } from './pacing.js';
67
+
68
+ export {
69
+ createNarrationSession,
70
+ narrationSessionStep,
71
+ reanchorSession,
72
+ type NarrationSessionConfig,
73
+ type NarrationSessionState,
74
+ } from './session.js';
75
+
76
+ export { traceWordPosAt, downsampleTrace, type NarrationTrace, type TraceSample } from './trace.js';
77
+
78
+ export { alignNarration, type AlignInput } from './align.js';
79
+
80
+ export {
81
+ buildNarrationTimingJson,
82
+ parseNarrationTimingJson,
83
+ type NarrationTimingJsonV3,
84
+ type NarrationTimingBlock,
85
+ type BuildNarrationTimingOptions,
86
+ } from './sidecar.js';
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Syllable-nuclei detection: vowel nuclei show up as peaks in a
3
+ * low-passed amplitude envelope of the speech-band signal.
4
+ *
5
+ * Envelope = one-pole low-pass (≈10 Hz) over √bandEnergy (amplitude
6
+ * domain, so peaks are nuclei rather than energy spikes). A peak is
7
+ * emitted one frame late (local-max needs one frame of lookahead —
8
+ * ~20 ms live latency) and accepted only when: VAD says speaking, it
9
+ * clears the minimum inter-onset spacing, it is prominent relative to
10
+ * the valley since the last accepted peak, and it clears a decaying
11
+ * loudness reference (guards against ripples inside quiet speech).
12
+ */
13
+
14
+ import type { FrameFeatures, NucleiConfig } from './types.js';
15
+ import { DEFAULT_NUCLEI_CONFIG } from './types.js';
16
+
17
+ export interface NucleiState {
18
+ /** One-pole envelope of √bandEnergy. */
19
+ env: number;
20
+ prevEnv: number;
21
+ prevPrevEnv: number;
22
+ /** tSec of the previous frame (the peak-candidate time). */
23
+ prevTSec: number;
24
+ /** Envelope minimum since the last accepted peak. */
25
+ valley: number;
26
+ lastOnsetTSec: number;
27
+ /** Decaying loudness reference. */
28
+ peakRef: number;
29
+ lastTSec: number;
30
+ framesSeen: number;
31
+ }
32
+
33
+ export function createNucleiState(_config?: Partial<NucleiConfig>): NucleiState {
34
+ return {
35
+ env: 0,
36
+ prevEnv: 0,
37
+ prevPrevEnv: 0,
38
+ prevTSec: 0,
39
+ valley: Number.POSITIVE_INFINITY,
40
+ lastOnsetTSec: Number.NEGATIVE_INFINITY,
41
+ peakRef: 0,
42
+ lastTSec: 0,
43
+ framesSeen: 0,
44
+ };
45
+ }
46
+
47
+ /**
48
+ * Pure per-frame step. `onset` is the tSec of a newly accepted syllable
49
+ * nucleus (emitted once, at its peak frame), or null.
50
+ */
51
+ export function nucleiStep(
52
+ state: NucleiState,
53
+ frame: FrameFeatures,
54
+ speaking: boolean,
55
+ config?: Partial<NucleiConfig>,
56
+ ): { state: NucleiState; onset: number | null } {
57
+ const c = { ...DEFAULT_NUCLEI_CONFIG, ...config };
58
+ const amp = Math.sqrt(Math.max(0, frame.bandEnergy));
59
+ const dt = state.framesSeen > 0 ? Math.max(0, frame.tSec - state.lastTSec) : 0;
60
+
61
+ const env =
62
+ state.framesSeen > 0
63
+ ? state.env + (amp - state.env) * (1 - Math.exp(-2 * Math.PI * c.envelopeHz * dt))
64
+ : amp;
65
+ const peakRef = Math.max(env, state.peakRef * Math.exp(-(dt || 0) / c.peakRefTauSec));
66
+
67
+ let onset: number | null = null;
68
+ let valley = state.framesSeen > 0 ? state.valley : env;
69
+ let lastOnsetTSec = state.lastOnsetTSec;
70
+
71
+ // Candidate peak at the PREVIOUS frame: env[t-1] ≥ env[t-2] && env[t-1] > env[t].
72
+ if (
73
+ state.framesSeen >= 2 &&
74
+ state.prevEnv >= state.prevPrevEnv &&
75
+ state.prevEnv > env &&
76
+ speaking &&
77
+ state.prevTSec - lastOnsetTSec >= c.minInterOnsetMs / 1000 &&
78
+ state.prevEnv >= valley * c.prominenceRatio &&
79
+ state.prevEnv >= peakRef * c.minRelPeak
80
+ ) {
81
+ onset = state.prevTSec;
82
+ lastOnsetTSec = state.prevTSec;
83
+ // Re-seed the valley at the accepted peak; it decays via min() below.
84
+ valley = state.prevEnv;
85
+ }
86
+ valley = Math.min(valley, env);
87
+
88
+ return {
89
+ state: {
90
+ env,
91
+ prevEnv: env,
92
+ prevPrevEnv: state.framesSeen > 0 ? state.prevEnv : env,
93
+ prevTSec: frame.tSec,
94
+ valley,
95
+ lastOnsetTSec,
96
+ peakRef,
97
+ lastTSec: frame.tSec,
98
+ framesSeen: state.framesSeen + 1,
99
+ },
100
+ onset,
101
+ };
102
+ }
103
+
104
+ /** Batch wrapper for the offline aligner. `vadFlags[i]` pairs with `frames[i]`. */
105
+ export function detectSyllableOnsets(
106
+ frames: FrameFeatures[],
107
+ vadFlags: boolean[],
108
+ config?: Partial<NucleiConfig>,
109
+ ): number[] {
110
+ let state = createNucleiState(config);
111
+ const onsets: number[] = [];
112
+ for (let i = 0; i < frames.length; i++) {
113
+ const step = nucleiStep(state, frames[i], vadFlags[i] ?? false, config);
114
+ state = step.state;
115
+ if (step.onset !== null) onsets.push(step.onset);
116
+ }
117
+ return onsets;
118
+ }
@@ -0,0 +1,211 @@
1
+ /**
2
+ * The teleprompter pacing controller.
3
+ *
4
+ * A pure, deterministic step function: given the current state, one
5
+ * analysis tick (VAD flag + syllable onsets), and the script, produce
6
+ * the next state. The prompter position (`wordPos`) advances at a
7
+ * velocity that (a) halts within ~250 ms of silence, (b) tracks the
8
+ * reader's detected syllable rate while speaking, and (c) is corrected
9
+ * by a PI loop on cumulative detected-vs-expected syllables so the
10
+ * highlight can't drift arbitrarily far from the voice. Silence near an
11
+ * expected paragraph/block break is legitimate and accrues no error.
12
+ */
13
+
14
+ import { expectedSyllablesAt, wordPosAtExpectedSyllables } from './script.js';
15
+ import type { NarrationScript, PacingConfig } from './types.js';
16
+ import { DEFAULT_PACING_CONFIG } from './types.js';
17
+
18
+ export interface PacingTick {
19
+ tSec: number;
20
+ speaking: boolean;
21
+ /** Syllable onsets detected in this tick (0 or 1 for frame-sized ticks). */
22
+ onsets: number;
23
+ }
24
+
25
+ export interface PacingState {
26
+ /** Fractional word position — the active token is `floor(wordPos)`. */
27
+ wordPos: number;
28
+ /** Current scroll velocity in words per second. */
29
+ velocityWps: number;
30
+ /** EMA of the detected syllable rate (syl/s); 0 until two onsets arrive. */
31
+ emaSylPerSec: number;
32
+ lastOnsetTSec: number | null;
33
+ /** Syllables detected since the last anchor. */
34
+ cumDetectedSyl: number;
35
+ /** Expected cumulative syllables at the last anchor position. */
36
+ anchorExpectedSyl: number;
37
+ /** PI integral of the cumulative-syllable error (syl·s). */
38
+ errIntegral: number;
39
+ /** Continuous silence observed so far (s). */
40
+ silenceSec: number;
41
+ lastTSec: number | null;
42
+ /** True when silent and fully stopped. */
43
+ halted: boolean;
44
+ }
45
+
46
+ export function createPacingState(startWordPos = 0): PacingState {
47
+ return {
48
+ wordPos: startWordPos,
49
+ velocityWps: 0,
50
+ emaSylPerSec: 0,
51
+ lastOnsetTSec: null,
52
+ cumDetectedSyl: 0,
53
+ anchorExpectedSyl: 0,
54
+ errIntegral: 0,
55
+ silenceSec: 0,
56
+ lastTSec: null,
57
+ halted: true,
58
+ };
59
+ }
60
+
61
+ function clamp(value: number, min: number, max: number): number {
62
+ return value < min ? min : value > max ? max : value;
63
+ }
64
+
65
+ /**
66
+ * Mean syllables-per-SPOKEN-word over a short window ahead of the prompter
67
+ * position. Standalone punctuation (0 syllables, `spoken: false`) is
68
+ * excluded so it doesn't deflate the average.
69
+ */
70
+ function localSyllablesPerWord(
71
+ script: NarrationScript,
72
+ wordPos: number,
73
+ windowWords: number,
74
+ ): number {
75
+ const n = script.tokens.length;
76
+ if (n === 0) return 1.4;
77
+ const start = clamp(Math.floor(wordPos), 0, n - 1);
78
+ let sum = 0;
79
+ let count = 0;
80
+ for (let i = start; i < n && count < windowWords; i++) {
81
+ if (!script.tokens[i].spoken) continue;
82
+ sum += script.tokens[i].syllables;
83
+ count += 1;
84
+ }
85
+ // Default to the English average (~1.4) when the window has no words yet.
86
+ return count > 0 ? Math.max(1, sum / count) : 1.4;
87
+ }
88
+
89
+ /** Pure controller step — same inputs always yield the same output state. */
90
+ export function pacingStep(
91
+ state: PacingState,
92
+ tick: PacingTick,
93
+ script: NarrationScript,
94
+ config?: Partial<PacingConfig>,
95
+ ): PacingState {
96
+ const c = { ...DEFAULT_PACING_CONFIG, ...config };
97
+ const baseWps = c.baseWpm / 60;
98
+ const dt = clamp(tick.tSec - (state.lastTSec ?? tick.tSec), 0, 0.25);
99
+
100
+ // 1. Onset bookkeeping: cumulative count + inter-onset-interval rate EMA.
101
+ let emaSylPerSec = state.emaSylPerSec;
102
+ let lastOnsetTSec = state.lastOnsetTSec;
103
+ let cumDetectedSyl = state.cumDetectedSyl;
104
+ for (let k = 0; k < tick.onsets; k++) {
105
+ if (lastOnsetTSec !== null) {
106
+ const ioi = tick.tSec - lastOnsetTSec;
107
+ if (ioi > 0) {
108
+ const instRate = clamp(1 / ioi, 0.5, 12);
109
+ const alpha = 1 - Math.exp(-ioi / c.rateEmaTauSec);
110
+ emaSylPerSec =
111
+ emaSylPerSec === 0 ? instRate : emaSylPerSec + (instRate - emaSylPerSec) * alpha;
112
+ }
113
+ }
114
+ lastOnsetTSec = tick.tSec;
115
+ cumDetectedSyl += 1;
116
+ }
117
+
118
+ // 2–3. Cruise velocity: BLEND the user's set pace with the voice-derived
119
+ // rate. The old design used `baseWps · clamp(voiceWps / baseWps)`, in
120
+ // which baseWps algebraically cancels in the unclamped range — so the WPM
121
+ // slider did nothing and a chronically under-counting detector dragged
122
+ // the prompter slow with no way to compensate. Blending keeps the set
123
+ // pace as a real feedforward term (WPM always felt), while the voice
124
+ // steers within a band. Then clamp to a band around the set pace so
125
+ // neither term alone can stall or run away.
126
+ const sylPerWordLocal = localSyllablesPerWord(script, state.wordPos, c.sylWindowWords);
127
+ const voiceWps = emaSylPerSec > 0 ? emaSylPerSec / sylPerWordLocal : baseWps;
128
+ const cruise = clamp(
129
+ c.voiceBlend * voiceWps + (1 - c.voiceBlend) * baseWps,
130
+ baseWps * c.minRateMult,
131
+ baseWps * c.maxRateMult,
132
+ );
133
+
134
+ // 4–5. FORWARD-ONLY position correction. `err` compares where the
135
+ // prompter is (expected syllables at wordPos) against how many syllables
136
+ // the voice has actually delivered. err < 0 → the reader is AHEAD of the
137
+ // prompter → speed up to catch them. err > 0 → the prompter looks ahead
138
+ // of the reader, but this is exactly the signal a chronically
139
+ // under-counting syllable detector produces even when the prompter is
140
+ // really BEHIND — so we deliberately do NOT slow or snap backward on it.
141
+ // (The old symmetric PI pinned the prompter to the DETECTED count, so a
142
+ // detector catching half the syllables parked the prompter at half the
143
+ // reader's true position — the lag the user saw.) Slowing down is instead
144
+ // handled honestly by the cruise blend (a slow voice lowers voiceWps) and
145
+ // by halt-on-silence.
146
+ const err =
147
+ expectedSyllablesAt(script, state.wordPos) - (state.anchorExpectedSyl + cumDetectedSyl);
148
+ let errIntegral = clamp(Math.min(0, state.errIntegral + err * dt), -c.intClamp, 0);
149
+ const boost = err < 0 ? clamp(c.kP * -err + c.kI * -errIntegral, 0, c.maxCorrection) : 0;
150
+
151
+ // 6. Velocity: track while speaking, decay to a halt in silence.
152
+ let velocityWps = state.velocityWps;
153
+ let silenceSec = state.silenceSec;
154
+ if (tick.speaking) {
155
+ silenceSec = 0;
156
+ const target = Math.max(0, cruise * (1 + boost));
157
+ velocityWps += (target - velocityWps) * (1 - Math.exp(-dt / c.velSlewTauSec));
158
+ } else {
159
+ silenceSec += dt;
160
+ velocityWps *= Math.exp(-dt / c.haltTauSec);
161
+ if (velocityWps < 0.02) velocityWps = 0;
162
+ }
163
+
164
+ // 7. Hard resync forward only: when the reader has clearly outrun the
165
+ // prompter by more than a paragraph, jump ahead to catch up. Never jump
166
+ // backward (a false "prompter ahead" from under-counting must not yank
167
+ // the highlight back).
168
+ let wordPos = state.wordPos;
169
+ if (err < -c.resyncSyllables) {
170
+ wordPos = Math.max(
171
+ wordPos,
172
+ wordPosAtExpectedSyllables(script, state.anchorExpectedSyl + cumDetectedSyl),
173
+ );
174
+ errIntegral = 0;
175
+ }
176
+
177
+ // 8. Integrate.
178
+ wordPos = clamp(wordPos + velocityWps * dt, 0, script.tokens.length);
179
+
180
+ return {
181
+ wordPos,
182
+ velocityWps,
183
+ emaSylPerSec,
184
+ lastOnsetTSec,
185
+ cumDetectedSyl,
186
+ anchorExpectedSyl: state.anchorExpectedSyl,
187
+ errIntegral,
188
+ silenceSec,
189
+ lastTSec: tick.tSec,
190
+ halted: !tick.speaking && velocityWps === 0,
191
+ };
192
+ }
193
+
194
+ /**
195
+ * Re-anchor after a manual nudge/scroll: the new position becomes the
196
+ * zero-error reference. The learned rate EMA survives.
197
+ */
198
+ export function reanchorPacing(
199
+ state: PacingState,
200
+ wordPos: number,
201
+ script: NarrationScript,
202
+ ): PacingState {
203
+ const pos = clamp(wordPos, 0, script.tokens.length);
204
+ return {
205
+ ...state,
206
+ wordPos: pos,
207
+ anchorExpectedSyl: expectedSyllablesAt(script, pos),
208
+ cumDetectedSyl: 0,
209
+ errIntegral: 0,
210
+ };
211
+ }