@open-take/compositor 0.5.2 → 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
@@ -0,0 +1,1285 @@
1
+ // `open-take film beats`: a piece of music (or a film's sound) as a grid to
2
+ // cut on — its tempo, the beats, which beat starts each bar, the sections
3
+ // where its texture changes, the drops where it lands hard, and every onset —
4
+ // written as <name>.beats.json for the page (kit/cut.js grid) and the score
5
+ // (kit/audio.mjs cutToBars). Every field says whether it was measured, is an
6
+ // estimate, or was not found; a downbeat is always an estimate, with how
7
+ // often the bars agreed on it.
8
+ //
9
+ // The analysis here is shared with `film listen` and `film probe`: a
10
+ // short-time spectrum, onsets from where its bands rise, a tempo from how the
11
+ // onset strength repeats, fitted to the onsets so the grid still sits on the
12
+ // beat minutes later, and sections from where the texture stops resembling
13
+ // what came before.
14
+
15
+ import { spawn } from "node:child_process";
16
+ import { existsSync } from "node:fs";
17
+ import { writeFile } from "node:fs/promises";
18
+ import { basename, resolve } from "node:path";
19
+ import { resolveFfmpeg } from "../ffmpeg";
20
+
21
+ // --- the spectrum, onsets, tempo ----------------------------------------------------
22
+
23
+ /** the rate the sound is analysed at: everything a film's rhythm and texture
24
+ * needs sits below its 11 kHz */
25
+ export const LISTEN_RATE = 22_050;
26
+ export const WIN = 1024; // 46 ms
27
+ const HOP = 256; // 11.6 ms
28
+ export const BANDS = 48;
29
+ export const LOW_HZ = 40;
30
+ export const HIGH_HZ = 10_000;
31
+ /** below this a frame is silence, not a quiet texture */
32
+ export const FLOOR_DB = -70;
33
+
34
+ export type Spectrum = {
35
+ /** seconds between frames */
36
+ hopS: number;
37
+ /** frame i covers [i·hop, i·hop + win) samples; its time is its centre */
38
+ frameTime: (i: number) => number;
39
+ /** per frame, log energy (dB) in BANDS log-spaced bands from 40 Hz to 10 kHz */
40
+ bands: Float32Array[];
41
+ /** per frame, the level (dBFS RMS) */
42
+ level: Float32Array;
43
+ };
44
+
45
+ export function spectrum(pcm: Float32Array, rate = LISTEN_RATE): Spectrum {
46
+ const n = pcm.length < WIN ? 0 : Math.floor((pcm.length - WIN) / HOP) + 1;
47
+ const hann = new Float32Array(WIN);
48
+ for (let i = 0; i < WIN; i++) hann[i] = 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / WIN);
49
+ // which FFT bins each band sums; a band narrower than a bin takes the nearest one
50
+ const binHz = rate / WIN;
51
+ const edges = Array.from(
52
+ { length: BANDS + 1 },
53
+ (_, b) => LOW_HZ * (HIGH_HZ / LOW_HZ) ** (b / BANDS),
54
+ );
55
+ const ranges = Array.from({ length: BANDS }, (_, b) => {
56
+ const lo = Math.max(1, Math.round(edges[b]! / binHz));
57
+ const hi = Math.max(lo + 1, Math.round(edges[b + 1]! / binHz));
58
+ return [lo, Math.min(hi, WIN / 2)] as const;
59
+ });
60
+ const fft = makeFft(WIN);
61
+ const re = new Float64Array(WIN);
62
+ const im = new Float64Array(WIN);
63
+ const bands: Float32Array[] = [];
64
+ const level = new Float32Array(n);
65
+ // a full-scale sine's windowed peak bin power, so bands read near dBFS
66
+ const ref = (WIN * 0.5 * 0.5) ** 2;
67
+ for (let f = 0; f < n; f++) {
68
+ let sq = 0;
69
+ for (let i = 0; i < WIN; i++) {
70
+ const x = pcm[f * HOP + i]!;
71
+ sq += x * x;
72
+ re[i] = x * hann[i]!;
73
+ im[i] = 0;
74
+ }
75
+ level[f] = 10 * Math.log10(sq / WIN + 1e-12);
76
+ fft(re, im);
77
+ const row = new Float32Array(BANDS);
78
+ for (let b = 0; b < BANDS; b++) {
79
+ const [lo, hi] = ranges[b]!;
80
+ let e = 0;
81
+ for (let k = lo; k < hi; k++) e += re[k]! * re[k]! + im[k]! * im[k]!;
82
+ row[b] = Math.max(FLOOR_DB - 20, 10 * Math.log10(e / ref + 1e-12));
83
+ }
84
+ bands.push(row);
85
+ }
86
+ const hopS = HOP / rate;
87
+ return { hopS, frameTime: (i) => (i * HOP + WIN / 2) / rate, bands, level };
88
+ }
89
+
90
+ /** in-place radix-2 FFT of a fixed size */
91
+ export function makeFft(size: number): (re: Float64Array, im: Float64Array) => void {
92
+ const bits = Math.log2(size);
93
+ const rev = new Uint32Array(size);
94
+ for (let i = 0; i < size; i++) {
95
+ let r = 0;
96
+ for (let b = 0; b < bits; b++) r |= ((i >> b) & 1) << (bits - 1 - b);
97
+ rev[i] = r;
98
+ }
99
+ const cos = new Float64Array(size / 2);
100
+ const sin = new Float64Array(size / 2);
101
+ for (let i = 0; i < size / 2; i++) {
102
+ cos[i] = Math.cos((2 * Math.PI * i) / size);
103
+ sin[i] = -Math.sin((2 * Math.PI * i) / size);
104
+ }
105
+ return (re, im) => {
106
+ for (let i = 0; i < size; i++) {
107
+ const j = rev[i]!;
108
+ if (j > i) {
109
+ [re[i], re[j]] = [re[j]!, re[i]!];
110
+ [im[i], im[j]] = [im[j]!, im[i]!];
111
+ }
112
+ }
113
+ for (let len = 2; len <= size; len <<= 1) {
114
+ const half = len >> 1;
115
+ const step = size / len;
116
+ for (let i = 0; i < size; i += len)
117
+ for (let k = 0; k < half; k++) {
118
+ const wr = cos[k * step]!;
119
+ const wi = sin[k * step]!;
120
+ const a = i + k;
121
+ const b = a + half;
122
+ const tr = re[b]! * wr - im[b]! * wi;
123
+ const ti = re[b]! * wi + im[b]! * wr;
124
+ re[b] = re[a]! - tr;
125
+ im[b] = im[a]! - ti;
126
+ re[a] = re[a]! + tr;
127
+ im[a] = im[a]! + ti;
128
+ }
129
+ }
130
+ };
131
+ }
132
+
133
+ /** how much new energy each frame brings: the summed rise of every band over
134
+ * the louder of the two frames before it (a rise, never a fall) */
135
+ export function onsetStrength(s: Spectrum): Float32Array {
136
+ return riseIn(s, 0, BANDS);
137
+ }
138
+
139
+ /** the same, over the bands between loHz and hiHz only: the low end (kick,
140
+ * bass) is where a beat lands when hats fill the gaps between */
141
+ export function bandOnsetStrength(s: Spectrum, loHz: number, hiHz: number): Float32Array {
142
+ const band = (hz: number) => (BANDS * Math.log(hz / LOW_HZ)) / Math.log(HIGH_HZ / LOW_HZ);
143
+ const k0 = Math.max(0, Math.floor(band(loHz)));
144
+ const k1 = Math.min(BANDS, Math.max(k0 + 1, Math.ceil(band(hiHz))));
145
+ return riseIn(s, k0, k1);
146
+ }
147
+
148
+ function riseIn(s: Spectrum, k0: number, k1: number): Float32Array {
149
+ const env = new Float32Array(s.bands.length);
150
+ for (let f = 1; f < s.bands.length; f++) {
151
+ const cur = s.bands[f]!;
152
+ const a = s.bands[f - 1]!;
153
+ const b = s.bands[Math.max(0, f - 2)]!;
154
+ let rise = 0;
155
+ for (let k = k0; k < k1; k++) {
156
+ const floor = Math.max(a[k]!, b[k]!, FLOOR_DB);
157
+ if (cur[k]! > floor) rise += cur[k]! - floor;
158
+ }
159
+ env[f] = rise / (k1 - k0);
160
+ }
161
+ return env;
162
+ }
163
+
164
+ /** the frame whose centre is nearest t (may fall outside the spectrum) */
165
+ const frameAt = (s: Spectrum, t: number) => Math.round((t - s.frameTime(0)) / s.hopS);
166
+
167
+ /** an envelope's largest value within ±`near` frames of t */
168
+ function peakNear(s: Spectrum, env: Float32Array, t: number, near = 2): number {
169
+ const f = frameAt(s, t);
170
+ let v = 0;
171
+ for (let k = Math.max(0, f - near); k <= Math.min(env.length - 1, f + near); k++)
172
+ v = Math.max(v, env[k]!);
173
+ return v;
174
+ }
175
+
176
+ /** onset times (s): frames whose new energy is a local peak and stands clear
177
+ * of its neighbourhood (the median of the surrounding 0.6 s plus half the
178
+ * film's spread), each placed on the sample where the sound itself rises */
179
+ export function pickOnsets(
180
+ s: Spectrum,
181
+ env: Float32Array,
182
+ pcm?: Float32Array,
183
+ rate = LISTEN_RATE,
184
+ ): number[] {
185
+ const n = env.length;
186
+ if (!n) return [];
187
+ let mean = 0;
188
+ for (const v of env) mean += v;
189
+ mean /= n;
190
+ let sd = 0;
191
+ for (const v of env) sd += (v - mean) ** 2;
192
+ sd = Math.sqrt(sd / n);
193
+ const W = Math.round(0.3 / s.hopS);
194
+ const near = 3; // ±35 ms
195
+ const out: number[] = [];
196
+ const window: number[] = [];
197
+ for (let f = 0; f < n; f++) {
198
+ const v = env[f]!;
199
+ if (v <= 0 || s.level[f]! < FLOOR_DB + 10) continue;
200
+ let peak = true;
201
+ for (let k = Math.max(0, f - near); k <= Math.min(n - 1, f + near) && peak; k++)
202
+ if (env[k]! > v || (env[k] === v && k < f)) peak = false;
203
+ if (!peak) continue;
204
+ window.length = 0;
205
+ for (let k = Math.max(0, f - W); k <= Math.min(n - 1, f + W); k++) window.push(env[k]!);
206
+ window.sort((a, b) => a - b);
207
+ const median = window[window.length >> 1]!;
208
+ if (v < median + 0.5 * sd || v < 0.5) continue;
209
+ out.push(pcm ? refineOnset(pcm, rate, s.frameTime(f)) : s.frameTime(f));
210
+ }
211
+ return out;
212
+ }
213
+
214
+ /** within ±one window of a frame's onset, the 2 ms step where the level rises
215
+ * most — the onset as heard, not as the spectrum's 46 ms window blurs it */
216
+ function refineOnset(pcm: Float32Array, rate: number, t: number): number {
217
+ const step = Math.round(rate * 0.002);
218
+ const span = WIN / rate;
219
+ const a = Math.max(0, Math.round((t - span) * rate));
220
+ const b = Math.min(pcm.length - step, Math.round((t + span * 0.5) * rate));
221
+ if (b - a < step * 4) return t;
222
+ const lv: number[] = [];
223
+ for (let i = a; i + step <= b; i += step) {
224
+ let sq = 0;
225
+ for (let k = i; k < i + step; k++) sq += pcm[k]! * pcm[k]!;
226
+ lv.push(10 * Math.log10(sq / step + 1e-12));
227
+ }
228
+ let best = -1;
229
+ let rise = 0;
230
+ for (let i = 2; i < lv.length; i++) {
231
+ const r = lv[i]! - Math.max(lv[i - 1]!, lv[i - 2]!);
232
+ if (r > rise) {
233
+ rise = r;
234
+ best = i;
235
+ }
236
+ }
237
+ // a rise under 6 dB is no edge: leave the frame's time
238
+ return best < 0 || rise < 6 ? t : (a + best * step) / rate;
239
+ }
240
+
241
+ export type Tempo = {
242
+ bpm: number;
243
+ /** seconds a beat, as fitted to the onsets */
244
+ periodS: number;
245
+ /** how strongly the onset strength repeats at this period: its
246
+ * autocorrelation there over at zero lag (0..1) */
247
+ strength: number;
248
+ /** the other periods that repeat almost as strongly (half, double…) */
249
+ alternatives: { bpm: number; strength: number }[];
250
+ /** the beat grid laid at this tempo, at the phase most onsets fall on */
251
+ beats: number[];
252
+ /** the share of beats with an onset within 40 ms */
253
+ gridFit: number;
254
+ /** the share of the sound within 40 ms of some onset: what gridFit would be
255
+ * for a grid laid anywhere */
256
+ chance: number;
257
+ /** false when the first half's period and the second half's differ by more
258
+ * than 0.4%: the beats then follow the onsets instead of one grid */
259
+ steady: boolean;
260
+ };
261
+
262
+ /** the period (60–200 BPM) at which the onset strength repeats most, and a
263
+ * beat grid at it: fitted to the onsets over the whole sound, on the beat the
264
+ * low end lands on, and following the onsets where the tempo does not hold;
265
+ * null when nothing repeats */
266
+ export function estimateTempo(
267
+ s: Spectrum,
268
+ env: Float32Array,
269
+ onsets: readonly number[],
270
+ duration: number,
271
+ ): Tempo | null {
272
+ const n = env.length;
273
+ const lagOf = (bpm: number) => 60 / bpm / s.hopS;
274
+ const minLag = Math.floor(lagOf(200));
275
+ const maxLag = Math.ceil(lagOf(60));
276
+ if (n < maxLag * 3) return null;
277
+ let mean = 0;
278
+ for (const v of env) mean += v;
279
+ mean /= n;
280
+ const x = Float64Array.from(env, (v) => v - mean);
281
+ let zero = 0;
282
+ for (const v of x) zero += v * v;
283
+ if (!(zero > 0)) return null;
284
+ const ac = new Float64Array(maxLag + 2);
285
+ for (let lag = minLag - 1; lag <= maxLag + 1; lag++) {
286
+ let sum = 0;
287
+ for (let i = 0; i + lag < n; i++) sum += x[i]! * x[i + lag]!;
288
+ // unbiased: a long lag sums fewer products
289
+ ac[lag] = (sum / (n - lag)) * (n / zero);
290
+ }
291
+ const peaks: { lag: number; v: number }[] = [];
292
+ for (let lag = minLag; lag <= maxLag; lag++)
293
+ if (ac[lag]! > 0 && ac[lag]! >= ac[lag - 1]! && ac[lag]! > ac[lag + 1]!) {
294
+ // the peak between whole frames, from the parabola through its neighbours
295
+ const a = ac[lag - 1]!;
296
+ const b = ac[lag]!;
297
+ const c = ac[lag + 1]!;
298
+ const d = a - 2 * b + c;
299
+ peaks.push({ lag: d < 0 ? lag + (0.5 * (a - c)) / d : lag, v: b });
300
+ }
301
+ if (!peaks.length) return null;
302
+ peaks.sort((p, q) => q.v - p.v);
303
+ // a pulse repeats at every multiple of its period too, and a half-time feel
304
+ // repeats at twice it: among the periods a whole multiple or fraction of the
305
+ // strongest (up to 4) that repeat at least half as strongly, the beat is
306
+ // the one whose strength, weighed by how usual its tempo is (a log-normal
307
+ // around 120 BPM, an octave wide — it only chooses between such multiples),
308
+ // is greatest
309
+ const usual = (lag: number) => Math.exp(-0.5 * Math.log2(60 / (lag * s.hopS) / 120) ** 2);
310
+ const top = peaks
311
+ .filter((p) => {
312
+ const r = peaks[0]!.lag / p.lag;
313
+ const whole = r >= 1 ? r : 1 / r;
314
+ return (
315
+ p.v >= peaks[0]!.v * 0.5 &&
316
+ Math.round(whole) <= 4 &&
317
+ Math.abs(whole - Math.round(whole)) < 0.04
318
+ );
319
+ })
320
+ .reduce((a, b) => (b.v * usual(b.lag) > a.v * usual(a.lag) ? b : a));
321
+ const bpmOf = (lag: number) => Math.round((60 / (lag * s.hopS)) * 10) / 10;
322
+ // the autocorrelation's period is good to a fraction of a frame a beat,
323
+ // which over minutes drifts off the beat by more than the gap between two
324
+ // sixteenths: the period and phase that line the most onset strength up
325
+ // over the whole sound, searched finely around it
326
+ const weight = (t: number) => peakNear(s, env, t);
327
+ const w = onsets.map(weight);
328
+ let { period, t0 } = combFit(onsets, w, top.lag * s.hopS, duration);
329
+ // on the beat or half a beat over: hats between the beats rise in as many
330
+ // bands as the beats do, so where the low end (kick, bass) clearly lands is
331
+ // the beat; without a clear low end, where the most new energy lands is
332
+ const low = bandOnsetStrength(s, 30, 160);
333
+ const comb = (e: Float32Array, from: number) => {
334
+ let sum = 0;
335
+ // ±35 ms: the low end rises later than the click of the attack in a 46 ms window
336
+ for (let t = from; t < duration; t += period) sum += peakNear(s, e, t, 3);
337
+ return sum;
338
+ };
339
+ const [lowOn, lowOff] = [comb(low, t0), comb(low, t0 + period / 2)];
340
+ const off =
341
+ lowOff > lowOn * 1.3 || (lowOn <= lowOff * 1.3 && comb(env, t0 + period / 2) > comb(env, t0));
342
+ if (off) t0 += period / 2;
343
+ // then polished on the onsets nearest each beat
344
+ const fit = fitGrid(onsets, weight, t0, period, duration);
345
+ period = fit.period;
346
+ t0 = fit.t0;
347
+ let beats: number[] = [];
348
+ const k0 = Math.ceil((-t0 - EARLY) / period - 1e-9);
349
+ for (let k = k0; t0 + k * period < duration; k++)
350
+ beats.push(Math.max(0, round3(t0 + k * period)));
351
+ if (!fit.steady) beats = followBeats(onsets, weight, beats[0] ?? t0, period, duration);
352
+ const hits = beats.filter((b) => {
353
+ const d = nearestOffset(onsets, b);
354
+ return d != null && Math.abs(d) <= 0.04;
355
+ }).length;
356
+ return {
357
+ bpm: Math.round((60 / period) * 10) / 10,
358
+ periodS: Math.round(period * 1e6) / 1e6,
359
+ strength: round2(Math.min(1, top.v)),
360
+ alternatives: peaks
361
+ .filter((p) => p !== top && p.v >= peaks[0]!.v * 0.6)
362
+ .slice(0, 3)
363
+ .map((p) => ({ bpm: bpmOf(p.lag), strength: round2(Math.min(1, p.v)) })),
364
+ beats,
365
+ gridFit: beats.length ? round2(hits / beats.length) : 0,
366
+ chance: chanceWithin(onsets, duration),
367
+ steady: fit.steady,
368
+ };
369
+ }
370
+
371
+ /** how far before 0 a fitted beat still counts as the beat at 0 (s) */
372
+ const EARLY = 0.03;
373
+
374
+ /** the period within 1% of `p0` and the phase whose grid lines the onsets'
375
+ * strength up best: each onset counts by its strength and how near a beat it
376
+ * falls (a Gaussian, 20 ms wide); periods are stepped so the grid's last
377
+ * beat moves 4 ms a step, phases 4 ms a step */
378
+ function combFit(
379
+ onsets: readonly number[],
380
+ w: readonly number[],
381
+ p0: number,
382
+ duration: number,
383
+ ): { period: number; t0: number } {
384
+ const beatsIn = Math.max(1, duration / p0);
385
+ const dp = Math.max(1e-6, 0.004 / beatsIn);
386
+ const span = Math.ceil((p0 * 0.01) / dp);
387
+ const k = 1 / (2 * 0.02 ** 2);
388
+ let best = { period: p0, t0: 0, v: -1 };
389
+ for (let i = -span; i <= span; i++) {
390
+ const p = p0 + i * dp;
391
+ const phases = Math.max(1, Math.round(p / 0.004));
392
+ const sums = new Float64Array(phases);
393
+ // each onset adds to the phases near its own place in the beat
394
+ for (let j = 0; j < onsets.length; j++) {
395
+ const o = onsets[j]!;
396
+ const at = ((o % p) + p) % p;
397
+ const c = Math.round((at / p) * phases);
398
+ for (let q = c - 3; q <= c + 3; q++) {
399
+ const qi = ((q % phases) + phases) % phases;
400
+ let d = Math.abs(at - qi * (p / phases));
401
+ d = Math.min(d, p - d);
402
+ sums[qi] = sums[qi]! + w[j]! * Math.exp(-d * d * k);
403
+ }
404
+ }
405
+ for (let q = 0; q < phases; q++)
406
+ if (sums[q]! > best.v) best = { period: p, t0: (q * p) / phases, v: sums[q]! };
407
+ }
408
+ return { period: best.period, t0: best.t0 };
409
+ }
410
+
411
+ /** a constant grid fitted to the onsets: each round pairs every beat with the
412
+ * onset nearest it, inside a window that narrows round by round, and solves
413
+ * period and phase by least squares weighted by each onset's strength. The
414
+ * same fit over each half says whether the tempo holds. */
415
+ function fitGrid(
416
+ onsets: readonly number[],
417
+ weight: (t: number) => number,
418
+ t0: number,
419
+ period: number,
420
+ duration: number,
421
+ ): { t0: number; period: number; steady: boolean } {
422
+ const pairs = (a: number, p: number, win: number) => {
423
+ const out: { k: number; t: number; w: number }[] = [];
424
+ const k0 = Math.ceil(-a / p - 1e-9);
425
+ for (let k = k0; a + k * p < duration; k++) {
426
+ const d = nearestOffset(onsets, a + k * p);
427
+ if (d != null && Math.abs(d) <= win) {
428
+ const t = a + k * p + d;
429
+ out.push({ k, t, w: Math.max(1e-6, weight(t)) });
430
+ }
431
+ }
432
+ return out;
433
+ };
434
+ const solve = (ps: { k: number; t: number; w: number }[]) => {
435
+ let sw = 0;
436
+ let sk = 0;
437
+ let st = 0;
438
+ for (const q of ps) {
439
+ sw += q.w;
440
+ sk += q.w * q.k;
441
+ st += q.w * q.t;
442
+ }
443
+ const mk = sk / sw;
444
+ const mt = st / sw;
445
+ let num = 0;
446
+ let den = 0;
447
+ for (const q of ps) {
448
+ num += q.w * (q.k - mk) * (q.t - mt);
449
+ den += q.w * (q.k - mk) ** 2;
450
+ }
451
+ if (!(den > 0)) return null;
452
+ const p = num / den;
453
+ return { t0: mt - p * mk, period: p };
454
+ };
455
+ let a = t0;
456
+ let p = period;
457
+ for (const win of [Math.min(0.07, p * 0.15), Math.min(0.05, p * 0.1), 0.035]) {
458
+ const ps = pairs(a, p, win);
459
+ if (ps.length < 8) break;
460
+ const r = solve(ps);
461
+ // a fit that moves the period by more than 2% found another pulse
462
+ if (!r || Math.abs(r.period - period) / period > 0.02) break;
463
+ a = r.t0;
464
+ p = r.period;
465
+ }
466
+ // the phase as close to 0 as it goes, so the first beat is the first one
467
+ // heard — one a hair before 0 is the beat at 0 (a sound that starts on its
468
+ // beat has no onset there: nothing came before it to rise over)
469
+ a -= Math.floor((a + EARLY) / p) * p;
470
+ const ps = pairs(a, p, 0.035);
471
+ let steady = true;
472
+ if (ps.length >= 16) {
473
+ const mid = ps[ps.length >> 1]!.k;
474
+ const one = solve(ps.filter((q) => q.k < mid));
475
+ const two = solve(ps.filter((q) => q.k >= mid));
476
+ if (one && two && Math.abs(one.period - two.period) / p > 0.004) steady = false;
477
+ }
478
+ return { t0: a, period: p, steady };
479
+ }
480
+
481
+ /** beats that follow the onsets where the tempo moves: from each beat the next
482
+ * is a period on, pulled half way to an onset within 12% of a period, and the
483
+ * period itself eased a tenth of the way toward what the pull says */
484
+ function followBeats(
485
+ onsets: readonly number[],
486
+ weight: (t: number) => number,
487
+ first: number,
488
+ period: number,
489
+ duration: number,
490
+ ): number[] {
491
+ const out: number[] = [];
492
+ let t = first;
493
+ let p = period;
494
+ while (t < duration) {
495
+ const d = nearestOffset(onsets, t);
496
+ if (d != null && Math.abs(d) <= p * 0.12 && weight(t + d) > 0) {
497
+ t += d * 0.5;
498
+ p += d * 0.1;
499
+ }
500
+ if (t >= 0) out.push(round3(t));
501
+ t += p;
502
+ }
503
+ return out;
504
+ }
505
+
506
+ /** the share of the sound within ±w of some onset: how often a time picked at
507
+ * random would already sit that close to a sound */
508
+ export function chanceWithin(onsets: readonly number[], duration: number, w = 0.04): number {
509
+ if (!(duration > 0) || !onsets.length) return 0;
510
+ let covered = 0;
511
+ let end = -Infinity;
512
+ for (const t of onsets) {
513
+ const a = Math.max(0, t - w, end);
514
+ const b = Math.min(duration, t + w);
515
+ if (b > a) covered += b - a;
516
+ end = Math.max(end, b);
517
+ }
518
+ return round2(covered / duration);
519
+ }
520
+
521
+ // --- sections -------------------------------------------------------------------------
522
+
523
+ export type Section = {
524
+ start: number;
525
+ end: number;
526
+ /** how sharply the texture changes at its start (0 for the first) */
527
+ change: number;
528
+ /** level (dBFS RMS, mean over the section's sounding frames) */
529
+ levelDb: number;
530
+ onsetsPerS: number;
531
+ /** spectral centre of mass (Hz) */
532
+ centroidHz: number;
533
+ };
534
+
535
+ const BLOCK_S = 0.5;
536
+
537
+ /** where the texture changes: half-second blocks of band energy, compared
538
+ * with each other (cosine), and the boundaries where the blocks before stop
539
+ * resembling the blocks after (a checkerboard over the similarity matrix) */
540
+ export function findSections(s: Spectrum, onsets: readonly number[], duration: number): Section[] {
541
+ const per = Math.max(1, Math.round(BLOCK_S / s.hopS));
542
+ const blocks: Float64Array[] = [];
543
+ for (let f = 0; f < s.bands.length; f += per) {
544
+ const v = new Float64Array(BANDS);
545
+ let k = 0;
546
+ for (let g = f; g < Math.min(f + per, s.bands.length); g++, k++)
547
+ for (let b = 0; b < BANDS; b++) v[b] = v[b]! + s.bands[g]![b]!;
548
+ for (let b = 0; b < BANDS; b++) v[b] = v[b]! / Math.max(1, k);
549
+ blocks.push(v);
550
+ }
551
+ const m = blocks.length;
552
+ if (m < 4) return [describe(s, onsets, 0, duration, 0)];
553
+ // centred on the film's mean texture, so similarity is about what differs
554
+ const mean = new Float64Array(BANDS);
555
+ for (const v of blocks) for (let b = 0; b < BANDS; b++) mean[b] = mean[b]! + v[b]! / m;
556
+ const unit = blocks.map((v) => {
557
+ const u = Float64Array.from(v, (x, b) => x - mean[b]!);
558
+ const norm = Math.hypot(...u) || 1;
559
+ return u.map((x) => x / norm);
560
+ });
561
+ const sim = (i: number, j: number) => {
562
+ let d = 0;
563
+ for (let b = 0; b < BANDS; b++) d += unit[i]![b]! * unit[j]![b]!;
564
+ return d;
565
+ };
566
+ const L = Math.min(6, Math.floor(m / 2)); // 3 s each side
567
+ const novelty = new Float64Array(m);
568
+ for (let c = 1; c < m; c++) {
569
+ let sum = 0;
570
+ let w = 0;
571
+ for (let i = -L; i < L; i++)
572
+ for (let j = -L; j < L; j++) {
573
+ const a = c + i;
574
+ const b = c + j;
575
+ if (a < 0 || b < 0 || a >= m || b >= m) continue;
576
+ // a taper so the blocks next to the boundary count most
577
+ const g = Math.exp(-(((i + 0.5) / L) ** 2 + ((j + 0.5) / L) ** 2) * 2);
578
+ sum += (i < 0 === j < 0 ? 1 : -1) * g * sim(a, b);
579
+ w += g;
580
+ }
581
+ novelty[c] = w ? Math.max(0, sum / w) : 0;
582
+ }
583
+ let nm = 0;
584
+ for (const v of novelty) nm += v / m;
585
+ let nsd = 0;
586
+ for (const v of novelty) nsd += (v - nm) ** 2 / m;
587
+ nsd = Math.sqrt(nsd);
588
+ const minGap = Math.round(2 / BLOCK_S);
589
+ const cand: { at: number; v: number }[] = [];
590
+ for (let c = 1; c < m; c++) {
591
+ const v = novelty[c]!;
592
+ if (v < nm + nsd || v < 0.05) continue;
593
+ let peak = true;
594
+ for (let k = Math.max(1, c - minGap); k <= Math.min(m - 1, c + minGap); k++)
595
+ if (novelty[k]! > v || (novelty[k] === v && k < c)) peak = false;
596
+ if (peak) cand.push({ at: c, v });
597
+ }
598
+ const top = Math.max(...cand.map((c) => c.v), 1e-9);
599
+ const bounds = cand
600
+ .map((c) => ({ t: c.at * per * s.hopS, v: c.v / top }))
601
+ .filter((b) => b.t >= 2 && b.t <= duration - 2);
602
+ const out: Section[] = [];
603
+ let start = 0;
604
+ let change = 0;
605
+ for (const b of bounds) {
606
+ out.push(describe(s, onsets, start, b.t, change));
607
+ start = b.t;
608
+ change = b.v;
609
+ }
610
+ out.push(describe(s, onsets, start, duration, change));
611
+ return out;
612
+ }
613
+
614
+ function describe(
615
+ s: Spectrum,
616
+ onsets: readonly number[],
617
+ start: number,
618
+ end: number,
619
+ change: number,
620
+ ): Section {
621
+ const a = Math.max(0, Math.floor(start / s.hopS));
622
+ const b = Math.min(s.bands.length, Math.ceil(end / s.hopS));
623
+ let lv = 0;
624
+ let lvN = 0;
625
+ let wsum = 0;
626
+ let csum = 0;
627
+ for (let f = a; f < b; f++) {
628
+ if (s.level[f]! > FLOOR_DB) {
629
+ lv += 10 ** (s.level[f]! / 10);
630
+ lvN++;
631
+ }
632
+ for (let k = 0; k < BANDS; k++) {
633
+ const e = 10 ** (s.bands[f]![k]! / 10);
634
+ const hz = Math.sqrt(
635
+ LOW_HZ *
636
+ (HIGH_HZ / LOW_HZ) ** (k / BANDS) *
637
+ LOW_HZ *
638
+ (HIGH_HZ / LOW_HZ) ** ((k + 1) / BANDS),
639
+ );
640
+ wsum += e;
641
+ csum += e * hz;
642
+ }
643
+ }
644
+ const len = Math.max(1e-6, end - start);
645
+ return {
646
+ start: round2(start),
647
+ end: round2(end),
648
+ change: round2(change),
649
+ levelDb: lvN ? round1(10 * Math.log10(lv / lvN)) : -120,
650
+ onsetsPerS: round1(onsets.filter((t) => t >= start && t < end).length / len),
651
+ centroidHz: lvN && wsum > 0 ? Math.round(csum / wsum) : 0,
652
+ };
653
+ }
654
+
655
+ /** signed seconds from t to the nearest onset (an onset before t is negative);
656
+ * null without onsets. `onsets` is sorted. */
657
+ export function nearestOffset(onsets: readonly number[], t: number): number | null {
658
+ if (!onsets.length) return null;
659
+ let lo = 0;
660
+ let hi = onsets.length - 1;
661
+ while (lo < hi) {
662
+ const mid = (lo + hi) >> 1;
663
+ if (onsets[mid]! < t) lo = mid + 1;
664
+ else hi = mid;
665
+ }
666
+ let best = onsets[lo]! - t;
667
+ if (lo > 0 && Math.abs(onsets[lo - 1]! - t) <= Math.abs(best)) best = onsets[lo - 1]! - t;
668
+ return round3(best);
669
+ }
670
+
671
+ /** any sound ffmpeg reads (the sound of a video too), as mono float samples at LISTEN_RATE */
672
+ export function decodeMono(ffmpeg: string, file: string): Promise<Float32Array> {
673
+ return new Promise((ok, fail) => {
674
+ const p = spawn(
675
+ ffmpeg,
676
+ [
677
+ "-v",
678
+ "error",
679
+ "-i",
680
+ file,
681
+ "-vn",
682
+ "-ac",
683
+ "1",
684
+ "-ar",
685
+ String(LISTEN_RATE),
686
+ "-f",
687
+ "f32le",
688
+ "-",
689
+ ],
690
+ { stdio: ["ignore", "pipe", "pipe"] },
691
+ );
692
+ const chunks: Buffer[] = [];
693
+ let err = "";
694
+ p.stdout.on("data", (d: Buffer) => chunks.push(d));
695
+ p.stderr.on("data", (d: Buffer) => {
696
+ err += d.toString();
697
+ });
698
+ p.on("error", fail);
699
+ p.on("close", (code) => {
700
+ if (code !== 0)
701
+ return fail(new Error(`ffmpeg could not decode ${file}: ${err.trim().slice(-400)}`));
702
+ const all = Buffer.concat(chunks);
703
+ ok(new Float32Array(all.buffer.slice(all.byteOffset, all.byteOffset + (all.length & ~3))));
704
+ });
705
+ });
706
+ }
707
+
708
+ // --- pitch classes and key ------------------------------------------------------------
709
+
710
+ const CHROMA_N = 8192; // 0.37 s: 2.7 Hz a bin, finer than a semitone from 50 Hz up
711
+ const CHROMA_HOP = 2048; // 93 ms
712
+
713
+ export type Chroma = {
714
+ hopS: number;
715
+ /** frame i is centred at (i·hop + n/2) / rate */
716
+ frameTime: (i: number) => number;
717
+ /** per frame, the energy of each of the 12 pitch classes (C = 0), summing to 1 */
718
+ frames: Float32Array[];
719
+ };
720
+
721
+ /** how much of each pitch class sounds in each frame: the spectrum from 55 Hz
722
+ * to 2 kHz, each bin's magnitude (log-compressed) given to its nearest note */
723
+ export function chromagram(pcm: Float32Array, rate = LISTEN_RATE): Chroma {
724
+ const n = pcm.length < CHROMA_N ? 0 : Math.floor((pcm.length - CHROMA_N) / CHROMA_HOP) + 1;
725
+ const fft = makeFft(CHROMA_N);
726
+ const hann = new Float64Array(CHROMA_N);
727
+ for (let i = 0; i < CHROMA_N; i++) hann[i] = 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / CHROMA_N);
728
+ const k0 = Math.ceil((55 * CHROMA_N) / rate);
729
+ const k1 = Math.floor((2000 * CHROMA_N) / rate);
730
+ const pc = new Int8Array(k1 + 1);
731
+ for (let k = k0; k <= k1; k++) {
732
+ const midi = 69 + 12 * Math.log2((k * rate) / CHROMA_N / 440);
733
+ pc[k] = ((Math.round(midi) % 12) + 12) % 12;
734
+ }
735
+ const re = new Float64Array(CHROMA_N);
736
+ const im = new Float64Array(CHROMA_N);
737
+ const frames: Float32Array[] = [];
738
+ for (let f = 0; f < n; f++) {
739
+ for (let i = 0; i < CHROMA_N; i++) {
740
+ re[i] = pcm[f * CHROMA_HOP + i]! * hann[i]!;
741
+ im[i] = 0;
742
+ }
743
+ fft(re, im);
744
+ const row = new Float32Array(12);
745
+ let sum = 0;
746
+ for (let k = k0; k <= k1; k++) {
747
+ const v = Math.log1p(100 * (Math.hypot(re[k]!, im[k]!) / CHROMA_N));
748
+ row[pc[k]!] = row[pc[k]!]! + v;
749
+ sum += v;
750
+ }
751
+ if (sum > 0) for (let c = 0; c < 12; c++) row[c] = row[c]! / sum;
752
+ frames.push(row);
753
+ }
754
+ return {
755
+ hopS: CHROMA_HOP / rate,
756
+ frameTime: (i) => (i * CHROMA_HOP + CHROMA_N / 2) / rate,
757
+ frames,
758
+ };
759
+ }
760
+
761
+ const NOTE = ["C", "C#", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B"];
762
+ // Krumhansl and Kessler's probe-tone ratings: how well each pitch class fits a key
763
+ const MAJOR = [6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2.88];
764
+ const MINOR = [6.33, 2.68, 3.52, 5.38, 2.6, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17];
765
+
766
+ export type Key = {
767
+ /** e.g. "A minor" */
768
+ name: string;
769
+ tonic: number;
770
+ mode: "major" | "minor";
771
+ /** the correlation of the sound's pitch classes with the key's profile (−1..1) */
772
+ correlation: number;
773
+ /** the next best key and its correlation; a relative major/minor is often close */
774
+ runnerUp: { name: string; correlation: number };
775
+ };
776
+
777
+ /** the key whose profile the whole sound's pitch classes correlate with best;
778
+ * null when nothing pitched sounds */
779
+ export function estimateKey(ch: Chroma): Key | null {
780
+ const total = new Float64Array(12);
781
+ for (const row of ch.frames) for (let c = 0; c < 12; c++) total[c] = total[c]! + row[c]!;
782
+ if (!(total.reduce((a, b) => a + b, 0) > 0)) return null;
783
+ const corr = (a: ArrayLike<number>, b: ArrayLike<number>) => {
784
+ let ma = 0;
785
+ let mb = 0;
786
+ for (let i = 0; i < 12; i++) {
787
+ ma += a[i]! / 12;
788
+ mb += b[i]! / 12;
789
+ }
790
+ let num = 0;
791
+ let da = 0;
792
+ let db = 0;
793
+ for (let i = 0; i < 12; i++) {
794
+ num += (a[i]! - ma) * (b[i]! - mb);
795
+ da += (a[i]! - ma) ** 2;
796
+ db += (b[i]! - mb) ** 2;
797
+ }
798
+ return da > 0 && db > 0 ? num / Math.sqrt(da * db) : 0;
799
+ };
800
+ const all: { tonic: number; mode: "major" | "minor"; r: number }[] = [];
801
+ for (let tonic = 0; tonic < 12; tonic++)
802
+ for (const [mode, prof] of [
803
+ ["major", MAJOR],
804
+ ["minor", MINOR],
805
+ ] as const) {
806
+ const rot = Array.from({ length: 12 }, (_, i) => prof[(i - tonic + 12) % 12]!);
807
+ all.push({ tonic, mode, r: corr(total, rot) });
808
+ }
809
+ all.sort((a, b) => b.r - a.r);
810
+ const [a, b] = [all[0]!, all[1]!];
811
+ const name = (k: { tonic: number; mode: string }) => `${NOTE[k.tonic]} ${k.mode}`;
812
+ return {
813
+ name: name(a),
814
+ tonic: a.tonic,
815
+ mode: a.mode,
816
+ correlation: round2(a.r),
817
+ runnerUp: { name: name(b), correlation: round2(b.r) },
818
+ };
819
+ }
820
+
821
+ // --- bars, drops ----------------------------------------------------------------------
822
+
823
+ export type Meter = {
824
+ beatsPerBar: number;
825
+ /** index into the beats of the first downbeat (0..beatsPerBar−1) */
826
+ first: number;
827
+ /** the share of bars whose own strongest beat is the chosen downbeat */
828
+ agreement: number;
829
+ /** what agreement would be by chance: 1 / beatsPerBar */
830
+ chance: number;
831
+ /** how alike each beat is to the beat 2, 3 and 4 later (mean cosine) */
832
+ likeness: { 2: number; 3: number; 4: number };
833
+ };
834
+
835
+ /** which beat starts each bar, and how many beats a bar holds. A bar starts
836
+ * where things change — the chord (pitch classes before against after), the
837
+ * texture (band energies), the low end landing (a kick) — so each beat is
838
+ * scored by those three, and the beat in the bar that scores highest most
839
+ * often is the downbeat. Three beats a bar only when bars of three agree on
840
+ * their downbeat clearly more often, over chance, than bars of four do. */
841
+ export function estimateMeter(s: Spectrum, ch: Chroma, beats: readonly number[]): Meter | null {
842
+ const nb = beats.length - 1;
843
+ if (nb < 16) return null;
844
+ const low = bandOnsetStrength(s, 30, 160);
845
+ // per beat: the mean band energies and pitch classes over [beat, next beat)
846
+ const tex: Float64Array[] = [];
847
+ const pcs: Float64Array[] = [];
848
+ for (let k = 0; k < nb; k++) {
849
+ const [a, b] = [beats[k]!, beats[k + 1]!];
850
+ const v = new Float64Array(BANDS);
851
+ const f0 = Math.max(0, frameAt(s, a));
852
+ const f1 = Math.min(s.bands.length, Math.max(f0 + 1, frameAt(s, b)));
853
+ for (let f = f0; f < f1; f++) for (let j = 0; j < BANDS; j++) v[j] = v[j]! + s.bands[f]![j]!;
854
+ for (let j = 0; j < BANDS; j++) v[j] = v[j]! / Math.max(1, f1 - f0);
855
+ tex.push(v);
856
+ const c = new Float64Array(12);
857
+ const g0 = Math.max(0, Math.round((a - ch.frameTime(0)) / ch.hopS));
858
+ const g1 = Math.min(
859
+ ch.frames.length,
860
+ Math.max(g0 + 1, Math.round((b - ch.frameTime(0)) / ch.hopS)),
861
+ );
862
+ for (let g = g0; g < g1; g++) for (let j = 0; j < 12; j++) c[j] = c[j]! + ch.frames[g]![j]!;
863
+ pcs.push(c);
864
+ }
865
+ const centred = (xs: Float64Array[]) => {
866
+ const dim = xs[0]?.length ?? 0;
867
+ const mean = new Float64Array(dim);
868
+ for (const x of xs) for (let j = 0; j < dim; j++) mean[j] = mean[j]! + x[j]! / xs.length;
869
+ return xs.map((x) => {
870
+ const u = Float64Array.from(x, (v, j) => v - mean[j]!);
871
+ const norm = Math.hypot(...u) || 1;
872
+ return u.map((v) => v / norm);
873
+ });
874
+ };
875
+ const ut = centred(tex);
876
+ const uc = centred(pcs);
877
+ const cos = (a: Float64Array, b: Float64Array) => {
878
+ let d = 0;
879
+ for (let j = 0; j < a.length; j++) d += a[j]! * b[j]!;
880
+ return d;
881
+ };
882
+ const likeAt = (lag: number) => {
883
+ let sum = 0;
884
+ let m = 0;
885
+ for (let k = 0; k + lag < nb; k++) {
886
+ sum += (cos(ut[k]!, ut[k + lag]!) + cos(uc[k]!, uc[k + lag]!)) / 2;
887
+ m++;
888
+ }
889
+ return m ? sum / m : 0;
890
+ };
891
+ const likeness = { 2: round2(likeAt(2)), 3: round2(likeAt(3)), 4: round2(likeAt(4)) };
892
+ // change at beat k: the two beats before against the two from it on
893
+ const change = (u: Float64Array[], k: number) => {
894
+ if (k < 2 || k + 2 > nb) return 0;
895
+ const dim = u[0]!.length;
896
+ const p = new Float64Array(dim);
897
+ const q = new Float64Array(dim);
898
+ for (let j = 0; j < dim; j++) {
899
+ p[j] = u[k - 2]![j]! + u[k - 1]![j]!;
900
+ q[j] = u[k]![j]! + u[k + 1]![j]!;
901
+ }
902
+ const np = Math.hypot(...p) || 1;
903
+ const nq = Math.hypot(...q) || 1;
904
+ return 1 - cos(p, q) / (np * nq);
905
+ };
906
+ const z = (xs: number[]) => {
907
+ const m = xs.reduce((a, b) => a + b, 0) / xs.length;
908
+ const sd = Math.sqrt(xs.reduce((a, b) => a + (b - m) ** 2, 0) / xs.length) || 1;
909
+ return xs.map((x) => (x - m) / sd);
910
+ };
911
+ const ks = Array.from({ length: nb }, (_, k) => k);
912
+ const zc = z(ks.map((k) => change(uc, k)));
913
+ const zt = z(ks.map((k) => change(ut, k)));
914
+ const zl = z(ks.map((k) => peakNear(s, low, beats[k]!, 3)));
915
+ const score = ks.map((k) => zc[k]! + zt[k]! + zl[k]!);
916
+ const barsOf = (B: number) => {
917
+ // per bar of B beats (counted from beat 0), which position scores highest
918
+ const wins = new Array<number>(B).fill(0);
919
+ let bars = 0;
920
+ for (let k = 0; k + B <= nb; k += B) {
921
+ let best = 0;
922
+ for (let j = 1; j < B; j++) if (score[k + j]! > score[k + best]!) best = j;
923
+ wins[best]!++;
924
+ bars++;
925
+ }
926
+ const mean = Array.from({ length: B }, (_, j) => {
927
+ let sum = 0;
928
+ let m = 0;
929
+ for (let k = j; k < nb; k += B) {
930
+ sum += score[k]!;
931
+ m++;
932
+ }
933
+ return m ? sum / m : -Infinity;
934
+ });
935
+ const first = mean.indexOf(Math.max(...mean));
936
+ const agreement = bars ? wins[first]! / bars : 0;
937
+ return { B, first, agreement, over: (agreement - 1 / B) / (1 - 1 / B) };
938
+ };
939
+ const [three, four] = [barsOf(3), barsOf(4)];
940
+ const m = three.over > four.over + 0.2 ? three : four;
941
+ return {
942
+ beatsPerBar: m.B,
943
+ first: m.first,
944
+ agreement: round2(m.agreement),
945
+ chance: round2(1 / m.B),
946
+ likeness,
947
+ };
948
+ }
949
+
950
+ /** where the music lands: a bar line (or, without bars, a second) after
951
+ * which a layer is there that was not — the low end (under 160 Hz) 4 dB or
952
+ * more up, or the mids or highs 6 dB or more, over the next two bars against
953
+ * the four before — or any rise at all right after a riser (a bar whose
954
+ * highs start where the four bars before started, or carry on a riser from
955
+ * the bar before, climb 3 dB or more from its first quarter to its last, and
956
+ * end 6 dB or more over where those bars ended). The riser bar itself is not a
957
+ * landing; neither is music starting after silence, nor a rise into the
958
+ * quietest quarter of the sound. Within four bars of each other the
959
+ * larger landing is kept. */
960
+ export function findDrops(s: Spectrum, marks: readonly number[], duration: number): number[] {
961
+ const band = (hz: number) =>
962
+ Math.round((BANDS * Math.log(hz / LOW_HZ)) / Math.log(HIGH_HZ / LOW_HZ));
963
+ const [b160, b2k] = [band(160), band(2000)];
964
+ const edges = [...marks.filter((t) => t >= 0 && t < duration), duration];
965
+ const db = (x: number, m: number) => 10 * Math.log10(x / Math.max(1, m) + 1e-12);
966
+ const seg: {
967
+ level: number;
968
+ low: number;
969
+ mid: number;
970
+ hi: number;
971
+ hiFirst: number;
972
+ hiLast: number;
973
+ climb: number;
974
+ }[] = [];
975
+ for (let i = 0; i + 1 < edges.length; i++) {
976
+ const f0 = Math.max(0, frameAt(s, edges[i]!));
977
+ const f1 = Math.min(s.bands.length, Math.max(f0 + 1, frameAt(s, edges[i + 1]!)));
978
+ const q = Math.max(1, Math.floor((f1 - f0) / 4));
979
+ let [lv, lo, mid, hi, hiFirst, hiLast] = [0, 0, 0, 0, 0, 0];
980
+ for (let f = f0; f < f1; f++) {
981
+ lv += 10 ** (s.level[f]! / 10);
982
+ let h = 0;
983
+ for (let k = 0; k < BANDS; k++) {
984
+ const e = 10 ** (s.bands[f]![k]! / 10);
985
+ if (k < b160) lo += e;
986
+ else if (k < b2k) mid += e;
987
+ else h += e;
988
+ }
989
+ hi += h;
990
+ if (f < f0 + q) hiFirst += h;
991
+ if (f >= f1 - q) hiLast += h;
992
+ }
993
+ const m = f1 - f0;
994
+ seg.push({
995
+ level: db(lv, m),
996
+ low: db(lo, m),
997
+ mid: db(mid, m),
998
+ hi: db(hi, m),
999
+ hiFirst: db(hiFirst, q),
1000
+ hiLast: db(hiLast, q),
1001
+ climb: db(hiLast, q) - db(hiFirst, q),
1002
+ });
1003
+ }
1004
+ if (seg.length < 6) return [];
1005
+ const sorted = seg.map((x) => x.level).sort((a, b) => a - b);
1006
+ const quiet = sorted[Math.floor(sorted.length * 0.25)]!;
1007
+ const pmean = (xs: number[]) =>
1008
+ 10 * Math.log10(xs.reduce((a, v) => a + 10 ** (v / 10), 0) / xs.length);
1009
+ const rise = (i: number, k: "level" | "low" | "mid" | "hi") =>
1010
+ pmean(seg.slice(i, i + 2).map((x) => x[k])) - pmean(seg.slice(i - 4, i).map((x) => x[k]));
1011
+ // a riser starts from where the highs were at that point of the bar (or
1012
+ // carries one on from the bar before), climbs through the bar, and ends
1013
+ // well over where they were at bars' ends
1014
+ const risers: boolean[] = [];
1015
+ seg.forEach((x, i) => {
1016
+ const prior = seg.slice(Math.max(0, i - 4), i);
1017
+ risers.push(
1018
+ i >= 4 &&
1019
+ x.climb >= 3 &&
1020
+ x.hiLast - pmean(prior.map((y) => y.hiLast)) >= 6 &&
1021
+ (x.hiFirst - pmean(prior.map((y) => y.hiFirst)) < 3 || !!risers[i - 1]),
1022
+ );
1023
+ });
1024
+ const riser = (i: number) => !!risers[i];
1025
+ const cand: { i: number; v: number }[] = [];
1026
+ for (let i = 4; i + 2 <= seg.length; i++) {
1027
+ if (riser(i)) continue;
1028
+ const before = pmean(seg.slice(i - 4, i).map((x) => x.level));
1029
+ const after = pmean(seg.slice(i, i + 2).map((x) => x.level));
1030
+ if (before < FLOOR_DB + 10 || after < quiet) continue;
1031
+ const low = rise(i, "low");
1032
+ const entry = Math.max(rise(i, "mid"), rise(i, "hi"));
1033
+ if (riser(i - 1) && (low >= 1 || entry >= 1)) cand.push({ i, v: 6 + low + entry / 2 });
1034
+ else if (low >= 4 || entry >= 6) cand.push({ i, v: low + entry / 2 });
1035
+ }
1036
+ const kept: { i: number; v: number }[] = [];
1037
+ for (const c of cand.sort((a, b) => b.v - a.v))
1038
+ if (kept.every((k) => Math.abs(k.i - c.i) >= 4)) kept.push(c);
1039
+ return kept.map((k) => round3(edges[k.i]!)).sort((a, b) => a - b);
1040
+ }
1041
+
1042
+ /** where the low end (under 160 Hz) lands in a bar, sixteen steps from its
1043
+ * downbeat, averaged over the bars: "x" where it rises in at least half as
1044
+ * many bars as its busiest step, "-" elsewhere; null without bars or a low end */
1045
+ export function lowPattern(s: Spectrum, downbeats: readonly number[], steps = 16): string | null {
1046
+ if (downbeats.length < 3) return null;
1047
+ const low = bandOnsetStrength(s, 30, 160);
1048
+ const sum = new Float64Array(steps);
1049
+ for (let i = 0; i + 1 < downbeats.length; i++) {
1050
+ const [a, b] = [downbeats[i]!, downbeats[i + 1]!];
1051
+ const row = Array.from({ length: steps }, (_, j) =>
1052
+ peakNear(s, low, a + ((b - a) * j) / steps, 2),
1053
+ );
1054
+ const top = Math.max(...row);
1055
+ if (top < 1) continue; // no low end in this bar
1056
+ row.forEach((v, j) => {
1057
+ sum[j] = sum[j]! + (v >= top * 0.5 ? 1 : 0);
1058
+ });
1059
+ }
1060
+ const max = Math.max(...sum);
1061
+ if (!(max > 0)) return null;
1062
+ return Array.from(sum, (v) => (v >= max * 0.5 ? "x" : "-")).join("");
1063
+ }
1064
+
1065
+ // --- the beats file ---------------------------------------------------------------------
1066
+
1067
+ export type BeatsHow = "measured" | "estimated" | "not detected";
1068
+
1069
+ /** `<name>.beats.json`; times in seconds of the sound */
1070
+ export type FilmBeats = {
1071
+ version: 1;
1072
+ source: string;
1073
+ duration: number;
1074
+ tempo: {
1075
+ bpm: number | null;
1076
+ /** how far the grid sits on onsets above what chance gives: (gridFit −
1077
+ * chance) / (1 − chance), 0..1 */
1078
+ confidence: number;
1079
+ label: BeatsHow;
1080
+ periodS?: number;
1081
+ /** the onset strength's autocorrelation at the period over zero lag */
1082
+ strength?: number;
1083
+ /** the share of beats with an onset within 40 ms */
1084
+ gridFit?: number;
1085
+ /** that share for a grid laid anywhere */
1086
+ chance?: number;
1087
+ steady?: boolean;
1088
+ alternatives?: { bpm: number; strength: number }[];
1089
+ };
1090
+ beats: number[];
1091
+ downbeats: number[];
1092
+ bars: { t: number; index: number }[];
1093
+ /** how the downbeats were chosen */
1094
+ meter: {
1095
+ beatsPerBar: number | null;
1096
+ /** (agreement − chance) / (1 − chance), 0..1 */
1097
+ confidence: number;
1098
+ agreement: number;
1099
+ chance: number;
1100
+ label: BeatsHow;
1101
+ };
1102
+ sections: {
1103
+ t: number;
1104
+ end: number;
1105
+ /** the section's level against the quietest (0) and loudest (1) section */
1106
+ energy: number;
1107
+ /** "drop" when a drop opens it */
1108
+ label?: string;
1109
+ levelDb: number;
1110
+ onsetsPerS: number;
1111
+ centroidHz: number;
1112
+ }[];
1113
+ drops: number[];
1114
+ onsets: number[];
1115
+ labels: Record<
1116
+ "duration" | "tempo" | "beats" | "downbeats" | "bars" | "sections" | "drops" | "onsets",
1117
+ BeatsHow
1118
+ >;
1119
+ };
1120
+
1121
+ /** the whole analysis on mono samples at LISTEN_RATE */
1122
+ export function analyzeBeats(pcm: Float32Array, source: string): FilmBeats {
1123
+ const duration = pcm.length / LISTEN_RATE;
1124
+ const s = spectrum(pcm);
1125
+ const env = onsetStrength(s);
1126
+ const onsets = pickOnsets(s, env, pcm).map(round3);
1127
+ const tempo = estimateTempo(s, env, onsets, duration);
1128
+ const ch = chromagram(pcm);
1129
+ const meter = tempo ? estimateMeter(s, ch, tempo.beats) : null;
1130
+ const beats = tempo?.beats ?? [];
1131
+ const downbeats = meter ? beats.filter((_, k) => k % meter.beatsPerBar === meter.first) : [];
1132
+ const drops = findDrops(
1133
+ s,
1134
+ downbeats.length >= 4 ? downbeats : Array.from({ length: Math.ceil(duration) }, (_, i) => i),
1135
+ duration,
1136
+ );
1137
+ // a section boundary sits on the bar line nearest it, when one is within half a bar
1138
+ const barLen = meter && tempo ? meter.beatsPerBar * tempo.periodS : 0;
1139
+ const snap = (t: number) => {
1140
+ if (!downbeats.length) return t;
1141
+ const d = nearestOffset(downbeats, t);
1142
+ return d != null && Math.abs(d) <= barLen / 2 ? round3(t + d) : t;
1143
+ };
1144
+ const raw = findSections(s, onsets, duration);
1145
+ const bounds = [0, ...raw.slice(1).map((x) => snap(x.start)), duration].filter(
1146
+ (t, i, a) => i === 0 || t > a[i - 1]! + 1e-6,
1147
+ );
1148
+ const sections = bounds.slice(0, -1).map((t, i) => describe(s, onsets, t, bounds[i + 1]!, 0));
1149
+ const levels = sections.map((x) => x.levelDb).filter((v) => v > -120);
1150
+ const [lo, hi] = [Math.min(...levels), Math.max(...levels)];
1151
+ const beatLen = tempo?.periodS ?? 0.5;
1152
+ const confidence = (fit: number, chance: number) =>
1153
+ chance < 1 ? round2(Math.max(0, (fit - chance) / (1 - chance))) : 0;
1154
+ return {
1155
+ version: 1,
1156
+ source,
1157
+ duration: round3(duration),
1158
+ tempo: tempo
1159
+ ? {
1160
+ bpm: tempo.bpm,
1161
+ confidence: confidence(tempo.gridFit, tempo.chance),
1162
+ label: "estimated",
1163
+ periodS: tempo.periodS,
1164
+ strength: tempo.strength,
1165
+ gridFit: tempo.gridFit,
1166
+ chance: tempo.chance,
1167
+ steady: tempo.steady,
1168
+ alternatives: tempo.alternatives,
1169
+ }
1170
+ : { bpm: null, confidence: 0, label: "not detected" },
1171
+ beats,
1172
+ downbeats,
1173
+ bars: downbeats.map((t, index) => ({ t, index })),
1174
+ meter: meter
1175
+ ? {
1176
+ beatsPerBar: meter.beatsPerBar,
1177
+ confidence: confidence(meter.agreement, meter.chance),
1178
+ agreement: meter.agreement,
1179
+ chance: meter.chance,
1180
+ label: "estimated",
1181
+ }
1182
+ : { beatsPerBar: null, confidence: 0, agreement: 0, chance: 0, label: "not detected" },
1183
+ sections: sections.map((x) => {
1184
+ const out: FilmBeats["sections"][number] = {
1185
+ t: x.start,
1186
+ end: x.end,
1187
+ energy: x.levelDb <= -120 ? 0 : hi > lo ? round2((x.levelDb - lo) / (hi - lo)) : 1,
1188
+ levelDb: x.levelDb,
1189
+ onsetsPerS: x.onsetsPerS,
1190
+ centroidHz: x.centroidHz,
1191
+ };
1192
+ if (drops.some((d) => Math.abs(d - x.start) <= beatLen)) out.label = "drop";
1193
+ return out;
1194
+ }),
1195
+ drops,
1196
+ onsets,
1197
+ labels: {
1198
+ duration: "measured",
1199
+ tempo: tempo ? "estimated" : "not detected",
1200
+ beats: beats.length ? "estimated" : "not detected",
1201
+ downbeats: downbeats.length ? "estimated" : "not detected",
1202
+ bars: downbeats.length ? "estimated" : "not detected",
1203
+ sections: "estimated",
1204
+ drops: drops.length ? "estimated" : "not detected",
1205
+ onsets: onsets.length ? "measured" : "not detected",
1206
+ },
1207
+ };
1208
+ }
1209
+
1210
+ export type FilmBeatsOptions = {
1211
+ /** any sound, or a film whose sound to read */
1212
+ input: string;
1213
+ /** default: `<input without extension>.beats.json` */
1214
+ out?: string;
1215
+ };
1216
+
1217
+ export async function filmBeats(
1218
+ opts: FilmBeatsOptions,
1219
+ ): Promise<{ out: string; beats: FilmBeats }> {
1220
+ const input = resolve(opts.input);
1221
+ if (!existsSync(input)) throw new Error(`film beats: no file at ${input}`);
1222
+ const out = resolve(opts.out ?? `${input.replace(/\.[^./]+$/, "")}.beats.json`);
1223
+ const pcm = await decodeMono(await resolveFfmpeg(), input);
1224
+ if (!pcm.length) throw new Error(`film beats: ${input} has no sound`);
1225
+ const beats = analyzeBeats(pcm, input);
1226
+ await writeFile(out, `${JSON.stringify(beats)}\n`);
1227
+ return { out, beats };
1228
+ }
1229
+
1230
+ export function formatFilmBeats(b: FilmBeats): string {
1231
+ const L: string[] = [];
1232
+ const tag = (h: BeatsHow) => `(${h})`;
1233
+ const fmtS = (t: number) => `${t.toFixed(2)}s`;
1234
+ const list = (xs: number[], max = 24) =>
1235
+ xs.length > max
1236
+ ? `${xs.slice(0, max).map(fmtS).join(", ")} … (${xs.length - max} more)`
1237
+ : xs.map(fmtS).join(", ");
1238
+ L.push(
1239
+ `# film beats — ${basename(b.source)}`,
1240
+ "",
1241
+ `duration ${fmtS(b.duration)} ${tag("measured")}`,
1242
+ );
1243
+ const t = b.tempo;
1244
+ if (t.bpm == null) L.push(`- tempo: no repeating period between 60 and 200 BPM ${tag(t.label)}`);
1245
+ else {
1246
+ L.push(
1247
+ `- tempo ≈ ${t.bpm} BPM (a beat ${t.periodS}s)${t.steady === false ? ", not steady: the beats follow the onsets" : ""}; ${Math.round((t.gridFit ?? 0) * 100)}% of beats have an onset within 40 ms, ${Math.round((t.chance ?? 0) * 100)}% would by chance — confidence ${t.confidence} ${tag(t.label)}`,
1248
+ );
1249
+ if (t.alternatives?.length)
1250
+ L.push(
1251
+ `- also repeating at: ${t.alternatives.map((a) => `${a.bpm} BPM (${a.strength})`).join(", ")} ${tag("estimated")}`,
1252
+ );
1253
+ L.push(`- beats: ${b.beats.length}, first at ${fmtS(b.beats[0] ?? 0)} ${tag(b.labels.beats)}`);
1254
+ }
1255
+ const m = b.meter;
1256
+ if (m.beatsPerBar == null) L.push(`- bars: no beat grid to count them on ${tag(m.label)}`);
1257
+ else
1258
+ L.push(
1259
+ `- bars of ${m.beatsPerBar} beats: ${b.bars.length}, first downbeat at ${fmtS(b.downbeats[0] ?? 0)}; in ${Math.round(m.agreement * 100)}% of bars that beat scored highest (chord, texture and low end changing), ${Math.round(m.chance * 100)}% by chance — confidence ${m.confidence} ${tag(m.label)}`,
1260
+ );
1261
+ L.push(
1262
+ b.drops.length
1263
+ ? `- drops: ${list(b.drops)} ${tag(b.labels.drops)}`
1264
+ : `- drops: none ${tag(b.labels.drops)}`,
1265
+ );
1266
+ L.push(`- sections ${tag(b.labels.sections)}:`);
1267
+ for (const [i, x] of b.sections.entries())
1268
+ L.push(
1269
+ ` ${i + 1}. ${fmtS(x.t)}–${fmtS(x.end)}: energy ${x.energy} (level ${x.levelDb} dBFS), ${x.onsetsPerS} onsets/s${x.label ? `, ${x.label}` : ""}`,
1270
+ );
1271
+ L.push(`- onsets: ${b.onsets.length} ${tag(b.labels.onsets)}`);
1272
+ return L.join("\n");
1273
+ }
1274
+
1275
+ // --- small arithmetic -----------------------------------------------------------------
1276
+
1277
+ export function median(xs: readonly number[]): number {
1278
+ if (!xs.length) return 0;
1279
+ const s = [...xs].sort((a, b) => a - b);
1280
+ const m = s.length >> 1;
1281
+ return s.length % 2 ? s[m]! : (s[m - 1]! + s[m]!) / 2;
1282
+ }
1283
+ const round1 = (v: number) => Math.round(v * 10) / 10;
1284
+ const round2 = (v: number) => Math.round(v * 100) / 100;
1285
+ const round3 = (v: number) => Math.round(v * 1000) / 1000;