@open-take/compositor 0.5.3 → 0.6.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 (439) hide show
  1. package/dist/cdp-CzT5BKNY.js +3 -0
  2. package/dist/cdp-QXbQfXna.js +373 -0
  3. package/dist/cdp-QXbQfXna.js.map +1 -0
  4. package/dist/index.d.ts +4327 -195
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +26282 -160
  7. package/dist/index.js.map +1 -1
  8. package/dist/server-841PMF2H.js +163 -0
  9. package/dist/server-841PMF2H.js.map +1 -0
  10. package/dist/server-C2aVv4-t.js +3 -0
  11. package/kit/audio.mjs +2366 -0
  12. package/kit/camera.js +587 -0
  13. package/kit/cursor.js +264 -0
  14. package/kit/cut.js +427 -0
  15. package/kit/draw.js +346 -0
  16. package/kit/look.js +589 -0
  17. package/kit/map.js +170 -0
  18. package/kit/media.js +3568 -0
  19. package/kit/motion.js +1115 -0
  20. package/kit/seams.js +1006 -0
  21. package/kit/stage.js +923 -0
  22. package/kit/time.js +812 -0
  23. package/kit/world.js +1072 -0
  24. package/package.json +7 -3
  25. package/src/ffmpeg.ts +63 -0
  26. package/src/film/beats.ts +1285 -0
  27. package/src/film/carry.ts +221 -0
  28. package/src/film/changes.ts +330 -0
  29. package/src/film/check.ts +996 -0
  30. package/src/film/clock.ts +2530 -0
  31. package/src/film/components-probe.ts +809 -0
  32. package/src/film/components.ts +1566 -0
  33. package/src/film/frames.ts +389 -0
  34. package/src/film/gallery.ts +3276 -0
  35. package/src/film/kit.ts +515 -0
  36. package/src/film/layout.ts +701 -0
  37. package/src/film/listen.ts +1979 -0
  38. package/src/film/look.ts +3829 -0
  39. package/src/film/materials.ts +976 -0
  40. package/src/film/moving.ts +248 -0
  41. package/src/film/part-files.ts +729 -0
  42. package/src/film/picture.ts +74 -0
  43. package/src/film/probe-text.ts +843 -0
  44. package/src/film/probe.ts +3456 -0
  45. package/src/film/provenance.ts +596 -0
  46. package/src/film/render.ts +2447 -0
  47. package/src/film/report.ts +1631 -0
  48. package/src/film/sheet.ts +156 -0
  49. package/src/film/study-declared.ts +123 -0
  50. package/src/film/study-picture.ts +791 -0
  51. package/src/film/study-sound.ts +416 -0
  52. package/src/film/study.ts +864 -0
  53. package/src/film/tuning.ts +155 -0
  54. package/src/film/viewer.ts +174 -0
  55. package/src/html/cdp.ts +575 -0
  56. package/src/html/server.ts +208 -0
  57. package/src/index.ts +202 -0
  58. package/src/launch-render.ts +3 -2
  59. package/src/math.ts +3 -3
  60. package/src/mjpeg-matroska.ts +228 -0
  61. package/src/render.ts +6 -4
  62. package/src/state-diff.ts +215 -0
  63. package/src/state-index.ts +99 -0
  64. package/src/types.ts +59 -1
  65. package/starter/PLAN.md +84 -0
  66. package/starter/START.md +460 -0
  67. package/starter/lib/anim.js +760 -0
  68. package/starter/lib/devices.js +1402 -0
  69. package/starter/lib/handoff.js +421 -0
  70. package/starter/lib/hud.js +1879 -0
  71. package/starter/lib/measure.mjs +154 -0
  72. package/starter/lib/moves.js +1095 -0
  73. package/starter/lib/palette.mjs +803 -0
  74. package/starter/lib/physics-seeds.mjs +198 -0
  75. package/starter/lib/physics.js +738 -0
  76. package/starter/lib/sampler.mjs +242 -0
  77. package/starter/lib/solid.js +727 -0
  78. package/starter/lib/space.js +1227 -0
  79. package/starter/lib/swarm.js +1398 -0
  80. package/starter/reference/motion.md +276 -0
  81. package/starter/reference/structure.md +466 -0
  82. package/starter/reference/travel/motion.md +433 -0
  83. package/starter/reference/travel/sound.md +241 -0
  84. package/starter/reference/travel/structure.md +518 -0
  85. package/starter/samples/NOTICE.txt +55 -0
  86. package/starter/samples/celli/celli_24_1.opus +0 -0
  87. package/starter/samples/celli/celli_24_3.opus +0 -0
  88. package/starter/samples/celli/celli_28_1.opus +0 -0
  89. package/starter/samples/celli/celli_28_3.opus +0 -0
  90. package/starter/samples/celli/celli_31_1.opus +0 -0
  91. package/starter/samples/celli/celli_31_3.opus +0 -0
  92. package/starter/samples/celli/celli_35_1.opus +0 -0
  93. package/starter/samples/celli/celli_35_3.opus +0 -0
  94. package/starter/samples/celli/celli_38_1.opus +0 -0
  95. package/starter/samples/celli/celli_38_3.opus +0 -0
  96. package/starter/samples/celli/celli_41_1.opus +0 -0
  97. package/starter/samples/celli/celli_41_3.opus +0 -0
  98. package/starter/samples/celli/celli_45_1.opus +0 -0
  99. package/starter/samples/celli/celli_45_3.opus +0 -0
  100. package/starter/samples/celli/celli_48_1.opus +0 -0
  101. package/starter/samples/celli/celli_48_3.opus +0 -0
  102. package/starter/samples/celli/celli_52_1.opus +0 -0
  103. package/starter/samples/celli/celli_52_3.opus +0 -0
  104. package/starter/samples/celli/celli_55_1.opus +0 -0
  105. package/starter/samples/celli/celli_55_3.opus +0 -0
  106. package/starter/samples/celli/celli_59_1.opus +0 -0
  107. package/starter/samples/celli/celli_59_3.opus +0 -0
  108. package/starter/samples/celli/celli_62_1.opus +0 -0
  109. package/starter/samples/celli/celli_62_3.opus +0 -0
  110. package/starter/samples/celli/celli_65_1.opus +0 -0
  111. package/starter/samples/celli/celli_65_3.opus +0 -0
  112. package/starter/samples/crash/crash_f_1.flac +0 -0
  113. package/starter/samples/crash/crash_fff_1.flac +0 -0
  114. package/starter/samples/ebass/ebass_0_x.flac +0 -0
  115. package/starter/samples/ebass/ebass_10_x.flac +0 -0
  116. package/starter/samples/ebass/ebass_11_x.flac +0 -0
  117. package/starter/samples/ebass/ebass_1_x.flac +0 -0
  118. package/starter/samples/ebass/ebass_2_x.flac +0 -0
  119. package/starter/samples/ebass/ebass_3_x.flac +0 -0
  120. package/starter/samples/ebass/ebass_4_x.flac +0 -0
  121. package/starter/samples/ebass/ebass_5_x.flac +0 -0
  122. package/starter/samples/ebass/ebass_6_x.flac +0 -0
  123. package/starter/samples/ebass/ebass_7_x.flac +0 -0
  124. package/starter/samples/ebass/ebass_8_x.flac +0 -0
  125. package/starter/samples/ebass/ebass_9_x.flac +0 -0
  126. package/starter/samples/ek_clap/ek_clap_1_1.flac +0 -0
  127. package/starter/samples/ek_hat/ek_hat_1_1.flac +0 -0
  128. package/starter/samples/ek_hat/ek_hat_1_2.flac +0 -0
  129. package/starter/samples/ek_kick/ek_kick_1_1.flac +0 -0
  130. package/starter/samples/ek_kick/ek_kick_1_2.flac +0 -0
  131. package/starter/samples/glock/glock_67_x.flac +0 -0
  132. package/starter/samples/glock/glock_72_x.flac +0 -0
  133. package/starter/samples/glock/glock_79_x.flac +0 -0
  134. package/starter/samples/glock/glock_84_x.flac +0 -0
  135. package/starter/samples/glock/glock_91_x.flac +0 -0
  136. package/starter/samples/glock/glock_96_x.flac +0 -0
  137. package/starter/samples/harp/harp_101_f.opus +0 -0
  138. package/starter/samples/harp/harp_28_f.opus +0 -0
  139. package/starter/samples/harp/harp_31_mp.opus +0 -0
  140. package/starter/samples/harp/harp_35_mf.opus +0 -0
  141. package/starter/samples/harp/harp_38_mf.opus +0 -0
  142. package/starter/samples/harp/harp_41_mf.opus +0 -0
  143. package/starter/samples/harp/harp_45_mf.opus +0 -0
  144. package/starter/samples/harp/harp_48_mf.opus +0 -0
  145. package/starter/samples/harp/harp_52_mf.opus +0 -0
  146. package/starter/samples/harp/harp_55_mf.opus +0 -0
  147. package/starter/samples/harp/harp_59_mf.opus +0 -0
  148. package/starter/samples/harp/harp_62_mf.opus +0 -0
  149. package/starter/samples/harp/harp_65_mf.opus +0 -0
  150. package/starter/samples/harp/harp_69_mf.opus +0 -0
  151. package/starter/samples/harp/harp_72_mf.opus +0 -0
  152. package/starter/samples/harp/harp_76_mf.opus +0 -0
  153. package/starter/samples/harp/harp_79_mf.opus +0 -0
  154. package/starter/samples/harp/harp_83_mf.opus +0 -0
  155. package/starter/samples/harp/harp_86_mf.opus +0 -0
  156. package/starter/samples/harp/harp_89_mf.opus +0 -0
  157. package/starter/samples/harp/harp_93_mf.opus +0 -0
  158. package/starter/samples/harp/harp_95_mf.opus +0 -0
  159. package/starter/samples/harp/harp_98_f.opus +0 -0
  160. package/starter/samples/manifest.json +2951 -0
  161. package/starter/samples/marimba/marimba_29_x.flac +0 -0
  162. package/starter/samples/marimba/marimba_36_x.flac +0 -0
  163. package/starter/samples/marimba/marimba_43_x.flac +0 -0
  164. package/starter/samples/marimba/marimba_47_x.flac +0 -0
  165. package/starter/samples/marimba/marimba_53_x.flac +0 -0
  166. package/starter/samples/marimba/marimba_60_x.flac +0 -0
  167. package/starter/samples/marimba/marimba_67_x.flac +0 -0
  168. package/starter/samples/marimba/marimba_71_x.flac +0 -0
  169. package/starter/samples/marimba/marimba_77_x.flac +0 -0
  170. package/starter/samples/marimba/marimba_84_x.flac +0 -0
  171. package/starter/samples/piano/piano_102_12.opus +0 -0
  172. package/starter/samples/piano/piano_102_16.opus +0 -0
  173. package/starter/samples/piano/piano_102_4.opus +0 -0
  174. package/starter/samples/piano/piano_102_8.opus +0 -0
  175. package/starter/samples/piano/piano_105_12.opus +0 -0
  176. package/starter/samples/piano/piano_105_16.opus +0 -0
  177. package/starter/samples/piano/piano_105_4.opus +0 -0
  178. package/starter/samples/piano/piano_105_8.opus +0 -0
  179. package/starter/samples/piano/piano_108_12.opus +0 -0
  180. package/starter/samples/piano/piano_108_16.opus +0 -0
  181. package/starter/samples/piano/piano_108_4.opus +0 -0
  182. package/starter/samples/piano/piano_108_8.opus +0 -0
  183. package/starter/samples/piano/piano_21_12.opus +0 -0
  184. package/starter/samples/piano/piano_21_16.opus +0 -0
  185. package/starter/samples/piano/piano_21_4.opus +0 -0
  186. package/starter/samples/piano/piano_21_8.opus +0 -0
  187. package/starter/samples/piano/piano_24_12.opus +0 -0
  188. package/starter/samples/piano/piano_24_16.opus +0 -0
  189. package/starter/samples/piano/piano_24_4.opus +0 -0
  190. package/starter/samples/piano/piano_24_8.opus +0 -0
  191. package/starter/samples/piano/piano_27_12.opus +0 -0
  192. package/starter/samples/piano/piano_27_16.opus +0 -0
  193. package/starter/samples/piano/piano_27_4.opus +0 -0
  194. package/starter/samples/piano/piano_27_8.opus +0 -0
  195. package/starter/samples/piano/piano_30_12.opus +0 -0
  196. package/starter/samples/piano/piano_30_16.opus +0 -0
  197. package/starter/samples/piano/piano_30_4.opus +0 -0
  198. package/starter/samples/piano/piano_30_8.opus +0 -0
  199. package/starter/samples/piano/piano_33_12.opus +0 -0
  200. package/starter/samples/piano/piano_33_16.opus +0 -0
  201. package/starter/samples/piano/piano_33_4.opus +0 -0
  202. package/starter/samples/piano/piano_33_8.opus +0 -0
  203. package/starter/samples/piano/piano_36_12.opus +0 -0
  204. package/starter/samples/piano/piano_36_16.opus +0 -0
  205. package/starter/samples/piano/piano_36_4.opus +0 -0
  206. package/starter/samples/piano/piano_36_8.opus +0 -0
  207. package/starter/samples/piano/piano_39_12.opus +0 -0
  208. package/starter/samples/piano/piano_39_16.opus +0 -0
  209. package/starter/samples/piano/piano_39_4.opus +0 -0
  210. package/starter/samples/piano/piano_39_8.opus +0 -0
  211. package/starter/samples/piano/piano_42_12.opus +0 -0
  212. package/starter/samples/piano/piano_42_16.opus +0 -0
  213. package/starter/samples/piano/piano_42_4.opus +0 -0
  214. package/starter/samples/piano/piano_42_8.opus +0 -0
  215. package/starter/samples/piano/piano_45_12.opus +0 -0
  216. package/starter/samples/piano/piano_45_16.opus +0 -0
  217. package/starter/samples/piano/piano_45_4.opus +0 -0
  218. package/starter/samples/piano/piano_45_8.opus +0 -0
  219. package/starter/samples/piano/piano_48_12.opus +0 -0
  220. package/starter/samples/piano/piano_48_16.opus +0 -0
  221. package/starter/samples/piano/piano_48_4.opus +0 -0
  222. package/starter/samples/piano/piano_48_8.opus +0 -0
  223. package/starter/samples/piano/piano_51_12.opus +0 -0
  224. package/starter/samples/piano/piano_51_16.opus +0 -0
  225. package/starter/samples/piano/piano_51_4.opus +0 -0
  226. package/starter/samples/piano/piano_51_8.opus +0 -0
  227. package/starter/samples/piano/piano_54_12.opus +0 -0
  228. package/starter/samples/piano/piano_54_16.opus +0 -0
  229. package/starter/samples/piano/piano_54_4.opus +0 -0
  230. package/starter/samples/piano/piano_54_8.opus +0 -0
  231. package/starter/samples/piano/piano_57_12.opus +0 -0
  232. package/starter/samples/piano/piano_57_16.opus +0 -0
  233. package/starter/samples/piano/piano_57_4.opus +0 -0
  234. package/starter/samples/piano/piano_57_8.opus +0 -0
  235. package/starter/samples/piano/piano_60_12.opus +0 -0
  236. package/starter/samples/piano/piano_60_16.opus +0 -0
  237. package/starter/samples/piano/piano_60_4.opus +0 -0
  238. package/starter/samples/piano/piano_60_8.opus +0 -0
  239. package/starter/samples/piano/piano_63_12.opus +0 -0
  240. package/starter/samples/piano/piano_63_16.opus +0 -0
  241. package/starter/samples/piano/piano_63_4.opus +0 -0
  242. package/starter/samples/piano/piano_63_8.opus +0 -0
  243. package/starter/samples/piano/piano_66_12.opus +0 -0
  244. package/starter/samples/piano/piano_66_16.opus +0 -0
  245. package/starter/samples/piano/piano_66_4.opus +0 -0
  246. package/starter/samples/piano/piano_66_8.opus +0 -0
  247. package/starter/samples/piano/piano_69_12.opus +0 -0
  248. package/starter/samples/piano/piano_69_16.opus +0 -0
  249. package/starter/samples/piano/piano_69_4.opus +0 -0
  250. package/starter/samples/piano/piano_69_8.opus +0 -0
  251. package/starter/samples/piano/piano_72_12.opus +0 -0
  252. package/starter/samples/piano/piano_72_16.opus +0 -0
  253. package/starter/samples/piano/piano_72_4.opus +0 -0
  254. package/starter/samples/piano/piano_72_8.opus +0 -0
  255. package/starter/samples/piano/piano_75_12.opus +0 -0
  256. package/starter/samples/piano/piano_75_16.opus +0 -0
  257. package/starter/samples/piano/piano_75_4.opus +0 -0
  258. package/starter/samples/piano/piano_75_8.opus +0 -0
  259. package/starter/samples/piano/piano_78_12.opus +0 -0
  260. package/starter/samples/piano/piano_78_16.opus +0 -0
  261. package/starter/samples/piano/piano_78_4.opus +0 -0
  262. package/starter/samples/piano/piano_78_8.opus +0 -0
  263. package/starter/samples/piano/piano_81_12.opus +0 -0
  264. package/starter/samples/piano/piano_81_16.opus +0 -0
  265. package/starter/samples/piano/piano_81_4.opus +0 -0
  266. package/starter/samples/piano/piano_81_8.opus +0 -0
  267. package/starter/samples/piano/piano_84_12.opus +0 -0
  268. package/starter/samples/piano/piano_84_16.opus +0 -0
  269. package/starter/samples/piano/piano_84_4.opus +0 -0
  270. package/starter/samples/piano/piano_84_8.opus +0 -0
  271. package/starter/samples/piano/piano_87_12.opus +0 -0
  272. package/starter/samples/piano/piano_87_16.opus +0 -0
  273. package/starter/samples/piano/piano_87_4.opus +0 -0
  274. package/starter/samples/piano/piano_87_8.opus +0 -0
  275. package/starter/samples/piano/piano_90_12.opus +0 -0
  276. package/starter/samples/piano/piano_90_16.opus +0 -0
  277. package/starter/samples/piano/piano_90_4.opus +0 -0
  278. package/starter/samples/piano/piano_90_8.opus +0 -0
  279. package/starter/samples/piano/piano_93_12.opus +0 -0
  280. package/starter/samples/piano/piano_93_16.opus +0 -0
  281. package/starter/samples/piano/piano_93_4.opus +0 -0
  282. package/starter/samples/piano/piano_93_8.opus +0 -0
  283. package/starter/samples/piano/piano_96_12.opus +0 -0
  284. package/starter/samples/piano/piano_96_16.opus +0 -0
  285. package/starter/samples/piano/piano_96_4.opus +0 -0
  286. package/starter/samples/piano/piano_96_8.opus +0 -0
  287. package/starter/samples/piano/piano_99_12.opus +0 -0
  288. package/starter/samples/piano/piano_99_16.opus +0 -0
  289. package/starter/samples/piano/piano_99_4.opus +0 -0
  290. package/starter/samples/piano/piano_99_8.opus +0 -0
  291. package/starter/samples/piano/piano_rel_102_x.opus +0 -0
  292. package/starter/samples/piano/piano_rel_105_x.opus +0 -0
  293. package/starter/samples/piano/piano_rel_108_x.opus +0 -0
  294. package/starter/samples/piano/piano_rel_21_x.opus +0 -0
  295. package/starter/samples/piano/piano_rel_24_x.opus +0 -0
  296. package/starter/samples/piano/piano_rel_27_x.opus +0 -0
  297. package/starter/samples/piano/piano_rel_30_x.opus +0 -0
  298. package/starter/samples/piano/piano_rel_33_x.opus +0 -0
  299. package/starter/samples/piano/piano_rel_36_x.opus +0 -0
  300. package/starter/samples/piano/piano_rel_39_x.opus +0 -0
  301. package/starter/samples/piano/piano_rel_42_x.opus +0 -0
  302. package/starter/samples/piano/piano_rel_45_x.opus +0 -0
  303. package/starter/samples/piano/piano_rel_48_x.opus +0 -0
  304. package/starter/samples/piano/piano_rel_51_x.opus +0 -0
  305. package/starter/samples/piano/piano_rel_54_x.opus +0 -0
  306. package/starter/samples/piano/piano_rel_57_x.opus +0 -0
  307. package/starter/samples/piano/piano_rel_60_x.opus +0 -0
  308. package/starter/samples/piano/piano_rel_63_x.opus +0 -0
  309. package/starter/samples/piano/piano_rel_66_x.opus +0 -0
  310. package/starter/samples/piano/piano_rel_69_x.opus +0 -0
  311. package/starter/samples/piano/piano_rel_72_x.opus +0 -0
  312. package/starter/samples/piano/piano_rel_75_x.opus +0 -0
  313. package/starter/samples/piano/piano_rel_78_x.opus +0 -0
  314. package/starter/samples/piano/piano_rel_81_x.opus +0 -0
  315. package/starter/samples/piano/piano_rel_84_x.opus +0 -0
  316. package/starter/samples/piano/piano_rel_87_x.opus +0 -0
  317. package/starter/samples/piano/piano_rel_90_x.opus +0 -0
  318. package/starter/samples/piano/piano_rel_93_x.opus +0 -0
  319. package/starter/samples/piano/piano_rel_96_x.opus +0 -0
  320. package/starter/samples/piano/piano_rel_99_x.opus +0 -0
  321. package/starter/samples/pizz/pizz_24_2.flac +0 -0
  322. package/starter/samples/pizz/pizz_28_2.flac +0 -0
  323. package/starter/samples/pizz/pizz_31_2.flac +0 -0
  324. package/starter/samples/pizz/pizz_35_2.flac +0 -0
  325. package/starter/samples/pizz/pizz_38_2.flac +0 -0
  326. package/starter/samples/pizz/pizz_41_2.flac +0 -0
  327. package/starter/samples/pizz/pizz_45_2.flac +0 -0
  328. package/starter/samples/pizz/pizz_48_2.flac +0 -0
  329. package/starter/samples/pizz/pizz_52_2.flac +0 -0
  330. package/starter/samples/pizz/pizz_57_2.flac +0 -0
  331. package/starter/samples/pizz/pizz_60_2.flac +0 -0
  332. package/starter/samples/pizz/pizz_64_2.flac +0 -0
  333. package/starter/samples/pizz/pizz_67_2.flac +0 -0
  334. package/starter/samples/pizz/pizz_71_2.flac +0 -0
  335. package/starter/samples/pizz/pizz_74_2.flac +0 -0
  336. package/starter/samples/pk_hat/pk_hat_2_1.flac +0 -0
  337. package/starter/samples/pk_hat/pk_hat_2_2.flac +0 -0
  338. package/starter/samples/pk_hat/pk_hat_6_1.flac +0 -0
  339. package/starter/samples/pk_hat/pk_hat_6_2.flac +0 -0
  340. package/starter/samples/pk_kick/pk_kick_3_1.flac +0 -0
  341. package/starter/samples/pk_kick/pk_kick_3_2.flac +0 -0
  342. package/starter/samples/pk_kick/pk_kick_7_1.flac +0 -0
  343. package/starter/samples/pk_kick/pk_kick_7_2.flac +0 -0
  344. package/starter/samples/pk_ohat/pk_ohat_3_1.flac +0 -0
  345. package/starter/samples/pk_ohat/pk_ohat_3_2.flac +0 -0
  346. package/starter/samples/pk_ohat/pk_ohat_6_1.flac +0 -0
  347. package/starter/samples/pk_ohat/pk_ohat_6_2.flac +0 -0
  348. package/starter/samples/pk_rim/pk_rim_2_1.flac +0 -0
  349. package/starter/samples/pk_rim/pk_rim_2_2.flac +0 -0
  350. package/starter/samples/pk_rim/pk_rim_5_1.flac +0 -0
  351. package/starter/samples/pk_rim/pk_rim_5_2.flac +0 -0
  352. package/starter/samples/pk_snare/pk_snare_3_1.flac +0 -0
  353. package/starter/samples/pk_snare/pk_snare_3_2.flac +0 -0
  354. package/starter/samples/pk_snare/pk_snare_7_1.flac +0 -0
  355. package/starter/samples/pk_snare/pk_snare_7_2.flac +0 -0
  356. package/starter/samples/shaker/shaker_1_1.flac +0 -0
  357. package/starter/samples/shaker/shaker_2_1.flac +0 -0
  358. package/starter/samples/snap/snap_r_1.flac +0 -0
  359. package/starter/samples/snap/snap_r_2.flac +0 -0
  360. package/starter/samples/snap/snap_r_3.flac +0 -0
  361. package/starter/samples/snap/snap_r_4.flac +0 -0
  362. package/starter/samples/snap/snap_r_5.flac +0 -0
  363. package/starter/samples/snap/snap_r_6.flac +0 -0
  364. package/starter/samples/tom/tom_3_1.flac +0 -0
  365. package/starter/samples/tom/tom_3_2.flac +0 -0
  366. package/starter/samples/tom/tom_4_1.flac +0 -0
  367. package/starter/samples/tom/tom_4_2.flac +0 -0
  368. package/starter/samples/vibes/vibes_41_1.opus +0 -0
  369. package/starter/samples/vibes/vibes_41_2.opus +0 -0
  370. package/starter/samples/vibes/vibes_45_1.opus +0 -0
  371. package/starter/samples/vibes/vibes_45_2.opus +0 -0
  372. package/starter/samples/vibes/vibes_48_1.opus +0 -0
  373. package/starter/samples/vibes/vibes_48_2.opus +0 -0
  374. package/starter/samples/vibes/vibes_52_1.opus +0 -0
  375. package/starter/samples/vibes/vibes_52_2.opus +0 -0
  376. package/starter/samples/vibes/vibes_55_1.opus +0 -0
  377. package/starter/samples/vibes/vibes_55_2.opus +0 -0
  378. package/starter/samples/vibes/vibes_59_1.opus +0 -0
  379. package/starter/samples/vibes/vibes_59_2.opus +0 -0
  380. package/starter/samples/vibes/vibes_62_1.opus +0 -0
  381. package/starter/samples/vibes/vibes_62_2.opus +0 -0
  382. package/starter/samples/vibes/vibes_65_1.opus +0 -0
  383. package/starter/samples/vibes/vibes_65_2.opus +0 -0
  384. package/starter/samples/vibes/vibes_69_1.opus +0 -0
  385. package/starter/samples/vibes/vibes_69_2.opus +0 -0
  386. package/starter/samples/vibes/vibes_72_1.opus +0 -0
  387. package/starter/samples/vibes/vibes_72_2.opus +0 -0
  388. package/starter/samples/vibes/vibes_76_1.opus +0 -0
  389. package/starter/samples/vibes/vibes_76_2.opus +0 -0
  390. package/starter/samples/violas/violas_36_1.opus +0 -0
  391. package/starter/samples/violas/violas_36_2.opus +0 -0
  392. package/starter/samples/violas/violas_38_1.opus +0 -0
  393. package/starter/samples/violas/violas_38_2.opus +0 -0
  394. package/starter/samples/violas/violas_40_1.opus +0 -0
  395. package/starter/samples/violas/violas_40_2.opus +0 -0
  396. package/starter/samples/violas/violas_43_1.opus +0 -0
  397. package/starter/samples/violas/violas_43_2.opus +0 -0
  398. package/starter/samples/violas/violas_47_1.opus +0 -0
  399. package/starter/samples/violas/violas_47_2.opus +0 -0
  400. package/starter/samples/violas/violas_50_1.opus +0 -0
  401. package/starter/samples/violas/violas_50_2.opus +0 -0
  402. package/starter/samples/violas/violas_53_1.opus +0 -0
  403. package/starter/samples/violas/violas_53_2.opus +0 -0
  404. package/starter/samples/violas/violas_57_1.opus +0 -0
  405. package/starter/samples/violas/violas_57_2.opus +0 -0
  406. package/starter/samples/violas/violas_60_1.opus +0 -0
  407. package/starter/samples/violas/violas_60_2.opus +0 -0
  408. package/starter/samples/violas/violas_64_1.opus +0 -0
  409. package/starter/samples/violas/violas_64_2.opus +0 -0
  410. package/starter/samples/violas/violas_67_1.opus +0 -0
  411. package/starter/samples/violas/violas_67_2.opus +0 -0
  412. package/starter/samples/violas/violas_71_1.opus +0 -0
  413. package/starter/samples/violas/violas_71_2.opus +0 -0
  414. package/starter/samples/violas/violas_74_1.opus +0 -0
  415. package/starter/samples/violas/violas_74_2.opus +0 -0
  416. package/starter/samples/violins/violins_43_1.opus +0 -0
  417. package/starter/samples/violins/violins_43_2.opus +0 -0
  418. package/starter/samples/violins/violins_45_1.opus +0 -0
  419. package/starter/samples/violins/violins_45_2.opus +0 -0
  420. package/starter/samples/violins/violins_47_1.opus +0 -0
  421. package/starter/samples/violins/violins_47_2.opus +0 -0
  422. package/starter/samples/violins/violins_50_1.opus +0 -0
  423. package/starter/samples/violins/violins_50_2.opus +0 -0
  424. package/starter/samples/violins/violins_54_1.opus +0 -0
  425. package/starter/samples/violins/violins_54_2.opus +0 -0
  426. package/starter/samples/violins/violins_57_1.opus +0 -0
  427. package/starter/samples/violins/violins_57_2.opus +0 -0
  428. package/starter/samples/violins/violins_60_1.opus +0 -0
  429. package/starter/samples/violins/violins_60_2.opus +0 -0
  430. package/starter/samples/violins/violins_64_1.opus +0 -0
  431. package/starter/samples/violins/violins_64_2.opus +0 -0
  432. package/starter/samples/violins/violins_67_1.opus +0 -0
  433. package/starter/samples/violins/violins_67_2.opus +0 -0
  434. package/starter/samples/violins/violins_71_1.opus +0 -0
  435. package/starter/samples/violins/violins_71_2.opus +0 -0
  436. package/starter/samples/violins/violins_74_1.opus +0 -0
  437. package/starter/samples/violins/violins_74_2.opus +0 -0
  438. package/starter/samples/woodblock/woodblock_f_1.flac +0 -0
  439. package/starter/samples/woodblock/woodblock_f_2.flac +0 -0
package/kit/audio.mjs ADDED
@@ -0,0 +1,2366 @@
1
+ // @ts-check
2
+ // Sound for a film — open-take's film kit, for the score's Node script (no
3
+ // dependencies). The music is yours: there are no melodies, chords,
4
+ // instruments, presets or samples here. What is here is the plumbing that
5
+ // eleven of twelve films wrote again for themselves — buffers and a mix, an
6
+ // envelope, filters, a reverb, a sidechain, seeded numbers, a WAV writer —
7
+ // without the ways theirs went wrong:
8
+ //
9
+ // - loudness measured the way ITU-R BS.1770-4 (EBU R128) measures it, and
10
+ // `normalize`, which lands the mix on −16 LUFS with its true peak under
11
+ // −1 dBTP. Guessing from the sample peak or the RMS shipped films at
12
+ // −12.2 LUFS (true peak −0.4) and −17.8 LUFS;
13
+ // - an envelope that releases from the level it reached. One that releases
14
+ // from the sustain level jumps when a note ends mid-decay, and the jump
15
+ // is a click;
16
+ // - a filter that is held below Nyquist, and that stops, naming its track,
17
+ // once its state is no longer a number. A film's filter blew up at a high
18
+ // cutoff and was found by ear, as two pops;
19
+ // - `diagnose`, which checks one stem at a time for what a mix hides: NaN,
20
+ // clipping, clicks (a note cut short, a release from the wrong level,
21
+ // saws started in phase), DC. Mark intended transients on a bus or by time;
22
+ // the attack of a recording played with `recorded` is left out;
23
+ // - `hitOf` finds the fastest rise. `play` with `align: "hit"` lands it on
24
+ // the picture. `"onset"` lines up the start of the attack and prints a
25
+ // warning when the hit would land more than 50 ms away;
26
+ // - `subIn`, `dropOut`, `filterOpen` and `filterClose` bring a band's level
27
+ // or the bus's cutoff up or down at a moment, with smooth edges;
28
+ // - `osc`, a saw, square or pulse that does not alias. Written as
29
+ // `2 * (phase % 1) - 1` or `sin(x) > 0 ? 1 : -1`, as films wrote theirs,
30
+ // the harmonics above 24 kHz fold back down as tones that are not in the
31
+ // note — the buzz and grit under a bass or a chord stab.
32
+ //
33
+ // Sound is Float32Array channels, −1..1 full scale, 48 kHz unless you say
34
+ // otherwise. A bus is a buffer you mix into. Times are seconds.
35
+ //
36
+ // import { buffer, mix, envelope, normalize, diagnose, writeWav } from "./kit/audio.mjs";
37
+ // const music = buffer(30); // 30 s of stereo silence
38
+ // mix(music, note, tl.t("search"), 0.4); // a sound at a moment, at 0.4
39
+ // const stems = { music, sfx };
40
+ // for (const [name, s] of Object.entries(stems)) console.log(diagnose(name, s));
41
+ // writeWav("score.wav", normalize(master)); // −16 LUFS, true peak ≤ −1 dBTP
42
+
43
+ import { spawnSync } from "node:child_process";
44
+ import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
45
+ import { homedir } from "node:os";
46
+ import { join } from "node:path";
47
+
48
+ /** the sample rate when nothing says otherwise: the film's soundtrack is 48 kHz */
49
+ const RATE = 48000;
50
+
51
+ /** @typedef {Float32Array | Float64Array} Signal one channel of samples */
52
+ /** @typedef {Signal[] & { sampleRate?: number }} Channels one Signal per channel; buffer() records its rate on it */
53
+
54
+ /** @param {Channels | Signal} x @returns {Signal[]} */
55
+ const chans = (x) => (ArrayBuffer.isView(x) ? [/** @type {Signal} */ (x)] : x);
56
+ /** @param {Channels | Signal} x */
57
+ const rateOf = (x) => /** @type {{ sampleRate?: number }} */ (x).sampleRate ?? RATE;
58
+ /** @param {Signal[]} chs @param {number} sampleRate @returns {Channels} */
59
+ const withRate = (chs, sampleRate) => Object.assign(chs, { sampleRate });
60
+ /** @param {number} db */
61
+ const gainOf = (db) => 10 ** (db / 20);
62
+ /** @param {number} g */
63
+ const dbOf = (g) => 20 * Math.log10(g);
64
+ /** @param {number} t */
65
+ const secs = (t) => Math.round(t * 1000) / 1000;
66
+
67
+ /** @param {string} who @param {Signal[]} chs */
68
+ function sameLength(who, chs) {
69
+ const n = chs[0]?.length ?? 0;
70
+ if (chs.some((c) => c.length !== n))
71
+ throw new Error(`${who}: its channels differ in length (${chs.map((c) => c.length)})`);
72
+ return n;
73
+ }
74
+
75
+ // ---------------------------------------------------------------- buffers
76
+
77
+ /**
78
+ * Silence to mix into: `seconds` long, one Float32Array per channel. A bus is
79
+ * one of these — mix sounds into it, process it, mix it into the master.
80
+ * @param {number} seconds
81
+ * @param {{ channels?: number, sampleRate?: number }} [o]
82
+ * @returns {Channels}
83
+ */
84
+ export function buffer(seconds, { channels = 2, sampleRate = RATE } = {}) {
85
+ if (!(seconds >= 0) || !Number.isFinite(seconds))
86
+ throw new Error(`buffer: ${seconds} is not a length in seconds`);
87
+ const n = Math.round(seconds * sampleRate);
88
+ return withRate(
89
+ Array.from({ length: channels }, () => new Float32Array(n)),
90
+ sampleRate,
91
+ );
92
+ }
93
+
94
+ // Where a bus holds the attack of a recording: a struck bar, a plucked string
95
+ // or a drum head starts with a jump that is the instrument, and in the
96
+ // waveform it reads as a sound starting mid-cycle does. `play` notes the time
97
+ // when told the sound is a recording (`recorded`), `mix` carries the times
98
+ // into what the bus is mixed into, and `diagnose` leaves a jump within 5 ms
99
+ // after one alone. Kept on the first channel, so a bus built by spreading or
100
+ // copying its channels starts with none.
101
+ /** @type {WeakMap<Signal, number[]>} */
102
+ const attacks = new WeakMap();
103
+ /** @param {Channels | Signal} x @returns {number[]} */
104
+ const attacksOf = (x) => {
105
+ const first = chans(x)[0];
106
+ return (first && attacks.get(first)) || [];
107
+ };
108
+ /** @param {Channels} bus @param {readonly number[]} times */
109
+ const noteAttacks = (bus, times) => {
110
+ const first = bus[0];
111
+ if (!first || !times.length) return;
112
+ const had = attacks.get(first);
113
+ if (had) had.push(...times);
114
+ else attacks.set(first, [...times]);
115
+ };
116
+
117
+ /**
118
+ * Add `from` into `into` from `at` seconds on, scaled by `gain`: one number,
119
+ * or one per channel of `into` (a pan, by hand). A mono sound goes into every
120
+ * channel. Whatever falls outside `into` is left out. Returns `into`.
121
+ * @param {Channels} into
122
+ * @param {Channels | Signal} from
123
+ * @param {number} [at]
124
+ * @param {number | number[]} [gain]
125
+ */
126
+ export function mix(into, from, at = 0, gain = 1) {
127
+ const src = chans(from);
128
+ const a = into.sampleRate;
129
+ const b = /** @type {{ sampleRate?: number }} */ (from).sampleRate;
130
+ if (a && b && a !== b) throw new Error(`mix: ${b} Hz into ${a} Hz — resample it first`);
131
+ if (!Number.isFinite(at)) throw new Error(`mix: ${at} is not a time in seconds`);
132
+ if (src.length !== 1 && src.length !== into.length)
133
+ throw new Error(`mix: ${src.length} channels into ${into.length} — give it mono, or as many`);
134
+ if (Array.isArray(gain) && gain.length !== into.length)
135
+ throw new Error(`mix: ${gain.length} gains for ${into.length} channels`);
136
+ const start = Math.round(at * (a ?? b ?? RATE));
137
+ into.forEach((dst, c) => {
138
+ const s = /** @type {Signal} */ (src.length === 1 ? src[0] : src[c]);
139
+ const g = Array.isArray(gain) ? (gain[c] ?? 0) : gain;
140
+ const i1 = Math.min(s.length, dst.length - start);
141
+ for (let i = Math.max(0, -start); i < i1; i++)
142
+ dst[start + i] = (dst[start + i] ?? 0) + (s[i] ?? 0) * g;
143
+ });
144
+ if (chans(from)[0] !== into[0])
145
+ noteAttacks(
146
+ into,
147
+ attacksOf(from).map((t) => t + at),
148
+ );
149
+ return into;
150
+ }
151
+
152
+ /**
153
+ * Numbers that look random but are the same every run (mulberry32): a score
154
+ * built on Math.random() changes each time it is rendered.
155
+ * @param {number} seed
156
+ * @returns {() => number} the next number in [0, 1)
157
+ */
158
+ export function rng(seed) {
159
+ let a = seed | 0;
160
+ return () => {
161
+ a = (a + 0x6d2b79f5) | 0;
162
+ let t = Math.imul(a ^ (a >>> 15), a | 1);
163
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
164
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
165
+ };
166
+ }
167
+
168
+ // ---------------------------------------------------------------- sources
169
+
170
+ /** the polyBLEP correction for a step at phase 0, `dt` the phase advanced a sample
171
+ * @param {number} t phase 0..1 @param {number} dt */
172
+ function blep(t, dt) {
173
+ if (t < dt) {
174
+ const u = t / dt;
175
+ return u + u - u * u - 1;
176
+ }
177
+ if (t > 1 - dt) {
178
+ const u = (t - 1) / dt;
179
+ return u * u + u + u + 1;
180
+ }
181
+ return 0;
182
+ }
183
+
184
+ /**
185
+ * One oscillator, mono: "sine", "triangle", or a "saw", "square" or "pulse"
186
+ * whose jumps are smoothed by polyBLEP, so its harmonics stop at Nyquist
187
+ * instead of folding back as tones that are not in the note. `freq` is Hz,
188
+ * or a function of the note's time for a glide or vibrato; the phase is
189
+ * carried sample to sample, so a moving pitch stays continuous and a fixed
190
+ * one stays exactly in tune. Start copies that sound together (a detuned
191
+ * pair, a chord of saws) at different `phase`s: saws started together make a
192
+ * click as they line up.
193
+ *
194
+ * const n = osc("saw", 110, 0.4); // A2, 0.4 s (Hz: 440 * 2 ** ((midi - 69) / 12))
195
+ * const glide = osc("square", (t) => 220 * 2 ** (t / 0.5), 0.5, { width: 0.3 });
196
+ *
197
+ * @param {"sine" | "triangle" | "saw" | "square" | "pulse"} wave
198
+ * @param {number | ((t: number) => number)} freq Hz, or Hz at t s into the note
199
+ * @param {number} seconds
200
+ * @param {{ width?: number, phase?: number, sampleRate?: number }} [o] width: the pulse's high part, 0..1 (a square is 0.5); phase: where in its cycle it starts, 0..1
201
+ * @returns {Float32Array}
202
+ */
203
+ export function osc(wave, freq, seconds, { width = 0.5, phase = 0, sampleRate = RATE } = {}) {
204
+ if (!["sine", "triangle", "saw", "square", "pulse"].includes(wave))
205
+ throw new Error(`osc: wave is sine, triangle, saw, square or pulse (got ${wave})`);
206
+ if (!(seconds >= 0) || !Number.isFinite(seconds))
207
+ throw new Error(`osc: seconds must be a number ≥ 0 (got ${seconds})`);
208
+ if (!Number.isFinite(width) || !Number.isFinite(phase))
209
+ throw new Error(`osc: width and phase are numbers (got ${width}, ${phase})`);
210
+ const w = wave === "square" ? 0.5 : Math.min(0.99, Math.max(0.01, width));
211
+ const n = Math.round(seconds * sampleRate);
212
+ const out = new Float32Array(n);
213
+ const f = typeof freq === "function" ? freq : () => freq;
214
+ let ph = ((phase % 1) + 1) % 1;
215
+ for (let i = 0; i < n; i++) {
216
+ const hz = f(i / sampleRate);
217
+ if (!Number.isFinite(hz))
218
+ throw new Error(`osc: the frequency at ${i / sampleRate} s is not a number`);
219
+ const dt = Math.min(0.5, Math.abs(hz) / sampleRate);
220
+ let v;
221
+ if (wave === "sine") v = Math.sin(2 * Math.PI * ph);
222
+ else if (wave === "triangle") v = 1 - 4 * Math.abs(ph - 0.5);
223
+ else if (wave === "saw") v = 2 * ph - 1 - blep(ph, dt);
224
+ else {
225
+ v = ph < w ? 1 : -1;
226
+ v += blep(ph, dt);
227
+ v -= blep((ph + 1 - w) % 1, dt);
228
+ // a pulse narrower than a square sits off centre; take its mean out
229
+ v -= 2 * w - 1;
230
+ }
231
+ out[i] = v;
232
+ ph += hz / sampleRate;
233
+ ph -= Math.floor(ph);
234
+ }
235
+ return out;
236
+ }
237
+
238
+ // ---------------------------------------------------------------- shaping
239
+
240
+ /**
241
+ * An envelope: attack, decay, sustain, release. `env(t, held)` is its level
242
+ * t s after the note starts, for a note held `held` s (default: held for
243
+ * good). Let go early — mid-attack, mid-decay — and it releases from the level
244
+ * it had reached, so the level never jumps. The defaults are a plain gate that
245
+ * cannot click (5 ms in, 20 ms out); the shape of a sound is yours.
246
+ *
247
+ * const env = envelope({ attack: 0.002, decay: 0.4, sustain: 0.3, release: 0.25 });
248
+ * const n = Math.ceil(env.end(0.5) * 48000); // the note sounds this long
249
+ * for (let i = 0; i < n; i++) note[i] = Math.sin(w * i) * env(i / 48000, 0.5);
250
+ *
251
+ * @param {object} [o]
252
+ * @param {number} [o.attack] s from 0 to the top (1, or the sustain level when there is no decay)
253
+ * @param {number} [o.decay] s from 1 down to the sustain level
254
+ * @param {number} [o.sustain] the level while held, 0..1
255
+ * @param {number} [o.release] s from wherever it was let go down to 0
256
+ * @param {number} [o.curve] 0 is a straight line; higher bends the decay and release toward an exponential fall
257
+ * @returns {((t: number, held?: number) => number) & { end: (held: number) => number }}
258
+ */
259
+ export function envelope({
260
+ attack = 0.005,
261
+ decay = 0,
262
+ sustain = 1,
263
+ release = 0.02,
264
+ curve = 0,
265
+ } = {}) {
266
+ for (const [k, v] of Object.entries({ attack, decay, sustain, release, curve }))
267
+ if (!(v >= 0) || !Number.isFinite(v))
268
+ throw new Error(`envelope: ${k} must be a number ≥ 0 (got ${v})`);
269
+ const top = decay > 0 ? 1 : sustain;
270
+ /** progress 0..1 through a fall, bent by `curve` @param {number} u */
271
+ const bend = (u) => (curve === 0 ? u : (1 - Math.exp(-curve * u)) / (1 - Math.exp(-curve)));
272
+ /** the level of a note still held @param {number} t */
273
+ const level = (t) => {
274
+ if (t < 0) return 0;
275
+ if (t < attack) return (top * t) / attack;
276
+ if (t < attack + decay) return 1 - (1 - sustain) * bend((t - attack) / decay);
277
+ return sustain;
278
+ };
279
+ /** @param {number} t @param {number} [held] */
280
+ const env = (t, held = Number.POSITIVE_INFINITY) => {
281
+ if (t < held) return level(t);
282
+ if (t >= held + release) return 0;
283
+ return level(held) * (1 - bend((t - held) / release));
284
+ };
285
+ /** when a note held `held` s falls silent @param {number} held */
286
+ const end = (held) => held + release;
287
+ return Object.assign(env, { end });
288
+ }
289
+
290
+ /**
291
+ * A filter from Robert Bristow-Johnson's cookbook, keeping its state between
292
+ * calls: one per track, and one state per channel (`ch`). `f(x)` filters one
293
+ * sample, `f.run(sound)` a whole buffer in place, `f.set({ freq })` moves it as
294
+ * it runs (a sweep) and keeps the state.
295
+ *
296
+ * Its frequency is held under Nyquist — above it these filters run away, the
297
+ * way a film's did at a high cutoff. If its state still stops being a number
298
+ * (a NaN coming in, a sweep it cannot follow), it throws, naming the track.
299
+ *
300
+ * @param {string} name the track, for the error
301
+ * @param {"lowpass" | "highpass" | "bandpass" | "peaking" | "lowshelf" | "highshelf"} type
302
+ * @param {{ freq: number, q?: number, gain?: number }} params Hz; q defaults to 0.707; gain in dB, for peaking and the shelves
303
+ * @param {number} [sampleRate]
304
+ */
305
+ export function biquad(name, type, params, sampleRate = RATE) {
306
+ let b0 = 1;
307
+ let b1 = 0;
308
+ let b2 = 0;
309
+ let a1 = 0;
310
+ let a2 = 0;
311
+ let p = { q: Math.SQRT1_2, gain: 0, ...params };
312
+ /** @param {{ freq?: number, q?: number, gain?: number }} next */
313
+ const set = (next) => {
314
+ p = { ...p, ...next };
315
+ if (!(p.freq > 0) || !(p.q > 0) || !Number.isFinite(p.gain))
316
+ throw new Error(
317
+ `biquad "${name}": it needs freq > 0, q > 0 and a gain in dB (got ${p.freq} Hz, q ${p.q}, ${p.gain} dB)`,
318
+ );
319
+ const w = (2 * Math.PI * Math.min(p.freq, 0.49 * sampleRate)) / sampleRate;
320
+ const cos = Math.cos(w);
321
+ const alpha = Math.sin(w) / (2 * p.q);
322
+ const A = 10 ** (p.gain / 40);
323
+ const sq = 2 * Math.sqrt(A) * alpha;
324
+ /** @type {[number, number, number, number, number, number]} b0 b1 b2 a0 a1 a2 */
325
+ let c;
326
+ if (type === "lowpass")
327
+ c = [(1 - cos) / 2, 1 - cos, (1 - cos) / 2, 1 + alpha, -2 * cos, 1 - alpha];
328
+ else if (type === "highpass")
329
+ c = [(1 + cos) / 2, -(1 + cos), (1 + cos) / 2, 1 + alpha, -2 * cos, 1 - alpha];
330
+ else if (type === "bandpass") c = [alpha, 0, -alpha, 1 + alpha, -2 * cos, 1 - alpha];
331
+ else if (type === "peaking")
332
+ c = [1 + alpha * A, -2 * cos, 1 - alpha * A, 1 + alpha / A, -2 * cos, 1 - alpha / A];
333
+ else if (type === "lowshelf")
334
+ c = [
335
+ A * (A + 1 - (A - 1) * cos + sq),
336
+ 2 * A * (A - 1 - (A + 1) * cos),
337
+ A * (A + 1 - (A - 1) * cos - sq),
338
+ A + 1 + (A - 1) * cos + sq,
339
+ -2 * (A - 1 + (A + 1) * cos),
340
+ A + 1 + (A - 1) * cos - sq,
341
+ ];
342
+ else if (type === "highshelf")
343
+ c = [
344
+ A * (A + 1 + (A - 1) * cos + sq),
345
+ -2 * A * (A - 1 + (A + 1) * cos),
346
+ A * (A + 1 + (A - 1) * cos - sq),
347
+ A + 1 - (A - 1) * cos + sq,
348
+ 2 * (A - 1 - (A + 1) * cos),
349
+ A + 1 - (A - 1) * cos - sq,
350
+ ];
351
+ else throw new Error(`biquad "${name}": no filter type "${type}"`);
352
+ const [n0, n1, n2, d0, d1, d2] = c;
353
+ b0 = n0 / d0;
354
+ b1 = n1 / d0;
355
+ b2 = n2 / d0;
356
+ a1 = d1 / d0;
357
+ a2 = d2 / d0;
358
+ };
359
+ set({});
360
+ /** per channel: the last two inputs and outputs, and how many samples it has seen */
361
+ /** @type {{ x1: number, x2: number, y1: number, y2: number, n: number }[]} */
362
+ const state = [];
363
+ /** @param {number} ch */
364
+ const stateOf = (ch) => {
365
+ let s = state[ch];
366
+ if (!s) {
367
+ s = { x1: 0, x2: 0, y1: 0, y2: 0, n: 0 };
368
+ state[ch] = s;
369
+ }
370
+ return s;
371
+ };
372
+ /** @param {number} y @param {number} x @param {number} ch @param {number} n */
373
+ const blewUp = (y, x, ch, n) =>
374
+ new Error(
375
+ `biquad "${name}" (${type}, ${Math.round(p.freq)} Hz): its state became ${y} ` +
376
+ `${secs(n / sampleRate)} s into channel ${ch} — ` +
377
+ (Number.isFinite(x) ? "the filter ran away" : `its input was ${x}`),
378
+ );
379
+ /** filter one sample @param {number} x @param {number} [ch] */
380
+ const f = (x, ch = 0) => {
381
+ const s = stateOf(ch);
382
+ const y = b0 * x + b1 * s.x1 + b2 * s.x2 - a1 * s.y1 - a2 * s.y2;
383
+ if (!Number.isFinite(y)) throw blewUp(y, x, ch, s.n);
384
+ s.x2 = s.x1;
385
+ s.x1 = x;
386
+ s.y2 = s.y1;
387
+ s.y1 = y;
388
+ s.n++;
389
+ return y;
390
+ };
391
+ /** filter a whole sound in place, each channel with its own state; returns it
392
+ * @template {Channels | Signal} T @param {T} sound @returns {T} */
393
+ const run = (sound) => {
394
+ chans(sound).forEach((sig, ch) => {
395
+ const s = stateOf(ch);
396
+ let { x1, x2, y1, y2 } = s;
397
+ for (let i = 0; i < sig.length; i++) {
398
+ const x = sig[i] ?? 0;
399
+ const y = b0 * x + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2;
400
+ if (!Number.isFinite(y)) throw blewUp(y, x, ch, s.n + i);
401
+ sig[i] = y;
402
+ x2 = x1;
403
+ x1 = x;
404
+ y2 = y1;
405
+ y1 = y;
406
+ }
407
+ Object.assign(s, { x1, x2, y1, y2, n: s.n + sig.length });
408
+ });
409
+ return sound;
410
+ };
411
+ return Object.assign(f, { run, set });
412
+ }
413
+
414
+ /** @param {number} t @param {number} dur */
415
+ const ramp = (t, dur) => 0.5 - 0.5 * Math.cos(Math.PI * Math.max(0, Math.min(1, t / dur)));
416
+
417
+ /**
418
+ * Change only the low band. Take it out with a fourth-order Butterworth
419
+ * lowpass at twice `edge` Hz, run forwards and backwards, so its phase still
420
+ * matches the dry bus when it goes back in. Below `edge` the filter keeps
421
+ * 99.6% of the band, so the full change applies there: a 19.4 dB drop is
422
+ * 19.1 dB at `edge` and a 27.9 dB rise is 27.1 dB. At 2 × `edge` half the
423
+ * amplitude is changed (about 5 dB of either), and from 3 × `edge` less than
424
+ * 4% (0.3 dB). Reflect the ends before filtering, so the filter can settle
425
+ * outside the bus.
426
+ * @param {Channels} bus @param {number} edge @param {(t: number) => number} gain
427
+ */
428
+ function lowGain(bus, edge, gain) {
429
+ const fs = rateOf(bus);
430
+ const n = sameLength("low band", bus);
431
+ if (!n) return bus;
432
+ const pad = Math.min(n - 1, Math.ceil((4 * fs) / edge));
433
+ for (const ch of bus) {
434
+ const low = new Float64Array(n + 2 * pad);
435
+ low.set(ch, pad);
436
+ for (let i = 1; i <= pad; i++) {
437
+ low[pad - i] = 2 * (ch[0] ?? 0) - (ch[i] ?? 0);
438
+ low[pad + n - 1 + i] = 2 * (ch[n - 1] ?? 0) - (ch[n - 1 - i] ?? 0);
439
+ }
440
+ for (let pass = 0; pass < 2; pass++) {
441
+ for (const q of BUTTERWORTH_4) biquad("low band", "lowpass", { freq: 2 * edge, q }, fs).run(low);
442
+ low.reverse();
443
+ }
444
+ for (let i = 0; i < n; i++) {
445
+ const g = gain(i / fs);
446
+ if (g !== 1) ch[i] = (ch[i] ?? 0) + (low[pad + i] ?? 0) * (g - 1);
447
+ }
448
+ }
449
+ return bus;
450
+ }
451
+
452
+ /** the q of the two sections of a fourth-order Butterworth */
453
+ const BUTTERWORTH_4 = [1 / (2 * Math.sin((3 * Math.PI) / 8)), 1 / (2 * Math.sin(Math.PI / 8))];
454
+
455
+ /** @param {string} name @param {number} span @param {number} fade @param {number} db @param {string} fix */
456
+ function reachesDepth(name, span, fade, db, fix) {
457
+ if (span >= fade - 1e-9) return;
458
+ const reached = -20 * Math.log10(1 - (1 - gainOf(-db)) * ramp((fade + span) / 2, fade) ** 2);
459
+ throw new Error(
460
+ `${name}: ${secs(span)} s between the edges is shorter than the ${secs(fade)} s fade, ` +
461
+ `so the level would only reach −${reached.toFixed(1)} dB of the −${db} dB asked; ${fix}`,
462
+ );
463
+ }
464
+
465
+ /**
466
+ * Bring the low band (below `freq` Hz) in at `at`. Without `since` it is
467
+ * `db` down from the very start of the bus; with `since`, the bus stays dry
468
+ * until then and fades down over `fade` s. At `at` it fades back to its own
469
+ * level over `fade` s. Changes and returns the bus.
470
+ * The defaults come from three such entries, read in the 20–80 Hz band:
471
+ * DdT1-vziRp3 at 4.958 s, +27.9 dB, and Df-JzBcCrDo at 7.042 and 76.917 s,
472
+ * +9.5 and +18.3 dB; `db` is their median. The fade is not read from them:
473
+ * there the low band takes 100–220 ms from 10% to 90%, which is the bass
474
+ * note's own attack. 40 ms is short enough to leave that attack to the note
475
+ * and long enough not to click.
476
+ * @param {Channels} bus @param {number} at
477
+ * @param {{ db?: number, freq?: number, fade?: number, since?: number }} [o] positive dB, band edge in Hz, times in s
478
+ */
479
+ export function subIn(bus, at, { db = 18.3, freq = 80, fade = 0.04, since } = {}) {
480
+ if (!Number.isFinite(at) || !Number.isFinite(db) || !Number.isFinite(fade) || !(freq > 0))
481
+ throw new Error("subIn: give it a time, a level in dB, a fade in seconds and a positive band edge");
482
+ if (since !== undefined && (!Number.isFinite(since) || since > at))
483
+ throw new Error("subIn: since must be a time at or before at");
484
+ const down = 1 - gainOf(-db);
485
+ const edge = Math.max(0.001, fade);
486
+ if (since !== undefined) reachesDepth("subIn", at - since, edge, db, "start since earlier or shorten the fade");
487
+ return lowGain(bus, freq, (t) => {
488
+ const inEffect = since === undefined ? 1 : ramp(t - since, edge);
489
+ return 1 - down * inEffect * (1 - ramp(t - at, edge));
490
+ });
491
+ }
492
+
493
+ /**
494
+ * Take the low band below `freq` Hz (or the `full` bus) down by `db` at
495
+ * `at`, then start bringing it back at `at + hold`. The same `fade` in
496
+ * seconds shapes both edges, so `hold` must be at least `fade`. Changes and
497
+ * returns the bus. DdT1-vziRp3 at 32.792 s: −19.4 dB in the 20–80 Hz band.
498
+ * Dfj2vYxC1pE at 60.300 s: the mix fell 21.9 LU in 0.1 s and returned after
499
+ * 1.4 s. The 40 ms fade of the low band is chosen, as in subIn.
500
+ * @param {Channels} bus @param {number} at
501
+ * @param {{ db?: number, freq?: number, fade?: number, hold?: number, full?: boolean }} [o]
502
+ */
503
+ export function dropOut(bus, at, { full = false, db = full ? 22 : 19.4, freq = 80, fade = full ? 0.1 : 0.04, hold = 1.4 } = {}) {
504
+ if (![at, db, fade, hold].every(Number.isFinite) || hold < 0 || (!full && !(freq > 0)))
505
+ throw new Error("dropOut: give it a time, a level in dB, a fade and hold in seconds and a positive band edge");
506
+ const down = 1 - gainOf(-db);
507
+ const edge = Math.max(0.001, fade);
508
+ reachesDepth("dropOut", hold, edge, db, "hold at least as long as the fade");
509
+ /** @param {number} t */
510
+ const gain = (t) => 1 - down * ramp(t - at, edge) * (1 - ramp(t - at - hold, edge));
511
+ if (!full) return lowGain(bus, freq, gain);
512
+ const fs = rateOf(bus);
513
+ const n = sameLength("dropOut", bus);
514
+ for (let i = 0; i < n; i++) {
515
+ const g = gain(i / fs);
516
+ for (const ch of bus) ch[i] = (ch[i] ?? 0) * g;
517
+ }
518
+ return bus;
519
+ }
520
+
521
+ /** @param {Channels} bus @param {number} from @param {number} to
522
+ * @param {number} a @param {number} b
523
+ * @param {{ since?: number, until?: number, fade: number }} o */
524
+ function sweepLowpass(bus, from, to, a, b, { since, until, fade }) {
525
+ if (!(to > from) || !Number.isFinite(to - from)) throw new Error("filter sweep: to must be after from");
526
+ if (since !== undefined && (!Number.isFinite(since) || since > from))
527
+ throw new Error("filter sweep: since must be a time at or before from");
528
+ if (until !== undefined && (!Number.isFinite(until) || until < to))
529
+ throw new Error("filter sweep: until must be a time at or after to");
530
+ if (!Number.isFinite(fade)) throw new Error("filter sweep: the fade is in seconds");
531
+ const fs = rateOf(bus);
532
+ const n = sameLength("filter sweep", bus);
533
+ const start = Math.min(a, fs * 0.49);
534
+ const end = Math.min(b, fs * 0.49);
535
+ if (!(end > 0)) throw new Error("filter sweep: both cutoffs in Hz must be positive");
536
+ const filter = biquad("filter sweep", "lowpass", { freq: start }, fs);
537
+ const edge = Math.max(0.001, fade);
538
+ let cutoff = start;
539
+ for (let i = 0; i < n; i++) {
540
+ const t = i / fs;
541
+ if (until !== undefined && t >= until + edge) break;
542
+ const u = Math.max(0, Math.min(1, (t - from) / (to - from)));
543
+ const freq = start * (end / start) ** u;
544
+ if (freq !== cutoff) {
545
+ cutoff = freq;
546
+ filter.set({ freq });
547
+ }
548
+ const wetIn = since === undefined ? 1 : ramp(t - since, edge);
549
+ const wetOut = until === undefined ? 1 : 1 - ramp(t - until, edge);
550
+ const wet = wetIn * wetOut;
551
+ for (let c = 0; c < bus.length; c++) {
552
+ const ch = /** @type {Signal} */ (bus[c]);
553
+ const dry = ch[i] ?? 0;
554
+ const filtered = filter(dry, c);
555
+ if (wet > 0) ch[i] = wet === 1 ? filtered : dry + wet * (filtered - dry);
556
+ }
557
+ }
558
+ return bus;
559
+ }
560
+
561
+ /**
562
+ * Sweep a lowpass open from `from` to `to` on an exponential path in Hz.
563
+ * By default the bus is filtered at `low` from the start. With `since` it
564
+ * stays dry until then and fades into the filter over `fade` s. The filter
565
+ * holds at `high` after `to`. Changes and returns the bus.
566
+ * Df-JzBcCrDo at 0–1.7 s: the high end is held back and opens at 1.7 s.
567
+ * @param {Channels} bus @param {number} from @param {number} to
568
+ * @param {{ low?: number, high?: number, since?: number, fade?: number }} [o] cutoffs in Hz, times in s
569
+ */
570
+ export function filterOpen(bus, from, to, { low = 1200, high = 20000, since, fade = 0.04 } = {}) {
571
+ return sweepLowpass(bus, from, to, low, high, { since, fade });
572
+ }
573
+
574
+ /**
575
+ * Sweep from `high` to `low` over `from`–`to`. The filter starts at `high`
576
+ * and holds at `low` through the end, or until `until` if given. At `until`
577
+ * it fades back to the dry bus over `fade` s. Changes and returns the bus.
578
+ * Df-JzBcCrDo at 23.080 s: the 5–16 kHz band falls about 20 dB.
579
+ * @param {Channels} bus @param {number} from @param {number} to
580
+ * @param {{ low?: number, high?: number, until?: number, fade?: number }} [o] cutoffs in Hz, times in s
581
+ */
582
+ export function filterClose(bus, from, to, { low = 1200, high = 20000, until, fade = 0.04 } = {}) {
583
+ return sweepLowpass(bus, from, to, high, low, { until, fade });
584
+ }
585
+
586
+ const COMBS = [1116, 1188, 1277, 1356, 1422, 1491, 1557, 1617];
587
+ const ALLPASSES = [556, 441, 341, 225];
588
+
589
+ /**
590
+ * A reverb: Jezar's Freeverb — eight damped combs side by side, then four
591
+ * all-passes, for each side (the right one's delays 23 samples longer).
592
+ * Returns the reverb alone, in stereo, as long as the sound plus its tail:
593
+ * mix it in at the level you want it.
594
+ * @param {Channels | Signal} sound
595
+ * @param {number} [sampleRate]
596
+ * @param {{ size?: number, damp?: number, width?: number, tail?: number }} [o]
597
+ * size 0..1, the room (a longer tail); damp 0..1, how much sooner the highs
598
+ * die; width 0..1, 0 is mono; tail, s kept after the sound (default: until
599
+ * it is 60 dB down)
600
+ * @returns {Channels}
601
+ */
602
+ export function reverb(
603
+ sound,
604
+ sampleRate = rateOf(sound),
605
+ { size = 0.5, damp = 0.5, width = 1, tail } = {},
606
+ ) {
607
+ const src = chans(sound);
608
+ const len = sameLength("reverb", src);
609
+ const k = sampleRate / 44100; // the tunings are samples at 44.1 kHz
610
+ const feedback = size * 0.28 + 0.7;
611
+ const damp1 = damp * 0.4;
612
+ const damp2 = 1 - damp1;
613
+ // the longest comb loses (1 − feedback) of its level per pass: 60 dB takes this long
614
+ const longest = Math.round((1617 + 23) * k);
615
+ const t60 = (longest * Math.log(1000)) / (-Math.log(feedback) * sampleRate);
616
+ const n = len + Math.round((tail ?? t60) * sampleRate);
617
+ /** @param {number} d */
618
+ const line = (d) => ({ buf: new Float64Array(Math.max(1, Math.round(d * k))), i: 0, store: 0 });
619
+ const sides = [0, 23].map((spread) => ({
620
+ combs: COMBS.map((d) => line(d + spread)),
621
+ passes: ALLPASSES.map((d) => line(d + spread)),
622
+ out: new Float32Array(n),
623
+ }));
624
+ // Freeverb takes (L + R) × 0.015; the mean × 0.03 is that, and the same for mono
625
+ const gain = 0.03 / src.length;
626
+ for (let i = 0; i < n; i++) {
627
+ let input = 0;
628
+ if (i < len) for (const s of src) input += s[i] ?? 0;
629
+ input *= gain;
630
+ for (const side of sides) {
631
+ let acc = 0;
632
+ for (const c of side.combs) {
633
+ const y = c.buf[c.i] ?? 0;
634
+ c.store = y * damp2 + c.store * damp1;
635
+ c.buf[c.i] = input + c.store * feedback;
636
+ if (++c.i === c.buf.length) c.i = 0;
637
+ acc += y;
638
+ }
639
+ for (const a of side.passes) {
640
+ const b = a.buf[a.i] ?? 0;
641
+ a.buf[a.i] = acc + b * 0.5;
642
+ if (++a.i === a.buf.length) a.i = 0;
643
+ acc = b - acc;
644
+ }
645
+ side.out[i] = acc;
646
+ }
647
+ }
648
+ const [l, r] = /** @type {[Float32Array, Float32Array]} */ (sides.map((s) => s.out));
649
+ const wet1 = width / 2 + 0.5;
650
+ const wet2 = (1 - width) / 2;
651
+ for (let i = 0; i < n; i++) {
652
+ const a = l[i] ?? 0;
653
+ const b = r[i] ?? 0;
654
+ l[i] = a * wet1 + b * wet2;
655
+ r[i] = b * wet1 + a * wet2;
656
+ }
657
+ return withRate([l, r], sampleRate);
658
+ }
659
+
660
+ /**
661
+ * Sidechain: `sound` dips while `key` plays — the music under a voice, under a
662
+ * hit. The key at its loudest takes the sound down by `amount` dB; quieter, it
663
+ * takes it down less (half as loud, half as far). `attack` and `release` are
664
+ * how fast the dip follows the key (time constants, s). Returns the ducked
665
+ * sound as new channels.
666
+ * @param {Channels | Signal} sound
667
+ * @param {Channels | Signal} key
668
+ * @param {number} [sampleRate]
669
+ * @param {{ amount?: number, attack?: number, release?: number }} [o]
670
+ * @returns {Channels}
671
+ */
672
+ export function duck(
673
+ sound,
674
+ key,
675
+ sampleRate = rateOf(sound),
676
+ { amount = 6, attack = 0.01, release = 0.25 } = {},
677
+ ) {
678
+ const src = chans(sound);
679
+ const keys = chans(key);
680
+ const n = sameLength("duck", src);
681
+ const up = Math.exp(-1 / (Math.max(attack, 1e-6) * sampleRate));
682
+ const down = Math.exp(-1 / (Math.max(release, 1e-6) * sampleRate));
683
+ // the key's level is its peak over the last 10 ms, so a tone's dips between
684
+ // peaks do not count; the dip follows that level, rising at `attack` and
685
+ // falling at `release`
686
+ const hold = Math.max(1, Math.round(0.01 * sampleRate));
687
+ const abs = new Float32Array(n);
688
+ const q = new Int32Array(n); // a window maximum: indices whose |key| falls from head to tail
689
+ let head = 0;
690
+ let tail = 0;
691
+ const env = new Float32Array(n);
692
+ let e = 0;
693
+ let loudest = 0;
694
+ for (let i = 0; i < n; i++) {
695
+ let x = 0;
696
+ for (const k of keys) x = Math.max(x, Math.abs(k[i] ?? 0));
697
+ abs[i] = x;
698
+ while (tail > head && (abs[q[tail - 1] ?? 0] ?? 0) <= x) tail--;
699
+ q[tail++] = i;
700
+ while ((q[head] ?? 0) <= i - hold) head++;
701
+ const level = abs[q[head] ?? 0] ?? 0;
702
+ e = level > e ? up * e + (1 - up) * level : down * e + (1 - down) * level;
703
+ env[i] = e;
704
+ if (e > loudest) loudest = e;
705
+ }
706
+ const out = src.map((s) => Float32Array.from(s));
707
+ if (loudest > 0)
708
+ for (let i = 0; i < n; i++) {
709
+ const g = gainOf((-amount * (env[i] ?? 0)) / loudest);
710
+ for (const o of out) o[i] = (o[i] ?? 0) * g;
711
+ }
712
+ return withRate(out, sampleRate);
713
+ }
714
+
715
+ // ---------------------------------------------------------------- loudness
716
+
717
+ /** @typedef {[number, number, number, number, number]} Stage b0, b1, b2, a1, a2 */
718
+
719
+ /** K-weighting, BS.1770-4's two stages (a high shelf for the head, then a
720
+ * high-pass), as coefficients for any sample rate — the derivation libebur128
721
+ * and ffmpeg use; at 48 kHz it gives the standard's own numbers
722
+ * @param {number} fs @returns {{ shelf: Stage, highpass: Stage }} */
723
+ function kWeighting(fs) {
724
+ let K = Math.tan((Math.PI * 1681.974450955533) / fs);
725
+ let Q = 0.7071752369554196;
726
+ const Vh = 10 ** (3.999843853973347 / 20);
727
+ const Vb = Vh ** 0.4996667741545416;
728
+ let a0 = 1 + K / Q + K * K;
729
+ /** @type {Stage} */
730
+ const shelf = [
731
+ (Vh + (Vb * K) / Q + K * K) / a0,
732
+ (2 * (K * K - Vh)) / a0,
733
+ (Vh - (Vb * K) / Q + K * K) / a0,
734
+ (2 * (K * K - 1)) / a0,
735
+ (1 - K / Q + K * K) / a0,
736
+ ];
737
+ K = Math.tan((Math.PI * 38.13547087602444) / fs);
738
+ Q = 0.5003270373238773;
739
+ a0 = 1 + K / Q + K * K;
740
+ /** @type {Stage} */
741
+ const highpass = [1, -2, 1, (2 * (K * K - 1)) / a0, (1 - K / Q + K * K) / a0];
742
+ return { shelf, highpass };
743
+ }
744
+
745
+ /** the mean square of each 400 ms block (a new one every 100 ms), K-weighted
746
+ * and summed over the channels, each weighted 1 (mono, stereo: no surrounds)
747
+ * @param {Signal[]} chs @param {number} fs */
748
+ function blockPowers(chs, fs) {
749
+ const step = Math.floor(fs / 10);
750
+ const steps = Math.floor((chs[0]?.length ?? 0) / step);
751
+ const sums = new Float64Array(steps);
752
+ const { shelf, highpass } = kWeighting(fs);
753
+ const [s0, s1, s2, s3, s4] = shelf;
754
+ const [h0, h1, h2, h3, h4] = highpass;
755
+ for (const x of chs) {
756
+ let x1 = 0;
757
+ let x2 = 0;
758
+ let y1 = 0;
759
+ let y2 = 0;
760
+ let z1 = 0;
761
+ let z2 = 0;
762
+ let i = 0;
763
+ for (let s = 0; s < steps; s++) {
764
+ let acc = 0;
765
+ for (const end = i + step; i < end; i++) {
766
+ const v = x[i] ?? 0;
767
+ const y = s0 * v + s1 * x1 + s2 * x2 - s3 * y1 - s4 * y2;
768
+ const z = h0 * y + h1 * y1 + h2 * y2 - h3 * z1 - h4 * z2;
769
+ x2 = x1;
770
+ x1 = v;
771
+ y2 = y1;
772
+ y1 = y;
773
+ z2 = z1;
774
+ z1 = z;
775
+ acc += z * z;
776
+ }
777
+ sums[s] = (sums[s] ?? 0) + acc;
778
+ }
779
+ }
780
+ const blocks = new Float64Array(Math.max(0, steps - 3));
781
+ for (let j = 0; j < blocks.length; j++)
782
+ blocks[j] =
783
+ ((sums[j] ?? 0) + (sums[j + 1] ?? 0) + (sums[j + 2] ?? 0) + (sums[j + 3] ?? 0)) / (4 * step);
784
+ return blocks;
785
+ }
786
+
787
+ /** the gated mean of the blocks: those over −70 LUFS, then those within 10 LU
788
+ * of the loudness of those — LUFS, −Infinity when no block is over −70
789
+ * @param {Float64Array} blocks */
790
+ function integrated(blocks) {
791
+ const floor = 10 ** ((-70 + 0.691) / 10);
792
+ let sum = 0;
793
+ let n = 0;
794
+ for (const z of blocks)
795
+ if (z > floor) {
796
+ sum += z;
797
+ n++;
798
+ }
799
+ if (n === 0) return Number.NEGATIVE_INFINITY;
800
+ const gate = sum / n / 10;
801
+ sum = 0;
802
+ n = 0;
803
+ for (const z of blocks)
804
+ if (z > floor && z > gate) {
805
+ sum += z;
806
+ n++;
807
+ }
808
+ return -0.691 + 10 * Math.log10(sum / n);
809
+ }
810
+
811
+ // True peak: the waveform between the samples, where a converter or an
812
+ // encoder's reconstruction overshoots the samples themselves. 4× oversampling
813
+ // by a Kaiser-windowed sinc (β 9, 32 taps a phase) — the filter ffmpeg's
814
+ // resampler builds for ebur128 — so the two read the same. Before the first
815
+ // sample is silence, as in the film (ffmpeg's resampler mirrors the first
816
+ // samples instead, so on a sound that starts at full tilt it reads higher).
817
+ const TAPS = 32;
818
+ const MID = 15; // the tap on the sample itself
819
+ const [P1, P2, P3] = /** @type {[Float64Array, Float64Array, Float64Array]} */ (
820
+ (() => {
821
+ /** @param {number} x */
822
+ const bessel0 = (x) => {
823
+ let sum = 1;
824
+ let term = 1;
825
+ for (let k = 1; k < 64 && term > sum * 1e-17; k++) {
826
+ term *= (x / (2 * k)) ** 2;
827
+ sum += term;
828
+ }
829
+ return sum;
830
+ };
831
+ // the three points a quarter, a half and three quarters past a sample
832
+ return [1, 2, 3].map((p) => {
833
+ const h = new Float64Array(TAPS);
834
+ for (let i = 0; i < TAPS; i++) {
835
+ const u = i - MID - p / 4;
836
+ const w = (2 * u) / TAPS;
837
+ h[i] =
838
+ (Math.sin(Math.PI * u) / (Math.PI * u)) * bessel0(9 * Math.sqrt(Math.max(1 - w * w, 0)));
839
+ }
840
+ const sum = h.reduce((a, v) => a + v, 0);
841
+ return h.map((v) => v / sum); // each passes DC at 1
842
+ });
843
+ })()
844
+ );
845
+ /** no point between samples can be further from 0 than this × the samples around it */
846
+ const REACH = Math.max(...[P1, P2, P3].map((h) => h.reduce((a, v) => a + Math.abs(v), 0)));
847
+
848
+ /** the largest |value| over [i, i + 1): the sample and the three points
849
+ * between it and the next (silence beyond the ends)
850
+ * @param {Signal} x @param {number} i */
851
+ function spanPeak(x, i) {
852
+ const k0 = i - MID;
853
+ let a = 0;
854
+ let b = 0;
855
+ let c = 0;
856
+ for (let t = Math.max(0, -k0); t < Math.min(TAPS, x.length - k0); t++) {
857
+ const v = x[k0 + t] ?? 0;
858
+ a += (P1[t] ?? 0) * v;
859
+ b += (P2[t] ?? 0) * v;
860
+ c += (P3[t] ?? 0) * v;
861
+ }
862
+ return Math.max(Math.abs(x[i] ?? 0), Math.abs(a), Math.abs(b), Math.abs(c));
863
+ }
864
+
865
+ /** samples are looked at in blocks: a block whose neighbourhood is too quiet
866
+ * to matter is passed over */
867
+ const BLOCK = 64;
868
+ /** REACH × the loudest sample any point in block b, or just before it, is made from
869
+ * @param {Signal[]} chs @param {number} b */
870
+ function blockBound(chs, b) {
871
+ let near = 0;
872
+ for (const x of chs) {
873
+ const end = Math.min(x.length, (b + 1) * BLOCK + TAPS - MID);
874
+ for (let k = Math.max(0, b * BLOCK - 1 - MID); k < end; k++)
875
+ near = Math.max(near, Math.abs(x[k] ?? 0));
876
+ }
877
+ return near * REACH;
878
+ }
879
+
880
+ /** the largest |value| of x, at and between its samples
881
+ * @param {Signal} x */
882
+ function truePeakOf(x) {
883
+ let best = 0;
884
+ for (const v of x) if (Math.abs(v) > best) best = Math.abs(v);
885
+ for (let b = 0; b * BLOCK < x.length; b++) {
886
+ if (blockBound([x], b) <= best) continue;
887
+ const end = Math.min(x.length, (b + 1) * BLOCK);
888
+ for (let i = b * BLOCK; i < end; i++) best = Math.max(best, spanPeak(x, i));
889
+ }
890
+ return best;
891
+ }
892
+
893
+ /**
894
+ * How loud a mix is, the way ITU-R BS.1770-4 (EBU R128) measures it — what
895
+ * `film check` and ffmpeg's ebur128 report: integrated loudness (K-weighted,
896
+ * 400 ms blocks every 100 ms, gated at −70 LUFS and at 10 LU under the level
897
+ * of what passed that) and true peak (between the samples too, at 4×). The
898
+ * channels count equally: mono and stereo, not surround.
899
+ * @param {Channels | Signal} channels
900
+ * @param {number} [sampleRate]
901
+ * @returns {{ lufs: number, truePeak: number, peak: number }}
902
+ * LUFS (−Infinity when silent, or shorter than 0.4 s); true peak dBTP; sample peak dBFS
903
+ */
904
+ export function loudness(channels, sampleRate = rateOf(channels)) {
905
+ const chs = chans(channels);
906
+ sameLength("loudness", chs);
907
+ let peak = 0;
908
+ for (const x of chs) for (const v of x) peak = Math.max(peak, Math.abs(v));
909
+ return {
910
+ lufs: integrated(blockPowers(chs, sampleRate)),
911
+ truePeak: dbOf(Math.max(0, ...chs.map(truePeakOf))),
912
+ peak: dbOf(peak),
913
+ };
914
+ }
915
+
916
+ /**
917
+ * @typedef {object} NormalizeReport
918
+ * @property {number} gain dB applied to the whole mix
919
+ * @property {number} lufs the loudness it landed on
920
+ * @property {number} truePeak dBTP after
921
+ * @property {{ db: number, at: number } | null} limited the deepest the limiter
922
+ * went (dB) and when (s); null when it never had to
923
+ */
924
+
925
+ /**
926
+ * The mix at a loudness — −16 LUFS, where online video plays — with its true
927
+ * peak at or under −1 dBTP, the headroom the film's AAC encode needs. One gain
928
+ * does it; where that gain would push a peak past the ceiling, a look-ahead
929
+ * limiter takes that peak down (from 5 ms before it, letting go over 100 ms;
930
+ * both channels together, so the image stays put). Returns new channels; their
931
+ * `report` says what it did. A limiter that has to dig deep (several dB) is a
932
+ * mix whose peaks stand far above its body: turn those sounds down instead.
933
+ * @param {Channels | Signal} channels
934
+ * @param {number} [sampleRate]
935
+ * @param {{ lufs?: number, truePeak?: number }} [o]
936
+ * @returns {Channels & { report: NormalizeReport }}
937
+ */
938
+ export function normalize(
939
+ channels,
940
+ sampleRate = rateOf(channels),
941
+ { lufs = -16, truePeak = -1 } = {},
942
+ ) {
943
+ const chs = chans(channels);
944
+ const n = sameLength("normalize", chs);
945
+ chs.forEach((x, c) => {
946
+ const i = x.findIndex((v) => !Number.isFinite(v));
947
+ if (i >= 0)
948
+ throw new Error(
949
+ `normalize: channel ${c} is ${x[i]} at ${secs(i / sampleRate)} s — diagnose the stems to find which one`,
950
+ );
951
+ });
952
+ const before = integrated(blockPowers(chs, sampleRate));
953
+ if (before === Number.NEGATIVE_INFINITY)
954
+ throw new Error(
955
+ "normalize: the mix is silent, or shorter than 0.4 s — it has no loudness to set",
956
+ );
957
+ const ceiling = gainOf(truePeak);
958
+ const peaks = peakField(chs);
959
+ const out = chs.map(() => new Float32Array(n));
960
+ let gain = new Float32Array(0);
961
+ /** the mix at `db`, limited under `limit`; its loudness @param {number} db @param {number} limit */
962
+ const render = (db, limit) => {
963
+ const g0 = gainOf(db);
964
+ gain = limiter(peaks, g0, limit, sampleRate);
965
+ chs.forEach((x, c) => {
966
+ const o = /** @type {Float32Array} */ (out[c]);
967
+ for (let i = 0; i < n; i++) o[i] = (x[i] ?? 0) * g0 * (gain[i] ?? 1);
968
+ });
969
+ return integrated(blockPowers(out, sampleRate));
970
+ };
971
+ // the gain that lands on the target: the limiter takes back a little of
972
+ // whatever it is given, so search (secant steps in dB). It never goes past
973
+ // MORE dB over the plain gain: by then the limiter is taking back nearly all
974
+ // of it (a few short peaks over quiet), and pushing on only wrecks the sound
975
+ const MORE = 24;
976
+ const most = lufs - before + MORE;
977
+ /** @param {number} limit */
978
+ const land = (limit) => {
979
+ let d0 = lufs - before;
980
+ let l0 = render(d0, limit);
981
+ if (Math.abs(l0 - lufs) < 0.01) return d0;
982
+ let d1 = Math.min(d0 + (lufs - l0), most);
983
+ let l1 = render(d1, limit);
984
+ for (let k = 0; k < 12 && Math.abs(l1 - lufs) >= 0.01; k++) {
985
+ const slope = (l1 - l0) / (d1 - d0);
986
+ if (!(slope > 0.05) || d1 >= most) break; // more gain no longer makes it louder
987
+ const d2 = Math.min(d1 + (lufs - l1) / slope, most);
988
+ d0 = d1;
989
+ l0 = l1;
990
+ d1 = d2;
991
+ l1 = render(d1, limit);
992
+ }
993
+ if (Math.abs(l1 - lufs) > 0.5)
994
+ throw new Error(
995
+ `normalize: the mix cannot reach ${lufs < 0 ? "−" : ""}${Math.abs(lufs)} LUFS with its true peak under ${truePeak} dBTP — it gets to ${l1.toFixed(1)} LUFS with ${MORE} dB of limiting (its loud moments are too few and too short); bring up its quieter parts, or aim lower`,
996
+ );
997
+ return d1;
998
+ };
999
+ // aim a hair under the ceiling; if the gain's own movement still lets an
1000
+ // in-between peak through, aim lower by what came through
1001
+ let limit = ceiling * 0.999;
1002
+ let db = 0;
1003
+ let tp = 0;
1004
+ for (let round = 0; round < 4; round++) {
1005
+ db = land(limit);
1006
+ tp = Math.max(...out.map(truePeakOf));
1007
+ if (tp <= ceiling) break;
1008
+ limit *= (ceiling / tp) * 0.999;
1009
+ }
1010
+ if (tp > ceiling) {
1011
+ for (const o of out) for (let i = 0; i < n; i++) o[i] = (o[i] ?? 0) * (ceiling / tp);
1012
+ tp = ceiling;
1013
+ }
1014
+ let least = 1;
1015
+ let at = 0;
1016
+ for (let i = 0; i < n; i++)
1017
+ if ((gain[i] ?? 1) < least) {
1018
+ least = gain[i] ?? 1;
1019
+ at = i;
1020
+ }
1021
+ const report = {
1022
+ gain: Math.round(db * 100) / 100,
1023
+ lufs: Math.round(integrated(blockPowers(out, sampleRate)) * 100) / 100,
1024
+ truePeak: Math.round(dbOf(tp) * 100) / 100,
1025
+ limited:
1026
+ least < 0.9999
1027
+ ? { db: Math.round(dbOf(least) * 100) / 100, at: secs(at / sampleRate) }
1028
+ : null,
1029
+ };
1030
+ return Object.assign(withRate(out, sampleRate), { report });
1031
+ }
1032
+
1033
+ /** the peaks the limiter keeps down: for each sample, the largest |value| over
1034
+ * the channels in the sample periods either side of it (between samples
1035
+ * included), which one gain at that sample has to keep under the ceiling.
1036
+ * Worked out exactly only in blocks loud enough to need it, once.
1037
+ * @param {Signal[]} chs */
1038
+ function peakField(chs) {
1039
+ const n = chs[0]?.length ?? 0;
1040
+ const blocks = Math.ceil(n / BLOCK);
1041
+ const bound = Float32Array.from({ length: blocks }, (_, b) => blockBound(chs, b));
1042
+ const span = new Float32Array(n); // the peak over [i, i + 1)
1043
+ const done = new Uint8Array(blocks);
1044
+ return {
1045
+ n,
1046
+ blocks,
1047
+ bound,
1048
+ /** the peak a gain at sample i has to answer for (block b worked out first)
1049
+ * @param {number} b */
1050
+ exact(b) {
1051
+ if (!done[b]) {
1052
+ for (const x of chs)
1053
+ for (let i = b * BLOCK; i < Math.min(n, (b + 1) * BLOCK); i++)
1054
+ span[i] = Math.max(span[i] ?? 0, spanPeak(x, i));
1055
+ done[b] = 1;
1056
+ }
1057
+ // a sample in a block left alone is under any limit this block's bound is over
1058
+ return /** @param {number} i */ (i) => Math.max(span[i] ?? 0, i > 0 ? (span[i - 1] ?? 0) : 0);
1059
+ },
1060
+ };
1061
+ }
1062
+
1063
+ /** the gain curve that keeps the peaks × `gain` under `limit`: each sample gets
1064
+ * the lowest gain anything in the next 5 ms needs, eased back toward 1 over
1065
+ * 100 ms, then smoothed twice over 2.5 ms — which never lifts it over what any
1066
+ * sample needs, because each smoothing window lies inside the 5 ms looked at
1067
+ * @param {ReturnType<typeof peakField>} peaks @param {number} gain @param {number} limit @param {number} fs */
1068
+ function limiter(peaks, gain, limit, fs) {
1069
+ const n = peaks.n;
1070
+ const half = Math.max(1, Math.round(0.0025 * fs));
1071
+ const reach = 2 * half - 1;
1072
+ const need = new Float32Array(n).fill(1);
1073
+ for (let b = 0; b < peaks.blocks; b++) {
1074
+ if ((peaks.bound[b] ?? 0) * gain <= limit) continue; // nothing here can reach it
1075
+ const around = peaks.exact(b);
1076
+ for (let i = b * BLOCK; i < Math.min(n, (b + 1) * BLOCK); i++)
1077
+ need[i] = Math.min(1, limit / (gain * around(i)));
1078
+ }
1079
+ // the smallest need in [i, i + reach): a window minimum, walking backwards
1080
+ const g = new Float32Array(n);
1081
+ const q = new Int32Array(n);
1082
+ let head = 0;
1083
+ let tail = 0;
1084
+ for (let i = n - 1; i >= 0; i--) {
1085
+ const v = need[i] ?? 1;
1086
+ while (tail > head && (need[q[tail - 1] ?? 0] ?? 1) >= v) tail--;
1087
+ q[tail++] = i;
1088
+ while ((q[head] ?? 0) > i + reach - 1) head++;
1089
+ g[i] = need[q[head] ?? 0] ?? 1;
1090
+ }
1091
+ const back = Math.exp(-1 / (0.1 * fs));
1092
+ let r = 1;
1093
+ for (let i = 0; i < n; i++) {
1094
+ r = Math.min(g[i] ?? 1, 1 - (1 - r) * back);
1095
+ g[i] = r;
1096
+ }
1097
+ for (let pass = 0; pass < 2; pass++) {
1098
+ const src = Float32Array.from(g);
1099
+ let sum = 0;
1100
+ for (let i = 0; i < n; i++) {
1101
+ sum += src[i] ?? 0;
1102
+ if (i >= half) sum -= src[i - half] ?? 0;
1103
+ g[i] = sum / Math.min(i + 1, half);
1104
+ }
1105
+ }
1106
+ return g;
1107
+ }
1108
+
1109
+ // ---------------------------------------------------------------- checking
1110
+
1111
+ /**
1112
+ * @typedef {object} Finding
1113
+ * @property {string} stem the name it was given
1114
+ * @property {"nonfinite" | "clip" | "click" | "dc"} kind
1115
+ * @property {number[]} channels where it was found
1116
+ * @property {number} at s
1117
+ * @property {number} [end] s, for what lasts
1118
+ * @property {string} message what it is, and what usually causes it
1119
+ */
1120
+
1121
+ /**
1122
+ * What a mix hides, one stem at a time, each with its time: samples that are
1123
+ * not numbers; clipping; clicks; DC. A click is a jump in the waveform — its
1124
+ * second difference far above the RMS around it and above the jumps the sound
1125
+ * itself makes nearby (a saw's own edges repeat, so they do not count). It
1126
+ * comes from an envelope that jumps (a note cut short, a release from the
1127
+ * wrong level), a sound starting mid-cycle, oscillators started in phase so
1128
+ * their edges land together, or a filter that blew up. Run it on each bus or
1129
+ * stem as well as the master: in the mix, other sounds mask what it looks for.
1130
+ * The strike of a recorded marimba, harp, vibraphone or piano note is such a
1131
+ * jump and is the instrument: 300 sampled notes read with no exemption gave
1132
+ * 100 "clicks", each within 2 ms of a note's attack. Where `play` was told the
1133
+ * sound is a recording, a jump up to 5 ms after its attack is left out.
1134
+ * @param {string} name
1135
+ * @param {Channels | Signal} channels
1136
+ * @param {number | DiagnoseOptions} [sampleRate] or the options when using the sound's rate
1137
+ * @param {DiagnoseOptions} [options]
1138
+ * @returns {Finding[]}
1139
+ */
1140
+ export function diagnose(name, channels, sampleRate = rateOf(channels), options = {}) {
1141
+ const fs = typeof sampleRate === "number" ? sampleRate : rateOf(channels);
1142
+ const { transients, at: marked } = typeof sampleRate === "object" ? sampleRate : options;
1143
+ const chs = chans(channels);
1144
+ // the attacks of recordings played into it are intended too
1145
+ const recorded = attacksOf(channels);
1146
+ const at = recorded.length ? [...(marked ?? []), ...recorded] : marked;
1147
+ /** @type {Finding[]} */
1148
+ const found = [];
1149
+ chs.forEach((x, c) => {
1150
+ /** @param {Omit<Finding, "stem" | "channels">} f */
1151
+ const add = (f) => found.push({ stem: name, channels: [c], ...f });
1152
+ nonfinite(name, x, fs, add);
1153
+ clipping(name, x, fs, add);
1154
+ if (!transients) clicks(name, x, fs, add, at);
1155
+ offset(name, x, fs, add);
1156
+ });
1157
+ // the same thing at the same moment in several channels is one finding
1158
+ /** @type {Finding[]} */
1159
+ const merged = [];
1160
+ for (const f of found) {
1161
+ const same = merged.find(
1162
+ (m) =>
1163
+ m.kind === f.kind &&
1164
+ Math.abs(m.at - f.at) < 0.002 &&
1165
+ !m.channels.includes(/** @type {number} */ (f.channels[0])),
1166
+ );
1167
+ if (same) same.channels.push(...f.channels);
1168
+ else merged.push(f);
1169
+ }
1170
+ return merged.sort((a, b) => a.at - b.at);
1171
+ }
1172
+
1173
+ /** @typedef {object} DiagnoseOptions
1174
+ * @property {boolean} [transients] this whole bus holds intended clicks, e.g. keys or UI ticks
1175
+ * @property {readonly number[]} [at] only clicks up to 5 ms after these film times are intended
1176
+ */
1177
+
1178
+ /** @typedef {(f: Omit<Finding, "stem" | "channels">) => void} Add */
1179
+
1180
+ /** @param {string} name @param {Signal} x @param {number} fs @param {Add} add */
1181
+ function nonfinite(name, x, fs, add) {
1182
+ let first = -1;
1183
+ let last = -1;
1184
+ let count = 0;
1185
+ x.forEach((v, i) => {
1186
+ if (Number.isFinite(v)) return;
1187
+ if (first < 0) first = i;
1188
+ last = i;
1189
+ count++;
1190
+ });
1191
+ if (count)
1192
+ add({
1193
+ kind: "nonfinite",
1194
+ at: secs(first / fs),
1195
+ end: secs(last / fs),
1196
+ message:
1197
+ `${name}: ${count} sample${count > 1 ? "s are" : " is"} NaN or infinite, ` +
1198
+ `${secs(first / fs)}–${secs(last / fs)} s — a filter or feedback loop blew up, ` +
1199
+ "or a NaN came in (0/0, a missing value)",
1200
+ });
1201
+ }
1202
+
1203
+ /** samples past full scale, or flat on it (the same sample twice: a peak
1204
+ * that only touches 1.0 is not clipped), joined when under 10 ms apart
1205
+ * @param {string} name @param {Signal} x @param {number} fs @param {Add} add */
1206
+ function clipping(name, x, fs, add) {
1207
+ const join = Math.round(0.01 * fs);
1208
+ /** @type {{ a: number, b: number, peak: number, flat: boolean }[]} */
1209
+ const all = [];
1210
+ let prev = 0;
1211
+ x.forEach((v, i) => {
1212
+ const m = Math.abs(v);
1213
+ const flat = v === prev;
1214
+ prev = v;
1215
+ if (!(m >= 1) || !Number.isFinite(m)) return;
1216
+ const r = all[all.length - 1];
1217
+ if (r && i - r.b <= join) {
1218
+ r.b = i;
1219
+ r.peak = Math.max(r.peak, m);
1220
+ r.flat ||= flat;
1221
+ } else all.push({ a: i, b: i, peak: m, flat });
1222
+ });
1223
+ const runs = all.filter((r) => r.peak > 1 || r.flat);
1224
+ for (const r of runs.slice(0, 20)) {
1225
+ const at = secs(r.a / fs);
1226
+ const end = secs((r.b + 1) / fs);
1227
+ const db = Math.round(dbOf(r.peak) * 10) / 10;
1228
+ add({
1229
+ kind: "clip",
1230
+ at,
1231
+ end,
1232
+ message:
1233
+ r.peak >= 16
1234
+ ? `${name}: far over full scale ${at}–${end} s (peak +${db} dBFS) — something ran away: a filter or a feedback loop`
1235
+ : r.peak > 1
1236
+ ? `${name}: over full scale ${at}–${end} s (peak +${db} dBFS) — it clips when written; bring it down (normalize does, on the master)`
1237
+ : `${name}: flat at full scale ${at}–${end} s — already clipped`,
1238
+ });
1239
+ }
1240
+ if (runs.length > 20)
1241
+ add({
1242
+ kind: "clip",
1243
+ at: secs((runs[20]?.a ?? 0) / fs),
1244
+ message: `${name}: ${runs.length - 20} more runs at full scale after these`,
1245
+ });
1246
+ }
1247
+
1248
+ /** jumps: a second difference over 8× its RMS in the 5 ms either side (past
1249
+ * 1 ms, the width of a click), and over the jumps the sound itself makes out
1250
+ * to 25 ms: 2.5× the typical one when a side is quiet (a start, a cut), 4×
1251
+ * when both are busy (in a chord of plain saws, a few edges that fall
1252
+ * together by chance are part of its buzz)
1253
+ * @param {string} name @param {Signal} x @param {number} fs @param {Add} add
1254
+ * @param {readonly number[]} [intended] */
1255
+ function clicks(name, x, fs, add, intended) {
1256
+ const n = x.length;
1257
+ const guard = Math.round(0.001 * fs);
1258
+ const wide = Math.round(0.005 * fs);
1259
+ const far = Math.round(0.025 * fs);
1260
+ // the second difference, the signal taken as 0 outside it (a stem that
1261
+ // starts or stops on a non-zero sample starts or stops with a jump). Where
1262
+ // a sample is not a number, none; past 4, which only samples past full
1263
+ // scale can reach, 4 — those have findings of their own
1264
+ /** @param {number} i */
1265
+ const at = (i) => (i >= 0 && i < n ? (x[i] ?? 0) : 0);
1266
+ const d = new Float32Array(n + 2); // d[k] is the second difference at sample k − 1
1267
+ for (let k = 0; k < n + 2; k++) {
1268
+ const v = Math.abs(at(k) - 2 * at(k - 1) + at(k - 2));
1269
+ d[k] = Number.isFinite(v) ? Math.min(v, 4) : 0;
1270
+ }
1271
+ const sq = new Float64Array(n + 3);
1272
+ for (let k = 0; k < n + 2; k++) sq[k + 1] = (sq[k] ?? 0) + (d[k] ?? 0) ** 2;
1273
+ /** @param {number} a @param {number} b */
1274
+ const rms = (a, b) => {
1275
+ const lo = Math.max(0, a);
1276
+ const hi = Math.min(n + 2, b);
1277
+ return hi > lo ? Math.sqrt(((sq[hi] ?? 0) - (sq[lo] ?? 0)) / (hi - lo)) : 0;
1278
+ };
1279
+ /** the typical jump in [a, b): the median of the peaks of d at least
1280
+ * `floor` high (a resonant filter's ringing is lower, and left out); 0
1281
+ * when there are none — that side is quiet
1282
+ * @param {number} a @param {number} b @param {number} floor */
1283
+ const typical = (a, b, floor) => {
1284
+ const peaks = [];
1285
+ for (let k = Math.max(1, a); k < Math.min(n + 2, b); k++) {
1286
+ const v = d[k] ?? 0;
1287
+ if (v >= floor && v >= (d[k - 1] ?? 0) && v > (d[k + 1] ?? 0)) peaks.push(v);
1288
+ }
1289
+ peaks.sort((p, q) => p - q);
1290
+ return peaks[peaks.length >> 1] ?? 0;
1291
+ };
1292
+ let count = 0;
1293
+ let more = 0;
1294
+ for (let k = 0; k < n + 2; k++) {
1295
+ const v = d[k] ?? 0;
1296
+ if (v < 0.003) continue;
1297
+ const around = Math.max(
1298
+ rms(k - guard - wide, k - guard),
1299
+ rms(k + guard + 1, k + guard + 1 + wide),
1300
+ );
1301
+ if (v < 8 * around) continue;
1302
+ const before = typical(k - far, k - guard, v / 4);
1303
+ const after = typical(k + guard + 1, k + far + 1, v / 4);
1304
+ if (before && after ? v < 4 * Math.max(before, after) : v < 2.5 * (before || after)) continue;
1305
+ const time = Math.max(0, k - 1) / fs;
1306
+ if (intended?.some((at) => time >= at - 1 / fs && time <= at + 0.005)) {
1307
+ k += guard;
1308
+ continue;
1309
+ }
1310
+ const t = secs(time);
1311
+ if (++count === 21) more = t;
1312
+ if (count <= 20)
1313
+ add({
1314
+ kind: "click",
1315
+ at: t,
1316
+ message:
1317
+ `${name}: a click at ${t} s — a jump ${around > 0 ? `${Math.round(v / around)}×` : "far above"} ` +
1318
+ "the sound around it: a note cut short, a release from the wrong level, a sound " +
1319
+ "starting mid-cycle, oscillators started in phase, or a filter that blew up",
1320
+ });
1321
+ k += guard; // one click, not its neighbours
1322
+ }
1323
+ if (count > 20)
1324
+ add({ kind: "click", at: more, message: `${name}: ${count - 20} more clicks from ${more} s` });
1325
+ }
1326
+
1327
+ /** DC: the mean of 1 s windows (every 0.5 s) past 0.01 (−40 dBFS)
1328
+ * @param {string} name @param {Signal} x @param {number} fs @param {Add} add */
1329
+ function offset(name, x, fs, add) {
1330
+ const win = Math.min(x.length, fs);
1331
+ if (win === 0) return;
1332
+ /** @type {{ a: number, b: number, worst: number } | null} */
1333
+ let run = null;
1334
+ /** @type {{ a: number, b: number, worst: number }[]} */
1335
+ const runs = [];
1336
+ for (let a = 0; a + win <= x.length; a += Math.max(1, Math.round(win / 2))) {
1337
+ let sum = 0;
1338
+ for (let i = a; i < a + win; i++) {
1339
+ const v = x[i] ?? 0;
1340
+ if (Number.isFinite(v)) sum += v;
1341
+ }
1342
+ const mean = sum / win;
1343
+ if (Math.abs(mean) <= 0.01) run = null;
1344
+ else if (run) {
1345
+ run.b = a + win;
1346
+ if (Math.abs(mean) > Math.abs(run.worst)) run.worst = mean;
1347
+ } else {
1348
+ run = { a, b: a + win, worst: mean };
1349
+ runs.push(run);
1350
+ }
1351
+ }
1352
+ for (const r of runs)
1353
+ add({
1354
+ kind: "dc",
1355
+ at: secs(r.a / fs),
1356
+ end: secs(r.b / fs),
1357
+ message:
1358
+ `${name}: a DC offset of ${r.worst > 0 ? "+" : ""}${Math.round(r.worst * 1000) / 1000} ` +
1359
+ `(${Math.round(dbOf(Math.abs(r.worst)))} dBFS), ${secs(r.a / fs)}–${secs(r.b / fs)} s — ` +
1360
+ "a wave not centred on 0 (Math.random() for noise instead of 2·random − 1, a one-sided pulse)",
1361
+ });
1362
+ }
1363
+
1364
+ // ---------------------------------------------------------------- material
1365
+
1366
+ // Sound that is not synthesized: a recording, the product's own sounds, a
1367
+ // licensed track. `load` decodes any audio file ffmpeg reads; the rest place a
1368
+ // piece of it in the film — a slice, aligned on its attack or its peak to a
1369
+ // moment, faster or slower, with its level, pan and send following numbers or
1370
+ // a curve the picture exported, into a bus or a shared room.
1371
+ //
1372
+ // const ev = readEvents("film.events.json"); // `film render` wrote it
1373
+ // const tap = slice(load("taps.wav"), 1.2, 1.5);
1374
+ // for (const e of ev.events.filter((e) => e.kind === "key"))
1375
+ // play(sfx, tap, e.t, { align: "onset", pan: panFor(e.x ?? 960), gain: 0.5 });
1376
+ // const room = space(ev.duration, { size: 0.3 });
1377
+ // play(music, load("track.m4a"), 0, { gain: curveOf(ev, "zoom", (z) => 0.6 + 0.2 * z),
1378
+ // send: { bus: room.send, amount: 0.15 } });
1379
+ // mix(master, room.wet());
1380
+
1381
+ /**
1382
+ * A number that stays put, or one that follows film time: `(t) => number`, t
1383
+ * in seconds of the film. Followed at 750 points a second (every 64 samples
1384
+ * at 48 kHz) and smoothed between them.
1385
+ * @typedef {number | ((t: number) => number)} Auto
1386
+ */
1387
+
1388
+ /** automation is read every this many samples, and linear between */
1389
+ const CTRL = 64;
1390
+
1391
+ /** the ffmpeg build `open-take` fetches for this machine, as its release names it */
1392
+ const managedKey = () =>
1393
+ process.platform === "win32" && process.arch === "arm64"
1394
+ ? "win32-x64"
1395
+ : `${process.platform}-${process.arch}`;
1396
+
1397
+ /** @type {string | null} */
1398
+ let ffmpegFound = null;
1399
+
1400
+ /**
1401
+ * The ffmpeg `load` decodes with: OPEN_TAKE_FFMPEG when it is set; else one on
1402
+ * PATH; else the one open-take keeps in ~/.open-take/ffmpeg (fetched by any
1403
+ * `open-take` render).
1404
+ * @returns {string}
1405
+ */
1406
+ export function findFfmpeg() {
1407
+ ffmpegFound ??= locateFfmpeg();
1408
+ return ffmpegFound;
1409
+ }
1410
+
1411
+ /** @returns {string} */
1412
+ function locateFfmpeg() {
1413
+ const exe = process.platform === "win32" ? "ffmpeg.exe" : "ffmpeg";
1414
+ /** @param {string} bin */
1415
+ const runs = (bin) => spawnSync(bin, ["-version"], { stdio: "ignore" }).status === 0;
1416
+ const named = process.env.OPEN_TAKE_FFMPEG;
1417
+ if (named) {
1418
+ if (!runs(named)) throw new Error(`load: OPEN_TAKE_FFMPEG (${named}) does not run`);
1419
+ return named;
1420
+ }
1421
+ if (runs("ffmpeg")) return "ffmpeg";
1422
+ const home = join(homedir(), ".open-take", "ffmpeg");
1423
+ const releases = existsSync(home) ? readdirSync(home).sort().reverse() : [];
1424
+ for (const r of releases) {
1425
+ const bin = join(home, r, managedKey(), exe);
1426
+ if (existsSync(bin) && runs(bin)) return bin;
1427
+ }
1428
+ throw new Error(
1429
+ "load: no ffmpeg — set OPEN_TAKE_FFMPEG, install one, or run any `open-take` render once (it fetches one)",
1430
+ );
1431
+ }
1432
+
1433
+ /**
1434
+ * Any audio file ffmpeg reads (wav, mp3, m4a, ogg, flac, the sound of a
1435
+ * video…), decoded to float channels at `sampleRate` (default the film's
1436
+ * 48 kHz). `channels` defaults to the file's: mono stays mono (pan places it),
1437
+ * anything wider comes as stereo.
1438
+ * @param {string} path
1439
+ * @param {{ sampleRate?: number, channels?: number }} [o]
1440
+ * @returns {Channels}
1441
+ */
1442
+ export function load(path, { sampleRate = RATE, channels } = {}) {
1443
+ if (!existsSync(path)) throw new Error(`load: there is no file at ${path}`);
1444
+ const ffmpeg = findFfmpeg();
1445
+ let n = channels;
1446
+ if (n == null) {
1447
+ // ffmpeg describes the input, then stops: no output was asked for
1448
+ const info = spawnSync(ffmpeg, ["-hide_banner", "-i", path], { encoding: "utf8" });
1449
+ const stream = /Stream #\S+.*?Audio: ([^\n]*)/.exec(info.stderr ?? "");
1450
+ if (!stream) throw new Error(`load: ${path} has no sound ffmpeg can read`);
1451
+ n = /\bmono\b|\b1 channels\b/.test(stream[1] ?? "") ? 1 : 2;
1452
+ }
1453
+ if (!(n >= 1 && Number.isInteger(n))) throw new Error(`load: ${channels} is not a channel count`);
1454
+ const r = spawnSync(
1455
+ ffmpeg,
1456
+ [
1457
+ "-v",
1458
+ "error",
1459
+ "-i",
1460
+ path,
1461
+ "-map",
1462
+ "0:a:0",
1463
+ "-f",
1464
+ "f32le",
1465
+ "-acodec",
1466
+ "pcm_f32le",
1467
+ "-ar",
1468
+ String(sampleRate),
1469
+ "-ac",
1470
+ String(n),
1471
+ "-",
1472
+ ],
1473
+ { maxBuffer: 2 ** 31 - 1 },
1474
+ );
1475
+ if (r.status !== 0)
1476
+ throw new Error(
1477
+ `load: ffmpeg could not decode ${path}: ${String(r.stderr).trim().slice(-400)}`,
1478
+ );
1479
+ const raw = /** @type {Buffer} */ (r.stdout);
1480
+ const frames = Math.floor(raw.length / 4 / n);
1481
+ const all = new Float32Array(raw.buffer.slice(raw.byteOffset, raw.byteOffset + frames * n * 4));
1482
+ const out = Array.from({ length: n }, () => new Float32Array(frames));
1483
+ for (let i = 0; i < frames; i++)
1484
+ for (let c = 0; c < n; c++) /** @type {Float32Array} */ (out[c])[i] = all[i * n + c] ?? 0;
1485
+ return withRate(out, sampleRate);
1486
+ }
1487
+
1488
+ /**
1489
+ * <film>.events.json, as `film render` writes it beside the film: the page's
1490
+ * events (t, kind, x, y, force, label), its cuts, its curves sampled once
1491
+ * a frame — for `curveOf` — and the credits the page kept (what it uses that
1492
+ * someone else made, and on what licence; [] in a file written before there
1493
+ * were credits).
1494
+ * @param {string} path
1495
+ * @returns {FilmEvents}
1496
+ */
1497
+ export function readEvents(path) {
1498
+ /** @type {FilmEvents} */
1499
+ let ev;
1500
+ try {
1501
+ ev = JSON.parse(readFileSync(path, "utf8"));
1502
+ } catch (e) {
1503
+ throw new Error(`readEvents: ${path}: ${/** @type {Error} */ (e).message}`);
1504
+ }
1505
+ if (ev?.version !== 1 || !Array.isArray(ev.events) || !ev.curves)
1506
+ throw new Error(`readEvents: ${path} is not an events file \`film render\` writes (version 1)`);
1507
+ if (!Array.isArray(ev.credits)) ev.credits = [];
1508
+ return ev;
1509
+ }
1510
+
1511
+ /**
1512
+ * @typedef {object} FilmEvents <film>.events.json (times in seconds of the page's timeline)
1513
+ * @property {1} version
1514
+ * @property {number} duration
1515
+ * @property {number} fps
1516
+ * @property {[number, number]} [range] [from, to) when only part of the film was rendered
1517
+ * @property {{ t: number, kind: string, x?: number, y?: number, force?: number, label?: string }[]} events
1518
+ * @property {number[]} cuts
1519
+ * @property {number[]} [declaredCuts]
1520
+ * @property {number[]} [detectedCuts]
1521
+ * @property {{ names: string[], t0: number, dt: number, rows: (number | null)[][] }} curves
1522
+ * @property {{ what?: string, by?: string, licence?: string, url?: string, text?: string }[]} [credits]
1523
+ * window.__film.credits: information only, nothing checks it
1524
+ */
1525
+
1526
+ /**
1527
+ * One of the film's curves as a function of film time, for an `Auto`: linear
1528
+ * between frames — and across frames the page gave no number — held past the ends.
1529
+ * `map` turns its value into what you want (a gain, a pan, a send).
1530
+ *
1531
+ * A hard cut is not a move: the curve is split there, not drawn straight
1532
+ * across. Each shot is its own curve — linear inside it, its last value held
1533
+ * up to the cut, the next shot's first value from the cut on — so a level
1534
+ * that follows the camera steps with the picture instead of gliding into the
1535
+ * cut a frame early or spiking over it. The cuts are, by default, the events
1536
+ * file's (`declaredCuts` and `detectedCuts`, merged when less than half a
1537
+ * frame apart); `{ cuts: [...] }` gives your own (times, or events of kind
1538
+ * "cut"), `{ cuts: [] }` draws straight across them all. A cut at c belongs to
1539
+ * the shot that starts at c. A shot the page gave no number in (or one
1540
+ * shorter than a frame, e.g. a declared cut a frame off the one the picture
1541
+ * shows) holds the last number before it, or the first after. A step is a step: smooth it in the
1542
+ * score (e.g. a short crossfade) if you want it softer.
1543
+ *
1544
+ * gain: curveOf(ev, "camSpeed", (v) => 0.2 + v / 4000) // split at the film's cuts
1545
+ * gain: curveOf(ev, "camSpeed", { map: (v) => v / 4000, cuts: [] }) // straight across
1546
+ * // "picture.energy", when the render could read it: how much the picture changes into each frame (0..1)
1547
+ * gain: curveOf(ev, "picture.energy", { map: (e) => 0.5 + Math.min(0.5, e * 40), cuts: [] })
1548
+ *
1549
+ * @param {FilmEvents} ev
1550
+ * @param {string} name
1551
+ * @param {((v: number) => number) | CurveOptions} [mapOrOptions]
1552
+ * @param {CurveOptions} [options]
1553
+ * @returns {(t: number) => number}
1554
+ * @typedef {object} CurveOptions
1555
+ * @property {(v: number) => number} [map]
1556
+ * @property {readonly (number | { t?: number, t0?: number, kind?: string })[]} [cuts] default the events file's
1557
+ */
1558
+ export function curveOf(ev, name, mapOrOptions, options = {}) {
1559
+ const o =
1560
+ typeof mapOrOptions === "function"
1561
+ ? { ...options, map: mapOrOptions }
1562
+ : { ...(mapOrOptions ?? {}), ...options };
1563
+ const map = o.map ?? ((v) => v);
1564
+ const j = ev.curves.names.indexOf(name);
1565
+ if (j < 0)
1566
+ throw new Error(
1567
+ `curveOf: the film has no curve "${name}" (it has: ${ev.curves.names.join(", ") || "none"})`,
1568
+ );
1569
+ const { t0, dt } = ev.curves;
1570
+ // the cuts, ascending: the caller's, or the events file's own
1571
+ /** @param {readonly (number | { t?: number, t0?: number, kind?: string })[] | undefined} list */
1572
+ const times = (list) =>
1573
+ (list ?? [])
1574
+ .map((c) =>
1575
+ typeof c === "number"
1576
+ ? c
1577
+ : c && c.kind === "cut"
1578
+ ? (c.t ?? c.t0 ?? Number.NaN)
1579
+ : Number.NaN,
1580
+ )
1581
+ .filter((t) => Number.isFinite(t));
1582
+ const cuts = (
1583
+ o.cuts != null
1584
+ ? times(o.cuts)
1585
+ : times([...(ev.declaredCuts ?? []), ...(ev.detectedCuts ?? []), ...(ev.cuts ?? [])])
1586
+ )
1587
+ .sort((a, b) => a - b)
1588
+ .filter((t, i, all) => i === 0 || t - (all[i - 1] ?? 0) >= dt / 2);
1589
+ // which shot a time is in: how many cuts lie at or before it
1590
+ const tol = Math.min(1e-6, dt / 1000);
1591
+ /** @param {number} t */
1592
+ const shotOf = (t) => {
1593
+ let k = 0;
1594
+ while (k < cuts.length && t >= (cuts[k] ?? 0) - tol) k++;
1595
+ return k;
1596
+ };
1597
+ // the frames the page gave a number for, with the number, and the shot each is in
1598
+ /** @type {number[]} */
1599
+ const at = [];
1600
+ /** @type {number[]} */
1601
+ const vs = [];
1602
+ /** @type {number[]} */
1603
+ const shots = [];
1604
+ ev.curves.rows.forEach((row, i) => {
1605
+ const v = row[j];
1606
+ if (typeof v === "number" && Number.isFinite(v)) {
1607
+ at.push(i);
1608
+ vs.push(v);
1609
+ shots.push(shotOf(t0 + i * dt));
1610
+ }
1611
+ });
1612
+ if (!at.length) throw new Error(`curveOf: the curve "${name}" has no numbers`);
1613
+ // each shot's run of frames in `at` (frames are in time order, so shots are runs)
1614
+ /** @type {Map<number, [number, number]>} */
1615
+ const runs = new Map();
1616
+ shots.forEach((k, i) => {
1617
+ const r = runs.get(k);
1618
+ if (r) r[1] = i + 1;
1619
+ else runs.set(k, [i, i + 1]);
1620
+ });
1621
+ /** linear between the frames lo..hi-1 of `at`, held past them @param {number} f @param {number} first @param {number} end */
1622
+ const within = (f, first, end) => {
1623
+ const last = end - 1;
1624
+ if (f <= (at[first] ?? 0)) return vs[first] ?? 0;
1625
+ if (f >= (at[last] ?? 0)) return vs[last] ?? 0;
1626
+ let lo = first;
1627
+ let hi = last;
1628
+ while (hi - lo > 1) {
1629
+ const mid = (lo + hi) >> 1;
1630
+ if ((at[mid] ?? 0) <= f) lo = mid;
1631
+ else hi = mid;
1632
+ }
1633
+ const a = at[lo] ?? 0;
1634
+ const b = at[hi] ?? a + 1;
1635
+ const u = (f - a) / (b - a);
1636
+ return (vs[lo] ?? 0) * (1 - u) + (vs[hi] ?? 0) * u;
1637
+ };
1638
+ return (t) => {
1639
+ const f = (t - t0) / dt;
1640
+ if (!cuts.length) return map(within(f, 0, at.length));
1641
+ const k = shotOf(t);
1642
+ const run = runs.get(k);
1643
+ if (run) return map(within(f, run[0], run[1]));
1644
+ // a shot with no numbers (none given there, or shorter than a frame): the
1645
+ // nearest number before it held, else the first after — never a glide
1646
+ // across a cut
1647
+ let i = shots.length - 1;
1648
+ while (i >= 0 && (shots[i] ?? 0) > k) i--;
1649
+ return map(vs[i >= 0 ? i : shots.findIndex((s) => s > k)] ?? 0);
1650
+ };
1651
+ }
1652
+
1653
+ /**
1654
+ * Where a point on the stage sits left to right, as a pan: −1 at the left
1655
+ * edge, 1 at the right, times `spread` (0.5 keeps it nearer the middle).
1656
+ * @param {number} x stage px
1657
+ * @param {number} [width] the stage's width (px)
1658
+ * @param {number} [spread]
1659
+ */
1660
+ export const panFor = (x, width = 1920, spread = 1) =>
1661
+ Math.max(-1, Math.min(1, ((2 * x) / width - 1) * spread));
1662
+
1663
+ /**
1664
+ * A copy of [from, to) s of a sound (to: its end).
1665
+ * @param {Channels | Signal} sound
1666
+ * @param {number} from
1667
+ * @param {number} [to]
1668
+ * @returns {Channels}
1669
+ */
1670
+ export function slice(sound, from, to) {
1671
+ const sr = rateOf(sound);
1672
+ const src = chans(sound);
1673
+ const n = src[0]?.length ?? 0;
1674
+ const a = Math.max(0, Math.min(n, Math.round(from * sr)));
1675
+ const b = Math.max(a, Math.min(n, Math.round((to ?? n / sr) * sr)));
1676
+ return withRate(
1677
+ src.map((c) => Float32Array.from(c.subarray(a, b))),
1678
+ sr,
1679
+ );
1680
+ }
1681
+
1682
+ /**
1683
+ * A copy with gentle edges: raised-cosine fades `in` s at the start and `out`
1684
+ * s at the end — a slice cut out of a recording starts and ends mid-wave,
1685
+ * which is a click.
1686
+ * @param {Channels | Signal} sound
1687
+ * @param {{ in?: number, out?: number }} [o]
1688
+ * @returns {Channels}
1689
+ */
1690
+ export function fade(sound, { in: fin = 0.003, out = 0.01 } = {}) {
1691
+ const sr = rateOf(sound);
1692
+ const out_ = chans(sound).map((c) => Float32Array.from(c));
1693
+ const n = out_[0]?.length ?? 0;
1694
+ const a = Math.min(n, Math.round(fin * sr));
1695
+ const b = Math.min(n, Math.round(out * sr));
1696
+ for (const c of out_) {
1697
+ for (let i = 0; i < a; i++) c[i] = (c[i] ?? 0) * 0.5 * (1 - Math.cos((Math.PI * i) / a));
1698
+ for (let i = 0; i < b; i++)
1699
+ c[n - 1 - i] = (c[n - 1 - i] ?? 0) * 0.5 * (1 - Math.cos((Math.PI * i) / b));
1700
+ }
1701
+ return withRate(out_, sr);
1702
+ }
1703
+
1704
+ /** |x| at its largest across channels, sample by sample @param {Signal[]} src */
1705
+ function magnitude(src) {
1706
+ const n = src[0]?.length ?? 0;
1707
+ const m = new Float32Array(n);
1708
+ for (const c of src) for (let i = 0; i < n; i++) m[i] = Math.max(m[i] ?? 0, Math.abs(c[i] ?? 0));
1709
+ return m;
1710
+ }
1711
+
1712
+ /**
1713
+ * When a sound's attack begins (s into it): where its level — the RMS over
1714
+ * `window` s — first reaches `threshold` of its loudest (0.1 is 20 dB down),
1715
+ * traced back to the first sample of that rise above a tenth of it. Line a
1716
+ * recorded key's attack up with the key, not the silence the recording starts
1717
+ * with. null when it is silent.
1718
+ * @param {Channels | Signal} sound
1719
+ * @param {{ threshold?: number, window?: number }} [o]
1720
+ * @returns {number | null}
1721
+ */
1722
+ export function onsetOf(sound, { threshold = 0.1, window = 0.002 } = {}) {
1723
+ const sr = rateOf(sound);
1724
+ const m = magnitude(chans(sound));
1725
+ const w = Math.max(1, Math.round(window * sr));
1726
+ const level = new Float32Array(m.length);
1727
+ let sum = 0;
1728
+ let top = 0;
1729
+ for (let i = 0; i < m.length; i++) {
1730
+ sum += (m[i] ?? 0) ** 2 - (i >= w ? (m[i - w] ?? 0) ** 2 : 0);
1731
+ const v = Math.sqrt(Math.max(0, sum) / w);
1732
+ level[i] = v;
1733
+ if (v > top) top = v;
1734
+ }
1735
+ if (top <= 0) return null;
1736
+ // the level reaches the threshold at i, over the w samples up to it; the
1737
+ // attack began at the first of those that is not still silence (a tenth of
1738
+ // the threshold, so the quiet before it does not count)
1739
+ const i = level.findIndex((v) => v >= threshold * top);
1740
+ let j = Math.max(0, i - w + 1);
1741
+ while (j < i && (m[j] ?? 0) < 0.1 * threshold * top) j++;
1742
+ return j / sr;
1743
+ }
1744
+
1745
+ /**
1746
+ * Where the attack hits (s into the sound): the boundary between adjacent
1747
+ * `window`-second windows with the largest rise in mean square level. A soft
1748
+ * lead-in can reach onsetOf's threshold long before this. null when silent.
1749
+ * @param {Channels | Signal} sound
1750
+ * @param {{ window?: number }} [o]
1751
+ * @returns {number | null}
1752
+ */
1753
+ export function hitOf(sound, { window = 0.004 } = {}) {
1754
+ if (!(window > 0) || !Number.isFinite(window)) throw new Error("hitOf: window must be positive");
1755
+ const sr = rateOf(sound);
1756
+ const m = magnitude(chans(sound));
1757
+ const w = Math.max(1, Math.min(m.length, Math.round(window * sr)));
1758
+ const sums = new Float64Array(m.length + 1);
1759
+ for (let i = 0; i < m.length; i++) sums[i + 1] = (sums[i] ?? 0) + (m[i] ?? 0) ** 2;
1760
+ // A sound that dies within one window rises by the same amount at every
1761
+ // boundary up to its first sample: take the last of those equal rises.
1762
+ let best = 0;
1763
+ let at = null;
1764
+ let level = false;
1765
+ for (let i = 0; i < m.length; i++) {
1766
+ const rise = (sums[Math.min(m.length, i + w)] ?? 0) - 2 * (sums[i] ?? 0) + (sums[Math.max(0, i - w)] ?? 0);
1767
+ const close = 1e-9 * (sums[m.length] ?? 0);
1768
+ if (rise > best + close) {
1769
+ best = rise;
1770
+ at = i / sr;
1771
+ level = true;
1772
+ } else if (level && rise >= best - close) at = i / sr;
1773
+ else level = false;
1774
+ }
1775
+ return at;
1776
+ }
1777
+
1778
+ /**
1779
+ * Where a sound is loudest (s into it): its largest sample. null when silent.
1780
+ * @param {Channels | Signal} sound
1781
+ * @returns {number | null}
1782
+ */
1783
+ export function peakOf(sound) {
1784
+ const m = magnitude(chans(sound));
1785
+ let best = 0;
1786
+ let at = -1;
1787
+ for (let i = 0; i < m.length; i++)
1788
+ if ((m[i] ?? 0) > best) {
1789
+ best = m[i] ?? 0;
1790
+ at = i;
1791
+ }
1792
+ return at < 0 ? null : at / rateOf(sound);
1793
+ }
1794
+
1795
+ /** I0, the modified Bessel function — for the Kaiser window @param {number} x */
1796
+ function bessel0(x) {
1797
+ let sum = 1;
1798
+ let term = 1;
1799
+ for (let k = 1; k < 64 && term > sum * 1e-17; k++) {
1800
+ term *= (x / (2 * k)) ** 2;
1801
+ sum += term;
1802
+ }
1803
+ return sum;
1804
+ }
1805
+
1806
+ /** the Kaiser window (β 8) at |r| = i / KAISER_N, 0..1, looked up and interpolated */
1807
+ const KAISER_N = 4096;
1808
+ /** @type {Float64Array | null} */
1809
+ let kaiserTable = null;
1810
+ /** @param {number} r −1..1 */
1811
+ function kaiser(r) {
1812
+ if (!kaiserTable) {
1813
+ const t = new Float64Array(KAISER_N + 2);
1814
+ const i0 = bessel0(8);
1815
+ for (let i = 0; i <= KAISER_N; i++)
1816
+ t[i] = bessel0(8 * Math.sqrt(Math.max(0, 1 - (i / KAISER_N) ** 2))) / i0;
1817
+ kaiserTable = t;
1818
+ }
1819
+ const x = Math.abs(r) * KAISER_N;
1820
+ const i = Math.floor(x);
1821
+ const a = kaiserTable[i] ?? 0;
1822
+ return a + ((kaiserTable[i + 1] ?? 0) - a) * (x - i);
1823
+ }
1824
+
1825
+ /**
1826
+ * A sound played `rate` times as fast: pitch and length change together, as
1827
+ * a tape's do (2 is an octave up and half as long; `2 ** (n / 12)` is n
1828
+ * semitones). Windowed-sinc interpolation (Kaiser, β 8, 16 zero crossings a
1829
+ * side), its cutoff lowered when it speeds up so nothing folds back.
1830
+ * @param {Channels | Signal} sound
1831
+ * @param {number} rate
1832
+ * @returns {Channels}
1833
+ */
1834
+ export function varispeed(sound, rate) {
1835
+ if (!(rate > 0) || !Number.isFinite(rate))
1836
+ throw new Error(`varispeed: rate must be a number above 0 (got ${rate})`);
1837
+ const sr = rateOf(sound);
1838
+ const src = chans(sound);
1839
+ if (rate === 1)
1840
+ return withRate(
1841
+ src.map((c) => Float32Array.from(c)),
1842
+ sr,
1843
+ );
1844
+ const n = src[0]?.length ?? 0;
1845
+ const m = Math.floor((n - 1) / rate) + 1;
1846
+ const cut = Math.min(1, 1 / rate); // of Nyquist
1847
+ const zeros = 16;
1848
+ const reach = Math.ceil(zeros / cut);
1849
+ const out = src.map(() => new Float32Array(m));
1850
+ const acc = new Float64Array(src.length);
1851
+ for (let j = 0; j < m; j++) {
1852
+ const pos = j * rate;
1853
+ const base = Math.floor(pos);
1854
+ let wsum = 0;
1855
+ acc.fill(0);
1856
+ for (let k = base - reach + 1; k <= base + reach; k++) {
1857
+ if (k < 0 || k >= n) continue;
1858
+ const u = (pos - k) * cut;
1859
+ const r = u / zeros;
1860
+ if (r <= -1 || r >= 1) continue;
1861
+ const sinc = u === 0 ? 1 : Math.sin(Math.PI * u) / (Math.PI * u);
1862
+ const w = sinc * kaiser(r);
1863
+ wsum += w;
1864
+ for (let c = 0; c < src.length; c++) acc[c] = (acc[c] ?? 0) + w * (src[c]?.[k] ?? 0);
1865
+ }
1866
+ // normalized by the weights: unity at DC, near the edges too
1867
+ for (let c = 0; c < src.length; c++)
1868
+ /** @type {Float32Array} */ (out[c])[j] = wsum ? (acc[c] ?? 0) / wsum : 0;
1869
+ }
1870
+ return withRate(out, sr);
1871
+ }
1872
+
1873
+ /** an Auto's value at film time t @param {Auto} v @param {number} t */
1874
+ const autoAt = (v, t) => (typeof v === "function" ? v(t) : v);
1875
+
1876
+ /**
1877
+ * Place a sound in a bus at film time `at`: the point of it named by `align`
1878
+ * — its start, its attack (`onsetOf`), its fastest rise (`hitOf`), its loudest sample (`peakOf`), or a
1879
+ * time into it (s) — lands on `at`. On the way it can be sped up or slowed
1880
+ * (`rate`, `semitones`: pitch and length together), and its gain, pan and send
1881
+ * can each be a number or follow film time (an `Auto`, e.g. `curveOf`). A pan
1882
+ * places a mono sound between the speakers at equal power (−3 dB each in the
1883
+ * middle) and balances a stereo one; without one, every channel gets the gain,
1884
+ * as `mix` does. `send` puts the same sound, times `amount`, into a shared
1885
+ * room's send bus (`space`) as well. Returns where in the film it sounds (s).
1886
+ * When `"onset"` and `"hit"` would land over 50 ms apart, it also prints a
1887
+ * warning to stderr and returns it as `warning`.
1888
+ * @param {Channels} into
1889
+ * @param {Channels | Signal} sound
1890
+ * @param {number} at
1891
+ * @param {object} [o]
1892
+ * @param {"start" | "onset" | "hit" | "peak" | number} [o.align]
1893
+ * @param {number} [o.rate]
1894
+ * @param {number} [o.semitones]
1895
+ * @param {Auto} [o.gain] linear (10 ** (dB / 20))
1896
+ * @param {Auto} [o.pan] -1 left to 1 right
1897
+ * @param {{ bus: Channels, amount?: Auto }} [o.send]
1898
+ * @param {boolean} [o.recorded] the sound is a recording of an instrument: its
1899
+ * attack is its own, and `diagnose` does not call it a click
1900
+ * @returns {{ start: number, end: number, warning?: string }}
1901
+ */
1902
+ export function play(
1903
+ into,
1904
+ sound,
1905
+ at,
1906
+ { align = "start", rate = 1, semitones = 0, gain = 1, pan, send, recorded = false } = {},
1907
+ ) {
1908
+ if (!Number.isFinite(at)) throw new Error(`play: ${at} is not a time in seconds`);
1909
+ const sr = into.sampleRate ?? RATE;
1910
+ const b = /** @type {{ sampleRate?: number }} */ (sound).sampleRate;
1911
+ if (b && b !== sr) throw new Error(`play: ${b} Hz into ${sr} Hz — load it at ${sr}`);
1912
+ const speed = rate * 2 ** (semitones / 12);
1913
+ // a sound without a rate plays at the bus's, so its times are read at that rate
1914
+ const timed = b ? sound : withRate([...chans(sound)], sr);
1915
+ const hit = align === "hit" || align === "onset" ? hitOf(timed) : null;
1916
+ const point =
1917
+ typeof align === "number"
1918
+ ? align
1919
+ : align === "onset"
1920
+ ? (onsetOf(timed) ?? 0)
1921
+ : align === "hit"
1922
+ ? (hit ?? 0)
1923
+ : align === "peak"
1924
+ ? (peakOf(timed) ?? 0)
1925
+ : 0;
1926
+ const src = speed === 1 ? chans(sound) : varispeed(sound, speed);
1927
+ const start = at - point / speed;
1928
+ const n = src[0]?.length ?? 0;
1929
+ const s0 = Math.round(start * sr);
1930
+ /** @param {Channels} bus @param {Auto} amount */
1931
+ const into1 = (bus, amount) => {
1932
+ const stereo = pan !== undefined && bus.length === 2;
1933
+ const i0 = Math.max(0, -s0);
1934
+ const i1 = Math.min(n, (bus[0]?.length ?? 0) - s0);
1935
+ for (let blk = i0; blk < i1; blk += CTRL) {
1936
+ const end = Math.min(i1, blk + CTRL);
1937
+ // the automation at both ends of the block, and linear between
1938
+ /** @param {number} i */
1939
+ const gains = (i) => {
1940
+ const t = (s0 + i) / sr;
1941
+ const g = autoAt(gain, t) * autoAt(amount, t);
1942
+ if (!stereo) return [g, g];
1943
+ const p = Math.max(-1, Math.min(1, autoAt(/** @type {Auto} */ (pan), t)));
1944
+ if (src.length === 1) {
1945
+ const th = ((p + 1) * Math.PI) / 4;
1946
+ return [g * Math.cos(th), g * Math.sin(th)];
1947
+ }
1948
+ return [
1949
+ g * (p > 0 ? Math.cos((p * Math.PI) / 2) : 1),
1950
+ g * (p < 0 ? Math.cos((-p * Math.PI) / 2) : 1),
1951
+ ];
1952
+ };
1953
+ const [la, ra] = /** @type {[number, number]} */ (gains(blk));
1954
+ const [lb, rb] = /** @type {[number, number]} */ (gains(end));
1955
+ if (![la, ra, lb, rb].every(Number.isFinite))
1956
+ throw new Error(`play: a gain, pan or send is not a number at ${secs((s0 + blk) / sr)} s`);
1957
+ bus.forEach((dst, c) => {
1958
+ const s = /** @type {Signal} */ (
1959
+ src.length === 1 ? src[0] : src[Math.min(c, src.length - 1)]
1960
+ );
1961
+ const g0 = stereo ? (c === 0 ? la : ra) : la;
1962
+ const g1 = stereo ? (c === 0 ? lb : rb) : lb;
1963
+ const span = end - blk;
1964
+ for (let i = blk; i < end; i++) {
1965
+ const g = g0 + ((g1 - g0) * (i - blk)) / span;
1966
+ dst[s0 + i] = (dst[s0 + i] ?? 0) + (s[i] ?? 0) * g;
1967
+ }
1968
+ });
1969
+ }
1970
+ };
1971
+ if (src.length !== 1 && src.length !== into.length)
1972
+ throw new Error(`play: ${src.length} channels into ${into.length} — give it mono, or as many`);
1973
+ if (send) {
1974
+ if (send.bus.sampleRate && send.bus.sampleRate !== sr)
1975
+ throw new Error(`play: the send bus is ${send.bus.sampleRate} Hz, the bus ${sr} Hz`);
1976
+ if (src.length !== 1 && src.length !== send.bus.length)
1977
+ throw new Error(
1978
+ `play: ${src.length} channels into a send bus of ${send.bus.length} — give it mono, or as many`,
1979
+ );
1980
+ }
1981
+ // checked before anything is mixed, so a refused play leaves the buses as they were
1982
+ into1(into, 1);
1983
+ if (send) into1(send.bus, send.amount ?? 1);
1984
+ if (recorded) {
1985
+ const attack = [start + (align === "onset" ? point : (onsetOf(timed) ?? 0)) / speed];
1986
+ noteAttacks(into, attack);
1987
+ if (send) noteAttacks(send.bus, attack);
1988
+ }
1989
+ const end = start + n / sr;
1990
+ if (align === "onset" && hit !== null && Math.abs(hit - point) / speed > 0.05) {
1991
+ const gap = Math.round((1000 * Math.abs(hit - point)) / speed);
1992
+ const side = hit > point ? "after" : "before";
1993
+ const warning = `play: the hit is ${gap} ms ${side} the onset at ${secs(at)} s; use align: "hit" or a time in seconds`;
1994
+ console.warn(warning);
1995
+ return { start, end, warning };
1996
+ }
1997
+ return { start, end };
1998
+ }
1999
+
2000
+ /**
2001
+ * Buses by name, each `seconds` of silence: mix into them, process each as a
2002
+ * whole (a filter, a duck), then mix them into the master.
2003
+ * @template {string} K
2004
+ * @param {number} seconds
2005
+ * @param {K[]} names
2006
+ * @param {{ channels?: number, sampleRate?: number }} [o]
2007
+ * @returns {Record<K, Channels>}
2008
+ */
2009
+ export function buses(seconds, names, o = {}) {
2010
+ return /** @type {Record<K, Channels>} */ (
2011
+ Object.fromEntries(names.map((k) => [k, buffer(seconds, o)]))
2012
+ );
2013
+ }
2014
+
2015
+ /**
2016
+ * One room the whole film shares: sounds `play` with a `send` go into its send
2017
+ * bus, and `wet()` is that bus through one reverb (see `reverb` for size,
2018
+ * damp, width), to mix into the master at the level you want. Optional: a
2019
+ * film can stay dry, or put a sound in the room alone.
2020
+ * @param {number} seconds
2021
+ * @param {{ sampleRate?: number, size?: number, damp?: number, width?: number, tail?: number }} [o]
2022
+ */
2023
+ export function space(seconds, { sampleRate = RATE, ...room } = {}) {
2024
+ const send = buffer(seconds, { sampleRate });
2025
+ return { send, wet: () => reverb(send, sampleRate, room) };
2026
+ }
2027
+
2028
+ /**
2029
+ * `a` until `at`, then `b`, crossing over `dur` s from `at` on. Both are on
2030
+ * the film's timeline (a sample of each is the same moment). "power" keeps
2031
+ * the level even across sounds that differ; "linear" sums to one, for two
2032
+ * takes of the same sound.
2033
+ * @param {Channels} a
2034
+ * @param {Channels} b
2035
+ * @param {number} at
2036
+ * @param {number} dur
2037
+ * @param {{ shape?: "power" | "linear" }} [o]
2038
+ * @returns {Channels}
2039
+ */
2040
+ export function crossfade(a, b, at, dur, { shape = "power" } = {}) {
2041
+ const sr = rateOf(a);
2042
+ if (rateOf(b) !== sr) throw new Error(`crossfade: ${rateOf(b)} Hz and ${sr} Hz`);
2043
+ if (a.length !== b.length) throw new Error(`crossfade: ${a.length} channels and ${b.length}`);
2044
+ if (!(dur >= 0)) throw new Error(`crossfade: dur must be ≥ 0 (got ${dur})`);
2045
+ const n = Math.max(a[0]?.length ?? 0, b[0]?.length ?? 0);
2046
+ const s = Math.round(at * sr);
2047
+ const d = Math.round(dur * sr);
2048
+ const out = a.map((ca, c) => {
2049
+ const cb = /** @type {Signal} */ (b[c]);
2050
+ const o = new Float32Array(n);
2051
+ for (let i = 0; i < n; i++) {
2052
+ const u = d === 0 ? (i < s ? 0 : 1) : Math.max(0, Math.min(1, (i - s) / d));
2053
+ const [ga, gb] =
2054
+ shape === "linear"
2055
+ ? [1 - u, u]
2056
+ : [Math.cos((u * Math.PI) / 2), Math.sin((u * Math.PI) / 2)];
2057
+ o[i] = (ca[i] ?? 0) * ga + (cb[i] ?? 0) * gb;
2058
+ }
2059
+ return o;
2060
+ });
2061
+ return withRate(out, sr);
2062
+ }
2063
+
2064
+ // ---------------------------------------------------------------- bars
2065
+
2066
+ // A licensed or recorded track edited by whole bars, the way an editor cuts
2067
+ // music under a film: keep some bars, skip others, loop one, each join a
2068
+ // short crossfade that ends on the bar line, so the incoming bar's downbeat
2069
+ // lands whole. The bars come from `open-take film beats track.mp3` (an
2070
+ // estimate — its confidence is in the file; listen to the joins).
2071
+ //
2072
+ // const track = load("track.mp3");
2073
+ // const beats = JSON.parse(readFileSync("track.beats.json", "utf8"));
2074
+ // // bar 40 (the drop) on the film's 16.0 s, then on through bar 46
2075
+ // const edit = cutToBars(track, beats, [...landOn(beats, { bar: 40, at: 16 }), { from: 40, to: 46 }]);
2076
+ // play(music, edit.sound, 0);
2077
+ // writeFileSync("music.beats.json", JSON.stringify(edit.beats)); // the edit's own grid, for cut.js
2078
+
2079
+ /**
2080
+ * `<name>.beats.json` as `open-take film beats` writes it (the fields used here).
2081
+ * @typedef {object} BeatsFile
2082
+ * @property {1} version
2083
+ * @property {string} [source]
2084
+ * @property {number} duration
2085
+ * @property {{ bpm: number | null, periodS?: number }} tempo
2086
+ * @property {number[]} beats
2087
+ * @property {number[]} downbeats
2088
+ * @property {{ t: number, index: number }[]} [bars]
2089
+ * @property {{ beatsPerBar: number | null }} [meter]
2090
+ * @property {{ t: number, end: number }[]} [sections]
2091
+ * @property {number[]} [drops]
2092
+ * @property {number[]} [onsets]
2093
+ */
2094
+
2095
+ /**
2096
+ * Source bars [from, to), played `times` over (default once). Bars count from
2097
+ * 0 at the first downbeat; `from` may fall mid-bar (a pickup into the first
2098
+ * piece), `to` may be "end" — the track's own ending.
2099
+ * @typedef {{ from: number, to: number | "end", times?: number }} BarPiece
2100
+ */
2101
+
2102
+ /** when a bar starts in the source (s): its downbeat, or past the known ones,
2103
+ * a bar's length on; fractional bars fall between @param {BeatsFile} beats */
2104
+ function barClock(beats) {
2105
+ const d = (beats.downbeats ?? []).filter((t) => Number.isFinite(t));
2106
+ if (d.length < 2)
2107
+ throw new Error(
2108
+ "cutToBars: the beats file has no bars (no downbeats were found) — cut by seconds with slice and crossfade",
2109
+ );
2110
+ const gaps = d
2111
+ .slice(1)
2112
+ .map((t, i) => t - /** @type {number} */ (d[i]))
2113
+ .sort((a, b) => a - b);
2114
+ const len = /** @type {number} */ (gaps[gaps.length >> 1]);
2115
+ const n = d.length;
2116
+ /** @param {number} i */
2117
+ return (i) => {
2118
+ if (i <= 0) return (d[0] ?? 0) + i * len;
2119
+ if (i >= n - 1) return (d[n - 1] ?? 0) + (i - (n - 1)) * len;
2120
+ const k = Math.floor(i);
2121
+ const a = d[k] ?? 0;
2122
+ const b = d[k + 1] ?? a;
2123
+ return a + (b - a) * (i - k);
2124
+ };
2125
+ }
2126
+
2127
+ /**
2128
+ * The pieces that put source bar `bar`'s downbeat on film time `at` when the
2129
+ * edit starts playing at film time `start` (default 0): the bars just before
2130
+ * it, as many as fit, the first one entered part-way. Add the bars after it
2131
+ * yourself. When the track has too little before that bar, it says so.
2132
+ * @param {BeatsFile} beats
2133
+ * @param {{ bar: number, at: number, start?: number }} o
2134
+ * @returns {BarPiece[]}
2135
+ */
2136
+ export function landOn(beats, { bar, at, start = 0 }) {
2137
+ if (![bar, at, start].every(Number.isFinite))
2138
+ throw new Error("landOn: bar, at and start are numbers");
2139
+ const clock = barClock(beats);
2140
+ const lead = at - start;
2141
+ if (lead < 0) throw new Error(`landOn: the edit starts at ${start} s, after ${at} s`);
2142
+ // the fractional bar `lead` s before it, along the bars as they fall (they
2143
+ // need not all be one length)
2144
+ const want = clock(bar) - lead;
2145
+ let lo = bar - lead / (clock(bar) - clock(bar - 1)) - 2;
2146
+ while (clock(lo) > want) lo -= 2;
2147
+ let hi = bar;
2148
+ for (let k = 0; k < 60; k++) {
2149
+ const mid = (lo + hi) / 2;
2150
+ if (clock(mid) < want) lo = mid;
2151
+ else hi = mid;
2152
+ }
2153
+ const from = (lo + hi) / 2;
2154
+ if (want < 0)
2155
+ throw new Error(
2156
+ `landOn: bar ${bar} is ${secs(clock(bar))} s into the track — it cannot sound ${secs(lead)} s after the edit starts; start the edit later (start: ${secs(at - clock(bar))}) or loop a bar before it`,
2157
+ );
2158
+ return lead > 0 ? [{ from, to: bar }] : [];
2159
+ }
2160
+
2161
+ /**
2162
+ * A track cut by whole bars: the pieces in order, each `times` over, joined
2163
+ * by an equal-power crossfade of `xfade` s (default 30 ms) that ends on the
2164
+ * join — the outgoing bar fades under the incoming one's last moment before
2165
+ * its bar line, so the downbeat after the join is the incoming bar's own,
2166
+ * whole. Pieces that follow on in the source (one's `to` the next one's
2167
+ * `from`) play straight through. The first piece fades in over `fadeIn` s
2168
+ * (default 5 ms); the last fades out over `fadeOut` s (default 30 ms) unless it
2169
+ * runs to the track's "end". Returns the sound; `map`, where each piece sits
2170
+ * in the edit and where it came from; `joins`, the edit's seams; and `beats`,
2171
+ * the beats file laid onto the edit's own time — every time plus `at` (default
2172
+ * 0), where you will place the edit in the film — for cut.js grid().
2173
+ * @param {Channels} sound
2174
+ * @param {BeatsFile} beats
2175
+ * @param {BarPiece[]} plan
2176
+ * @param {{ xfade?: number, fadeIn?: number, fadeOut?: number, at?: number }} [o]
2177
+ */
2178
+ export function cutToBars(
2179
+ sound,
2180
+ beats,
2181
+ plan,
2182
+ { xfade = 0.03, fadeIn = 0.005, fadeOut = 0.03, at = 0 } = {},
2183
+ ) {
2184
+ const sr = rateOf(sound);
2185
+ const src = chans(sound);
2186
+ const total = (src[0]?.length ?? 0) / sr;
2187
+ const clock = barClock(beats);
2188
+ if (!Array.isArray(plan) || !plan.length)
2189
+ throw new Error("cutToBars: the plan is a list of { from, to } bars");
2190
+ if (!(xfade >= 0 && fadeIn >= 0 && fadeOut >= 0)) throw new Error("cutToBars: fades are ≥ 0 s");
2191
+ /** @type {{ s0: number, s1: number, from: number, to: number | "end", toEnd: boolean }[]} */
2192
+ const runs = [];
2193
+ for (const p of plan) {
2194
+ const times = p.times ?? 1;
2195
+ if (!(Number.isInteger(times) && times >= 1))
2196
+ throw new Error(`cutToBars: times is a whole number ≥ 1 (got ${p.times})`);
2197
+ if (!Number.isFinite(p.from) || !(p.to === "end" || Number.isFinite(p.to)))
2198
+ throw new Error(`cutToBars: a piece is { from, to } bars (got ${JSON.stringify(p)})`);
2199
+ const s0 = Math.max(0, clock(p.from));
2200
+ const s1 = p.to === "end" ? total : Math.min(total, clock(p.to));
2201
+ if (!(s1 > s0))
2202
+ throw new Error(`cutToBars: bars ${p.from}–${p.to} hold no sound in this track`);
2203
+ for (let k = 0; k < times; k++)
2204
+ runs.push({ s0, s1, from: p.from, to: p.to, toEnd: p.to === "end" || s1 >= total });
2205
+ }
2206
+ // a piece that carries straight on from the last is no join
2207
+ /** @type {typeof runs} */
2208
+ const pieces = [];
2209
+ for (const r of runs) {
2210
+ const last = pieces[pieces.length - 1];
2211
+ if (last && Math.abs(last.s1 - r.s0) < 1 / sr && last.to !== "end") {
2212
+ last.s1 = r.s1;
2213
+ last.to = r.to;
2214
+ last.toEnd = r.toEnd;
2215
+ } else pieces.push({ ...r });
2216
+ }
2217
+ // in whole samples, piece by piece, as they are laid in below
2218
+ const n = pieces.reduce((a, p) => a + Math.round(p.s1 * sr) - Math.round(p.s0 * sr), 0);
2219
+ const length = n / sr;
2220
+ const out = src.map(() => new Float32Array(n));
2221
+ const xf = Math.round(xfade * sr);
2222
+ /** @type {{ at: number, end: number, from: number, to: number | "end", source: [number, number] }[]} */
2223
+ const map = [];
2224
+ /** the same, unrounded: the beats are moved by these, so a mark on a join stays on it
2225
+ * @type {{ at: number, s0: number, s1: number }[]} */
2226
+ const exact = [];
2227
+ /** @type {number[]} */
2228
+ const joins = [];
2229
+ let pos = 0; // samples into the edit
2230
+ pieces.forEach((p, i) => {
2231
+ const a = Math.round(p.s0 * sr);
2232
+ const b = Math.round(p.s1 * sr);
2233
+ // the incoming piece starts xf before its bar line, under the outgoing one's tail
2234
+ const pre = i === 0 ? 0 : Math.min(xf, a, pos);
2235
+ for (let c = 0; c < out.length; c++) {
2236
+ const o = /** @type {Float32Array} */ (out[c]);
2237
+ const s = /** @type {Signal} */ (src[c]);
2238
+ for (let j = 0; j < pre; j++) {
2239
+ const u = (j + 0.5) / pre;
2240
+ const at_ = pos - pre + j;
2241
+ o[at_] =
2242
+ (o[at_] ?? 0) * Math.cos((u * Math.PI) / 2) +
2243
+ (s[a - pre + j] ?? 0) * Math.sin((u * Math.PI) / 2);
2244
+ }
2245
+ for (let j = 0; j < b - a && pos + j < n; j++) o[pos + j] = s[a + j] ?? 0;
2246
+ }
2247
+ if (i > 0) joins.push(secs(at + pos / sr));
2248
+ map.push({
2249
+ at: secs(at + pos / sr),
2250
+ end: secs(at + (pos + b - a) / sr),
2251
+ from: p.from,
2252
+ to: p.to,
2253
+ source: [secs(p.s0), secs(p.s1)],
2254
+ });
2255
+ exact.push({ at: at + pos / sr, s0: p.s0, s1: p.s1 });
2256
+ pos += b - a;
2257
+ });
2258
+ const edges = {
2259
+ in: Math.min(n, Math.round(fadeIn * sr)),
2260
+ out: pieces[pieces.length - 1]?.toEnd ? 0 : Math.min(n, Math.round(fadeOut * sr)),
2261
+ };
2262
+ for (const o of out) {
2263
+ for (let i = 0; i < edges.in; i++)
2264
+ o[i] = (o[i] ?? 0) * Math.sin(((i + 0.5) / edges.in) * (Math.PI / 2));
2265
+ for (let i = 0; i < edges.out; i++)
2266
+ o[n - 1 - i] = (o[n - 1 - i] ?? 0) * Math.sin(((i + 0.5) / edges.out) * (Math.PI / 2));
2267
+ }
2268
+ // the beats file on the edit's time: each source time inside a piece, moved with it
2269
+ /** @param {number[] | undefined} xs */
2270
+ const moved = (xs) =>
2271
+ exact.flatMap((m) =>
2272
+ (xs ?? [])
2273
+ .filter((t) => t >= m.s0 - 1e-6 && t < m.s1 - 1e-6)
2274
+ .map((t) => secs(m.at + (t - m.s0))),
2275
+ );
2276
+ const downbeats = moved(beats.downbeats);
2277
+ return {
2278
+ sound: withRate(out, sr),
2279
+ map,
2280
+ joins,
2281
+ beats: {
2282
+ ...beats,
2283
+ source: `${beats.source ?? "a track"}, cut to bars`,
2284
+ duration: secs(length),
2285
+ beats: moved(beats.beats),
2286
+ downbeats,
2287
+ bars: downbeats.map((t, index) => ({ t, index })),
2288
+ onsets: moved(beats.onsets),
2289
+ drops: moved(beats.drops),
2290
+ sections: exact.flatMap((m) =>
2291
+ (beats.sections ?? [])
2292
+ .filter((s) => s.end > m.s0 && s.t < m.s1)
2293
+ .map((s) => ({
2294
+ ...s,
2295
+ t: secs(m.at + Math.max(0, s.t - m.s0)),
2296
+ end: secs(m.at + Math.min(m.s1, s.end) - m.s0),
2297
+ })),
2298
+ ),
2299
+ },
2300
+ };
2301
+ }
2302
+
2303
+ // ---------------------------------------------------------------- files
2304
+
2305
+ /**
2306
+ * Write a WAV file: 24-bit by default, or 16-bit, or 32-bit float. A sample
2307
+ * that is not a number stops it — that is a bug upstream, and `diagnose` says
2308
+ * where. Samples past full scale are clipped (not in float) and counted.
2309
+ * @param {string} path
2310
+ * @param {Channels | Signal} channels
2311
+ * @param {number} [sampleRate]
2312
+ * @param {16 | 24 | 32} [bits]
2313
+ * @returns {{ path: string, seconds: number, clipped: number }}
2314
+ */
2315
+ export function writeWav(path, channels, sampleRate = rateOf(channels), bits = 24) {
2316
+ const chs = chans(channels);
2317
+ const n = sameLength("writeWav", chs);
2318
+ if (bits !== 16 && bits !== 24 && bits !== 32)
2319
+ throw new Error(`writeWav: ${bits}-bit is not one it writes (16, 24, or 32 for float)`);
2320
+ const bytes = bits / 8;
2321
+ const frame = bytes * chs.length;
2322
+ const out = Buffer.alloc(68 + n * frame);
2323
+ out.write("RIFF", 0, "ascii");
2324
+ out.writeUInt32LE(60 + n * frame, 4);
2325
+ out.write("WAVEfmt ", 8, "ascii");
2326
+ // WAVE_FORMAT_EXTENSIBLE, which the format asks for past 16 bits: it also
2327
+ // names the speakers (a plain header leaves "2 channels" for players to guess)
2328
+ out.writeUInt32LE(40, 16);
2329
+ out.writeUInt16LE(0xfffe, 20);
2330
+ out.writeUInt16LE(chs.length, 22);
2331
+ out.writeUInt32LE(sampleRate, 24);
2332
+ out.writeUInt32LE(sampleRate * frame, 28);
2333
+ out.writeUInt16LE(frame, 32);
2334
+ out.writeUInt16LE(bits, 34);
2335
+ out.writeUInt16LE(22, 36);
2336
+ out.writeUInt16LE(bits, 38);
2337
+ out.writeUInt32LE(chs.length === 1 ? 0x4 : 2 ** chs.length - 1, 40); // centre; or left, right, …
2338
+ out.writeUInt32LE(bits === 32 ? 3 : 1, 44); // the sample kind: 3 IEEE float, 1 PCM …
2339
+ Buffer.from("00001000800000aa00389b71", "hex").copy(out, 48); // … and the rest of its GUID
2340
+ out.write("data", 60, "ascii");
2341
+ out.writeUInt32LE(n * frame, 64);
2342
+ const full = bits === 16 ? 32768 : 8388608;
2343
+ let clipped = 0;
2344
+ chs.forEach((x, c) => {
2345
+ for (let i = 0; i < n; i++) {
2346
+ const v = x[i] ?? 0;
2347
+ if (!Number.isFinite(v))
2348
+ throw new Error(
2349
+ `writeWav ${path}: channel ${c} is ${v} at ${secs(i / sampleRate)} s — diagnose the stems to find which one`,
2350
+ );
2351
+ const o = 68 + i * frame + c * bytes;
2352
+ if (bits === 32) {
2353
+ out.writeFloatLE(v, o);
2354
+ continue;
2355
+ }
2356
+ if (v > 1 || v < -1) clipped++;
2357
+ // +1.0 itself is one step past the largest code: it lands on that code
2358
+ const q = Math.max(-full, Math.min(full - 1, Math.round(v * full)));
2359
+ out[o] = q & 255;
2360
+ out[o + 1] = (q >> 8) & 255;
2361
+ if (bits === 24) out[o + 2] = (q >> 16) & 255;
2362
+ }
2363
+ });
2364
+ writeFileSync(path, out);
2365
+ return { path, seconds: n / sampleRate, clipped };
2366
+ }